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; }
136 static inline bool classof(const Node *) { return true; }
138 void *operator new ( size_t Size
139 , BumpPtrAllocator &Alloc
140 , size_t Alignment = 16) throw() {
141 return Alloc.Allocate(Size, Alignment);
144 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
145 Alloc.Deallocate(Ptr);
149 OwningPtr<Document> &Doc;
159 /// @brief A null value.
163 class NullNode : public Node {
165 NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
167 static inline bool classof(const NullNode *) { return true; }
168 static inline bool classof(const Node *N) {
169 return N->getType() == NK_Null;
176 /// @brief A scalar node is an opaque datum that can be presented as a
177 /// series of zero or more Unicode scalar values.
181 class ScalarNode : public Node {
183 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
184 : Node(NK_Scalar, D, Anchor)
186 SMLoc Start = SMLoc::getFromPointer(Val.begin());
187 SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
188 SourceRange = SMRange(Start, End);
191 // Return Value without any escaping or folding or other fun YAML stuff. This
192 // is the exact bytes that are contained in the file (after conversion to
194 StringRef getRawValue() const { return Value; }
196 /// @brief Gets the value of this node as a StringRef.
198 /// @param Storage is used to store the content of the returned StringRef iff
199 /// it requires any modification from how it appeared in the source.
200 /// This happens with escaped characters and multi-line literals.
201 StringRef getValue(SmallVectorImpl<char> &Storage) const;
203 static inline bool classof(const ScalarNode *) { return true; }
204 static inline bool classof(const Node *N) {
205 return N->getType() == NK_Scalar;
209 virtual ~ScalarNode();
214 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
215 , StringRef::size_type Start
216 , SmallVectorImpl<char> &Storage) const;
219 /// @brief A key and value pair. While not technically a Node under the YAML
220 /// representation graph, it is easier to treat them this way.
222 /// TODO: Consider making this not a child of Node.
226 class KeyValueNode : public Node {
228 KeyValueNode(OwningPtr<Document> &D)
229 : Node(NK_KeyValue, D, StringRef())
234 /// @brief Parse and return the key.
236 /// This may be called multiple times.
238 /// @returns The key, or nullptr if failed() == true.
241 /// @brief Parse and return the value.
243 /// This may be called multiple times.
245 /// @returns The value, or nullptr if failed() == true.
248 virtual void skip() {
253 static inline bool classof(const KeyValueNode *) { return true; }
254 static inline bool classof(const Node *N) {
255 return N->getType() == NK_KeyValue;
259 virtual ~KeyValueNode();
266 /// @brief This is an iterator abstraction over YAML collections shared by both
267 /// sequences and maps.
269 /// BaseT must have a ValueT* member named CurrentEntry and a member function
270 /// increment() which must set CurrentEntry to 0 to create an end iterator.
271 template <class BaseT, class ValueT>
272 class basic_collection_iterator
273 : public std::iterator<std::forward_iterator_tag, ValueT> {
275 basic_collection_iterator() : Base(0) {}
276 basic_collection_iterator(BaseT *B) : Base(B) {}
278 ValueT *operator ->() const {
279 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
280 return Base->CurrentEntry;
283 ValueT &operator *() const {
284 assert(Base && Base->CurrentEntry &&
285 "Attempted to dereference end iterator!");
286 return *Base->CurrentEntry;
289 operator ValueT*() const {
290 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
291 return Base->CurrentEntry;
294 bool operator !=(const basic_collection_iterator &Other) const {
295 if(Base != Other.Base)
297 return (Base && Other.Base) && Base->CurrentEntry
298 != Other.Base->CurrentEntry;
301 basic_collection_iterator &operator++() {
302 assert(Base && "Attempted to advance iterator past end!");
304 // Create an end iterator.
305 if (Base->CurrentEntry == 0)
314 // The following two templates are used for both MappingNode and Sequence Node.
315 template <class CollectionType>
316 typename CollectionType::iterator begin(CollectionType &C) {
317 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
318 C.IsAtBeginning = false;
319 typename CollectionType::iterator ret(&C);
324 template <class CollectionType>
325 void skip(CollectionType &C) {
326 // TODO: support skipping from the middle of a parsed collection ;/
327 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
329 for (typename CollectionType::iterator i = begin(C), e = C.end();
334 /// @brief Represents a YAML map created from either a block map for a flow map.
336 /// This parses the YAML stream as increment() is called.
341 class MappingNode : public Node {
346 MT_Inline //< An inline mapping node is used for "[key: value]".
349 MappingNode(OwningPtr<Document> &D, StringRef Anchor, MappingType MT)
350 : Node(NK_Mapping, D, Anchor)
352 , IsAtBeginning(true)
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() {
372 static inline bool classof(const MappingNode *) { return true; }
373 static inline bool classof(const Node *N) {
374 return N->getType() == NK_Mapping;
378 virtual ~MappingNode();
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 {
408 // As a BlockMappingEntry and BlockEnd are not created in this case.
412 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, SequenceType ST)
413 : Node(NK_Sequence, D, Anchor)
415 , IsAtBeginning(true)
417 , 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() {
438 static inline bool classof(const SequenceNode *) { return true; }
439 static inline bool classof(const Node *N) {
440 return N->getType() == NK_Sequence;
444 virtual ~SequenceNode();
447 SequenceType SeqType;
450 bool WasPreviousTokenFlowEntry;
454 /// @brief Represents an alias to a Node with an anchor.
458 class AliasNode : public Node {
460 AliasNode(OwningPtr<Document> &D, StringRef Val)
461 : Node(NK_Alias, D, StringRef()), Name(Val) {}
463 StringRef getName() const { return Name; }
466 static inline bool classof(const ScalarNode *) { return true; }
467 static inline bool classof(const Node *N) {
468 return N->getType() == NK_Alias;
472 virtual ~AliasNode();
478 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
482 /// @brief Root for parsing a node. Returns a single node.
483 Node *parseBlockNode();
485 Document(Stream &ParentStream);
487 /// @brief Finish parsing the current document and return true if there are
488 /// more. Return false otherwise.
491 /// @brief Parse and return the root level node.
495 return Root = parseBlockNode();
500 friend class document_iterator;
502 /// @brief Stream to read tokens from.
505 /// @brief Used to allocate nodes to. All are destroyed without calling their
506 /// destructor when the document is destroyed.
507 BumpPtrAllocator NodeAllocator;
509 /// @brief The root node. Used to support skipping a partially parsed
515 void setError(const Twine &Message, Token &Location) const;
518 void handleTagDirective(const Token &Tag) {
522 /// @brief Parse %BLAH directives and return true if any were encountered.
523 bool parseDirectives();
525 /// @brief Consume the next token and error if it is not \a TK.
526 bool expectToken(int TK);
529 /// @brief Iterator abstraction for Documents over a Stream.
530 class document_iterator {
532 document_iterator() : Doc(NullDoc) {}
533 document_iterator(OwningPtr<Document> &D) : Doc(D) {}
535 bool operator !=(const document_iterator &Other) {
536 return Doc != Other.Doc;
539 document_iterator operator ++() {
543 Stream &S = Doc->stream;
544 Doc.reset(new Document(S));
549 Document &operator *() {
553 OwningPtr<Document> &operator ->() {
558 static OwningPtr<Document> NullDoc;
559 OwningPtr<Document> &Doc;