1 //===- YAMLParser.h - Simple YAML parser ------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a YAML 1.2 parser.
12 // See http://www.yaml.org/spec/1.2/spec.html for the full standard.
14 // This currently does not implement the following:
15 // * Multi-line literal folding.
18 // * BOMs anywhere other than the first Unicode scalar value in the file.
20 // The most important class here is Stream. This represents a YAML stream with
21 // 0, 1, or many documents.
24 // StringRef input = getInput();
25 // yaml::Stream stream(input, sm);
27 // for (yaml::document_iterator di = stream.begin(), de = stream.end();
29 // yaml::Node *n = di->getRoot();
31 // // Do something with n...
36 //===----------------------------------------------------------------------===//
38 #ifndef LLVM_SUPPORT_YAMLPARSER_H
39 #define LLVM_SUPPORT_YAMLPARSER_H
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/Allocator.h"
43 #include "llvm/Support/SMLoc.h"
50 #include <system_error>
54 class MemoryBufferRef;
62 class document_iterator;
67 /// \brief Dump all the tokens in this stream to OS.
68 /// \returns true if there was an error, false otherwise.
69 bool dumpTokens(StringRef Input, raw_ostream &);
71 /// \brief Scans all tokens in input without outputting anything. This is used
72 /// for benchmarking the tokenizer.
73 /// \returns true if there was an error, false otherwise.
74 bool scanTokens(StringRef Input);
76 /// \brief Escape \a Input for a double quoted scalar.
77 std::string escape(StringRef Input);
79 /// \brief This class represents a YAML stream potentially containing multiple
83 /// \brief This keeps a reference to the string referenced by \p Input.
84 Stream(StringRef Input, SourceMgr &, bool ShowColors = true,
85 std::error_code *EC = nullptr);
87 Stream(MemoryBufferRef InputBuffer, SourceMgr &, bool ShowColors = true,
88 std::error_code *EC = nullptr);
91 document_iterator begin();
92 document_iterator end();
101 void printError(Node *N, const Twine &Msg);
104 friend class Document;
106 std::unique_ptr<Scanner> scanner;
107 std::unique_ptr<Document> CurrentDoc;
110 /// \brief Abstract base class for all Nodes.
112 virtual void anchor();
125 Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
128 void *operator new(size_t Size, BumpPtrAllocator &Alloc,
129 size_t Alignment = 16) noexcept {
130 return Alloc.Allocate(Size, Alignment);
133 void operator delete(void *Ptr, BumpPtrAllocator &Alloc,
134 size_t Size) noexcept {
135 Alloc.Deallocate(Ptr, Size);
138 void operator delete(void *) noexcept = delete;
140 /// \brief Get the value of the anchor attached to this node. If it does not
141 /// have one, getAnchor().size() will be 0.
142 StringRef getAnchor() const { return Anchor; }
144 /// \brief Get the tag as it was written in the document. This does not
145 /// perform tag resolution.
146 StringRef getRawTag() const { return Tag; }
148 /// \brief Get the verbatium tag for a given Node. This performs tag resoluton
149 /// and substitution.
150 std::string getVerbatimTag() const;
152 SMRange getSourceRange() const { return SourceRange; }
153 void setSourceRange(SMRange SR) { SourceRange = SR; }
155 // These functions forward to Document and Scanner.
158 Node *parseBlockNode();
159 BumpPtrAllocator &getAllocator();
160 void setError(const Twine &Message, Token &Location) const;
163 virtual void skip() {}
165 unsigned int getType() const { return TypeID; }
168 std::unique_ptr<Document> &Doc;
176 /// \brief The tag as typed in the document.
180 /// \brief A null value.
184 class NullNode final : public Node {
185 void anchor() override;
188 NullNode(std::unique_ptr<Document> &D)
189 : Node(NK_Null, D, StringRef(), StringRef()) {}
191 static bool classof(const Node *N) { return N->getType() == NK_Null; }
194 /// \brief A scalar node is an opaque datum that can be presented as a
195 /// series of zero or more Unicode scalar values.
199 class ScalarNode final : public Node {
200 void anchor() override;
203 ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
205 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
206 SMLoc Start = SMLoc::getFromPointer(Val.begin());
207 SMLoc End = SMLoc::getFromPointer(Val.end());
208 SourceRange = SMRange(Start, End);
211 // Return Value without any escaping or folding or other fun YAML stuff. This
212 // is the exact bytes that are contained in the file (after conversion to
214 StringRef getRawValue() const { return Value; }
216 /// \brief Gets the value of this node as a StringRef.
218 /// \param Storage is used to store the content of the returned StringRef iff
219 /// it requires any modification from how it appeared in the source.
220 /// This happens with escaped characters and multi-line literals.
221 StringRef getValue(SmallVectorImpl<char> &Storage) const;
223 static bool classof(const Node *N) {
224 return N->getType() == NK_Scalar;
230 StringRef unescapeDoubleQuoted(StringRef UnquotedValue,
231 StringRef::size_type Start,
232 SmallVectorImpl<char> &Storage) const;
235 /// \brief A block scalar node is an opaque datum that can be presented as a
236 /// series of zero or more Unicode scalar values.
242 class BlockScalarNode final : public Node {
243 void anchor() override;
246 BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
247 StringRef Value, StringRef RawVal)
248 : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) {
249 SMLoc Start = SMLoc::getFromPointer(RawVal.begin());
250 SMLoc End = SMLoc::getFromPointer(RawVal.end());
251 SourceRange = SMRange(Start, End);
254 /// \brief Gets the value of this node as a StringRef.
255 StringRef getValue() const { return Value; }
257 static bool classof(const Node *N) {
258 return N->getType() == NK_BlockScalar;
265 /// \brief A key and value pair. While not technically a Node under the YAML
266 /// representation graph, it is easier to treat them this way.
268 /// TODO: Consider making this not a child of Node.
272 class KeyValueNode final : public Node {
273 void anchor() override;
276 KeyValueNode(std::unique_ptr<Document> &D)
277 : Node(NK_KeyValue, D, StringRef(), StringRef()) {}
279 /// \brief Parse and return the key.
281 /// This may be called multiple times.
283 /// \returns The key, or nullptr if failed() == true.
286 /// \brief Parse and return the value.
288 /// This may be called multiple times.
290 /// \returns The value, or nullptr if failed() == true.
293 void skip() override {
294 if (Node *Key = getKey()) {
296 if (Node *Val = getValue())
301 static bool classof(const Node *N) {
302 return N->getType() == NK_KeyValue;
307 Node *Value = nullptr;
310 /// \brief This is an iterator abstraction over YAML collections shared by both
311 /// sequences and maps.
313 /// BaseT must have a ValueT* member named CurrentEntry and a member function
314 /// increment() which must set CurrentEntry to 0 to create an end iterator.
315 template <class BaseT, class ValueT>
316 class basic_collection_iterator
317 : public std::iterator<std::input_iterator_tag, ValueT> {
319 basic_collection_iterator() = default;
320 basic_collection_iterator(BaseT *B) : Base(B) {}
322 ValueT *operator->() const {
323 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
324 return Base->CurrentEntry;
327 ValueT &operator*() const {
328 assert(Base && Base->CurrentEntry &&
329 "Attempted to dereference end iterator!");
330 return *Base->CurrentEntry;
333 operator ValueT *() const {
334 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
335 return Base->CurrentEntry;
338 /// Note on EqualityComparable:
340 /// The iterator is not re-entrant,
341 /// it is meant to be used for parsing YAML on-demand
342 /// Once iteration started - it can point only to one entry at a time
343 /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
344 /// iff Base and Other.Base are equal.
345 bool operator==(const basic_collection_iterator &Other) const {
346 if (Base && (Base == Other.Base)) {
347 assert((Base->CurrentEntry == Other.Base->CurrentEntry)
348 && "Equal Bases expected to point to equal Entries");
351 return Base == Other.Base;
354 bool operator!=(const basic_collection_iterator &Other) const {
355 return !(Base == Other.Base);
358 basic_collection_iterator &operator++() {
359 assert(Base && "Attempted to advance iterator past end!");
361 // Create an end iterator.
362 if (!Base->CurrentEntry)
368 BaseT *Base = nullptr;
371 // The following two templates are used for both MappingNode and Sequence Node.
372 template <class CollectionType>
373 typename CollectionType::iterator begin(CollectionType &C) {
374 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
375 C.IsAtBeginning = false;
376 typename CollectionType::iterator ret(&C);
381 template <class CollectionType> void skip(CollectionType &C) {
382 // TODO: support skipping from the middle of a parsed collection ;/
383 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
385 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
390 /// \brief Represents a YAML map created from either a block map for a flow map.
392 /// This parses the YAML stream as increment() is called.
397 class MappingNode final : public Node {
398 void anchor() override;
404 MT_Inline ///< An inline mapping node is used for "[key: value]".
407 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
409 : Node(NK_Mapping, D, Anchor, Tag), Type(MT) {}
411 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
413 using iterator = basic_collection_iterator<MappingNode, KeyValueNode>;
415 template <class T> friend typename T::iterator yaml::begin(T &);
416 template <class T> friend void yaml::skip(T &);
418 iterator begin() { return yaml::begin(*this); }
420 iterator end() { return iterator(); }
422 void skip() override { yaml::skip(*this); }
424 static bool classof(const Node *N) {
425 return N->getType() == NK_Mapping;
430 bool IsAtBeginning = true;
431 bool IsAtEnd = false;
432 KeyValueNode *CurrentEntry = nullptr;
437 /// \brief Represents a YAML sequence created from either a block sequence for a
440 /// This parses the YAML stream as increment() is called.
445 class SequenceNode final : public Node {
446 void anchor() override;
458 // As a BlockMappingEntry and BlockEnd are not created in this case.
462 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
464 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST) {}
466 friend class basic_collection_iterator<SequenceNode, Node>;
468 using iterator = basic_collection_iterator<SequenceNode, Node>;
470 template <class T> friend typename T::iterator yaml::begin(T &);
471 template <class T> friend void yaml::skip(T &);
475 iterator begin() { return yaml::begin(*this); }
477 iterator end() { return iterator(); }
479 void skip() override { yaml::skip(*this); }
481 static bool classof(const Node *N) {
482 return N->getType() == NK_Sequence;
486 SequenceType SeqType;
487 bool IsAtBeginning = true;
488 bool IsAtEnd = false;
489 bool WasPreviousTokenFlowEntry = true; // Start with an imaginary ','.
490 Node *CurrentEntry = nullptr;
493 /// \brief Represents an alias to a Node with an anchor.
497 class AliasNode final : public Node {
498 void anchor() override;
501 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
502 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
504 StringRef getName() const { return Name; }
507 static bool classof(const Node *N) { return N->getType() == NK_Alias; }
513 /// \brief A YAML Stream is a sequence of Documents. A document contains a root
517 Document(Stream &ParentStream);
519 /// \brief Root for parsing a node. Returns a single node.
520 Node *parseBlockNode();
522 /// \brief Finish parsing the current document and return true if there are
523 /// more. Return false otherwise.
526 /// \brief Parse and return the root level node.
530 return Root = parseBlockNode();
533 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
537 friend class document_iterator;
539 /// \brief Stream to read tokens from.
542 /// \brief Used to allocate nodes to. All are destroyed without calling their
543 /// destructor when the document is destroyed.
544 BumpPtrAllocator NodeAllocator;
546 /// \brief The root node. Used to support skipping a partially parsed
550 /// \brief Maps tag prefixes to their expansion.
551 std::map<StringRef, StringRef> TagMap;
555 void setError(const Twine &Message, Token &Location) const;
558 /// \brief Parse %BLAH directives and return true if any were encountered.
559 bool parseDirectives();
561 /// \brief Parse %YAML
562 void parseYAMLDirective();
564 /// \brief Parse %TAG
565 void parseTAGDirective();
567 /// \brief Consume the next token and error if it is not \a TK.
568 bool expectToken(int TK);
571 /// \brief Iterator abstraction for Documents over a Stream.
572 class document_iterator {
574 document_iterator() = default;
575 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
577 bool operator==(const document_iterator &Other) const {
578 if (isAtEnd() || Other.isAtEnd())
579 return isAtEnd() && Other.isAtEnd();
581 return Doc == Other.Doc;
583 bool operator!=(const document_iterator &Other) const {
584 return !(*this == Other);
587 document_iterator operator++() {
588 assert(Doc && "incrementing iterator past the end.");
589 if (!(*Doc)->skip()) {
592 Stream &S = (*Doc)->stream;
593 Doc->reset(new Document(S));
598 Document &operator*() { return *Doc->get(); }
600 std::unique_ptr<Document> &operator->() { return *Doc; }
603 bool isAtEnd() const { return !Doc || !*Doc; }
605 std::unique_ptr<Document> *Doc = nullptr;
608 } // end namespace yaml
610 } // end namespace llvm
612 #endif // LLVM_SUPPORT_YAMLPARSER_H