1 //===--- YAMLParser.h - Simple YAML parser --------------------------------===//
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"
49 class MemoryBufferRef;
56 class document_iterator;
62 /// \brief Dump all the tokens in this stream to OS.
63 /// \returns true if there was an error, false otherwise.
64 bool dumpTokens(StringRef Input, raw_ostream &);
66 /// \brief Scans all tokens in input without outputting anything. This is used
67 /// for benchmarking the tokenizer.
68 /// \returns true if there was an error, false otherwise.
69 bool scanTokens(StringRef Input);
71 /// \brief Escape \a Input for a double quoted scalar.
72 std::string escape(StringRef Input);
74 /// \brief This class represents a YAML stream potentially containing multiple
78 /// \brief This keeps a reference to the string referenced by \p Input.
79 Stream(StringRef Input, SourceMgr &, bool ShowColors = true);
81 Stream(MemoryBufferRef InputBuffer, SourceMgr &, bool ShowColors = true);
84 document_iterator begin();
85 document_iterator end();
93 void printError(Node *N, const Twine &Msg);
96 std::unique_ptr<Scanner> scanner;
97 std::unique_ptr<Document> CurrentDoc;
99 friend class Document;
102 /// \brief Abstract base class for all Nodes.
104 virtual void anchor();
117 Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
120 /// \brief Get the value of the anchor attached to this node. If it does not
121 /// have one, getAnchor().size() will be 0.
122 StringRef getAnchor() const { return Anchor; }
124 /// \brief Get the tag as it was written in the document. This does not
125 /// perform tag resolution.
126 StringRef getRawTag() const { return Tag; }
128 /// \brief Get the verbatium tag for a given Node. This performs tag resoluton
129 /// and substitution.
130 std::string getVerbatimTag() const;
132 SMRange getSourceRange() const { return SourceRange; }
133 void setSourceRange(SMRange SR) { SourceRange = SR; }
135 // These functions forward to Document and Scanner.
138 Node *parseBlockNode();
139 BumpPtrAllocator &getAllocator();
140 void setError(const Twine &Message, Token &Location) const;
143 virtual void skip() {}
145 unsigned int getType() const { return TypeID; }
147 void *operator new(size_t Size, BumpPtrAllocator &Alloc,
148 size_t Alignment = 16) LLVM_NOEXCEPT {
149 return Alloc.Allocate(Size, Alignment);
152 void operator delete(void *Ptr, BumpPtrAllocator &Alloc,
153 size_t Size) LLVM_NOEXCEPT {
154 Alloc.Deallocate(Ptr, Size);
158 std::unique_ptr<Document> &Doc;
161 void operator delete(void *) LLVM_NOEXCEPT = delete;
168 /// \brief The tag as typed in the document.
172 /// \brief A null value.
176 class NullNode final : public Node {
177 void anchor() override;
180 NullNode(std::unique_ptr<Document> &D)
181 : Node(NK_Null, D, StringRef(), StringRef()) {}
183 static inline bool classof(const Node *N) { return N->getType() == NK_Null; }
186 /// \brief A scalar node is an opaque datum that can be presented as a
187 /// series of zero or more Unicode scalar values.
191 class ScalarNode final : public Node {
192 void anchor() override;
195 ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
197 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
198 SMLoc Start = SMLoc::getFromPointer(Val.begin());
199 SMLoc End = SMLoc::getFromPointer(Val.end());
200 SourceRange = SMRange(Start, End);
203 // Return Value without any escaping or folding or other fun YAML stuff. This
204 // is the exact bytes that are contained in the file (after conversion to
206 StringRef getRawValue() const { return Value; }
208 /// \brief Gets the value of this node as a StringRef.
210 /// \param Storage is used to store the content of the returned StringRef iff
211 /// it requires any modification from how it appeared in the source.
212 /// This happens with escaped characters and multi-line literals.
213 StringRef getValue(SmallVectorImpl<char> &Storage) const;
215 static inline bool classof(const Node *N) {
216 return N->getType() == NK_Scalar;
222 StringRef unescapeDoubleQuoted(StringRef UnquotedValue,
223 StringRef::size_type Start,
224 SmallVectorImpl<char> &Storage) const;
227 /// \brief A block scalar node is an opaque datum that can be presented as a
228 /// series of zero or more Unicode scalar values.
234 class BlockScalarNode final : public Node {
235 void anchor() override;
238 BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
239 StringRef Value, StringRef RawVal)
240 : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) {
241 SMLoc Start = SMLoc::getFromPointer(RawVal.begin());
242 SMLoc End = SMLoc::getFromPointer(RawVal.end());
243 SourceRange = SMRange(Start, End);
246 /// \brief Gets the value of this node as a StringRef.
247 StringRef getValue() const { return Value; }
249 static inline bool classof(const Node *N) {
250 return N->getType() == NK_BlockScalar;
257 /// \brief A key and value pair. While not technically a Node under the YAML
258 /// representation graph, it is easier to treat them this way.
260 /// TODO: Consider making this not a child of Node.
264 class KeyValueNode final : public Node {
265 void anchor() override;
268 KeyValueNode(std::unique_ptr<Document> &D)
269 : Node(NK_KeyValue, D, StringRef(), StringRef()), Key(nullptr),
272 /// \brief Parse and return the key.
274 /// This may be called multiple times.
276 /// \returns The key, or nullptr if failed() == true.
279 /// \brief Parse and return the value.
281 /// This may be called multiple times.
283 /// \returns The value, or nullptr if failed() == true.
286 void skip() override {
288 if (Node *Val = getValue())
292 static inline bool classof(const Node *N) {
293 return N->getType() == NK_KeyValue;
301 /// \brief This is an iterator abstraction over YAML collections shared by both
302 /// sequences and maps.
304 /// BaseT must have a ValueT* member named CurrentEntry and a member function
305 /// increment() which must set CurrentEntry to 0 to create an end iterator.
306 template <class BaseT, class ValueT>
307 class basic_collection_iterator
308 : public std::iterator<std::input_iterator_tag, ValueT> {
310 basic_collection_iterator() : Base(nullptr) {}
311 basic_collection_iterator(BaseT *B) : Base(B) {}
313 ValueT *operator->() const {
314 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
315 return Base->CurrentEntry;
318 ValueT &operator*() const {
319 assert(Base && Base->CurrentEntry &&
320 "Attempted to dereference end iterator!");
321 return *Base->CurrentEntry;
324 operator ValueT *() const {
325 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
326 return Base->CurrentEntry;
329 /// Note on EqualityComparable:
331 /// The iterator is not re-entrant,
332 /// it is meant to be used for parsing YAML on-demand
333 /// Once iteration started - it can point only to one entry at a time
334 /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
335 /// iff Base and Other.Base are equal.
336 bool operator==(const basic_collection_iterator &Other) const {
337 if (Base && (Base == Other.Base)) {
338 assert((Base->CurrentEntry == Other.Base->CurrentEntry)
339 && "Equal Bases expected to point to equal Entries");
342 return Base == Other.Base;
345 bool operator!=(const basic_collection_iterator &Other) const {
346 return !(Base == Other.Base);
349 basic_collection_iterator &operator++() {
350 assert(Base && "Attempted to advance iterator past end!");
352 // Create an end iterator.
353 if (!Base->CurrentEntry)
362 // The following two templates are used for both MappingNode and Sequence Node.
363 template <class CollectionType>
364 typename CollectionType::iterator begin(CollectionType &C) {
365 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
366 C.IsAtBeginning = false;
367 typename CollectionType::iterator ret(&C);
372 template <class CollectionType> void skip(CollectionType &C) {
373 // TODO: support skipping from the middle of a parsed collection ;/
374 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
376 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
381 /// \brief Represents a YAML map created from either a block map for a flow map.
383 /// This parses the YAML stream as increment() is called.
388 class MappingNode final : public Node {
389 void anchor() override;
395 MT_Inline ///< An inline mapping node is used for "[key: value]".
398 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
400 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
401 IsAtEnd(false), CurrentEntry(nullptr) {}
403 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
404 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
405 template <class T> friend typename T::iterator yaml::begin(T &);
406 template <class T> friend void yaml::skip(T &);
408 iterator begin() { return yaml::begin(*this); }
410 iterator end() { return iterator(); }
412 void skip() override { yaml::skip(*this); }
414 static inline bool classof(const Node *N) {
415 return N->getType() == NK_Mapping;
422 KeyValueNode *CurrentEntry;
427 /// \brief Represents a YAML sequence created from either a block sequence for a
430 /// This parses the YAML stream as increment() is called.
435 class SequenceNode final : public Node {
436 void anchor() override;
448 // As a BlockMappingEntry and BlockEnd are not created in this case.
452 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
454 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true),
456 WasPreviousTokenFlowEntry(true), // Start with an imaginary ','.
457 CurrentEntry(nullptr) {}
459 friend class basic_collection_iterator<SequenceNode, Node>;
460 typedef basic_collection_iterator<SequenceNode, Node> iterator;
461 template <class T> friend typename T::iterator yaml::begin(T &);
462 template <class T> friend void yaml::skip(T &);
466 iterator begin() { return yaml::begin(*this); }
468 iterator end() { return iterator(); }
470 void skip() override { yaml::skip(*this); }
472 static inline bool classof(const Node *N) {
473 return N->getType() == NK_Sequence;
477 SequenceType SeqType;
480 bool WasPreviousTokenFlowEntry;
484 /// \brief Represents an alias to a Node with an anchor.
488 class AliasNode final : public Node {
489 void anchor() override;
492 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
493 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
495 StringRef getName() const { return Name; }
498 static inline bool classof(const Node *N) { return N->getType() == NK_Alias; }
504 /// \brief A YAML Stream is a sequence of Documents. A document contains a root
508 /// \brief Root for parsing a node. Returns a single node.
509 Node *parseBlockNode();
511 Document(Stream &ParentStream);
513 /// \brief Finish parsing the current document and return true if there are
514 /// more. Return false otherwise.
517 /// \brief Parse and return the root level node.
521 return Root = parseBlockNode();
524 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
528 friend class document_iterator;
530 /// \brief Stream to read tokens from.
533 /// \brief Used to allocate nodes to. All are destroyed without calling their
534 /// destructor when the document is destroyed.
535 BumpPtrAllocator NodeAllocator;
537 /// \brief The root node. Used to support skipping a partially parsed
541 /// \brief Maps tag prefixes to their expansion.
542 std::map<StringRef, StringRef> TagMap;
546 void setError(const Twine &Message, Token &Location) const;
549 /// \brief Parse %BLAH directives and return true if any were encountered.
550 bool parseDirectives();
552 /// \brief Parse %YAML
553 void parseYAMLDirective();
555 /// \brief Parse %TAG
556 void parseTAGDirective();
558 /// \brief Consume the next token and error if it is not \a TK.
559 bool expectToken(int TK);
562 /// \brief Iterator abstraction for Documents over a Stream.
563 class document_iterator {
565 document_iterator() : Doc(nullptr) {}
566 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
568 bool operator==(const document_iterator &Other) {
569 if (isAtEnd() || Other.isAtEnd())
570 return isAtEnd() && Other.isAtEnd();
572 return Doc == Other.Doc;
574 bool operator!=(const document_iterator &Other) { return !(*this == Other); }
576 document_iterator operator++() {
577 assert(Doc && "incrementing iterator past the end.");
578 if (!(*Doc)->skip()) {
581 Stream &S = (*Doc)->stream;
582 Doc->reset(new Document(S));
587 Document &operator*() { return *Doc->get(); }
589 std::unique_ptr<Document> &operator->() { return *Doc; }
592 bool isAtEnd() const { return !Doc || !*Doc; }
594 std::unique_ptr<Document> *Doc;
597 } // End namespace yaml.
599 } // End namespace llvm.