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 /// 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 /// 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 /// Escape \a Input for a double quoted scalar; if \p EscapePrintable
77 /// is true, all UTF8 sequences will be escaped, if \p EscapePrintable is
78 /// false, those UTF8 sequences encoding printable unicode scalars will not be
79 /// escaped, but emitted verbatim.
80 std::string escape(StringRef Input, bool EscapePrintable = true);
82 /// This class represents a YAML stream potentially containing multiple
86 /// This keeps a reference to the string referenced by \p Input.
87 Stream(StringRef Input, SourceMgr &, bool ShowColors = true,
88 std::error_code *EC = nullptr);
90 Stream(MemoryBufferRef InputBuffer, SourceMgr &, bool ShowColors = true,
91 std::error_code *EC = nullptr);
94 document_iterator begin();
95 document_iterator end();
104 void printError(Node *N, const Twine &Msg);
107 friend class Document;
109 std::unique_ptr<Scanner> scanner;
110 std::unique_ptr<Document> CurrentDoc;
113 /// Abstract base class for all Nodes.
115 virtual void anchor();
128 Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
131 // It's not safe to copy YAML nodes; the document is streamed and the position
132 // is part of the state.
133 Node(const Node &) = delete;
134 void operator=(const Node &) = delete;
136 void *operator new(size_t Size, BumpPtrAllocator &Alloc,
137 size_t Alignment = 16) noexcept {
138 return Alloc.Allocate(Size, Alignment);
141 void operator delete(void *Ptr, BumpPtrAllocator &Alloc,
142 size_t Size) noexcept {
143 Alloc.Deallocate(Ptr, Size);
146 void operator delete(void *) noexcept = delete;
148 /// Get the value of the anchor attached to this node. If it does not
149 /// have one, getAnchor().size() will be 0.
150 StringRef getAnchor() const { return Anchor; }
152 /// Get the tag as it was written in the document. This does not
153 /// perform tag resolution.
154 StringRef getRawTag() const { return Tag; }
156 /// Get the verbatium tag for a given Node. This performs tag resoluton
157 /// and substitution.
158 std::string getVerbatimTag() const;
160 SMRange getSourceRange() const { return SourceRange; }
161 void setSourceRange(SMRange SR) { SourceRange = SR; }
163 // These functions forward to Document and Scanner.
166 Node *parseBlockNode();
167 BumpPtrAllocator &getAllocator();
168 void setError(const Twine &Message, Token &Location) const;
171 virtual void skip() {}
173 unsigned int getType() const { return TypeID; }
176 std::unique_ptr<Document> &Doc;
184 /// The tag as typed in the document.
192 class NullNode final : public Node {
193 void anchor() override;
196 NullNode(std::unique_ptr<Document> &D)
197 : Node(NK_Null, D, StringRef(), StringRef()) {}
199 static bool classof(const Node *N) { return N->getType() == NK_Null; }
202 /// A scalar node is an opaque datum that can be presented as a
203 /// series of zero or more Unicode scalar values.
207 class ScalarNode final : public Node {
208 void anchor() override;
211 ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
213 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
214 SMLoc Start = SMLoc::getFromPointer(Val.begin());
215 SMLoc End = SMLoc::getFromPointer(Val.end());
216 SourceRange = SMRange(Start, End);
219 // Return Value without any escaping or folding or other fun YAML stuff. This
220 // is the exact bytes that are contained in the file (after conversion to
222 StringRef getRawValue() const { return Value; }
224 /// Gets the value of this node as a StringRef.
226 /// \param Storage is used to store the content of the returned StringRef iff
227 /// it requires any modification from how it appeared in the source.
228 /// This happens with escaped characters and multi-line literals.
229 StringRef getValue(SmallVectorImpl<char> &Storage) const;
231 static bool classof(const Node *N) {
232 return N->getType() == NK_Scalar;
238 StringRef unescapeDoubleQuoted(StringRef UnquotedValue,
239 StringRef::size_type Start,
240 SmallVectorImpl<char> &Storage) const;
243 /// A block scalar node is an opaque datum that can be presented as a
244 /// series of zero or more Unicode scalar values.
250 class BlockScalarNode final : public Node {
251 void anchor() override;
254 BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
255 StringRef Value, StringRef RawVal)
256 : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) {
257 SMLoc Start = SMLoc::getFromPointer(RawVal.begin());
258 SMLoc End = SMLoc::getFromPointer(RawVal.end());
259 SourceRange = SMRange(Start, End);
262 /// Gets the value of this node as a StringRef.
263 StringRef getValue() const { return Value; }
265 static bool classof(const Node *N) {
266 return N->getType() == NK_BlockScalar;
273 /// A key and value pair. While not technically a Node under the YAML
274 /// representation graph, it is easier to treat them this way.
276 /// TODO: Consider making this not a child of Node.
280 class KeyValueNode final : public Node {
281 void anchor() override;
284 KeyValueNode(std::unique_ptr<Document> &D)
285 : Node(NK_KeyValue, D, StringRef(), StringRef()) {}
287 /// Parse and return the key.
289 /// This may be called multiple times.
291 /// \returns The key, or nullptr if failed() == true.
294 /// Parse and return the value.
296 /// This may be called multiple times.
298 /// \returns The value, or nullptr if failed() == true.
301 void skip() override {
302 if (Node *Key = getKey()) {
304 if (Node *Val = getValue())
309 static bool classof(const Node *N) {
310 return N->getType() == NK_KeyValue;
315 Node *Value = nullptr;
318 /// This is an iterator abstraction over YAML collections shared by both
319 /// sequences and maps.
321 /// BaseT must have a ValueT* member named CurrentEntry and a member function
322 /// increment() which must set CurrentEntry to 0 to create an end iterator.
323 template <class BaseT, class ValueT>
324 class basic_collection_iterator
325 : public std::iterator<std::input_iterator_tag, ValueT> {
327 basic_collection_iterator() = default;
328 basic_collection_iterator(BaseT *B) : Base(B) {}
330 ValueT *operator->() const {
331 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
332 return Base->CurrentEntry;
335 ValueT &operator*() const {
336 assert(Base && Base->CurrentEntry &&
337 "Attempted to dereference end iterator!");
338 return *Base->CurrentEntry;
341 operator ValueT *() const {
342 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
343 return Base->CurrentEntry;
346 /// Note on EqualityComparable:
348 /// The iterator is not re-entrant,
349 /// it is meant to be used for parsing YAML on-demand
350 /// Once iteration started - it can point only to one entry at a time
351 /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
352 /// iff Base and Other.Base are equal.
353 bool operator==(const basic_collection_iterator &Other) const {
354 if (Base && (Base == Other.Base)) {
355 assert((Base->CurrentEntry == Other.Base->CurrentEntry)
356 && "Equal Bases expected to point to equal Entries");
359 return Base == Other.Base;
362 bool operator!=(const basic_collection_iterator &Other) const {
363 return !(Base == Other.Base);
366 basic_collection_iterator &operator++() {
367 assert(Base && "Attempted to advance iterator past end!");
369 // Create an end iterator.
370 if (!Base->CurrentEntry)
376 BaseT *Base = nullptr;
379 // The following two templates are used for both MappingNode and Sequence Node.
380 template <class CollectionType>
381 typename CollectionType::iterator begin(CollectionType &C) {
382 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
383 C.IsAtBeginning = false;
384 typename CollectionType::iterator ret(&C);
389 template <class CollectionType> void skip(CollectionType &C) {
390 // TODO: support skipping from the middle of a parsed collection ;/
391 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
393 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
398 /// Represents a YAML map created from either a block map for a flow map.
400 /// This parses the YAML stream as increment() is called.
405 class MappingNode final : public Node {
406 void anchor() override;
412 MT_Inline ///< An inline mapping node is used for "[key: value]".
415 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
417 : Node(NK_Mapping, D, Anchor, Tag), Type(MT) {}
419 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
421 using iterator = basic_collection_iterator<MappingNode, KeyValueNode>;
423 template <class T> friend typename T::iterator yaml::begin(T &);
424 template <class T> friend void yaml::skip(T &);
426 iterator begin() { return yaml::begin(*this); }
428 iterator end() { return iterator(); }
430 void skip() override { yaml::skip(*this); }
432 static bool classof(const Node *N) {
433 return N->getType() == NK_Mapping;
438 bool IsAtBeginning = true;
439 bool IsAtEnd = false;
440 KeyValueNode *CurrentEntry = nullptr;
445 /// Represents a YAML sequence created from either a block sequence for a
448 /// This parses the YAML stream as increment() is called.
453 class SequenceNode final : public Node {
454 void anchor() override;
466 // As a BlockMappingEntry and BlockEnd are not created in this case.
470 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
472 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST) {}
474 friend class basic_collection_iterator<SequenceNode, Node>;
476 using iterator = basic_collection_iterator<SequenceNode, Node>;
478 template <class T> friend typename T::iterator yaml::begin(T &);
479 template <class T> friend void yaml::skip(T &);
483 iterator begin() { return yaml::begin(*this); }
485 iterator end() { return iterator(); }
487 void skip() override { yaml::skip(*this); }
489 static bool classof(const Node *N) {
490 return N->getType() == NK_Sequence;
494 SequenceType SeqType;
495 bool IsAtBeginning = true;
496 bool IsAtEnd = false;
497 bool WasPreviousTokenFlowEntry = true; // Start with an imaginary ','.
498 Node *CurrentEntry = nullptr;
501 /// Represents an alias to a Node with an anchor.
505 class AliasNode final : public Node {
506 void anchor() override;
509 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
510 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
512 StringRef getName() const { return Name; }
515 static bool classof(const Node *N) { return N->getType() == NK_Alias; }
521 /// A YAML Stream is a sequence of Documents. A document contains a root
525 Document(Stream &ParentStream);
527 /// Root for parsing a node. Returns a single node.
528 Node *parseBlockNode();
530 /// Finish parsing the current document and return true if there are
531 /// more. Return false otherwise.
534 /// Parse and return the root level node.
538 return Root = parseBlockNode();
541 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
545 friend class document_iterator;
547 /// Stream to read tokens from.
550 /// Used to allocate nodes to. All are destroyed without calling their
551 /// destructor when the document is destroyed.
552 BumpPtrAllocator NodeAllocator;
554 /// The root node. Used to support skipping a partially parsed
558 /// Maps tag prefixes to their expansion.
559 std::map<StringRef, StringRef> TagMap;
563 void setError(const Twine &Message, Token &Location) const;
566 /// Parse %BLAH directives and return true if any were encountered.
567 bool parseDirectives();
570 void parseYAMLDirective();
573 void parseTAGDirective();
575 /// Consume the next token and error if it is not \a TK.
576 bool expectToken(int TK);
579 /// Iterator abstraction for Documents over a Stream.
580 class document_iterator {
582 document_iterator() = default;
583 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
585 bool operator==(const document_iterator &Other) const {
586 if (isAtEnd() || Other.isAtEnd())
587 return isAtEnd() && Other.isAtEnd();
589 return Doc == Other.Doc;
591 bool operator!=(const document_iterator &Other) const {
592 return !(*this == Other);
595 document_iterator operator++() {
596 assert(Doc && "incrementing iterator past the end.");
597 if (!(*Doc)->skip()) {
600 Stream &S = (*Doc)->stream;
601 Doc->reset(new Document(S));
606 Document &operator*() { return *Doc->get(); }
608 std::unique_ptr<Document> &operator->() { return *Doc; }
611 bool isAtEnd() const { return !Doc || !*Doc; }
613 std::unique_ptr<Document> *Doc = nullptr;
616 } // end namespace yaml
618 } // end namespace llvm
620 #endif // LLVM_SUPPORT_YAMLPARSER_H