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/MemoryBuffer.h"
45 #include "llvm/Support/SMLoc.h"
46 #include <limits>
47 #include <map>
48 #include <utility>
49
50 namespace llvm {
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 Stream(MemoryBufferRef InputBuffer, SourceMgr &);
83 ~Stream();
84
85 document_iterator begin();
86 document_iterator end();
87 void skip();
88 bool failed();
validate()89 bool validate() {
90 skip();
91 return !failed();
92 }
93
94 void printError(Node *N, const Twine &Msg);
95
96 private:
97 std::unique_ptr<Scanner> scanner;
98 std::unique_ptr<Document> CurrentDoc;
99
100 friend class Document;
101 };
102
103 /// \brief Abstract base class for all Nodes.
104 class Node {
105 virtual void anchor();
106
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.
getAnchor()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.
getRawTag()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
getSourceRange()132 SMRange getSourceRange() const { return SourceRange; }
setSourceRange(SMRange SR)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
skip()143 virtual void skip() {}
144
getType()145 unsigned int getType() const { return TypeID; }
146
147 void *operator new(size_t Size, BumpPtrAllocator &Alloc,
throw()148 size_t Alignment = 16) throw() {
149 return Alloc.Allocate(Size, Alignment);
150 }
151
delete(void * Ptr,BumpPtrAllocator & Alloc,size_t Size)152 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t Size) throw() {
153 Alloc.Deallocate(Ptr, Size);
154 }
155
156 protected:
157 std::unique_ptr<Document> &Doc;
158 SMRange SourceRange;
159
delete(void *)160 void operator delete(void *) throw() {}
161
~Node()162 virtual ~Node() {}
163
164 private:
165 unsigned int TypeID;
166 StringRef Anchor;
167 /// \brief The tag as typed in the document.
168 StringRef Tag;
169 };
170
171 /// \brief A null value.
172 ///
173 /// Example:
174 /// !!null null
175 class NullNode : public Node {
176 void anchor() override;
177
178 public:
NullNode(std::unique_ptr<Document> & D)179 NullNode(std::unique_ptr<Document> &D)
180 : Node(NK_Null, D, StringRef(), StringRef()) {}
181
classof(const Node * N)182 static inline bool classof(const Node *N) { return N->getType() == NK_Null; }
183 };
184
185 /// \brief A scalar node is an opaque datum that can be presented as a
186 /// series of zero or more Unicode scalar values.
187 ///
188 /// Example:
189 /// Adena
190 class ScalarNode : public Node {
191 void anchor() override;
192
193 public:
ScalarNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,StringRef Val)194 ScalarNode(std::unique_ptr<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).
getRawValue()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
classof(const Node * N)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 void anchor() override;
235
236 public:
KeyValueNode(std::unique_ptr<Document> & D)237 KeyValueNode(std::unique_ptr<Document> &D)
238 : Node(NK_KeyValue, D, StringRef(), StringRef()), Key(nullptr),
239 Value(nullptr) {}
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
skip()255 void skip() override {
256 getKey()->skip();
257 getValue()->skip();
258 }
259
classof(const Node * N)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:
basic_collection_iterator()278 basic_collection_iterator() : Base(nullptr) {}
basic_collection_iterator(BaseT * B)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 explicit 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 false;
300 return !Base || Base->CurrentEntry == Other.Base->CurrentEntry;
301 }
302 bool operator!=(const basic_collection_iterator &Other) {
303 return !(*this == Other);
304 }
305
306 basic_collection_iterator &operator++() {
307 assert(Base && "Attempted to advance iterator past end!");
308 Base->increment();
309 // Create an end iterator.
310 if (!Base->CurrentEntry)
311 Base = nullptr;
312 return *this;
313 }
314
315 private:
316 BaseT *Base;
317 };
318
319 // The following two templates are used for both MappingNode and Sequence Node.
320 template <class CollectionType>
begin(CollectionType & C)321 typename CollectionType::iterator begin(CollectionType &C) {
322 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
323 C.IsAtBeginning = false;
324 typename CollectionType::iterator ret(&C);
325 ++ret;
326 return ret;
327 }
328
skip(CollectionType & C)329 template <class CollectionType> void skip(CollectionType &C) {
330 // TODO: support skipping from the middle of a parsed collection ;/
331 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
332 if (C.IsAtBeginning)
333 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
334 ++i)
335 i->skip();
336 }
337
338 /// \brief Represents a YAML map created from either a block map for a flow map.
339 ///
340 /// This parses the YAML stream as increment() is called.
341 ///
342 /// Example:
343 /// Name: _main
344 /// Scope: Global
345 class MappingNode : public Node {
346 void anchor() override;
347
348 public:
349 enum MappingType {
350 MT_Block,
351 MT_Flow,
352 MT_Inline ///< An inline mapping node is used for "[key: value]".
353 };
354
MappingNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,MappingType MT)355 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
356 MappingType MT)
357 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
358 IsAtEnd(false), CurrentEntry(nullptr) {}
359
360 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
361 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
362 template <class T> friend typename T::iterator yaml::begin(T &);
363 template <class T> friend void yaml::skip(T &);
364
begin()365 iterator begin() { return yaml::begin(*this); }
366
end()367 iterator end() { return iterator(); }
368
skip()369 void skip() override { yaml::skip(*this); }
370
classof(const Node * N)371 static inline bool classof(const Node *N) {
372 return N->getType() == NK_Mapping;
373 }
374
375 private:
376 MappingType Type;
377 bool IsAtBeginning;
378 bool IsAtEnd;
379 KeyValueNode *CurrentEntry;
380
381 void increment();
382 };
383
384 /// \brief Represents a YAML sequence created from either a block sequence for a
385 /// flow sequence.
386 ///
387 /// This parses the YAML stream as increment() is called.
388 ///
389 /// Example:
390 /// - Hello
391 /// - World
392 class SequenceNode : public Node {
393 void anchor() override;
394
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
SequenceNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,SequenceType ST)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(nullptr) {}
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
begin()423 iterator begin() { return yaml::begin(*this); }
424
end()425 iterator end() { return iterator(); }
426
skip()427 void skip() override { yaml::skip(*this); }
428
classof(const Node * N)429 static inline bool classof(const Node *N) {
430 return N->getType() == NK_Sequence;
431 }
432
433 private:
434 SequenceType SeqType;
435 bool IsAtBeginning;
436 bool IsAtEnd;
437 bool WasPreviousTokenFlowEntry;
438 Node *CurrentEntry;
439 };
440
441 /// \brief Represents an alias to a Node with an anchor.
442 ///
443 /// Example:
444 /// *AnchorName
445 class AliasNode : public Node {
446 void anchor() override;
447
448 public:
AliasNode(std::unique_ptr<Document> & D,StringRef Val)449 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
450 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
451
getName()452 StringRef getName() const { return Name; }
453 Node *getTarget();
454
classof(const Node * N)455 static inline bool classof(const Node *N) { return N->getType() == NK_Alias; }
456
457 private:
458 StringRef Name;
459 };
460
461 /// \brief A YAML Stream is a sequence of Documents. A document contains a root
462 /// node.
463 class Document {
464 public:
465 /// \brief Root for parsing a node. Returns a single node.
466 Node *parseBlockNode();
467
468 Document(Stream &ParentStream);
469
470 /// \brief Finish parsing the current document and return true if there are
471 /// more. Return false otherwise.
472 bool skip();
473
474 /// \brief Parse and return the root level node.
getRoot()475 Node *getRoot() {
476 if (Root)
477 return Root;
478 return Root = parseBlockNode();
479 }
480
getTagMap()481 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
482
483 private:
484 friend class Node;
485 friend class document_iterator;
486
487 /// \brief Stream to read tokens from.
488 Stream &stream;
489
490 /// \brief Used to allocate nodes to. All are destroyed without calling their
491 /// destructor when the document is destroyed.
492 BumpPtrAllocator NodeAllocator;
493
494 /// \brief The root node. Used to support skipping a partially parsed
495 /// document.
496 Node *Root;
497
498 /// \brief Maps tag prefixes to their expansion.
499 std::map<StringRef, StringRef> TagMap;
500
501 Token &peekNext();
502 Token getNext();
503 void setError(const Twine &Message, Token &Location) const;
504 bool failed() const;
505
506 /// \brief Parse %BLAH directives and return true if any were encountered.
507 bool parseDirectives();
508
509 /// \brief Parse %YAML
510 void parseYAMLDirective();
511
512 /// \brief Parse %TAG
513 void parseTAGDirective();
514
515 /// \brief Consume the next token and error if it is not \a TK.
516 bool expectToken(int TK);
517 };
518
519 /// \brief Iterator abstraction for Documents over a Stream.
520 class document_iterator {
521 public:
document_iterator()522 document_iterator() : Doc(nullptr) {}
document_iterator(std::unique_ptr<Document> & D)523 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
524
525 bool operator==(const document_iterator &Other) {
526 if (isAtEnd() || Other.isAtEnd())
527 return isAtEnd() && Other.isAtEnd();
528
529 return Doc == Other.Doc;
530 }
531 bool operator!=(const document_iterator &Other) { return !(*this == Other); }
532
533 document_iterator operator++() {
534 assert(Doc && "incrementing iterator past the end.");
535 if (!(*Doc)->skip()) {
536 Doc->reset(nullptr);
537 } else {
538 Stream &S = (*Doc)->stream;
539 Doc->reset(new Document(S));
540 }
541 return *this;
542 }
543
544 Document &operator*() { return *Doc->get(); }
545
546 std::unique_ptr<Document> &operator->() { return *Doc; }
547
548 private:
isAtEnd()549 bool isAtEnd() const { return !Doc || !*Doc; }
550
551 std::unique_ptr<Document> *Doc;
552 };
553
554 } // End namespace yaml.
555
556 } // End namespace llvm.
557
558 #endif
559