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;
157 /// @brief A null value.
161 class NullNode : public Node {
163 NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
165 static inline bool classof(const NullNode *) { return true; }
166 static inline bool classof(const Node *N) {
167 return N->getType() == NK_Null;
171 /// @brief A scalar node is an opaque datum that can be presented as a
172 /// series of zero or more Unicode scalar values.
176 class ScalarNode : public Node {
178 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
179 : Node(NK_Scalar, D, Anchor)
181 SMLoc Start = SMLoc::getFromPointer(Val.begin());
182 SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
183 SourceRange = SMRange(Start, End);
186 // Return Value without any escaping or folding or other fun YAML stuff. This
187 // is the exact bytes that are contained in the file (after conversion to
189 StringRef getRawValue() const { return Value; }
191 /// @brief Gets the value of this node as a StringRef.
193 /// @param Storage is used to store the content of the returned StringRef iff
194 /// it requires any modification from how it appeared in the source.
195 /// This happens with escaped characters and multi-line literals.
196 StringRef getValue(SmallVectorImpl<char> &Storage) const;
198 static inline bool classof(const ScalarNode *) { return true; }
199 static inline bool classof(const Node *N) {
200 return N->getType() == NK_Scalar;
206 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
207 , StringRef::size_type Start
208 , SmallVectorImpl<char> &Storage) const;
211 /// @brief A key and value pair. While not technically a Node under the YAML
212 /// representation graph, it is easier to treat them this way.
214 /// TODO: Consider making this not a child of Node.
218 class KeyValueNode : public Node {
220 KeyValueNode(OwningPtr<Document> &D)
221 : Node(NK_KeyValue, D, StringRef())
226 /// @brief Parse and return the key.
228 /// This may be called multiple times.
230 /// @returns The key, or nullptr if failed() == true.
233 /// @brief Parse and return the value.
235 /// This may be called multiple times.
237 /// @returns The value, or nullptr if failed() == true.
240 virtual void skip() {
245 static inline bool classof(const KeyValueNode *) { return true; }
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() {
361 static inline bool classof(const MappingNode *) { return true; }
362 static inline bool classof(const Node *N) {
363 return N->getType() == NK_Mapping;
370 KeyValueNode *CurrentEntry;
375 /// @brief Represents a YAML sequence created from either a block sequence for a
378 /// This parses the YAML stream as increment() is called.
383 class SequenceNode : public Node {
394 // As a BlockMappingEntry and BlockEnd are not created in this case.
398 SequenceNode(OwningPtr<Document> &D, StringRef Anchor, SequenceType ST)
399 : Node(NK_Sequence, D, Anchor)
401 , IsAtBeginning(true)
403 , WasPreviousTokenFlowEntry(true) // Start with an imaginary ','.
407 friend class basic_collection_iterator<SequenceNode, Node>;
408 typedef basic_collection_iterator<SequenceNode, Node> iterator;
409 template <class T> friend typename T::iterator yaml::begin(T &);
410 template <class T> friend void yaml::skip(T &);
415 return yaml::begin(*this);
418 iterator end() { return iterator(); }
420 virtual void skip() {
424 static inline bool classof(const SequenceNode *) { return true; }
425 static inline bool classof(const Node *N) {
426 return N->getType() == NK_Sequence;
430 SequenceType SeqType;
433 bool WasPreviousTokenFlowEntry;
437 /// @brief Represents an alias to a Node with an anchor.
441 class AliasNode : public Node {
443 AliasNode(OwningPtr<Document> &D, StringRef Val)
444 : Node(NK_Alias, D, StringRef()), Name(Val) {}
446 StringRef getName() const { return Name; }
449 static inline bool classof(const ScalarNode *) { return true; }
450 static inline bool classof(const Node *N) {
451 return N->getType() == NK_Alias;
458 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
462 /// @brief Root for parsing a node. Returns a single node.
463 Node *parseBlockNode();
465 Document(Stream &ParentStream);
467 /// @brief Finish parsing the current document and return true if there are
468 /// more. Return false otherwise.
471 /// @brief Parse and return the root level node.
475 return Root = parseBlockNode();
480 friend class document_iterator;
482 /// @brief Stream to read tokens from.
485 /// @brief Used to allocate nodes to. All are destroyed without calling their
486 /// destructor when the document is destroyed.
487 BumpPtrAllocator NodeAllocator;
489 /// @brief The root node. Used to support skipping a partially parsed
495 void setError(const Twine &Message, Token &Location) const;
498 void handleTagDirective(const Token &Tag) {
502 /// @brief Parse %BLAH directives and return true if any were encountered.
503 bool parseDirectives();
505 /// @brief Consume the next token and error if it is not \a TK.
506 bool expectToken(int TK);
509 /// @brief Iterator abstraction for Documents over a Stream.
510 class document_iterator {
512 document_iterator() : Doc(NullDoc) {}
513 document_iterator(OwningPtr<Document> &D) : Doc(D) {}
515 bool operator !=(const document_iterator &Other) {
516 return Doc != Other.Doc;
519 document_iterator operator ++() {
523 Stream &S = Doc->stream;
524 Doc.reset(new Document(S));
529 Document &operator *() {
533 OwningPtr<Document> &operator ->() {
538 static OwningPtr<Document> NullDoc;
539 OwningPtr<Document> &Doc;