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/OwningPtr.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringRef.h"
44 #include "llvm/Support/Allocator.h"
45 #include "llvm/Support/SMLoc.h"
59 class document_iterator;
65 /// @brief Dump all the tokens in this stream to OS.
66 /// @returns true if there was an error, false otherwise.
67 bool dumpTokens(StringRef Input, raw_ostream &);
69 /// @brief Scans all tokens in input without outputting anything. This is used
70 /// for benchmarking the tokenizer.
71 /// @returns true if there was an error, false otherwise.
72 bool scanTokens(StringRef Input);
74 /// @brief Escape \a Input for a double quoted scalar.
75 std::string escape(StringRef Input);
77 /// @brief This class represents a YAML stream potentially containing multiple
81 /// @brief This keeps a reference to the string referenced by \p Input.
82 Stream(StringRef Input, SourceMgr &);
84 /// @brief This takes ownership of \p InputBuffer.
85 Stream(MemoryBuffer *InputBuffer, SourceMgr &);
88 document_iterator begin();
89 document_iterator end();
97 void printError(Node *N, const Twine &Msg);
100 OwningPtr<Scanner> scanner;
101 OwningPtr<Document> CurrentDoc;
103 friend class Document;
106 /// @brief Abstract base class for all Nodes.
118 Node(unsigned int Type, OwningPtr<Document> &, StringRef Anchor,
121 /// @brief Get the value of the anchor attached to this node. If it does not
122 /// have one, getAnchor().size() will be 0.
123 StringRef getAnchor() const { return Anchor; }
125 /// \brief Get the tag as it was written in the document. This does not
126 /// perform tag resolution.
127 StringRef getRawTag() const { return Tag; }
129 /// \brief Get the verbatium tag for a given Node. This performs tag resoluton
130 /// and substitution.
131 std::string getVerbatimTag() const;
133 SMRange getSourceRange() const { return SourceRange; }
134 void setSourceRange(SMRange SR) { SourceRange = SR; }
136 // These functions forward to Document and Scanner.
139 Node *parseBlockNode();
140 BumpPtrAllocator &getAllocator();
141 void setError(const Twine &Message, Token &Location) const;
144 virtual void skip() {}
146 unsigned int getType() const { return TypeID; }
148 void *operator new ( size_t Size
149 , BumpPtrAllocator &Alloc
150 , size_t Alignment = 16) throw() {
151 return Alloc.Allocate(Size, Alignment);
154 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
155 Alloc.Deallocate(Ptr);
159 OwningPtr<Document> &Doc;
162 void operator delete(void *) throw() {}
169 /// \brief The tag as typed in the document.
173 /// @brief A null value.
177 class NullNode : public Node {
179 NullNode(OwningPtr<Document> &D)
180 : Node(NK_Null, D, StringRef(), StringRef()) {}
182 static inline bool classof(const Node *N) {
183 return N->getType() == NK_Null;
187 /// @brief A scalar node is an opaque datum that can be presented as a
188 /// series of zero or more Unicode scalar values.
192 class ScalarNode : public Node {
194 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
196 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
197 SMLoc Start = SMLoc::getFromPointer(Val.begin());
198 SMLoc End = SMLoc::getFromPointer(Val.end());
199 SourceRange = SMRange(Start, End);
202 // Return Value without any escaping or folding or other fun YAML stuff. This
203 // is the exact bytes that are contained in the file (after conversion to
205 StringRef getRawValue() const { return Value; }
207 /// @brief Gets the value of this node as a StringRef.
209 /// @param Storage is used to store the content of the returned StringRef iff
210 /// it requires any modification from how it appeared in the source.
211 /// This happens with escaped characters and multi-line literals.
212 StringRef getValue(SmallVectorImpl<char> &Storage) const;
214 static inline bool classof(const Node *N) {
215 return N->getType() == NK_Scalar;
221 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
222 , StringRef::size_type Start
223 , SmallVectorImpl<char> &Storage) const;
226 /// @brief A key and value pair. While not technically a Node under the YAML
227 /// representation graph, it is easier to treat them this way.
229 /// TODO: Consider making this not a child of Node.
233 class KeyValueNode : public Node {
235 KeyValueNode(OwningPtr<Document> &D)
236 : Node(NK_KeyValue, D, StringRef(), StringRef())
241 /// @brief Parse and return the key.
243 /// This may be called multiple times.
245 /// @returns The key, or nullptr if failed() == true.
248 /// @brief Parse and return the value.
250 /// This may be called multiple times.
252 /// @returns The value, or nullptr if failed() == true.
255 virtual void skip() LLVM_OVERRIDE {
260 static inline bool classof(const Node *N) {
261 return N->getType() == NK_KeyValue;
269 /// @brief This is an iterator abstraction over YAML collections shared by both
270 /// sequences and maps.
272 /// BaseT must have a ValueT* member named CurrentEntry and a member function
273 /// increment() which must set CurrentEntry to 0 to create an end iterator.
274 template <class BaseT, class ValueT>
275 class basic_collection_iterator
276 : public std::iterator<std::forward_iterator_tag, ValueT> {
278 basic_collection_iterator() : Base(0) {}
279 basic_collection_iterator(BaseT *B) : Base(B) {}
281 ValueT *operator ->() const {
282 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
283 return Base->CurrentEntry;
286 ValueT &operator *() const {
287 assert(Base && Base->CurrentEntry &&
288 "Attempted to dereference end iterator!");
289 return *Base->CurrentEntry;
292 operator ValueT*() const {
293 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
294 return Base->CurrentEntry;
297 bool operator !=(const basic_collection_iterator &Other) const {
298 if(Base != Other.Base)
300 return (Base && Other.Base) && Base->CurrentEntry
301 != Other.Base->CurrentEntry;
304 basic_collection_iterator &operator++() {
305 assert(Base && "Attempted to advance iterator past end!");
307 // Create an end iterator.
308 if (Base->CurrentEntry == 0)
317 // The following two templates are used for both MappingNode and Sequence Node.
318 template <class CollectionType>
319 typename CollectionType::iterator begin(CollectionType &C) {
320 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
321 C.IsAtBeginning = false;
322 typename CollectionType::iterator ret(&C);
327 template <class CollectionType>
328 void skip(CollectionType &C) {
329 // TODO: support skipping from the middle of a parsed collection ;/
330 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
332 for (typename CollectionType::iterator i = begin(C), e = C.end();
337 /// @brief Represents a YAML map created from either a block map for a flow map.
339 /// This parses the YAML stream as increment() is called.
344 class MappingNode : public Node {
349 MT_Inline ///< An inline mapping node is used for "[key: value]".
352 MappingNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
354 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
355 IsAtEnd(false), CurrentEntry(0) {}
357 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
358 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
359 template <class T> friend typename T::iterator yaml::begin(T &);
360 template <class T> friend void yaml::skip(T &);
363 return yaml::begin(*this);
366 iterator end() { return iterator(); }
368 virtual void skip() LLVM_OVERRIDE {
372 static inline bool classof(const Node *N) {
373 return N->getType() == NK_Mapping;
380 KeyValueNode *CurrentEntry;
385 /// @brief Represents a YAML sequence created from either a block sequence for a
388 /// This parses the YAML stream as increment() is called.
393 class SequenceNode : public Node {
404 // As a BlockMappingEntry and BlockEnd are not created in this case.
408 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
410 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true),
412 WasPreviousTokenFlowEntry(true), // Start with an imaginary ','.
415 friend class basic_collection_iterator<SequenceNode, Node>;
416 typedef basic_collection_iterator<SequenceNode, Node> iterator;
417 template <class T> friend typename T::iterator yaml::begin(T &);
418 template <class T> friend void yaml::skip(T &);
423 return yaml::begin(*this);
426 iterator end() { return iterator(); }
428 virtual void skip() LLVM_OVERRIDE {
432 static inline bool classof(const Node *N) {
433 return N->getType() == NK_Sequence;
437 SequenceType SeqType;
440 bool WasPreviousTokenFlowEntry;
444 /// @brief Represents an alias to a Node with an anchor.
448 class AliasNode : public Node {
450 AliasNode(OwningPtr<Document> &D, StringRef Val)
451 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
453 StringRef getName() const { return Name; }
456 static inline bool classof(const Node *N) {
457 return N->getType() == NK_Alias;
464 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
468 /// @brief Root for parsing a node. Returns a single node.
469 Node *parseBlockNode();
471 Document(Stream &ParentStream);
473 /// @brief Finish parsing the current document and return true if there are
474 /// more. Return false otherwise.
477 /// @brief Parse and return the root level node.
481 return Root = parseBlockNode();
484 const std::map<StringRef, StringRef> &getTagMap() const {
490 friend class document_iterator;
492 /// @brief Stream to read tokens from.
495 /// @brief Used to allocate nodes to. All are destroyed without calling their
496 /// destructor when the document is destroyed.
497 BumpPtrAllocator NodeAllocator;
499 /// @brief The root node. Used to support skipping a partially parsed
503 /// \brief Maps tag prefixes to their expansion.
504 std::map<StringRef, StringRef> TagMap;
508 void setError(const Twine &Message, Token &Location) const;
511 /// @brief Parse %BLAH directives and return true if any were encountered.
512 bool parseDirectives();
514 /// \brief Parse %YAML
515 void parseYAMLDirective();
517 /// \brief Parse %TAG
518 void parseTAGDirective();
520 /// @brief Consume the next token and error if it is not \a TK.
521 bool expectToken(int TK);
524 /// @brief Iterator abstraction for Documents over a Stream.
525 class document_iterator {
527 document_iterator() : Doc(0) {}
528 document_iterator(OwningPtr<Document> &D) : Doc(&D) {}
530 bool operator ==(const document_iterator &Other) {
531 if (isAtEnd() || Other.isAtEnd())
532 return isAtEnd() && Other.isAtEnd();
534 return Doc == Other.Doc;
536 bool operator !=(const document_iterator &Other) {
537 return !(*this == Other);
540 document_iterator operator ++() {
541 assert(Doc != 0 && "incrementing iterator past the end.");
542 if (!(*Doc)->skip()) {
545 Stream &S = (*Doc)->stream;
546 Doc->reset(new Document(S));
551 Document &operator *() {
555 OwningPtr<Document> &operator ->() {
560 bool isAtEnd() const {
561 return !Doc || !*Doc;
564 OwningPtr<Document> *Doc;