-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfarpy.ts
More file actions
310 lines (253 loc) · 7.13 KB
/
farpy.ts
File metadata and controls
310 lines (253 loc) · 7.13 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/**
* Farpy - A programming language
*
* Copyright (c) 2025 Fernando (FernandoTheDev)
*
* This software is licensed under the MIT License.
* See the LICENSE file in the project root for full license information.
*/
import { parseArgs } from "jsr:@std/cli";
import { Lexer } from "./src/frontend/lexer/lexer.ts";
import { Parser } from "./src/frontend/parser/parser.ts";
import { Semantic } from "./src/middle/semantic.ts";
import { LLVMIRGenerator } from "./src/middle/llvm_ir_gen.ts";
import { FarpyCompiler, Logger } from "./src/backend/compiler.ts";
import { DiagnosticReporter } from "./src/error/diagnosticReporter.ts";
import { Token } from "./src/frontend/lexer/token.ts";
import { Optimizer } from "./src/middle/optimizer.ts";
import { Program } from "./src/frontend/parser/ast.ts";
import { DeadCodeAnalyzer } from "./src/middle/dead_code_analyzer.ts";
import {
ARG_CONFIG,
HELP_MESSAGE,
TARGET_HELP_MESSAGE,
VERSION,
} from "./config.ts";
import { repl } from "./cli/repl.ts";
export class FarpyCompilerMain {
private fileName: string;
private fileData: string;
private readonly reporter: DiagnosticReporter;
private args;
constructor(args: string[]) {
this.args = parseArgs(args, ARG_CONFIG);
this.reporter = new DiagnosticReporter();
if (this.shouldShowTargetHelp()) {
this.showTargetHelp();
Deno.exit(0);
}
if (this.shouldShowHelp()) {
this.showHelp();
Deno.exit(0);
}
if (this.shouldShowVersion()) {
this.showVersion();
Deno.exit(0);
}
if (this.isCliMode()) {
this.cliMode();
Deno.exit(0);
}
this.fileName = this.args._[0] as string;
if (!this.validateFile()) {
console.error("ERROR: Valid source file is required.");
Deno.exit(-1);
}
try {
this.fileData = Deno.readTextFileSync(this.fileName);
} catch (_error) {
Logger.error(`O arquivo '${this.fileName}' não existe.`);
Deno.exit(-1);
}
}
private shouldShowTargetHelp(): boolean {
return this.args.targeth === true;
}
private showTargetHelp(): void {
console.log(TARGET_HELP_MESSAGE);
}
private shouldDeadCode(): boolean {
return this.args.dc === true;
}
private shouldOptimize(): boolean {
return this.args.optimize === true;
}
private shouldShowHelp(): boolean {
return this.args.help === true;
}
private shouldShowVersion(): boolean {
return this.args.version === true;
}
private isDebug(): boolean {
return this.args.debug === true;
}
private isCliMode(): boolean {
return this.args.cli === true;
}
private async cliMode(): Promise<void> {
await repl();
}
private showHelp(): void {
console.log(HELP_MESSAGE);
}
private showVersion(): void {
console.log(`Farpy Compiler ${VERSION}`);
}
private validateFile(): boolean {
return typeof this.fileName === "string" && this.fileName.length > 0 &&
this.fileName.endsWith(".fp");
}
private checkErrorsAndWarnings(): boolean {
if (this.reporter.hasWarnings() && !this.reporter.hasErrors()) {
this.reporter.printDiagnostics();
console.log(this.reporter.getSummary());
}
if (this.reporter.hasErrors()) {
this.reporter.printDiagnostics();
console.log(this.reporter.getSummary());
Deno.exit(-1);
}
return true;
}
private runLexer(): Token[] | null {
const dir = Deno.cwd() + "/" +
this.fileName.substring(0, this.fileName.lastIndexOf("/")) + "/";
const tokens = new Lexer(
this.fileName,
this.fileData,
dir,
this.reporter,
)
.tokenize();
if (!this.checkErrorsAndWarnings()) return null;
return tokens as Token[];
}
private runParser(tokens: Token[]): Program | null {
const ast = new Parser(tokens, this.reporter).parse();
if (!this.checkErrorsAndWarnings()) return null;
return ast;
}
private handleAstJson(ast: Program): boolean {
if (this.args["emit-ast"]) {
Deno.writeTextFileSync(
"ast.json",
JSON.stringify(ast, null, "\t"),
);
return true;
}
return false;
}
private runDeadCodeAnalyzer(
ast: Program,
semantic: Semantic,
): Program | null {
const analyzer = new DeadCodeAnalyzer(semantic, this.reporter).analyze(
ast,
);
if (!this.checkErrorsAndWarnings()) return null;
return analyzer;
}
private runOptimizer(ast: Program): Program | null {
const optimizer = new Optimizer(this.reporter).resume(ast);
if (!this.checkErrorsAndWarnings()) return null;
return optimizer;
}
private generateLLVMIR(
semanticAST: Program,
semantic: Semantic,
debug: boolean,
): { ir: string; externs: string[] } {
const llvmIrGen = LLVMIRGenerator.getInstance(this.reporter, debug);
const ir = llvmIrGen.generateIR(semanticAST, semantic, this.fileName);
llvmIrGen.resetInstance(); // Reset
return {
ir: ir,
externs: llvmIrGen.externs,
};
}
private handleEmitIR(): boolean {
return this.args["emit-ir"] != "";
}
private async runBackendCompilation(
llvmIR: string,
semantic: Semantic,
target: string = "",
externs: string[],
): Promise<void> {
const compiler = new FarpyCompiler(
llvmIR,
this.args["output"],
semantic,
this.args["debug"],
target,
externs,
);
await compiler.compile();
}
public async run(): Promise<void> {
try {
const tokens = this.runLexer();
if (!tokens) return;
let ast = this.runParser(tokens);
if (!ast) return;
if (this.handleAstJson(ast)) return;
const semantic = Semantic.getInstance(this.reporter);
ast = semantic.semantic(ast);
if (!this.checkErrorsAndWarnings()) return;
semantic.resetInstance(); // Reset
if (this.shouldOptimize()) {
ast = this.runOptimizer(ast);
}
if (this.shouldDeadCode()) {
ast = this.runDeadCodeAnalyzer(ast!, semantic);
}
const llvmIR = this.generateLLVMIR(
ast!,
semantic,
this.isDebug(),
);
if (this.handleEmitIR()) {
await Deno.writeFile(
`${this.fileName.replace(".fp", ".ll")}`,
new TextEncoder().encode(llvmIR.ir),
);
return;
}
await this.runBackendCompilation(
llvmIR.ir,
semantic,
this.args.target ?? "",
llvmIR.externs,
);
} catch (error: unknown) {
console.error("Compilation failed:", error);
Deno.exit(1);
}
}
}
async function main() {
const home = Deno.env.get("HOME");
if (!home) {
Logger.error("Could not get $HOME variable from your environment.");
return;
}
const path = `${home}/.farpy/`;
try {
if ((await Deno.stat(path)).isDirectory === false) {
throw new Error("Directory does not exist.");
}
} catch (_err) {
Logger.error(
`Compiler installation failed, directory '${path}' not found, please reinstall the compiler.`,
);
return;
}
const compiler = new FarpyCompilerMain(Deno.args);
await compiler.run();
}
if (import.meta.main) {
main().catch((error) => {
console.error("Fatal error:", error);
Deno.exit(1);
});
}