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