Tighten up the yamilizer so it stops eliding empty sequences if the embedded empty...
[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/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 StringRef (*Signature_input)(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 template <class T>
232 struct has_SequenceMethodTraits
233 {
234   typedef size_t (*Signature_size)(class IO&, T&);
235
236   template <typename U>
237   static char test(SameType<Signature_size, &U::size>*);
238
239   template <typename U>
240   static double test(...);
241
242 public:
243   static bool const value =  (sizeof(test<SequenceTraits<T> >(0)) == 1);
244 };
245
246
247 // has_FlowTraits<int> will cause an error with some compilers because
248 // it subclasses int.  Using this wrapper only instantiates the
249 // real has_FlowTraits only if the template type is a class.
250 template <typename T, bool Enabled = llvm::is_class<T>::value>
251 class has_FlowTraits
252 {
253 public:
254    static const bool value = false;
255 };
256
257 // Some older gcc compilers don't support straight forward tests
258 // for members, so test for ambiguity cause by the base and derived
259 // classes both defining the member.
260 template <class T>
261 struct has_FlowTraits<T, true>
262 {
263   struct Fallback { bool flow; };
264   struct Derived : T, Fallback { };
265
266   template<typename C>
267   static char (&f(SameType<bool Fallback::*, &C::flow>*))[1];
268
269   template<typename C>
270   static char (&f(...))[2];
271
272 public:
273   static bool const value = sizeof(f<Derived>(0)) == 2;
274 };
275
276
277
278 // Test if SequenceTraits<T> is defined on type T
279 template<typename T>
280 struct has_SequenceTraits : public  llvm::integral_constant<bool,
281                                       has_SequenceMethodTraits<T>::value > { };
282
283
284 // Test if DocumentListTraits<T> is defined on type T
285 template <class T>
286 struct has_DocumentListTraits
287 {
288   typedef size_t (*Signature_size)(class IO&, T&);
289
290   template <typename U>
291   static char test(SameType<Signature_size, &U::size>*);
292
293   template <typename U>
294   static double test(...);
295
296 public:
297   static bool const value =  (sizeof(test<DocumentListTraits<T> >(0)) == 1);
298 };
299
300
301
302
303 template<typename T>
304 struct missingTraits : public  llvm::integral_constant<bool,
305                                          !has_ScalarEnumerationTraits<T>::value
306                                       && !has_ScalarBitSetTraits<T>::value
307                                       && !has_ScalarTraits<T>::value
308                                       && !has_MappingTraits<T>::value
309                                       && !has_SequenceTraits<T>::value
310                                       && !has_DocumentListTraits<T>::value >  {};
311
312
313 // Base class for Input and Output.
314 class IO {
315 public:
316
317   IO(void *Ctxt=NULL);
318   virtual ~IO();
319
320   virtual bool outputting() = 0;
321
322   virtual unsigned beginSequence() = 0;
323   virtual bool preflightElement(unsigned, void *&) = 0;
324   virtual void postflightElement(void*) = 0;
325   virtual void endSequence() = 0;
326   virtual bool canElideEmptySequence() = 0;
327
328   virtual unsigned beginFlowSequence() = 0;
329   virtual bool preflightFlowElement(unsigned, void *&) = 0;
330   virtual void postflightFlowElement(void*) = 0;
331   virtual void endFlowSequence() = 0;
332
333   virtual void beginMapping() = 0;
334   virtual void endMapping() = 0;
335   virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
336   virtual void postflightKey(void*) = 0;
337
338   virtual void beginEnumScalar() = 0;
339   virtual bool matchEnumScalar(const char*, bool) = 0;
340   virtual void endEnumScalar() = 0;
341
342   virtual bool beginBitSetScalar(bool &) = 0;
343   virtual bool bitSetMatch(const char*, bool) = 0;
344   virtual void endBitSetScalar() = 0;
345
346   virtual void scalarString(StringRef &) = 0;
347
348   virtual void setError(const Twine &) = 0;
349
350   template <typename T>
351   void enumCase(T &Val, const char* Str, const T ConstVal) {
352     if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
353       Val = ConstVal;
354     }
355   }
356
357   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
358   template <typename T>
359   void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
360     if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
361       Val = ConstVal;
362     }
363   }
364
365   template <typename T>
366   void bitSetCase(T &Val, const char* Str, const T ConstVal) {
367     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
368       Val = Val | ConstVal;
369     }
370   }
371
372   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
373   template <typename T>
374   void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
375     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
376       Val = Val | ConstVal;
377     }
378   }
379
380   void *getContext();
381   void setContext(void *);
382
383   template <typename T>
384   void mapRequired(const char* Key, T& Val) {
385     this->processKey(Key, Val, true);
386   }
387
388   template <typename T>
389   typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
390   mapOptional(const char* Key, T& Val) {
391     // omit key/value instead of outputting empty sequence
392     if ( this->canElideEmptySequence() && !(Val.begin() != Val.end()) )
393       return;
394     this->processKey(Key, Val, false);
395   }
396
397   template <typename T>
398   typename llvm::enable_if_c<!has_SequenceTraits<T>::value,void>::type
399   mapOptional(const char* Key, T& Val) {
400     this->processKey(Key, Val, false);
401   }
402
403   template <typename T>
404   void mapOptional(const char* Key, T& Val, const T& Default) {
405     this->processKeyWithDefault(Key, Val, Default, false);
406   }
407
408
409 private:
410   template <typename T>
411   void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
412                                                                 bool Required) {
413     void *SaveInfo;
414     bool UseDefault;
415     const bool sameAsDefault = outputting() && Val == DefaultValue;
416     if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
417                                                                   SaveInfo) ) {
418       yamlize(*this, Val, Required);
419       this->postflightKey(SaveInfo);
420     }
421     else {
422       if ( UseDefault )
423         Val = DefaultValue;
424     }
425   }
426
427   template <typename T>
428   void processKey(const char *Key, T &Val, bool Required) {
429     void *SaveInfo;
430     bool UseDefault;
431     if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
432       yamlize(*this, Val, Required);
433       this->postflightKey(SaveInfo);
434     }
435   }
436
437 private:
438   void  *Ctxt;
439 };
440
441
442
443 template<typename T>
444 typename llvm::enable_if_c<has_ScalarEnumerationTraits<T>::value,void>::type
445 yamlize(IO &io, T &Val, bool) {
446   io.beginEnumScalar();
447   ScalarEnumerationTraits<T>::enumeration(io, Val);
448   io.endEnumScalar();
449 }
450
451 template<typename T>
452 typename llvm::enable_if_c<has_ScalarBitSetTraits<T>::value,void>::type
453 yamlize(IO &io, T &Val, bool) {
454   bool DoClear;
455   if ( io.beginBitSetScalar(DoClear) ) {
456     if ( DoClear )
457       Val = static_cast<T>(0);
458     ScalarBitSetTraits<T>::bitset(io, Val);
459     io.endBitSetScalar();
460   }
461 }
462
463
464 template<typename T>
465 typename llvm::enable_if_c<has_ScalarTraits<T>::value,void>::type
466 yamlize(IO &io, T &Val, bool) {
467   if ( io.outputting() ) {
468     std::string Storage;
469     llvm::raw_string_ostream Buffer(Storage);
470     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
471     StringRef Str = Buffer.str();
472     io.scalarString(Str);
473   }
474   else {
475     StringRef Str;
476     io.scalarString(Str);
477     StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
478     if ( !Result.empty() ) {
479       io.setError(llvm::Twine(Result));
480     }
481   }
482 }
483
484
485 template<typename T>
486 typename llvm::enable_if_c<has_MappingTraits<T>::value, void>::type
487 yamlize(IO &io, T &Val, bool) {
488   io.beginMapping();
489   MappingTraits<T>::mapping(io, Val);
490   io.endMapping();
491 }
492
493 template<typename T>
494 typename llvm::enable_if_c<missingTraits<T>::value, void>::type
495 yamlize(IO &io, T &Val, bool) {
496   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
497 }
498
499 template<typename T>
500 typename llvm::enable_if_c<has_SequenceTraits<T>::value,void>::type
501 yamlize(IO &io, T &Seq, bool) {
502   if ( has_FlowTraits< SequenceTraits<T> >::value ) {
503     unsigned incnt = io.beginFlowSequence();
504     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
505     for(unsigned i=0; i < count; ++i) {
506       void *SaveInfo;
507       if ( io.preflightFlowElement(i, SaveInfo) ) {
508         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
509         io.postflightFlowElement(SaveInfo);
510       }
511     }
512     io.endFlowSequence();
513   }
514   else {
515     unsigned incnt = io.beginSequence();
516     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
517     for(unsigned i=0; i < count; ++i) {
518       void *SaveInfo;
519       if ( io.preflightElement(i, SaveInfo) ) {
520         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
521         io.postflightElement(SaveInfo);
522       }
523     }
524     io.endSequence();
525   }
526 }
527
528
529 template<>
530 struct ScalarTraits<bool> {
531   static void output(const bool &, void*, llvm::raw_ostream &);
532   static StringRef input(StringRef, void*, bool &);
533 };
534
535 template<>
536 struct ScalarTraits<StringRef> {
537   static void output(const StringRef &, void*, llvm::raw_ostream &);
538   static StringRef input(StringRef, void*, StringRef &);
539 };
540
541 template<>
542 struct ScalarTraits<uint8_t> {
543   static void output(const uint8_t &, void*, llvm::raw_ostream &);
544   static StringRef input(StringRef, void*, uint8_t &);
545 };
546
547 template<>
548 struct ScalarTraits<uint16_t> {
549   static void output(const uint16_t &, void*, llvm::raw_ostream &);
550   static StringRef input(StringRef, void*, uint16_t &);
551 };
552
553 template<>
554 struct ScalarTraits<uint32_t> {
555   static void output(const uint32_t &, void*, llvm::raw_ostream &);
556   static StringRef input(StringRef, void*, uint32_t &);
557 };
558
559 template<>
560 struct ScalarTraits<uint64_t> {
561   static void output(const uint64_t &, void*, llvm::raw_ostream &);
562   static StringRef input(StringRef, void*, uint64_t &);
563 };
564
565 template<>
566 struct ScalarTraits<int8_t> {
567   static void output(const int8_t &, void*, llvm::raw_ostream &);
568   static StringRef input(StringRef, void*, int8_t &);
569 };
570
571 template<>
572 struct ScalarTraits<int16_t> {
573   static void output(const int16_t &, void*, llvm::raw_ostream &);
574   static StringRef input(StringRef, void*, int16_t &);
575 };
576
577 template<>
578 struct ScalarTraits<int32_t> {
579   static void output(const int32_t &, void*, llvm::raw_ostream &);
580   static StringRef input(StringRef, void*, int32_t &);
581 };
582
583 template<>
584 struct ScalarTraits<int64_t> {
585   static void output(const int64_t &, void*, llvm::raw_ostream &);
586   static StringRef input(StringRef, void*, int64_t &);
587 };
588
589 template<>
590 struct ScalarTraits<float> {
591   static void output(const float &, void*, llvm::raw_ostream &);
592   static StringRef input(StringRef, void*, float &);
593 };
594
595 template<>
596 struct ScalarTraits<double> {
597   static void output(const double &, void*, llvm::raw_ostream &);
598   static StringRef input(StringRef, void*, double &);
599 };
600
601
602
603 // Utility for use within MappingTraits<>::mapping() method
604 // to [de]normalize an object for use with YAML conversion.
605 template <typename TNorm, typename TFinal>
606 struct MappingNormalization {
607   MappingNormalization(IO &i_o, TFinal &Obj)
608       : io(i_o), BufPtr(NULL), Result(Obj) {
609     if ( io.outputting() ) {
610       BufPtr = new (&Buffer) TNorm(io, Obj);
611     }
612     else {
613       BufPtr = new (&Buffer) TNorm(io);
614     }
615   }
616
617   ~MappingNormalization() {
618     if ( ! io.outputting() ) {
619       Result = BufPtr->denormalize(io);
620     }
621     BufPtr->~TNorm();
622   }
623
624   TNorm* operator->() { return BufPtr; }
625
626 private:
627   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
628
629   Storage       Buffer;
630   IO           &io;
631   TNorm        *BufPtr;
632   TFinal       &Result;
633 };
634
635
636
637 // Utility for use within MappingTraits<>::mapping() method
638 // to [de]normalize an object for use with YAML conversion.
639 template <typename TNorm, typename TFinal>
640 struct MappingNormalizationHeap {
641   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
642     : io(i_o), BufPtr(NULL), Result(Obj) {
643     if ( io.outputting() ) {
644       BufPtr = new (&Buffer) TNorm(io, Obj);
645     }
646     else {
647       BufPtr = new TNorm(io);
648     }
649   }
650
651   ~MappingNormalizationHeap() {
652     if ( io.outputting() ) {
653       BufPtr->~TNorm();
654     }
655     else {
656       Result = BufPtr->denormalize(io);
657     }
658   }
659
660   TNorm* operator->() { return BufPtr; }
661
662 private:
663   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
664
665   Storage       Buffer;
666   IO           &io;
667   TNorm        *BufPtr;
668   TFinal       &Result;
669 };
670
671
672
673 ///
674 /// The Input class is used to parse a yaml document into in-memory structs
675 /// and vectors.
676 ///
677 /// It works by using YAMLParser to do a syntax parse of the entire yaml
678 /// document, then the Input class builds a graph of HNodes which wraps
679 /// each yaml Node.  The extra layer is buffering.  The low level yaml
680 /// parser only lets you look at each node once.  The buffering layer lets
681 /// you search and interate multiple times.  This is necessary because
682 /// the mapRequired() method calls may not be in the same order
683 /// as the keys in the document.
684 ///
685 class Input : public IO {
686 public:
687   // Construct a yaml Input object from a StringRef and optional user-data.
688   Input(StringRef InputContent, void *Ctxt=NULL);
689   ~Input();
690   
691   // Check if there was an syntax or semantic error during parsing.
692   llvm::error_code error();
693
694   // To set alternate error reporting.
695   void setDiagHandler(llvm::SourceMgr::DiagHandlerTy Handler, void *Ctxt = 0);
696
697 private:
698   virtual bool outputting();
699   virtual void beginMapping();
700   virtual void endMapping();
701   virtual bool preflightKey(const char *, bool, bool, bool &, void *&);
702   virtual void postflightKey(void *);
703   virtual unsigned beginSequence();
704   virtual void endSequence();
705   virtual bool preflightElement(unsigned index, void *&);
706   virtual void postflightElement(void *);
707   virtual unsigned beginFlowSequence();
708   virtual bool preflightFlowElement(unsigned , void *&);
709   virtual void postflightFlowElement(void *);
710   virtual void endFlowSequence();
711   virtual void beginEnumScalar();
712   virtual bool matchEnumScalar(const char*, bool);
713   virtual void endEnumScalar();
714   virtual bool beginBitSetScalar(bool &);
715   virtual bool bitSetMatch(const char *, bool );
716   virtual void endBitSetScalar();
717   virtual void scalarString(StringRef &);
718   virtual void setError(const Twine &message);
719   virtual bool canElideEmptySequence();
720
721   class HNode {
722   public:
723     HNode(Node *n) : _node(n) { }
724     virtual ~HNode() { }
725     static inline bool classof(const HNode *) { return true; }
726
727     Node *_node;
728   };
729
730   class EmptyHNode : public HNode {
731   public:
732     EmptyHNode(Node *n) : HNode(n) { }
733     virtual ~EmptyHNode() {}
734     static inline bool classof(const HNode *n) {
735       return NullNode::classof(n->_node);
736     }
737     static inline bool classof(const EmptyHNode *) { return true; }
738   };
739
740   class ScalarHNode : public HNode {
741   public:
742     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
743     virtual ~ScalarHNode() { }
744
745     StringRef value() const { return _value; }
746
747     static inline bool classof(const HNode *n) {
748       return ScalarNode::classof(n->_node);
749     }
750     static inline bool classof(const ScalarHNode *) { return true; }
751   protected:
752     StringRef _value;
753   };
754
755   class MapHNode : public HNode {
756   public:
757     MapHNode(Node *n) : HNode(n) { }
758     virtual ~MapHNode();
759
760     static inline bool classof(const HNode *n) {
761       return MappingNode::classof(n->_node);
762     }
763     static inline bool classof(const MapHNode *) { return true; }
764
765     typedef llvm::StringMap<HNode*> 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     virtual ~SequenceHNode();
777
778     static inline bool classof(const HNode *n) {
779       return SequenceNode::classof(n->_node);
780     }
781     static inline bool classof(const SequenceHNode *) { return true; }
782
783     std::vector<HNode*> Entries;
784   };
785
786   Input::HNode *createHNodes(Node *node);
787   void setError(HNode *hnode, const Twine &message);
788   void setError(Node *node, const Twine &message);
789
790
791 public:
792   // These are only used by operator>>. They could be private
793   // if those templated things could be made friends.
794   bool setCurrentDocument();
795   void nextDocument();
796
797 private:
798   llvm::SourceMgr                  SrcMgr; // must be before Strm
799   OwningPtr<llvm::yaml::Stream>    Strm;
800   OwningPtr<HNode>                 TopNode;
801   llvm::error_code                 EC;
802   llvm::BumpPtrAllocator           StringAllocator;
803   llvm::yaml::document_iterator    DocIterator;
804   std::vector<bool>                BitValuesUsed;
805   HNode                           *CurrentNode;
806   bool                             ScalarMatchFound;
807 };
808
809
810
811
812 ///
813 /// The Output class is used to generate a yaml document from in-memory structs
814 /// and vectors.
815 ///
816 class Output : public IO {
817 public:
818   Output(llvm::raw_ostream &, void *Ctxt=NULL);
819   virtual ~Output();
820
821   virtual bool outputting();
822   virtual void beginMapping();
823   virtual void endMapping();
824   virtual bool preflightKey(const char *key, bool, bool, bool &, void *&);
825   virtual void postflightKey(void *);
826   virtual unsigned beginSequence();
827   virtual void endSequence();
828   virtual bool preflightElement(unsigned, void *&);
829   virtual void postflightElement(void *);
830   virtual unsigned beginFlowSequence();
831   virtual bool preflightFlowElement(unsigned, void *&);
832   virtual void postflightFlowElement(void *);
833   virtual void endFlowSequence();
834   virtual void beginEnumScalar();
835   virtual bool matchEnumScalar(const char*, bool);
836   virtual void endEnumScalar();
837   virtual bool beginBitSetScalar(bool &);
838   virtual bool bitSetMatch(const char *, bool );
839   virtual void endBitSetScalar();
840   virtual void scalarString(StringRef &);
841   virtual void setError(const Twine &message);
842   virtual bool canElideEmptySequence();
843 public:
844   // These are only used by operator<<. They could be private
845   // if that templated operator could be made a friend.
846   void beginDocuments();
847   bool preflightDocument(unsigned);
848   void postflightDocument();
849   void endDocuments();
850
851 private:
852   void output(StringRef s);
853   void outputUpToEndOfLine(StringRef s);
854   void newLineCheck();
855   void outputNewLine();
856   void paddedKey(StringRef key);
857
858   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
859
860   llvm::raw_ostream       &Out;
861   SmallVector<InState, 8>  StateStack;
862   int                      Column;
863   int                      ColumnAtFlowStart;
864   bool                     NeedBitValueComma;
865   bool                     NeedFlowSequenceComma;
866   bool                     EnumerationMatchFound;
867   bool                     NeedsNewLine;
868 };
869
870
871
872
873 /// YAML I/O does conversion based on types. But often native data types
874 /// are just a typedef of built in intergral types (e.g. int).  But the C++
875 /// type matching system sees through the typedef and all the typedefed types
876 /// look like a built in type. This will cause the generic YAML I/O conversion
877 /// to be used. To provide better control over the YAML conversion, you can
878 /// use this macro instead of typedef.  It will create a class with one field
879 /// and automatic conversion operators to and from the base type.
880 /// Based on BOOST_STRONG_TYPEDEF
881 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
882     struct _type {                                                             \
883         _type() { }                                                            \
884         _type(const _base v) : value(v) { }                                    \
885         _type(const _type &v) : value(v.value) {}                              \
886         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
887         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
888         operator const _base & () const { return value; }                      \
889         bool operator==(const _type &rhs) const { return value == rhs.value; } \
890         bool operator==(const _base &rhs) const { return value == rhs; }       \
891         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
892         _base value;                                                           \
893     };
894
895
896
897 ///
898 /// Use these types instead of uintXX_t in any mapping to have
899 /// its yaml output formatted as hexadecimal.
900 ///
901 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
902 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
903 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
904 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
905
906
907 template<>
908 struct ScalarTraits<Hex8> {
909   static void output(const Hex8 &, void*, llvm::raw_ostream &);
910   static StringRef input(StringRef, void*, Hex8 &);
911 };
912
913 template<>
914 struct ScalarTraits<Hex16> {
915   static void output(const Hex16 &, void*, llvm::raw_ostream &);
916   static StringRef input(StringRef, void*, Hex16 &);
917 };
918
919 template<>
920 struct ScalarTraits<Hex32> {
921   static void output(const Hex32 &, void*, llvm::raw_ostream &);
922   static StringRef input(StringRef, void*, Hex32 &);
923 };
924
925 template<>
926 struct ScalarTraits<Hex64> {
927   static void output(const Hex64 &, void*, llvm::raw_ostream &);
928   static StringRef input(StringRef, void*, Hex64 &);
929 };
930
931
932 // Define non-member operator>> so that Input can stream in a document list.
933 template <typename T>
934 inline
935 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Input &>::type
936 operator>>(Input &yin, T &docList) {
937   int i = 0;
938   while ( yin.setCurrentDocument() ) {
939     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
940     if ( yin.error() )
941       return yin;
942     yin.nextDocument();
943     ++i;
944   }
945   return yin;
946 }
947
948 // Define non-member operator>> so that Input can stream in a map as a document.
949 template <typename T>
950 inline
951 typename llvm::enable_if_c<has_MappingTraits<T>::value,Input &>::type
952 operator>>(Input &yin, T &docMap) {
953   yin.setCurrentDocument();
954   yamlize(yin, docMap, true);
955   return yin;
956 }
957
958 // Define non-member operator>> so that Input can stream in a sequence as
959 // a document.
960 template <typename T>
961 inline
962 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Input &>::type
963 operator>>(Input &yin, T &docSeq) {
964   yin.setCurrentDocument();
965   yamlize(yin, docSeq, true);
966   return yin;
967 }
968
969 // Provide better error message about types missing a trait specialization
970 template <typename T>
971 inline
972 typename llvm::enable_if_c<missingTraits<T>::value,Input &>::type
973 operator>>(Input &yin, T &docSeq) {
974   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
975   return yin;
976 }
977
978
979 // Define non-member operator<< so that Output can stream out document list.
980 template <typename T>
981 inline
982 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Output &>::type
983 operator<<(Output &yout, T &docList) {
984   yout.beginDocuments();
985   const size_t count = DocumentListTraits<T>::size(yout, docList);
986   for(size_t i=0; i < count; ++i) {
987     if ( yout.preflightDocument(i) ) {
988       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
989       yout.postflightDocument();
990     }
991   }
992   yout.endDocuments();
993   return yout;
994 }
995
996 // Define non-member operator<< so that Output can stream out a map.
997 template <typename T>
998 inline
999 typename llvm::enable_if_c<has_MappingTraits<T>::value,Output &>::type
1000 operator<<(Output &yout, T &map) {
1001   yout.beginDocuments();
1002   if ( yout.preflightDocument(0) ) {
1003     yamlize(yout, map, true);
1004     yout.postflightDocument();
1005   }
1006   yout.endDocuments();
1007   return yout;
1008 }
1009
1010 // Define non-member operator<< so that Output can stream out a sequence.
1011 template <typename T>
1012 inline
1013 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Output &>::type
1014 operator<<(Output &yout, T &seq) {
1015   yout.beginDocuments();
1016   if ( yout.preflightDocument(0) ) {
1017     yamlize(yout, seq, true);
1018     yout.postflightDocument();
1019   }
1020   yout.endDocuments();
1021   return yout;
1022 }
1023
1024 // Provide better error message about types missing a trait specialization
1025 template <typename T>
1026 inline
1027 typename llvm::enable_if_c<missingTraits<T>::value,Output &>::type
1028 operator<<(Output &yout, T &seq) {
1029   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1030   return yout;
1031 }
1032
1033
1034 } // namespace yaml
1035 } // namespace llvm
1036
1037
1038 /// Utility for declaring that a std::vector of a particular type
1039 /// should be considered a YAML sequence.
1040 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1041   namespace llvm {                                                          \
1042   namespace yaml {                                                          \
1043     template<>                                                              \
1044     struct SequenceTraits< std::vector<_type> > {                           \
1045       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1046         return seq.size();                                                  \
1047       }                                                                     \
1048       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1049         if ( index >= seq.size() )                                          \
1050           seq.resize(index+1);                                              \
1051         return seq[index];                                                  \
1052       }                                                                     \
1053     };                                                                      \
1054   }                                                                         \
1055   }
1056
1057 /// Utility for declaring that a std::vector of a particular type
1058 /// should be considered a YAML flow sequence.
1059 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1060   namespace llvm {                                                          \
1061   namespace yaml {                                                          \
1062     template<>                                                              \
1063     struct SequenceTraits< std::vector<_type> > {                           \
1064       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1065         return seq.size();                                                  \
1066       }                                                                     \
1067       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1068         if ( index >= seq.size() )                                          \
1069           seq.resize(index+1);                                              \
1070         return seq[index];                                                  \
1071       }                                                                     \
1072       static const bool flow = true;                                        \
1073     };                                                                      \
1074   }                                                                         \
1075   }
1076
1077 /// Utility for declaring that a std::vector of a particular type
1078 /// should be considered a YAML document list.
1079 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1080   namespace llvm {                                                          \
1081   namespace yaml {                                                          \
1082     template<>                                                              \
1083     struct DocumentListTraits< std::vector<_type> > {                       \
1084       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1085         return seq.size();                                                  \
1086       }                                                                     \
1087       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1088         if ( index >= seq.size() )                                          \
1089           seq.resize(index+1);                                              \
1090         return seq[index];                                                  \
1091       }                                                                     \
1092     };                                                                      \
1093   }                                                                         \
1094   }
1095
1096
1097
1098 #endif // LLVM_SUPPORT_YAMLTRAITS_H