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 &);
82 document_iterator begin();
83 document_iterator end();
91 void printError(Node *N, const Twine &Msg);
94 OwningPtr<Scanner> scanner;
95 OwningPtr<Document> CurrentDoc;
97 friend class Document;
99 /// @brief Validate a %YAML x.x directive.
100 void handleYAMLDirective(const Token &);
103 /// @brief Abstract base class for all Nodes.
115 Node(unsigned int Type, OwningPtr<Document>&, StringRef Anchor);
117 /// @brief Get the value of the anchor attached to this node. If it does not
118 /// have one, getAnchor().size() will be 0.
119 StringRef getAnchor() const { return Anchor; }
121 SMRange getSourceRange() const { return SourceRange; }
122 void setSourceRange(SMRange SR) { SourceRange = SR; }
124 // These functions forward to Document and Scanner.
127 Node *parseBlockNode();
128 BumpPtrAllocator &getAllocator();
129 void setError(const Twine &Message, Token &Location) const;
132 virtual void skip() {};
134 unsigned int getType() const { return TypeID; }
135 static inline bool classof(const Node *) { return true; }
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;
156 /// @brief A null value.
160 class NullNode : public Node {
162 NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
164 static inline bool classof(const NullNode *) { return true; }
165 static inline bool classof(const Node *N) {
166 return N->getType() == NK_Null;
170 /// @brief A scalar node is an opaque datum that can be presented as a
171 /// series of zero or more Unicode scalar values.
175 class ScalarNode : public Node {
177 ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
178 : Node(NK_Scalar, D, Anchor)
180 SMLoc Start = SMLoc::getFromPointer(Val.begin());
181 SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
182 SourceRange = SMRange(Start, End);
185 // Return Value without any escaping or folding or other fun YAML stuff. This
186 // is the exact bytes that are contained in the file (after conversion to
188 StringRef getRawValue() const { return Value; }
190 /// @brief Gets the value of this node as a StringRef.
192 /// @param Storage is used to store the content of the returned StringRef iff
193 /// it requires any modification from how it appeared in the source.
194 /// This happens with escaped characters and multi-line literals.
195 StringRef getValue(SmallVectorImpl<char> &Storage) const;
197 static inline bool classof(const ScalarNode *) { return true; }
198 static inline bool classof(const Node *N) {
199 return N->getType() == NK_Scalar;
205 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
206 , StringRef::size_type Start
207 , SmallVectorImpl<char> &Storage) const;
210 /// @brief A key and value pair. While not technically a Node under the YAML
211 /// representation graph, it is easier to treat them this way.
213 /// TODO: Consider making this not a child of Node.
217 class KeyValueNode : public Node {
219 KeyValueNode(OwningPtr<Document> &D)
220 : Node(NK_KeyValue, D, StringRef())
225 /// @brief Parse and return the key.
227 /// This may be called multiple times.
229 /// @returns The key, or nullptr if failed() == true.
232 /// @brief Parse and return the value.
234 /// This may be called multiple times.
236 /// @returns The value, or nullptr if failed() == true.
239 virtual void skip() {
244 static inline bool classof(const KeyValueNode *) { return true; }
245 static inline bool classof(const Node *N) {
246 return N->getType() == NK_KeyValue;
254 /// @brief This is an iterator abstraction over YAML collections shared by both
255 /// sequences and maps.
257 /// BaseT must have a ValueT* member named CurrentEntry and a member function
258 /// increment() which must set CurrentEntry to 0 to create an end iterator.
259 template <class BaseT, class ValueT>
260 class basic_collection_iterator
261 : public std::iterator<std::forward_iterator_tag, ValueT> {
263 basic_collection_iterator() : Base(0) {}
264 basic_collection_iterator(BaseT *B) : Base(B) {}
266 ValueT *operator ->() const {
267 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
268 return Base->CurrentEntry;
271 ValueT &operator *() const {
272 assert(Base && Base->CurrentEntry &&
273 "Attempted to dereference end iterator!");
274 return *Base->CurrentEntry;
277 operator ValueT*() const {
278 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
279 return Base->CurrentEntry;
282 bool operator !=(const basic_collection_iterator &Other) const {
283 if(Base != Other.Base)
285 return (Base && Other.Base) && Base->CurrentEntry
286 != Other.Base->CurrentEntry;
289 basic_collection_iterator &operator++() {
290 assert(Base && "Attempted to advance iterator past end!");
292 // Create an end iterator.
293 if (Base->CurrentEntry == 0)
302 // The following two templates are used for both MappingNode and Sequence Node.
303 template <class CollectionType>
304 typename CollectionType::iterator begin(CollectionType &C) {
305 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
306 C.IsAtBeginning = false;
307 typename CollectionType::iterator ret(&C);
312 template <class CollectionType>
313 void skip(CollectionType &C) {
314 // TODO: support skipping from the middle of a parsed collection ;/
315 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
317 for (typename CollectionType::iterator i = begin(C), e = C.end();
322 /// @brief Represents a YAML map created from either a block map for a flow map.
324 /// This parses the YAML stream as increment() is called.
329 class MappingNode : public Node {
334 MT_Inline //< An inline mapping node is used for "[key: value]".
337 MappingNode(OwningPtr<Document> &D, StringRef Anchor, MappingType MT)
338 : Node(NK_Mapping, D, Anchor)
340 , IsAtBeginning(true)
345 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
346 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
347 template <class T> friend typename T::iterator yaml::begin(T &);
348 template <class T> friend void yaml::skip(T &);
351 return yaml::begin(*this);
354 iterator end() { return iterator(); }
356 virtual void skip() {
360 static inline bool classof(const MappingNode *) { return true; }
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() {
423 static inline bool classof(const SequenceNode *) { return true; }
424 static inline bool classof(const Node *N) {
425 return N->getType() == NK_Sequence;
429 SequenceType SeqType;
432 bool WasPreviousTokenFlowEntry;
436 /// @brief Represents an alias to a Node with an anchor.
440 class AliasNode : public Node {
442 AliasNode(OwningPtr<Document> &D, StringRef Val)
443 : Node(NK_Alias, D, StringRef()), Name(Val) {}
445 StringRef getName() const { return Name; }
448 static inline bool classof(const ScalarNode *) { return true; }
449 static inline bool classof(const Node *N) {
450 return N->getType() == NK_Alias;
457 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
461 /// @brief Root for parsing a node. Returns a single node.
462 Node *parseBlockNode();
464 Document(Stream &ParentStream);
466 /// @brief Finish parsing the current document and return true if there are
467 /// more. Return false otherwise.
470 /// @brief Parse and return the root level node.
474 return Root = parseBlockNode();
479 friend class document_iterator;
481 /// @brief Stream to read tokens from.
484 /// @brief Used to allocate nodes to. All are destroyed without calling their
485 /// destructor when the document is destroyed.
486 BumpPtrAllocator NodeAllocator;
488 /// @brief The root node. Used to support skipping a partially parsed
494 void setError(const Twine &Message, Token &Location) const;
497 void handleTagDirective(const Token &Tag) {
501 /// @brief Parse %BLAH directives and return true if any were encountered.
502 bool parseDirectives();
504 /// @brief Consume the next token and error if it is not \a TK.
505 bool expectToken(int TK);
508 /// @brief Iterator abstraction for Documents over a Stream.
509 class document_iterator {
511 document_iterator() : Doc(NullDoc) {}
512 document_iterator(OwningPtr<Document> &D) : Doc(D) {}
514 bool operator !=(const document_iterator &Other) {
515 return Doc != Other.Doc;
518 document_iterator operator ++() {
522 Stream &S = Doc->stream;
523 Doc.reset(new Document(S));
528 Document &operator *() {
532 OwningPtr<Document> &operator ->() {
537 static OwningPtr<Document> NullDoc;
538 OwningPtr<Document> &Doc;