-
Notifications
You must be signed in to change notification settings - Fork 0
/
Compiler.cpp
151 lines (118 loc) · 2.48 KB
/
Compiler.cpp
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include "Compiler.h"
#include "Node.h"
#include "Package.h"
#include "StaticChecker.h"
#include "CodeGen.h"
#include "grammar/SSLexer.hpp"
#include "grammar/SSParser.hpp"
namespace SS {
static Compiler* g_compiler = 0;
Compiler* GetActiveCompiler()
{
return g_compiler;
}
template<class T>
String ToString(const T& val)
{
std::stringstream ss;
ss << val;
return ss.str();
}
String CompilerMessage::Format() const
{
String result;
if(m_file != 0)
{
result += m_file->GetFilename();
if(m_line > 0)
{
result += ":";
result += ToString(m_line);
}
result += ": ";
}
if(m_msgType == MSG_WARNING)
result += "warning: ";
return result + m_text;
}
Compiler::Compiler() : m_compiled(false), m_errors(0), m_warnings(0), m_succeeded(false), m_pkg(0), m_listener(0)
{
m_pkg = new Package();
}
Compiler::~Compiler()
{
if(m_pkg != 0)
delete m_pkg;
}
void Compiler::Parse(const String& filename, const String& scriptText)
{
std::stringstream sstream(scriptText);
Compiler::Parse(filename, sstream);
}
void Compiler::Parse(const String& filename, std::istream& scriptStream)
{
SSAssert(!m_compiled);
g_compiler = this;
FileInfo* fileInfo = m_pkg->AddFile(filename);
SSAssert(fileInfo != 0);
try
{
SSLexer lexer(scriptStream);
SSParser parser(lexer);
parser.m_fileInfo = fileInfo;
parser.translationUnit(m_pkg);
}
catch(antlr::ANTLRException& e)
{
ReportError(e.toString());
}
g_compiler = 0;
}
Package* Compiler::Compile(const String& pkgName)
{
SSAssert(!m_compiled);
Package* ret = 0;
m_compiled = true;
g_compiler = this;
if(AnyErrors())
goto Failed;
m_pkg->SetName(pkgName);
{
StaticChecker checker(m_pkg);
if(!checker.Check())
goto Failed;
}
// CODE GENERATION
for(int i=0; i < m_pkg->GetClassCount(); ++i)
{
Class* cls = m_pkg->GetClass(i);
for(int j=0; j < cls->GetFunctionCount(); ++j)
{
Function* func = cls->GetFunction(j);
CodeGen gen;
gen.Generate(func);
}
}
if(AnyErrors())
goto Failed;
ret = m_pkg;
m_pkg = 0;
m_succeeded = true;
g_compiler = 0;
return ret;
Failed:
g_compiler = 0;
delete m_pkg;
m_pkg = 0;
return 0;
}
void Compiler::ReportMessage(const CompilerMessage& msg)
{
if(msg.GetMessageType() == MSG_ERROR)
++m_errors;
else if(msg.GetMessageType() == MSG_WARNING)
++m_warnings;
if(m_listener != 0)
m_listener->OnCompilerMessage(msg);
}
}