Allow using MemoryBuffers with yaml::Stream directly.
[oota-llvm.git] / include / llvm / Support / YAMLParser.h
1 //===--- YAMLParser.h - Simple YAML parser --------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This is a YAML 1.2 parser.
11 //
12 //  See http://www.yaml.org/spec/1.2/spec.html for the full standard.
13 //
14 //  This currently does not implement the following:
15 //    * Multi-line literal folding.
16 //    * Tag resolution.
17 //    * UTF-16.
18 //    * BOMs anywhere other than the first Unicode scalar value in the file.
19 //
20 //  The most important class here is Stream. This represents a YAML stream with
21 //  0, 1, or many documents.
22 //
23 //  SourceMgr sm;
24 //  StringRef input = getInput();
25 //  yaml::Stream stream(input, sm);
26 //
27 //  for (yaml::document_iterator di = stream.begin(), de = stream.end();
28 //       di != de; ++di) {
29 //    yaml::Node *n = di->getRoot();
30 //    if (n) {
31 //      // Do something with n...
32 //    } else
33 //      break;
34 //  }
35 //
36 //===----------------------------------------------------------------------===//
37
38 #ifndef LLVM_SUPPORT_YAML_PARSER_H
39 #define LLVM_SUPPORT_YAML_PARSER_H
40
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"
46
47 #include <limits>
48 #include <utility>
49
50 namespace llvm {
51 class MemoryBuffer;
52 class SourceMgr;
53 class raw_ostream;
54 class Twine;
55
56 namespace yaml {
57
58 class document_iterator;
59 class Document;
60 class Node;
61 class Scanner;
62 struct Token;
63
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 &);
67
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);
72
73 /// @brief Escape \a Input for a double quoted scalar.
74 std::string escape(StringRef Input);
75
76 /// @brief This class represents a YAML stream potentially containing multiple
77 ///        documents.
78 class Stream {
79 public:
80   /// @brief This keeps a reference to the string referenced by \p Input.
81   Stream(StringRef Input, SourceMgr &);
82
83   /// @brief This takes ownership of \p InputBuffer.
84   Stream(MemoryBuffer *InputBuffer, SourceMgr &);
85   ~Stream();
86
87   document_iterator begin();
88   document_iterator end();
89   void skip();
90   bool failed();
91   bool validate() {
92     skip();
93     return !failed();
94   }
95
96   void printError(Node *N, const Twine &Msg);
97
98 private:
99   OwningPtr<Scanner> scanner;
100   OwningPtr<Document> CurrentDoc;
101
102   friend class Document;
103
104   /// @brief Validate a %YAML x.x directive.
105   void handleYAMLDirective(const Token &);
106 };
107
108 /// @brief Abstract base class for all Nodes.
109 class Node {
110 public:
111   enum NodeKind {
112     NK_Null,
113     NK_Scalar,
114     NK_KeyValue,
115     NK_Mapping,
116     NK_Sequence,
117     NK_Alias
118   };
119
120   Node(unsigned int Type, OwningPtr<Document>&, StringRef Anchor);
121
122   /// @brief Get the value of the anchor attached to this node. If it does not
123   ///        have one, getAnchor().size() will be 0.
124   StringRef getAnchor() const { return Anchor; }
125
126   SMRange getSourceRange() const { return SourceRange; }
127   void setSourceRange(SMRange SR) { SourceRange = SR; }
128
129   // These functions forward to Document and Scanner.
130   Token &peekNext();
131   Token getNext();
132   Node *parseBlockNode();
133   BumpPtrAllocator &getAllocator();
134   void setError(const Twine &Message, Token &Location) const;
135   bool failed() const;
136
137   virtual void skip() {}
138
139   unsigned int getType() const { return TypeID; }
140
141   void *operator new ( size_t Size
142                      , BumpPtrAllocator &Alloc
143                      , size_t Alignment = 16) throw() {
144     return Alloc.Allocate(Size, Alignment);
145   }
146
147   void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
148     Alloc.Deallocate(Ptr);
149   }
150
151 protected:
152   OwningPtr<Document> &Doc;
153   SMRange SourceRange;
154
155   void operator delete(void *) throw() {}
156
157   virtual ~Node() {}
158
159 private:
160   unsigned int TypeID;
161   StringRef Anchor;
162 };
163
164 /// @brief A null value.
165 ///
166 /// Example:
167 ///   !!null null
168 class NullNode : public Node {
169 public:
170   NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
171
172   static inline bool classof(const Node *N) {
173     return N->getType() == NK_Null;
174   }
175 };
176
177 /// @brief A scalar node is an opaque datum that can be presented as a
178 ///        series of zero or more Unicode scalar values.
179 ///
180 /// Example:
181 ///   Adena
182 class ScalarNode : public Node {
183 public:
184   ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
185     : Node(NK_Scalar, D, Anchor)
186     , Value(Val) {
187     SMLoc Start = SMLoc::getFromPointer(Val.begin());
188     SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
189     SourceRange = SMRange(Start, End);
190   }
191
192   // Return Value without any escaping or folding or other fun YAML stuff. This
193   // is the exact bytes that are contained in the file (after conversion to
194   // utf8).
195   StringRef getRawValue() const { return Value; }
196
197   /// @brief Gets the value of this node as a StringRef.
198   ///
199   /// @param Storage is used to store the content of the returned StringRef iff
200   ///        it requires any modification from how it appeared in the source.
201   ///        This happens with escaped characters and multi-line literals.
202   StringRef getValue(SmallVectorImpl<char> &Storage) const;
203
204   static inline bool classof(const Node *N) {
205     return N->getType() == NK_Scalar;
206   }
207
208 private:
209   StringRef Value;
210
211   StringRef unescapeDoubleQuoted( StringRef UnquotedValue
212                                 , StringRef::size_type Start
213                                 , SmallVectorImpl<char> &Storage) const;
214 };
215
216 /// @brief A key and value pair. While not technically a Node under the YAML
217 ///        representation graph, it is easier to treat them this way.
218 ///
219 /// TODO: Consider making this not a child of Node.
220 ///
221 /// Example:
222 ///   Section: .text
223 class KeyValueNode : public Node {
224 public:
225   KeyValueNode(OwningPtr<Document> &D)
226     : Node(NK_KeyValue, D, StringRef())
227     , Key(0)
228     , Value(0)
229   {}
230
231   /// @brief Parse and return the key.
232   ///
233   /// This may be called multiple times.
234   ///
235   /// @returns The key, or nullptr if failed() == true.
236   Node *getKey();
237
238   /// @brief Parse and return the value.
239   ///
240   /// This may be called multiple times.
241   ///
242   /// @returns The value, or nullptr if failed() == true.
243   Node *getValue();
244
245   virtual void skip() LLVM_OVERRIDE {
246     getKey()->skip();
247     getValue()->skip();
248   }
249
250   static inline bool classof(const Node *N) {
251     return N->getType() == NK_KeyValue;
252   }
253
254 private:
255   Node *Key;
256   Node *Value;
257 };
258
259 /// @brief This is an iterator abstraction over YAML collections shared by both
260 ///        sequences and maps.
261 ///
262 /// BaseT must have a ValueT* member named CurrentEntry and a member function
263 /// increment() which must set CurrentEntry to 0 to create an end iterator.
264 template <class BaseT, class ValueT>
265 class basic_collection_iterator
266   : public std::iterator<std::forward_iterator_tag, ValueT> {
267 public:
268   basic_collection_iterator() : Base(0) {}
269   basic_collection_iterator(BaseT *B) : Base(B) {}
270
271   ValueT *operator ->() const {
272     assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
273     return Base->CurrentEntry;
274   }
275
276   ValueT &operator *() const {
277     assert(Base && Base->CurrentEntry &&
278            "Attempted to dereference end iterator!");
279     return *Base->CurrentEntry;
280   }
281
282   operator ValueT*() const {
283     assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
284     return Base->CurrentEntry;
285   }
286
287   bool operator !=(const basic_collection_iterator &Other) const {
288     if(Base != Other.Base)
289       return true;
290     return (Base && Other.Base) && Base->CurrentEntry
291                                    != Other.Base->CurrentEntry;
292   }
293
294   basic_collection_iterator &operator++() {
295     assert(Base && "Attempted to advance iterator past end!");
296     Base->increment();
297     // Create an end iterator.
298     if (Base->CurrentEntry == 0)
299       Base = 0;
300     return *this;
301   }
302
303 private:
304   BaseT *Base;
305 };
306
307 // The following two templates are used for both MappingNode and Sequence Node.
308 template <class CollectionType>
309 typename CollectionType::iterator begin(CollectionType &C) {
310   assert(C.IsAtBeginning && "You may only iterate over a collection once!");
311   C.IsAtBeginning = false;
312   typename CollectionType::iterator ret(&C);
313   ++ret;
314   return ret;
315 }
316
317 template <class CollectionType>
318 void skip(CollectionType &C) {
319   // TODO: support skipping from the middle of a parsed collection ;/
320   assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
321   if (C.IsAtBeginning)
322     for (typename CollectionType::iterator i = begin(C), e = C.end();
323                                            i != e; ++i)
324       i->skip();
325 }
326
327 /// @brief Represents a YAML map created from either a block map for a flow map.
328 ///
329 /// This parses the YAML stream as increment() is called.
330 ///
331 /// Example:
332 ///   Name: _main
333 ///   Scope: Global
334 class MappingNode : public Node {
335 public:
336   enum MappingType {
337     MT_Block,
338     MT_Flow,
339     MT_Inline ///< An inline mapping node is used for "[key: value]".
340   };
341
342   MappingNode(OwningPtr<Document> &D, StringRef Anchor, MappingType MT)
343     : Node(NK_Mapping, D, Anchor)
344     , Type(MT)
345     , IsAtBeginning(true)
346     , IsAtEnd(false)
347     , CurrentEntry(0)
348   {}
349
350   friend class basic_collection_iterator<MappingNode, KeyValueNode>;
351   typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
352   template <class T> friend typename T::iterator yaml::begin(T &);
353   template <class T> friend void yaml::skip(T &);
354
355   iterator begin() {
356     return yaml::begin(*this);
357   }
358
359   iterator end() { return iterator(); }
360
361   virtual void skip() LLVM_OVERRIDE {
362     yaml::skip(*this);
363   }
364
365   static inline bool classof(const Node *N) {
366     return N->getType() == NK_Mapping;
367   }
368
369 private:
370   MappingType Type;
371   bool IsAtBeginning;
372   bool IsAtEnd;
373   KeyValueNode *CurrentEntry;
374
375   void increment();
376 };
377
378 /// @brief Represents a YAML sequence created from either a block sequence for a
379 ///        flow sequence.
380 ///
381 /// This parses the YAML stream as increment() is called.
382 ///
383 /// Example:
384 ///   - Hello
385 ///   - World
386 class SequenceNode : public Node {
387 public:
388   enum SequenceType {
389     ST_Block,
390     ST_Flow,
391     // Use for:
392     //
393     // key:
394     // - val1
395     // - val2
396     //
397     // As a BlockMappingEntry and BlockEnd are not created in this case.
398     ST_Indentless
399   };
400
401   SequenceNode(OwningPtr<Document> &D, StringRef Anchor, SequenceType ST)
402     : Node(NK_Sequence, D, Anchor)
403     , SeqType(ST)
404     , IsAtBeginning(true)
405     , IsAtEnd(false)
406     , WasPreviousTokenFlowEntry(true) // Start with an imaginary ','.
407     , CurrentEntry(0)
408   {}
409
410   friend class basic_collection_iterator<SequenceNode, Node>;
411   typedef basic_collection_iterator<SequenceNode, Node> iterator;
412   template <class T> friend typename T::iterator yaml::begin(T &);
413   template <class T> friend void yaml::skip(T &);
414
415   void increment();
416
417   iterator begin() {
418     return yaml::begin(*this);
419   }
420
421   iterator end() { return iterator(); }
422
423   virtual void skip() LLVM_OVERRIDE {
424     yaml::skip(*this);
425   }
426
427   static inline bool classof(const Node *N) {
428     return N->getType() == NK_Sequence;
429   }
430
431 private:
432   SequenceType SeqType;
433   bool IsAtBeginning;
434   bool IsAtEnd;
435   bool WasPreviousTokenFlowEntry;
436   Node *CurrentEntry;
437 };
438
439 /// @brief Represents an alias to a Node with an anchor.
440 ///
441 /// Example:
442 ///   *AnchorName
443 class AliasNode : public Node {
444 public:
445   AliasNode(OwningPtr<Document> &D, StringRef Val)
446     : Node(NK_Alias, D, StringRef()), Name(Val) {}
447
448   StringRef getName() const { return Name; }
449   Node *getTarget();
450
451   static inline bool classof(const Node *N) {
452     return N->getType() == NK_Alias;
453   }
454
455 private:
456   StringRef Name;
457 };
458
459 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
460 ///        node.
461 class Document {
462 public:
463   /// @brief Root for parsing a node. Returns a single node.
464   Node *parseBlockNode();
465
466   Document(Stream &ParentStream);
467
468   /// @brief Finish parsing the current document and return true if there are
469   ///        more. Return false otherwise.
470   bool skip();
471
472   /// @brief Parse and return the root level node.
473   Node *getRoot() {
474     if (Root)
475       return Root;
476     return Root = parseBlockNode();
477   }
478
479 private:
480   friend class Node;
481   friend class document_iterator;
482
483   /// @brief Stream to read tokens from.
484   Stream &stream;
485
486   /// @brief Used to allocate nodes to. All are destroyed without calling their
487   ///        destructor when the document is destroyed.
488   BumpPtrAllocator NodeAllocator;
489
490   /// @brief The root node. Used to support skipping a partially parsed
491   ///        document.
492   Node *Root;
493
494   Token &peekNext();
495   Token getNext();
496   void setError(const Twine &Message, Token &Location) const;
497   bool failed() const;
498
499   void handleTagDirective(const Token &Tag) {
500     // TODO: Track tags.
501   }
502
503   /// @brief Parse %BLAH directives and return true if any were encountered.
504   bool parseDirectives();
505
506   /// @brief Consume the next token and error if it is not \a TK.
507   bool expectToken(int TK);
508 };
509
510 /// @brief Iterator abstraction for Documents over a Stream.
511 class document_iterator {
512 public:
513   document_iterator() : Doc(0) {}
514   document_iterator(OwningPtr<Document> &D) : Doc(&D) {}
515
516   bool operator ==(const document_iterator &Other) {
517     if (isAtEnd() || Other.isAtEnd())
518       return isAtEnd() && Other.isAtEnd();
519
520     return *Doc == *Other.Doc;
521   }
522   bool operator !=(const document_iterator &Other) {
523     return !(*this == Other);
524   }
525
526   document_iterator operator ++() {
527     assert(Doc != 0 && "incrementing iterator past the end.");
528     if (!(*Doc)->skip()) {
529       Doc->reset(0);
530     } else {
531       Stream &S = (*Doc)->stream;
532       Doc->reset(new Document(S));
533     }
534     return *this;
535   }
536
537   Document &operator *() {
538     return *Doc->get();
539   }
540
541   OwningPtr<Document> &operator ->() {
542     return *Doc;
543   }
544
545 private:
546   bool isAtEnd() const {
547     return Doc == 0 || *Doc == 0;
548   }
549
550   OwningPtr<Document> *Doc;
551 };
552
553 }
554 }
555
556 #endif