YAMLTraits.h 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/YAMLTraits.h --------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_YAMLTRAITS_H
  14. #define LLVM_SUPPORT_YAMLTRAITS_H
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringMap.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Support/AlignOf.h"
  23. #include "llvm/Support/Allocator.h"
  24. #include "llvm/Support/Endian.h"
  25. #include "llvm/Support/SMLoc.h"
  26. #include "llvm/Support/SourceMgr.h"
  27. #include "llvm/Support/YAMLParser.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include <cassert>
  30. #include <cctype>
  31. #include <map>
  32. #include <memory>
  33. #include <new>
  34. #include <string>
  35. #include <system_error>
  36. #include <type_traits>
  37. #include <vector>
  38. namespace llvm {
  39. class VersionTuple;
  40. namespace yaml {
  41. enum class NodeKind : uint8_t {
  42. Scalar,
  43. Map,
  44. Sequence,
  45. };
  46. struct EmptyContext {};
  47. /// This class should be specialized by any type that needs to be converted
  48. /// to/from a YAML mapping. For example:
  49. ///
  50. /// struct MappingTraits<MyStruct> {
  51. /// static void mapping(IO &io, MyStruct &s) {
  52. /// io.mapRequired("name", s.name);
  53. /// io.mapRequired("size", s.size);
  54. /// io.mapOptional("age", s.age);
  55. /// }
  56. /// };
  57. template<class T>
  58. struct MappingTraits {
  59. // Must provide:
  60. // static void mapping(IO &io, T &fields);
  61. // Optionally may provide:
  62. // static std::string validate(IO &io, T &fields);
  63. //
  64. // The optional flow flag will cause generated YAML to use a flow mapping
  65. // (e.g. { a: 0, b: 1 }):
  66. // static const bool flow = true;
  67. };
  68. /// This class is similar to MappingTraits<T> but allows you to pass in
  69. /// additional context for each map operation. For example:
  70. ///
  71. /// struct MappingContextTraits<MyStruct, MyContext> {
  72. /// static void mapping(IO &io, MyStruct &s, MyContext &c) {
  73. /// io.mapRequired("name", s.name);
  74. /// io.mapRequired("size", s.size);
  75. /// io.mapOptional("age", s.age);
  76. /// ++c.TimesMapped;
  77. /// }
  78. /// };
  79. template <class T, class Context> struct MappingContextTraits {
  80. // Must provide:
  81. // static void mapping(IO &io, T &fields, Context &Ctx);
  82. // Optionally may provide:
  83. // static std::string validate(IO &io, T &fields, Context &Ctx);
  84. //
  85. // The optional flow flag will cause generated YAML to use a flow mapping
  86. // (e.g. { a: 0, b: 1 }):
  87. // static const bool flow = true;
  88. };
  89. /// This class should be specialized by any integral type that converts
  90. /// to/from a YAML scalar where there is a one-to-one mapping between
  91. /// in-memory values and a string in YAML. For example:
  92. ///
  93. /// struct ScalarEnumerationTraits<Colors> {
  94. /// static void enumeration(IO &io, Colors &value) {
  95. /// io.enumCase(value, "red", cRed);
  96. /// io.enumCase(value, "blue", cBlue);
  97. /// io.enumCase(value, "green", cGreen);
  98. /// }
  99. /// };
  100. template <typename T, typename Enable = void> struct ScalarEnumerationTraits {
  101. // Must provide:
  102. // static void enumeration(IO &io, T &value);
  103. };
  104. /// This class should be specialized by any integer type that is a union
  105. /// of bit values and the YAML representation is a flow sequence of
  106. /// strings. For example:
  107. ///
  108. /// struct ScalarBitSetTraits<MyFlags> {
  109. /// static void bitset(IO &io, MyFlags &value) {
  110. /// io.bitSetCase(value, "big", flagBig);
  111. /// io.bitSetCase(value, "flat", flagFlat);
  112. /// io.bitSetCase(value, "round", flagRound);
  113. /// }
  114. /// };
  115. template <typename T, typename Enable = void> struct ScalarBitSetTraits {
  116. // Must provide:
  117. // static void bitset(IO &io, T &value);
  118. };
  119. /// Describe which type of quotes should be used when quoting is necessary.
  120. /// Some non-printable characters need to be double-quoted, while some others
  121. /// are fine with simple-quoting, and some don't need any quoting.
  122. enum class QuotingType { None, Single, Double };
  123. /// This class should be specialized by type that requires custom conversion
  124. /// to/from a yaml scalar. For example:
  125. ///
  126. /// template<>
  127. /// struct ScalarTraits<MyType> {
  128. /// static void output(const MyType &val, void*, llvm::raw_ostream &out) {
  129. /// // stream out custom formatting
  130. /// out << llvm::format("%x", val);
  131. /// }
  132. /// static StringRef input(StringRef scalar, void*, MyType &value) {
  133. /// // parse scalar and set `value`
  134. /// // return empty string on success, or error string
  135. /// return StringRef();
  136. /// }
  137. /// static QuotingType mustQuote(StringRef) { return QuotingType::Single; }
  138. /// };
  139. template <typename T, typename Enable = void> struct ScalarTraits {
  140. // Must provide:
  141. //
  142. // Function to write the value as a string:
  143. // static void output(const T &value, void *ctxt, llvm::raw_ostream &out);
  144. //
  145. // Function to convert a string to a value. Returns the empty
  146. // StringRef on success or an error string if string is malformed:
  147. // static StringRef input(StringRef scalar, void *ctxt, T &value);
  148. //
  149. // Function to determine if the value should be quoted.
  150. // static QuotingType mustQuote(StringRef);
  151. };
  152. /// This class should be specialized by type that requires custom conversion
  153. /// to/from a YAML literal block scalar. For example:
  154. ///
  155. /// template <>
  156. /// struct BlockScalarTraits<MyType> {
  157. /// static void output(const MyType &Value, void*, llvm::raw_ostream &Out)
  158. /// {
  159. /// // stream out custom formatting
  160. /// Out << Value;
  161. /// }
  162. /// static StringRef input(StringRef Scalar, void*, MyType &Value) {
  163. /// // parse scalar and set `value`
  164. /// // return empty string on success, or error string
  165. /// return StringRef();
  166. /// }
  167. /// };
  168. template <typename T>
  169. struct BlockScalarTraits {
  170. // Must provide:
  171. //
  172. // Function to write the value as a string:
  173. // static void output(const T &Value, void *ctx, llvm::raw_ostream &Out);
  174. //
  175. // Function to convert a string to a value. Returns the empty
  176. // StringRef on success or an error string if string is malformed:
  177. // static StringRef input(StringRef Scalar, void *ctxt, T &Value);
  178. //
  179. // Optional:
  180. // static StringRef inputTag(T &Val, std::string Tag)
  181. // static void outputTag(const T &Val, raw_ostream &Out)
  182. };
  183. /// This class should be specialized by type that requires custom conversion
  184. /// to/from a YAML scalar with optional tags. For example:
  185. ///
  186. /// template <>
  187. /// struct TaggedScalarTraits<MyType> {
  188. /// static void output(const MyType &Value, void*, llvm::raw_ostream
  189. /// &ScalarOut, llvm::raw_ostream &TagOut)
  190. /// {
  191. /// // stream out custom formatting including optional Tag
  192. /// Out << Value;
  193. /// }
  194. /// static StringRef input(StringRef Scalar, StringRef Tag, void*, MyType
  195. /// &Value) {
  196. /// // parse scalar and set `value`
  197. /// // return empty string on success, or error string
  198. /// return StringRef();
  199. /// }
  200. /// static QuotingType mustQuote(const MyType &Value, StringRef) {
  201. /// return QuotingType::Single;
  202. /// }
  203. /// };
  204. template <typename T> struct TaggedScalarTraits {
  205. // Must provide:
  206. //
  207. // Function to write the value and tag as strings:
  208. // static void output(const T &Value, void *ctx, llvm::raw_ostream &ScalarOut,
  209. // llvm::raw_ostream &TagOut);
  210. //
  211. // Function to convert a string to a value. Returns the empty
  212. // StringRef on success or an error string if string is malformed:
  213. // static StringRef input(StringRef Scalar, StringRef Tag, void *ctxt, T
  214. // &Value);
  215. //
  216. // Function to determine if the value should be quoted.
  217. // static QuotingType mustQuote(const T &Value, StringRef Scalar);
  218. };
  219. /// This class should be specialized by any type that needs to be converted
  220. /// to/from a YAML sequence. For example:
  221. ///
  222. /// template<>
  223. /// struct SequenceTraits<MyContainer> {
  224. /// static size_t size(IO &io, MyContainer &seq) {
  225. /// return seq.size();
  226. /// }
  227. /// static MyType& element(IO &, MyContainer &seq, size_t index) {
  228. /// if ( index >= seq.size() )
  229. /// seq.resize(index+1);
  230. /// return seq[index];
  231. /// }
  232. /// };
  233. template<typename T, typename EnableIf = void>
  234. struct SequenceTraits {
  235. // Must provide:
  236. // static size_t size(IO &io, T &seq);
  237. // static T::value_type& element(IO &io, T &seq, size_t index);
  238. //
  239. // The following is option and will cause generated YAML to use
  240. // a flow sequence (e.g. [a,b,c]).
  241. // static const bool flow = true;
  242. };
  243. /// This class should be specialized by any type for which vectors of that
  244. /// type need to be converted to/from a YAML sequence.
  245. template<typename T, typename EnableIf = void>
  246. struct SequenceElementTraits {
  247. // Must provide:
  248. // static const bool flow;
  249. };
  250. /// This class should be specialized by any type that needs to be converted
  251. /// to/from a list of YAML documents.
  252. template<typename T>
  253. struct DocumentListTraits {
  254. // Must provide:
  255. // static size_t size(IO &io, T &seq);
  256. // static T::value_type& element(IO &io, T &seq, size_t index);
  257. };
  258. /// This class should be specialized by any type that needs to be converted
  259. /// to/from a YAML mapping in the case where the names of the keys are not known
  260. /// in advance, e.g. a string map.
  261. template <typename T>
  262. struct CustomMappingTraits {
  263. // static void inputOne(IO &io, StringRef key, T &elem);
  264. // static void output(IO &io, T &elem);
  265. };
  266. /// This class should be specialized by any type that can be represented as
  267. /// a scalar, map, or sequence, decided dynamically. For example:
  268. ///
  269. /// typedef std::unique_ptr<MyBase> MyPoly;
  270. ///
  271. /// template<>
  272. /// struct PolymorphicTraits<MyPoly> {
  273. /// static NodeKind getKind(const MyPoly &poly) {
  274. /// return poly->getKind();
  275. /// }
  276. /// static MyScalar& getAsScalar(MyPoly &poly) {
  277. /// if (!poly || !isa<MyScalar>(poly))
  278. /// poly.reset(new MyScalar());
  279. /// return *cast<MyScalar>(poly.get());
  280. /// }
  281. /// // ...
  282. /// };
  283. template <typename T> struct PolymorphicTraits {
  284. // Must provide:
  285. // static NodeKind getKind(const T &poly);
  286. // static scalar_type &getAsScalar(T &poly);
  287. // static map_type &getAsMap(T &poly);
  288. // static sequence_type &getAsSequence(T &poly);
  289. };
  290. // Only used for better diagnostics of missing traits
  291. template <typename T>
  292. struct MissingTrait;
  293. // Test if ScalarEnumerationTraits<T> is defined on type T.
  294. template <class T>
  295. struct has_ScalarEnumerationTraits
  296. {
  297. using Signature_enumeration = void (*)(class IO&, T&);
  298. template <typename U>
  299. static char test(SameType<Signature_enumeration, &U::enumeration>*);
  300. template <typename U>
  301. static double test(...);
  302. static bool const value =
  303. (sizeof(test<ScalarEnumerationTraits<T>>(nullptr)) == 1);
  304. };
  305. // Test if ScalarBitSetTraits<T> is defined on type T.
  306. template <class T>
  307. struct has_ScalarBitSetTraits
  308. {
  309. using Signature_bitset = void (*)(class IO&, T&);
  310. template <typename U>
  311. static char test(SameType<Signature_bitset, &U::bitset>*);
  312. template <typename U>
  313. static double test(...);
  314. static bool const value = (sizeof(test<ScalarBitSetTraits<T>>(nullptr)) == 1);
  315. };
  316. // Test if ScalarTraits<T> is defined on type T.
  317. template <class T>
  318. struct has_ScalarTraits
  319. {
  320. using Signature_input = StringRef (*)(StringRef, void*, T&);
  321. using Signature_output = void (*)(const T&, void*, raw_ostream&);
  322. using Signature_mustQuote = QuotingType (*)(StringRef);
  323. template <typename U>
  324. static char test(SameType<Signature_input, &U::input> *,
  325. SameType<Signature_output, &U::output> *,
  326. SameType<Signature_mustQuote, &U::mustQuote> *);
  327. template <typename U>
  328. static double test(...);
  329. static bool const value =
  330. (sizeof(test<ScalarTraits<T>>(nullptr, nullptr, nullptr)) == 1);
  331. };
  332. // Test if BlockScalarTraits<T> is defined on type T.
  333. template <class T>
  334. struct has_BlockScalarTraits
  335. {
  336. using Signature_input = StringRef (*)(StringRef, void *, T &);
  337. using Signature_output = void (*)(const T &, void *, raw_ostream &);
  338. template <typename U>
  339. static char test(SameType<Signature_input, &U::input> *,
  340. SameType<Signature_output, &U::output> *);
  341. template <typename U>
  342. static double test(...);
  343. static bool const value =
  344. (sizeof(test<BlockScalarTraits<T>>(nullptr, nullptr)) == 1);
  345. };
  346. // Test if TaggedScalarTraits<T> is defined on type T.
  347. template <class T> struct has_TaggedScalarTraits {
  348. using Signature_input = StringRef (*)(StringRef, StringRef, void *, T &);
  349. using Signature_output = void (*)(const T &, void *, raw_ostream &,
  350. raw_ostream &);
  351. using Signature_mustQuote = QuotingType (*)(const T &, StringRef);
  352. template <typename U>
  353. static char test(SameType<Signature_input, &U::input> *,
  354. SameType<Signature_output, &U::output> *,
  355. SameType<Signature_mustQuote, &U::mustQuote> *);
  356. template <typename U> static double test(...);
  357. static bool const value =
  358. (sizeof(test<TaggedScalarTraits<T>>(nullptr, nullptr, nullptr)) == 1);
  359. };
  360. // Test if MappingContextTraits<T> is defined on type T.
  361. template <class T, class Context> struct has_MappingTraits {
  362. using Signature_mapping = void (*)(class IO &, T &, Context &);
  363. template <typename U>
  364. static char test(SameType<Signature_mapping, &U::mapping>*);
  365. template <typename U>
  366. static double test(...);
  367. static bool const value =
  368. (sizeof(test<MappingContextTraits<T, Context>>(nullptr)) == 1);
  369. };
  370. // Test if MappingTraits<T> is defined on type T.
  371. template <class T> struct has_MappingTraits<T, EmptyContext> {
  372. using Signature_mapping = void (*)(class IO &, T &);
  373. template <typename U>
  374. static char test(SameType<Signature_mapping, &U::mapping> *);
  375. template <typename U> static double test(...);
  376. static bool const value = (sizeof(test<MappingTraits<T>>(nullptr)) == 1);
  377. };
  378. // Test if MappingContextTraits<T>::validate() is defined on type T.
  379. template <class T, class Context> struct has_MappingValidateTraits {
  380. using Signature_validate = std::string (*)(class IO &, T &, Context &);
  381. template <typename U>
  382. static char test(SameType<Signature_validate, &U::validate>*);
  383. template <typename U>
  384. static double test(...);
  385. static bool const value =
  386. (sizeof(test<MappingContextTraits<T, Context>>(nullptr)) == 1);
  387. };
  388. // Test if MappingTraits<T>::validate() is defined on type T.
  389. template <class T> struct has_MappingValidateTraits<T, EmptyContext> {
  390. using Signature_validate = std::string (*)(class IO &, T &);
  391. template <typename U>
  392. static char test(SameType<Signature_validate, &U::validate> *);
  393. template <typename U> static double test(...);
  394. static bool const value = (sizeof(test<MappingTraits<T>>(nullptr)) == 1);
  395. };
  396. // Test if SequenceTraits<T> is defined on type T.
  397. template <class T>
  398. struct has_SequenceMethodTraits
  399. {
  400. using Signature_size = size_t (*)(class IO&, T&);
  401. template <typename U>
  402. static char test(SameType<Signature_size, &U::size>*);
  403. template <typename U>
  404. static double test(...);
  405. static bool const value = (sizeof(test<SequenceTraits<T>>(nullptr)) == 1);
  406. };
  407. // Test if CustomMappingTraits<T> is defined on type T.
  408. template <class T>
  409. struct has_CustomMappingTraits
  410. {
  411. using Signature_input = void (*)(IO &io, StringRef key, T &v);
  412. template <typename U>
  413. static char test(SameType<Signature_input, &U::inputOne>*);
  414. template <typename U>
  415. static double test(...);
  416. static bool const value =
  417. (sizeof(test<CustomMappingTraits<T>>(nullptr)) == 1);
  418. };
  419. // has_FlowTraits<int> will cause an error with some compilers because
  420. // it subclasses int. Using this wrapper only instantiates the
  421. // real has_FlowTraits only if the template type is a class.
  422. template <typename T, bool Enabled = std::is_class<T>::value>
  423. class has_FlowTraits
  424. {
  425. public:
  426. static const bool value = false;
  427. };
  428. // Some older gcc compilers don't support straight forward tests
  429. // for members, so test for ambiguity cause by the base and derived
  430. // classes both defining the member.
  431. template <class T>
  432. struct has_FlowTraits<T, true>
  433. {
  434. struct Fallback { bool flow; };
  435. struct Derived : T, Fallback { };
  436. template<typename C>
  437. static char (&f(SameType<bool Fallback::*, &C::flow>*))[1];
  438. template<typename C>
  439. static char (&f(...))[2];
  440. static bool const value = sizeof(f<Derived>(nullptr)) == 2;
  441. };
  442. // Test if SequenceTraits<T> is defined on type T
  443. template<typename T>
  444. struct has_SequenceTraits : public std::integral_constant<bool,
  445. has_SequenceMethodTraits<T>::value > { };
  446. // Test if DocumentListTraits<T> is defined on type T
  447. template <class T>
  448. struct has_DocumentListTraits
  449. {
  450. using Signature_size = size_t (*)(class IO &, T &);
  451. template <typename U>
  452. static char test(SameType<Signature_size, &U::size>*);
  453. template <typename U>
  454. static double test(...);
  455. static bool const value = (sizeof(test<DocumentListTraits<T>>(nullptr))==1);
  456. };
  457. template <class T> struct has_PolymorphicTraits {
  458. using Signature_getKind = NodeKind (*)(const T &);
  459. template <typename U>
  460. static char test(SameType<Signature_getKind, &U::getKind> *);
  461. template <typename U> static double test(...);
  462. static bool const value = (sizeof(test<PolymorphicTraits<T>>(nullptr)) == 1);
  463. };
  464. inline bool isNumeric(StringRef S) {
  465. const static auto skipDigits = [](StringRef Input) {
  466. return Input.drop_front(
  467. std::min(Input.find_first_not_of("0123456789"), Input.size()));
  468. };
  469. // Make S.front() and S.drop_front().front() (if S.front() is [+-]) calls
  470. // safe.
  471. if (S.empty() || S.equals("+") || S.equals("-"))
  472. return false;
  473. if (S.equals(".nan") || S.equals(".NaN") || S.equals(".NAN"))
  474. return true;
  475. // Infinity and decimal numbers can be prefixed with sign.
  476. StringRef Tail = (S.front() == '-' || S.front() == '+') ? S.drop_front() : S;
  477. // Check for infinity first, because checking for hex and oct numbers is more
  478. // expensive.
  479. if (Tail.equals(".inf") || Tail.equals(".Inf") || Tail.equals(".INF"))
  480. return true;
  481. // Section 10.3.2 Tag Resolution
  482. // YAML 1.2 Specification prohibits Base 8 and Base 16 numbers prefixed with
  483. // [-+], so S should be used instead of Tail.
  484. if (S.startswith("0o"))
  485. return S.size() > 2 &&
  486. S.drop_front(2).find_first_not_of("01234567") == StringRef::npos;
  487. if (S.startswith("0x"))
  488. return S.size() > 2 && S.drop_front(2).find_first_not_of(
  489. "0123456789abcdefABCDEF") == StringRef::npos;
  490. // Parse float: [-+]? (\. [0-9]+ | [0-9]+ (\. [0-9]* )?) ([eE] [-+]? [0-9]+)?
  491. S = Tail;
  492. // Handle cases when the number starts with '.' and hence needs at least one
  493. // digit after dot (as opposed by number which has digits before the dot), but
  494. // doesn't have one.
  495. if (S.startswith(".") &&
  496. (S.equals(".") ||
  497. (S.size() > 1 && std::strchr("0123456789", S[1]) == nullptr)))
  498. return false;
  499. if (S.startswith("E") || S.startswith("e"))
  500. return false;
  501. enum ParseState {
  502. Default,
  503. FoundDot,
  504. FoundExponent,
  505. };
  506. ParseState State = Default;
  507. S = skipDigits(S);
  508. // Accept decimal integer.
  509. if (S.empty())
  510. return true;
  511. if (S.front() == '.') {
  512. State = FoundDot;
  513. S = S.drop_front();
  514. } else if (S.front() == 'e' || S.front() == 'E') {
  515. State = FoundExponent;
  516. S = S.drop_front();
  517. } else {
  518. return false;
  519. }
  520. if (State == FoundDot) {
  521. S = skipDigits(S);
  522. if (S.empty())
  523. return true;
  524. if (S.front() == 'e' || S.front() == 'E') {
  525. State = FoundExponent;
  526. S = S.drop_front();
  527. } else {
  528. return false;
  529. }
  530. }
  531. assert(State == FoundExponent && "Should have found exponent at this point.");
  532. if (S.empty())
  533. return false;
  534. if (S.front() == '+' || S.front() == '-') {
  535. S = S.drop_front();
  536. if (S.empty())
  537. return false;
  538. }
  539. return skipDigits(S).empty();
  540. }
  541. inline bool isNull(StringRef S) {
  542. return S.equals("null") || S.equals("Null") || S.equals("NULL") ||
  543. S.equals("~");
  544. }
  545. inline bool isBool(StringRef S) {
  546. // FIXME: using parseBool is causing multiple tests to fail.
  547. return S.equals("true") || S.equals("True") || S.equals("TRUE") ||
  548. S.equals("false") || S.equals("False") || S.equals("FALSE");
  549. }
  550. // 5.1. Character Set
  551. // The allowed character range explicitly excludes the C0 control block #x0-#x1F
  552. // (except for TAB #x9, LF #xA, and CR #xD which are allowed), DEL #x7F, the C1
  553. // control block #x80-#x9F (except for NEL #x85 which is allowed), the surrogate
  554. // block #xD800-#xDFFF, #xFFFE, and #xFFFF.
  555. inline QuotingType needsQuotes(StringRef S) {
  556. if (S.empty())
  557. return QuotingType::Single;
  558. QuotingType MaxQuotingNeeded = QuotingType::None;
  559. if (isSpace(static_cast<unsigned char>(S.front())) ||
  560. isSpace(static_cast<unsigned char>(S.back())))
  561. MaxQuotingNeeded = QuotingType::Single;
  562. if (isNull(S))
  563. MaxQuotingNeeded = QuotingType::Single;
  564. if (isBool(S))
  565. MaxQuotingNeeded = QuotingType::Single;
  566. if (isNumeric(S))
  567. MaxQuotingNeeded = QuotingType::Single;
  568. // 7.3.3 Plain Style
  569. // Plain scalars must not begin with most indicators, as this would cause
  570. // ambiguity with other YAML constructs.
  571. static constexpr char Indicators[] = R"(-?:\,[]{}#&*!|>'"%@`)";
  572. if (S.find_first_of(Indicators) == 0)
  573. MaxQuotingNeeded = QuotingType::Single;
  574. for (unsigned char C : S) {
  575. // Alphanum is safe.
  576. if (isAlnum(C))
  577. continue;
  578. switch (C) {
  579. // Safe scalar characters.
  580. case '_':
  581. case '-':
  582. case '^':
  583. case '.':
  584. case ',':
  585. case ' ':
  586. // TAB (0x9) is allowed in unquoted strings.
  587. case 0x9:
  588. continue;
  589. // LF(0xA) and CR(0xD) may delimit values and so require at least single
  590. // quotes. LLVM YAML parser cannot handle single quoted multiline so use
  591. // double quoting to produce valid YAML.
  592. case 0xA:
  593. case 0xD:
  594. return QuotingType::Double;
  595. // DEL (0x7F) are excluded from the allowed character range.
  596. case 0x7F:
  597. return QuotingType::Double;
  598. // Forward slash is allowed to be unquoted, but we quote it anyway. We have
  599. // many tests that use FileCheck against YAML output, and this output often
  600. // contains paths. If we quote backslashes but not forward slashes then
  601. // paths will come out either quoted or unquoted depending on which platform
  602. // the test is run on, making FileCheck comparisons difficult.
  603. case '/':
  604. default: {
  605. // C0 control block (0x0 - 0x1F) is excluded from the allowed character
  606. // range.
  607. if (C <= 0x1F)
  608. return QuotingType::Double;
  609. // Always double quote UTF-8.
  610. if ((C & 0x80) != 0)
  611. return QuotingType::Double;
  612. // The character is not safe, at least simple quoting needed.
  613. MaxQuotingNeeded = QuotingType::Single;
  614. }
  615. }
  616. }
  617. return MaxQuotingNeeded;
  618. }
  619. template <typename T, typename Context>
  620. struct missingTraits
  621. : public std::integral_constant<bool,
  622. !has_ScalarEnumerationTraits<T>::value &&
  623. !has_ScalarBitSetTraits<T>::value &&
  624. !has_ScalarTraits<T>::value &&
  625. !has_BlockScalarTraits<T>::value &&
  626. !has_TaggedScalarTraits<T>::value &&
  627. !has_MappingTraits<T, Context>::value &&
  628. !has_SequenceTraits<T>::value &&
  629. !has_CustomMappingTraits<T>::value &&
  630. !has_DocumentListTraits<T>::value &&
  631. !has_PolymorphicTraits<T>::value> {};
  632. template <typename T, typename Context>
  633. struct validatedMappingTraits
  634. : public std::integral_constant<
  635. bool, has_MappingTraits<T, Context>::value &&
  636. has_MappingValidateTraits<T, Context>::value> {};
  637. template <typename T, typename Context>
  638. struct unvalidatedMappingTraits
  639. : public std::integral_constant<
  640. bool, has_MappingTraits<T, Context>::value &&
  641. !has_MappingValidateTraits<T, Context>::value> {};
  642. // Base class for Input and Output.
  643. class IO {
  644. public:
  645. IO(void *Ctxt = nullptr);
  646. virtual ~IO();
  647. virtual bool outputting() const = 0;
  648. virtual unsigned beginSequence() = 0;
  649. virtual bool preflightElement(unsigned, void *&) = 0;
  650. virtual void postflightElement(void*) = 0;
  651. virtual void endSequence() = 0;
  652. virtual bool canElideEmptySequence() = 0;
  653. virtual unsigned beginFlowSequence() = 0;
  654. virtual bool preflightFlowElement(unsigned, void *&) = 0;
  655. virtual void postflightFlowElement(void*) = 0;
  656. virtual void endFlowSequence() = 0;
  657. virtual bool mapTag(StringRef Tag, bool Default=false) = 0;
  658. virtual void beginMapping() = 0;
  659. virtual void endMapping() = 0;
  660. virtual bool preflightKey(const char*, bool, bool, bool &, void *&) = 0;
  661. virtual void postflightKey(void*) = 0;
  662. virtual std::vector<StringRef> keys() = 0;
  663. virtual void beginFlowMapping() = 0;
  664. virtual void endFlowMapping() = 0;
  665. virtual void beginEnumScalar() = 0;
  666. virtual bool matchEnumScalar(const char*, bool) = 0;
  667. virtual bool matchEnumFallback() = 0;
  668. virtual void endEnumScalar() = 0;
  669. virtual bool beginBitSetScalar(bool &) = 0;
  670. virtual bool bitSetMatch(const char*, bool) = 0;
  671. virtual void endBitSetScalar() = 0;
  672. virtual void scalarString(StringRef &, QuotingType) = 0;
  673. virtual void blockScalarString(StringRef &) = 0;
  674. virtual void scalarTag(std::string &) = 0;
  675. virtual NodeKind getNodeKind() = 0;
  676. virtual void setError(const Twine &) = 0;
  677. virtual void setAllowUnknownKeys(bool Allow);
  678. template <typename T>
  679. void enumCase(T &Val, const char* Str, const T ConstVal) {
  680. if ( matchEnumScalar(Str, outputting() && Val == ConstVal) ) {
  681. Val = ConstVal;
  682. }
  683. }
  684. // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
  685. template <typename T>
  686. void enumCase(T &Val, const char* Str, const uint32_t ConstVal) {
  687. if ( matchEnumScalar(Str, outputting() && Val == static_cast<T>(ConstVal)) ) {
  688. Val = ConstVal;
  689. }
  690. }
  691. template <typename FBT, typename T>
  692. void enumFallback(T &Val) {
  693. if (matchEnumFallback()) {
  694. EmptyContext Context;
  695. // FIXME: Force integral conversion to allow strong typedefs to convert.
  696. FBT Res = static_cast<typename FBT::BaseType>(Val);
  697. yamlize(*this, Res, true, Context);
  698. Val = static_cast<T>(static_cast<typename FBT::BaseType>(Res));
  699. }
  700. }
  701. template <typename T>
  702. void bitSetCase(T &Val, const char* Str, const T ConstVal) {
  703. if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
  704. Val = static_cast<T>(Val | ConstVal);
  705. }
  706. }
  707. // allow anonymous enum values to be used with LLVM_YAML_STRONG_TYPEDEF
  708. template <typename T>
  709. void bitSetCase(T &Val, const char* Str, const uint32_t ConstVal) {
  710. if ( bitSetMatch(Str, outputting() && (Val & ConstVal) == ConstVal) ) {
  711. Val = static_cast<T>(Val | ConstVal);
  712. }
  713. }
  714. template <typename T>
  715. void maskedBitSetCase(T &Val, const char *Str, T ConstVal, T Mask) {
  716. if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
  717. Val = Val | ConstVal;
  718. }
  719. template <typename T>
  720. void maskedBitSetCase(T &Val, const char *Str, uint32_t ConstVal,
  721. uint32_t Mask) {
  722. if (bitSetMatch(Str, outputting() && (Val & Mask) == ConstVal))
  723. Val = Val | ConstVal;
  724. }
  725. void *getContext() const;
  726. void setContext(void *);
  727. template <typename T> void mapRequired(const char *Key, T &Val) {
  728. EmptyContext Ctx;
  729. this->processKey(Key, Val, true, Ctx);
  730. }
  731. template <typename T, typename Context>
  732. void mapRequired(const char *Key, T &Val, Context &Ctx) {
  733. this->processKey(Key, Val, true, Ctx);
  734. }
  735. template <typename T> void mapOptional(const char *Key, T &Val) {
  736. EmptyContext Ctx;
  737. mapOptionalWithContext(Key, Val, Ctx);
  738. }
  739. template <typename T, typename DefaultT>
  740. void mapOptional(const char *Key, T &Val, const DefaultT &Default) {
  741. EmptyContext Ctx;
  742. mapOptionalWithContext(Key, Val, Default, Ctx);
  743. }
  744. template <typename T, typename Context>
  745. std::enable_if_t<has_SequenceTraits<T>::value, void>
  746. mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
  747. // omit key/value instead of outputting empty sequence
  748. if (this->canElideEmptySequence() && !(Val.begin() != Val.end()))
  749. return;
  750. this->processKey(Key, Val, false, Ctx);
  751. }
  752. template <typename T, typename Context>
  753. void mapOptionalWithContext(const char *Key, Optional<T> &Val, Context &Ctx) {
  754. this->processKeyWithDefault(Key, Val, Optional<T>(), /*Required=*/false,
  755. Ctx);
  756. }
  757. template <typename T, typename Context>
  758. std::enable_if_t<!has_SequenceTraits<T>::value, void>
  759. mapOptionalWithContext(const char *Key, T &Val, Context &Ctx) {
  760. this->processKey(Key, Val, false, Ctx);
  761. }
  762. template <typename T, typename Context, typename DefaultT>
  763. void mapOptionalWithContext(const char *Key, T &Val, const DefaultT &Default,
  764. Context &Ctx) {
  765. static_assert(std::is_convertible<DefaultT, T>::value,
  766. "Default type must be implicitly convertible to value type!");
  767. this->processKeyWithDefault(Key, Val, static_cast<const T &>(Default),
  768. false, Ctx);
  769. }
  770. private:
  771. template <typename T, typename Context>
  772. void processKeyWithDefault(const char *Key, Optional<T> &Val,
  773. const Optional<T> &DefaultValue, bool Required,
  774. Context &Ctx);
  775. template <typename T, typename Context>
  776. void processKeyWithDefault(const char *Key, T &Val, const T &DefaultValue,
  777. bool Required, Context &Ctx) {
  778. void *SaveInfo;
  779. bool UseDefault;
  780. const bool sameAsDefault = outputting() && Val == DefaultValue;
  781. if ( this->preflightKey(Key, Required, sameAsDefault, UseDefault,
  782. SaveInfo) ) {
  783. yamlize(*this, Val, Required, Ctx);
  784. this->postflightKey(SaveInfo);
  785. }
  786. else {
  787. if ( UseDefault )
  788. Val = DefaultValue;
  789. }
  790. }
  791. template <typename T, typename Context>
  792. void processKey(const char *Key, T &Val, bool Required, Context &Ctx) {
  793. void *SaveInfo;
  794. bool UseDefault;
  795. if ( this->preflightKey(Key, Required, false, UseDefault, SaveInfo) ) {
  796. yamlize(*this, Val, Required, Ctx);
  797. this->postflightKey(SaveInfo);
  798. }
  799. }
  800. private:
  801. void *Ctxt;
  802. };
  803. namespace detail {
  804. template <typename T, typename Context>
  805. void doMapping(IO &io, T &Val, Context &Ctx) {
  806. MappingContextTraits<T, Context>::mapping(io, Val, Ctx);
  807. }
  808. template <typename T> void doMapping(IO &io, T &Val, EmptyContext &Ctx) {
  809. MappingTraits<T>::mapping(io, Val);
  810. }
  811. } // end namespace detail
  812. template <typename T>
  813. std::enable_if_t<has_ScalarEnumerationTraits<T>::value, void>
  814. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  815. io.beginEnumScalar();
  816. ScalarEnumerationTraits<T>::enumeration(io, Val);
  817. io.endEnumScalar();
  818. }
  819. template <typename T>
  820. std::enable_if_t<has_ScalarBitSetTraits<T>::value, void>
  821. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  822. bool DoClear;
  823. if ( io.beginBitSetScalar(DoClear) ) {
  824. if ( DoClear )
  825. Val = T();
  826. ScalarBitSetTraits<T>::bitset(io, Val);
  827. io.endBitSetScalar();
  828. }
  829. }
  830. template <typename T>
  831. std::enable_if_t<has_ScalarTraits<T>::value, void> yamlize(IO &io, T &Val, bool,
  832. EmptyContext &Ctx) {
  833. if ( io.outputting() ) {
  834. std::string Storage;
  835. raw_string_ostream Buffer(Storage);
  836. ScalarTraits<T>::output(Val, io.getContext(), Buffer);
  837. StringRef Str = Buffer.str();
  838. io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
  839. }
  840. else {
  841. StringRef Str;
  842. io.scalarString(Str, ScalarTraits<T>::mustQuote(Str));
  843. StringRef Result = ScalarTraits<T>::input(Str, io.getContext(), Val);
  844. if ( !Result.empty() ) {
  845. io.setError(Twine(Result));
  846. }
  847. }
  848. }
  849. template <typename T>
  850. std::enable_if_t<has_BlockScalarTraits<T>::value, void>
  851. yamlize(IO &YamlIO, T &Val, bool, EmptyContext &Ctx) {
  852. if (YamlIO.outputting()) {
  853. std::string Storage;
  854. raw_string_ostream Buffer(Storage);
  855. BlockScalarTraits<T>::output(Val, YamlIO.getContext(), Buffer);
  856. StringRef Str = Buffer.str();
  857. YamlIO.blockScalarString(Str);
  858. } else {
  859. StringRef Str;
  860. YamlIO.blockScalarString(Str);
  861. StringRef Result =
  862. BlockScalarTraits<T>::input(Str, YamlIO.getContext(), Val);
  863. if (!Result.empty())
  864. YamlIO.setError(Twine(Result));
  865. }
  866. }
  867. template <typename T>
  868. std::enable_if_t<has_TaggedScalarTraits<T>::value, void>
  869. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  870. if (io.outputting()) {
  871. std::string ScalarStorage, TagStorage;
  872. raw_string_ostream ScalarBuffer(ScalarStorage), TagBuffer(TagStorage);
  873. TaggedScalarTraits<T>::output(Val, io.getContext(), ScalarBuffer,
  874. TagBuffer);
  875. io.scalarTag(TagBuffer.str());
  876. StringRef ScalarStr = ScalarBuffer.str();
  877. io.scalarString(ScalarStr,
  878. TaggedScalarTraits<T>::mustQuote(Val, ScalarStr));
  879. } else {
  880. std::string Tag;
  881. io.scalarTag(Tag);
  882. StringRef Str;
  883. io.scalarString(Str, QuotingType::None);
  884. StringRef Result =
  885. TaggedScalarTraits<T>::input(Str, Tag, io.getContext(), Val);
  886. if (!Result.empty()) {
  887. io.setError(Twine(Result));
  888. }
  889. }
  890. }
  891. template <typename T, typename Context>
  892. std::enable_if_t<validatedMappingTraits<T, Context>::value, void>
  893. yamlize(IO &io, T &Val, bool, Context &Ctx) {
  894. if (has_FlowTraits<MappingTraits<T>>::value)
  895. io.beginFlowMapping();
  896. else
  897. io.beginMapping();
  898. if (io.outputting()) {
  899. std::string Err = MappingTraits<T>::validate(io, Val);
  900. if (!Err.empty()) {
  901. errs() << Err << "\n";
  902. assert(Err.empty() && "invalid struct trying to be written as yaml");
  903. }
  904. }
  905. detail::doMapping(io, Val, Ctx);
  906. if (!io.outputting()) {
  907. std::string Err = MappingTraits<T>::validate(io, Val);
  908. if (!Err.empty())
  909. io.setError(Err);
  910. }
  911. if (has_FlowTraits<MappingTraits<T>>::value)
  912. io.endFlowMapping();
  913. else
  914. io.endMapping();
  915. }
  916. template <typename T, typename Context>
  917. std::enable_if_t<unvalidatedMappingTraits<T, Context>::value, void>
  918. yamlize(IO &io, T &Val, bool, Context &Ctx) {
  919. if (has_FlowTraits<MappingTraits<T>>::value) {
  920. io.beginFlowMapping();
  921. detail::doMapping(io, Val, Ctx);
  922. io.endFlowMapping();
  923. } else {
  924. io.beginMapping();
  925. detail::doMapping(io, Val, Ctx);
  926. io.endMapping();
  927. }
  928. }
  929. template <typename T>
  930. std::enable_if_t<has_CustomMappingTraits<T>::value, void>
  931. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  932. if ( io.outputting() ) {
  933. io.beginMapping();
  934. CustomMappingTraits<T>::output(io, Val);
  935. io.endMapping();
  936. } else {
  937. io.beginMapping();
  938. for (StringRef key : io.keys())
  939. CustomMappingTraits<T>::inputOne(io, key, Val);
  940. io.endMapping();
  941. }
  942. }
  943. template <typename T>
  944. std::enable_if_t<has_PolymorphicTraits<T>::value, void>
  945. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  946. switch (io.outputting() ? PolymorphicTraits<T>::getKind(Val)
  947. : io.getNodeKind()) {
  948. case NodeKind::Scalar:
  949. return yamlize(io, PolymorphicTraits<T>::getAsScalar(Val), true, Ctx);
  950. case NodeKind::Map:
  951. return yamlize(io, PolymorphicTraits<T>::getAsMap(Val), true, Ctx);
  952. case NodeKind::Sequence:
  953. return yamlize(io, PolymorphicTraits<T>::getAsSequence(Val), true, Ctx);
  954. }
  955. }
  956. template <typename T>
  957. std::enable_if_t<missingTraits<T, EmptyContext>::value, void>
  958. yamlize(IO &io, T &Val, bool, EmptyContext &Ctx) {
  959. char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
  960. }
  961. template <typename T, typename Context>
  962. std::enable_if_t<has_SequenceTraits<T>::value, void>
  963. yamlize(IO &io, T &Seq, bool, Context &Ctx) {
  964. if ( has_FlowTraits< SequenceTraits<T>>::value ) {
  965. unsigned incnt = io.beginFlowSequence();
  966. unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
  967. for(unsigned i=0; i < count; ++i) {
  968. void *SaveInfo;
  969. if ( io.preflightFlowElement(i, SaveInfo) ) {
  970. yamlize(io, SequenceTraits<T>::element(io, Seq, i), true, Ctx);
  971. io.postflightFlowElement(SaveInfo);
  972. }
  973. }
  974. io.endFlowSequence();
  975. }
  976. else {
  977. unsigned incnt = io.beginSequence();
  978. unsigned count = io.outputting() ? SequenceTraits<T>::size(io, Seq) : incnt;
  979. for(unsigned i=0; i < count; ++i) {
  980. void *SaveInfo;
  981. if ( io.preflightElement(i, SaveInfo) ) {
  982. yamlize(io, SequenceTraits<T>::element(io, Seq, i), true, Ctx);
  983. io.postflightElement(SaveInfo);
  984. }
  985. }
  986. io.endSequence();
  987. }
  988. }
  989. template<>
  990. struct ScalarTraits<bool> {
  991. static void output(const bool &, void* , raw_ostream &);
  992. static StringRef input(StringRef, void *, bool &);
  993. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  994. };
  995. template<>
  996. struct ScalarTraits<StringRef> {
  997. static void output(const StringRef &, void *, raw_ostream &);
  998. static StringRef input(StringRef, void *, StringRef &);
  999. static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
  1000. };
  1001. template<>
  1002. struct ScalarTraits<std::string> {
  1003. static void output(const std::string &, void *, raw_ostream &);
  1004. static StringRef input(StringRef, void *, std::string &);
  1005. static QuotingType mustQuote(StringRef S) { return needsQuotes(S); }
  1006. };
  1007. template<>
  1008. struct ScalarTraits<uint8_t> {
  1009. static void output(const uint8_t &, void *, raw_ostream &);
  1010. static StringRef input(StringRef, void *, uint8_t &);
  1011. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1012. };
  1013. template<>
  1014. struct ScalarTraits<uint16_t> {
  1015. static void output(const uint16_t &, void *, raw_ostream &);
  1016. static StringRef input(StringRef, void *, uint16_t &);
  1017. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1018. };
  1019. template<>
  1020. struct ScalarTraits<uint32_t> {
  1021. static void output(const uint32_t &, void *, raw_ostream &);
  1022. static StringRef input(StringRef, void *, uint32_t &);
  1023. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1024. };
  1025. template<>
  1026. struct ScalarTraits<uint64_t> {
  1027. static void output(const uint64_t &, void *, raw_ostream &);
  1028. static StringRef input(StringRef, void *, uint64_t &);
  1029. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1030. };
  1031. template<>
  1032. struct ScalarTraits<int8_t> {
  1033. static void output(const int8_t &, void *, raw_ostream &);
  1034. static StringRef input(StringRef, void *, int8_t &);
  1035. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1036. };
  1037. template<>
  1038. struct ScalarTraits<int16_t> {
  1039. static void output(const int16_t &, void *, raw_ostream &);
  1040. static StringRef input(StringRef, void *, int16_t &);
  1041. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1042. };
  1043. template<>
  1044. struct ScalarTraits<int32_t> {
  1045. static void output(const int32_t &, void *, raw_ostream &);
  1046. static StringRef input(StringRef, void *, int32_t &);
  1047. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1048. };
  1049. template<>
  1050. struct ScalarTraits<int64_t> {
  1051. static void output(const int64_t &, void *, raw_ostream &);
  1052. static StringRef input(StringRef, void *, int64_t &);
  1053. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1054. };
  1055. template<>
  1056. struct ScalarTraits<float> {
  1057. static void output(const float &, void *, raw_ostream &);
  1058. static StringRef input(StringRef, void *, float &);
  1059. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1060. };
  1061. template<>
  1062. struct ScalarTraits<double> {
  1063. static void output(const double &, void *, raw_ostream &);
  1064. static StringRef input(StringRef, void *, double &);
  1065. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1066. };
  1067. // For endian types, we use existing scalar Traits class for the underlying
  1068. // type. This way endian aware types are supported whenever the traits are
  1069. // defined for the underlying type.
  1070. template <typename value_type, support::endianness endian, size_t alignment>
  1071. struct ScalarTraits<support::detail::packed_endian_specific_integral<
  1072. value_type, endian, alignment>,
  1073. std::enable_if_t<has_ScalarTraits<value_type>::value>> {
  1074. using endian_type =
  1075. support::detail::packed_endian_specific_integral<value_type, endian,
  1076. alignment>;
  1077. static void output(const endian_type &E, void *Ctx, raw_ostream &Stream) {
  1078. ScalarTraits<value_type>::output(static_cast<value_type>(E), Ctx, Stream);
  1079. }
  1080. static StringRef input(StringRef Str, void *Ctx, endian_type &E) {
  1081. value_type V;
  1082. auto R = ScalarTraits<value_type>::input(Str, Ctx, V);
  1083. E = static_cast<endian_type>(V);
  1084. return R;
  1085. }
  1086. static QuotingType mustQuote(StringRef Str) {
  1087. return ScalarTraits<value_type>::mustQuote(Str);
  1088. }
  1089. };
  1090. template <typename value_type, support::endianness endian, size_t alignment>
  1091. struct ScalarEnumerationTraits<
  1092. support::detail::packed_endian_specific_integral<value_type, endian,
  1093. alignment>,
  1094. std::enable_if_t<has_ScalarEnumerationTraits<value_type>::value>> {
  1095. using endian_type =
  1096. support::detail::packed_endian_specific_integral<value_type, endian,
  1097. alignment>;
  1098. static void enumeration(IO &io, endian_type &E) {
  1099. value_type V = E;
  1100. ScalarEnumerationTraits<value_type>::enumeration(io, V);
  1101. E = V;
  1102. }
  1103. };
  1104. template <typename value_type, support::endianness endian, size_t alignment>
  1105. struct ScalarBitSetTraits<
  1106. support::detail::packed_endian_specific_integral<value_type, endian,
  1107. alignment>,
  1108. std::enable_if_t<has_ScalarBitSetTraits<value_type>::value>> {
  1109. using endian_type =
  1110. support::detail::packed_endian_specific_integral<value_type, endian,
  1111. alignment>;
  1112. static void bitset(IO &io, endian_type &E) {
  1113. value_type V = E;
  1114. ScalarBitSetTraits<value_type>::bitset(io, V);
  1115. E = V;
  1116. }
  1117. };
  1118. // Utility for use within MappingTraits<>::mapping() method
  1119. // to [de]normalize an object for use with YAML conversion.
  1120. template <typename TNorm, typename TFinal>
  1121. struct MappingNormalization {
  1122. MappingNormalization(IO &i_o, TFinal &Obj)
  1123. : io(i_o), BufPtr(nullptr), Result(Obj) {
  1124. if ( io.outputting() ) {
  1125. BufPtr = new (&Buffer) TNorm(io, Obj);
  1126. }
  1127. else {
  1128. BufPtr = new (&Buffer) TNorm(io);
  1129. }
  1130. }
  1131. ~MappingNormalization() {
  1132. if ( ! io.outputting() ) {
  1133. Result = BufPtr->denormalize(io);
  1134. }
  1135. BufPtr->~TNorm();
  1136. }
  1137. TNorm* operator->() { return BufPtr; }
  1138. private:
  1139. using Storage = AlignedCharArrayUnion<TNorm>;
  1140. Storage Buffer;
  1141. IO &io;
  1142. TNorm *BufPtr;
  1143. TFinal &Result;
  1144. };
  1145. // Utility for use within MappingTraits<>::mapping() method
  1146. // to [de]normalize an object for use with YAML conversion.
  1147. template <typename TNorm, typename TFinal>
  1148. struct MappingNormalizationHeap {
  1149. MappingNormalizationHeap(IO &i_o, TFinal &Obj, BumpPtrAllocator *allocator)
  1150. : io(i_o), Result(Obj) {
  1151. if ( io.outputting() ) {
  1152. BufPtr = new (&Buffer) TNorm(io, Obj);
  1153. }
  1154. else if (allocator) {
  1155. BufPtr = allocator->Allocate<TNorm>();
  1156. new (BufPtr) TNorm(io);
  1157. } else {
  1158. BufPtr = new TNorm(io);
  1159. }
  1160. }
  1161. ~MappingNormalizationHeap() {
  1162. if ( io.outputting() ) {
  1163. BufPtr->~TNorm();
  1164. }
  1165. else {
  1166. Result = BufPtr->denormalize(io);
  1167. }
  1168. }
  1169. TNorm* operator->() { return BufPtr; }
  1170. private:
  1171. using Storage = AlignedCharArrayUnion<TNorm>;
  1172. Storage Buffer;
  1173. IO &io;
  1174. TNorm *BufPtr = nullptr;
  1175. TFinal &Result;
  1176. };
  1177. ///
  1178. /// The Input class is used to parse a yaml document into in-memory structs
  1179. /// and vectors.
  1180. ///
  1181. /// It works by using YAMLParser to do a syntax parse of the entire yaml
  1182. /// document, then the Input class builds a graph of HNodes which wraps
  1183. /// each yaml Node. The extra layer is buffering. The low level yaml
  1184. /// parser only lets you look at each node once. The buffering layer lets
  1185. /// you search and interate multiple times. This is necessary because
  1186. /// the mapRequired() method calls may not be in the same order
  1187. /// as the keys in the document.
  1188. ///
  1189. class Input : public IO {
  1190. public:
  1191. // Construct a yaml Input object from a StringRef and optional
  1192. // user-data. The DiagHandler can be specified to provide
  1193. // alternative error reporting.
  1194. Input(StringRef InputContent,
  1195. void *Ctxt = nullptr,
  1196. SourceMgr::DiagHandlerTy DiagHandler = nullptr,
  1197. void *DiagHandlerCtxt = nullptr);
  1198. Input(MemoryBufferRef Input,
  1199. void *Ctxt = nullptr,
  1200. SourceMgr::DiagHandlerTy DiagHandler = nullptr,
  1201. void *DiagHandlerCtxt = nullptr);
  1202. ~Input() override;
  1203. // Check if there was an syntax or semantic error during parsing.
  1204. std::error_code error();
  1205. private:
  1206. bool outputting() const override;
  1207. bool mapTag(StringRef, bool) override;
  1208. void beginMapping() override;
  1209. void endMapping() override;
  1210. bool preflightKey(const char *, bool, bool, bool &, void *&) override;
  1211. void postflightKey(void *) override;
  1212. std::vector<StringRef> keys() override;
  1213. void beginFlowMapping() override;
  1214. void endFlowMapping() override;
  1215. unsigned beginSequence() override;
  1216. void endSequence() override;
  1217. bool preflightElement(unsigned index, void *&) override;
  1218. void postflightElement(void *) override;
  1219. unsigned beginFlowSequence() override;
  1220. bool preflightFlowElement(unsigned , void *&) override;
  1221. void postflightFlowElement(void *) override;
  1222. void endFlowSequence() override;
  1223. void beginEnumScalar() override;
  1224. bool matchEnumScalar(const char*, bool) override;
  1225. bool matchEnumFallback() override;
  1226. void endEnumScalar() override;
  1227. bool beginBitSetScalar(bool &) override;
  1228. bool bitSetMatch(const char *, bool ) override;
  1229. void endBitSetScalar() override;
  1230. void scalarString(StringRef &, QuotingType) override;
  1231. void blockScalarString(StringRef &) override;
  1232. void scalarTag(std::string &) override;
  1233. NodeKind getNodeKind() override;
  1234. void setError(const Twine &message) override;
  1235. bool canElideEmptySequence() override;
  1236. class HNode {
  1237. virtual void anchor();
  1238. public:
  1239. HNode(Node *n) : _node(n) { }
  1240. virtual ~HNode() = default;
  1241. static bool classof(const HNode *) { return true; }
  1242. Node *_node;
  1243. };
  1244. class EmptyHNode : public HNode {
  1245. void anchor() override;
  1246. public:
  1247. EmptyHNode(Node *n) : HNode(n) { }
  1248. static bool classof(const HNode *n) { return NullNode::classof(n->_node); }
  1249. static bool classof(const EmptyHNode *) { return true; }
  1250. };
  1251. class ScalarHNode : public HNode {
  1252. void anchor() override;
  1253. public:
  1254. ScalarHNode(Node *n, StringRef s) : HNode(n), _value(s) { }
  1255. StringRef value() const { return _value; }
  1256. static bool classof(const HNode *n) {
  1257. return ScalarNode::classof(n->_node) ||
  1258. BlockScalarNode::classof(n->_node);
  1259. }
  1260. static bool classof(const ScalarHNode *) { return true; }
  1261. protected:
  1262. StringRef _value;
  1263. };
  1264. class MapHNode : public HNode {
  1265. void anchor() override;
  1266. public:
  1267. MapHNode(Node *n) : HNode(n) { }
  1268. static bool classof(const HNode *n) {
  1269. return MappingNode::classof(n->_node);
  1270. }
  1271. static bool classof(const MapHNode *) { return true; }
  1272. using NameToNodeAndLoc =
  1273. StringMap<std::pair<std::unique_ptr<HNode>, SMRange>>;
  1274. NameToNodeAndLoc Mapping;
  1275. SmallVector<std::string, 6> ValidKeys;
  1276. };
  1277. class SequenceHNode : public HNode {
  1278. void anchor() override;
  1279. public:
  1280. SequenceHNode(Node *n) : HNode(n) { }
  1281. static bool classof(const HNode *n) {
  1282. return SequenceNode::classof(n->_node);
  1283. }
  1284. static bool classof(const SequenceHNode *) { return true; }
  1285. std::vector<std::unique_ptr<HNode>> Entries;
  1286. };
  1287. std::unique_ptr<Input::HNode> createHNodes(Node *node);
  1288. void setError(HNode *hnode, const Twine &message);
  1289. void setError(Node *node, const Twine &message);
  1290. void setError(const SMRange &Range, const Twine &message);
  1291. void reportWarning(HNode *hnode, const Twine &message);
  1292. void reportWarning(Node *hnode, const Twine &message);
  1293. void reportWarning(const SMRange &Range, const Twine &message);
  1294. public:
  1295. // These are only used by operator>>. They could be private
  1296. // if those templated things could be made friends.
  1297. bool setCurrentDocument();
  1298. bool nextDocument();
  1299. /// Returns the current node that's being parsed by the YAML Parser.
  1300. const Node *getCurrentNode() const;
  1301. void setAllowUnknownKeys(bool Allow) override;
  1302. private:
  1303. SourceMgr SrcMgr; // must be before Strm
  1304. std::unique_ptr<llvm::yaml::Stream> Strm;
  1305. std::unique_ptr<HNode> TopNode;
  1306. std::error_code EC;
  1307. BumpPtrAllocator StringAllocator;
  1308. document_iterator DocIterator;
  1309. llvm::BitVector BitValuesUsed;
  1310. HNode *CurrentNode = nullptr;
  1311. bool ScalarMatchFound = false;
  1312. bool AllowUnknownKeys = false;
  1313. };
  1314. ///
  1315. /// The Output class is used to generate a yaml document from in-memory structs
  1316. /// and vectors.
  1317. ///
  1318. class Output : public IO {
  1319. public:
  1320. Output(raw_ostream &, void *Ctxt = nullptr, int WrapColumn = 70);
  1321. ~Output() override;
  1322. /// Set whether or not to output optional values which are equal
  1323. /// to the default value. By default, when outputting if you attempt
  1324. /// to write a value that is equal to the default, the value gets ignored.
  1325. /// Sometimes, it is useful to be able to see these in the resulting YAML
  1326. /// anyway.
  1327. void setWriteDefaultValues(bool Write) { WriteDefaultValues = Write; }
  1328. bool outputting() const override;
  1329. bool mapTag(StringRef, bool) override;
  1330. void beginMapping() override;
  1331. void endMapping() override;
  1332. bool preflightKey(const char *key, bool, bool, bool &, void *&) override;
  1333. void postflightKey(void *) override;
  1334. std::vector<StringRef> keys() override;
  1335. void beginFlowMapping() override;
  1336. void endFlowMapping() override;
  1337. unsigned beginSequence() override;
  1338. void endSequence() override;
  1339. bool preflightElement(unsigned, void *&) override;
  1340. void postflightElement(void *) override;
  1341. unsigned beginFlowSequence() override;
  1342. bool preflightFlowElement(unsigned, void *&) override;
  1343. void postflightFlowElement(void *) override;
  1344. void endFlowSequence() override;
  1345. void beginEnumScalar() override;
  1346. bool matchEnumScalar(const char*, bool) override;
  1347. bool matchEnumFallback() override;
  1348. void endEnumScalar() override;
  1349. bool beginBitSetScalar(bool &) override;
  1350. bool bitSetMatch(const char *, bool ) override;
  1351. void endBitSetScalar() override;
  1352. void scalarString(StringRef &, QuotingType) override;
  1353. void blockScalarString(StringRef &) override;
  1354. void scalarTag(std::string &) override;
  1355. NodeKind getNodeKind() override;
  1356. void setError(const Twine &message) override;
  1357. bool canElideEmptySequence() override;
  1358. // These are only used by operator<<. They could be private
  1359. // if that templated operator could be made a friend.
  1360. void beginDocuments();
  1361. bool preflightDocument(unsigned);
  1362. void postflightDocument();
  1363. void endDocuments();
  1364. private:
  1365. void output(StringRef s);
  1366. void outputUpToEndOfLine(StringRef s);
  1367. void newLineCheck(bool EmptySequence = false);
  1368. void outputNewLine();
  1369. void paddedKey(StringRef key);
  1370. void flowKey(StringRef Key);
  1371. enum InState {
  1372. inSeqFirstElement,
  1373. inSeqOtherElement,
  1374. inFlowSeqFirstElement,
  1375. inFlowSeqOtherElement,
  1376. inMapFirstKey,
  1377. inMapOtherKey,
  1378. inFlowMapFirstKey,
  1379. inFlowMapOtherKey
  1380. };
  1381. static bool inSeqAnyElement(InState State);
  1382. static bool inFlowSeqAnyElement(InState State);
  1383. static bool inMapAnyKey(InState State);
  1384. static bool inFlowMapAnyKey(InState State);
  1385. raw_ostream &Out;
  1386. int WrapColumn;
  1387. SmallVector<InState, 8> StateStack;
  1388. int Column = 0;
  1389. int ColumnAtFlowStart = 0;
  1390. int ColumnAtMapFlowStart = 0;
  1391. bool NeedBitValueComma = false;
  1392. bool NeedFlowSequenceComma = false;
  1393. bool EnumerationMatchFound = false;
  1394. bool WriteDefaultValues = false;
  1395. StringRef Padding;
  1396. StringRef PaddingBeforeContainer;
  1397. };
  1398. template <typename T, typename Context>
  1399. void IO::processKeyWithDefault(const char *Key, Optional<T> &Val,
  1400. const Optional<T> &DefaultValue, bool Required,
  1401. Context &Ctx) {
  1402. assert(DefaultValue.hasValue() == false &&
  1403. "Optional<T> shouldn't have a value!");
  1404. void *SaveInfo;
  1405. bool UseDefault = true;
  1406. const bool sameAsDefault = outputting() && !Val.hasValue();
  1407. if (!outputting() && !Val.hasValue())
  1408. Val = T();
  1409. if (Val.hasValue() &&
  1410. this->preflightKey(Key, Required, sameAsDefault, UseDefault, SaveInfo)) {
  1411. // When reading an Optional<X> key from a YAML description, we allow the
  1412. // special "<none>" value, which can be used to specify that no value was
  1413. // requested, i.e. the DefaultValue will be assigned. The DefaultValue is
  1414. // usually None.
  1415. bool IsNone = false;
  1416. if (!outputting())
  1417. if (const auto *Node = dyn_cast<ScalarNode>(((Input *)this)->getCurrentNode()))
  1418. // We use rtrim to ignore possible white spaces that might exist when a
  1419. // comment is present on the same line.
  1420. IsNone = Node->getRawValue().rtrim(' ') == "<none>";
  1421. if (IsNone)
  1422. Val = DefaultValue;
  1423. else
  1424. yamlize(*this, Val.getValue(), Required, Ctx);
  1425. this->postflightKey(SaveInfo);
  1426. } else {
  1427. if (UseDefault)
  1428. Val = DefaultValue;
  1429. }
  1430. }
  1431. /// YAML I/O does conversion based on types. But often native data types
  1432. /// are just a typedef of built in intergral types (e.g. int). But the C++
  1433. /// type matching system sees through the typedef and all the typedefed types
  1434. /// look like a built in type. This will cause the generic YAML I/O conversion
  1435. /// to be used. To provide better control over the YAML conversion, you can
  1436. /// use this macro instead of typedef. It will create a class with one field
  1437. /// and automatic conversion operators to and from the base type.
  1438. /// Based on BOOST_STRONG_TYPEDEF
  1439. #define LLVM_YAML_STRONG_TYPEDEF(_base, _type) \
  1440. struct _type { \
  1441. _type() = default; \
  1442. _type(const _base v) : value(v) {} \
  1443. _type(const _type &v) = default; \
  1444. _type &operator=(const _type &rhs) = default; \
  1445. _type &operator=(const _base &rhs) { value = rhs; return *this; } \
  1446. operator const _base & () const { return value; } \
  1447. bool operator==(const _type &rhs) const { return value == rhs.value; } \
  1448. bool operator==(const _base &rhs) const { return value == rhs; } \
  1449. bool operator<(const _type &rhs) const { return value < rhs.value; } \
  1450. _base value; \
  1451. using BaseType = _base; \
  1452. };
  1453. ///
  1454. /// Use these types instead of uintXX_t in any mapping to have
  1455. /// its yaml output formatted as hexadecimal.
  1456. ///
  1457. LLVM_YAML_STRONG_TYPEDEF(uint8_t, Hex8)
  1458. LLVM_YAML_STRONG_TYPEDEF(uint16_t, Hex16)
  1459. LLVM_YAML_STRONG_TYPEDEF(uint32_t, Hex32)
  1460. LLVM_YAML_STRONG_TYPEDEF(uint64_t, Hex64)
  1461. template<>
  1462. struct ScalarTraits<Hex8> {
  1463. static void output(const Hex8 &, void *, raw_ostream &);
  1464. static StringRef input(StringRef, void *, Hex8 &);
  1465. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1466. };
  1467. template<>
  1468. struct ScalarTraits<Hex16> {
  1469. static void output(const Hex16 &, void *, raw_ostream &);
  1470. static StringRef input(StringRef, void *, Hex16 &);
  1471. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1472. };
  1473. template<>
  1474. struct ScalarTraits<Hex32> {
  1475. static void output(const Hex32 &, void *, raw_ostream &);
  1476. static StringRef input(StringRef, void *, Hex32 &);
  1477. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1478. };
  1479. template<>
  1480. struct ScalarTraits<Hex64> {
  1481. static void output(const Hex64 &, void *, raw_ostream &);
  1482. static StringRef input(StringRef, void *, Hex64 &);
  1483. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1484. };
  1485. template <> struct ScalarTraits<VersionTuple> {
  1486. static void output(const VersionTuple &Value, void *, llvm::raw_ostream &Out);
  1487. static StringRef input(StringRef, void *, VersionTuple &);
  1488. static QuotingType mustQuote(StringRef) { return QuotingType::None; }
  1489. };
  1490. // Define non-member operator>> so that Input can stream in a document list.
  1491. template <typename T>
  1492. inline std::enable_if_t<has_DocumentListTraits<T>::value, Input &>
  1493. operator>>(Input &yin, T &docList) {
  1494. int i = 0;
  1495. EmptyContext Ctx;
  1496. while ( yin.setCurrentDocument() ) {
  1497. yamlize(yin, DocumentListTraits<T>::element(yin, docList, i), true, Ctx);
  1498. if ( yin.error() )
  1499. return yin;
  1500. yin.nextDocument();
  1501. ++i;
  1502. }
  1503. return yin;
  1504. }
  1505. // Define non-member operator>> so that Input can stream in a map as a document.
  1506. template <typename T>
  1507. inline std::enable_if_t<has_MappingTraits<T, EmptyContext>::value, Input &>
  1508. operator>>(Input &yin, T &docMap) {
  1509. EmptyContext Ctx;
  1510. yin.setCurrentDocument();
  1511. yamlize(yin, docMap, true, Ctx);
  1512. return yin;
  1513. }
  1514. // Define non-member operator>> so that Input can stream in a sequence as
  1515. // a document.
  1516. template <typename T>
  1517. inline std::enable_if_t<has_SequenceTraits<T>::value, Input &>
  1518. operator>>(Input &yin, T &docSeq) {
  1519. EmptyContext Ctx;
  1520. if (yin.setCurrentDocument())
  1521. yamlize(yin, docSeq, true, Ctx);
  1522. return yin;
  1523. }
  1524. // Define non-member operator>> so that Input can stream in a block scalar.
  1525. template <typename T>
  1526. inline std::enable_if_t<has_BlockScalarTraits<T>::value, Input &>
  1527. operator>>(Input &In, T &Val) {
  1528. EmptyContext Ctx;
  1529. if (In.setCurrentDocument())
  1530. yamlize(In, Val, true, Ctx);
  1531. return In;
  1532. }
  1533. // Define non-member operator>> so that Input can stream in a string map.
  1534. template <typename T>
  1535. inline std::enable_if_t<has_CustomMappingTraits<T>::value, Input &>
  1536. operator>>(Input &In, T &Val) {
  1537. EmptyContext Ctx;
  1538. if (In.setCurrentDocument())
  1539. yamlize(In, Val, true, Ctx);
  1540. return In;
  1541. }
  1542. // Define non-member operator>> so that Input can stream in a polymorphic type.
  1543. template <typename T>
  1544. inline std::enable_if_t<has_PolymorphicTraits<T>::value, Input &>
  1545. operator>>(Input &In, T &Val) {
  1546. EmptyContext Ctx;
  1547. if (In.setCurrentDocument())
  1548. yamlize(In, Val, true, Ctx);
  1549. return In;
  1550. }
  1551. // Provide better error message about types missing a trait specialization
  1552. template <typename T>
  1553. inline std::enable_if_t<missingTraits<T, EmptyContext>::value, Input &>
  1554. operator>>(Input &yin, T &docSeq) {
  1555. char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
  1556. return yin;
  1557. }
  1558. // Define non-member operator<< so that Output can stream out document list.
  1559. template <typename T>
  1560. inline std::enable_if_t<has_DocumentListTraits<T>::value, Output &>
  1561. operator<<(Output &yout, T &docList) {
  1562. EmptyContext Ctx;
  1563. yout.beginDocuments();
  1564. const size_t count = DocumentListTraits<T>::size(yout, docList);
  1565. for(size_t i=0; i < count; ++i) {
  1566. if ( yout.preflightDocument(i) ) {
  1567. yamlize(yout, DocumentListTraits<T>::element(yout, docList, i), true,
  1568. Ctx);
  1569. yout.postflightDocument();
  1570. }
  1571. }
  1572. yout.endDocuments();
  1573. return yout;
  1574. }
  1575. // Define non-member operator<< so that Output can stream out a map.
  1576. template <typename T>
  1577. inline std::enable_if_t<has_MappingTraits<T, EmptyContext>::value, Output &>
  1578. operator<<(Output &yout, T &map) {
  1579. EmptyContext Ctx;
  1580. yout.beginDocuments();
  1581. if ( yout.preflightDocument(0) ) {
  1582. yamlize(yout, map, true, Ctx);
  1583. yout.postflightDocument();
  1584. }
  1585. yout.endDocuments();
  1586. return yout;
  1587. }
  1588. // Define non-member operator<< so that Output can stream out a sequence.
  1589. template <typename T>
  1590. inline std::enable_if_t<has_SequenceTraits<T>::value, Output &>
  1591. operator<<(Output &yout, T &seq) {
  1592. EmptyContext Ctx;
  1593. yout.beginDocuments();
  1594. if ( yout.preflightDocument(0) ) {
  1595. yamlize(yout, seq, true, Ctx);
  1596. yout.postflightDocument();
  1597. }
  1598. yout.endDocuments();
  1599. return yout;
  1600. }
  1601. // Define non-member operator<< so that Output can stream out a block scalar.
  1602. template <typename T>
  1603. inline std::enable_if_t<has_BlockScalarTraits<T>::value, Output &>
  1604. operator<<(Output &Out, T &Val) {
  1605. EmptyContext Ctx;
  1606. Out.beginDocuments();
  1607. if (Out.preflightDocument(0)) {
  1608. yamlize(Out, Val, true, Ctx);
  1609. Out.postflightDocument();
  1610. }
  1611. Out.endDocuments();
  1612. return Out;
  1613. }
  1614. // Define non-member operator<< so that Output can stream out a string map.
  1615. template <typename T>
  1616. inline std::enable_if_t<has_CustomMappingTraits<T>::value, Output &>
  1617. operator<<(Output &Out, T &Val) {
  1618. EmptyContext Ctx;
  1619. Out.beginDocuments();
  1620. if (Out.preflightDocument(0)) {
  1621. yamlize(Out, Val, true, Ctx);
  1622. Out.postflightDocument();
  1623. }
  1624. Out.endDocuments();
  1625. return Out;
  1626. }
  1627. // Define non-member operator<< so that Output can stream out a polymorphic
  1628. // type.
  1629. template <typename T>
  1630. inline std::enable_if_t<has_PolymorphicTraits<T>::value, Output &>
  1631. operator<<(Output &Out, T &Val) {
  1632. EmptyContext Ctx;
  1633. Out.beginDocuments();
  1634. if (Out.preflightDocument(0)) {
  1635. // FIXME: The parser does not support explicit documents terminated with a
  1636. // plain scalar; the end-marker is included as part of the scalar token.
  1637. assert(PolymorphicTraits<T>::getKind(Val) != NodeKind::Scalar && "plain scalar documents are not supported");
  1638. yamlize(Out, Val, true, Ctx);
  1639. Out.postflightDocument();
  1640. }
  1641. Out.endDocuments();
  1642. return Out;
  1643. }
  1644. // Provide better error message about types missing a trait specialization
  1645. template <typename T>
  1646. inline std::enable_if_t<missingTraits<T, EmptyContext>::value, Output &>
  1647. operator<<(Output &yout, T &seq) {
  1648. char missing_yaml_trait_for_type[sizeof(MissingTrait<T>)];
  1649. return yout;
  1650. }
  1651. template <bool B> struct IsFlowSequenceBase {};
  1652. template <> struct IsFlowSequenceBase<true> { static const bool flow = true; };
  1653. template <typename T, bool Flow>
  1654. struct SequenceTraitsImpl : IsFlowSequenceBase<Flow> {
  1655. private:
  1656. using type = typename T::value_type;
  1657. public:
  1658. static size_t size(IO &io, T &seq) { return seq.size(); }
  1659. static type &element(IO &io, T &seq, size_t index) {
  1660. if (index >= seq.size())
  1661. seq.resize(index + 1);
  1662. return seq[index];
  1663. }
  1664. };
  1665. // Simple helper to check an expression can be used as a bool-valued template
  1666. // argument.
  1667. template <bool> struct CheckIsBool { static const bool value = true; };
  1668. // If T has SequenceElementTraits, then vector<T> and SmallVector<T, N> have
  1669. // SequenceTraits that do the obvious thing.
  1670. template <typename T>
  1671. struct SequenceTraits<
  1672. std::vector<T>,
  1673. std::enable_if_t<CheckIsBool<SequenceElementTraits<T>::flow>::value>>
  1674. : SequenceTraitsImpl<std::vector<T>, SequenceElementTraits<T>::flow> {};
  1675. template <typename T, unsigned N>
  1676. struct SequenceTraits<
  1677. SmallVector<T, N>,
  1678. std::enable_if_t<CheckIsBool<SequenceElementTraits<T>::flow>::value>>
  1679. : SequenceTraitsImpl<SmallVector<T, N>, SequenceElementTraits<T>::flow> {};
  1680. template <typename T>
  1681. struct SequenceTraits<
  1682. SmallVectorImpl<T>,
  1683. std::enable_if_t<CheckIsBool<SequenceElementTraits<T>::flow>::value>>
  1684. : SequenceTraitsImpl<SmallVectorImpl<T>, SequenceElementTraits<T>::flow> {};
  1685. // Sequences of fundamental types use flow formatting.
  1686. template <typename T>
  1687. struct SequenceElementTraits<T,
  1688. std::enable_if_t<std::is_fundamental<T>::value>> {
  1689. static const bool flow = true;
  1690. };
  1691. // Sequences of strings use block formatting.
  1692. template<> struct SequenceElementTraits<std::string> {
  1693. static const bool flow = false;
  1694. };
  1695. template<> struct SequenceElementTraits<StringRef> {
  1696. static const bool flow = false;
  1697. };
  1698. template<> struct SequenceElementTraits<std::pair<std::string, std::string>> {
  1699. static const bool flow = false;
  1700. };
  1701. /// Implementation of CustomMappingTraits for std::map<std::string, T>.
  1702. template <typename T> struct StdMapStringCustomMappingTraitsImpl {
  1703. using map_type = std::map<std::string, T>;
  1704. static void inputOne(IO &io, StringRef key, map_type &v) {
  1705. io.mapRequired(key.str().c_str(), v[std::string(key)]);
  1706. }
  1707. static void output(IO &io, map_type &v) {
  1708. for (auto &p : v)
  1709. io.mapRequired(p.first.c_str(), p.second);
  1710. }
  1711. };
  1712. } // end namespace yaml
  1713. } // end namespace llvm
  1714. #define LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(TYPE, FLOW) \
  1715. namespace llvm { \
  1716. namespace yaml { \
  1717. static_assert( \
  1718. !std::is_fundamental<TYPE>::value && \
  1719. !std::is_same<TYPE, std::string>::value && \
  1720. !std::is_same<TYPE, llvm::StringRef>::value, \
  1721. "only use LLVM_YAML_IS_SEQUENCE_VECTOR for types you control"); \
  1722. template <> struct SequenceElementTraits<TYPE> { \
  1723. static const bool flow = FLOW; \
  1724. }; \
  1725. } \
  1726. }
  1727. /// Utility for declaring that a std::vector of a particular type
  1728. /// should be considered a YAML sequence.
  1729. #define LLVM_YAML_IS_SEQUENCE_VECTOR(type) \
  1730. LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, false)
  1731. /// Utility for declaring that a std::vector of a particular type
  1732. /// should be considered a YAML flow sequence.
  1733. #define LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(type) \
  1734. LLVM_YAML_IS_SEQUENCE_VECTOR_IMPL(type, true)
  1735. #define LLVM_YAML_DECLARE_MAPPING_TRAITS(Type) \
  1736. namespace llvm { \
  1737. namespace yaml { \
  1738. template <> struct MappingTraits<Type> { \
  1739. static void mapping(IO &IO, Type &Obj); \
  1740. }; \
  1741. } \
  1742. }
  1743. #define LLVM_YAML_DECLARE_ENUM_TRAITS(Type) \
  1744. namespace llvm { \
  1745. namespace yaml { \
  1746. template <> struct ScalarEnumerationTraits<Type> { \
  1747. static void enumeration(IO &io, Type &Value); \
  1748. }; \
  1749. } \
  1750. }
  1751. #define LLVM_YAML_DECLARE_BITSET_TRAITS(Type) \
  1752. namespace llvm { \
  1753. namespace yaml { \
  1754. template <> struct ScalarBitSetTraits<Type> { \
  1755. static void bitset(IO &IO, Type &Options); \
  1756. }; \
  1757. } \
  1758. }
  1759. #define LLVM_YAML_DECLARE_SCALAR_TRAITS(Type, MustQuote) \
  1760. namespace llvm { \
  1761. namespace yaml { \
  1762. template <> struct ScalarTraits<Type> { \
  1763. static void output(const Type &Value, void *ctx, raw_ostream &Out); \
  1764. static StringRef input(StringRef Scalar, void *ctxt, Type &Value); \
  1765. static QuotingType mustQuote(StringRef) { return MustQuote; } \
  1766. }; \
  1767. } \
  1768. }
  1769. /// Utility for declaring that a std::vector of a particular type
  1770. /// should be considered a YAML document list.
  1771. #define LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(_type) \
  1772. namespace llvm { \
  1773. namespace yaml { \
  1774. template <unsigned N> \
  1775. struct DocumentListTraits<SmallVector<_type, N>> \
  1776. : public SequenceTraitsImpl<SmallVector<_type, N>, false> {}; \
  1777. template <> \
  1778. struct DocumentListTraits<std::vector<_type>> \
  1779. : public SequenceTraitsImpl<std::vector<_type>, false> {}; \
  1780. } \
  1781. }
  1782. /// Utility for declaring that std::map<std::string, _type> should be considered
  1783. /// a YAML map.
  1784. #define LLVM_YAML_IS_STRING_MAP(_type) \
  1785. namespace llvm { \
  1786. namespace yaml { \
  1787. template <> \
  1788. struct CustomMappingTraits<std::map<std::string, _type>> \
  1789. : public StdMapStringCustomMappingTraitsImpl<_type> {}; \
  1790. } \
  1791. }
  1792. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::Hex64)
  1793. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::Hex32)
  1794. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::Hex16)
  1795. LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(llvm::yaml::Hex8)
  1796. #endif // LLVM_SUPPORT_YAMLTRAITS_H
  1797. #ifdef __GNUC__
  1798. #pragma GCC diagnostic pop
  1799. #endif