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