1 //===- lib/Support/YAMLTraits.cpp -----------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Support/YAMLTraits.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Casting.h"
14 #include "llvm/Support/Errc.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/Format.h"
17 #include "llvm/Support/LineIterator.h"
18 #include "llvm/Support/YAMLParser.h"
19 #include "llvm/Support/raw_ostream.h"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 IO::IO(void *Context) : Ctxt(Context) {
35 void *IO::getContext() {
39 void IO::setContext(void *Context) {
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 Input::Input(StringRef InputContent,
49 SourceMgr::DiagHandlerTy DiagHandler,
50 void *DiagHandlerCtxt)
52 Strm(new Stream(InputContent, SrcMgr)),
53 CurrentNode(nullptr) {
55 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
56 DocIterator = Strm->begin();
62 std::error_code Input::error() { return EC; }
64 // Pin the vtables to this file.
65 void Input::HNode::anchor() {}
66 void Input::EmptyHNode::anchor() {}
67 void Input::ScalarHNode::anchor() {}
68 void Input::MapHNode::anchor() {}
69 void Input::SequenceHNode::anchor() {}
71 bool Input::outputting() {
75 bool Input::setCurrentDocument() {
76 if (DocIterator != Strm->end()) {
77 Node *N = DocIterator->getRoot();
79 assert(Strm->failed() && "Root is NULL iff parsing failed");
80 EC = make_error_code(errc::invalid_argument);
84 if (isa<NullNode>(N)) {
85 // Empty files are allowed and ignored
87 return setCurrentDocument();
89 TopNode = this->createHNodes(N);
90 CurrentNode = TopNode.get();
96 bool Input::nextDocument() {
97 return ++DocIterator != Strm->end();
100 const Node *Input::getCurrentNode() const {
101 return CurrentNode ? CurrentNode->_node : nullptr;
104 bool Input::mapTag(StringRef Tag, bool Default) {
105 std::string foundTag = CurrentNode->_node->getVerbatimTag();
106 if (foundTag.empty()) {
107 // If no tag found and 'Tag' is the default, say it was found.
110 // Return true iff found tag matches supplied tag.
111 return Tag.equals(foundTag);
114 void Input::beginMapping() {
117 // CurrentNode can be null if the document is empty.
118 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
120 MN->ValidKeys.clear();
124 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
130 // CurrentNode is null for empty documents, which is an error in case required
131 // nodes are present.
134 EC = make_error_code(errc::invalid_argument);
138 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
140 setError(CurrentNode, "not a mapping");
143 MN->ValidKeys.push_back(Key);
144 HNode *Value = MN->Mapping[Key].get();
147 setError(CurrentNode, Twine("missing required key '") + Key + "'");
152 SaveInfo = CurrentNode;
157 void Input::postflightKey(void *saveInfo) {
158 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
161 void Input::endMapping() {
164 // CurrentNode can be null if the document is empty.
165 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
168 for (const auto &NN : MN->Mapping) {
169 if (!MN->isValidKey(NN.first())) {
170 setError(NN.second.get(), Twine("unknown key '") + NN.first() + "'");
176 void Input::beginFlowMapping() { beginMapping(); }
178 void Input::endFlowMapping() { endMapping(); }
180 unsigned Input::beginSequence() {
181 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode))
182 return SQ->Entries.size();
183 if (isa<EmptyHNode>(CurrentNode))
185 // Treat case where there's a scalar "null" value as an empty sequence.
186 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
187 if (isNull(SN->value()))
190 // Any other type of HNode is an error.
191 setError(CurrentNode, "not a sequence");
195 void Input::endSequence() {
198 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
201 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
202 SaveInfo = CurrentNode;
203 CurrentNode = SQ->Entries[Index].get();
209 void Input::postflightElement(void *SaveInfo) {
210 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
213 unsigned Input::beginFlowSequence() { return beginSequence(); }
215 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
218 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
219 SaveInfo = CurrentNode;
220 CurrentNode = SQ->Entries[index].get();
226 void Input::postflightFlowElement(void *SaveInfo) {
227 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
230 void Input::endFlowSequence() {
233 void Input::beginEnumScalar() {
234 ScalarMatchFound = false;
237 bool Input::matchEnumScalar(const char *Str, bool) {
238 if (ScalarMatchFound)
240 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
241 if (SN->value().equals(Str)) {
242 ScalarMatchFound = true;
249 bool Input::matchEnumFallback() {
250 if (ScalarMatchFound)
252 ScalarMatchFound = true;
256 void Input::endEnumScalar() {
257 if (!ScalarMatchFound) {
258 setError(CurrentNode, "unknown enumerated scalar");
262 bool Input::beginBitSetScalar(bool &DoClear) {
263 BitValuesUsed.clear();
264 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
265 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
267 setError(CurrentNode, "expected sequence of bit values");
273 bool Input::bitSetMatch(const char *Str, bool) {
276 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
278 for (auto &N : SQ->Entries) {
279 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) {
280 if (SN->value().equals(Str)) {
281 BitValuesUsed[Index] = true;
285 setError(CurrentNode, "unexpected scalar in sequence of bit values");
290 setError(CurrentNode, "expected sequence of bit values");
295 void Input::endBitSetScalar() {
298 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
299 assert(BitValuesUsed.size() == SQ->Entries.size());
300 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
301 if (!BitValuesUsed[i]) {
302 setError(SQ->Entries[i].get(), "unknown bit value");
309 void Input::scalarString(StringRef &S, bool) {
310 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
313 setError(CurrentNode, "unexpected scalar");
317 void Input::blockScalarString(StringRef &S) { scalarString(S, false); }
319 void Input::setError(HNode *hnode, const Twine &message) {
320 assert(hnode && "HNode must not be NULL");
321 this->setError(hnode->_node, message);
324 void Input::setError(Node *node, const Twine &message) {
325 Strm->printError(node, message);
326 EC = make_error_code(errc::invalid_argument);
329 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
330 SmallString<128> StringStorage;
331 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
332 StringRef KeyStr = SN->getValue(StringStorage);
333 if (!StringStorage.empty()) {
334 // Copy string to permanent storage
335 unsigned Len = StringStorage.size();
336 char *Buf = StringAllocator.Allocate<char>(Len);
337 memcpy(Buf, &StringStorage[0], Len);
338 KeyStr = StringRef(Buf, Len);
340 return llvm::make_unique<ScalarHNode>(N, KeyStr);
341 } else if (BlockScalarNode *BSN = dyn_cast<BlockScalarNode>(N)) {
342 StringRef Value = BSN->getValue();
343 char *Buf = StringAllocator.Allocate<char>(Value.size());
344 memcpy(Buf, Value.data(), Value.size());
345 return llvm::make_unique<ScalarHNode>(N, StringRef(Buf, Value.size()));
346 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
347 auto SQHNode = llvm::make_unique<SequenceHNode>(N);
348 for (Node &SN : *SQ) {
349 auto Entry = this->createHNodes(&SN);
352 SQHNode->Entries.push_back(std::move(Entry));
354 return std::move(SQHNode);
355 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
356 auto mapHNode = llvm::make_unique<MapHNode>(N);
357 for (KeyValueNode &KVN : *Map) {
358 Node *KeyNode = KVN.getKey();
359 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(KeyNode);
361 setError(KeyNode, "Map key must be a scalar");
364 StringStorage.clear();
365 StringRef KeyStr = KeyScalar->getValue(StringStorage);
366 if (!StringStorage.empty()) {
367 // Copy string to permanent storage
368 unsigned Len = StringStorage.size();
369 char *Buf = StringAllocator.Allocate<char>(Len);
370 memcpy(Buf, &StringStorage[0], Len);
371 KeyStr = StringRef(Buf, Len);
373 auto ValueHNode = this->createHNodes(KVN.getValue());
376 mapHNode->Mapping[KeyStr] = std::move(ValueHNode);
378 return std::move(mapHNode);
379 } else if (isa<NullNode>(N)) {
380 return llvm::make_unique<EmptyHNode>(N);
382 setError(N, "unknown node kind");
387 bool Input::MapHNode::isValidKey(StringRef Key) {
388 for (const char *K : ValidKeys) {
395 void Input::setError(const Twine &Message) {
396 this->setError(CurrentNode, Message);
399 bool Input::canElideEmptySequence() {
403 //===----------------------------------------------------------------------===//
405 //===----------------------------------------------------------------------===//
407 Output::Output(raw_ostream &yout, void *context, int WrapColumn)
410 WrapColumn(WrapColumn),
412 ColumnAtFlowStart(0),
413 ColumnAtMapFlowStart(0),
414 NeedBitValueComma(false),
415 NeedFlowSequenceComma(false),
416 EnumerationMatchFound(false),
417 NeedsNewLine(false) {
423 bool Output::outputting() {
427 void Output::beginMapping() {
428 StateStack.push_back(inMapFirstKey);
432 bool Output::mapTag(StringRef Tag, bool Use) {
440 void Output::endMapping() {
441 StateStack.pop_back();
444 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
445 bool &UseDefault, void *&) {
447 if (Required || !SameAsDefault) {
448 auto State = StateStack.back();
449 if (State == inFlowMapFirstKey || State == inFlowMapOtherKey) {
452 this->newLineCheck();
453 this->paddedKey(Key);
460 void Output::postflightKey(void *) {
461 if (StateStack.back() == inMapFirstKey) {
462 StateStack.pop_back();
463 StateStack.push_back(inMapOtherKey);
464 } else if (StateStack.back() == inFlowMapFirstKey) {
465 StateStack.pop_back();
466 StateStack.push_back(inFlowMapOtherKey);
470 void Output::beginFlowMapping() {
471 StateStack.push_back(inFlowMapFirstKey);
472 this->newLineCheck();
473 ColumnAtMapFlowStart = Column;
477 void Output::endFlowMapping() {
478 StateStack.pop_back();
479 this->outputUpToEndOfLine(" }");
482 void Output::beginDocuments() {
483 this->outputUpToEndOfLine("---");
486 bool Output::preflightDocument(unsigned index) {
488 this->outputUpToEndOfLine("\n---");
492 void Output::postflightDocument() {
495 void Output::endDocuments() {
499 unsigned Output::beginSequence() {
500 StateStack.push_back(inSeq);
505 void Output::endSequence() {
506 StateStack.pop_back();
509 bool Output::preflightElement(unsigned, void *&) {
513 void Output::postflightElement(void *) {
516 unsigned Output::beginFlowSequence() {
517 StateStack.push_back(inFlowSeq);
518 this->newLineCheck();
519 ColumnAtFlowStart = Column;
521 NeedFlowSequenceComma = false;
525 void Output::endFlowSequence() {
526 StateStack.pop_back();
527 this->outputUpToEndOfLine(" ]");
530 bool Output::preflightFlowElement(unsigned, void *&) {
531 if (NeedFlowSequenceComma)
533 if (WrapColumn && Column > WrapColumn) {
535 for (int i = 0; i < ColumnAtFlowStart; ++i)
537 Column = ColumnAtFlowStart;
543 void Output::postflightFlowElement(void *) {
544 NeedFlowSequenceComma = true;
547 void Output::beginEnumScalar() {
548 EnumerationMatchFound = false;
551 bool Output::matchEnumScalar(const char *Str, bool Match) {
552 if (Match && !EnumerationMatchFound) {
553 this->newLineCheck();
554 this->outputUpToEndOfLine(Str);
555 EnumerationMatchFound = true;
560 bool Output::matchEnumFallback() {
561 if (EnumerationMatchFound)
563 EnumerationMatchFound = true;
567 void Output::endEnumScalar() {
568 if (!EnumerationMatchFound)
569 llvm_unreachable("bad runtime enum value");
572 bool Output::beginBitSetScalar(bool &DoClear) {
573 this->newLineCheck();
575 NeedBitValueComma = false;
580 bool Output::bitSetMatch(const char *Str, bool Matches) {
582 if (NeedBitValueComma)
585 NeedBitValueComma = true;
590 void Output::endBitSetScalar() {
591 this->outputUpToEndOfLine(" ]");
594 void Output::scalarString(StringRef &S, bool MustQuote) {
595 this->newLineCheck();
597 // Print '' for the empty string because leaving the field empty is not
599 this->outputUpToEndOfLine("''");
603 // Only quote if we must.
604 this->outputUpToEndOfLine(S);
609 unsigned End = S.size();
610 output("'"); // Starting single quote.
611 const char *Base = S.data();
613 // Escape a single quote by doubling it.
615 output(StringRef(&Base[i], j - i + 1));
621 output(StringRef(&Base[i], j - i));
622 this->outputUpToEndOfLine("'"); // Ending single quote.
625 void Output::blockScalarString(StringRef &S) {
626 if (!StateStack.empty())
631 unsigned Indent = StateStack.empty() ? 1 : StateStack.size();
633 auto Buffer = MemoryBuffer::getMemBuffer(S, "", false);
634 for (line_iterator Lines(*Buffer, false); !Lines.is_at_end(); ++Lines) {
635 for (unsigned I = 0; I < Indent; ++I) {
643 void Output::setError(const Twine &message) {
646 bool Output::canElideEmptySequence() {
647 // Normally, with an optional key/value where the value is an empty sequence,
648 // the whole key/value can be not written. But, that produces wrong yaml
649 // if the key/value is the only thing in the map and the map is used in
650 // a sequence. This detects if the this sequence is the first key/value
651 // in map that itself is embedded in a sequnce.
652 if (StateStack.size() < 2)
654 if (StateStack.back() != inMapFirstKey)
656 return (StateStack[StateStack.size()-2] != inSeq);
659 void Output::output(StringRef s) {
664 void Output::outputUpToEndOfLine(StringRef s) {
666 if (StateStack.empty() || (StateStack.back() != inFlowSeq &&
667 StateStack.back() != inFlowMapFirstKey &&
668 StateStack.back() != inFlowMapOtherKey))
672 void Output::outputNewLine() {
677 // if seq at top, indent as if map, then add "- "
678 // if seq in middle, use "- " if firstKey, else use " "
681 void Output::newLineCheck() {
684 NeedsNewLine = false;
686 this->outputNewLine();
688 assert(StateStack.size() > 0);
689 unsigned Indent = StateStack.size() - 1;
690 bool OutputDash = false;
692 if (StateStack.back() == inSeq) {
694 } else if ((StateStack.size() > 1) && ((StateStack.back() == inMapFirstKey) ||
695 (StateStack.back() == inFlowSeq) ||
696 (StateStack.back() == inFlowMapFirstKey)) &&
697 (StateStack[StateStack.size() - 2] == inSeq)) {
702 for (unsigned i = 0; i < Indent; ++i) {
711 void Output::paddedKey(StringRef key) {
714 const char *spaces = " ";
715 if (key.size() < strlen(spaces))
716 output(&spaces[key.size()]);
721 void Output::flowKey(StringRef Key) {
722 if (StateStack.back() == inFlowMapOtherKey)
724 if (WrapColumn && Column > WrapColumn) {
726 for (int I = 0; I < ColumnAtMapFlowStart; ++I)
728 Column = ColumnAtMapFlowStart;
735 //===----------------------------------------------------------------------===//
736 // traits for built-in types
737 //===----------------------------------------------------------------------===//
739 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
740 Out << (Val ? "true" : "false");
743 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
744 if (Scalar.equals("true")) {
747 } else if (Scalar.equals("false")) {
751 return "invalid boolean";
754 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
759 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
765 void ScalarTraits<std::string>::output(const std::string &Val, void *,
770 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
776 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
778 // use temp uin32_t because ostream thinks uint8_t is a character
783 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
784 unsigned long long n;
785 if (getAsUnsignedInteger(Scalar, 0, n))
786 return "invalid number";
788 return "out of range number";
793 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
798 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
800 unsigned long long n;
801 if (getAsUnsignedInteger(Scalar, 0, n))
802 return "invalid number";
804 return "out of range number";
809 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
814 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
816 unsigned long long n;
817 if (getAsUnsignedInteger(Scalar, 0, n))
818 return "invalid number";
819 if (n > 0xFFFFFFFFUL)
820 return "out of range number";
825 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
830 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
832 unsigned long long N;
833 if (getAsUnsignedInteger(Scalar, 0, N))
834 return "invalid number";
839 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
840 // use temp in32_t because ostream thinks int8_t is a character
845 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
847 if (getAsSignedInteger(Scalar, 0, N))
848 return "invalid number";
849 if ((N > 127) || (N < -128))
850 return "out of range number";
855 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
860 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
862 if (getAsSignedInteger(Scalar, 0, N))
863 return "invalid number";
864 if ((N > INT16_MAX) || (N < INT16_MIN))
865 return "out of range number";
870 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
875 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
877 if (getAsSignedInteger(Scalar, 0, N))
878 return "invalid number";
879 if ((N > INT32_MAX) || (N < INT32_MIN))
880 return "out of range number";
885 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
890 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
892 if (getAsSignedInteger(Scalar, 0, N))
893 return "invalid number";
898 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
899 Out << format("%g", Val);
902 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
903 SmallString<32> buff(Scalar.begin(), Scalar.end());
905 Val = strtod(buff.c_str(), &end);
907 return "invalid floating point number";
911 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
912 Out << format("%g", Val);
915 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
916 SmallString<32> buff(Scalar.begin(), Scalar.end());
918 Val = strtod(buff.c_str(), &end);
920 return "invalid floating point number";
924 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
926 Out << format("0x%02X", Num);
929 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
930 unsigned long long n;
931 if (getAsUnsignedInteger(Scalar, 0, n))
932 return "invalid hex8 number";
934 return "out of range hex8 number";
939 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
941 Out << format("0x%04X", Num);
944 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
945 unsigned long long n;
946 if (getAsUnsignedInteger(Scalar, 0, n))
947 return "invalid hex16 number";
949 return "out of range hex16 number";
954 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
956 Out << format("0x%08X", Num);
959 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
960 unsigned long long n;
961 if (getAsUnsignedInteger(Scalar, 0, n))
962 return "invalid hex32 number";
963 if (n > 0xFFFFFFFFUL)
964 return "out of range hex32 number";
969 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
971 Out << format("0x%016llX", Num);
974 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
975 unsigned long long Num;
976 if (getAsUnsignedInteger(Scalar, 0, Num))
977 return "invalid hex64 number";