Really fix -Wnon-virtual-dtor warnings; gcc needs the dtors to be
[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   Stream(StringRef Input, SourceMgr &);
81   ~Stream();
82
83   document_iterator begin();
84   document_iterator end();
85   void skip();
86   bool failed();
87   bool validate() {
88     skip();
89     return !failed();
90   }
91
92   void printError(Node *N, const Twine &Msg);
93
94 private:
95   OwningPtr<Scanner> scanner;
96   OwningPtr<Document> CurrentDoc;
97
98   friend class Document;
99
100   /// @brief Validate a %YAML x.x directive.
101   void handleYAMLDirective(const Token &);
102 };
103
104 /// @brief Abstract base class for all Nodes.
105 class Node {
106 public:
107   enum NodeKind {
108     NK_Null,
109     NK_Scalar,
110     NK_KeyValue,
111     NK_Mapping,
112     NK_Sequence,
113     NK_Alias
114   };
115
116   Node(unsigned int Type, OwningPtr<Document>&, StringRef Anchor);
117
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; }
121
122   SMRange getSourceRange() const { return SourceRange; }
123   void setSourceRange(SMRange SR) { SourceRange = SR; }
124
125   // These functions forward to Document and Scanner.
126   Token &peekNext();
127   Token getNext();
128   Node *parseBlockNode();
129   BumpPtrAllocator &getAllocator();
130   void setError(const Twine &Message, Token &Location) const;
131   bool failed() const;
132
133   virtual void skip() {};
134
135   unsigned int getType() const { return TypeID; }
136   static inline bool classof(const Node *) { return true; }
137
138   void *operator new ( size_t Size
139                      , BumpPtrAllocator &Alloc
140                      , size_t Alignment = 16) throw() {
141     return Alloc.Allocate(Size, Alignment);
142   }
143
144   void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
145     Alloc.Deallocate(Ptr);
146   }
147
148 protected:
149   OwningPtr<Document> &Doc;
150   SMRange SourceRange;
151
152   virtual ~Node();
153
154 private:
155   unsigned int TypeID;
156   StringRef Anchor;
157 };
158
159 /// @brief A null value.
160 ///
161 /// Example:
162 ///   !!null null
163 class NullNode : public Node {
164 public:
165   NullNode(OwningPtr<Document> &D) : Node(NK_Null, D, StringRef()) {}
166
167   static inline bool classof(const NullNode *) { return true; }
168   static inline bool classof(const Node *N) {
169     return N->getType() == NK_Null;
170   }
171
172 protected:
173   virtual ~NullNode();
174 };
175
176 /// @brief A scalar node is an opaque datum that can be presented as a
177 ///        series of zero or more Unicode scalar values.
178 ///
179 /// Example:
180 ///   Adena
181 class ScalarNode : public Node {
182 public:
183   ScalarNode(OwningPtr<Document> &D, StringRef Anchor, StringRef Val)
184     : Node(NK_Scalar, D, Anchor)
185     , Value(Val) {
186     SMLoc Start = SMLoc::getFromPointer(Val.begin());
187     SMLoc End = SMLoc::getFromPointer(Val.end() - 1);
188     SourceRange = SMRange(Start, End);
189   }
190
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
193   // utf8).
194   StringRef getRawValue() const { return Value; }
195
196   /// @brief Gets the value of this node as a StringRef.
197   ///
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;
202
203   static inline bool classof(const ScalarNode *) { return true; }
204   static inline bool classof(const Node *N) {
205     return N->getType() == NK_Scalar;
206   }
207
208 protected:
209   virtual ~ScalarNode();
210
211 private:
212   StringRef Value;
213
214   StringRef unescapeDoubleQuoted( StringRef UnquotedValue
215                                 , StringRef::size_type Start
216                                 , SmallVectorImpl<char> &Storage) const;
217 };
218
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.
221 ///
222 /// TODO: Consider making this not a child of Node.
223 ///
224 /// Example:
225 ///   Section: .text
226 class KeyValueNode : public Node {
227 public:
228   KeyValueNode(OwningPtr<Document> &D)
229     : Node(NK_KeyValue, D, StringRef())
230     , Key(0)
231     , Value(0)
232   {}
233
234   /// @brief Parse and return the key.
235   ///
236   /// This may be called multiple times.
237   ///
238   /// @returns The key, or nullptr if failed() == true.
239   Node *getKey();
240
241   /// @brief Parse and return the value.
242   ///
243   /// This may be called multiple times.
244   ///
245   /// @returns The value, or nullptr if failed() == true.
246   Node *getValue();
247
248   virtual void skip() {
249     getKey()->skip();
250     getValue()->skip();
251   }
252
253   static inline bool classof(const KeyValueNode *) { return true; }
254   static inline bool classof(const Node *N) {
255     return N->getType() == NK_KeyValue;
256   }
257
258 protected:
259   virtual ~KeyValueNode();
260
261 private:
262   Node *Key;
263   Node *Value;
264 };
265
266 /// @brief This is an iterator abstraction over YAML collections shared by both
267 ///        sequences and maps.
268 ///
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> {
274 public:
275   basic_collection_iterator() : Base(0) {}
276   basic_collection_iterator(BaseT *B) : Base(B) {}
277
278   ValueT *operator ->() const {
279     assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
280     return Base->CurrentEntry;
281   }
282
283   ValueT &operator *() const {
284     assert(Base && Base->CurrentEntry &&
285            "Attempted to dereference end iterator!");
286     return *Base->CurrentEntry;
287   }
288
289   operator ValueT*() const {
290     assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
291     return Base->CurrentEntry;
292   }
293
294   bool operator !=(const basic_collection_iterator &Other) const {
295     if(Base != Other.Base)
296       return true;
297     return (Base && Other.Base) && Base->CurrentEntry
298                                    != Other.Base->CurrentEntry;
299   }
300
301   basic_collection_iterator &operator++() {
302     assert(Base && "Attempted to advance iterator past end!");
303     Base->increment();
304     // Create an end iterator.
305     if (Base->CurrentEntry == 0)
306       Base = 0;
307     return *this;
308   }
309
310 private:
311   BaseT *Base;
312 };
313
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);
320   ++ret;
321   return ret;
322 }
323
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!");
328   if (C.IsAtBeginning)
329     for (typename CollectionType::iterator i = begin(C), e = C.end();
330                                            i != e; ++i)
331       i->skip();
332 }
333
334 /// @brief Represents a YAML map created from either a block map for a flow map.
335 ///
336 /// This parses the YAML stream as increment() is called.
337 ///
338 /// Example:
339 ///   Name: _main
340 ///   Scope: Global
341 class MappingNode : public Node {
342 public:
343   enum MappingType {
344     MT_Block,
345     MT_Flow,
346     MT_Inline //< An inline mapping node is used for "[key: value]".
347   };
348
349   MappingNode(OwningPtr<Document> &D, StringRef Anchor, MappingType MT)
350     : Node(NK_Mapping, D, Anchor)
351     , Type(MT)
352     , IsAtBeginning(true)
353     , IsAtEnd(false)
354     , CurrentEntry(0)
355   {}
356
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 &);
361
362   iterator begin() {
363     return yaml::begin(*this);
364   }
365
366   iterator end() { return iterator(); }
367
368   virtual void skip() {
369     yaml::skip(*this);
370   }
371
372   static inline bool classof(const MappingNode *) { return true; }
373   static inline bool classof(const Node *N) {
374     return N->getType() == NK_Mapping;
375   }
376
377 protected:
378   virtual ~MappingNode();
379
380 private:
381   MappingType Type;
382   bool IsAtBeginning;
383   bool IsAtEnd;
384   KeyValueNode *CurrentEntry;
385
386   void increment();
387 };
388
389 /// @brief Represents a YAML sequence created from either a block sequence for a
390 ///        flow sequence.
391 ///
392 /// This parses the YAML stream as increment() is called.
393 ///
394 /// Example:
395 ///   - Hello
396 ///   - World
397 class SequenceNode : public Node {
398 public:
399   enum SequenceType {
400     ST_Block,
401     ST_Flow,
402     // Use for:
403     //
404     // key:
405     // - val1
406     // - val2
407     //
408     // As a BlockMappingEntry and BlockEnd are not created in this case.
409     ST_Indentless
410   };
411
412   SequenceNode(OwningPtr<Document> &D, StringRef Anchor, SequenceType ST)
413     : Node(NK_Sequence, D, Anchor)
414     , SeqType(ST)
415     , IsAtBeginning(true)
416     , IsAtEnd(false)
417     , WasPreviousTokenFlowEntry(true) // Start with an imaginary ','.
418     , CurrentEntry(0)
419   {}
420
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 &);
425
426   void increment();
427
428   iterator begin() {
429     return yaml::begin(*this);
430   }
431
432   iterator end() { return iterator(); }
433
434   virtual void skip() {
435     yaml::skip(*this);
436   }
437
438   static inline bool classof(const SequenceNode *) { return true; }
439   static inline bool classof(const Node *N) {
440     return N->getType() == NK_Sequence;
441   }
442
443 protected:
444   virtual ~SequenceNode();
445
446 private:
447   SequenceType SeqType;
448   bool IsAtBeginning;
449   bool IsAtEnd;
450   bool WasPreviousTokenFlowEntry;
451   Node *CurrentEntry;
452 };
453
454 /// @brief Represents an alias to a Node with an anchor.
455 ///
456 /// Example:
457 ///   *AnchorName
458 class AliasNode : public Node {
459 public:
460   AliasNode(OwningPtr<Document> &D, StringRef Val)
461     : Node(NK_Alias, D, StringRef()), Name(Val) {}
462
463   StringRef getName() const { return Name; }
464   Node *getTarget();
465
466   static inline bool classof(const ScalarNode *) { return true; }
467   static inline bool classof(const Node *N) {
468     return N->getType() == NK_Alias;
469   }
470
471 protected:
472   virtual ~AliasNode();
473
474 private:
475   StringRef Name;
476 };
477
478 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
479 ///        node.
480 class Document {
481 public:
482   /// @brief Root for parsing a node. Returns a single node.
483   Node *parseBlockNode();
484
485   Document(Stream &ParentStream);
486
487   /// @brief Finish parsing the current document and return true if there are
488   ///        more. Return false otherwise.
489   bool skip();
490
491   /// @brief Parse and return the root level node.
492   Node *getRoot() {
493     if (Root)
494       return Root;
495     return Root = parseBlockNode();
496   }
497
498 private:
499   friend class Node;
500   friend class document_iterator;
501
502   /// @brief Stream to read tokens from.
503   Stream &stream;
504
505   /// @brief Used to allocate nodes to. All are destroyed without calling their
506   ///        destructor when the document is destroyed.
507   BumpPtrAllocator NodeAllocator;
508
509   /// @brief The root node. Used to support skipping a partially parsed
510   ///        document.
511   Node *Root;
512
513   Token &peekNext();
514   Token getNext();
515   void setError(const Twine &Message, Token &Location) const;
516   bool failed() const;
517
518   void handleTagDirective(const Token &Tag) {
519     // TODO: Track tags.
520   }
521
522   /// @brief Parse %BLAH directives and return true if any were encountered.
523   bool parseDirectives();
524
525   /// @brief Consume the next token and error if it is not \a TK.
526   bool expectToken(int TK);
527 };
528
529 /// @brief Iterator abstraction for Documents over a Stream.
530 class document_iterator {
531 public:
532   document_iterator() : Doc(NullDoc) {}
533   document_iterator(OwningPtr<Document> &D) : Doc(D) {}
534
535   bool operator !=(const document_iterator &Other) {
536     return Doc != Other.Doc;
537   }
538
539   document_iterator operator ++() {
540     if (!Doc->skip()) {
541       Doc.reset(0);
542     } else {
543       Stream &S = Doc->stream;
544       Doc.reset(new Document(S));
545     }
546     return *this;
547   }
548
549   Document &operator *() {
550     return *Doc;
551   }
552
553   OwningPtr<Document> &operator ->() {
554     return Doc;
555   }
556
557 private:
558   static OwningPtr<Document> NullDoc;
559   OwningPtr<Document> &Doc;
560 };
561
562 }
563 }
564
565 #endif