1 //===--- YAMLParser.h - Simple YAML parser --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a YAML 1.2 parser.
12 // See http://www.yaml.org/spec/1.2/spec.html for the full standard.
14 // This currently does not implement the following:
15 // * Multi-line literal folding.
18 // * BOMs anywhere other than the first Unicode scalar value in the file.
20 // The most important class here is Stream. This represents a YAML stream with
21 // 0, 1, or many documents.
24 // StringRef input = getInput();
25 // yaml::Stream stream(input, sm);
27 // for (yaml::document_iterator di = stream.begin(), de = stream.end();
29 // yaml::Node *n = di->getRoot();
31 // // Do something with n...
36 //===----------------------------------------------------------------------===//
38 #ifndef LLVM_SUPPORT_YAMLPARSER_H
39 #define LLVM_SUPPORT_YAMLPARSER_H
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/Support/Allocator.h"
44 #include "llvm/Support/SMLoc.h"
57 class document_iterator;
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 &);
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);
72 /// @brief Escape \a Input for a double quoted scalar.
73 std::string escape(StringRef Input);
75 /// @brief This class represents a YAML stream potentially containing multiple
79 /// @brief This keeps a reference to the string referenced by \p Input.
80 Stream(StringRef Input, SourceMgr &);
82 /// @brief This takes ownership of \p InputBuffer.
83 Stream(MemoryBuffer *InputBuffer, SourceMgr &);
86 document_iterator begin();
87 document_iterator end();
95 void printError(Node *N, const Twine &Msg);
98 std::unique_ptr<Scanner> scanner;
99 std::unique_ptr<Document> CurrentDoc;
101 friend class Document;
104 /// @brief Abstract base class for all Nodes.
106 virtual void anchor();
117 Node(unsigned int Type, std::unique_ptr<Document> &, StringRef Anchor,
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; }
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; }
128 /// \brief Get the verbatium tag for a given Node. This performs tag resoluton
129 /// and substitution.
130 std::string getVerbatimTag() const;
132 SMRange getSourceRange() const { return SourceRange; }
133 void setSourceRange(SMRange SR) { SourceRange = SR; }
135 // These functions forward to Document and Scanner.
138 Node *parseBlockNode();
139 BumpPtrAllocator &getAllocator();
140 void setError(const Twine &Message, Token &Location) const;
143 virtual void skip() {}
145 unsigned int getType() const { return TypeID; }
147 void *operator new ( size_t Size
148 , BumpPtrAllocator &Alloc
149 , size_t Alignment = 16) throw() {
150 return Alloc.Allocate(Size, Alignment);
153 void operator delete(void *Ptr, BumpPtrAllocator &Alloc, size_t) throw() {
154 Alloc.Deallocate(Ptr);
158 std::unique_ptr<Document> &Doc;
161 void operator delete(void *) throw() {}
168 /// \brief The tag as typed in the document.
172 /// @brief A null value.
176 class NullNode : public Node {
177 void anchor() override;
179 NullNode(std::unique_ptr<Document> &D)
180 : Node(NK_Null, D, StringRef(), StringRef()) {}
182 static inline bool classof(const Node *N) {
183 return N->getType() == NK_Null;
187 /// @brief A scalar node is an opaque datum that can be presented as a
188 /// series of zero or more Unicode scalar values.
192 class ScalarNode : public Node {
193 void anchor() override;
195 ScalarNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
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);
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
206 StringRef getRawValue() const { return Value; }
208 /// @brief Gets the value of this node as a StringRef.
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;
215 static inline bool classof(const Node *N) {
216 return N->getType() == NK_Scalar;
222 StringRef unescapeDoubleQuoted( StringRef UnquotedValue
223 , StringRef::size_type Start
224 , SmallVectorImpl<char> &Storage) const;
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.
230 /// TODO: Consider making this not a child of Node.
234 class KeyValueNode : public Node {
235 void anchor() override;
237 KeyValueNode(std::unique_ptr<Document> &D)
238 : Node(NK_KeyValue, D, StringRef(), StringRef()), Key(nullptr),
241 /// @brief Parse and return the key.
243 /// This may be called multiple times.
245 /// @returns The key, or nullptr if failed() == true.
248 /// @brief Parse and return the value.
250 /// This may be called multiple times.
252 /// @returns The value, or nullptr if failed() == true.
255 void skip() override {
260 static inline bool classof(const Node *N) {
261 return N->getType() == NK_KeyValue;
269 /// @brief This is an iterator abstraction over YAML collections shared by both
270 /// sequences and maps.
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> {
278 basic_collection_iterator() : Base(nullptr) {}
279 basic_collection_iterator(BaseT *B) : Base(B) {}
281 ValueT *operator ->() const {
282 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
283 return Base->CurrentEntry;
286 ValueT &operator *() const {
287 assert(Base && Base->CurrentEntry &&
288 "Attempted to dereference end iterator!");
289 return *Base->CurrentEntry;
292 operator ValueT*() const {
293 assert(Base && Base->CurrentEntry && "Attempted to access end iterator!");
294 return Base->CurrentEntry;
297 bool operator !=(const basic_collection_iterator &Other) const {
298 if(Base != Other.Base)
300 return (Base && Other.Base) && Base->CurrentEntry
301 != Other.Base->CurrentEntry;
304 basic_collection_iterator &operator++() {
305 assert(Base && "Attempted to advance iterator past end!");
307 // Create an end iterator.
308 if (!Base->CurrentEntry)
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);
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!");
332 for (typename CollectionType::iterator i = begin(C), e = C.end();
337 /// @brief Represents a YAML map created from either a block map for a flow map.
339 /// This parses the YAML stream as increment() is called.
344 class MappingNode : public Node {
345 void anchor() override;
350 MT_Inline ///< An inline mapping node is used for "[key: value]".
353 MappingNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
355 : Node(NK_Mapping, D, Anchor, Tag), Type(MT), IsAtBeginning(true),
356 IsAtEnd(false), CurrentEntry(nullptr) {}
358 friend class basic_collection_iterator<MappingNode, KeyValueNode>;
359 typedef basic_collection_iterator<MappingNode, KeyValueNode> iterator;
360 template <class T> friend typename T::iterator yaml::begin(T &);
361 template <class T> friend void yaml::skip(T &);
364 return yaml::begin(*this);
367 iterator end() { return iterator(); }
369 void skip() override {
373 static inline bool classof(const Node *N) {
374 return N->getType() == NK_Mapping;
381 KeyValueNode *CurrentEntry;
386 /// @brief Represents a YAML sequence created from either a block sequence for a
389 /// This parses the YAML stream as increment() is called.
394 class SequenceNode : public Node {
395 void anchor() override;
406 // As a BlockMappingEntry and BlockEnd are not created in this case.
410 SequenceNode(std::unique_ptr<Document> &D, StringRef Anchor, StringRef Tag,
412 : Node(NK_Sequence, D, Anchor, Tag), SeqType(ST), IsAtBeginning(true),
414 WasPreviousTokenFlowEntry(true), // Start with an imaginary ','.
415 CurrentEntry(nullptr) {}
417 friend class basic_collection_iterator<SequenceNode, Node>;
418 typedef basic_collection_iterator<SequenceNode, Node> iterator;
419 template <class T> friend typename T::iterator yaml::begin(T &);
420 template <class T> friend void yaml::skip(T &);
425 return yaml::begin(*this);
428 iterator end() { return iterator(); }
430 void skip() override {
434 static inline bool classof(const Node *N) {
435 return N->getType() == NK_Sequence;
439 SequenceType SeqType;
442 bool WasPreviousTokenFlowEntry;
446 /// @brief Represents an alias to a Node with an anchor.
450 class AliasNode : public Node {
451 void anchor() override;
453 AliasNode(std::unique_ptr<Document> &D, StringRef Val)
454 : Node(NK_Alias, D, StringRef(), StringRef()), Name(Val) {}
456 StringRef getName() const { return Name; }
459 static inline bool classof(const Node *N) {
460 return N->getType() == NK_Alias;
467 /// @brief A YAML Stream is a sequence of Documents. A document contains a root
471 /// @brief Root for parsing a node. Returns a single node.
472 Node *parseBlockNode();
474 Document(Stream &ParentStream);
476 /// @brief Finish parsing the current document and return true if there are
477 /// more. Return false otherwise.
480 /// @brief Parse and return the root level node.
484 return Root = parseBlockNode();
487 const std::map<StringRef, StringRef> &getTagMap() const {
493 friend class document_iterator;
495 /// @brief Stream to read tokens from.
498 /// @brief Used to allocate nodes to. All are destroyed without calling their
499 /// destructor when the document is destroyed.
500 BumpPtrAllocator NodeAllocator;
502 /// @brief The root node. Used to support skipping a partially parsed
506 /// \brief Maps tag prefixes to their expansion.
507 std::map<StringRef, StringRef> TagMap;
511 void setError(const Twine &Message, Token &Location) const;
514 /// @brief Parse %BLAH directives and return true if any were encountered.
515 bool parseDirectives();
517 /// \brief Parse %YAML
518 void parseYAMLDirective();
520 /// \brief Parse %TAG
521 void parseTAGDirective();
523 /// @brief Consume the next token and error if it is not \a TK.
524 bool expectToken(int TK);
527 /// @brief Iterator abstraction for Documents over a Stream.
528 class document_iterator {
530 document_iterator() : Doc(nullptr) {}
531 document_iterator(std::unique_ptr<Document> &D) : Doc(&D) {}
533 bool operator ==(const document_iterator &Other) {
534 if (isAtEnd() || Other.isAtEnd())
535 return isAtEnd() && Other.isAtEnd();
537 return Doc == Other.Doc;
539 bool operator !=(const document_iterator &Other) {
540 return !(*this == Other);
543 document_iterator operator ++() {
544 assert(Doc && "incrementing iterator past the end.");
545 if (!(*Doc)->skip()) {
548 Stream &S = (*Doc)->stream;
549 Doc->reset(new Document(S));
554 Document &operator *() {
558 std::unique_ptr<Document> &operator->() { return *Doc; }
561 bool isAtEnd() const {
562 return !Doc || !*Doc;
565 std::unique_ptr<Document> *Doc;