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_YAML_PARSER_H
39 #define LLVM_SUPPORT_YAML_PARSER_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 Stream(StringRef Input, SourceMgr &);
83 document_iterator begin();
84 document_iterator end();
92 void printError(Node *N, const Twine &Msg);
95 OwningPtr<Scanner> scanner;
96 OwningPtr<Document> CurrentDoc;
98 friend class Document;
100 /// @brief Validate a %YAML x.x directive.
101 void handleYAMLDirective(const Token &);
104 /// @brief Abstract base class for all Nodes.
116 Node(unsigned int Type, OwningPtr<Document>&, StringRef Anchor);
118 /// @brief Get the value of the anchor attached to this node. If it does not
119 /// have one, getAnchor().size() will be 0.
120 StringRef getAnchor() const { return Anchor; }
122 SMRange getSourceRange() const { return SourceRange; }
123 void setSourceRange(SMRange SR) { SourceRange = SR; }
125 // These functions forward to Document and Scanner.
128 Node *parseBlockNode();
129 BumpPtrAllocator &getAllocator();
130 void setError(const Twine &Message, Token &Location) const;
133 virtual void skip() {}
135 unsigned int getType() const { return TypeID; }
137 void *operator new ( size_t Size
138 , BumpPtrAllocator &Alloc
139 , size_t Alignment = 16) throw() {
140 return Alloc.Allocate(Size, Alignment);
143 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
144 Alloc.Deallocate(Ptr);
148 OwningPtr<Document> &Doc;
151 void operator delete(void *) throw() {}
160 /// @brief A null value.
164 class NullNode : public Node {
166 NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
168 static inline bool classof(const Node *N) {
169 return N->getType() == NK_Null;
173 /// @brief A scalar node is an opaque datum that can be presented as a
174 /// series of zero or more Unicode scalar values.
178 class ScalarNode : public Node {
180 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
181 : Node(NK_Scalar, D, Anchor)
183 SMLoc Start = SMLoc::getFromPointer(Val.begin());
184 SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
185 SourceRange = SMRange(Start, End);
188 // Return Value without any escaping or folding or other fun YAML stuff. This
189 // is the exact bytes that are contained in the file (after conversion to
191 StringRef getRawValue() const { return Value; }
193 /// @brief Gets the value of this node as a StringRef.
195 /// @param Storage is used to store the content of the returned StringRef iff
196 /// it requires any modification from how it appeared in the source.
197 /// This happens with escaped characters and multi-line literals.
198 StringRef getValue(SmallVectorImpl<char> &Storage) const;
200 static inline bool classof(const Node *N) {
201 return N->getType() == NK_Scalar;
207 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
208 , StringRef::size_type Start
209 , SmallVectorImpl<char> &Storage) const;
212 /// @brief A key and value pair. While not technically a Node under the YAML
213 /// representation graph, it is easier to treat them this way.
215 /// TODO: Consider making this not a child of Node.
219 class KeyValueNode : public Node {
221 KeyValueNode(OwningPtr<Document> &D)
222 : Node(NK_KeyValue, D, StringRef())
227 /// @brief Parse and return the key.
229 /// This may be called multiple times.
231 /// @returns The key, or nullptr if failed() == true.
234 /// @brief Parse and return the value.
236 /// This may be called multiple times.
238 /// @returns The value, or nullptr if failed() == true.
241 virtual void skip() LLVM_OVERRIDE {
246 static inline bool classof(const Node *N) {
247 return N->getType() == NK_KeyValue;
255 /// @brief This is an iterator abstraction over YAML collections shared by both
256 /// sequences and maps.
258 /// BaseT must have a ValueT* member named CurrentEntry and a member function
259 /// increment() which must set CurrentEntry to 0 to create an end iterator.
260 template <class BaseT, class ValueT>
261 class basic_collection_iterator
262 : public std::iterator<std::forward_iterator_tag, ValueT> {
264 basic_collection_iterator() : Base(0) {}
265 basic_collection_iterator(BaseT *B) : Base(B) {}
267 ValueT *operator ->() const {
268 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
269 return Base->CurrentEntry;
272 ValueT &operator *() const {
273 assert(Base && Base->CurrentEntry &&
274 "Attempted to dereference end iterator!");
275 return *Base->CurrentEntry;
278 operator ValueT*() const {
279 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
280 return Base->CurrentEntry;
283 bool operator !=(const basic_collection_iterator &Other) const {
284 if(Base != Other.Base)
286 return (Base && Other.Base) && Base->CurrentEntry
287 != Other.Base->CurrentEntry;
290 basic_collection_iterator &operator++() {
291 assert(Base && "Attempted to advance iterator past end!");
293 // Create an end iterator.
294 if (Base->CurrentEntry == 0)
303 // The following two templates are used for both MappingNode and Sequence Node.
304 template <class CollectionType>
305 typename CollectionType::iterator begin(CollectionType &C) {
306 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
307 C.IsAtBeginning = false;
308 typename CollectionType::iterator ret(&C);
313 template <class CollectionType>
314 void skip(CollectionType &C) {
315 // TODO: support skipping from the middle of a parsed collection ;/
316 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
318 for (typename CollectionType::iterator i = begin(C), e = C.end();
323 /// @brief Represents a YAML map created from either a block map for a flow map.
325 /// This parses the YAML stream as increment() is called.
330 class MappingNode : public Node {
335 MT_Inline ///< An inline mapping node is used for "[key: value]".
338 MappingNode(OwningPtr<Document> &D, StringRef Anchor, MappingType MT)
339 : Node(NK_Mapping, D, Anchor)
341 , IsAtBeginning(true)
346 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
347 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
348 template <class T> friend typename T::iterator yaml::begin(T &);
349 template <class T> friend void yaml::skip(T &);
352 return yaml::begin(*this);
355 iterator end() { return iterator(); }
357 virtual void skip() LLVM_OVERRIDE {
361 static inline bool classof(const Node *N) {
362 return N->getType() == NK_Mapping;
369 KeyValueNode *CurrentEntry;
374 /// @brief Represents a YAML sequence created from either a block sequence for a
377 /// This parses the YAML stream as increment() is called.
382 class SequenceNode : public Node {
393 // As a BlockMappingEntry and BlockEnd are not created in this case.
397 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, SequenceType ST)
398 : Node(NK_Sequence, D, Anchor)
400 , IsAtBeginning(true)
402 , WasPreviousTokenFlowEntry(true) // Start with an imaginary ','.
406 friend class basic_collection_iterator<SequenceNode, Node>;
407 typedef basic_collection_iterator<SequenceNode, Node> iterator;
408 template <class T> friend typename T::iterator yaml::begin(T &);
409 template <class T> friend void yaml::skip(T &);
414 return yaml::begin(*this);
417 iterator end() { return iterator(); }
419 virtual void skip() LLVM_OVERRIDE {
423 static inline bool classof(const Node *N) {
424 return N->getType() == NK_Sequence;
428 SequenceType SeqType;
431 bool WasPreviousTokenFlowEntry;
435 /// @brief Represents an alias to a Node with an anchor.
439 class AliasNode : public Node {
441 AliasNode(OwningPtr<Document> &D, StringRef Val)
442 : Node(NK_Alias, D, StringRef()), Name(Val) {}
444 StringRef getName() const { return Name; }
447 static inline bool classof(const Node *N) {
448 return N->getType() == NK_Alias;
455 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
459 /// @brief Root for parsing a node. Returns a single node.
460 Node *parseBlockNode();
462 Document(Stream &ParentStream);
464 /// @brief Finish parsing the current document and return true if there are
465 /// more. Return false otherwise.
468 /// @brief Parse and return the root level node.
472 return Root = parseBlockNode();
477 friend class document_iterator;
479 /// @brief Stream to read tokens from.
482 /// @brief Used to allocate nodes to. All are destroyed without calling their
483 /// destructor when the document is destroyed.
484 BumpPtrAllocator NodeAllocator;
486 /// @brief The root node. Used to support skipping a partially parsed
492 void setError(const Twine &Message, Token &Location) const;
495 void handleTagDirective(const Token &Tag) {
499 /// @brief Parse %BLAH directives and return true if any were encountered.
500 bool parseDirectives();
502 /// @brief Consume the next token and error if it is not \a TK.
503 bool expectToken(int TK);
506 /// @brief Iterator abstraction for Documents over a Stream.
507 class document_iterator {
509 document_iterator() : Doc(0) {}
510 document_iterator(OwningPtr<Document> &D) : Doc(&D) {}
512 bool operator ==(const document_iterator &Other) {
513 if (isAtEnd() || Other.isAtEnd())
514 return isAtEnd() && Other.isAtEnd();
516 return *Doc == *Other.Doc;
518 bool operator !=(const document_iterator &Other) {
519 return !(*this == Other);
522 document_iterator operator ++() {
523 assert(Doc != 0 && "incrementing iterator past the end.");
524 if (!(*Doc)->skip()) {
527 Stream &S = (*Doc)->stream;
528 Doc->reset(new Document(S));
533 Document &operator *() {
537 OwningPtr<Document> &operator ->() {
542 bool isAtEnd() const {
543 return Doc == 0 || *Doc == 0;
546 OwningPtr<Document> *Doc;