YAML I/O - Added default trait support for std:string. Making another attempt at...
[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<std::string> {
544   static void output(const std::string &, void*, llvm::raw_ostream &);
545   static StringRef input(StringRef, void*, std::string &);
546 };
547
548 template<>
549 struct ScalarTraits<uint8_t> {
550   static void output(const uint8_t &, void*, llvm::raw_ostream &);
551   static StringRef input(StringRef, void*, uint8_t &);
552 };
553
554 template<>
555 struct ScalarTraits<uint16_t> {
556   static void output(const uint16_t &, void*, llvm::raw_ostream &);
557   static StringRef input(StringRef, void*, uint16_t &);
558 };
559
560 template<>
561 struct ScalarTraits<uint32_t> {
562   static void output(const uint32_t &, void*, llvm::raw_ostream &);
563   static StringRef input(StringRef, void*, uint32_t &);
564 };
565
566 template<>
567 struct ScalarTraits<uint64_t> {
568   static void output(const uint64_t &, void*, llvm::raw_ostream &);
569   static StringRef input(StringRef, void*, uint64_t &);
570 };
571
572 template<>
573 struct ScalarTraits<int8_t> {
574   static void output(const int8_t &, void*, llvm::raw_ostream &);
575   static StringRef input(StringRef, void*, int8_t &);
576 };
577
578 template<>
579 struct ScalarTraits<int16_t> {
580   static void output(const int16_t &, void*, llvm::raw_ostream &);
581   static StringRef input(StringRef, void*, int16_t &);
582 };
583
584 template<>
585 struct ScalarTraits<int32_t> {
586   static void output(const int32_t &, void*, llvm::raw_ostream &);
587   static StringRef input(StringRef, void*, int32_t &);
588 };
589
590 template<>
591 struct ScalarTraits<int64_t> {
592   static void output(const int64_t &, void*, llvm::raw_ostream &);
593   static StringRef input(StringRef, void*, int64_t &);
594 };
595
596 template<>
597 struct ScalarTraits<float> {
598   static void output(const float &, void*, llvm::raw_ostream &);
599   static StringRef input(StringRef, void*, float &);
600 };
601
602 template<>
603 struct ScalarTraits<double> {
604   static void output(const double &, void*, llvm::raw_ostream &);
605   static StringRef input(StringRef, void*, double &);
606 };
607
608
609
610 // Utility for use within MappingTraits<>::mapping() method
611 // to [de]normalize an object for use with YAML conversion.
612 template <typename TNorm, typename TFinal>
613 struct MappingNormalization {
614   MappingNormalization(IO &i_o, TFinal &Obj)
615       : io(i_o), BufPtr(NULL), Result(Obj) {
616     if ( io.outputting() ) {
617       BufPtr = new (&Buffer) TNorm(io, Obj);
618     }
619     else {
620       BufPtr = new (&Buffer) TNorm(io);
621     }
622   }
623
624   ~MappingNormalization() {
625     if ( ! io.outputting() ) {
626       Result = BufPtr->denormalize(io);
627     }
628     BufPtr->~TNorm();
629   }
630
631   TNorm* operator->() { return BufPtr; }
632
633 private:
634   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
635
636   Storage       Buffer;
637   IO           &io;
638   TNorm        *BufPtr;
639   TFinal       &Result;
640 };
641
642
643
644 // Utility for use within MappingTraits<>::mapping() method
645 // to [de]normalize an object for use with YAML conversion.
646 template <typename TNorm, typename TFinal>
647 struct MappingNormalizationHeap {
648   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
649     : io(i_o), BufPtr(NULL), Result(Obj) {
650     if ( io.outputting() ) {
651       BufPtr = new (&Buffer) TNorm(io, Obj);
652     }
653     else {
654       BufPtr = new TNorm(io);
655     }
656   }
657
658   ~MappingNormalizationHeap() {
659     if ( io.outputting() ) {
660       BufPtr->~TNorm();
661     }
662     else {
663       Result = BufPtr->denormalize(io);
664     }
665   }
666
667   TNorm* operator->() { return BufPtr; }
668
669 private:
670   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
671
672   Storage       Buffer;
673   IO           &io;
674   TNorm        *BufPtr;
675   TFinal       &Result;
676 };
677
678
679
680 ///
681 /// The Input class is used to parse a yaml document into in-memory structs
682 /// and vectors.
683 ///
684 /// It works by using YAMLParser to do a syntax parse of the entire yaml
685 /// document, then the Input class builds a graph of HNodes which wraps
686 /// each yaml Node.  The extra layer is buffering.  The low level yaml
687 /// parser only lets you look at each node once.  The buffering layer lets
688 /// you search and interate multiple times.  This is necessary because
689 /// the mapRequired() method calls may not be in the same order
690 /// as the keys in the document.
691 ///
692 class Input : public IO {
693 public:
694   // Construct a yaml Input object from a StringRef and optional
695   // user-data. The DiagHandler can be specified to provide
696   // alternative error reporting.
697   Input(StringRef InputContent,
698         void *Ctxt = NULL,
699         SourceMgr::DiagHandlerTy DiagHandler = NULL,
700         void *DiagHandlerCtxt = NULL);
701   ~Input();
702
703   // Check if there was an syntax or semantic error during parsing.
704   llvm::error_code error();
705
706   static bool classof(const IO *io) { return !io->outputting(); }
707
708 private:
709   virtual bool outputting() const;
710   virtual bool mapTag(StringRef, bool);
711   virtual void beginMapping();
712   virtual void endMapping();
713   virtual bool preflightKey(const char *, bool, bool, bool &, void *&);
714   virtual void postflightKey(void *);
715   virtual unsigned beginSequence();
716   virtual void endSequence();
717   virtual bool preflightElement(unsigned index, void *&);
718   virtual void postflightElement(void *);
719   virtual unsigned beginFlowSequence();
720   virtual bool preflightFlowElement(unsigned , void *&);
721   virtual void postflightFlowElement(void *);
722   virtual void endFlowSequence();
723   virtual void beginEnumScalar();
724   virtual bool matchEnumScalar(const char*, bool);
725   virtual void endEnumScalar();
726   virtual bool beginBitSetScalar(bool &);
727   virtual bool bitSetMatch(const char *, bool );
728   virtual void endBitSetScalar();
729   virtual void scalarString(StringRef &);
730   virtual void setError(const Twine &message);
731   virtual bool canElideEmptySequence();
732
733   class HNode {
734     virtual void anchor();
735   public:
736     HNode(Node *n) : _node(n) { }
737     virtual ~HNode() { }
738     static inline bool classof(const HNode *) { return true; }
739
740     Node *_node;
741   };
742
743   class EmptyHNode : public HNode {
744     virtual void anchor();
745   public:
746     EmptyHNode(Node *n) : HNode(n) { }
747     static inline bool classof(const HNode *n) {
748       return NullNode::classof(n->_node);
749     }
750     static inline bool classof(const EmptyHNode *) { return true; }
751   };
752
753   class ScalarHNode : public HNode {
754     virtual void anchor();
755   public:
756     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
757
758     StringRef value() const { return _value; }
759
760     static inline bool classof(const HNode *n) {
761       return ScalarNode::classof(n->_node);
762     }
763     static inline bool classof(const ScalarHNode *) { return true; }
764   protected:
765     StringRef _value;
766   };
767
768   class MapHNode : public HNode {
769   public:
770     MapHNode(Node *n) : HNode(n) { }
771     virtual ~MapHNode();
772
773     static inline bool classof(const HNode *n) {
774       return MappingNode::classof(n->_node);
775     }
776     static inline bool classof(const MapHNode *) { return true; }
777
778     typedef llvm::StringMap<HNode*> NameToNode;
779
780     bool isValidKey(StringRef key);
781
782     NameToNode                        Mapping;
783     llvm::SmallVector<const char*, 6> ValidKeys;
784   };
785
786   class SequenceHNode : public HNode {
787   public:
788     SequenceHNode(Node *n) : HNode(n) { }
789     virtual ~SequenceHNode();
790
791     static inline bool classof(const HNode *n) {
792       return SequenceNode::classof(n->_node);
793     }
794     static inline bool classof(const SequenceHNode *) { return true; }
795
796     std::vector<HNode*> Entries;
797   };
798
799   Input::HNode *createHNodes(Node *node);
800   void setError(HNode *hnode, const Twine &message);
801   void setError(Node *node, const Twine &message);
802
803
804 public:
805   // These are only used by operator>>. They could be private
806   // if those templated things could be made friends.
807   bool setCurrentDocument();
808   void nextDocument();
809
810 private:
811   llvm::SourceMgr                  SrcMgr; // must be before Strm
812   OwningPtr<llvm::yaml::Stream>    Strm;
813   OwningPtr<HNode>                 TopNode;
814   llvm::error_code                 EC;
815   llvm::BumpPtrAllocator           StringAllocator;
816   llvm::yaml::document_iterator    DocIterator;
817   std::vector<bool>                BitValuesUsed;
818   HNode                           *CurrentNode;
819   bool                             ScalarMatchFound;
820 };
821
822
823
824
825 ///
826 /// The Output class is used to generate a yaml document from in-memory structs
827 /// and vectors.
828 ///
829 class Output : public IO {
830 public:
831   Output(llvm::raw_ostream &, void *Ctxt=NULL);
832   virtual ~Output();
833
834   static bool classof(const IO *io) { return io->outputting(); }
835   
836   virtual bool outputting() const;
837   virtual bool mapTag(StringRef, bool);
838   virtual void beginMapping();
839   virtual void endMapping();
840   virtual bool preflightKey(const char *key, bool, bool, bool &, void *&);
841   virtual void postflightKey(void *);
842   virtual unsigned beginSequence();
843   virtual void endSequence();
844   virtual bool preflightElement(unsigned, void *&);
845   virtual void postflightElement(void *);
846   virtual unsigned beginFlowSequence();
847   virtual bool preflightFlowElement(unsigned, void *&);
848   virtual void postflightFlowElement(void *);
849   virtual void endFlowSequence();
850   virtual void beginEnumScalar();
851   virtual bool matchEnumScalar(const char*, bool);
852   virtual void endEnumScalar();
853   virtual bool beginBitSetScalar(bool &);
854   virtual bool bitSetMatch(const char *, bool );
855   virtual void endBitSetScalar();
856   virtual void scalarString(StringRef &);
857   virtual void setError(const Twine &message);
858   virtual bool canElideEmptySequence();
859 public:
860   // These are only used by operator<<. They could be private
861   // if that templated operator could be made a friend.
862   void beginDocuments();
863   bool preflightDocument(unsigned);
864   void postflightDocument();
865   void endDocuments();
866
867 private:
868   void output(StringRef s);
869   void outputUpToEndOfLine(StringRef s);
870   void newLineCheck();
871   void outputNewLine();
872   void paddedKey(StringRef key);
873
874   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
875
876   llvm::raw_ostream       &Out;
877   SmallVector<InState, 8>  StateStack;
878   int                      Column;
879   int                      ColumnAtFlowStart;
880   bool                     NeedBitValueComma;
881   bool                     NeedFlowSequenceComma;
882   bool                     EnumerationMatchFound;
883   bool                     NeedsNewLine;
884 };
885
886
887
888
889 /// YAML I/O does conversion based on types. But often native data types
890 /// are just a typedef of built in intergral types (e.g. int).  But the C++
891 /// type matching system sees through the typedef and all the typedefed types
892 /// look like a built in type. This will cause the generic YAML I/O conversion
893 /// to be used. To provide better control over the YAML conversion, you can
894 /// use this macro instead of typedef.  It will create a class with one field
895 /// and automatic conversion operators to and from the base type.
896 /// Based on BOOST_STRONG_TYPEDEF
897 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
898     struct _type {                                                             \
899         _type() { }                                                            \
900         _type(const _base v) : value(v) { }                                    \
901         _type(const _type &v) : value(v.value) {}                              \
902         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
903         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
904         operator const _base & () const { return value; }                      \
905         bool operator==(const _type &rhs) const { return value == rhs.value; } \
906         bool operator==(const _base &rhs) const { return value == rhs; }       \
907         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
908         _base value;                                                           \
909     };
910
911
912
913 ///
914 /// Use these types instead of uintXX_t in any mapping to have
915 /// its yaml output formatted as hexadecimal.
916 ///
917 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
918 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
919 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
920 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
921
922
923 template<>
924 struct ScalarTraits<Hex8> {
925   static void output(const Hex8 &, void*, llvm::raw_ostream &);
926   static StringRef input(StringRef, void*, Hex8 &);
927 };
928
929 template<>
930 struct ScalarTraits<Hex16> {
931   static void output(const Hex16 &, void*, llvm::raw_ostream &);
932   static StringRef input(StringRef, void*, Hex16 &);
933 };
934
935 template<>
936 struct ScalarTraits<Hex32> {
937   static void output(const Hex32 &, void*, llvm::raw_ostream &);
938   static StringRef input(StringRef, void*, Hex32 &);
939 };
940
941 template<>
942 struct ScalarTraits<Hex64> {
943   static void output(const Hex64 &, void*, llvm::raw_ostream &);
944   static StringRef input(StringRef, void*, Hex64 &);
945 };
946
947
948 // Define non-member operator>> so that Input can stream in a document list.
949 template <typename T>
950 inline
951 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Input &>::type
952 operator>>(Input &yin, T &docList) {
953   int i = 0;
954   while ( yin.setCurrentDocument() ) {
955     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
956     if ( yin.error() )
957       return yin;
958     yin.nextDocument();
959     ++i;
960   }
961   return yin;
962 }
963
964 // Define non-member operator>> so that Input can stream in a map as a document.
965 template <typename T>
966 inline
967 typename llvm::enable_if_c<has_MappingTraits<T>::value,Input &>::type
968 operator>>(Input &yin, T &docMap) {
969   yin.setCurrentDocument();
970   yamlize(yin, docMap, true);
971   return yin;
972 }
973
974 // Define non-member operator>> so that Input can stream in a sequence as
975 // a document.
976 template <typename T>
977 inline
978 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Input &>::type
979 operator>>(Input &yin, T &docSeq) {
980   if (yin.setCurrentDocument())
981     yamlize(yin, docSeq, true);
982   return yin;
983 }
984
985 // Provide better error message about types missing a trait specialization
986 template <typename T>
987 inline
988 typename llvm::enable_if_c<missingTraits<T>::value,Input &>::type
989 operator>>(Input &yin, T &docSeq) {
990   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
991   return yin;
992 }
993
994
995 // Define non-member operator<< so that Output can stream out document list.
996 template <typename T>
997 inline
998 typename llvm::enable_if_c<has_DocumentListTraits<T>::value,Output &>::type
999 operator<<(Output &yout, T &docList) {
1000   yout.beginDocuments();
1001   const size_t count = DocumentListTraits<T>::size(yout, docList);
1002   for(size_t i=0; i < count; ++i) {
1003     if ( yout.preflightDocument(i) ) {
1004       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
1005       yout.postflightDocument();
1006     }
1007   }
1008   yout.endDocuments();
1009   return yout;
1010 }
1011
1012 // Define non-member operator<< so that Output can stream out a map.
1013 template <typename T>
1014 inline
1015 typename llvm::enable_if_c<has_MappingTraits<T>::value,Output &>::type
1016 operator<<(Output &yout, T &map) {
1017   yout.beginDocuments();
1018   if ( yout.preflightDocument(0) ) {
1019     yamlize(yout, map, true);
1020     yout.postflightDocument();
1021   }
1022   yout.endDocuments();
1023   return yout;
1024 }
1025
1026 // Define non-member operator<< so that Output can stream out a sequence.
1027 template <typename T>
1028 inline
1029 typename llvm::enable_if_c<has_SequenceTraits<T>::value,Output &>::type
1030 operator<<(Output &yout, T &seq) {
1031   yout.beginDocuments();
1032   if ( yout.preflightDocument(0) ) {
1033     yamlize(yout, seq, true);
1034     yout.postflightDocument();
1035   }
1036   yout.endDocuments();
1037   return yout;
1038 }
1039
1040 // Provide better error message about types missing a trait specialization
1041 template <typename T>
1042 inline
1043 typename llvm::enable_if_c<missingTraits<T>::value,Output &>::type
1044 operator<<(Output &yout, T &seq) {
1045   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1046   return yout;
1047 }
1048
1049
1050 } // namespace yaml
1051 } // namespace llvm
1052
1053
1054 /// Utility for declaring that a std::vector of a particular type
1055 /// should be considered a YAML sequence.
1056 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1057   namespace llvm {                                                          \
1058   namespace yaml {                                                          \
1059     template<>                                                              \
1060     struct SequenceTraits< std::vector<_type> > {                           \
1061       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1062         return seq.size();                                                  \
1063       }                                                                     \
1064       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1065         if ( index >= seq.size() )                                          \
1066           seq.resize(index+1);                                              \
1067         return seq[index];                                                  \
1068       }                                                                     \
1069     };                                                                      \
1070   }                                                                         \
1071   }
1072
1073 /// Utility for declaring that a std::vector of a particular type
1074 /// should be considered a YAML flow sequence.
1075 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1076   namespace llvm {                                                          \
1077   namespace yaml {                                                          \
1078     template<>                                                              \
1079     struct SequenceTraits< std::vector<_type> > {                           \
1080       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1081         return seq.size();                                                  \
1082       }                                                                     \
1083       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1084         if ( index >= seq.size() )                                          \
1085           seq.resize(index+1);                                              \
1086         return seq[index];                                                  \
1087       }                                                                     \
1088       static const bool flow = true;                                        \
1089     };                                                                      \
1090   }                                                                         \
1091   }
1092
1093 /// Utility for declaring that a std::vector of a particular type
1094 /// should be considered a YAML document list.
1095 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1096   namespace llvm {                                                          \
1097   namespace yaml {                                                          \
1098     template<>                                                              \
1099     struct DocumentListTraits< std::vector<_type> > {                       \
1100       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1101         return seq.size();                                                  \
1102       }                                                                     \
1103       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1104         if ( index >= seq.size() )                                          \
1105           seq.resize(index+1);                                              \
1106         return seq[index];                                                  \
1107       }                                                                     \
1108     };                                                                      \
1109   }                                                                         \
1110   }
1111
1112
1113
1114 #endif // LLVM_SUPPORT_YAMLTRAITS_H