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/YAMLParser.h"
18 #include "llvm/Support/raw_ostream.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 IO::IO(void *Context) : Ctxt(Context) {
34 void *IO::getContext() {
38 void IO::setContext(void *Context) {
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
46 Input::Input(StringRef InputContent,
48 SourceMgr::DiagHandlerTy DiagHandler,
49 void *DiagHandlerCtxt)
51 Strm(new Stream(InputContent, SrcMgr)),
52 CurrentNode(nullptr) {
54 SrcMgr.setDiagHandler(DiagHandler, DiagHandlerCtxt);
55 DocIterator = Strm->begin();
61 std::error_code Input::error() { return EC; }
63 // Pin the vtables to this file.
64 void Input::HNode::anchor() {}
65 void Input::EmptyHNode::anchor() {}
66 void Input::ScalarHNode::anchor() {}
67 void Input::MapHNode::anchor() {}
68 void Input::SequenceHNode::anchor() {}
70 bool Input::outputting() {
74 bool Input::setCurrentDocument() {
75 if (DocIterator != Strm->end()) {
76 Node *N = DocIterator->getRoot();
78 assert(Strm->failed() && "Root is NULL iff parsing failed");
79 EC = make_error_code(errc::invalid_argument);
83 if (isa<NullNode>(N)) {
84 // Empty files are allowed and ignored
86 return setCurrentDocument();
88 TopNode = this->createHNodes(N);
89 CurrentNode = TopNode.get();
95 bool Input::nextDocument() {
96 return ++DocIterator != Strm->end();
99 bool Input::mapTag(StringRef Tag, bool Default) {
100 std::string foundTag = CurrentNode->_node->getVerbatimTag();
101 if (foundTag.empty()) {
102 // If no tag found and 'Tag' is the default, say it was found.
105 // Return true iff found tag matches supplied tag.
106 return Tag.equals(foundTag);
109 void Input::beginMapping() {
112 // CurrentNode can be null if the document is empty.
113 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
115 MN->ValidKeys.clear();
119 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
125 // CurrentNode is null for empty documents, which is an error in case required
126 // nodes are present.
129 EC = make_error_code(errc::invalid_argument);
133 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
135 setError(CurrentNode, "not a mapping");
138 MN->ValidKeys.push_back(Key);
139 HNode *Value = MN->Mapping[Key].get();
142 setError(CurrentNode, Twine("missing required key '") + Key + "'");
147 SaveInfo = CurrentNode;
152 void Input::postflightKey(void *saveInfo) {
153 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
156 void Input::endMapping() {
159 // CurrentNode can be null if the document is empty.
160 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
163 for (const auto &NN : MN->Mapping) {
164 if (!MN->isValidKey(NN.first())) {
165 setError(NN.second.get(), Twine("unknown key '") + NN.first() + "'");
171 unsigned Input::beginSequence() {
172 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode))
173 return SQ->Entries.size();
174 if (isa<EmptyHNode>(CurrentNode))
176 // Treat case where there's a scalar "null" value as an empty sequence.
177 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
178 if (isNull(SN->value()))
181 // Any other type of HNode is an error.
182 setError(CurrentNode, "not a sequence");
186 void Input::endSequence() {
189 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
192 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
193 SaveInfo = CurrentNode;
194 CurrentNode = SQ->Entries[Index].get();
200 void Input::postflightElement(void *SaveInfo) {
201 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
204 unsigned Input::beginFlowSequence() { return beginSequence(); }
206 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
209 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
210 SaveInfo = CurrentNode;
211 CurrentNode = SQ->Entries[index].get();
217 void Input::postflightFlowElement(void *SaveInfo) {
218 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
221 void Input::endFlowSequence() {
224 void Input::beginEnumScalar() {
225 ScalarMatchFound = false;
228 bool Input::matchEnumScalar(const char *Str, bool) {
229 if (ScalarMatchFound)
231 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
232 if (SN->value().equals(Str)) {
233 ScalarMatchFound = true;
240 bool Input::matchEnumFallback() {
241 if (ScalarMatchFound)
243 ScalarMatchFound = true;
247 void Input::endEnumScalar() {
248 if (!ScalarMatchFound) {
249 setError(CurrentNode, "unknown enumerated scalar");
253 bool Input::beginBitSetScalar(bool &DoClear) {
254 BitValuesUsed.clear();
255 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
256 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
258 setError(CurrentNode, "expected sequence of bit values");
264 bool Input::bitSetMatch(const char *Str, bool) {
267 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
269 for (auto &N : SQ->Entries) {
270 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) {
271 if (SN->value().equals(Str)) {
272 BitValuesUsed[Index] = true;
276 setError(CurrentNode, "unexpected scalar in sequence of bit values");
281 setError(CurrentNode, "expected sequence of bit values");
286 void Input::endBitSetScalar() {
289 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
290 assert(BitValuesUsed.size() == SQ->Entries.size());
291 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
292 if (!BitValuesUsed[i]) {
293 setError(SQ->Entries[i].get(), "unknown bit value");
300 void Input::scalarString(StringRef &S, bool) {
301 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
304 setError(CurrentNode, "unexpected scalar");
308 void Input::setError(HNode *hnode, const Twine &message) {
309 assert(hnode && "HNode must not be NULL");
310 this->setError(hnode->_node, message);
313 void Input::setError(Node *node, const Twine &message) {
314 Strm->printError(node, message);
315 EC = make_error_code(errc::invalid_argument);
318 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
319 SmallString<128> StringStorage;
320 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
321 StringRef KeyStr = SN->getValue(StringStorage);
322 if (!StringStorage.empty()) {
323 // Copy string to permanent storage
324 unsigned Len = StringStorage.size();
325 char *Buf = StringAllocator.Allocate<char>(Len);
326 memcpy(Buf, &StringStorage[0], Len);
327 KeyStr = StringRef(Buf, Len);
329 return llvm::make_unique<ScalarHNode>(N, KeyStr);
330 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
331 auto SQHNode = llvm::make_unique<SequenceHNode>(N);
332 for (Node &SN : *SQ) {
333 auto Entry = this->createHNodes(&SN);
336 SQHNode->Entries.push_back(std::move(Entry));
338 return std::move(SQHNode);
339 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
340 auto mapHNode = llvm::make_unique<MapHNode>(N);
341 for (KeyValueNode &KVN : *Map) {
342 Node *KeyNode = KVN.getKey();
343 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(KeyNode);
345 setError(KeyNode, "Map key must be a scalar");
348 StringStorage.clear();
349 StringRef KeyStr = KeyScalar->getValue(StringStorage);
350 if (!StringStorage.empty()) {
351 // Copy string to permanent storage
352 unsigned Len = StringStorage.size();
353 char *Buf = StringAllocator.Allocate<char>(Len);
354 memcpy(Buf, &StringStorage[0], Len);
355 KeyStr = StringRef(Buf, Len);
357 auto ValueHNode = this->createHNodes(KVN.getValue());
360 mapHNode->Mapping[KeyStr] = std::move(ValueHNode);
362 return std::move(mapHNode);
363 } else if (isa<NullNode>(N)) {
364 return llvm::make_unique<EmptyHNode>(N);
366 setError(N, "unknown node kind");
371 bool Input::MapHNode::isValidKey(StringRef Key) {
372 for (const char *K : ValidKeys) {
379 void Input::setError(const Twine &Message) {
380 this->setError(CurrentNode, Message);
383 bool Input::canElideEmptySequence() {
387 //===----------------------------------------------------------------------===//
389 //===----------------------------------------------------------------------===//
391 Output::Output(raw_ostream &yout, void *context)
395 ColumnAtFlowStart(0),
396 NeedBitValueComma(false),
397 NeedFlowSequenceComma(false),
398 EnumerationMatchFound(false),
399 NeedsNewLine(false) {
405 bool Output::outputting() {
409 void Output::beginMapping() {
410 StateStack.push_back(inMapFirstKey);
414 bool Output::mapTag(StringRef Tag, bool Use) {
422 void Output::endMapping() {
423 StateStack.pop_back();
426 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
427 bool &UseDefault, void *&) {
429 if (Required || !SameAsDefault) {
430 this->newLineCheck();
431 this->paddedKey(Key);
437 void Output::postflightKey(void *) {
438 if (StateStack.back() == inMapFirstKey) {
439 StateStack.pop_back();
440 StateStack.push_back(inMapOtherKey);
444 void Output::beginDocuments() {
445 this->outputUpToEndOfLine("---");
448 bool Output::preflightDocument(unsigned index) {
450 this->outputUpToEndOfLine("\n---");
454 void Output::postflightDocument() {
457 void Output::endDocuments() {
461 unsigned Output::beginSequence() {
462 StateStack.push_back(inSeq);
467 void Output::endSequence() {
468 StateStack.pop_back();
471 bool Output::preflightElement(unsigned, void *&) {
475 void Output::postflightElement(void *) {
478 unsigned Output::beginFlowSequence() {
479 StateStack.push_back(inFlowSeq);
480 this->newLineCheck();
481 ColumnAtFlowStart = Column;
483 NeedFlowSequenceComma = false;
487 void Output::endFlowSequence() {
488 StateStack.pop_back();
489 this->outputUpToEndOfLine(" ]");
492 bool Output::preflightFlowElement(unsigned, void *&) {
493 if (NeedFlowSequenceComma)
497 for (int i = 0; i < ColumnAtFlowStart; ++i)
499 Column = ColumnAtFlowStart;
505 void Output::postflightFlowElement(void *) {
506 NeedFlowSequenceComma = true;
509 void Output::beginEnumScalar() {
510 EnumerationMatchFound = false;
513 bool Output::matchEnumScalar(const char *Str, bool Match) {
514 if (Match && !EnumerationMatchFound) {
515 this->newLineCheck();
516 this->outputUpToEndOfLine(Str);
517 EnumerationMatchFound = true;
522 bool Output::matchEnumFallback() {
523 if (EnumerationMatchFound)
525 EnumerationMatchFound = true;
529 void Output::endEnumScalar() {
530 if (!EnumerationMatchFound)
531 llvm_unreachable("bad runtime enum value");
534 bool Output::beginBitSetScalar(bool &DoClear) {
535 this->newLineCheck();
537 NeedBitValueComma = false;
542 bool Output::bitSetMatch(const char *Str, bool Matches) {
544 if (NeedBitValueComma)
547 NeedBitValueComma = true;
552 void Output::endBitSetScalar() {
553 this->outputUpToEndOfLine(" ]");
556 void Output::scalarString(StringRef &S, bool MustQuote) {
557 this->newLineCheck();
559 // Print '' for the empty string because leaving the field empty is not
561 this->outputUpToEndOfLine("''");
565 // Only quote if we must.
566 this->outputUpToEndOfLine(S);
571 unsigned End = S.size();
572 output("'"); // Starting single quote.
573 const char *Base = S.data();
575 // Escape a single quote by doubling it.
577 output(StringRef(&Base[i], j - i + 1));
583 output(StringRef(&Base[i], j - i));
584 this->outputUpToEndOfLine("'"); // Ending single quote.
587 void Output::setError(const Twine &message) {
590 bool Output::canElideEmptySequence() {
591 // Normally, with an optional key/value where the value is an empty sequence,
592 // the whole key/value can be not written. But, that produces wrong yaml
593 // if the key/value is the only thing in the map and the map is used in
594 // a sequence. This detects if the this sequence is the first key/value
595 // in map that itself is embedded in a sequnce.
596 if (StateStack.size() < 2)
598 if (StateStack.back() != inMapFirstKey)
600 return (StateStack[StateStack.size()-2] != inSeq);
603 void Output::output(StringRef s) {
608 void Output::outputUpToEndOfLine(StringRef s) {
610 if (StateStack.empty() || StateStack.back() != inFlowSeq)
614 void Output::outputNewLine() {
619 // if seq at top, indent as if map, then add "- "
620 // if seq in middle, use "- " if firstKey, else use " "
623 void Output::newLineCheck() {
626 NeedsNewLine = false;
628 this->outputNewLine();
630 assert(StateStack.size() > 0);
631 unsigned Indent = StateStack.size() - 1;
632 bool OutputDash = false;
634 if (StateStack.back() == inSeq) {
636 } else if ((StateStack.size() > 1) && (StateStack.back() == inMapFirstKey) &&
637 (StateStack[StateStack.size() - 2] == inSeq)) {
642 for (unsigned i = 0; i < Indent; ++i) {
651 void Output::paddedKey(StringRef key) {
654 const char *spaces = " ";
655 if (key.size() < strlen(spaces))
656 output(&spaces[key.size()]);
661 //===----------------------------------------------------------------------===//
662 // traits for built-in types
663 //===----------------------------------------------------------------------===//
665 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
666 Out << (Val ? "true" : "false");
669 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
670 if (Scalar.equals("true")) {
673 } else if (Scalar.equals("false")) {
677 return "invalid boolean";
680 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
685 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
691 void ScalarTraits<std::string>::output(const std::string &Val, void *,
696 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
702 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
704 // use temp uin32_t because ostream thinks uint8_t is a character
709 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
710 unsigned long long n;
711 if (getAsUnsignedInteger(Scalar, 0, n))
712 return "invalid number";
714 return "out of range number";
719 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
724 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
726 unsigned long long n;
727 if (getAsUnsignedInteger(Scalar, 0, n))
728 return "invalid number";
730 return "out of range number";
735 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
740 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
742 unsigned long long n;
743 if (getAsUnsignedInteger(Scalar, 0, n))
744 return "invalid number";
745 if (n > 0xFFFFFFFFUL)
746 return "out of range number";
751 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
756 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
758 unsigned long long N;
759 if (getAsUnsignedInteger(Scalar, 0, N))
760 return "invalid number";
765 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
766 // use temp in32_t because ostream thinks int8_t is a character
771 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
773 if (getAsSignedInteger(Scalar, 0, N))
774 return "invalid number";
775 if ((N > 127) || (N < -128))
776 return "out of range number";
781 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
786 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
788 if (getAsSignedInteger(Scalar, 0, N))
789 return "invalid number";
790 if ((N > INT16_MAX) || (N < INT16_MIN))
791 return "out of range number";
796 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
801 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
803 if (getAsSignedInteger(Scalar, 0, N))
804 return "invalid number";
805 if ((N > INT32_MAX) || (N < INT32_MIN))
806 return "out of range number";
811 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
816 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
818 if (getAsSignedInteger(Scalar, 0, N))
819 return "invalid number";
824 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
825 Out << format("%g", Val);
828 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
829 SmallString<32> buff(Scalar.begin(), Scalar.end());
831 Val = strtod(buff.c_str(), &end);
833 return "invalid floating point number";
837 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
838 Out << format("%g", Val);
841 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
842 SmallString<32> buff(Scalar.begin(), Scalar.end());
844 Val = strtod(buff.c_str(), &end);
846 return "invalid floating point number";
850 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
852 Out << format("0x%02X", Num);
855 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
856 unsigned long long n;
857 if (getAsUnsignedInteger(Scalar, 0, n))
858 return "invalid hex8 number";
860 return "out of range hex8 number";
865 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
867 Out << format("0x%04X", Num);
870 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
871 unsigned long long n;
872 if (getAsUnsignedInteger(Scalar, 0, n))
873 return "invalid hex16 number";
875 return "out of range hex16 number";
880 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
882 Out << format("0x%08X", Num);
885 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
886 unsigned long long n;
887 if (getAsUnsignedInteger(Scalar, 0, n))
888 return "invalid hex32 number";
889 if (n > 0xFFFFFFFFUL)
890 return "out of range hex32 number";
895 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
897 Out << format("0x%016llX", Num);
900 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
901 unsigned long long Num;
902 if (getAsUnsignedInteger(Scalar, 0, Num))
903 return "invalid hex64 number";