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 {
295 if (Node *Val = getValue())
299 static bool classof(const Node *N) {
300 return N->getType() == NK_KeyValue;
305 Node *Value = nullptr;
308 /// \brief This is an iterator abstraction over YAML collections shared by both
309 /// sequences and maps.
311 /// BaseT must have a ValueT* member named CurrentEntry and a member function
312 /// increment() which must set CurrentEntry to 0 to create an end iterator.
313 template <class BaseT, class ValueT>
314 class basic_collection_iterator
315 : public std::iterator<std::input_iterator_tag, ValueT> {
317 basic_collection_iterator() = default;
318 basic_collection_iterator(BaseT *B) : Base(B) {}
320 ValueT *operator->() const {
321 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
322 return Base->CurrentEntry;
325 ValueT &operator*() const {
326 assert(Base && Base->CurrentEntry &&
327 "Attempted to dereference end iterator!");
328 return *Base->CurrentEntry;
331 operator ValueT *() const {
332 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
333 return Base->CurrentEntry;
336 /// Note on EqualityComparable:
338 /// The iterator is not re-entrant,
339 /// it is meant to be used for parsing YAML on-demand
340 /// Once iteration started - it can point only to one entry at a time
341 /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
342 /// iff Base and Other.Base are equal.
343 bool operator==(const basic_collection_iterator &Other) const {
344 if (Base && (Base == Other.Base)) {
345 assert((Base->CurrentEntry == Other.Base->CurrentEntry)
346 && "Equal Bases expected to point to equal Entries");
349 return Base == Other.Base;
352 bool operator!=(const basic_collection_iterator &Other) const {
353 return !(Base == Other.Base);
356 basic_collection_iterator &operator++() {
357 assert(Base && "Attempted to advance iterator past end!");
359 // Create an end iterator.
360 if (!Base->CurrentEntry)
366 BaseT *Base = nullptr;
369 // The following two templates are used for both MappingNode and Sequence Node.
370 template <class CollectionType>
371 typename CollectionType::iterator begin(CollectionType &C) {
372 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
373 C.IsAtBeginning = false;
374 typename CollectionType::iterator ret(&C);
379 template <class CollectionType> void skip(CollectionType &C) {
380 // TODO: support skipping from the middle of a parsed collection ;/
381 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
383 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
388 /// \brief Represents a YAML map created from either a block map for a flow map.
390 /// This parses the YAML stream as increment() is called.
395 class MappingNode final : public Node {
396 void anchor() override;
402 MT_Inline ///< An inline mapping node is used for "[key: value]".
405 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
407 : Node(NK_Mapping, D, Anchor, Tag), Type(MT) {}
409 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
411 using iterator = basic_collection_iterator<MappingNode, KeyValueNode>;
413 template <class T> friend typename T::iterator yaml::begin(T &);
414 template <class T> friend void yaml::skip(T &);
416 iterator begin() { return yaml::begin(*this); }
418 iterator end() { return iterator(); }
420 void skip() override { yaml::skip(*this); }
422 static bool classof(const Node *N) {
423 return N->getType() == NK_Mapping;
428 bool IsAtBeginning = true;
429 bool IsAtEnd = false;
430 KeyValueNode *CurrentEntry = nullptr;
435 /// \brief Represents a YAML sequence created from either a block sequence for a
438 /// This parses the YAML stream as increment() is called.
443 class SequenceNode final : public Node {
444 void anchor() override;
456 // As a BlockMappingEntry and BlockEnd are not created in this case.
460 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
462 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST) {}
464 friend class basic_collection_iterator<SequenceNode, Node>;
466 using iterator = basic_collection_iterator<SequenceNode, Node>;
468 template <class T> friend typename T::iterator yaml::begin(T &);
469 template <class T> friend void yaml::skip(T &);
473 iterator begin() { return yaml::begin(*this); }
475 iterator end() { return iterator(); }
477 void skip() override { yaml::skip(*this); }
479 static bool classof(const Node *N) {
480 return N->getType() == NK_Sequence;
484 SequenceType SeqType;
485 bool IsAtBeginning = true;
486 bool IsAtEnd = false;
487 bool WasPreviousTokenFlowEntry = true; // Start with an imaginary ','.
488 Node *CurrentEntry = nullptr;
491 /// \brief Represents an alias to a Node with an anchor.
495 class AliasNode final : public Node {
496 void anchor() override;
499 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
500 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
502 StringRef getName() const { return Name; }
505 static bool classof(const Node *N) { return N->getType() == NK_Alias; }
511 /// \brief A YAML Stream is a sequence of Documents. A document contains a root
515 Document(Stream &ParentStream);
517 /// \brief Root for parsing a node. Returns a single node.
518 Node *parseBlockNode();
520 /// \brief Finish parsing the current document and return true if there are
521 /// more. Return false otherwise.
524 /// \brief Parse and return the root level node.
528 return Root = parseBlockNode();
531 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
535 friend class document_iterator;
537 /// \brief Stream to read tokens from.
540 /// \brief Used to allocate nodes to. All are destroyed without calling their
541 /// destructor when the document is destroyed.
542 BumpPtrAllocator NodeAllocator;
544 /// \brief The root node. Used to support skipping a partially parsed
548 /// \brief Maps tag prefixes to their expansion.
549 std::map<StringRef, StringRef> TagMap;
553 void setError(const Twine &Message, Token &Location) const;
556 /// \brief Parse %BLAH directives and return true if any were encountered.
557 bool parseDirectives();
559 /// \brief Parse %YAML
560 void parseYAMLDirective();
562 /// \brief Parse %TAG
563 void parseTAGDirective();
565 /// \brief Consume the next token and error if it is not \a TK.
566 bool expectToken(int TK);
569 /// \brief Iterator abstraction for Documents over a Stream.
570 class document_iterator {
572 document_iterator() = default;
573 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
575 bool operator==(const document_iterator &Other) {
576 if (isAtEnd() || Other.isAtEnd())
577 return isAtEnd() && Other.isAtEnd();
579 return Doc == Other.Doc;
581 bool operator!=(const document_iterator &Other) { return !(*this == Other); }
583 document_iterator operator++() {
584 assert(Doc && "incrementing iterator past the end.");
585 if (!(*Doc)->skip()) {
588 Stream &S = (*Doc)->stream;
589 Doc->reset(new Document(S));
594 Document &operator*() { return *Doc->get(); }
596 std::unique_ptr<Document> &operator->() { return *Doc; }
599 bool isAtEnd() const { return !Doc || !*Doc; }
601 std::unique_ptr<Document> *Doc = nullptr;
604 } // end namespace yaml
606 } // end namespace llvm
608 #endif // LLVM_SUPPORT_YAMLPARSER_H