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