YAMLParser.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. //===- YAMLParser.h - Simple YAML parser ------------------------*- 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. //
  9. // This is a YAML 1.2 parser.
  10. //
  11. // See http://www.yaml.org/spec/1.2/spec.html for the full standard.
  12. //
  13. // This currently does not implement the following:
  14. // * Multi-line literal folding.
  15. // * Tag resolution.
  16. // * UTF-16.
  17. // * BOMs anywhere other than the first Unicode scalar value in the file.
  18. //
  19. // The most important class here is Stream. This represents a YAML stream with
  20. // 0, 1, or many documents.
  21. //
  22. // SourceMgr sm;
  23. // StringRef input = getInput();
  24. // yaml::Stream stream(input, sm);
  25. //
  26. // for (yaml::document_iterator di = stream.begin(), de = stream.end();
  27. // di != de; ++di) {
  28. // yaml::Node *n = di->getRoot();
  29. // if (n) {
  30. // // Do something with n...
  31. // } else
  32. // break;
  33. // }
  34. //
  35. //===----------------------------------------------------------------------===//
  36. #ifndef LLVM_SUPPORT_YAMLPARSER_H
  37. #define LLVM_SUPPORT_YAMLPARSER_H
  38. #include "llvm/ADT/StringRef.h"
  39. #include "llvm/Support/Allocator.h"
  40. #include "llvm/Support/SMLoc.h"
  41. #include "llvm/Support/SourceMgr.h"
  42. #include <cassert>
  43. #include <cstddef>
  44. #include <iterator>
  45. #include <map>
  46. #include <memory>
  47. #include <string>
  48. #include <system_error>
  49. namespace llvm {
  50. class MemoryBufferRef;
  51. class raw_ostream;
  52. class Twine;
  53. namespace yaml {
  54. class Document;
  55. class document_iterator;
  56. class Node;
  57. class Scanner;
  58. struct Token;
  59. /// Dump all the tokens in this stream to OS.
  60. /// \returns true if there was an error, false otherwise.
  61. bool dumpTokens(StringRef Input, raw_ostream &);
  62. /// Scans all tokens in input without outputting anything. This is used
  63. /// for benchmarking the tokenizer.
  64. /// \returns true if there was an error, false otherwise.
  65. bool scanTokens(StringRef Input);
  66. /// Escape \a Input for a double quoted scalar; if \p EscapePrintable
  67. /// is true, all UTF8 sequences will be escaped, if \p EscapePrintable is
  68. /// false, those UTF8 sequences encoding printable unicode scalars will not be
  69. /// escaped, but emitted verbatim.
  70. std::string escape(StringRef Input, bool EscapePrintable = true);
  71. /// Parse \p S as a bool according to https://yaml.org/type/bool.html.
  72. llvm::Optional<bool> parseBool(StringRef S);
  73. /// This class represents a YAML stream potentially containing multiple
  74. /// documents.
  75. class Stream {
  76. public:
  77. /// This keeps a reference to the string referenced by \p Input.
  78. Stream(StringRef Input, SourceMgr &, bool ShowColors = true,
  79. std::error_code *EC = nullptr);
  80. Stream(MemoryBufferRef InputBuffer, SourceMgr &, bool ShowColors = true,
  81. std::error_code *EC = nullptr);
  82. ~Stream();
  83. document_iterator begin();
  84. document_iterator end();
  85. void skip();
  86. bool failed();
  87. bool validate() {
  88. skip();
  89. return !failed();
  90. }
  91. void printError(Node *N, const Twine &Msg,
  92. SourceMgr::DiagKind Kind = SourceMgr::DK_Error);
  93. void printError(const SMRange &Range, const Twine &Msg,
  94. SourceMgr::DiagKind Kind = SourceMgr::DK_Error);
  95. private:
  96. friend class Document;
  97. std::unique_ptr<Scanner> scanner;
  98. std::unique_ptr<Document> CurrentDoc;
  99. };
  100. /// Abstract base class for all Nodes.
  101. class Node {
  102. virtual void anchor();
  103. public:
  104. enum NodeKind {
  105. NK_Null,
  106. NK_Scalar,
  107. NK_BlockScalar,
  108. NK_KeyValue,
  109. NK_Mapping,
  110. NK_Sequence,
  111. NK_Alias
  112. };
  113. Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
  114. StringRef Tag);
  115. // It's not safe to copy YAML nodes; the document is streamed and the position
  116. // is part of the state.
  117. Node(const Node &) = delete;
  118. void operator=(const Node &) = delete;
  119. void *operator new(size_t Size, BumpPtrAllocator &Alloc,
  120. size_t Alignment = 16) noexcept {
  121. return Alloc.Allocate(Size, Alignment);
  122. }
  123. void operator delete(void *Ptr, BumpPtrAllocator &Alloc,
  124. size_t Size) noexcept {
  125. Alloc.Deallocate(Ptr, Size, 0);
  126. }
  127. void operator delete(void *) noexcept = delete;
  128. /// Get the value of the anchor attached to this node. If it does not
  129. /// have one, getAnchor().size() will be 0.
  130. StringRef getAnchor() const { return Anchor; }
  131. /// Get the tag as it was written in the document. This does not
  132. /// perform tag resolution.
  133. StringRef getRawTag() const { return Tag; }
  134. /// Get the verbatium tag for a given Node. This performs tag resoluton
  135. /// and substitution.
  136. std::string getVerbatimTag() const;
  137. SMRange getSourceRange() const { return SourceRange; }
  138. void setSourceRange(SMRange SR) { SourceRange = SR; }
  139. // These functions forward to Document and Scanner.
  140. Token &peekNext();
  141. Token getNext();
  142. Node *parseBlockNode();
  143. BumpPtrAllocator &getAllocator();
  144. void setError(const Twine &Message, Token &Location) const;
  145. bool failed() const;
  146. virtual void skip() {}
  147. unsigned int getType() const { return TypeID; }
  148. protected:
  149. std::unique_ptr<Document> &Doc;
  150. SMRange SourceRange;
  151. ~Node() = default;
  152. private:
  153. unsigned int TypeID;
  154. StringRef Anchor;
  155. /// The tag as typed in the document.
  156. StringRef Tag;
  157. };
  158. /// A null value.
  159. ///
  160. /// Example:
  161. /// !!null null
  162. class NullNode final : public Node {
  163. void anchor() override;
  164. public:
  165. NullNode(std::unique_ptr<Document> &D)
  166. : Node(NK_Null, D, StringRef(), StringRef()) {}
  167. static bool classof(const Node *N) { return N->getType() == NK_Null; }
  168. };
  169. /// A scalar node is an opaque datum that can be presented as a
  170. /// series of zero or more Unicode scalar values.
  171. ///
  172. /// Example:
  173. /// Adena
  174. class ScalarNode final : public Node {
  175. void anchor() override;
  176. public:
  177. ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
  178. StringRef Val)
  179. : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
  180. SMLoc Start = SMLoc::getFromPointer(Val.begin());
  181. SMLoc End = SMLoc::getFromPointer(Val.end());
  182. SourceRange = SMRange(Start, End);
  183. }
  184. // Return Value without any escaping or folding or other fun YAML stuff. This
  185. // is the exact bytes that are contained in the file (after conversion to
  186. // utf8).
  187. StringRef getRawValue() const { return Value; }
  188. /// Gets the value of this node as a StringRef.
  189. ///
  190. /// \param Storage is used to store the content of the returned StringRef if
  191. /// it requires any modification from how it appeared in the source.
  192. /// This happens with escaped characters and multi-line literals.
  193. StringRef getValue(SmallVectorImpl<char> &Storage) const;
  194. static bool classof(const Node *N) {
  195. return N->getType() == NK_Scalar;
  196. }
  197. private:
  198. StringRef Value;
  199. StringRef unescapeDoubleQuoted(StringRef UnquotedValue,
  200. StringRef::size_type Start,
  201. SmallVectorImpl<char> &Storage) const;
  202. };
  203. /// A block scalar node is an opaque datum that can be presented as a
  204. /// series of zero or more Unicode scalar values.
  205. ///
  206. /// Example:
  207. /// |
  208. /// Hello
  209. /// World
  210. class BlockScalarNode final : public Node {
  211. void anchor() override;
  212. public:
  213. BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
  214. StringRef Value, StringRef RawVal)
  215. : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) {
  216. SMLoc Start = SMLoc::getFromPointer(RawVal.begin());
  217. SMLoc End = SMLoc::getFromPointer(RawVal.end());
  218. SourceRange = SMRange(Start, End);
  219. }
  220. /// Gets the value of this node as a StringRef.
  221. StringRef getValue() const { return Value; }
  222. static bool classof(const Node *N) {
  223. return N->getType() == NK_BlockScalar;
  224. }
  225. private:
  226. StringRef Value;
  227. };
  228. /// A key and value pair. While not technically a Node under the YAML
  229. /// representation graph, it is easier to treat them this way.
  230. ///
  231. /// TODO: Consider making this not a child of Node.
  232. ///
  233. /// Example:
  234. /// Section: .text
  235. class KeyValueNode final : public Node {
  236. void anchor() override;
  237. public:
  238. KeyValueNode(std::unique_ptr<Document> &D)
  239. : Node(NK_KeyValue, D, StringRef(), StringRef()) {}
  240. /// Parse and return the key.
  241. ///
  242. /// This may be called multiple times.
  243. ///
  244. /// \returns The key, or nullptr if failed() == true.
  245. Node *getKey();
  246. /// Parse and return the value.
  247. ///
  248. /// This may be called multiple times.
  249. ///
  250. /// \returns The value, or nullptr if failed() == true.
  251. Node *getValue();
  252. void skip() override {
  253. if (Node *Key = getKey()) {
  254. Key->skip();
  255. if (Node *Val = getValue())
  256. Val->skip();
  257. }
  258. }
  259. static bool classof(const Node *N) {
  260. return N->getType() == NK_KeyValue;
  261. }
  262. private:
  263. Node *Key = nullptr;
  264. Node *Value = nullptr;
  265. };
  266. /// This is an iterator abstraction over YAML collections shared by both
  267. /// sequences and maps.
  268. ///
  269. /// BaseT must have a ValueT* member named CurrentEntry and a member function
  270. /// increment() which must set CurrentEntry to 0 to create an end iterator.
  271. template <class BaseT, class ValueT> class basic_collection_iterator {
  272. public:
  273. using iterator_category = std::input_iterator_tag;
  274. using value_type = ValueT;
  275. using difference_type = std::ptrdiff_t;
  276. using pointer = value_type *;
  277. using reference = value_type &;
  278. basic_collection_iterator() = default;
  279. basic_collection_iterator(BaseT *B) : Base(B) {}
  280. ValueT *operator->() const {
  281. assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
  282. return Base->CurrentEntry;
  283. }
  284. ValueT &operator*() const {
  285. assert(Base && Base->CurrentEntry &&
  286. "Attempted to dereference end iterator!");
  287. return *Base->CurrentEntry;
  288. }
  289. operator ValueT *() const {
  290. assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
  291. return Base->CurrentEntry;
  292. }
  293. /// Note on EqualityComparable:
  294. ///
  295. /// The iterator is not re-entrant,
  296. /// it is meant to be used for parsing YAML on-demand
  297. /// Once iteration started - it can point only to one entry at a time
  298. /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
  299. /// iff Base and Other.Base are equal.
  300. bool operator==(const basic_collection_iterator &Other) const {
  301. if (Base && (Base == Other.Base)) {
  302. assert((Base->CurrentEntry == Other.Base->CurrentEntry)
  303. && "Equal Bases expected to point to equal Entries");
  304. }
  305. return Base == Other.Base;
  306. }
  307. bool operator!=(const basic_collection_iterator &Other) const {
  308. return !(Base == Other.Base);
  309. }
  310. basic_collection_iterator &operator++() {
  311. assert(Base && "Attempted to advance iterator past end!");
  312. Base->increment();
  313. // Create an end iterator.
  314. if (!Base->CurrentEntry)
  315. Base = nullptr;
  316. return *this;
  317. }
  318. private:
  319. BaseT *Base = nullptr;
  320. };
  321. // The following two templates are used for both MappingNode and Sequence Node.
  322. template <class CollectionType>
  323. typename CollectionType::iterator begin(CollectionType &C) {
  324. assert(C.IsAtBeginning && "You may only iterate over a collection once!");
  325. C.IsAtBeginning = false;
  326. typename CollectionType::iterator ret(&C);
  327. ++ret;
  328. return ret;
  329. }
  330. template <class CollectionType> void skip(CollectionType &C) {
  331. // TODO: support skipping from the middle of a parsed collection ;/
  332. assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
  333. if (C.IsAtBeginning)
  334. for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
  335. ++i)
  336. i->skip();
  337. }
  338. /// Represents a YAML map created from either a block map for a flow map.
  339. ///
  340. /// This parses the YAML stream as increment() is called.
  341. ///
  342. /// Example:
  343. /// Name: _main
  344. /// Scope: Global
  345. class MappingNode final : public Node {
  346. void anchor() override;
  347. public:
  348. enum MappingType {
  349. MT_Block,
  350. MT_Flow,
  351. MT_Inline ///< An inline mapping node is used for "[key: value]".
  352. };
  353. MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
  354. MappingType MT)
  355. : Node(NK_Mapping, D, Anchor, Tag), Type(MT) {}
  356. friend class basic_collection_iterator<MappingNode, KeyValueNode>;
  357. using iterator = basic_collection_iterator<MappingNode, KeyValueNode>;
  358. template <class T> friend typename T::iterator yaml::begin(T &);
  359. template <class T> friend void yaml::skip(T &);
  360. iterator begin() { return yaml::begin(*this); }
  361. iterator end() { return iterator(); }
  362. void skip() override { yaml::skip(*this); }
  363. static bool classof(const Node *N) {
  364. return N->getType() == NK_Mapping;
  365. }
  366. private:
  367. MappingType Type;
  368. bool IsAtBeginning = true;
  369. bool IsAtEnd = false;
  370. KeyValueNode *CurrentEntry = nullptr;
  371. void increment();
  372. };
  373. /// Represents a YAML sequence created from either a block sequence for a
  374. /// flow sequence.
  375. ///
  376. /// This parses the YAML stream as increment() is called.
  377. ///
  378. /// Example:
  379. /// - Hello
  380. /// - World
  381. class SequenceNode final : public Node {
  382. void anchor() override;
  383. public:
  384. enum SequenceType {
  385. ST_Block,
  386. ST_Flow,
  387. // Use for:
  388. //
  389. // key:
  390. // - val1
  391. // - val2
  392. //
  393. // As a BlockMappingEntry and BlockEnd are not created in this case.
  394. ST_Indentless
  395. };
  396. SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
  397. SequenceType ST)
  398. : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST) {}
  399. friend class basic_collection_iterator<SequenceNode, Node>;
  400. using iterator = basic_collection_iterator<SequenceNode, Node>;
  401. template <class T> friend typename T::iterator yaml::begin(T &);
  402. template <class T> friend void yaml::skip(T &);
  403. void increment();
  404. iterator begin() { return yaml::begin(*this); }
  405. iterator end() { return iterator(); }
  406. void skip() override { yaml::skip(*this); }
  407. static bool classof(const Node *N) {
  408. return N->getType() == NK_Sequence;
  409. }
  410. private:
  411. SequenceType SeqType;
  412. bool IsAtBeginning = true;
  413. bool IsAtEnd = false;
  414. bool WasPreviousTokenFlowEntry = true; // Start with an imaginary ','.
  415. Node *CurrentEntry = nullptr;
  416. };
  417. /// Represents an alias to a Node with an anchor.
  418. ///
  419. /// Example:
  420. /// *AnchorName
  421. class AliasNode final : public Node {
  422. void anchor() override;
  423. public:
  424. AliasNode(std::unique_ptr<Document> &D, StringRef Val)
  425. : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
  426. StringRef getName() const { return Name; }
  427. static bool classof(const Node *N) { return N->getType() == NK_Alias; }
  428. private:
  429. StringRef Name;
  430. };
  431. /// A YAML Stream is a sequence of Documents. A document contains a root
  432. /// node.
  433. class Document {
  434. public:
  435. Document(Stream &ParentStream);
  436. /// Root for parsing a node. Returns a single node.
  437. Node *parseBlockNode();
  438. /// Finish parsing the current document and return true if there are
  439. /// more. Return false otherwise.
  440. bool skip();
  441. /// Parse and return the root level node.
  442. Node *getRoot() {
  443. if (Root)
  444. return Root;
  445. return Root = parseBlockNode();
  446. }
  447. const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
  448. private:
  449. friend class Node;
  450. friend class document_iterator;
  451. /// Stream to read tokens from.
  452. Stream &stream;
  453. /// Used to allocate nodes to. All are destroyed without calling their
  454. /// destructor when the document is destroyed.
  455. BumpPtrAllocator NodeAllocator;
  456. /// The root node. Used to support skipping a partially parsed
  457. /// document.
  458. Node *Root;
  459. /// Maps tag prefixes to their expansion.
  460. std::map<StringRef, StringRef> TagMap;
  461. Token &peekNext();
  462. Token getNext();
  463. void setError(const Twine &Message, Token &Location) const;
  464. bool failed() const;
  465. /// Parse %BLAH directives and return true if any were encountered.
  466. bool parseDirectives();
  467. /// Parse %YAML
  468. void parseYAMLDirective();
  469. /// Parse %TAG
  470. void parseTAGDirective();
  471. /// Consume the next token and error if it is not \a TK.
  472. bool expectToken(int TK);
  473. };
  474. /// Iterator abstraction for Documents over a Stream.
  475. class document_iterator {
  476. public:
  477. document_iterator() = default;
  478. document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
  479. bool operator==(const document_iterator &Other) const {
  480. if (isAtEnd() || Other.isAtEnd())
  481. return isAtEnd() && Other.isAtEnd();
  482. return Doc == Other.Doc;
  483. }
  484. bool operator!=(const document_iterator &Other) const {
  485. return !(*this == Other);
  486. }
  487. document_iterator operator++() {
  488. assert(Doc && "incrementing iterator past the end.");
  489. if (!(*Doc)->skip()) {
  490. Doc->reset(nullptr);
  491. } else {
  492. Stream &S = (*Doc)->stream;
  493. Doc->reset(new Document(S));
  494. }
  495. return *this;
  496. }
  497. Document &operator*() { return *Doc->get(); }
  498. std::unique_ptr<Document> &operator->() { return *Doc; }
  499. private:
  500. bool isAtEnd() const { return !Doc || !*Doc; }
  501. std::unique_ptr<Document> *Doc = nullptr;
  502. };
  503. } // end namespace yaml
  504. } // end namespace llvm
  505. #endif // LLVM_SUPPORT_YAMLPARSER_H