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