YAMLTraits.h 69 KB

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