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