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