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 #define BUILDING_YAMLIO
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"
25 //===----------------------------------------------------------------------===//
27 //===----------------------------------------------------------------------===//
29 IO::IO(void *Context) : Ctxt(Context) {
35 void *IO::getContext() {
39 void IO::setContext(void *Context) {
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 Input::Input(StringRef InputContent, void *Ctxt)
49 : IO(Ctxt), CurrentNode(NULL) {
50 Strm = new Stream(InputContent, SrcMgr);
51 DocIterator = Strm->begin();
55 llvm::error_code Input::error() {
59 void Input::setDiagHandler(llvm::SourceMgr::DiagHandlerTy Handler, void *Ctxt) {
60 SrcMgr.setDiagHandler(Handler, Ctxt);
63 bool Input::outputting() {
67 bool Input::setCurrentDocument() {
68 if ( DocIterator != Strm->end() ) {
69 Node *N = DocIterator->getRoot();
70 if (llvm::isa<NullNode>(N)) {
71 // Empty files are allowed and ignored
73 return setCurrentDocument();
75 CurrentNode = this->createHNodes(N);
81 void Input::nextDocument() {
85 void Input::beginMapping() {
88 MapHNode *MN = llvm::dyn_cast<MapHNode>(CurrentNode);
90 MN->ValidKeys.clear();
94 bool Input::preflightKey(const char *Key, bool Required, bool,
95 bool &UseDefault, void *&SaveInfo) {
99 MapHNode *MN = llvm::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 = llvm::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 + "'" );
138 unsigned Input::beginSequence() {
139 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
140 return SQ->Entries.size();
144 void Input::endSequence() {
146 bool Input::preflightElement(unsigned Index, void *&SaveInfo) {
149 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
150 SaveInfo = CurrentNode;
151 CurrentNode = SQ->Entries[Index];
156 void Input::postflightElement(void *SaveInfo) {
157 CurrentNode = reinterpret_cast<HNode*>(SaveInfo);
160 unsigned Input::beginFlowSequence() {
161 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
162 return SQ->Entries.size();
166 bool Input::preflightFlowElement(unsigned index, void *&SaveInfo) {
169 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
170 SaveInfo = CurrentNode;
171 CurrentNode = SQ->Entries[index];
176 void Input::postflightFlowElement(void *SaveInfo) {
177 CurrentNode = reinterpret_cast<HNode*>(SaveInfo);
179 void Input::endFlowSequence() {
183 void Input::beginEnumScalar() {
184 ScalarMatchFound = false;
187 bool Input::matchEnumScalar(const char *Str, bool) {
188 if ( ScalarMatchFound )
190 if ( ScalarHNode *SN = llvm::dyn_cast<ScalarHNode>(CurrentNode) ) {
191 if ( SN->value().equals(Str) ) {
192 ScalarMatchFound = true;
199 void Input::endEnumScalar() {
200 if ( !ScalarMatchFound ) {
201 setError(CurrentNode, "unknown enumerated scalar");
207 bool Input::beginBitSetScalar(bool &DoClear) {
208 BitValuesUsed.clear();
209 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
210 BitValuesUsed.insert(BitValuesUsed.begin(), SQ->Entries.size(), false);
213 setError(CurrentNode, "expected sequence of bit values");
219 bool Input::bitSetMatch(const char *Str, bool) {
222 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
224 for (std::vector<HNode*>::iterator i=SQ->Entries.begin(),
225 End=SQ->Entries.end(); i != End; ++i) {
226 if ( ScalarHNode *SN = llvm::dyn_cast<ScalarHNode>(*i) ) {
227 if ( SN->value().equals(Str) ) {
228 BitValuesUsed[Index] = true;
233 setError(CurrentNode, "unexpected scalar in sequence of bit values");
239 setError(CurrentNode, "expected sequence of bit values");
244 void Input::endBitSetScalar() {
247 if ( SequenceHNode *SQ = llvm::dyn_cast<SequenceHNode>(CurrentNode) ) {
248 assert(BitValuesUsed.size() == SQ->Entries.size());
249 for ( unsigned i=0; i < SQ->Entries.size(); ++i ) {
250 if ( !BitValuesUsed[i] ) {
251 setError(SQ->Entries[i], "unknown bit value");
259 void Input::scalarString(StringRef &S) {
260 if ( ScalarHNode *SN = llvm::dyn_cast<ScalarHNode>(CurrentNode) ) {
264 setError(CurrentNode, "unexpected scalar");
268 void Input::setError(HNode *hnode, const Twine &message) {
269 this->setError(hnode->_node, message);
272 void Input::setError(Node *node, const Twine &message) {
273 Strm->printError(node, message);
274 EC = make_error_code(errc::invalid_argument);
277 Input::HNode *Input::createHNodes(Node *N) {
278 llvm::SmallString<128> StringStorage;
279 if ( ScalarNode *SN = llvm::dyn_cast<ScalarNode>(N) ) {
280 StringRef KeyStr = SN->getValue(StringStorage);
281 if ( !StringStorage.empty() ) {
282 // Copy string to permanent storage
283 unsigned Len = StringStorage.size();
284 char* Buf = Allocator.Allocate<char>(Len);
285 memcpy(Buf, &StringStorage[0], Len);
286 KeyStr = StringRef(Buf, Len);
288 return new (Allocator) ScalarHNode(N, KeyStr);
290 else if ( SequenceNode *SQ = llvm::dyn_cast<SequenceNode>(N) ) {
291 SequenceHNode *SQHNode = new (Allocator) SequenceHNode(N);
292 for (SequenceNode::iterator i=SQ->begin(),End=SQ->end(); i != End; ++i ) {
293 HNode *Entry = this->createHNodes(i);
296 SQHNode->Entries.push_back(Entry);
300 else if ( MappingNode *Map = llvm::dyn_cast<MappingNode>(N) ) {
301 MapHNode *mapHNode = new (Allocator) MapHNode(N);
302 for (MappingNode::iterator i=Map->begin(), End=Map->end(); i != End; ++i ) {
303 ScalarNode *KeyScalar = llvm::dyn_cast<ScalarNode>(i->getKey());
304 StringStorage.clear();
305 llvm::StringRef KeyStr = KeyScalar->getValue(StringStorage);
306 if ( !StringStorage.empty() ) {
307 // Copy string to permanent storage
308 unsigned Len = StringStorage.size();
309 char* Buf = Allocator.Allocate<char>(Len);
310 memcpy(Buf, &StringStorage[0], Len);
311 KeyStr = StringRef(Buf, Len);
313 HNode *ValueHNode = this->createHNodes(i->getValue());
316 mapHNode->Mapping[KeyStr] = ValueHNode;
320 else if ( llvm::isa<NullNode>(N) ) {
321 return new (Allocator) EmptyHNode(N);
324 setError(N, "unknown node kind");
330 bool Input::MapHNode::isValidKey(StringRef Key) {
331 for (SmallVector<const char*, 6>::iterator i=ValidKeys.begin(),
332 End=ValidKeys.end(); i != End; ++i) {
333 if ( Key.equals(*i) )
339 void Input::setError(const Twine &Message) {
340 this->setError(CurrentNode, Message);
344 //===----------------------------------------------------------------------===//
346 //===----------------------------------------------------------------------===//
348 Output::Output(llvm::raw_ostream &yout, void *context)
349 : IO(context), Out(yout), Column(0), ColumnAtFlowStart(0),
350 NeedBitValueComma(false), NeedFlowSequenceComma(false),
351 EnumerationMatchFound(false), NeedsNewLine(false) {
357 bool Output::outputting() {
361 void Output::beginMapping() {
362 StateStack.push_back(inMapFirstKey);
366 void Output::endMapping() {
367 StateStack.pop_back();
371 bool Output::preflightKey(const char *Key, bool Required, bool SameAsDefault,
372 bool &UseDefault, void *&) {
374 if ( Required || !SameAsDefault ) {
375 this->newLineCheck();
376 this->paddedKey(Key);
382 void Output::postflightKey(void*) {
383 if ( StateStack.back() == inMapFirstKey ) {
384 StateStack.pop_back();
385 StateStack.push_back(inMapOtherKey);
389 void Output::beginDocuments() {
390 this->outputUpToEndOfLine("---");
393 bool Output::preflightDocument(unsigned index) {
395 this->outputUpToEndOfLine("\n---");
399 void Output::postflightDocument() {
402 void Output::endDocuments() {
406 unsigned Output::beginSequence() {
407 StateStack.push_back(inSeq);
411 void Output::endSequence() {
412 StateStack.pop_back();
414 bool Output::preflightElement(unsigned , void *&) {
417 void Output::postflightElement(void*) {
420 unsigned Output::beginFlowSequence() {
421 this->newLineCheck();
422 StateStack.push_back(inFlowSeq);
423 ColumnAtFlowStart = Column;
425 NeedFlowSequenceComma = false;
428 void Output::endFlowSequence() {
429 StateStack.pop_back();
430 this->outputUpToEndOfLine(" ]");
432 bool Output::preflightFlowElement(unsigned , void *&) {
433 if ( NeedFlowSequenceComma )
437 for(int i=0; i < ColumnAtFlowStart; ++i)
439 Column = ColumnAtFlowStart;
444 void Output::postflightFlowElement(void*) {
445 NeedFlowSequenceComma = true;
450 void Output::beginEnumScalar() {
451 EnumerationMatchFound = false;
454 bool Output::matchEnumScalar(const char *Str, bool Match) {
455 if ( Match && !EnumerationMatchFound ) {
456 this->newLineCheck();
457 this->outputUpToEndOfLine(Str);
458 EnumerationMatchFound = true;
463 void Output::endEnumScalar() {
464 if ( !EnumerationMatchFound )
465 llvm_unreachable("bad runtime enum value");
470 bool Output::beginBitSetScalar(bool &DoClear) {
471 this->newLineCheck();
473 NeedBitValueComma = false;
478 bool Output::bitSetMatch(const char *Str, bool Matches) {
480 if ( NeedBitValueComma )
483 NeedBitValueComma = true;
488 void Output::endBitSetScalar() {
489 this->outputUpToEndOfLine(" ]");
492 void Output::scalarString(StringRef &S) {
493 this->newLineCheck();
494 if (S.find('\n') == StringRef::npos) {
495 // No embedded new-line chars, just print string.
496 this->outputUpToEndOfLine(S);
501 unsigned End = S.size();
502 output("'"); // Starting single quote.
503 const char *Base = S.data();
505 // Escape a single quote by doubling it.
507 output(StringRef(&Base[i], j - i + 1));
513 output(StringRef(&Base[i], j - i));
514 this->outputUpToEndOfLine("'"); // Ending single quote.
517 void Output::setError(const Twine &message) {
521 void Output::output(StringRef s) {
526 void Output::outputUpToEndOfLine(StringRef s) {
528 if ( StateStack.back() != inFlowSeq )
532 void Output::outputNewLine() {
537 // if seq at top, indent as if map, then add "- "
538 // if seq in middle, use "- " if firstKey, else use " "
541 void Output::newLineCheck() {
542 if ( ! NeedsNewLine )
544 NeedsNewLine = false;
546 this->outputNewLine();
548 assert(StateStack.size() > 0);
549 unsigned Indent = StateStack.size() - 1;
550 bool OutputDash = false;
552 if ( StateStack.back() == inSeq ) {
555 else if ( (StateStack.size() > 1)
556 && (StateStack.back() == inMapFirstKey)
557 && (StateStack[StateStack.size()-2] == inSeq) ) {
562 for (unsigned i=0; i < Indent; ++i) {
571 void Output::paddedKey(StringRef key) {
574 const char *spaces = " ";
575 if ( key.size() < strlen(spaces) )
576 output(&spaces[key.size()]);
581 //===----------------------------------------------------------------------===//
582 // traits for built-in types
583 //===----------------------------------------------------------------------===//
586 struct ScalarTraits<bool> {
587 static void output(const bool &Val, void*, llvm::raw_ostream &Out) {
588 Out << ( Val ? "true" : "false");
590 static llvm::StringRef input(llvm::StringRef Scalar, void*, bool &Val) {
591 if ( Scalar.equals("true") ) {
595 else if ( Scalar.equals("false") ) {
599 return "invalid boolean";
605 struct ScalarTraits<StringRef> {
606 static void output(const StringRef &Val, void*, llvm::raw_ostream &Out) {
609 static llvm::StringRef input(llvm::StringRef Scalar, void*, StringRef &Val){
617 struct ScalarTraits<uint8_t> {
618 static void output(const uint8_t &Val, void*, llvm::raw_ostream &Out) {
619 // use temp uin32_t because ostream thinks uint8_t is a character
623 static llvm::StringRef input(llvm::StringRef Scalar, void*, uint8_t &Val) {
625 if ( getAsUnsignedInteger(Scalar, 0, n) )
626 return "invalid number";
628 return "out of range number";
636 struct ScalarTraits<uint16_t> {
637 static void output(const uint16_t &Val, void*, llvm::raw_ostream &Out) {
640 static llvm::StringRef input(llvm::StringRef Scalar, void*, uint16_t &Val) {
642 if ( getAsUnsignedInteger(Scalar, 0, n) )
643 return "invalid number";
645 return "out of range number";
652 struct ScalarTraits<uint32_t> {
653 static void output(const uint32_t &Val, void*, llvm::raw_ostream &Out) {
656 static llvm::StringRef input(llvm::StringRef Scalar, void*, uint32_t &Val) {
658 if ( getAsUnsignedInteger(Scalar, 0, n) )
659 return "invalid number";
660 if ( n > 0xFFFFFFFFUL )
661 return "out of range number";
669 struct ScalarTraits<uint64_t> {
670 static void output(const uint64_t &Val, void*, llvm::raw_ostream &Out) {
673 static llvm::StringRef input(llvm::StringRef Scalar, void*, uint64_t &Val) {
674 if ( getAsUnsignedInteger(Scalar, 0, Val) )
675 return "invalid number";
682 struct ScalarTraits<int8_t> {
683 static void output(const int8_t &Val, void*, llvm::raw_ostream &Out) {
684 // use temp in32_t because ostream thinks int8_t is a character
688 static llvm::StringRef input(llvm::StringRef Scalar, void*, int8_t &Val) {
690 if ( getAsSignedInteger(Scalar, 0, n) )
691 return "invalid number";
692 if ( (n > 127) || (n < -128) )
693 return "out of range number";
701 struct ScalarTraits<int16_t> {
702 static void output(const int16_t &Val, void*, llvm::raw_ostream &Out) {
705 static llvm::StringRef input(llvm::StringRef Scalar, void*, int16_t &Val) {
707 if ( getAsSignedInteger(Scalar, 0, n) )
708 return "invalid number";
709 if ( (n > INT16_MAX) || (n < INT16_MIN) )
710 return "out of range number";
718 struct ScalarTraits<int32_t> {
719 static void output(const int32_t &Val, void*, llvm::raw_ostream &Out) {
722 static llvm::StringRef input(llvm::StringRef Scalar, void*, int32_t &Val) {
724 if ( getAsSignedInteger(Scalar, 0, n) )
725 return "invalid number";
726 if ( (n > INT32_MAX) || (n < INT32_MIN) )
727 return "out of range number";
734 struct ScalarTraits<int64_t> {
735 static void output(const int64_t &Val, void*, llvm::raw_ostream &Out) {
738 static llvm::StringRef input(llvm::StringRef Scalar, void*, int64_t &Val) {
739 if ( getAsSignedInteger(Scalar, 0, Val) )
740 return "invalid number";
746 struct ScalarTraits<double> {
747 static void output(const double &Val, void*, llvm::raw_ostream &Out) {
748 Out << format("%g", Val);
750 static llvm::StringRef input(llvm::StringRef Scalar, void*, double &Val) {
751 SmallString<32> buff(Scalar.begin(), Scalar.end());
753 Val = strtod(buff.c_str(), &end);
755 return "invalid floating point number";
761 struct ScalarTraits<float> {
762 static void output(const float &Val, void*, llvm::raw_ostream &Out) {
763 Out << format("%g", Val);
765 static llvm::StringRef input(llvm::StringRef Scalar, void*, float &Val) {
766 SmallString<32> buff(Scalar.begin(), Scalar.end());
768 Val = strtod(buff.c_str(), &end);
770 return "invalid floating point number";
778 struct ScalarTraits<Hex8> {
779 static void output(const Hex8 &Val, void*, llvm::raw_ostream &Out) {
781 Out << format("0x%02X", Num);
783 static llvm::StringRef input(llvm::StringRef Scalar, void*, Hex8 &Val) {
785 if ( getAsUnsignedInteger(Scalar, 0, n) )
786 return "invalid hex8 number";
788 return "out of range hex8 number";
796 struct ScalarTraits<Hex16> {
797 static void output(const Hex16 &Val, void*, llvm::raw_ostream &Out) {
799 Out << format("0x%04X", Num);
801 static llvm::StringRef input(llvm::StringRef Scalar, void*, Hex16 &Val) {
803 if ( getAsUnsignedInteger(Scalar, 0, n) )
804 return "invalid hex16 number";
806 return "out of range hex16 number";
813 struct ScalarTraits<Hex32> {
814 static void output(const Hex32 &Val, void*, llvm::raw_ostream &Out) {
816 Out << format("0x%08X", Num);
818 static llvm::StringRef input(llvm::StringRef Scalar, void*, Hex32 &Val) {
820 if ( getAsUnsignedInteger(Scalar, 0, n) )
821 return "invalid hex32 number";
822 if ( n > 0xFFFFFFFFUL )
823 return "out of range hex32 number";
831 struct ScalarTraits<Hex64> {
832 static void output(const Hex64 &Val, void*, llvm::raw_ostream &Out) {
834 Out << format("0x%016llX", Num);
836 static llvm::StringRef input(llvm::StringRef Scalar, void*, Hex64 &Val) {
838 if ( getAsUnsignedInteger(Scalar, 0, Num) )
839 return "invalid hex64 number";
848 // We want all the ScalarTrait specialized on built-in types
849 // to be instantiated here.
850 template <typename T>
852 ForceUse() : oproc(ScalarTraits<T>::output), iproc(ScalarTraits<T>::input) {}
853 void (*oproc)(const T &, void*, llvm::raw_ostream &);
854 llvm::StringRef (*iproc)(llvm::StringRef, void*, T &);
857 static ForceUse<bool> Dummy1;
858 static ForceUse<llvm::StringRef> Dummy2;
859 static ForceUse<uint8_t> Dummy3;
860 static ForceUse<uint16_t> Dummy4;
861 static ForceUse<uint32_t> Dummy5;
862 static ForceUse<uint64_t> Dummy6;
863 static ForceUse<int8_t> Dummy7;
864 static ForceUse<int16_t> Dummy8;
865 static ForceUse<int32_t> Dummy9;
866 static ForceUse<int64_t> Dummy10;
867 static ForceUse<float> Dummy11;
868 static ForceUse<double> Dummy12;
869 static ForceUse<Hex8> Dummy13;
870 static ForceUse<Hex16> Dummy14;
871 static ForceUse<Hex32> Dummy15;
872 static ForceUse<Hex64> Dummy16;