[C++] Use 'nullptr'.
[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 "llvm/Support/system_error.h"
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 void endEnumScalar() = 0;
451
452   virtual bool beginBitSetScalar(bool &) = 0;
453   virtual bool bitSetMatch(const char*, bool) = 0;
454   virtual void endBitSetScalar() = 0;
455
456   virtual void scalarString(StringRef &, bool) = 0;
457
458   virtual void setError(const Twine &) = 0;
459
460   template <typename T>
461   void enumCase(T &Val, const char* Str, const T ConstVal) {
462     if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
463       Val = ConstVal;
464     }
465   }
466
467   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
468   template <typename T>
469   void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
470     if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
471       Val = ConstVal;
472     }
473   }
474
475   template <typename T>
476   void bitSetCase(T &Val, const char* Str, const T ConstVal) {
477     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
478       Val = Val | ConstVal;
479     }
480   }
481
482   // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
483   template <typename T>
484   void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
485     if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
486       Val = Val | ConstVal;
487     }
488   }
489
490   void *getContext();
491   void setContext(void *);
492
493   template <typename T>
494   void mapRequired(const char* Key, T& Val) {
495     this->processKey(Key, Val, true);
496   }
497
498   template <typename T>
499   typename std::enable_if<has_SequenceTraits<T>::value,void>::type
500   mapOptional(const char* Key, T& Val) {
501     // omit key/value instead of outputting empty sequence
502     if ( this->canElideEmptySequence() && !(Val.begin() != Val.end()) )
503       return;
504     this->processKey(Key, Val, false);
505   }
506
507   template <typename T>
508   void mapOptional(const char* Key, Optional<T> &Val) {
509     processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false);
510   }
511
512   template <typename T>
513   typename std::enable_if<!has_SequenceTraits<T>::value,void>::type
514   mapOptional(const char* Key, T& Val) {
515     this->processKey(Key, Val, false);
516   }
517
518   template <typename T>
519   void mapOptional(const char* Key, T& Val, const T& Default) {
520     this->processKeyWithDefault(Key, Val, Default, false);
521   }
522   
523 private:
524   template <typename T>
525   void processKeyWithDefault(const char *Key, Optional<T> &Val,
526                              const Optional<T> &DefaultValue, bool Required) {
527     assert(DefaultValue.hasValue() == false &&
528            "Optional<T> shouldn't have a value!");
529     void *SaveInfo;
530     bool UseDefault;
531     const bool sameAsDefault = outputting() && !Val.hasValue();
532     if (!outputting() && !Val.hasValue())
533       Val = T();
534     if (this->preflightKey(Key, Required, sameAsDefault, UseDefault,
535                            SaveInfo)) {
536       yamlize(*this, Val.getValue(), Required);
537       this->postflightKey(SaveInfo);
538     } else {
539       if (UseDefault)
540         Val = DefaultValue;
541     }
542   }
543
544   template <typename T>
545   void processKeyWithDefault(const char *Key, T &Val, const T& DefaultValue,
546                                                                 bool Required) {
547     void *SaveInfo;
548     bool UseDefault;
549     const bool sameAsDefault = outputting() && Val == DefaultValue;
550     if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
551                                                                   SaveInfo) ) {
552       yamlize(*this, Val, Required);
553       this->postflightKey(SaveInfo);
554     }
555     else {
556       if ( UseDefault )
557         Val = DefaultValue;
558     }
559   }
560
561   template <typename T>
562   void processKey(const char *Key, T &Val, bool Required) {
563     void *SaveInfo;
564     bool UseDefault;
565     if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
566       yamlize(*this, Val, Required);
567       this->postflightKey(SaveInfo);
568     }
569   }
570
571 private:
572   void  *Ctxt;
573 };
574
575
576
577 template<typename T>
578 typename std::enable_if<has_ScalarEnumerationTraits<T>::value,void>::type
579 yamlize(IO &io, T &Val, bool) {
580   io.beginEnumScalar();
581   ScalarEnumerationTraits<T>::enumeration(io, Val);
582   io.endEnumScalar();
583 }
584
585 template<typename T>
586 typename std::enable_if<has_ScalarBitSetTraits<T>::value,void>::type
587 yamlize(IO &io, T &Val, bool) {
588   bool DoClear;
589   if ( io.beginBitSetScalar(DoClear) ) {
590     if ( DoClear )
591       Val = static_cast<T>(0);
592     ScalarBitSetTraits<T>::bitset(io, Val);
593     io.endBitSetScalar();
594   }
595 }
596
597
598 template<typename T>
599 typename std::enable_if<has_ScalarTraits<T>::value,void>::type
600 yamlize(IO &io, T &Val, bool) {
601   if ( io.outputting() ) {
602     std::string Storage;
603     llvm::raw_string_ostream Buffer(Storage);
604     ScalarTraits<T>::output(Val, io.getContext(), Buffer);
605     StringRef Str = Buffer.str();
606     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
607   }
608   else {
609     StringRef Str;
610     io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
611     StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
612     if ( !Result.empty() ) {
613       io.setError(llvm::Twine(Result));
614     }
615   }
616 }
617
618
619 template<typename T>
620 typename std::enable_if<validatedMappingTraits<T>::value, void>::type
621 yamlize(IO &io, T &Val, bool) {
622   io.beginMapping();
623   if (io.outputting()) {
624     StringRef Err = MappingTraits<T>::validate(io, Val);
625     if (!Err.empty()) {
626       llvm::errs() << Err << "\n";
627       assert(Err.empty() && "invalid struct trying to be written as yaml");
628     }
629   }
630   MappingTraits<T>::mapping(io, Val);
631   if (!io.outputting()) {
632     StringRef Err = MappingTraits<T>::validate(io, Val);
633     if (!Err.empty())
634       io.setError(Err);
635   }
636   io.endMapping();
637 }
638
639 template<typename T>
640 typename std::enable_if<unvalidatedMappingTraits<T>::value, void>::type
641 yamlize(IO &io, T &Val, bool) {
642   io.beginMapping();
643   MappingTraits<T>::mapping(io, Val);
644   io.endMapping();
645 }
646
647 template<typename T>
648 typename std::enable_if<missingTraits<T>::value, void>::type
649 yamlize(IO &io, T &Val, bool) {
650   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
651 }
652
653 template<typename T>
654 typename std::enable_if<has_SequenceTraits<T>::value,void>::type
655 yamlize(IO &io, T &Seq, bool) {
656   if ( has_FlowTraits< SequenceTraits<T> >::value ) {
657     unsigned incnt = io.beginFlowSequence();
658     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
659     for(unsigned i=0; i < count; ++i) {
660       void *SaveInfo;
661       if ( io.preflightFlowElement(i, SaveInfo) ) {
662         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
663         io.postflightFlowElement(SaveInfo);
664       }
665     }
666     io.endFlowSequence();
667   }
668   else {
669     unsigned incnt = io.beginSequence();
670     unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
671     for(unsigned i=0; i < count; ++i) {
672       void *SaveInfo;
673       if ( io.preflightElement(i, SaveInfo) ) {
674         yamlize(io, SequenceTraits<T>::element(io, Seq, i), true);
675         io.postflightElement(SaveInfo);
676       }
677     }
678     io.endSequence();
679   }
680 }
681
682
683 template<>
684 struct ScalarTraits<bool> {
685   static void output(const bool &, void*, llvm::raw_ostream &);
686   static StringRef input(StringRef, void*, bool &);
687   static bool mustQuote(StringRef) { return false; }
688 };
689
690 template<>
691 struct ScalarTraits<StringRef> {
692   static void output(const StringRef &, void*, llvm::raw_ostream &);
693   static StringRef input(StringRef, void*, StringRef &);
694   static bool mustQuote(StringRef S) { return needsQuotes(S); }
695 };
696  
697 template<>
698 struct ScalarTraits<std::string> {
699   static void output(const std::string &, void*, llvm::raw_ostream &);
700   static StringRef input(StringRef, void*, std::string &);
701   static bool mustQuote(StringRef S) { return needsQuotes(S); }
702 };
703
704 template<>
705 struct ScalarTraits<uint8_t> {
706   static void output(const uint8_t &, void*, llvm::raw_ostream &);
707   static StringRef input(StringRef, void*, uint8_t &);
708   static bool mustQuote(StringRef) { return false; }
709 };
710
711 template<>
712 struct ScalarTraits<uint16_t> {
713   static void output(const uint16_t &, void*, llvm::raw_ostream &);
714   static StringRef input(StringRef, void*, uint16_t &);
715   static bool mustQuote(StringRef) { return false; }
716 };
717
718 template<>
719 struct ScalarTraits<uint32_t> {
720   static void output(const uint32_t &, void*, llvm::raw_ostream &);
721   static StringRef input(StringRef, void*, uint32_t &);
722   static bool mustQuote(StringRef) { return false; }
723 };
724
725 template<>
726 struct ScalarTraits<uint64_t> {
727   static void output(const uint64_t &, void*, llvm::raw_ostream &);
728   static StringRef input(StringRef, void*, uint64_t &);
729   static bool mustQuote(StringRef) { return false; }
730 };
731
732 template<>
733 struct ScalarTraits<int8_t> {
734   static void output(const int8_t &, void*, llvm::raw_ostream &);
735   static StringRef input(StringRef, void*, int8_t &);
736   static bool mustQuote(StringRef) { return false; }
737 };
738
739 template<>
740 struct ScalarTraits<int16_t> {
741   static void output(const int16_t &, void*, llvm::raw_ostream &);
742   static StringRef input(StringRef, void*, int16_t &);
743   static bool mustQuote(StringRef) { return false; }
744 };
745
746 template<>
747 struct ScalarTraits<int32_t> {
748   static void output(const int32_t &, void*, llvm::raw_ostream &);
749   static StringRef input(StringRef, void*, int32_t &);
750   static bool mustQuote(StringRef) { return false; }
751 };
752
753 template<>
754 struct ScalarTraits<int64_t> {
755   static void output(const int64_t &, void*, llvm::raw_ostream &);
756   static StringRef input(StringRef, void*, int64_t &);
757   static bool mustQuote(StringRef) { return false; }
758 };
759
760 template<>
761 struct ScalarTraits<float> {
762   static void output(const float &, void*, llvm::raw_ostream &);
763   static StringRef input(StringRef, void*, float &);
764   static bool mustQuote(StringRef) { return false; }
765 };
766
767 template<>
768 struct ScalarTraits<double> {
769   static void output(const double &, void*, llvm::raw_ostream &);
770   static StringRef input(StringRef, void*, double &);
771   static bool mustQuote(StringRef) { return false; }
772 };
773
774
775
776 // Utility for use within MappingTraits<>::mapping() method
777 // to [de]normalize an object for use with YAML conversion.
778 template <typename TNorm, typename TFinal>
779 struct MappingNormalization {
780   MappingNormalization(IO &i_o, TFinal &Obj)
781       : io(i_o), BufPtr(nullptr), Result(Obj) {
782     if ( io.outputting() ) {
783       BufPtr = new (&Buffer) TNorm(io, Obj);
784     }
785     else {
786       BufPtr = new (&Buffer) TNorm(io);
787     }
788   }
789
790   ~MappingNormalization() {
791     if ( ! io.outputting() ) {
792       Result = BufPtr->denormalize(io);
793     }
794     BufPtr->~TNorm();
795   }
796
797   TNorm* operator->() { return BufPtr; }
798
799 private:
800   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
801
802   Storage       Buffer;
803   IO           &io;
804   TNorm        *BufPtr;
805   TFinal       &Result;
806 };
807
808
809
810 // Utility for use within MappingTraits<>::mapping() method
811 // to [de]normalize an object for use with YAML conversion.
812 template <typename TNorm, typename TFinal>
813 struct MappingNormalizationHeap {
814   MappingNormalizationHeap(IO &i_o, TFinal &Obj)
815     : io(i_o), BufPtr(NULL), Result(Obj) {
816     if ( io.outputting() ) {
817       BufPtr = new (&Buffer) TNorm(io, Obj);
818     }
819     else {
820       BufPtr = new TNorm(io);
821     }
822   }
823
824   ~MappingNormalizationHeap() {
825     if ( io.outputting() ) {
826       BufPtr->~TNorm();
827     }
828     else {
829       Result = BufPtr->denormalize(io);
830     }
831   }
832
833   TNorm* operator->() { return BufPtr; }
834
835 private:
836   typedef llvm::AlignedCharArrayUnion<TNorm> Storage;
837
838   Storage       Buffer;
839   IO           &io;
840   TNorm        *BufPtr;
841   TFinal       &Result;
842 };
843
844
845
846 ///
847 /// The Input class is used to parse a yaml document into in-memory structs
848 /// and vectors.
849 ///
850 /// It works by using YAMLParser to do a syntax parse of the entire yaml
851 /// document, then the Input class builds a graph of HNodes which wraps
852 /// each yaml Node.  The extra layer is buffering.  The low level yaml
853 /// parser only lets you look at each node once.  The buffering layer lets
854 /// you search and interate multiple times.  This is necessary because
855 /// the mapRequired() method calls may not be in the same order
856 /// as the keys in the document.
857 ///
858 class Input : public IO {
859 public:
860   // Construct a yaml Input object from a StringRef and optional
861   // user-data. The DiagHandler can be specified to provide
862   // alternative error reporting.
863   Input(StringRef InputContent,
864         void *Ctxt = nullptr,
865         SourceMgr::DiagHandlerTy DiagHandler = nullptr,
866         void *DiagHandlerCtxt = nullptr);
867   ~Input();
868
869   // Check if there was an syntax or semantic error during parsing.
870   llvm::error_code error();
871
872 private:
873   bool outputting() override;
874   bool mapTag(StringRef, bool) override;
875   void beginMapping() override;
876   void endMapping() override;
877   bool preflightKey(const char *, bool, bool, bool &, void *&) override;
878   void postflightKey(void *) override;
879   unsigned beginSequence() override;
880   void endSequence() override;
881   bool preflightElement(unsigned index, void *&) override;
882   void postflightElement(void *) override;
883   unsigned beginFlowSequence() override;
884   bool preflightFlowElement(unsigned , void *&) override;
885   void postflightFlowElement(void *) override;
886   void endFlowSequence() override;
887   void beginEnumScalar() override;
888   bool matchEnumScalar(const char*, bool) override;
889   void endEnumScalar() override;
890   bool beginBitSetScalar(bool &) override;
891   bool bitSetMatch(const char *, bool ) override;
892   void endBitSetScalar() override;
893   void scalarString(StringRef &, bool) override;
894   void setError(const Twine &message) override;
895   bool canElideEmptySequence() override;
896
897   class HNode {
898     virtual void anchor();
899   public:
900     HNode(Node *n) : _node(n) { }
901     virtual ~HNode() { }
902     static inline bool classof(const HNode *) { return true; }
903
904     Node *_node;
905   };
906
907   class EmptyHNode : public HNode {
908     void anchor() override;
909   public:
910     EmptyHNode(Node *n) : HNode(n) { }
911     static inline bool classof(const HNode *n) {
912       return NullNode::classof(n->_node);
913     }
914     static inline bool classof(const EmptyHNode *) { return true; }
915   };
916
917   class ScalarHNode : public HNode {
918     void anchor() override;
919   public:
920     ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
921
922     StringRef value() const { return _value; }
923
924     static inline bool classof(const HNode *n) {
925       return ScalarNode::classof(n->_node);
926     }
927     static inline bool classof(const ScalarHNode *) { return true; }
928   protected:
929     StringRef _value;
930   };
931
932   class MapHNode : public HNode {
933   public:
934     MapHNode(Node *n) : HNode(n) { }
935     virtual ~MapHNode();
936
937     static inline bool classof(const HNode *n) {
938       return MappingNode::classof(n->_node);
939     }
940     static inline bool classof(const MapHNode *) { return true; }
941
942     typedef llvm::StringMap<HNode*> NameToNode;
943
944     bool isValidKey(StringRef key);
945
946     NameToNode                        Mapping;
947     llvm::SmallVector<const char*, 6> ValidKeys;
948   };
949
950   class SequenceHNode : public HNode {
951   public:
952     SequenceHNode(Node *n) : HNode(n) { }
953     virtual ~SequenceHNode();
954
955     static inline bool classof(const HNode *n) {
956       return SequenceNode::classof(n->_node);
957     }
958     static inline bool classof(const SequenceHNode *) { return true; }
959
960     std::vector<HNode*> Entries;
961   };
962
963   Input::HNode *createHNodes(Node *node);
964   void setError(HNode *hnode, const Twine &message);
965   void setError(Node *node, const Twine &message);
966
967
968 public:
969   // These are only used by operator>>. They could be private
970   // if those templated things could be made friends.
971   bool setCurrentDocument();
972   void nextDocument();
973
974 private:
975   llvm::SourceMgr                     SrcMgr; // must be before Strm
976   std::unique_ptr<llvm::yaml::Stream> Strm;
977   std::unique_ptr<HNode>              TopNode;
978   llvm::error_code                    EC;
979   llvm::BumpPtrAllocator              StringAllocator;
980   llvm::yaml::document_iterator       DocIterator;
981   std::vector<bool>                   BitValuesUsed;
982   HNode                              *CurrentNode;
983   bool                                ScalarMatchFound;
984 };
985
986
987
988
989 ///
990 /// The Output class is used to generate a yaml document from in-memory structs
991 /// and vectors.
992 ///
993 class Output : public IO {
994 public:
995   Output(llvm::raw_ostream &, void *Ctxt=nullptr);
996   virtual ~Output();
997
998   bool outputting() override;
999   bool mapTag(StringRef, bool) override;
1000   void beginMapping() override;
1001   void endMapping() override;
1002   bool preflightKey(const char *key, bool, bool, bool &, void *&) override;
1003   void postflightKey(void *) override;
1004   unsigned beginSequence() override;
1005   void endSequence() override;
1006   bool preflightElement(unsigned, void *&) override;
1007   void postflightElement(void *) override;
1008   unsigned beginFlowSequence() override;
1009   bool preflightFlowElement(unsigned, void *&) override;
1010   void postflightFlowElement(void *) override;
1011   void endFlowSequence() override;
1012   void beginEnumScalar() override;
1013   bool matchEnumScalar(const char*, bool) override;
1014   void endEnumScalar() override;
1015   bool beginBitSetScalar(bool &) override;
1016   bool bitSetMatch(const char *, bool ) override;
1017   void endBitSetScalar() override;
1018   void scalarString(StringRef &, bool) override;
1019   void setError(const Twine &message) override;
1020   bool canElideEmptySequence() override;
1021 public:
1022   // These are only used by operator<<. They could be private
1023   // if that templated operator could be made a friend.
1024   void beginDocuments();
1025   bool preflightDocument(unsigned);
1026   void postflightDocument();
1027   void endDocuments();
1028
1029 private:
1030   void output(StringRef s);
1031   void outputUpToEndOfLine(StringRef s);
1032   void newLineCheck();
1033   void outputNewLine();
1034   void paddedKey(StringRef key);
1035
1036   enum InState { inSeq, inFlowSeq, inMapFirstKey, inMapOtherKey };
1037
1038   llvm::raw_ostream       &Out;
1039   SmallVector<InState, 8>  StateStack;
1040   int                      Column;
1041   int                      ColumnAtFlowStart;
1042   bool                     NeedBitValueComma;
1043   bool                     NeedFlowSequenceComma;
1044   bool                     EnumerationMatchFound;
1045   bool                     NeedsNewLine;
1046 };
1047
1048
1049
1050
1051 /// YAML I/O does conversion based on types. But often native data types
1052 /// are just a typedef of built in intergral types (e.g. int).  But the C++
1053 /// type matching system sees through the typedef and all the typedefed types
1054 /// look like a built in type. This will cause the generic YAML I/O conversion
1055 /// to be used. To provide better control over the YAML conversion, you can
1056 /// use this macro instead of typedef.  It will create a class with one field
1057 /// and automatic conversion operators to and from the base type.
1058 /// Based on BOOST_STRONG_TYPEDEF
1059 #define LLVM_YAML_STRONG_TYPEDEF(_base, _type)                                 \
1060     struct _type {                                                             \
1061         _type() { }                                                            \
1062         _type(const _base v) : value(v) { }                                    \
1063         _type(const _type &v) : value(v.value) {}                              \
1064         _type &operator=(const _type &rhs) { value = rhs.value; return *this; }\
1065         _type &operator=(const _base &rhs) { value = rhs; return *this; }      \
1066         operator const _base & () const { return value; }                      \
1067         bool operator==(const _type &rhs) const { return value == rhs.value; } \
1068         bool operator==(const _base &rhs) const { return value == rhs; }       \
1069         bool operator<(const _type &rhs) const { return value < rhs.value; }   \
1070         _base value;                                                           \
1071     };
1072
1073
1074
1075 ///
1076 /// Use these types instead of uintXX_t in any mapping to have
1077 /// its yaml output formatted as hexadecimal.
1078 ///
1079 LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
1080 LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
1081 LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
1082 LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
1083
1084
1085 template<>
1086 struct ScalarTraits<Hex8> {
1087   static void output(const Hex8 &, void*, llvm::raw_ostream &);
1088   static StringRef input(StringRef, void*, Hex8 &);
1089   static bool mustQuote(StringRef) { return false; }
1090 };
1091
1092 template<>
1093 struct ScalarTraits<Hex16> {
1094   static void output(const Hex16 &, void*, llvm::raw_ostream &);
1095   static StringRef input(StringRef, void*, Hex16 &);
1096   static bool mustQuote(StringRef) { return false; }
1097 };
1098
1099 template<>
1100 struct ScalarTraits<Hex32> {
1101   static void output(const Hex32 &, void*, llvm::raw_ostream &);
1102   static StringRef input(StringRef, void*, Hex32 &);
1103   static bool mustQuote(StringRef) { return false; }
1104 };
1105
1106 template<>
1107 struct ScalarTraits<Hex64> {
1108   static void output(const Hex64 &, void*, llvm::raw_ostream &);
1109   static StringRef input(StringRef, void*, Hex64 &);
1110   static bool mustQuote(StringRef) { return false; }
1111 };
1112
1113
1114 // Define non-member operator>> so that Input can stream in a document list.
1115 template <typename T>
1116 inline
1117 typename std::enable_if<has_DocumentListTraits<T>::value, Input &>::type
1118 operator>>(Input &yin, T &docList) {
1119   int i = 0;
1120   while ( yin.setCurrentDocument() ) {
1121     yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true);
1122     if ( yin.error() )
1123       return yin;
1124     yin.nextDocument();
1125     ++i;
1126   }
1127   return yin;
1128 }
1129
1130 // Define non-member operator>> so that Input can stream in a map as a document.
1131 template <typename T>
1132 inline
1133 typename std::enable_if<has_MappingTraits<T>::value, Input &>::type
1134 operator>>(Input &yin, T &docMap) {
1135   yin.setCurrentDocument();
1136   yamlize(yin, docMap, true);
1137   return yin;
1138 }
1139
1140 // Define non-member operator>> so that Input can stream in a sequence as
1141 // a document.
1142 template <typename T>
1143 inline
1144 typename std::enable_if<has_SequenceTraits<T>::value, Input &>::type
1145 operator>>(Input &yin, T &docSeq) {
1146   if (yin.setCurrentDocument())
1147     yamlize(yin, docSeq, true);
1148   return yin;
1149 }
1150
1151 // Provide better error message about types missing a trait specialization
1152 template <typename T>
1153 inline
1154 typename std::enable_if<missingTraits<T>::value, Input &>::type
1155 operator>>(Input &yin, T &docSeq) {
1156   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1157   return yin;
1158 }
1159
1160
1161 // Define non-member operator<< so that Output can stream out document list.
1162 template <typename T>
1163 inline
1164 typename std::enable_if<has_DocumentListTraits<T>::value, Output &>::type
1165 operator<<(Output &yout, T &docList) {
1166   yout.beginDocuments();
1167   const size_t count = DocumentListTraits<T>::size(yout, docList);
1168   for(size_t i=0; i < count; ++i) {
1169     if ( yout.preflightDocument(i) ) {
1170       yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true);
1171       yout.postflightDocument();
1172     }
1173   }
1174   yout.endDocuments();
1175   return yout;
1176 }
1177
1178 // Define non-member operator<< so that Output can stream out a map.
1179 template <typename T>
1180 inline
1181 typename std::enable_if<has_MappingTraits<T>::value, Output &>::type
1182 operator<<(Output &yout, T &map) {
1183   yout.beginDocuments();
1184   if ( yout.preflightDocument(0) ) {
1185     yamlize(yout, map, true);
1186     yout.postflightDocument();
1187   }
1188   yout.endDocuments();
1189   return yout;
1190 }
1191
1192 // Define non-member operator<< so that Output can stream out a sequence.
1193 template <typename T>
1194 inline
1195 typename std::enable_if<has_SequenceTraits<T>::value, Output &>::type
1196 operator<<(Output &yout, T &seq) {
1197   yout.beginDocuments();
1198   if ( yout.preflightDocument(0) ) {
1199     yamlize(yout, seq, true);
1200     yout.postflightDocument();
1201   }
1202   yout.endDocuments();
1203   return yout;
1204 }
1205
1206 // Provide better error message about types missing a trait specialization
1207 template <typename T>
1208 inline
1209 typename std::enable_if<missingTraits<T>::value, Output &>::type
1210 operator<<(Output &yout, T &seq) {
1211   char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
1212   return yout;
1213 }
1214
1215
1216 } // namespace yaml
1217 } // namespace llvm
1218
1219
1220 /// Utility for declaring that a std::vector of a particular type
1221 /// should be considered a YAML sequence.
1222 #define LLVM_YAML_IS_SEQUENCE_VECTOR(_type)                                 \
1223   namespace llvm {                                                          \
1224   namespace yaml {                                                          \
1225     template<>                                                              \
1226     struct SequenceTraits< std::vector<_type> > {                           \
1227       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1228         return seq.size();                                                  \
1229       }                                                                     \
1230       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1231         if ( index >= seq.size() )                                          \
1232           seq.resize(index+1);                                              \
1233         return seq[index];                                                  \
1234       }                                                                     \
1235     };                                                                      \
1236   }                                                                         \
1237   }
1238
1239 /// Utility for declaring that a std::vector of a particular type
1240 /// should be considered a YAML flow sequence.
1241 #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(_type)                            \
1242   namespace llvm {                                                          \
1243   namespace yaml {                                                          \
1244     template<>                                                              \
1245     struct SequenceTraits< std::vector<_type> > {                           \
1246       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1247         return seq.size();                                                  \
1248       }                                                                     \
1249       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1250         (void)flow; /* Remove this workaround after PR17897 is fixed */     \
1251         if ( index >= seq.size() )                                          \
1252           seq.resize(index+1);                                              \
1253         return seq[index];                                                  \
1254       }                                                                     \
1255       static const bool flow = true;                                        \
1256     };                                                                      \
1257   }                                                                         \
1258   }
1259
1260 /// Utility for declaring that a std::vector of a particular type
1261 /// should be considered a YAML document list.
1262 #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type)                            \
1263   namespace llvm {                                                          \
1264   namespace yaml {                                                          \
1265     template<>                                                              \
1266     struct DocumentListTraits< std::vector<_type> > {                       \
1267       static size_t size(IO &io, std::vector<_type> &seq) {                 \
1268         return seq.size();                                                  \
1269       }                                                                     \
1270       static _type& element(IO &io, std::vector<_type> &seq, size_t index) {\
1271         if ( index >= seq.size() )                                          \
1272           seq.resize(index+1);                                              \
1273         return seq[index];                                                  \
1274       }                                                                     \
1275     };                                                                      \
1276   }                                                                         \
1277   }
1278
1279
1280
1281 #endif // LLVM_SUPPORT_YAMLTRAITS_H