-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpasses.hh
118 lines (102 loc) · 1.96 KB
/
passes.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#pragma once
#include "document.hh"
#include <memory>
#include <fstream>
/**
* A pass that processes a text tree.
*/
struct TextPass
{
/**
* The name of the pass.
*/
virtual TextTreePointer process(TextTreePointer tree) = 0;
/**
* Virtual destructor.
*/
virtual ~TextPass() = default;
};
struct OutputPass : public TextPass
{
std::unique_ptr<std::fstream> file;
enum OutputType {
StdOut,
StdErr,
File
} output_type = StdOut;
std::ostream &out()
{
switch (output_type)
{
case StdOut:
return std::cout;
case StdErr:
return std::cerr;
case File:
return *file;
}
}
void output_stdout()
{
file.reset();
output_type = StdOut;
}
void output_stderr()
{
file.reset();
output_type = StdErr;
}
void output_file(std::string filename)
{
file = std::make_unique<std::fstream>(
filename, std::ios::out | std::ios::binary | std::ios::trunc);
output_type = File;
}
};
struct TextPassFactory
{
virtual std::string name() = 0;
virtual std::shared_ptr<TextPass> create() = 0;
};
class TextPassRegistry
{
inline static std::unordered_map<std::string,
std::shared_ptr<TextPassFactory>>
passes;
template<typename T>
struct SingletonTextPassFactory : public TextPassFactory
{
std::string name() override
{
return T::name();
}
std::shared_ptr<TextPass> create() override
{
static std::shared_ptr<T> instance = std::make_shared<T>();
return instance;
}
static std::shared_ptr<TextPassFactory> factory()
{
return std::make_shared<SingletonTextPassFactory<T>>();
}
};
public:
static void add(std::shared_ptr<TextPassFactory> pass)
{
passes[pass->name()] = pass;
}
static std::shared_ptr<TextPass> create(const std::string &name)
{
auto it = passes.find(name);
if (it == passes.end())
{
return nullptr;
}
return it->second->create();
}
template<typename T>
static void add()
{
add(SingletonTextPassFactory<T>::factory());
}
};