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/Twine.h"
12 #include "llvm/Support/Casting.h"
13 #include "llvm/Support/ErrorHandling.h"
14 #include "llvm/Support/Format.h"
15 #include "llvm/Support/YAMLParser.h"
16 #include "llvm/Support/raw_ostream.h"
22 //===----------------------------------------------------------------------===//
24 //===----------------------------------------------------------------------===//
26 IO::IO(void *Context) : Ctxt(Context) {
32 void *IO::getContext() {
36 void IO::setContext(void *Context) {
40 //===----------------------------------------------------------------------===//
42 //===----------------------------------------------------------------------===//
44 Input::Input(StringRef InputContent,
46 SourceMgr::DiagHandlerTy DiagHandler,
47 void *DiagHandlerCtxt)
49 Strm(new Stream(InputContent, SrcMgr)),
50 CurrentNode(nullptr) {
52 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
53 DocIterator = Strm->begin();
59 error_code Input::error() {
63 // Pin the vtables to this file.
64 void Input::HNode::anchor() {}
65 void Input::EmptyHNode::anchor() {}
66 void Input::ScalarHNode::anchor() {}
68 bool Input::outputting() {
72 bool Input::setCurrentDocument() {
73 if (DocIterator != Strm->end()) {
74 Node *N = DocIterator->getRoot();
76 assert(Strm->failed() && "Root is NULL iff parsing failed");
77 EC = make_error_code(errc::invalid_argument);
81 if (isa<NullNode>(N)) {
82 // Empty files are allowed and ignored
84 return setCurrentDocument();
86 TopNode.reset(this->createHNodes(N));
87 CurrentNode = TopNode.get();
93 void Input::nextDocument() {
97 bool Input::mapTag(StringRef Tag, bool Default) {
98 std::string foundTag = CurrentNode->_node->getVerbatimTag();
99 if (foundTag.empty()) {
100 // If no tag found and 'Tag' is the default, say it was found.
103 // Return true iff found tag matches supplied tag.
104 return Tag.equals(foundTag);
107 void Input::beginMapping() {
110 // CurrentNode can be null if the document is empty.
111 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
113 MN->ValidKeys.clear();
117 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
123 // CurrentNode is null for empty documents, which is an error in case required
124 // nodes are present.
127 EC = make_error_code(errc::invalid_argument);
131 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
133 setError(CurrentNode, "not a mapping");
136 MN->ValidKeys.push_back(Key);
137 HNode *Value = MN->Mapping[Key];
140 setError(CurrentNode, Twine("missing required key '") + Key + "'");
145 SaveInfo = CurrentNode;
150 void Input::postflightKey(void *saveInfo) {
151 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
154 void Input::endMapping() {
157 // CurrentNode can be null if the document is empty.
158 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
161 for (const auto &NN : MN->Mapping) {
162 if (!MN->isValidKey(NN.first())) {
163 setError(NN.second, Twine("unknown key '") + NN.first() + "'");
169 unsigned Input::beginSequence() {
170 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
171 return SQ->Entries.size();
176 void Input::endSequence() {
179 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
182 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
183 SaveInfo = CurrentNode;
184 CurrentNode = SQ->Entries[Index];
190 void Input::postflightElement(void *SaveInfo) {
191 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
194 unsigned Input::beginFlowSequence() {
195 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
196 return SQ->Entries.size();
201 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
204 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
205 SaveInfo = CurrentNode;
206 CurrentNode = SQ->Entries[index];
212 void Input::postflightFlowElement(void *SaveInfo) {
213 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
216 void Input::endFlowSequence() {
219 void Input::beginEnumScalar() {
220 ScalarMatchFound = false;
223 bool Input::matchEnumScalar(const char *Str, bool) {
224 if (ScalarMatchFound)
226 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
227 if (SN->value().equals(Str)) {
228 ScalarMatchFound = true;
235 void Input::endEnumScalar() {
236 if (!ScalarMatchFound) {
237 setError(CurrentNode, "unknown enumerated scalar");
241 bool Input::beginBitSetScalar(bool &DoClear) {
242 BitValuesUsed.clear();
243 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
244 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
246 setError(CurrentNode, "expected sequence of bit values");
252 bool Input::bitSetMatch(const char *Str, bool) {
255 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
257 for (HNode *N : SQ->Entries) {
258 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N)) {
259 if (SN->value().equals(Str)) {
260 BitValuesUsed[Index] = true;
264 setError(CurrentNode, "unexpected scalar in sequence of bit values");
269 setError(CurrentNode, "expected sequence of bit values");
274 void Input::endBitSetScalar() {
277 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
278 assert(BitValuesUsed.size() == SQ->Entries.size());
279 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
280 if (!BitValuesUsed[i]) {
281 setError(SQ->Entries[i], "unknown bit value");
288 void Input::scalarString(StringRef &S, bool) {
289 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
292 setError(CurrentNode, "unexpected scalar");
296 void Input::setError(HNode *hnode, const Twine &message) {
297 assert(hnode && "HNode must not be NULL");
298 this->setError(hnode->_node, message);
301 void Input::setError(Node *node, const Twine &message) {
302 Strm->printError(node, message);
303 EC = make_error_code(errc::invalid_argument);
306 Input::HNode *Input::createHNodes(Node *N) {
307 SmallString<128> StringStorage;
308 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
309 StringRef KeyStr = SN->getValue(StringStorage);
310 if (!StringStorage.empty()) {
311 // Copy string to permanent storage
312 unsigned Len = StringStorage.size();
313 char *Buf = StringAllocator.Allocate<char>(Len);
314 memcpy(Buf, &StringStorage[0], Len);
315 KeyStr = StringRef(Buf, Len);
317 return new ScalarHNode(N, KeyStr);
318 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
319 SequenceHNode *SQHNode = new SequenceHNode(N);
320 for (Node &SN : *SQ) {
321 HNode *Entry = this->createHNodes(&SN);
324 SQHNode->Entries.push_back(Entry);
327 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
328 MapHNode *mapHNode = new MapHNode(N);
329 for (KeyValueNode &KVN : *Map) {
330 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(KVN.getKey());
331 StringStorage.clear();
332 StringRef KeyStr = KeyScalar->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 HNode *ValueHNode = this->createHNodes(KVN.getValue());
343 mapHNode->Mapping[KeyStr] = ValueHNode;
346 } else if (isa<NullNode>(N)) {
347 return new EmptyHNode(N);
349 setError(N, "unknown node kind");
354 bool Input::MapHNode::isValidKey(StringRef Key) {
355 for (const char *K : ValidKeys) {
362 void Input::setError(const Twine &Message) {
363 this->setError(CurrentNode, Message);
366 bool Input::canElideEmptySequence() {
370 Input::MapHNode::~MapHNode() {
371 for (auto &N : Mapping)
375 Input::SequenceHNode::~SequenceHNode() {
376 for (HNode *N : Entries)
382 //===----------------------------------------------------------------------===//
384 //===----------------------------------------------------------------------===//
386 Output::Output(raw_ostream &yout, void *context)
390 ColumnAtFlowStart(0),
391 NeedBitValueComma(false),
392 NeedFlowSequenceComma(false),
393 EnumerationMatchFound(false),
394 NeedsNewLine(false) {
400 bool Output::outputting() {
404 void Output::beginMapping() {
405 StateStack.push_back(inMapFirstKey);
409 bool Output::mapTag(StringRef Tag, bool Use) {
417 void Output::endMapping() {
418 StateStack.pop_back();
421 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
422 bool &UseDefault, void *&) {
424 if (Required || !SameAsDefault) {
425 this->newLineCheck();
426 this->paddedKey(Key);
432 void Output::postflightKey(void *) {
433 if (StateStack.back() == inMapFirstKey) {
434 StateStack.pop_back();
435 StateStack.push_back(inMapOtherKey);
439 void Output::beginDocuments() {
440 this->outputUpToEndOfLine("---");
443 bool Output::preflightDocument(unsigned index) {
445 this->outputUpToEndOfLine("\n---");
449 void Output::postflightDocument() {
452 void Output::endDocuments() {
456 unsigned Output::beginSequence() {
457 StateStack.push_back(inSeq);
462 void Output::endSequence() {
463 StateStack.pop_back();
466 bool Output::preflightElement(unsigned, void *&) {
470 void Output::postflightElement(void *) {
473 unsigned Output::beginFlowSequence() {
474 StateStack.push_back(inFlowSeq);
475 this->newLineCheck();
476 ColumnAtFlowStart = Column;
478 NeedFlowSequenceComma = false;
482 void Output::endFlowSequence() {
483 StateStack.pop_back();
484 this->outputUpToEndOfLine(" ]");
487 bool Output::preflightFlowElement(unsigned, void *&) {
488 if (NeedFlowSequenceComma)
492 for (int i = 0; i < ColumnAtFlowStart; ++i)
494 Column = ColumnAtFlowStart;
500 void Output::postflightFlowElement(void *) {
501 NeedFlowSequenceComma = true;
504 void Output::beginEnumScalar() {
505 EnumerationMatchFound = false;
508 bool Output::matchEnumScalar(const char *Str, bool Match) {
509 if (Match && !EnumerationMatchFound) {
510 this->newLineCheck();
511 this->outputUpToEndOfLine(Str);
512 EnumerationMatchFound = true;
517 void Output::endEnumScalar() {
518 if (!EnumerationMatchFound)
519 llvm_unreachable("bad runtime enum value");
522 bool Output::beginBitSetScalar(bool &DoClear) {
523 this->newLineCheck();
525 NeedBitValueComma = false;
530 bool Output::bitSetMatch(const char *Str, bool Matches) {
532 if (NeedBitValueComma)
535 NeedBitValueComma = true;
540 void Output::endBitSetScalar() {
541 this->outputUpToEndOfLine(" ]");
544 void Output::scalarString(StringRef &S, bool MustQuote) {
545 this->newLineCheck();
547 // Print '' for the empty string because leaving the field empty is not
549 this->outputUpToEndOfLine("''");
553 // Only quote if we must.
554 this->outputUpToEndOfLine(S);
559 unsigned End = S.size();
560 output("'"); // Starting single quote.
561 const char *Base = S.data();
563 // Escape a single quote by doubling it.
565 output(StringRef(&Base[i], j - i + 1));
571 output(StringRef(&Base[i], j - i));
572 this->outputUpToEndOfLine("'"); // Ending single quote.
575 void Output::setError(const Twine &message) {
578 bool Output::canElideEmptySequence() {
579 // Normally, with an optional key/value where the value is an empty sequence,
580 // the whole key/value can be not written. But, that produces wrong yaml
581 // if the key/value is the only thing in the map and the map is used in
582 // a sequence. This detects if the this sequence is the first key/value
583 // in map that itself is embedded in a sequnce.
584 if (StateStack.size() < 2)
586 if (StateStack.back() != inMapFirstKey)
588 return (StateStack[StateStack.size()-2] != inSeq);
591 void Output::output(StringRef s) {
596 void Output::outputUpToEndOfLine(StringRef s) {
598 if (StateStack.empty() || StateStack.back() != inFlowSeq)
602 void Output::outputNewLine() {
607 // if seq at top, indent as if map, then add "- "
608 // if seq in middle, use "- " if firstKey, else use " "
611 void Output::newLineCheck() {
614 NeedsNewLine = false;
616 this->outputNewLine();
618 assert(StateStack.size() > 0);
619 unsigned Indent = StateStack.size() - 1;
620 bool OutputDash = false;
622 if (StateStack.back() == inSeq) {
624 } else if ((StateStack.size() > 1) && (StateStack.back() == inMapFirstKey) &&
625 (StateStack[StateStack.size() - 2] == inSeq)) {
630 for (unsigned i = 0; i < Indent; ++i) {
639 void Output::paddedKey(StringRef key) {
642 const char *spaces = " ";
643 if (key.size() < strlen(spaces))
644 output(&spaces[key.size()]);
649 //===----------------------------------------------------------------------===//
650 // traits for built-in types
651 //===----------------------------------------------------------------------===//
653 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
654 Out << (Val ? "true" : "false");
657 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
658 if (Scalar.equals("true")) {
661 } else if (Scalar.equals("false")) {
665 return "invalid boolean";
668 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
673 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
679 void ScalarTraits<std::string>::output(const std::string &Val, void *,
684 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
690 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
692 // use temp uin32_t because ostream thinks uint8_t is a character
697 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
698 unsigned long long n;
699 if (getAsUnsignedInteger(Scalar, 0, n))
700 return "invalid number";
702 return "out of range number";
707 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
712 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
714 unsigned long long n;
715 if (getAsUnsignedInteger(Scalar, 0, n))
716 return "invalid number";
718 return "out of range number";
723 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
728 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
730 unsigned long long n;
731 if (getAsUnsignedInteger(Scalar, 0, n))
732 return "invalid number";
733 if (n > 0xFFFFFFFFUL)
734 return "out of range number";
739 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
744 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
746 unsigned long long N;
747 if (getAsUnsignedInteger(Scalar, 0, N))
748 return "invalid number";
753 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
754 // use temp in32_t because ostream thinks int8_t is a character
759 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
761 if (getAsSignedInteger(Scalar, 0, N))
762 return "invalid number";
763 if ((N > 127) || (N < -128))
764 return "out of range number";
769 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
774 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
776 if (getAsSignedInteger(Scalar, 0, N))
777 return "invalid number";
778 if ((N > INT16_MAX) || (N < INT16_MIN))
779 return "out of range number";
784 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
789 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
791 if (getAsSignedInteger(Scalar, 0, N))
792 return "invalid number";
793 if ((N > INT32_MAX) || (N < INT32_MIN))
794 return "out of range number";
799 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
804 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
806 if (getAsSignedInteger(Scalar, 0, N))
807 return "invalid number";
812 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
813 Out << format("%g", Val);
816 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
817 SmallString<32> buff(Scalar.begin(), Scalar.end());
819 Val = strtod(buff.c_str(), &end);
821 return "invalid floating point number";
825 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
826 Out << format("%g", Val);
829 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
830 SmallString<32> buff(Scalar.begin(), Scalar.end());
832 Val = strtod(buff.c_str(), &end);
834 return "invalid floating point number";
838 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
840 Out << format("0x%02X", Num);
843 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
844 unsigned long long n;
845 if (getAsUnsignedInteger(Scalar, 0, n))
846 return "invalid hex8 number";
848 return "out of range hex8 number";
853 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
855 Out << format("0x%04X", Num);
858 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
859 unsigned long long n;
860 if (getAsUnsignedInteger(Scalar, 0, n))
861 return "invalid hex16 number";
863 return "out of range hex16 number";
868 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
870 Out << format("0x%08X", Num);
873 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
874 unsigned long long n;
875 if (getAsUnsignedInteger(Scalar, 0, n))
876 return "invalid hex32 number";
877 if (n > 0xFFFFFFFFUL)
878 return "out of range hex32 number";
883 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
885 Out << format("0x%016llX", Num);
888 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
889 unsigned long long Num;
890 if (getAsUnsignedInteger(Scalar, 0, Num))
891 return "invalid hex64 number";