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