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() {}
66 void Input::MapHNode::anchor() {}
67 void Input::SequenceHNode::anchor() {}
69 bool Input::outputting() {
73 bool Input::setCurrentDocument() {
74 if (DocIterator != Strm->end()) {
75 Node *N = DocIterator->getRoot();
77 assert(Strm->failed() && "Root is NULL iff parsing failed");
78 EC = make_error_code(errc::invalid_argument);
82 if (isa<NullNode>(N)) {
83 // Empty files are allowed and ignored
85 return setCurrentDocument();
87 TopNode = this->createHNodes(N);
88 CurrentNode = TopNode.get();
94 bool Input::nextDocument() {
95 return ++DocIterator != Strm->end();
98 bool Input::mapTag(StringRef Tag, bool Default) {
99 std::string foundTag = CurrentNode->_node->getVerbatimTag();
100 if (foundTag.empty()) {
101 // If no tag found and 'Tag' is the default, say it was found.
104 // Return true iff found tag matches supplied tag.
105 return Tag.equals(foundTag);
108 void Input::beginMapping() {
111 // CurrentNode can be null if the document is empty.
112 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
114 MN->ValidKeys.clear();
118 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
124 // CurrentNode is null for empty documents, which is an error in case required
125 // nodes are present.
128 EC = make_error_code(errc::invalid_argument);
132 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
134 setError(CurrentNode, "not a mapping");
137 MN->ValidKeys.push_back(Key);
138 HNode *Value = MN->Mapping[Key].get();
141 setError(CurrentNode, Twine("missing required key '") + Key + "'");
146 SaveInfo = CurrentNode;
151 void Input::postflightKey(void *saveInfo) {
152 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
155 void Input::endMapping() {
158 // CurrentNode can be null if the document is empty.
159 MapHNode *MN = dyn_cast_or_null<MapHNode>(CurrentNode);
162 for (const auto &NN : MN->Mapping) {
163 if (!MN->isValidKey(NN.first())) {
164 setError(NN.second.get(), Twine("unknown key '") + NN.first() + "'");
170 unsigned Input::beginSequence() {
171 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
172 return SQ->Entries.size();
177 void Input::endSequence() {
180 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
183 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
184 SaveInfo = CurrentNode;
185 CurrentNode = SQ->Entries[Index].get();
191 void Input::postflightElement(void *SaveInfo) {
192 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
195 unsigned Input::beginFlowSequence() {
196 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
197 return SQ->Entries.size();
202 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
205 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
206 SaveInfo = CurrentNode;
207 CurrentNode = SQ->Entries[index].get();
213 void Input::postflightFlowElement(void *SaveInfo) {
214 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
217 void Input::endFlowSequence() {
220 void Input::beginEnumScalar() {
221 ScalarMatchFound = false;
224 bool Input::matchEnumScalar(const char *Str, bool) {
225 if (ScalarMatchFound)
227 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
228 if (SN->value().equals(Str)) {
229 ScalarMatchFound = true;
236 void Input::endEnumScalar() {
237 if (!ScalarMatchFound) {
238 setError(CurrentNode, "unknown enumerated scalar");
242 bool Input::beginBitSetScalar(bool &DoClear) {
243 BitValuesUsed.clear();
244 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
245 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
247 setError(CurrentNode, "expected sequence of bit values");
253 bool Input::bitSetMatch(const char *Str, bool) {
256 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
258 for (auto &N : SQ->Entries) {
259 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(N.get())) {
260 if (SN->value().equals(Str)) {
261 BitValuesUsed[Index] = true;
265 setError(CurrentNode, "unexpected scalar in sequence of bit values");
270 setError(CurrentNode, "expected sequence of bit values");
275 void Input::endBitSetScalar() {
278 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
279 assert(BitValuesUsed.size() == SQ->Entries.size());
280 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
281 if (!BitValuesUsed[i]) {
282 setError(SQ->Entries[i].get(), "unknown bit value");
289 void Input::scalarString(StringRef &S, bool) {
290 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
293 setError(CurrentNode, "unexpected scalar");
297 void Input::setError(HNode *hnode, const Twine &message) {
298 assert(hnode && "HNode must not be NULL");
299 this->setError(hnode->_node, message);
302 void Input::setError(Node *node, const Twine &message) {
303 Strm->printError(node, message);
304 EC = make_error_code(errc::invalid_argument);
307 std::unique_ptr<Input::HNode> Input::createHNodes(Node *N) {
308 SmallString<128> StringStorage;
309 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
310 StringRef KeyStr = SN->getValue(StringStorage);
311 if (!StringStorage.empty()) {
312 // Copy string to permanent storage
313 unsigned Len = StringStorage.size();
314 char *Buf = StringAllocator.Allocate<char>(Len);
315 memcpy(Buf, &StringStorage[0], Len);
316 KeyStr = StringRef(Buf, Len);
318 return llvm::make_unique<ScalarHNode>(N, KeyStr);
319 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
320 auto SQHNode = llvm::make_unique<SequenceHNode>(N);
321 for (Node &SN : *SQ) {
322 auto Entry = this->createHNodes(&SN);
325 SQHNode->Entries.push_back(std::move(Entry));
327 return std::move(SQHNode);
328 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
329 auto mapHNode = llvm::make_unique<MapHNode>(N);
330 for (KeyValueNode &KVN : *Map) {
331 Node *KeyNode = KVN.getKey();
332 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(KeyNode);
334 setError(KeyNode, "Map key must be a scalar");
337 StringStorage.clear();
338 StringRef KeyStr = KeyScalar->getValue(StringStorage);
339 if (!StringStorage.empty()) {
340 // Copy string to permanent storage
341 unsigned Len = StringStorage.size();
342 char *Buf = StringAllocator.Allocate<char>(Len);
343 memcpy(Buf, &StringStorage[0], Len);
344 KeyStr = StringRef(Buf, Len);
346 auto ValueHNode = this->createHNodes(KVN.getValue());
349 mapHNode->Mapping[KeyStr] = std::move(ValueHNode);
351 return std::move(mapHNode);
352 } else if (isa<NullNode>(N)) {
353 return llvm::make_unique<EmptyHNode>(N);
355 setError(N, "unknown node kind");
360 bool Input::MapHNode::isValidKey(StringRef Key) {
361 for (const char *K : ValidKeys) {
368 void Input::setError(const Twine &Message) {
369 this->setError(CurrentNode, Message);
372 bool Input::canElideEmptySequence() {
376 //===----------------------------------------------------------------------===//
378 //===----------------------------------------------------------------------===//
380 Output::Output(raw_ostream &yout, void *context)
384 ColumnAtFlowStart(0),
385 NeedBitValueComma(false),
386 NeedFlowSequenceComma(false),
387 EnumerationMatchFound(false),
388 NeedsNewLine(false) {
394 bool Output::outputting() {
398 void Output::beginMapping() {
399 StateStack.push_back(inMapFirstKey);
403 bool Output::mapTag(StringRef Tag, bool Use) {
411 void Output::endMapping() {
412 StateStack.pop_back();
415 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
416 bool &UseDefault, void *&) {
418 if (Required || !SameAsDefault) {
419 this->newLineCheck();
420 this->paddedKey(Key);
426 void Output::postflightKey(void *) {
427 if (StateStack.back() == inMapFirstKey) {
428 StateStack.pop_back();
429 StateStack.push_back(inMapOtherKey);
433 void Output::beginDocuments() {
434 this->outputUpToEndOfLine("---");
437 bool Output::preflightDocument(unsigned index) {
439 this->outputUpToEndOfLine("\n---");
443 void Output::postflightDocument() {
446 void Output::endDocuments() {
450 unsigned Output::beginSequence() {
451 StateStack.push_back(inSeq);
456 void Output::endSequence() {
457 StateStack.pop_back();
460 bool Output::preflightElement(unsigned, void *&) {
464 void Output::postflightElement(void *) {
467 unsigned Output::beginFlowSequence() {
468 StateStack.push_back(inFlowSeq);
469 this->newLineCheck();
470 ColumnAtFlowStart = Column;
472 NeedFlowSequenceComma = false;
476 void Output::endFlowSequence() {
477 StateStack.pop_back();
478 this->outputUpToEndOfLine(" ]");
481 bool Output::preflightFlowElement(unsigned, void *&) {
482 if (NeedFlowSequenceComma)
486 for (int i = 0; i < ColumnAtFlowStart; ++i)
488 Column = ColumnAtFlowStart;
494 void Output::postflightFlowElement(void *) {
495 NeedFlowSequenceComma = true;
498 void Output::beginEnumScalar() {
499 EnumerationMatchFound = false;
502 bool Output::matchEnumScalar(const char *Str, bool Match) {
503 if (Match && !EnumerationMatchFound) {
504 this->newLineCheck();
505 this->outputUpToEndOfLine(Str);
506 EnumerationMatchFound = true;
511 void Output::endEnumScalar() {
512 if (!EnumerationMatchFound)
513 llvm_unreachable("bad runtime enum value");
516 bool Output::beginBitSetScalar(bool &DoClear) {
517 this->newLineCheck();
519 NeedBitValueComma = false;
524 bool Output::bitSetMatch(const char *Str, bool Matches) {
526 if (NeedBitValueComma)
529 NeedBitValueComma = true;
534 void Output::endBitSetScalar() {
535 this->outputUpToEndOfLine(" ]");
538 void Output::scalarString(StringRef &S, bool MustQuote) {
539 this->newLineCheck();
541 // Print '' for the empty string because leaving the field empty is not
543 this->outputUpToEndOfLine("''");
547 // Only quote if we must.
548 this->outputUpToEndOfLine(S);
553 unsigned End = S.size();
554 output("'"); // Starting single quote.
555 const char *Base = S.data();
557 // Escape a single quote by doubling it.
559 output(StringRef(&Base[i], j - i + 1));
565 output(StringRef(&Base[i], j - i));
566 this->outputUpToEndOfLine("'"); // Ending single quote.
569 void Output::setError(const Twine &message) {
572 bool Output::canElideEmptySequence() {
573 // Normally, with an optional key/value where the value is an empty sequence,
574 // the whole key/value can be not written. But, that produces wrong yaml
575 // if the key/value is the only thing in the map and the map is used in
576 // a sequence. This detects if the this sequence is the first key/value
577 // in map that itself is embedded in a sequnce.
578 if (StateStack.size() < 2)
580 if (StateStack.back() != inMapFirstKey)
582 return (StateStack[StateStack.size()-2] != inSeq);
585 void Output::output(StringRef s) {
590 void Output::outputUpToEndOfLine(StringRef s) {
592 if (StateStack.empty() || StateStack.back() != inFlowSeq)
596 void Output::outputNewLine() {
601 // if seq at top, indent as if map, then add "- "
602 // if seq in middle, use "- " if firstKey, else use " "
605 void Output::newLineCheck() {
608 NeedsNewLine = false;
610 this->outputNewLine();
612 assert(StateStack.size() > 0);
613 unsigned Indent = StateStack.size() - 1;
614 bool OutputDash = false;
616 if (StateStack.back() == inSeq) {
618 } else if ((StateStack.size() > 1) && (StateStack.back() == inMapFirstKey) &&
619 (StateStack[StateStack.size() - 2] == inSeq)) {
624 for (unsigned i = 0; i < Indent; ++i) {
633 void Output::paddedKey(StringRef key) {
636 const char *spaces = " ";
637 if (key.size() < strlen(spaces))
638 output(&spaces[key.size()]);
643 //===----------------------------------------------------------------------===//
644 // traits for built-in types
645 //===----------------------------------------------------------------------===//
647 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
648 Out << (Val ? "true" : "false");
651 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
652 if (Scalar.equals("true")) {
655 } else if (Scalar.equals("false")) {
659 return "invalid boolean";
662 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
667 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
673 void ScalarTraits<std::string>::output(const std::string &Val, void *,
678 StringRef ScalarTraits<std::string>::input(StringRef Scalar, void *,
684 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
686 // use temp uin32_t because ostream thinks uint8_t is a character
691 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
692 unsigned long long n;
693 if (getAsUnsignedInteger(Scalar, 0, n))
694 return "invalid number";
696 return "out of range number";
701 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
706 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
708 unsigned long long n;
709 if (getAsUnsignedInteger(Scalar, 0, n))
710 return "invalid number";
712 return "out of range number";
717 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
722 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
724 unsigned long long n;
725 if (getAsUnsignedInteger(Scalar, 0, n))
726 return "invalid number";
727 if (n > 0xFFFFFFFFUL)
728 return "out of range number";
733 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
738 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
740 unsigned long long N;
741 if (getAsUnsignedInteger(Scalar, 0, N))
742 return "invalid number";
747 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
748 // use temp in32_t because ostream thinks int8_t is a character
753 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
755 if (getAsSignedInteger(Scalar, 0, N))
756 return "invalid number";
757 if ((N > 127) || (N < -128))
758 return "out of range number";
763 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
768 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
770 if (getAsSignedInteger(Scalar, 0, N))
771 return "invalid number";
772 if ((N > INT16_MAX) || (N < INT16_MIN))
773 return "out of range number";
778 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
783 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
785 if (getAsSignedInteger(Scalar, 0, N))
786 return "invalid number";
787 if ((N > INT32_MAX) || (N < INT32_MIN))
788 return "out of range number";
793 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
798 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
800 if (getAsSignedInteger(Scalar, 0, N))
801 return "invalid number";
806 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
807 Out << format("%g", Val);
810 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
811 SmallString<32> buff(Scalar.begin(), Scalar.end());
813 Val = strtod(buff.c_str(), &end);
815 return "invalid floating point number";
819 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
820 Out << format("%g", Val);
823 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
824 SmallString<32> buff(Scalar.begin(), Scalar.end());
826 Val = strtod(buff.c_str(), &end);
828 return "invalid floating point number";
832 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
834 Out << format("0x%02X", Num);
837 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
838 unsigned long long n;
839 if (getAsUnsignedInteger(Scalar, 0, n))
840 return "invalid hex8 number";
842 return "out of range hex8 number";
847 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
849 Out << format("0x%04X", Num);
852 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
853 unsigned long long n;
854 if (getAsUnsignedInteger(Scalar, 0, n))
855 return "invalid hex16 number";
857 return "out of range hex16 number";
862 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
864 Out << format("0x%08X", Num);
867 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
868 unsigned long long n;
869 if (getAsUnsignedInteger(Scalar, 0, n))
870 return "invalid hex32 number";
871 if (n > 0xFFFFFFFFUL)
872 return "out of range hex32 number";
877 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
879 Out << format("0x%016llX", Num);
882 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
883 unsigned long long Num;
884 if (getAsUnsignedInteger(Scalar, 0, Num))
885 return "invalid hex64 number";