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"
58 class document_iterator;
64 /// @brief Dump all the tokens in this stream to OS.
65 /// @returns true if there was an error, false otherwise.
66 bool dumpTokens(StringRef Input, raw_ostream &);
68 /// @brief Scans all tokens in input without outputting anything. This is used
69 /// for benchmarking the tokenizer.
70 /// @returns true if there was an error, false otherwise.
71 bool scanTokens(StringRef Input);
73 /// @brief Escape \a Input for a double quoted scalar.
74 std::string escape(StringRef Input);
76 /// @brief This class represents a YAML stream potentially containing multiple
80 /// @brief This keeps a reference to the string referenced by \p Input.
81 Stream(StringRef Input, SourceMgr &);
83 /// @brief This takes ownership of \p InputBuffer.
84 Stream(MemoryBuffer *InputBuffer, SourceMgr &);
87 document_iterator begin();
88 document_iterator end();
96 void printError(Node *N, const Twine &Msg);
99 OwningPtr<Scanner> scanner;
100 OwningPtr<Document> CurrentDoc;
102 friend class Document;
105 /// @brief Abstract base class for all Nodes.
107 virtual void anchor();
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 {
178 virtual void anchor();
180 NullNode(OwningPtr<Document> &D)
181 : Node(NK_Null, D, StringRef(), StringRef()) {}
183 static inline bool classof(const Node *N) {
184 return N->getType() == NK_Null;
188 /// @brief A scalar node is an opaque datum that can be presented as a
189 /// series of zero or more Unicode scalar values.
193 class ScalarNode : public Node {
194 virtual void anchor();
196 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
198 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
199 SMLoc Start = SMLoc::getFromPointer(Val.begin());
200 SMLoc End = SMLoc::getFromPointer(Val.end());
201 SourceRange = SMRange(Start, End);
204 // Return Value without any escaping or folding or other fun YAML stuff. This
205 // is the exact bytes that are contained in the file (after conversion to
207 StringRef getRawValue() const { return Value; }
209 /// @brief Gets the value of this node as a StringRef.
211 /// @param Storage is used to store the content of the returned StringRef iff
212 /// it requires any modification from how it appeared in the source.
213 /// This happens with escaped characters and multi-line literals.
214 StringRef getValue(SmallVectorImpl<char> &Storage) const;
216 static inline bool classof(const Node *N) {
217 return N->getType() == NK_Scalar;
223 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
224 , StringRef::size_type Start
225 , SmallVectorImpl<char> &Storage) const;
228 /// @brief A key and value pair. While not technically a Node under the YAML
229 /// representation graph, it is easier to treat them this way.
231 /// TODO: Consider making this not a child of Node.
235 class KeyValueNode : public Node {
236 virtual void anchor();
238 KeyValueNode(OwningPtr<Document> &D)
239 : Node(NK_KeyValue, D, StringRef(), StringRef())
244 /// @brief Parse and return the key.
246 /// This may be called multiple times.
248 /// @returns The key, or nullptr if failed() == true.
251 /// @brief Parse and return the value.
253 /// This may be called multiple times.
255 /// @returns The value, or nullptr if failed() == true.
258 virtual void skip() override {
263 static inline bool classof(const Node *N) {
264 return N->getType() == NK_KeyValue;
272 /// @brief This is an iterator abstraction over YAML collections shared by both
273 /// sequences and maps.
275 /// BaseT must have a ValueT* member named CurrentEntry and a member function
276 /// increment() which must set CurrentEntry to 0 to create an end iterator.
277 template <class BaseT, class ValueT>
278 class basic_collection_iterator
279 : public std::iterator<std::forward_iterator_tag, ValueT> {
281 basic_collection_iterator() : Base(0) {}
282 basic_collection_iterator(BaseT *B) : Base(B) {}
284 ValueT *operator ->() const {
285 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
286 return Base->CurrentEntry;
289 ValueT &operator *() const {
290 assert(Base && Base->CurrentEntry &&
291 "Attempted to dereference end iterator!");
292 return *Base->CurrentEntry;
295 operator ValueT*() const {
296 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
297 return Base->CurrentEntry;
300 bool operator !=(const basic_collection_iterator &Other) const {
301 if(Base != Other.Base)
303 return (Base && Other.Base) && Base->CurrentEntry
304 != Other.Base->CurrentEntry;
307 basic_collection_iterator &operator++() {
308 assert(Base && "Attempted to advance iterator past end!");
310 // Create an end iterator.
311 if (Base->CurrentEntry == 0)
320 // The following two templates are used for both MappingNode and Sequence Node.
321 template <class CollectionType>
322 typename CollectionType::iterator begin(CollectionType &C) {
323 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
324 C.IsAtBeginning = false;
325 typename CollectionType::iterator ret(&C);
330 template <class CollectionType>
331 void skip(CollectionType &C) {
332 // TODO: support skipping from the middle of a parsed collection ;/
333 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
335 for (typename CollectionType::iterator i = begin(C), e = C.end();
340 /// @brief Represents a YAML map created from either a block map for a flow map.
342 /// This parses the YAML stream as increment() is called.
347 class MappingNode : public Node {
348 virtual void anchor();
353 MT_Inline ///< An inline mapping node is used for "[key: value]".
356 MappingNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
358 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
359 IsAtEnd(false), CurrentEntry(0) {}
361 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
362 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
363 template <class T> friend typename T::iterator yaml::begin(T &);
364 template <class T> friend void yaml::skip(T &);
367 return yaml::begin(*this);
370 iterator end() { return iterator(); }
372 virtual void skip() override {
376 static inline bool classof(const Node *N) {
377 return N->getType() == NK_Mapping;
384 KeyValueNode *CurrentEntry;
389 /// @brief Represents a YAML sequence created from either a block sequence for a
392 /// This parses the YAML stream as increment() is called.
397 class SequenceNode : public Node {
398 virtual void anchor();
409 // As a BlockMappingEntry and BlockEnd are not created in this case.
413 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Tag,
415 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true),
417 WasPreviousTokenFlowEntry(true), // Start with an imaginary ','.
420 friend class basic_collection_iterator<SequenceNode, Node>;
421 typedef basic_collection_iterator<SequenceNode, Node> iterator;
422 template <class T> friend typename T::iterator yaml::begin(T &);
423 template <class T> friend void yaml::skip(T &);
428 return yaml::begin(*this);
431 iterator end() { return iterator(); }
433 virtual void skip() override {
437 static inline bool classof(const Node *N) {
438 return N->getType() == NK_Sequence;
442 SequenceType SeqType;
445 bool WasPreviousTokenFlowEntry;
449 /// @brief Represents an alias to a Node with an anchor.
453 class AliasNode : public Node {
454 virtual void anchor();
456 AliasNode(OwningPtr<Document> &D, StringRef Val)
457 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
459 StringRef getName() const { return Name; }
462 static inline bool classof(const Node *N) {
463 return N->getType() == NK_Alias;
470 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
474 /// @brief Root for parsing a node. Returns a single node.
475 Node *parseBlockNode();
477 Document(Stream &ParentStream);
479 /// @brief Finish parsing the current document and return true if there are
480 /// more. Return false otherwise.
483 /// @brief Parse and return the root level node.
487 return Root = parseBlockNode();
490 const std::map<StringRef, StringRef> &getTagMap() const {
496 friend class document_iterator;
498 /// @brief Stream to read tokens from.
501 /// @brief Used to allocate nodes to. All are destroyed without calling their
502 /// destructor when the document is destroyed.
503 BumpPtrAllocator NodeAllocator;
505 /// @brief The root node. Used to support skipping a partially parsed
509 /// \brief Maps tag prefixes to their expansion.
510 std::map<StringRef, StringRef> TagMap;
514 void setError(const Twine &Message, Token &Location) const;
517 /// @brief Parse %BLAH directives and return true if any were encountered.
518 bool parseDirectives();
520 /// \brief Parse %YAML
521 void parseYAMLDirective();
523 /// \brief Parse %TAG
524 void parseTAGDirective();
526 /// @brief Consume the next token and error if it is not \a TK.
527 bool expectToken(int TK);
530 /// @brief Iterator abstraction for Documents over a Stream.
531 class document_iterator {
533 document_iterator() : Doc(0) {}
534 document_iterator(OwningPtr<Document> &D) : Doc(&D) {}
536 bool operator ==(const document_iterator &Other) {
537 if (isAtEnd() || Other.isAtEnd())
538 return isAtEnd() && Other.isAtEnd();
540 return Doc == Other.Doc;
542 bool operator !=(const document_iterator &Other) {
543 return !(*this == Other);
546 document_iterator operator ++() {
547 assert(Doc != 0 && "incrementing iterator past the end.");
548 if (!(*Doc)->skip()) {
551 Stream &S = (*Doc)->stream;
552 Doc->reset(new Document(S));
557 Document &operator *() {
561 OwningPtr<Document> &operator ->() {
566 bool isAtEnd() const {
567 return !Doc || !*Doc;
570 OwningPtr<Document> *Doc;