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.
108 virtual void anchor();
119 Node(unsigned int Type, OwningPtr<Document> &, StringRef Anchor,
122 /// @brief Get the value of the anchor attached to this node. If it does not
123 /// have one, getAnchor().size() will be 0.
124 StringRef getAnchor() const { return Anchor; }
126 /// \brief Get the tag as it was written in the document. This does not
127 /// perform tag resolution.
128 StringRef getRawTag() const { return Tag; }
130 /// \brief Get the verbatium tag for a given Node. This performs tag resoluton
131 /// and substitution.
132 std::string getVerbatimTag() const;
134 SMRange getSourceRange() const { return SourceRange; }
135 void setSourceRange(SMRange SR) { SourceRange = SR; }
137 // These functions forward to Document and Scanner.
140 Node *parseBlockNode();
141 BumpPtrAllocator &getAllocator();
142 void setError(const Twine &Message, Token &Location) const;
145 virtual void skip() {}
147 unsigned int getType() const { return TypeID; }
149 void *operator new ( size_t Size
150 , BumpPtrAllocator &Alloc
151 , size_t Alignment = 16) throw() {
152 return Alloc.Allocate(Size, Alignment);
155 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
156 Alloc.Deallocate(Ptr);
160 OwningPtr<Document> &Doc;
163 void operator delete(void *) throw() {}
170 /// \brief The tag as typed in the document.
174 /// @brief A null value.
178 class NullNode : public Node {
179 virtual void anchor();
181 NullNode(OwningPtr<Document> &D)
182 : Node(NK_Null, D, StringRef(), StringRef()) {}
184 static inline bool classof(const Node *N) {
185 return N->getType() == NK_Null;
189 /// @brief A scalar node is an opaque datum that can be presented as a
190 /// series of zero or more Unicode scalar values.
194 class ScalarNode : public Node {
195 virtual void anchor();
197 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
199 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
200 SMLoc Start = SMLoc::getFromPointer(Val.begin());
201 SMLoc End = SMLoc::getFromPointer(Val.end());
202 SourceRange = SMRange(Start, End);
205 // Return Value without any escaping or folding or other fun YAML stuff. This
206 // is the exact bytes that are contained in the file (after conversion to
208 StringRef getRawValue() const { return Value; }
210 /// @brief Gets the value of this node as a StringRef.
212 /// @param Storage is used to store the content of the returned StringRef iff
213 /// it requires any modification from how it appeared in the source.
214 /// This happens with escaped characters and multi-line literals.
215 StringRef getValue(SmallVectorImpl<char> &Storage) const;
217 static inline bool classof(const Node *N) {
218 return N->getType() == NK_Scalar;
224 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
225 , StringRef::size_type Start
226 , SmallVectorImpl<char> &Storage) const;
229 /// @brief A key and value pair. While not technically a Node under the YAML
230 /// representation graph, it is easier to treat them this way.
232 /// TODO: Consider making this not a child of Node.
236 class KeyValueNode : public Node {
237 virtual void anchor();
239 KeyValueNode(OwningPtr<Document> &D)
240 : Node(NK_KeyValue, D, StringRef(), StringRef())
245 /// @brief Parse and return the key.
247 /// This may be called multiple times.
249 /// @returns The key, or nullptr if failed() == true.
252 /// @brief Parse and return the value.
254 /// This may be called multiple times.
256 /// @returns The value, or nullptr if failed() == true.
259 virtual void skip() LLVM_OVERRIDE {
264 static inline bool classof(const Node *N) {
265 return N->getType() == NK_KeyValue;
273 /// @brief This is an iterator abstraction over YAML collections shared by both
274 /// sequences and maps.
276 /// BaseT must have a ValueT* member named CurrentEntry and a member function
277 /// increment() which must set CurrentEntry to 0 to create an end iterator.
278 template <class BaseT, class ValueT>
279 class basic_collection_iterator
280 : public std::iterator<std::forward_iterator_tag, ValueT> {
282 basic_collection_iterator() : Base(0) {}
283 basic_collection_iterator(BaseT *B) : Base(B) {}
285 ValueT *operator ->() const {
286 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
287 return Base->CurrentEntry;
290 ValueT &operator *() const {
291 assert(Base && Base->CurrentEntry &&
292 "Attempted to dereference end iterator!");
293 return *Base->CurrentEntry;
296 operator ValueT*() const {
297 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
298 return Base->CurrentEntry;
301 bool operator !=(const basic_collection_iterator &Other) const {
302 if(Base != Other.Base)
304 return (Base && Other.Base) && Base->CurrentEntry
305 != Other.Base->CurrentEntry;
308 basic_collection_iterator &operator++() {
309 assert(Base && "Attempted to advance iterator past end!");
311 // Create an end iterator.
312 if (Base->CurrentEntry == 0)
321 // The following two templates are used for both MappingNode and Sequence Node.
322 template <class CollectionType>
323 typename CollectionType::iterator begin(CollectionType &C) {
324 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
325 C.IsAtBeginning = false;
326 typename CollectionType::iterator ret(&C);
331 template <class CollectionType>
332 void skip(CollectionType &C) {
333 // TODO: support skipping from the middle of a parsed collection ;/
334 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
336 for (typename CollectionType::iterator i = begin(C), e = C.end();
341 /// @brief Represents a YAML map created from either a block map for a flow map.
343 /// This parses the YAML stream as increment() is called.
348 class MappingNode : public Node {
349 virtual void anchor();
354 MT_Inline ///< An inline mapping node is used for "[key: value]".
357 MappingNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
359 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
360 IsAtEnd(false), CurrentEntry(0) {}
362 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
363 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
364 template <class T> friend typename T::iterator yaml::begin(T &);
365 template <class T> friend void yaml::skip(T &);
368 return yaml::begin(*this);
371 iterator end() { return iterator(); }
373 virtual void skip() LLVM_OVERRIDE {
377 static inline bool classof(const Node *N) {
378 return N->getType() == NK_Mapping;
385 KeyValueNode *CurrentEntry;
390 /// @brief Represents a YAML sequence created from either a block sequence for a
393 /// This parses the YAML stream as increment() is called.
398 class SequenceNode : public Node {
399 virtual void anchor();
410 // As a BlockMappingEntry and BlockEnd are not created in this case.
414 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
416 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true),
418 WasPreviousTokenFlowEntry(true), // Start with an imaginary ','.
421 friend class basic_collection_iterator<SequenceNode, Node>;
422 typedef basic_collection_iterator<SequenceNode, Node> iterator;
423 template <class T> friend typename T::iterator yaml::begin(T &);
424 template <class T> friend void yaml::skip(T &);
429 return yaml::begin(*this);
432 iterator end() { return iterator(); }
434 virtual void skip() LLVM_OVERRIDE {
438 static inline bool classof(const Node *N) {
439 return N->getType() == NK_Sequence;
443 SequenceType SeqType;
446 bool WasPreviousTokenFlowEntry;
450 /// @brief Represents an alias to a Node with an anchor.
454 class AliasNode : public Node {
455 virtual void anchor();
457 AliasNode(OwningPtr<Document> &D, StringRef Val)
458 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
460 StringRef getName() const { return Name; }
463 static inline bool classof(const Node *N) {
464 return N->getType() == NK_Alias;
471 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
475 /// @brief Root for parsing a node. Returns a single node.
476 Node *parseBlockNode();
478 Document(Stream &ParentStream);
480 /// @brief Finish parsing the current document and return true if there are
481 /// more. Return false otherwise.
484 /// @brief Parse and return the root level node.
488 return Root = parseBlockNode();
491 const std::map<StringRef, StringRef> &getTagMap() const {
497 friend class document_iterator;
499 /// @brief Stream to read tokens from.
502 /// @brief Used to allocate nodes to. All are destroyed without calling their
503 /// destructor when the document is destroyed.
504 BumpPtrAllocator NodeAllocator;
506 /// @brief The root node. Used to support skipping a partially parsed
510 /// \brief Maps tag prefixes to their expansion.
511 std::map<StringRef, StringRef> TagMap;
515 void setError(const Twine &Message, Token &Location) const;
518 /// @brief Parse %BLAH directives and return true if any were encountered.
519 bool parseDirectives();
521 /// \brief Parse %YAML
522 void parseYAMLDirective();
524 /// \brief Parse %TAG
525 void parseTAGDirective();
527 /// @brief Consume the next token and error if it is not \a TK.
528 bool expectToken(int TK);
531 /// @brief Iterator abstraction for Documents over a Stream.
532 class document_iterator {
534 document_iterator() : Doc(0) {}
535 document_iterator(OwningPtr<Document> &D) : Doc(&D) {}
537 bool operator ==(const document_iterator &Other) {
538 if (isAtEnd() || Other.isAtEnd())
539 return isAtEnd() && Other.isAtEnd();
541 return Doc == Other.Doc;
543 bool operator !=(const document_iterator &Other) {
544 return !(*this == Other);
547 document_iterator operator ++() {
548 assert(Doc != 0 && "incrementing iterator past the end.");
549 if (!(*Doc)->skip()) {
552 Stream &S = (*Doc)->stream;
553 Doc->reset(new Document(S));
558 Document &operator *() {
562 OwningPtr<Document> &operator ->() {
567 bool isAtEnd() const {
568 return !Doc || !*Doc;
571 OwningPtr<Document> *Doc;