YAMLIO: Remove all of the template instantiation hacks, I don't see why they're neces...
[oota-llvm.git] / include / llvm / Support / YAMLTraits.h
1 //===- llvm/Supporrt/YAMLTraits.h -------------------------------*- C++ -*-===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_YAML_TRAITS_H_
11 #define LLVM_YAML_TRAITS_H_
12
13
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseMapInfo.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/YAMLParser.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/system_error.h"
26 #include "llvm/Support/type_traits.h"
27
28
29 namespace llvm {
30 namespace yaml {
31
32
33 /// This class should be specialized by any type that needs to be converted
34 /// to/from a YAML mapping.  For example:
35 ///
36 ///     struct ScalarBitSetTraits<MyStruct> {
37 ///       static void mapping(IO &io, MyStruct &s) {
38 ///         io.mapRequired("name", s.name);
39 ///         io.mapRequired("size", s.size);
40 ///         io.mapOptional("age",  s.age);
41 ///       }
42 ///     };
43 template<class T>
44 struct MappingTraits {
45   // Must provide:
46   // static void mapping(IO &io, T &fields);
47 };
48
49
50 /// This class should be specialized by any integral type that converts
51 /// to/from a YAML scalar where there is a one-to-one mapping between
52 /// in-memory values and a string in YAML.  For example:
53 ///
54 ///     struct ScalarEnumerationTraits<Colors> {
55 ///         static void enumeration(IO &io, Colors &value) {
56 ///           io.enumCase(value, "red",   cRed);
57 ///           io.enumCase(value, "blue",  cBlue);
58 ///           io.enumCase(value, "green", cGreen);
59 ///         }
60 ///       };
61 template<typename T>
62 struct ScalarEnumerationTraits {
63   // Must provide:
64   // static void enumeration(IO &io, T &value);
65 };
66
67
68 /// This class should be specialized by any integer type that is a union
69 /// of bit values and the YAML representation is a flow sequence of
70 /// strings.  For example:
71 ///
72 ///      struct ScalarBitSetTraits<MyFlags> {
73 ///        static void bitset(IO &io, MyFlags &value) {
74 ///          io.bitSetCase(value, "big",   flagBig);
75 ///          io.bitSetCase(value, "flat",  flagFlat);
76 ///          io.bitSetCase(value, "round", flagRound);
77 ///        }
78 ///      };
79 template<typename T>
80 struct ScalarBitSetTraits {
81   // Must provide:
82   // static void bitset(IO &io, T &value);
83 };
84
85
86 /// This class should be specialized by type that requires custom conversion
87 /// to/from a yaml scalar.  For example:
88 ///
89 ///    template<>
90 ///    struct ScalarTraits<MyType> {
91 ///      static void output(const MyType &val, void*, llvm::raw_ostream &out) {
92 ///        // stream out custom formatting
93 ///        out << llvm::format("%x", val);
94 ///      }
95 ///      static StringRef input(StringRef scalar, void*, MyType &value) {
96 ///        // parse scalar and set `value`
97 ///        // return empty string on success, or error string
98 ///        return StringRef();
99 ///      }
100 ///    };
101 template<typename T>
102 struct ScalarTraits {
103   // Must provide:
104   //
105   // Function to write the value as a string:
106   //static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
107   //
108   // Function to convert a string to a value.  Returns the empty
109   // StringRef on success or an error string if string is malformed:
110   //static StringRef input(StringRef scalar, void *ctxt, T &value);
111 };
112
113
114 /// This class should be specialized by any type that needs to be converted
115 /// to/from a YAML sequence.  For example:
116 ///
117 ///    template<>
118 ///    struct SequenceTraits< std::vector<MyType> > {
119 ///      static size_t size(IO &io, std::vector<MyType> &seq) {
120 ///        return seq.size();
121 ///      }
122 ///      static MyType& element(IO &, std::vector<MyType> &seq, size_t index) {
123 ///        if ( index >= seq.size() )
124 ///          seq.resize(index+1);
125 ///        return seq[index];
126 ///      }
127 ///    };
128 template<typename T>
129 struct SequenceTraits {
130   // Must provide:
131   // static size_t size(IO &io, T &seq);
132   // static T::value_type& element(IO &io, T &seq, size_t index);
133   //
134   // The following is option and will cause generated YAML to use
135   // a flow sequence (e.g. [a,b,c]).
136   // static const bool flow = true;
137 };
138
139
140 /// This class should be specialized by any type that needs to be converted
141 /// to/from a list of YAML documents.
142 template<typename T>
143 struct DocumentListTraits {
144   // Must provide:
145   // static size_t size(IO &io, T &seq);
146   // static T::value_type& element(IO &io, T &seq, size_t index);
147 };
148
149
150 // Only used by compiler if both template types are the same
151 template <typename T, T>
152 struct SameType;
153
154 // Only used for better diagnostics of missing traits
155 template <typename T>
156 struct MissingTrait;
157
158
159
160 // Test if ScalarEnumerationTraits<T> is defined on type T.
161 template <class T>
162 struct has_ScalarEnumerationTraits
163 {
164   typedef void (*Signature_enumeration)(class IO&, T&);
165
166   template <typename U>
167   static char test(SameType<Signature_enumeration, &U::enumeration>*);
168
169   template <typename U>
170   static double test(...);
171
172 public:
173   static bool const value = (sizeof(test<ScalarEnumerationTraits<T> >(0)) == 1);
174 };
175
176
177 // Test if ScalarBitSetTraits<T> is defined on type T.
178 template <class T>
179 struct has_ScalarBitSetTraits
180 {
181   typedef void (*Signature_bitset)(class IO&, T&);
182
183   template <typename U>
184   static char test(SameType<Signature_bitset, &U::bitset>*);
185
186   template <typename U>
187   static double test(...);
188
189 public:
190   static bool const value = (sizeof(test<ScalarBitSetTraits<T> >(0)) == 1);
191 };
192
193
194 // Test if ScalarTraits<T> is defined on type T.
195 template <class T>
196 struct has_ScalarTraits
197 {
198   typedef llvm::StringRef (*Signature_input)(llvm::StringRef, void*, T&);
199   typedef void (*Signature_output)(const T&, void*, llvm::raw_ostream&);
200
201   template <typename U>
202   static char test(SameType<Signature_input, &U::input>*,
203                    SameType<Signature_output, &U::output>*);
204
205   template <typename U>
206   static double test(...);
207
208 public:
209   static bool const value = (sizeof(test<ScalarTraits<T> >(0,0)) == 1);
210 };
211
212
213 // Test if MappingTraits<T> is defined on type T.
214 template <class T>
215 struct has_MappingTraits
216 {
217   typedef void (*Signature_mapping)(class IO&, T&);
218
219   template <typename U>
220   static char test(SameType<Signature_mapping, &U::mapping>*);
221
222   template <typename U>
223   static double test(...);
224
225 public:
226   static bool const value = (sizeof(test<MappingTraits<T> >(0)) == 1);
227 };
228
229
230 // Test if SequenceTraits<T> is defined on type T
231 // and SequenceTraits<T>::flow is *not* defined.
232 template <class T>
233 struct has_SequenceTraits
234 {
235   typedef size_t (*Signature_size)(class IO&, T&);
236
237   template <typename U>
238   static char test(SameType<Signature_size, &U::size>*);
239
240   template <typename U>
241   static double test(...);
242
243   template <typename U> static
244   char flowtest( char[sizeof(&U::flow)] ) ;
245
246   template <typename U>
247   static double flowtest(...);
248
249 public:
250   static bool const value =  (sizeof(test<SequenceTraits<T> >(0)) == 1)
251                           && (sizeof(flowtest<T>(0)) != 1);
252 };
253
254
255 // Test if SequenceTraits<T> is defined on type T
256 // and SequenceTraits<T>::flow is defined.
257 template <class T>
258 struct has_FlowSequenceTraits
259 {
260   typedef size_t (*Signature_size)(class IO&, T&);
261
262   template <typename U>
263   static char test(SameType<Signature_size, &U::size>*);
264
265   template <typename U>
266   static double test(...);
267
268   template <typename U> static
269   char flowtest( char[sizeof(&U::flow)] ) ;
270
271   template <typename U>
272   static double flowtest(...);
273
274 public:
275   static bool const value =  (sizeof(test<SequenceTraits<T> >(0)) == 1)
276                           && (sizeof(flowtest<T>(0)) == 1);
277 };
278
279
280 // Test if DocumentListTraits<T> is defined on type T
281 template <class T>
282 struct has_DocumentListTraits
283 {
284   typedef size_t (*Signature_size)(class IO&, T&);
285
286   template <typename U>
287   static char test(SameType<Signature_size, &U::size>*);
288
289   template <typename U>
290   static double test(...);
291
292 public:
293   static bool const value =  (sizeof(test<DocumentListTraits<T> >(0)) == 1);
294 };
295
296
297
298
299 template<typename T>
300 struct missingTraits : public  llvm::integral_constant<bool,
301                                          !has_ScalarEnumerationTraits<T>::value
302                                       && !has_ScalarBitSetTraits<T>::value
303                                       && !has_ScalarTraits<T>::value
304                                       && !has_MappingTraits<T>::value
305                                       && !has_SequenceTraits<T>::value
306                                       && !has_FlowSequenceTraits<T>::value
307                                       && !has_DocumentListTraits<T>::value >  {};
308
309
310 // Base class for Input and Output.
311 class IO {
312 public:
313
314   IO(void *Ctxt=NULL);
315   virtual ~IO();
316
317   virtual bool outputting() = 0;
318
319   virtual unsigned beginSequence() = 0;
320   virtual bool preflightElement(unsigned, void *&) = 0;
321   virtual void postflightElement(void*) = 0;
322   virtual void endSequence() = 0;
323
324   virtual unsigned beginFlowSequence() = 0;
325   virtual bool preflightFlowElement(unsigned, void *&) = 0;
326   virtual void postflightFlowElement(void*) = 0;
327   virtual void endFlowSequence() = 0;
328
329   virtual void beginMapping() = 0;
330   virtual void endMapping() = 0;
331   virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
332   virtual void postflightKey(void*) = 0;
333
334   virtual void beginEnumScalar() = 0;
335   virtual bool matchEnumScalar(const char*, bool) = 0;
336   virtual void endEnumScalar() = 0;
337
338   virtual bool beginBitSetScalar(bool &) = 0;
339   virtual bool bitSetMatch(const char*, bool) = 0;
340   virtual void endBitSetScalar() = 0;
341
342   virtual void scalarString(StringRef &) = 0;
343
344   virtual void setError(const Twine &) = 0;
345
346   template <typename T>
347   void enumCase(T &Val, const char* Str, const T ConstVal) {
348     if ( matchEnumScalar(Str, (Val == ConstVal)) ) {
349       Val = ConstVal;
350     }
351   }
352
353   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
354   template <typename T>
355   void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
356     if ( matchEnumScalar(Str, (Val == static_cast<T>(ConstVal))) ) {
357       Val = ConstVal;
358     }
359   }
360
361   template <typename T>
362   void bitSetCase(T &Val, const char* Str, const T ConstVal) {
363     if ( bitSetMatch(Str, ((Val & ConstVal) == ConstVal)) ) {
364       Val = Val | ConstVal;
365     }
366   }
367
368   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
369   template <typename T>
370   void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
371     if ( bitSetMatch(Str, ((Val & ConstVal) == ConstVal)) ) {
372       Val = Val | ConstVal;
373     }
374   }
375
376   void *getContext();
377   void setContext(void *);
378
379   template <typename T>
380   void mapRequired(const char* Key, T& Val) {
381     this->processKey(Key, Val, true);
382   }
383
384   template <typename T>
385   typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
386   mapOptional(const char* Key, T& Val) {
387     // omit key/value instead of outputting empty sequence
388     if ( this->outputting() && !(Val.begin() != Val.end()) )
389       return;
390     this->processKey(Key, Val, false);
391   }
392
393   template <typename T>
394   typename llvm::enable_if_c<!has_SequenceTraits<T>::value,void>::type
395   mapOptional(const char* Key, T& Val) {
396     this->processKey(Key, Val, false);
397   }
398
399   template <typename T>
400   void mapOptional(const char* Key, T& Val, const T& Default) {
401     this->processKeyWithDefault(Key, Val, Default, false);
402   }
403
404
405 private:
406   template <typename T>
407   void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
408                                                                 bool Required) {
409     void *SaveInfo;
410     bool UseDefault;
411     const bool sameAsDefault = (Val == DefaultValue);
412     if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
413                                                                   SaveInfo) ) {
414       yamlize(*this, Val, Required);
415       this->postflightKey(SaveInfo);
416     }
417     else {
418       if ( UseDefault )
419         Val = DefaultValue;
420     }
421   }
422
423   template <typename T>
424   void processKey(const char *Key, T &Val, bool Required) {
425     void *SaveInfo;
426     bool UseDefault;
427     if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
428       yamlize(*this, Val, Required);
429       this->postflightKey(SaveInfo);
430     }
431   }
432
433 private:
434   void  *Ctxt;
435 };
436
437
438
439 template<typename T>
440 typename llvm::enable_if_c<has_ScalarEnumerationTraits<T>::value,void>::type
441 yamlize(IO &io, T &Val, bool) {
442   io.beginEnumScalar();
443   ScalarEnumerationTraits<T>::enumeration(io, Val);
444   io.endEnumScalar();
445 }
446
447 template<typename T>
448 typename llvm::enable_if_c<has_ScalarBitSetTraits<T>::value,void>::type
449 yamlize(IO &io, T &Val, bool) {
450   bool DoClear;
451   if ( io.beginBitSetScalar(DoClear) ) {
452     if ( DoClear )
453       Val = static_cast<T>(0);
454     ScalarBitSetTraits<T>::bitset(io, Val);
455     io.endBitSetScalar();
456   }
457 }
458
459
460 template<typename T>
461 typename llvm::enable_if_c<has_ScalarTraits<T>::value,void>::type
462 yamlize(IO &io, T &Val, bool) {
463   if ( io.outputting() ) {
464     std::string Storage;
465     llvm::raw_string_ostream Buffer(Storage);
466     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
467     StringRef Str = Buffer.str();
468     io.scalarString(Str);
469   }
470   else {
471     StringRef Str;
472     io.scalarString(Str);
473     StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
474     if ( !Result.empty() ) {
475       io.setError(llvm::Twine(Result));
476     }
477   }
478 }
479
480
481 template<typename T>
482 typename llvm::enable_if_c<has_MappingTraits<T>::value, void>::type
483 yamlize(IO &io, T &Val, bool) {
484   io.beginMapping();
485   MappingTraits<T>::mapping(io, Val);
486   io.endMapping();
487 }
488
489 template<typename T>
490 typename llvm::enable_if_c<missingTraits<T>::value, void>::type
491 yamlize(IO &io, T &Val, bool) {
492   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
493 }
494
495 template<typename T>
496 typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
497 yamlize(IO &io, T &Seq, bool) {
498   unsigned incount = io.beginSequence();
499   unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incount;
500   for(unsigned i=0; i < count; ++i) {
501     void *SaveInfo;
502     if ( io.preflightElement(i, SaveInfo) ) {
503       yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
504       io.postflightElement(SaveInfo);
505     }
506   }
507   io.endSequence();
508 }
509
510 template<typename T>
511 typename llvm::enable_if_c<has_FlowSequenceTraits<T>::value,void>::type
512 yamlize(IO &io, T &Seq, bool) {
513   unsigned incount = io.beginFlowSequence();
514   unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incount;
515   for(unsigned i=0; i < count; ++i) {
516     void *SaveInfo;
517     if ( io.preflightFlowElement(i, SaveInfo) ) {
518       yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
519       io.postflightFlowElement(SaveInfo);
520     }
521   }
522   io.endFlowSequence();
523 }
524
525
526
527 template<>
528 struct ScalarTraits<bool> {
529   static void output(const bool &, void*, llvm::raw_ostream &);
530   static llvm::StringRef input(llvm::StringRef , void*, bool &);
531 };
532
533 template<>
534 struct ScalarTraits<StringRef> {
535   static void output(const StringRef &, void*, llvm::raw_ostream &);
536   static llvm::StringRef input(llvm::StringRef , void*, StringRef &);
537 };
538
539 template<>
540 struct ScalarTraits<uint8_t> {
541   static void output(const uint8_t &, void*, llvm::raw_ostream &);
542   static llvm::StringRef input(llvm::StringRef , void*, uint8_t &);
543 };
544
545 template<>
546 struct ScalarTraits<uint16_t> {
547   static void output(const uint16_t &, void*, llvm::raw_ostream &);
548   static llvm::StringRef input(llvm::StringRef , void*, uint16_t &);
549 };
550
551 template<>
552 struct ScalarTraits<uint32_t> {
553   static void output(const uint32_t &, void*, llvm::raw_ostream &);
554   static llvm::StringRef input(llvm::StringRef , void*, uint32_t &);
555 };
556
557 template<>
558 struct ScalarTraits<uint64_t> {
559   static void output(const uint64_t &, void*, llvm::raw_ostream &);
560   static llvm::StringRef input(llvm::StringRef , void*, uint64_t &);
561 };
562
563 template<>
564 struct ScalarTraits<int8_t> {
565   static void output(const int8_t &, void*, llvm::raw_ostream &);
566   static llvm::StringRef input(llvm::StringRef , void*, int8_t &);
567 };
568
569 template<>
570 struct ScalarTraits<int16_t> {
571   static void output(const int16_t &, void*, llvm::raw_ostream &);
572   static llvm::StringRef input(llvm::StringRef , void*, int16_t &);
573 };
574
575 template<>
576 struct ScalarTraits<int32_t> {
577   static void output(const int32_t &, void*, llvm::raw_ostream &);
578   static llvm::StringRef input(llvm::StringRef , void*, int32_t &);
579 };
580
581 template<>
582 struct ScalarTraits<int64_t> {
583   static void output(const int64_t &, void*, llvm::raw_ostream &);
584   static llvm::StringRef input(llvm::StringRef , void*, int64_t &);
585 };
586
587 template<>
588 struct ScalarTraits<float> {
589   static void output(const float &, void*, llvm::raw_ostream &);
590   static llvm::StringRef input(llvm::StringRef , void*, float &);
591 };
592
593 template<>
594 struct ScalarTraits<double> {
595   static void output(const double &, void*, llvm::raw_ostream &);
596   static llvm::StringRef input(llvm::StringRef , void*, double &);
597 };
598
599
600
601 // Utility for use within MappingTraits<>::mapping() method
602 // to [de]normalize an object for use with YAML conversion.
603 template <typename TNorm, typename TFinal>
604 struct MappingNormalization {
605   MappingNormalization(IO &i_o, TFinal &Obj)
606       : io(i_o), BufPtr(NULL), Result(Obj) {
607     if ( io.outputting() ) {
608       BufPtr = new (&Buffer) TNorm(io, Obj);
609     }
610     else {
611       BufPtr = new (&Buffer) TNorm(io);
612     }
613   }
614
615   ~MappingNormalization() {
616     if ( ! io.outputting() ) {
617       Result = BufPtr->denormalize(io);
618     }
619     BufPtr->~TNorm();
620   }
621
622   TNorm* operator->() { return BufPtr; }
623
624 private:
625   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
626
627   Storage       Buffer;
628   IO           &io;
629   TNorm        *BufPtr;
630   TFinal       &Result;
631 };
632
633
634
635 // Utility for use within MappingTraits<>::mapping() method
636 // to [de]normalize an object for use with YAML conversion.
637 template <typename TNorm, typename TFinal>
638 struct MappingNormalizationHeap {
639   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
640     : io(i_o), BufPtr(NULL), Result(Obj) {
641     if ( io.outputting() ) {
642       BufPtr = new (&Buffer) TNorm(io, Obj);
643     }
644     else {
645       BufPtr = new TNorm(io);
646     }
647   }
648
649   ~MappingNormalizationHeap() {
650     if ( io.outputting() ) {
651       BufPtr->~TNorm();
652     }
653     else {
654       Result = BufPtr->denormalize(io);
655     }
656   }
657
658   TNorm* operator->() { return BufPtr; }
659
660 private:
661   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
662
663   Storage       Buffer;
664   IO           &io;
665   TNorm        *BufPtr;
666   TFinal       &Result;
667 };
668
669
670
671 ///
672 /// The Input class is used to parse a yaml document into in-memory structs
673 /// and vectors.
674 ///
675 /// It works by using YAMLParser to do a syntax parse of the entire yaml
676 /// document, then the Input class builds a graph of HNodes which wraps
677 /// each yaml Node.  The extra layer is buffering.  The low level yaml
678 /// parser only lets you look at each node once.  The buffering layer lets
679 /// you search and interate multiple times.  This is necessary because
680 /// the mapRequired() method calls may not be in the same order
681 /// as the keys in the document.
682 ///
683 class Input : public IO {
684 public:
685   // Construct a yaml Input object from a StringRef and optional user-data.
686   Input(StringRef InputContent, void *Ctxt=NULL);
687
688   // Check if there was an syntax or semantic error during parsing.
689   llvm::error_code error();
690
691   // To set alternate error reporting.
692   void setDiagHandler(llvm::SourceMgr::DiagHandlerTy Handler, void *Ctxt = 0);
693
694 private:
695   virtual bool outputting();
696   virtual void beginMapping();
697   virtual void endMapping();
698   virtual bool preflightKey(const char *, bool, bool, bool &, void *&);
699   virtual void postflightKey(void *);
700   virtual unsigned beginSequence();
701   virtual void endSequence();
702   virtual bool preflightElement(unsigned index, void *&);
703   virtual void postflightElement(void *);
704   virtual unsigned beginFlowSequence();
705   virtual bool preflightFlowElement(unsigned , void *&);
706   virtual void postflightFlowElement(void *);
707   virtual void endFlowSequence();
708   virtual void beginEnumScalar();
709   virtual bool matchEnumScalar(const char*, bool);
710   virtual void endEnumScalar();
711   virtual bool beginBitSetScalar(bool &);
712   virtual bool bitSetMatch(const char *, bool );
713   virtual void endBitSetScalar();
714   virtual void scalarString(StringRef &);
715   virtual void setError(const Twine &message);
716
717   class HNode {
718   public:
719     HNode(Node *n) : _node(n) { }
720     static inline bool classof(const HNode *) { return true; }
721
722     Node *_node;
723   };
724
725   class EmptyHNode : public HNode {
726   public:
727     EmptyHNode(Node *n) : HNode(n) { }
728     static inline bool classof(const HNode *n) {
729       return NullNode::classof(n->_node);
730     }
731     static inline bool classof(const EmptyHNode *) { return true; }
732   };
733
734   class ScalarHNode : public HNode {
735   public:
736     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
737
738     StringRef value() const { return _value; }
739
740     static inline bool classof(const HNode *n) {
741       return ScalarNode::classof(n->_node);
742     }
743     static inline bool classof(const ScalarHNode *) { return true; }
744   protected:
745     StringRef _value;
746   };
747
748   class MapHNode : public HNode {
749   public:
750     MapHNode(Node *n) : HNode(n) { }
751
752     static inline bool classof(const HNode *n) {
753       return MappingNode::classof(n->_node);
754     }
755     static inline bool classof(const MapHNode *) { return true; }
756
757     struct StrMappingInfo {
758       static StringRef getEmptyKey() { return StringRef(); }
759       static StringRef getTombstoneKey() { return StringRef(" ", 0); }
760       static unsigned getHashValue(StringRef const val) {
761                                                 return llvm::HashString(val); }
762       static bool isEqual(StringRef const lhs,
763                           StringRef const rhs) { return lhs.equals(rhs); }
764     };
765     typedef llvm::DenseMap<StringRef, HNode*, StrMappingInfo> NameToNode;
766
767     bool isValidKey(StringRef key);
768
769     NameToNode                        Mapping;
770     llvm::SmallVector<const char*, 6> ValidKeys;
771   };
772
773   class SequenceHNode : public HNode {
774   public:
775     SequenceHNode(Node *n) : HNode(n) { }
776
777     static inline bool classof(const HNode *n) {
778       return SequenceNode::classof(n->_node);
779     }
780     static inline bool classof(const SequenceHNode *) { return true; }
781
782     std::vector<HNode*> Entries;
783   };
784
785   Input::HNode *createHNodes(Node *node);
786   void setError(HNode *hnode, const Twine &message);
787   void setError(Node *node, const Twine &message);
788
789
790 public:
791   // These are only used by operator>>. They could be private
792   // if those templated things could be made friends.
793   bool setCurrentDocument();
794   void nextDocument();
795
796 private:
797   llvm::yaml::Stream              *Strm;
798   llvm::SourceMgr                  SrcMgr;
799   llvm::error_code                 EC;
800   llvm::BumpPtrAllocator           Allocator;
801   llvm::yaml::document_iterator    DocIterator;
802   std::vector<bool>                BitValuesUsed;
803   HNode                           *CurrentNode;
804   bool                             ScalarMatchFound;
805 };
806
807
808
809
810 ///
811 /// The Output class is used to generate a yaml document from in-memory structs
812 /// and vectors.
813 ///
814 class Output : public IO {
815 public:
816   Output(llvm::raw_ostream &, void *Ctxt=NULL);
817   virtual ~Output();
818
819   virtual bool outputting();
820   virtual void beginMapping();
821   virtual void endMapping();
822   virtual bool preflightKey(const char *key, bool, bool, bool &, void *&);
823   virtual void postflightKey(void *);
824   virtual unsigned beginSequence();
825   virtual void endSequence();
826   virtual bool preflightElement(unsigned, void *&);
827   virtual void postflightElement(void *);
828   virtual unsigned beginFlowSequence();
829   virtual bool preflightFlowElement(unsigned, void *&);
830   virtual void postflightFlowElement(void *);
831   virtual void endFlowSequence();
832   virtual void beginEnumScalar();
833   virtual bool matchEnumScalar(const char*, bool);
834   virtual void endEnumScalar();
835   virtual bool beginBitSetScalar(bool &);
836   virtual bool bitSetMatch(const char *, bool );
837   virtual void endBitSetScalar();
838   virtual void scalarString(StringRef &);
839   virtual void setError(const Twine &message);
840
841 public:
842   // These are only used by operator<<. They could be private
843   // if that templated operator could be made a friend.
844   void beginDocuments();
845   bool preflightDocument(unsigned);
846   void postflightDocument();
847   void endDocuments();
848
849 private:
850   void output(StringRef s);
851   void outputUpToEndOfLine(StringRef s);
852   void newLineCheck();
853   void outputNewLine();
854   void paddedKey(StringRef key);
855
856   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
857
858   llvm::raw_ostream       &Out;
859   SmallVector<InState, 8>  StateStack;
860   int                      Column;
861   int                      ColumnAtFlowStart;
862   bool                     NeedBitValueComma;
863   bool                     NeedFlowSequenceComma;
864   bool                     EnumerationMatchFound;
865   bool                     NeedsNewLine;
866 };
867
868
869
870
871 /// YAML I/O does conversion based on types. But often native data types
872 /// are just a typedef of built in intergral types (e.g. int).  But the C++
873 /// type matching system sees through the typedef and all the typedefed types
874 /// look like a built in type. This will cause the generic YAML I/O conversion
875 /// to be used. To provide better control over the YAML conversion, you can
876 /// use this macro instead of typedef.  It will create a class with one field
877 /// and automatic conversion operators to and from the base type.
878 /// Based on BOOST_STRONG_TYPEDEF
879 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
880     struct _type {                                                             \
881         _type() { }                                                            \
882         _type(const _base v) : value(v) { }                                    \
883         _type(const _type &v) : value(v.value) {}                              \
884         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
885         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
886         operator const _base & () const { return value; }                      \
887         bool operator==(const _type &rhs) const { return value == rhs.value; } \
888         bool operator==(const _base &rhs) const { return value == rhs; }       \
889         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
890         _base value;                                                           \
891     };
892
893
894
895 ///
896 /// Use these types instead of uintXX_t in any mapping to have
897 /// its yaml output formatted as hexadecimal.
898 ///
899 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
900 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
901 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
902 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
903
904
905 template<>
906 struct ScalarTraits<Hex8> {
907   static void output(const Hex8 &, void*, llvm::raw_ostream &);
908   static llvm::StringRef input(llvm::StringRef , void*, Hex8 &);
909 };
910
911 template<>
912 struct ScalarTraits<Hex16> {
913   static void output(const Hex16 &, void*, llvm::raw_ostream &);
914   static llvm::StringRef input(llvm::StringRef , void*, Hex16 &);
915 };
916
917 template<>
918 struct ScalarTraits<Hex32> {
919   static void output(const Hex32 &, void*, llvm::raw_ostream &);
920   static llvm::StringRef input(llvm::StringRef , void*, Hex32 &);
921 };
922
923 template<>
924 struct ScalarTraits<Hex64> {
925   static void output(const Hex64 &, void*, llvm::raw_ostream &);
926   static llvm::StringRef input(llvm::StringRef , void*, Hex64 &);
927 };
928
929
930 // Define non-member operator>> so that Input can stream in a document list.
931 template <typename T>
932 inline
933 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Input &>::type
934 operator>>(Input &yin, T &docList) {
935   int i = 0;
936   while ( yin.setCurrentDocument() ) {
937     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
938     if ( yin.error() )
939       return yin;
940     yin.nextDocument();
941     ++i;
942   }
943   return yin;
944 }
945
946 // Define non-member operator>> so that Input can stream in a map as a document.
947 template <typename T>
948 inline
949 typename llvm::enable_if_c<has_MappingTraits<T>::value,Input &>::type
950 operator>>(Input &yin, T &docMap) {
951   yin.setCurrentDocument();
952   yamlize(yin, docMap, true);
953   return yin;
954 }
955
956 // Define non-member operator>> so that Input can stream in a sequence as
957 // a document.
958 template <typename T>
959 inline
960 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Input &>::type
961 operator>>(Input &yin, T &docSeq) {
962   yin.setCurrentDocument();
963   yamlize(yin, docSeq, true);
964   return yin;
965 }
966
967 // Provide better error message about types missing a trait specialization
968 template <typename T>
969 inline
970 typename llvm::enable_if_c<missingTraits<T>::value,Input &>::type
971 operator>>(Input &yin, T &docSeq) {
972   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
973   return yin;
974 }
975
976
977 // Define non-member operator<< so that Output can stream out document list.
978 template <typename T>
979 inline
980 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Output &>::type
981 operator<<(Output &yout, T &docList) {
982   yout.beginDocuments();
983   const size_t count = DocumentListTraits<T>::size(yout, docList);
984   for(size_t i=0; i < count; ++i) {
985     if ( yout.preflightDocument(i) ) {
986       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
987       yout.postflightDocument();
988     }
989   }
990   yout.endDocuments();
991   return yout;
992 }
993
994 // Define non-member operator<< so that Output can stream out a map.
995 template <typename T>
996 inline
997 typename llvm::enable_if_c<has_MappingTraits<T>::value,Output &>::type
998 operator<<(Output &yout, T &map) {
999   yout.beginDocuments();
1000   if ( yout.preflightDocument(0) ) {
1001     yamlize(yout, map, true);
1002     yout.postflightDocument();
1003   }
1004   yout.endDocuments();
1005   return yout;
1006 }
1007
1008 // Define non-member operator<< so that Output can stream out a sequence.
1009 template <typename T>
1010 inline
1011 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Output &>::type
1012 operator<<(Output &yout, T &seq) {
1013   yout.beginDocuments();
1014   if ( yout.preflightDocument(0) ) {
1015     yamlize(yout, seq, true);
1016     yout.postflightDocument();
1017   }
1018   yout.endDocuments();
1019   return yout;
1020 }
1021
1022 // Provide better error message about types missing a trait specialization
1023 template <typename T>
1024 inline
1025 typename llvm::enable_if_c<missingTraits<T>::value,Output &>::type
1026 operator<<(Output &yout, T &seq) {
1027   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1028   return yout;
1029 }
1030
1031
1032 } // namespace yaml
1033 } // namespace llvm
1034
1035
1036 /// Utility for declaring that a std::vector of a particular type
1037 /// should be considered a YAML sequence.
1038 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1039   namespace llvm {                                                          \
1040   namespace yaml {                                                          \
1041     template<>                                                              \
1042     struct SequenceTraits< std::vector<_type> > {                           \
1043       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1044         return seq.size();                                                  \
1045       }                                                                     \
1046       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1047         if ( index >= seq.size() )                                          \
1048           seq.resize(index+1);                                              \
1049         return seq[index];                                                  \
1050       }                                                                     \
1051     };                                                                      \
1052   }                                                                         \
1053   }
1054
1055 /// Utility for declaring that a std::vector of a particular type
1056 /// should be considered a YAML flow sequence.
1057 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1058   namespace llvm {                                                          \
1059   namespace yaml {                                                          \
1060     template<>                                                              \
1061     struct SequenceTraits< std::vector<_type> > {                           \
1062       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1063         return seq.size();                                                  \
1064       }                                                                     \
1065       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1066         if ( index >= seq.size() )                                          \
1067           seq.resize(index+1);                                              \
1068         return seq[index];                                                  \
1069       }                                                                     \
1070       static const bool flow = true;                                        \
1071     };                                                                      \
1072   }                                                                         \
1073   }
1074
1075 /// Utility for declaring that a std::vector of a particular type
1076 /// should be considered a YAML document list.
1077 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1078   namespace llvm {                                                          \
1079   namespace yaml {                                                          \
1080     template<>                                                              \
1081     struct DocumentListTraits< std::vector<_type> > {                       \
1082       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1083         return seq.size();                                                  \
1084       }                                                                     \
1085       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1086         if ( index >= seq.size() )                                          \
1087           seq.resize(index+1);                                              \
1088         return seq[index];                                                  \
1089       }                                                                     \
1090     };                                                                      \
1091   }                                                                         \
1092   }
1093
1094
1095
1096 #endif // LLVM_YAML_TRAITS_H_