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/Errc.h"
11 #include "llvm/Support/YAMLTraits.h"
12 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Casting.h"
14 #include "llvm/Support/ErrorHandling.h"
15 #include "llvm/Support/Format.h"
16 #include "llvm/Support/YAMLParser.h"
17 #include "llvm/Support/raw_ostream.h"
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 IO::IO(void *Context) : Ctxt(Context) {
33 void *IO::getContext() {
37 void IO::setContext(void *Context) {
41 //===----------------------------------------------------------------------===//
43 //===----------------------------------------------------------------------===//
45 Input::Input(StringRef InputContent,
47 SourceMgr::DiagHandlerTy DiagHandler,
48 void *DiagHandlerCtxt)
50 Strm(new Stream(InputContent, SrcMgr)),
51 CurrentNode(nullptr) {
53 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
54 DocIterator = Strm->begin();
60 std::error_code Input::error() { return EC; }
62 // Pin the vtables to this file.
63 void Input::HNode::anchor() {}
64 void Input::EmptyHNode::anchor() {}
65 void Input::ScalarHNode::anchor() {}
67 bool Input::outputting() {
71 bool Input::setCurrentDocument() {
72 if (DocIterator != Strm->end()) {
73 Node *N = DocIterator->getRoot();
75 assert(Strm->failed() && "Root is NULL iff parsing failed");
76 EC = make_error_code(errc::invalid_argument);
80 if (isa<NullNode>(N)) {
81 // Empty files are allowed and ignored
83 return setCurrentDocument();
85 TopNode.reset(this->createHNodes(N));
86 CurrentNode = TopNode.get();
92 bool Input::nextDocument() {
93 return ++DocIterator != Strm->end();
96 bool Input::mapTag(StringRef Tag, bool Default) {
97 std::string foundTag = CurrentNode->_node->getVerbatimTag();
98 if (foundTag.empty()) {
99 // If no tag found and 'Tag' is the default, say it was found.
102 // Return true iff found tag matches supplied tag.
103 return Tag.equals(foundTag);
106 void Input::beginMapping() {
109 // CurrentNode can be null if the document is empty.
110 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
112 MN->ValidKeys.clear();
116 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
122 // CurrentNode is null for empty documents, which is an error in case required
123 // nodes are present.
126 EC = make_error_code(errc::invalid_argument);
130 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
132 setError(CurrentNode, "not a mapping");
135 MN->ValidKeys.push_back(Key);
136 HNode *Value = MN->Mapping[Key];
139 setError(CurrentNode, Twine("missing required key '") + Key + "'");
144 SaveInfo = CurrentNode;
149 void Input::postflightKey(void *saveInfo) {
150 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
153 void Input::endMapping() {
156 // CurrentNode can be null if the document is empty.
157 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
160 for (const auto &NN : MN->Mapping) {
161 if (!MN->isValidKey(NN.first())) {
162 setError(NN.second, Twine("unknown key '") + NN.first() + "'");
168 unsigned Input::beginSequence() {
169 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
170 return SQ->Entries.size();
175 void Input::endSequence() {
178 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
181 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
182 SaveInfo = CurrentNode;
183 CurrentNode = SQ->Entries[Index];
189 void Input::postflightElement(void *SaveInfo) {
190 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
193 unsigned Input::beginFlowSequence() {
194 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
195 return SQ->Entries.size();
200 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
203 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
204 SaveInfo = CurrentNode;
205 CurrentNode = SQ->Entries[index];
211 void Input::postflightFlowElement(void *SaveInfo) {
212 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
215 void Input::endFlowSequence() {
218 void Input::beginEnumScalar() {
219 ScalarMatchFound = false;
222 bool Input::matchEnumScalar(const char *Str, bool) {
223 if (ScalarMatchFound)
225 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
226 if (SN->value().equals(Str)) {
227 ScalarMatchFound = true;
234 void Input::endEnumScalar() {
235 if (!ScalarMatchFound) {
236 setError(CurrentNode, "unknown enumerated scalar");
240 bool Input::beginBitSetScalar(bool &DoClear) {
241 BitValuesUsed.clear();
242 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
243 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
245 setError(CurrentNode, "expected sequence of bit values");
251 bool Input::bitSetMatch(const char *Str, bool) {
254 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
256 for (HNode *N : SQ->Entries) {
257 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N)) {
258 if (SN->value().equals(Str)) {
259 BitValuesUsed[Index] = true;
263 setError(CurrentNode, "unexpected scalar in sequence of bit values");
268 setError(CurrentNode, "expected sequence of bit values");
273 void Input::endBitSetScalar() {
276 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
277 assert(BitValuesUsed.size() == SQ->Entries.size());
278 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
279 if (!BitValuesUsed[i]) {
280 setError(SQ->Entries[i], "unknown bit value");
287 void Input::scalarString(StringRef &S, bool) {
288 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
291 setError(CurrentNode, "unexpected scalar");
295 void Input::setError(HNode *hnode, const Twine &message) {
296 assert(hnode && "HNode must not be NULL");
297 this->setError(hnode->_node, message);
300 void Input::setError(Node *node, const Twine &message) {
301 Strm->printError(node, message);
302 EC = make_error_code(errc::invalid_argument);
305 Input::HNode *Input::createHNodes(Node *N) {
306 SmallString<128> StringStorage;
307 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
308 StringRef KeyStr = SN->getValue(StringStorage);
309 if (!StringStorage.empty()) {
310 // Copy string to permanent storage
311 unsigned Len = StringStorage.size();
312 char *Buf = StringAllocator.Allocate<char>(Len);
313 memcpy(Buf, &StringStorage[0], Len);
314 KeyStr = StringRef(Buf, Len);
316 return new ScalarHNode(N, KeyStr);
317 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
318 SequenceHNode *SQHNode = new SequenceHNode(N);
319 for (Node &SN : *SQ) {
320 HNode *Entry = this->createHNodes(&SN);
323 SQHNode->Entries.push_back(Entry);
326 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
327 MapHNode *mapHNode = new MapHNode(N);
328 for (KeyValueNode &KVN : *Map) {
329 Node *KeyNode = KVN.getKey();
330 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(KeyNode);
332 setError(KeyNode, "Map key must be a scalar");
335 StringStorage.clear();
336 StringRef KeyStr = KeyScalar->getValue(StringStorage);
337 if (!StringStorage.empty()) {
338 // Copy string to permanent storage
339 unsigned Len = StringStorage.size();
340 char *Buf = StringAllocator.Allocate<char>(Len);
341 memcpy(Buf, &StringStorage[0], Len);
342 KeyStr = StringRef(Buf, Len);
344 HNode *ValueHNode = this->createHNodes(KVN.getValue());
347 mapHNode->Mapping[KeyStr] = ValueHNode;
350 } else if (isa<NullNode>(N)) {
351 return new EmptyHNode(N);
353 setError(N, "unknown node kind");
358 bool Input::MapHNode::isValidKey(StringRef Key) {
359 for (const char *K : ValidKeys) {
366 void Input::setError(const Twine &Message) {
367 this->setError(CurrentNode, Message);
370 bool Input::canElideEmptySequence() {
374 Input::MapHNode::~MapHNode() {
375 for (auto &N : Mapping)
379 Input::SequenceHNode::~SequenceHNode() {
380 for (HNode *N : Entries)
386 //===----------------------------------------------------------------------===//
388 //===----------------------------------------------------------------------===//
390 Output::Output(raw_ostream &yout, void *context)
394 ColumnAtFlowStart(0),
395 NeedBitValueComma(false),
396 NeedFlowSequenceComma(false),
397 EnumerationMatchFound(false),
398 NeedsNewLine(false) {
404 bool Output::outputting() {
408 void Output::beginMapping() {
409 StateStack.push_back(inMapFirstKey);
413 bool Output::mapTag(StringRef Tag, bool Use) {
421 void Output::endMapping() {
422 StateStack.pop_back();
425 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
426 bool &UseDefault, void *&) {
428 if (Required || !SameAsDefault) {
429 this->newLineCheck();
430 this->paddedKey(Key);
436 void Output::postflightKey(void *) {
437 if (StateStack.back() == inMapFirstKey) {
438 StateStack.pop_back();
439 StateStack.push_back(inMapOtherKey);
443 void Output::beginDocuments() {
444 this->outputUpToEndOfLine("---");
447 bool Output::preflightDocument(unsigned index) {
449 this->outputUpToEndOfLine("\n---");
453 void Output::postflightDocument() {
456 void Output::endDocuments() {
460 unsigned Output::beginSequence() {
461 StateStack.push_back(inSeq);
466 void Output::endSequence() {
467 StateStack.pop_back();
470 bool Output::preflightElement(unsigned, void *&) {
474 void Output::postflightElement(void *) {
477 unsigned Output::beginFlowSequence() {
478 StateStack.push_back(inFlowSeq);
479 this->newLineCheck();
480 ColumnAtFlowStart = Column;
482 NeedFlowSequenceComma = false;
486 void Output::endFlowSequence() {
487 StateStack.pop_back();
488 this->outputUpToEndOfLine(" ]");
491 bool Output::preflightFlowElement(unsigned, void *&) {
492 if (NeedFlowSequenceComma)
496 for (int i = 0; i < ColumnAtFlowStart; ++i)
498 Column = ColumnAtFlowStart;
504 void Output::postflightFlowElement(void *) {
505 NeedFlowSequenceComma = true;
508 void Output::beginEnumScalar() {
509 EnumerationMatchFound = false;
512 bool Output::matchEnumScalar(const char *Str, bool Match) {
513 if (Match && !EnumerationMatchFound) {
514 this->newLineCheck();
515 this->outputUpToEndOfLine(Str);
516 EnumerationMatchFound = true;
521 void Output::endEnumScalar() {
522 if (!EnumerationMatchFound)
523 llvm_unreachable("bad runtime enum value");
526 bool Output::beginBitSetScalar(bool &DoClear) {
527 this->newLineCheck();
529 NeedBitValueComma = false;
534 bool Output::bitSetMatch(const char *Str, bool Matches) {
536 if (NeedBitValueComma)
539 NeedBitValueComma = true;
544 void Output::endBitSetScalar() {
545 this->outputUpToEndOfLine(" ]");
548 void Output::scalarString(StringRef &S, bool MustQuote) {
549 this->newLineCheck();
551 // Print '' for the empty string because leaving the field empty is not
553 this->outputUpToEndOfLine("''");
557 // Only quote if we must.
558 this->outputUpToEndOfLine(S);
563 unsigned End = S.size();
564 output("'"); // Starting single quote.
565 const char *Base = S.data();
567 // Escape a single quote by doubling it.
569 output(StringRef(&Base[i], j - i + 1));
575 output(StringRef(&Base[i], j - i));
576 this->outputUpToEndOfLine("'"); // Ending single quote.
579 void Output::setError(const Twine &message) {
582 bool Output::canElideEmptySequence() {
583 // Normally, with an optional key/value where the value is an empty sequence,
584 // the whole key/value can be not written. But, that produces wrong yaml
585 // if the key/value is the only thing in the map and the map is used in
586 // a sequence. This detects if the this sequence is the first key/value
587 // in map that itself is embedded in a sequnce.
588 if (StateStack.size() < 2)
590 if (StateStack.back() != inMapFirstKey)
592 return (StateStack[StateStack.size()-2] != inSeq);
595 void Output::output(StringRef s) {
600 void Output::outputUpToEndOfLine(StringRef s) {
602 if (StateStack.empty() || StateStack.back() != inFlowSeq)
606 void Output::outputNewLine() {
611 // if seq at top, indent as if map, then add "- "
612 // if seq in middle, use "- " if firstKey, else use " "
615 void Output::newLineCheck() {
618 NeedsNewLine = false;
620 this->outputNewLine();
622 assert(StateStack.size() > 0);
623 unsigned Indent = StateStack.size() - 1;
624 bool OutputDash = false;
626 if (StateStack.back() == inSeq) {
628 } else if ((StateStack.size() > 1) && (StateStack.back() == inMapFirstKey) &&
629 (StateStack[StateStack.size() - 2] == inSeq)) {
634 for (unsigned i = 0; i < Indent; ++i) {
643 void Output::paddedKey(StringRef key) {
646 const char *spaces = " ";
647 if (key.size() < strlen(spaces))
648 output(&spaces[key.size()]);
653 //===----------------------------------------------------------------------===//
654 // traits for built-in types
655 //===----------------------------------------------------------------------===//
657 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
658 Out << (Val ? "true" : "false");
661 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
662 if (Scalar.equals("true")) {
665 } else if (Scalar.equals("false")) {
669 return "invalid boolean";
672 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
677 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
683 void ScalarTraits<std::string>::output(const std::string &Val, void *,
688 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
694 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
696 // use temp uin32_t because ostream thinks uint8_t is a character
701 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
702 unsigned long long n;
703 if (getAsUnsignedInteger(Scalar, 0, n))
704 return "invalid number";
706 return "out of range number";
711 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
716 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
718 unsigned long long n;
719 if (getAsUnsignedInteger(Scalar, 0, n))
720 return "invalid number";
722 return "out of range number";
727 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
732 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
734 unsigned long long n;
735 if (getAsUnsignedInteger(Scalar, 0, n))
736 return "invalid number";
737 if (n > 0xFFFFFFFFUL)
738 return "out of range number";
743 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
748 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
750 unsigned long long N;
751 if (getAsUnsignedInteger(Scalar, 0, N))
752 return "invalid number";
757 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
758 // use temp in32_t because ostream thinks int8_t is a character
763 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
765 if (getAsSignedInteger(Scalar, 0, N))
766 return "invalid number";
767 if ((N > 127) || (N < -128))
768 return "out of range number";
773 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
778 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
780 if (getAsSignedInteger(Scalar, 0, N))
781 return "invalid number";
782 if ((N > INT16_MAX) || (N < INT16_MIN))
783 return "out of range number";
788 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
793 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
795 if (getAsSignedInteger(Scalar, 0, N))
796 return "invalid number";
797 if ((N > INT32_MAX) || (N < INT32_MIN))
798 return "out of range number";
803 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
808 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
810 if (getAsSignedInteger(Scalar, 0, N))
811 return "invalid number";
816 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
817 Out << format("%g", Val);
820 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
821 SmallString<32> buff(Scalar.begin(), Scalar.end());
823 Val = strtod(buff.c_str(), &end);
825 return "invalid floating point number";
829 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
830 Out << format("%g", Val);
833 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
834 SmallString<32> buff(Scalar.begin(), Scalar.end());
836 Val = strtod(buff.c_str(), &end);
838 return "invalid floating point number";
842 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
844 Out << format("0x%02X", Num);
847 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
848 unsigned long long n;
849 if (getAsUnsignedInteger(Scalar, 0, n))
850 return "invalid hex8 number";
852 return "out of range hex8 number";
857 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
859 Out << format("0x%04X", Num);
862 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
863 unsigned long long n;
864 if (getAsUnsignedInteger(Scalar, 0, n))
865 return "invalid hex16 number";
867 return "out of range hex16 number";
872 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
874 Out << format("0x%08X", Num);
877 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
878 unsigned long long n;
879 if (getAsUnsignedInteger(Scalar, 0, n))
880 return "invalid hex32 number";
881 if (n > 0xFFFFFFFFUL)
882 return "out of range hex32 number";
887 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
889 Out << format("0x%016llX", Num);
892 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
893 unsigned long long Num;
894 if (getAsUnsignedInteger(Scalar, 0, Num))
895 return "invalid hex64 number";