Yume
print_visitor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "util.hpp"
4#include "visitor.hpp"
5#include <iosfwd>
6#include <string>
7
8namespace yume::ast {
9class AST;
10}
11namespace llvm {
12class raw_ostream;
13}
14
15namespace yume::diagnostic {
16class PrintVisitor : public Visitor {
17 llvm::raw_ostream& m_stream;
18 bool m_pretty;
19 bool m_needs_sep = false;
20 int m_indent = 0;
21
22 void header(string_view label);
23 void indent(string_view text);
24
25public:
26 explicit PrintVisitor(llvm::raw_ostream& stream, bool pretty = false) : m_stream{stream}, m_pretty(pretty) {}
27 ~PrintVisitor() override = default;
28
29 PrintVisitor(const PrintVisitor&) = delete;
31 auto operator=(const PrintVisitor&) -> PrintVisitor& = delete;
32 auto operator=(PrintVisitor&&) -> PrintVisitor& = delete;
33
34 auto visit(const ast::AST& expr, string_view label) -> PrintVisitor& override;
35 auto visit(std::nullptr_t null, string_view label) -> PrintVisitor& override;
36 auto visit(const string& str, string_view label) -> PrintVisitor& override;
37};
38
39inline void PrintVisitor::header(string_view label) {
40 if (m_needs_sep)
41 m_stream << (m_pretty ? ("\n" + std::string(m_indent * 2UL, ' ')) : " ");
42 else
43 m_needs_sep = true;
44
45 if (!label.empty())
46 m_stream << label << "=";
47}
48
49inline void PrintVisitor::indent(string_view text) {
50 m_stream << text;
51 ++m_indent;
52 m_stream << std::string(m_indent * 2UL, ' ');
53}
54
55inline auto PrintVisitor::visit(const ast::AST& expr, string_view label) -> PrintVisitor& {
56 header(label);
57
58 m_stream.changeColor(llvm::raw_ostream::SAVEDCOLOR, true) << expr.kind_name();
59 m_stream.resetColor();
60 m_stream << "(";
61 if (m_pretty)
62 indent("\n");
63 m_needs_sep = false;
64
65 expr.visit(*this);
66 if (m_pretty)
67 --m_indent;
68 m_stream << ")";
69 m_needs_sep = true;
70
71 return *this;
72}
73
74inline auto PrintVisitor::visit(const string& str, string_view label) -> PrintVisitor& {
75 header(label);
76
77 m_stream << '\"';
78 m_stream.write_escaped(str);
79 m_stream << '\"';
80
81 return *this;
82}
83
84inline auto PrintVisitor::visit(std::nullptr_t, string_view label) -> PrintVisitor& {
85 header(label);
86
87 m_stream.changeColor(llvm::raw_ostream::RED) << "null";
88 m_stream.resetColor();
89
90 return *this;
91}
92} // namespace yume::diagnostic
All nodes in the AST tree of the program inherit from this class.
Definition: ast.hpp:224
PrintVisitor(PrintVisitor &&)=delete
auto visit(const ast::AST &expr, string_view label) -> PrintVisitor &override
auto operator=(const PrintVisitor &) -> PrintVisitor &=delete
PrintVisitor(const PrintVisitor &)=delete
auto operator=(PrintVisitor &&) -> PrintVisitor &=delete
PrintVisitor(llvm::raw_ostream &stream, bool pretty=false)
~PrintVisitor() override=default
Definition: ast.hpp:20
Definition: ast.cpp:8