1 //===- YAMLParser.h - Simple YAML parser ------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is a YAML 1.2 parser.
10 //
11 // See http://www.yaml.org/spec/1.2/spec.html for the full standard.
12 //
13 // This currently does not implement the following:
14 // * Tag resolution.
15 // * UTF-16.
16 // * BOMs anywhere other than the first Unicode scalar value in the file.
17 //
18 // The most important class here is Stream. This represents a YAML stream with
19 // 0, 1, or many documents.
20 //
21 // SourceMgr sm;
22 // StringRef input = getInput();
23 // yaml::Stream stream(input, sm);
24 //
25 // for (yaml::document_iterator di = stream.begin(), de = stream.end();
26 // di != de; ++di) {
27 // yaml::Node *n = di->getRoot();
28 // if (n) {
29 // // Do something with n...
30 // } else {
31 // break;
32 // }
33 // }
34 //
35 //===----------------------------------------------------------------------===//
36
37 #ifndef LLVM_SUPPORT_YAMLPARSER_H
38 #define LLVM_SUPPORT_YAMLPARSER_H
39
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Support/Allocator.h"
42 #include "llvm/Support/Compiler.h"
43 #include "llvm/Support/SMLoc.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include <cassert>
46 #include <cstddef>
47 #include <iterator>
48 #include <map>
49 #include <memory>
50 #include <optional>
51 #include <string>
52 #include <system_error>
53
54 namespace llvm {
55
56 class MemoryBufferRef;
57 class raw_ostream;
58 class Twine;
59
60 namespace yaml {
61
62 class Document;
63 class document_iterator;
64 class Node;
65 class Scanner;
66 struct Token;
67
68 /// Dump all the tokens in this stream to OS.
69 /// \returns true if there was an error, false otherwise.
70 LLVM_ABI bool dumpTokens(StringRef Input, raw_ostream &);
71
72 /// Scans all tokens in input without outputting anything. This is used
73 /// for benchmarking the tokenizer.
74 /// \returns true if there was an error, false otherwise.
75 LLVM_ABI bool scanTokens(StringRef Input);
76
77 /// Escape \a Input for a double quoted scalar; if \p EscapePrintable
78 /// is true, all UTF8 sequences will be escaped, if \p EscapePrintable is
79 /// false, those UTF8 sequences encoding printable unicode scalars will not be
80 /// escaped, but emitted verbatim.
81 LLVM_ABI std::string escape(StringRef Input, bool EscapePrintable = true);
82
83 /// Parse \p S as a bool according to https://yaml.org/type/bool.html.
84 LLVM_ABI std::optional<bool> parseBool(StringRef S);
85
86 /// This class represents a YAML stream potentially containing multiple
87 /// documents.
88 class Stream {
89 public:
90 /// This keeps a reference to the string referenced by \p Input.
91 LLVM_ABI Stream(StringRef Input, SourceMgr &, bool ShowColors = true,
92 std::error_code *EC = nullptr);
93
94 LLVM_ABI Stream(MemoryBufferRef InputBuffer, SourceMgr &,
95 bool ShowColors = true, std::error_code *EC = nullptr);
96 LLVM_ABI ~Stream();
97
98 LLVM_ABI document_iterator begin();
99 LLVM_ABI document_iterator end();
100 LLVM_ABI void skip();
101 LLVM_ABI bool failed();
102
validate()103 bool validate() {
104 skip();
105 return !failed();
106 }
107
108 LLVM_ABI void printError(Node *N, const Twine &Msg,
109 SourceMgr::DiagKind Kind = SourceMgr::DK_Error);
110 LLVM_ABI void printError(const SMRange &Range, const Twine &Msg,
111 SourceMgr::DiagKind Kind = SourceMgr::DK_Error);
112
113 private:
114 friend class Document;
115
116 std::unique_ptr<Scanner> scanner;
117 std::unique_ptr<Document> CurrentDoc;
118 };
119
120 /// Abstract base class for all Nodes.
121 class LLVM_ABI Node {
122 virtual void anchor();
123
124 public:
125 enum NodeKind {
126 NK_Null,
127 NK_Scalar,
128 NK_BlockScalar,
129 NK_KeyValue,
130 NK_Mapping,
131 NK_Sequence,
132 NK_Alias
133 };
134
135 Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
136 StringRef Tag);
137
138 // It's not safe to copy YAML nodes; the document is streamed and the position
139 // is part of the state.
140 Node(const Node &) = delete;
141 void operator=(const Node &) = delete;
142
143 void *operator new(size_t Size, BumpPtrAllocator &Alloc,
144 size_t Alignment = 16) noexcept {
145 return Alloc.Allocate(Size, Alignment);
146 }
147
delete(void * Ptr,BumpPtrAllocator & Alloc,size_t Size)148 void operator delete(void *Ptr, BumpPtrAllocator &Alloc,
149 size_t Size) noexcept {
150 Alloc.Deallocate(Ptr, Size, 0);
151 }
152
153 void operator delete(void *) noexcept = delete;
154
155 /// Get the value of the anchor attached to this node. If it does not
156 /// have one, getAnchor().size() will be 0.
getAnchor()157 StringRef getAnchor() const { return Anchor; }
158
159 /// Get the tag as it was written in the document. This does not
160 /// perform tag resolution.
getRawTag()161 StringRef getRawTag() const { return Tag; }
162
163 /// Get the verbatium tag for a given Node. This performs tag resoluton
164 /// and substitution.
165 std::string getVerbatimTag() const;
166
getSourceRange()167 SMRange getSourceRange() const { return SourceRange; }
setSourceRange(SMRange SR)168 void setSourceRange(SMRange SR) { SourceRange = SR; }
169
170 // These functions forward to Document and Scanner.
171 Token &peekNext();
172 Token getNext();
173 Node *parseBlockNode();
174 BumpPtrAllocator &getAllocator();
175 void setError(const Twine &Message, Token &Location) const;
176 bool failed() const;
177
skip()178 virtual void skip() {}
179
getType()180 unsigned int getType() const { return TypeID; }
181
182 protected:
183 std::unique_ptr<Document> &Doc;
184 SMRange SourceRange;
185
186 ~Node() = default;
187
188 private:
189 unsigned int TypeID;
190 StringRef Anchor;
191 /// The tag as typed in the document.
192 StringRef Tag;
193 };
194
195 /// A null value.
196 ///
197 /// Example:
198 /// !!null null
199 class LLVM_ABI NullNode final : public Node {
200 void anchor() override;
201
202 public:
NullNode(std::unique_ptr<Document> & D)203 NullNode(std::unique_ptr<Document> &D)
204 : Node(NK_Null, D, StringRef(), StringRef()) {}
205
classof(const Node * N)206 static bool classof(const Node *N) { return N->getType() == NK_Null; }
207 };
208
209 /// A scalar node is an opaque datum that can be presented as a
210 /// series of zero or more Unicode scalar values.
211 ///
212 /// Example:
213 /// Adena
214 class LLVM_ABI ScalarNode final : public Node {
215 void anchor() override;
216
217 public:
ScalarNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,StringRef Val)218 ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
219 StringRef Val)
220 : Node(NK_Scalar, D, Anchor, Tag), Value(Val) {
221 SMLoc Start = SMLoc::getFromPointer(Val.begin());
222 SMLoc End = SMLoc::getFromPointer(Val.end());
223 SourceRange = SMRange(Start, End);
224 }
225
226 // Return Value without any escaping or folding or other fun YAML stuff. This
227 // is the exact bytes that are contained in the file (after conversion to
228 // utf8).
getRawValue()229 StringRef getRawValue() const { return Value; }
230
231 /// Gets the value of this node as a StringRef.
232 ///
233 /// \param Storage is used to store the content of the returned StringRef if
234 /// it requires any modification from how it appeared in the source.
235 /// This happens with escaped characters and multi-line literals.
236 StringRef getValue(SmallVectorImpl<char> &Storage) const;
237
classof(const Node * N)238 static bool classof(const Node *N) {
239 return N->getType() == NK_Scalar;
240 }
241
242 private:
243 StringRef Value;
244
245 StringRef getDoubleQuotedValue(StringRef UnquotedValue,
246 SmallVectorImpl<char> &Storage) const;
247
248 static StringRef getSingleQuotedValue(StringRef RawValue,
249 SmallVectorImpl<char> &Storage);
250
251 static StringRef getPlainValue(StringRef RawValue,
252 SmallVectorImpl<char> &Storage);
253 };
254
255 /// A block scalar node is an opaque datum that can be presented as a
256 /// series of zero or more Unicode scalar values.
257 ///
258 /// Example:
259 /// |
260 /// Hello
261 /// World
262 class LLVM_ABI BlockScalarNode final : public Node {
263 void anchor() override;
264
265 public:
BlockScalarNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,StringRef Value,StringRef RawVal)266 BlockScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
267 StringRef Value, StringRef RawVal)
268 : Node(NK_BlockScalar, D, Anchor, Tag), Value(Value) {
269 SMLoc Start = SMLoc::getFromPointer(RawVal.begin());
270 SMLoc End = SMLoc::getFromPointer(RawVal.end());
271 SourceRange = SMRange(Start, End);
272 }
273
274 /// Gets the value of this node as a StringRef.
getValue()275 StringRef getValue() const { return Value; }
276
classof(const Node * N)277 static bool classof(const Node *N) {
278 return N->getType() == NK_BlockScalar;
279 }
280
281 private:
282 StringRef Value;
283 };
284
285 /// A key and value pair. While not technically a Node under the YAML
286 /// representation graph, it is easier to treat them this way.
287 ///
288 /// TODO: Consider making this not a child of Node.
289 ///
290 /// Example:
291 /// Section: .text
292 class LLVM_ABI KeyValueNode final : public Node {
293 void anchor() override;
294
295 public:
KeyValueNode(std::unique_ptr<Document> & D)296 KeyValueNode(std::unique_ptr<Document> &D)
297 : Node(NK_KeyValue, D, StringRef(), StringRef()) {}
298
299 /// Parse and return the key.
300 ///
301 /// This may be called multiple times.
302 ///
303 /// \returns The key, or nullptr if failed() == true.
304 Node *getKey();
305
306 /// Parse and return the value.
307 ///
308 /// This may be called multiple times.
309 ///
310 /// \returns The value, or nullptr if failed() == true.
311 Node *getValue();
312
skip()313 void skip() override {
314 if (Node *Key = getKey()) {
315 Key->skip();
316 if (Node *Val = getValue())
317 Val->skip();
318 }
319 }
320
classof(const Node * N)321 static bool classof(const Node *N) {
322 return N->getType() == NK_KeyValue;
323 }
324
325 private:
326 Node *Key = nullptr;
327 Node *Value = nullptr;
328 };
329
330 /// This is an iterator abstraction over YAML collections shared by both
331 /// sequences and maps.
332 ///
333 /// BaseT must have a ValueT* member named CurrentEntry and a member function
334 /// increment() which must set CurrentEntry to 0 to create an end iterator.
335 template <class BaseT, class ValueT> class basic_collection_iterator {
336 public:
337 using iterator_category = std::input_iterator_tag;
338 using value_type = ValueT;
339 using difference_type = std::ptrdiff_t;
340 using pointer = value_type *;
341 using reference = value_type &;
342
343 basic_collection_iterator() = default;
basic_collection_iterator(BaseT * B)344 basic_collection_iterator(BaseT *B) : Base(B) {}
345
346 ValueT *operator->() const {
347 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
348 return Base->CurrentEntry;
349 }
350
351 ValueT &operator*() const {
352 assert(Base && Base->CurrentEntry &&
353 "Attempted to dereference end iterator!");
354 return *Base->CurrentEntry;
355 }
356
357 operator ValueT *() const {
358 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
359 return Base->CurrentEntry;
360 }
361
362 /// Note on EqualityComparable:
363 ///
364 /// The iterator is not re-entrant,
365 /// it is meant to be used for parsing YAML on-demand
366 /// Once iteration started - it can point only to one entry at a time
367 /// hence Base.CurrentEntry and Other.Base.CurrentEntry are equal
368 /// iff Base and Other.Base are equal.
369 bool operator==(const basic_collection_iterator &Other) const {
370 if (Base && (Base == Other.Base)) {
371 assert((Base->CurrentEntry == Other.Base->CurrentEntry)
372 && "Equal Bases expected to point to equal Entries");
373 }
374
375 return Base == Other.Base;
376 }
377
378 bool operator!=(const basic_collection_iterator &Other) const {
379 return !(Base == Other.Base);
380 }
381
382 basic_collection_iterator &operator++() {
383 assert(Base && "Attempted to advance iterator past end!");
384 Base->increment();
385 // Create an end iterator.
386 if (!Base->CurrentEntry)
387 Base = nullptr;
388 return *this;
389 }
390
391 private:
392 BaseT *Base = nullptr;
393 };
394
395 // The following two templates are used for both MappingNode and Sequence Node.
396 template <class CollectionType>
begin(CollectionType & C)397 typename CollectionType::iterator begin(CollectionType &C) {
398 assert(C.IsAtBeginning && "You may only iterate over a collection once!");
399 C.IsAtBeginning = false;
400 typename CollectionType::iterator ret(&C);
401 ++ret;
402 return ret;
403 }
404
skip(CollectionType & C)405 template <class CollectionType> void skip(CollectionType &C) {
406 // TODO: support skipping from the middle of a parsed collection ;/
407 assert((C.IsAtBeginning || C.IsAtEnd) && "Cannot skip mid parse!");
408 if (C.IsAtBeginning)
409 for (typename CollectionType::iterator i = begin(C), e = C.end(); i != e;
410 ++i)
411 i->skip();
412 }
413
414 /// Represents a YAML map created from either a block map for a flow map.
415 ///
416 /// This parses the YAML stream as increment() is called.
417 ///
418 /// Example:
419 /// Name: _main
420 /// Scope: Global
421 class LLVM_ABI MappingNode final : public Node {
422 void anchor() override;
423
424 public:
425 enum MappingType {
426 MT_Block,
427 MT_Flow,
428 MT_Inline ///< An inline mapping node is used for "[key: value]".
429 };
430
MappingNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,MappingType MT)431 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
432 MappingType MT)
433 : Node(NK_Mapping, D, Anchor, Tag), Type(MT) {}
434
435 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
436
437 using iterator = basic_collection_iterator<MappingNode, KeyValueNode>;
438
439 template <class T> friend typename T::iterator yaml::begin(T &);
440 template <class T> friend void yaml::skip(T &);
441
begin()442 iterator begin() { return yaml::begin(*this); }
443
end()444 iterator end() { return iterator(); }
445
skip()446 void skip() override { yaml::skip(*this); }
447
classof(const Node * N)448 static bool classof(const Node *N) {
449 return N->getType() == NK_Mapping;
450 }
451
452 private:
453 MappingType Type;
454 bool IsAtBeginning = true;
455 bool IsAtEnd = false;
456 KeyValueNode *CurrentEntry = nullptr;
457
458 void increment();
459 };
460
461 /// Represents a YAML sequence created from either a block sequence for a
462 /// flow sequence.
463 ///
464 /// This parses the YAML stream as increment() is called.
465 ///
466 /// Example:
467 /// - Hello
468 /// - World
469 class LLVM_ABI SequenceNode final : public Node {
470 void anchor() override;
471
472 public:
473 enum SequenceType {
474 ST_Block,
475 ST_Flow,
476 // Use for:
477 //
478 // key:
479 // - val1
480 // - val2
481 //
482 // As a BlockMappingEntry and BlockEnd are not created in this case.
483 ST_Indentless
484 };
485
SequenceNode(std::unique_ptr<Document> & D,StringRef Anchor,StringRef Tag,SequenceType ST)486 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
487 SequenceType ST)
488 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST) {}
489
490 friend class basic_collection_iterator<SequenceNode, Node>;
491
492 using iterator = basic_collection_iterator<SequenceNode, Node>;
493
494 template <class T> friend typename T::iterator yaml::begin(T &);
495 template <class T> friend void yaml::skip(T &);
496
497 void increment();
498
begin()499 iterator begin() { return yaml::begin(*this); }
500
end()501 iterator end() { return iterator(); }
502
skip()503 void skip() override { yaml::skip(*this); }
504
classof(const Node * N)505 static bool classof(const Node *N) {
506 return N->getType() == NK_Sequence;
507 }
508
509 private:
510 SequenceType SeqType;
511 bool IsAtBeginning = true;
512 bool IsAtEnd = false;
513 bool WasPreviousTokenFlowEntry = true; // Start with an imaginary ','.
514 Node *CurrentEntry = nullptr;
515 };
516
517 /// Represents an alias to a Node with an anchor.
518 ///
519 /// Example:
520 /// *AnchorName
521 class LLVM_ABI AliasNode final : public Node {
522 void anchor() override;
523
524 public:
AliasNode(std::unique_ptr<Document> & D,StringRef Val)525 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
526 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
527
getName()528 StringRef getName() const { return Name; }
529
classof(const Node * N)530 static bool classof(const Node *N) { return N->getType() == NK_Alias; }
531
532 private:
533 StringRef Name;
534 };
535
536 /// A YAML Stream is a sequence of Documents. A document contains a root
537 /// node.
538 class Document {
539 public:
540 LLVM_ABI Document(Stream &ParentStream);
541
542 /// Root for parsing a node. Returns a single node.
543 LLVM_ABI Node *parseBlockNode();
544
545 /// Finish parsing the current document and return true if there are
546 /// more. Return false otherwise.
547 LLVM_ABI bool skip();
548
549 /// Parse and return the root level node.
getRoot()550 Node *getRoot() {
551 if (Root)
552 return Root;
553 return Root = parseBlockNode();
554 }
555
getTagMap()556 const std::map<StringRef, StringRef> &getTagMap() const { return TagMap; }
557
558 private:
559 friend class Node;
560 friend class document_iterator;
561
562 /// Stream to read tokens from.
563 Stream &stream;
564
565 /// Used to allocate nodes to. All are destroyed without calling their
566 /// destructor when the document is destroyed.
567 BumpPtrAllocator NodeAllocator;
568
569 /// The root node. Used to support skipping a partially parsed
570 /// document.
571 Node *Root;
572
573 /// Maps tag prefixes to their expansion.
574 std::map<StringRef, StringRef> TagMap;
575
576 Token &peekNext();
577 Token getNext();
578 void setError(const Twine &Message, Token &Location) const;
579 bool failed() const;
580
581 /// Parse %BLAH directives and return true if any were encountered.
582 bool parseDirectives();
583
584 /// Parse %YAML
585 void parseYAMLDirective();
586
587 /// Parse %TAG
588 void parseTAGDirective();
589
590 /// Consume the next token and error if it is not \a TK.
591 bool expectToken(int TK);
592 };
593
594 /// Iterator abstraction for Documents over a Stream.
595 class document_iterator {
596 public:
597 document_iterator() = default;
document_iterator(std::unique_ptr<Document> & D)598 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
599
600 bool operator==(const document_iterator &Other) const {
601 if (isAtEnd() || Other.isAtEnd())
602 return isAtEnd() && Other.isAtEnd();
603
604 return Doc == Other.Doc;
605 }
606 bool operator!=(const document_iterator &Other) const {
607 return !(*this == Other);
608 }
609
610 document_iterator operator++() {
611 assert(Doc && "incrementing iterator past the end.");
612 if (!(*Doc)->skip()) {
613 Doc->reset(nullptr);
614 } else {
615 Stream &S = (*Doc)->stream;
616 Doc->reset(new Document(S));
617 }
618 return *this;
619 }
620
621 Document &operator*() { return **Doc; }
622
623 std::unique_ptr<Document> &operator->() { return *Doc; }
624
625 private:
isAtEnd()626 bool isAtEnd() const { return !Doc || !*Doc; }
627
628 std::unique_ptr<Document> *Doc = nullptr;
629 };
630
631 } // end namespace yaml
632
633 } // end namespace llvm
634
635 #endif // LLVM_SUPPORT_YAMLPARSER_H
636