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, void *Ctxt)
46 Strm(new Stream(InputContent, SrcMgr)),
48 DocIterator = Strm->begin();
54 error_code Input::error() {
58 void Input::setDiagHandler(SourceMgr::DiagHandlerTy Handler, void *Ctxt) {
59 SrcMgr.setDiagHandler(Handler, Ctxt);
62 bool Input::outputting() {
66 bool Input::setCurrentDocument() {
67 if (DocIterator != Strm->end()) {
68 Node *N = DocIterator->getRoot();
69 if (isa<NullNode>(N)) {
70 // Empty files are allowed and ignored
72 return setCurrentDocument();
74 TopNode.reset(this->createHNodes(N));
75 CurrentNode = TopNode.get();
81 void Input::nextDocument() {
85 void Input::beginMapping() {
88 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
90 MN->ValidKeys.clear();
94 bool Input::preflightKey(const char *Key, bool Required, bool, bool &UseDefault,
99 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
101 setError(CurrentNode, "not a mapping");
104 MN->ValidKeys.push_back(Key);
105 HNode *Value = MN->Mapping[Key];
108 setError(CurrentNode, Twine("missing required key '") + Key + "'");
113 SaveInfo = CurrentNode;
118 void Input::postflightKey(void *saveInfo) {
119 CurrentNode = reinterpret_cast<HNode *>(saveInfo);
122 void Input::endMapping() {
125 MapHNode *MN = dyn_cast<MapHNode>(CurrentNode);
128 for (MapHNode::NameToNode::iterator i = MN->Mapping.begin(),
129 End = MN->Mapping.end(); i != End; ++i) {
130 if (!MN->isValidKey(i->first())) {
131 setError(i->second, Twine("unknown key '") + i->first() + "'");
137 unsigned Input::beginSequence() {
138 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
139 return SQ->Entries.size();
144 void Input::endSequence() {
147 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
150 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
151 SaveInfo = CurrentNode;
152 CurrentNode = SQ->Entries[Index];
158 void Input::postflightElement(void *SaveInfo) {
159 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
162 unsigned Input::beginFlowSequence() {
163 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
164 return SQ->Entries.size();
169 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
172 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
173 SaveInfo = CurrentNode;
174 CurrentNode = SQ->Entries[index];
180 void Input::postflightFlowElement(void *SaveInfo) {
181 CurrentNode = reinterpret_cast<HNode *>(SaveInfo);
184 void Input::endFlowSequence() {
187 void Input::beginEnumScalar() {
188 ScalarMatchFound = false;
191 bool Input::matchEnumScalar(const char *Str, bool) {
192 if (ScalarMatchFound)
194 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
195 if (SN->value().equals(Str)) {
196 ScalarMatchFound = true;
203 void Input::endEnumScalar() {
204 if (!ScalarMatchFound) {
205 setError(CurrentNode, "unknown enumerated scalar");
209 bool Input::beginBitSetScalar(bool &DoClear) {
210 BitValuesUsed.clear();
211 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
212 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
214 setError(CurrentNode, "expected sequence of bit values");
220 bool Input::bitSetMatch(const char *Str, bool) {
223 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
225 for (std::vector<HNode *>::iterator i = SQ->Entries.begin(),
226 End = SQ->Entries.end(); i != End; ++i) {
227 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(*i)) {
228 if (SN->value().equals(Str)) {
229 BitValuesUsed[Index] = true;
233 setError(CurrentNode, "unexpected scalar in sequence of bit values");
238 setError(CurrentNode, "expected sequence of bit values");
243 void Input::endBitSetScalar() {
246 if (SequenceHNode *SQ = dyn_cast<SequenceHNode>(CurrentNode)) {
247 assert(BitValuesUsed.size() == SQ->Entries.size());
248 for (unsigned i = 0; i < SQ->Entries.size(); ++i) {
249 if (!BitValuesUsed[i]) {
250 setError(SQ->Entries[i], "unknown bit value");
257 void Input::scalarString(StringRef &S) {
258 if (ScalarHNode *SN = dyn_cast<ScalarHNode>(CurrentNode)) {
261 setError(CurrentNode, "unexpected scalar");
265 void Input::setError(HNode *hnode, const Twine &message) {
266 this->setError(hnode->_node, message);
269 void Input::setError(Node *node, const Twine &message) {
270 Strm->printError(node, message);
271 EC = make_error_code(errc::invalid_argument);
274 Input::HNode *Input::createHNodes(Node *N) {
275 SmallString<128> StringStorage;
276 if (ScalarNode *SN = dyn_cast<ScalarNode>(N)) {
277 StringRef KeyStr = SN->getValue(StringStorage);
278 if (!StringStorage.empty()) {
279 // Copy string to permanent storage
280 unsigned Len = StringStorage.size();
281 char *Buf = StringAllocator.Allocate<char>(Len);
282 memcpy(Buf, &StringStorage[0], Len);
283 KeyStr = StringRef(Buf, Len);
285 return new ScalarHNode(N, KeyStr);
286 } else if (SequenceNode *SQ = dyn_cast<SequenceNode>(N)) {
287 SequenceHNode *SQHNode = new SequenceHNode(N);
288 for (SequenceNode::iterator i = SQ->begin(), End = SQ->end(); i != End;
290 HNode *Entry = this->createHNodes(i);
293 SQHNode->Entries.push_back(Entry);
296 } else if (MappingNode *Map = dyn_cast<MappingNode>(N)) {
297 MapHNode *mapHNode = new MapHNode(N);
298 for (MappingNode::iterator i = Map->begin(), End = Map->end(); i != End;
300 ScalarNode *KeyScalar = dyn_cast<ScalarNode>(i->getKey());
301 StringStorage.clear();
302 StringRef KeyStr = KeyScalar->getValue(StringStorage);
303 if (!StringStorage.empty()) {
304 // Copy string to permanent storage
305 unsigned Len = StringStorage.size();
306 char *Buf = StringAllocator.Allocate<char>(Len);
307 memcpy(Buf, &StringStorage[0], Len);
308 KeyStr = StringRef(Buf, Len);
310 HNode *ValueHNode = this->createHNodes(i->getValue());
313 mapHNode->Mapping[KeyStr] = ValueHNode;
316 } else if (isa<NullNode>(N)) {
317 return new EmptyHNode(N);
319 setError(N, "unknown node kind");
324 bool Input::MapHNode::isValidKey(StringRef Key) {
325 for (SmallVectorImpl<const char *>::iterator i = ValidKeys.begin(),
326 End = ValidKeys.end(); i != End; ++i) {
333 void Input::setError(const Twine &Message) {
334 this->setError(CurrentNode, Message);
337 bool Input::canElideEmptySequence() {
341 Input::MapHNode::~MapHNode() {
342 for (MapHNode::NameToNode::iterator i = Mapping.begin(), End = Mapping.end();
348 Input::SequenceHNode::~SequenceHNode() {
349 for (std::vector<HNode*>::iterator i = Entries.begin(), End = Entries.end();
357 //===----------------------------------------------------------------------===//
359 //===----------------------------------------------------------------------===//
361 Output::Output(raw_ostream &yout, void *context)
365 ColumnAtFlowStart(0),
366 NeedBitValueComma(false),
367 NeedFlowSequenceComma(false),
368 EnumerationMatchFound(false),
369 NeedsNewLine(false) {
375 bool Output::outputting() {
379 void Output::beginMapping() {
380 StateStack.push_back(inMapFirstKey);
384 void Output::endMapping() {
385 StateStack.pop_back();
388 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
389 bool &UseDefault, void *&) {
391 if (Required || !SameAsDefault) {
392 this->newLineCheck();
393 this->paddedKey(Key);
399 void Output::postflightKey(void *) {
400 if (StateStack.back() == inMapFirstKey) {
401 StateStack.pop_back();
402 StateStack.push_back(inMapOtherKey);
406 void Output::beginDocuments() {
407 this->outputUpToEndOfLine("---");
410 bool Output::preflightDocument(unsigned index) {
412 this->outputUpToEndOfLine("\n---");
416 void Output::postflightDocument() {
419 void Output::endDocuments() {
423 unsigned Output::beginSequence() {
424 StateStack.push_back(inSeq);
429 void Output::endSequence() {
430 StateStack.pop_back();
433 bool Output::preflightElement(unsigned, void *&) {
437 void Output::postflightElement(void *) {
440 unsigned Output::beginFlowSequence() {
441 StateStack.push_back(inFlowSeq);
442 this->newLineCheck();
443 ColumnAtFlowStart = Column;
445 NeedFlowSequenceComma = false;
449 void Output::endFlowSequence() {
450 StateStack.pop_back();
451 this->outputUpToEndOfLine(" ]");
454 bool Output::preflightFlowElement(unsigned, void *&) {
455 if (NeedFlowSequenceComma)
459 for (int i = 0; i < ColumnAtFlowStart; ++i)
461 Column = ColumnAtFlowStart;
467 void Output::postflightFlowElement(void *) {
468 NeedFlowSequenceComma = true;
471 void Output::beginEnumScalar() {
472 EnumerationMatchFound = false;
475 bool Output::matchEnumScalar(const char *Str, bool Match) {
476 if (Match && !EnumerationMatchFound) {
477 this->newLineCheck();
478 this->outputUpToEndOfLine(Str);
479 EnumerationMatchFound = true;
484 void Output::endEnumScalar() {
485 if (!EnumerationMatchFound)
486 llvm_unreachable("bad runtime enum value");
489 bool Output::beginBitSetScalar(bool &DoClear) {
490 this->newLineCheck();
492 NeedBitValueComma = false;
497 bool Output::bitSetMatch(const char *Str, bool Matches) {
499 if (NeedBitValueComma)
502 NeedBitValueComma = true;
507 void Output::endBitSetScalar() {
508 this->outputUpToEndOfLine(" ]");
511 void Output::scalarString(StringRef &S) {
512 const char ScalarSafeChars[] = "abcdefghijklmnopqrstuvwxyz"
513 "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-/^., \t";
515 this->newLineCheck();
517 // Print '' for the empty string because leaving the field empty is not
519 this->outputUpToEndOfLine("''");
522 if (S.find_first_not_of(ScalarSafeChars) == StringRef::npos &&
523 !isspace(S.front()) && !isspace(S.back())) {
524 // If the string consists only of safe characters, print it out without
526 this->outputUpToEndOfLine(S);
531 unsigned End = S.size();
532 output("'"); // Starting single quote.
533 const char *Base = S.data();
535 // Escape a single quote by doubling it.
537 output(StringRef(&Base[i], j - i + 1));
543 output(StringRef(&Base[i], j - i));
544 this->outputUpToEndOfLine("'"); // Ending single quote.
547 void Output::setError(const Twine &message) {
550 bool Output::canElideEmptySequence() {
551 // Normally, with an optional key/value where the value is an empty sequence,
552 // the whole key/value can be not written. But, that produces wrong yaml
553 // if the key/value is the only thing in the map and the map is used in
554 // a sequence. This detects if the this sequence is the first key/value
555 // in map that itself is embedded in a sequnce.
556 if (StateStack.size() < 2)
558 if (StateStack.back() != inMapFirstKey)
560 return (StateStack[StateStack.size()-2] != inSeq);
563 void Output::output(StringRef s) {
568 void Output::outputUpToEndOfLine(StringRef s) {
570 if (StateStack.empty() || StateStack.back() != inFlowSeq)
574 void Output::outputNewLine() {
579 // if seq at top, indent as if map, then add "- "
580 // if seq in middle, use "- " if firstKey, else use " "
583 void Output::newLineCheck() {
586 NeedsNewLine = false;
588 this->outputNewLine();
590 assert(StateStack.size() > 0);
591 unsigned Indent = StateStack.size() - 1;
592 bool OutputDash = false;
594 if (StateStack.back() == inSeq) {
596 } else if ((StateStack.size() > 1) && (StateStack.back() == inMapFirstKey) &&
597 (StateStack[StateStack.size() - 2] == inSeq)) {
602 for (unsigned i = 0; i < Indent; ++i) {
611 void Output::paddedKey(StringRef key) {
614 const char *spaces = " ";
615 if (key.size() < strlen(spaces))
616 output(&spaces[key.size()]);
621 //===----------------------------------------------------------------------===//
622 // traits for built-in types
623 //===----------------------------------------------------------------------===//
625 void ScalarTraits<bool>::output(const bool &Val, void *, raw_ostream &Out) {
626 Out << (Val ? "true" : "false");
629 StringRef ScalarTraits<bool>::input(StringRef Scalar, void *, bool &Val) {
630 if (Scalar.equals("true")) {
633 } else if (Scalar.equals("false")) {
637 return "invalid boolean";
640 void ScalarTraits<StringRef>::output(const StringRef &Val, void *,
645 StringRef ScalarTraits<StringRef>::input(StringRef Scalar, void *,
651 void ScalarTraits<uint8_t>::output(const uint8_t &Val, void *,
653 // use temp uin32_t because ostream thinks uint8_t is a character
658 StringRef ScalarTraits<uint8_t>::input(StringRef Scalar, void *, uint8_t &Val) {
659 unsigned long long n;
660 if (getAsUnsignedInteger(Scalar, 0, n))
661 return "invalid number";
663 return "out of range number";
668 void ScalarTraits<uint16_t>::output(const uint16_t &Val, void *,
673 StringRef ScalarTraits<uint16_t>::input(StringRef Scalar, void *,
675 unsigned long long n;
676 if (getAsUnsignedInteger(Scalar, 0, n))
677 return "invalid number";
679 return "out of range number";
684 void ScalarTraits<uint32_t>::output(const uint32_t &Val, void *,
689 StringRef ScalarTraits<uint32_t>::input(StringRef Scalar, void *,
691 unsigned long long n;
692 if (getAsUnsignedInteger(Scalar, 0, n))
693 return "invalid number";
694 if (n > 0xFFFFFFFFUL)
695 return "out of range number";
700 void ScalarTraits<uint64_t>::output(const uint64_t &Val, void *,
705 StringRef ScalarTraits<uint64_t>::input(StringRef Scalar, void *,
707 unsigned long long N;
708 if (getAsUnsignedInteger(Scalar, 0, N))
709 return "invalid number";
714 void ScalarTraits<int8_t>::output(const int8_t &Val, void *, raw_ostream &Out) {
715 // use temp in32_t because ostream thinks int8_t is a character
720 StringRef ScalarTraits<int8_t>::input(StringRef Scalar, void *, int8_t &Val) {
722 if (getAsSignedInteger(Scalar, 0, N))
723 return "invalid number";
724 if ((N > 127) || (N < -128))
725 return "out of range number";
730 void ScalarTraits<int16_t>::output(const int16_t &Val, void *,
735 StringRef ScalarTraits<int16_t>::input(StringRef Scalar, void *, int16_t &Val) {
737 if (getAsSignedInteger(Scalar, 0, N))
738 return "invalid number";
739 if ((N > INT16_MAX) || (N < INT16_MIN))
740 return "out of range number";
745 void ScalarTraits<int32_t>::output(const int32_t &Val, void *,
750 StringRef ScalarTraits<int32_t>::input(StringRef Scalar, void *, int32_t &Val) {
752 if (getAsSignedInteger(Scalar, 0, N))
753 return "invalid number";
754 if ((N > INT32_MAX) || (N < INT32_MIN))
755 return "out of range number";
760 void ScalarTraits<int64_t>::output(const int64_t &Val, void *,
765 StringRef ScalarTraits<int64_t>::input(StringRef Scalar, void *, int64_t &Val) {
767 if (getAsSignedInteger(Scalar, 0, N))
768 return "invalid number";
773 void ScalarTraits<double>::output(const double &Val, void *, raw_ostream &Out) {
774 Out << format("%g", Val);
777 StringRef ScalarTraits<double>::input(StringRef Scalar, void *, double &Val) {
778 SmallString<32> buff(Scalar.begin(), Scalar.end());
780 Val = strtod(buff.c_str(), &end);
782 return "invalid floating point number";
786 void ScalarTraits<float>::output(const float &Val, void *, raw_ostream &Out) {
787 Out << format("%g", Val);
790 StringRef ScalarTraits<float>::input(StringRef Scalar, void *, float &Val) {
791 SmallString<32> buff(Scalar.begin(), Scalar.end());
793 Val = strtod(buff.c_str(), &end);
795 return "invalid floating point number";
799 void ScalarTraits<Hex8>::output(const Hex8 &Val, void *, raw_ostream &Out) {
801 Out << format("0x%02X", Num);
804 StringRef ScalarTraits<Hex8>::input(StringRef Scalar, void *, Hex8 &Val) {
805 unsigned long long n;
806 if (getAsUnsignedInteger(Scalar, 0, n))
807 return "invalid hex8 number";
809 return "out of range hex8 number";
814 void ScalarTraits<Hex16>::output(const Hex16 &Val, void *, raw_ostream &Out) {
816 Out << format("0x%04X", Num);
819 StringRef ScalarTraits<Hex16>::input(StringRef Scalar, void *, Hex16 &Val) {
820 unsigned long long n;
821 if (getAsUnsignedInteger(Scalar, 0, n))
822 return "invalid hex16 number";
824 return "out of range hex16 number";
829 void ScalarTraits<Hex32>::output(const Hex32 &Val, void *, raw_ostream &Out) {
831 Out << format("0x%08X", Num);
834 StringRef ScalarTraits<Hex32>::input(StringRef Scalar, void *, Hex32 &Val) {
835 unsigned long long n;
836 if (getAsUnsignedInteger(Scalar, 0, n))
837 return "invalid hex32 number";
838 if (n > 0xFFFFFFFFUL)
839 return "out of range hex32 number";
844 void ScalarTraits<Hex64>::output(const Hex64 &Val, void *, raw_ostream &Out) {
846 Out << format("0x%016llX", Num);
849 StringRef ScalarTraits<Hex64>::input(StringRef Scalar, void *, Hex64 &Val) {
850 unsigned long long Num;
851 if (getAsUnsignedInteger(Scalar, 0, Num))
852 return "invalid hex64 number";