-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompiler.cpp
592 lines (504 loc) · 14.4 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
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
#include "Compiler.h"
#include "CompilerContext.h"
#include "Source.h"
#include "Parser.h"
#include "Lexer.h"
#include "Expressions.h"
#include "UniquePtr.h"
#include "Project.h"
#include "OptionParser.h"
#ifdef _WIN32
#include <direct.h>
#else
#include <sys/stat.h>
#endif
#include <fstream>
#include <sstream>
using namespace Jet;
#ifdef _WIN32
#include <Windows.h>
#include <sys/stat.h>
#else
#include <sys/types.h>
#include <unistd.h>
#endif
#include <process.h>
#include <thread>
//this adds all the available options to the parser for jet
void Jet::SetupDefaultCommandOptions(OptionParser* parser)
{
parser->AddOption("o", "0", true);
parser->AddOption("f", "0", true);
parser->AddOption("t", "0", true);
parser->AddOption("r", "0", true);
parser->AddOption("target", "", false);
parser->AddOption("linker", "", false);
parser->AddOption("debug", "2", false);
parser->AddOption("ir", "0", true);
}
//this reads the options out of the parser and applys them
void CompilerOptions::ApplyOptions(OptionParser* parser)
{
this->optimization = parser->GetOption("o").GetInt();
this->force = parser->GetOption("f").GetBool();
this->time = parser->GetOption("t").GetBool();
this->run = parser->GetOption("r").GetBool();
this->target = parser->GetOption("target").GetString();
this->linker = parser->GetOption("linker").GetString();
this->debug = parser->GetOption("debug").GetInt();
this->output_ir = parser->GetOption("ir").GetBool();
}
void Jet::Diagnostic::Print()
{
if (token.type != TokenType::InvalidToken)
{
unsigned int startrow = token.column;
unsigned int endrow = token.column + token.text.length();
std::string code = this->line;
std::string underline = "";
for (unsigned int i = 0; i < code.length(); i++)
{
if (code[i] == '\t')
underline += '\t';
else if (i >= startrow && i < endrow)
underline += '~';
else
underline += ' ';
}
printf("[error] %s %d:%d to %d:%d: %s\n[error] >>>%s\n[error] >>>%s\n\n", this->file.c_str(), token.line, startrow, token.line, endrow, message.c_str(), code.c_str(), underline.c_str());
}
else
{
//just print something out, it was probably a build system error, not one that occurred in the code
printf("[error] %s: %s\n", this->file.c_str(), message.c_str());
}
}
class MemberRenamer : public ExpressionVisitor
{
std::string stru, member, newname;
Compilation* compiler;
public:
MemberRenamer(std::string stru, std::string member, std::string newname, Compilation* compiler) : stru(stru), member(member), newname(newname), compiler(compiler)
{
}
virtual void Visit(CallExpression* expr)
{
}
virtual void Visit(StructExpression* expr)
{
if (expr->GetName() == stru)
{
for (auto ii : expr->members)
{
if (ii.type == StructMember::VariableMember)
{
ii.variable.name.text = newname;
}
}
}
}
virtual void Visit(IndexExpression* expr)
{
if (expr->member.text.length() > 0 && expr->member.text == member)
{
auto type = expr->GetBaseType(compiler);
if ((expr->token.type == TokenType::Dot && type->type == Types::Struct && type->data->name == stru) || (expr->token.type == TokenType::Pointy && type->base->type == Types::Struct))
{
expr->member.text = newname;
}
}
}
};
void ExecuteProject(JetProject* project, const char* projectdir)
{
//now try running it if we are supposed to
#ifdef _WIN32
STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
std::string path = "build\\" + project->project_name + ".exe ";
CreateProcessA(path.c_str(), "", 0, 0, 0, CREATE_NEW_CONSOLE, 0, 0, &si, &pi);
//throw up a thread that closes the handle when its done
std::thread x([pi](){
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
});
x.detach();
#else
// todo run for linux
printf("WARNING: Running your program from the compiler is not yet supported in linux.");
#endif
//system(path.c_str());
//spawnl(P_NOWAIT, "cmd.exe", "cmd.exe", path.c_str(), 0);
}
extern std::string executable_path;
int Compiler::Compile(const char* projectdir, CompilerOptions* optons, const std::string& confg_name, OptionParser* parser)
{
std::unique_ptr<JetProject> project(JetProject::Load(projectdir));
if (project == 0)
return 0;
char olddir[1000];
getcwd(olddir, 1000);
std::string path = projectdir;
path += '/';
if (path.length() > 1)
chdir(path.c_str());
//build each dependency
bool needs_rebuild = false;
int deps = project->dependencies.size();
const std::vector<std::string>& resolved_deps = project->ResolveDependencies();
for (int i = 0; i < deps; i++)
{
auto ii = project->dependencies[i];
if (resolved_deps[i].length() == 0)
{
printf("Dependency: %s could not be found!\nMake sure to build it at least once so we can find it.\n", ii.c_str());
//make sure to restore old cwd
chdir(olddir);
return 0;
}
else
{
printf("Dependency \"%s\" resolved to %s.\n", ii.c_str(), resolved_deps[i].c_str());
}
ii = resolved_deps[i];
if (ii[0] != '.' && ii.find('/') == -1 && ii.find('\\') == -1)
{
//ok, search for the p/ackage using our database, we didnt give a path to one
std::string path = this->FindProject(ii, "0.0.0");
}
//spin up new compiler instance and build it
Compiler compiler;
auto success = compiler.Compile(ii.c_str());
if (success == 0)
{
printf("Dependency compilation failed, stopping compilation.");
//restore working directory
chdir(olddir);
return 0;
}
else if (success == 2)//compilation was successful but a rebuild was done, so we also need to rebuild
{
needs_rebuild = true;
}
}
printf("\nCompiling Project: %s\n", projectdir);
//read in buildtimes
std::vector<int> buildtimes;
std::ifstream rebuild("build/rebuild.txt");
std::string compiler_version;
if (rebuild.is_open())
{
bool first = true;
do
{
std::string line;
std::getline(rebuild, line, '\n');
if (line.length() == 0)
break;
int hi;
sscanf(line.c_str(), "%i", &hi);
if (first)
{
compiler_version = line;
first = false;
}
else
{
buildtimes.push_back(hi);
}
} while (true);
}
std::vector<time_t> modifiedtimes;
struct stat data;
int x = stat("project.jp", &data);
modifiedtimes.push_back(data.st_mtime);
for (auto ii : project->files)
{
struct stat data;
int x = stat(ii.c_str(), &data);
modifiedtimes.push_back(data.st_mtime);
}
//lets look at the .jlib modification time
//this need to use the correct paths from the located dependencies
for (auto ii : resolved_deps)
{
std::string path = ii;
path += "/build/symbols.jlib";
struct stat data;
int x = stat(path.c_str(), &data);
modifiedtimes.push_back(data.st_mtime);
}
std::string config_name = "";
if (parser)
{
SetupDefaultCommandOptions(parser);
if (parser->commands.size() > 1)
config_name = parser->commands[1];
}
//get the config, or default
JetProject::BuildConfig configuration;
if (config_name.length() > 0)
{
//find the configuration
bool found = false;
for (auto ii : project->configurations)
{
if (ii.name == confg_name)
{
configuration = ii;
found = true;
}
}
if (found == false && project->configurations.size() > 0)
{
configuration = *project->configurations.begin();
printf("WARNING: Build Configuration Name: '%s' Does Not Exist, Defaulting To '%s'\n", config_name.c_str(), project->configurations.begin()->name.c_str());
}
else if (found == false)
{
printf("WARNING: Build Configuration Name: '%s' Does Not Exist\n", config_name.c_str());
}
}
else
{
if (project->configurations.size() > 0)
{
configuration = *project->configurations.begin();
}
}
//read in config from command and stuff
CompilerOptions options;
if (parser)
{
parser->Parse(configuration.options);
options.ApplyOptions(parser);
}
else
{
OptionParser p;
SetupDefaultCommandOptions(&p);
p.Parse(configuration.options);
options.ApplyOptions(&p);
}
//add options to this later
FILE* jlib = fopen("build/symbols.jlib", "rb");
FILE* output = fopen(("build/" + project->project_name + ".o").c_str(), "rb");
if (options.force || needs_rebuild)
{
//the rebuild was forced
}
else if (strcmp(__TIME__, compiler_version.c_str()) != 0)//see if the compiler was the same
{
//do a rebuild compiler version is different
}
else if ((project->IsExecutable() == false && jlib == 0) || output == 0)//check if .jlib or .o exists
{
//output file missing, do a rebuild
}
else if (modifiedtimes.size() == buildtimes.size())//check if files were modified
{
for (unsigned int i = 0; i < modifiedtimes.size(); i++)
{
if (modifiedtimes[i] == buildtimes[i])
{
if (i == modifiedtimes.size() - 1)
{
printf("No Changes Detected, Compiling Skipped\n");
if (options.run && project->IsExecutable())
{
ExecuteProject(project.get(), projectdir);
Sleep(50);//give it a moment to run, for some reason derps up without this
}
else if (options.run)
{
printf("Warning: Ignoring run option because program is not executable.\n");
}
//restore working directory
chdir(olddir);
return 1;
}
}
else
{
break;
}
}
}
if (jlib) fclose(jlib);
if (output) fclose(output);
//Run prebuild commands
if (configuration.prebuild.length() > 0)
{
printf("%s", exec(configuration.prebuild.c_str()).c_str());
}
DiagnosticBuilder diagnostics([](Diagnostic& msg)
{
msg.Print();
});
std::unique_ptr<Compilation> compilation(Compilation::Make(project.get(), &diagnostics, options.time, options.debug));
error:
if (compilation == 0)
{
//compiling failed completely
//restore working directory
chdir(olddir);
return 0;
}
else if (compilation->GetErrors().size() > 0)
{
printf("Compiling Failed: %d Errors Found\n", compilation->GetErrors().size());
//restore working directory
chdir(olddir);
return 0;
}
else
{
compilation->Assemble(options.target, options.linker, options.optimization, options.time, options.output_ir);
//output build times
std::ofstream rebuild("build/rebuild.txt");
//output compiler version
rebuild.write(__TIME__, strlen(__TIME__));
rebuild.write("\n", 1);
for (auto ii : modifiedtimes)
{
char str[150];
#if 0 //_WIN32
int len = sprintf(str, "%i,%i\n", ii.first, ii.second);
#else
int len = sprintf(str, "%li\n", ii);
#endif
rebuild.write(str, len);
}
//todo: output for dependencies too
printf("Project built successfully.\n\n");
//running postbuild
if (configuration.postbuild.length() > 0)
printf("%s", exec(configuration.postbuild.c_str()).c_str());
//ok now lets add it to the project cache, lets be sure to always save a backup though and need to get current path of the jetc
if (executable_path.length())
{
this->UpdateProjectList(project.get());
}
if (options.run && project->IsExecutable())
{
ExecuteProject(project.get(), projectdir);
Sleep(50);//give it a moment to run, for some reason derps up without this
}
else if (options.run)
{
printf("Warning: Ignoring run option because program is not executable.\n");
}
//restore working directory
chdir(olddir);
return 2;
}
//restore working directory
chdir(olddir);
return 1;
}
std::string GetProjectDatabasePath()
{
//ok, now we need to remove our executable name from this
int pos = executable_path.find_last_of('\\');
if (pos == -1)
pos = executable_path.find_last_of('/');
std::string path = executable_path.substr(0, pos);
return path + "/project_database.txt";
}
std::vector<Compiler::ProjectInfo> Compiler::GetProjectList()
{
std::ifstream file(GetProjectDatabasePath(), std::ios_base::binary);
bool found = false;
std::string line;
std::vector<Compiler::ProjectInfo> vec;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string name, path, version;
//there is three parts, name, path and version separated by | and delimited by lines
int first = line.find_first_of('|');
int last = line.find_last_of('|');
if (first == -1 || first == last)
continue;//invalid line
name = line.substr(0, first);
path = line.substr(first + 1, last - 1 - first);
version = line.substr(last + 1, line.length() - last);
vec.push_back({ name, path, version });
}
return vec;
}
std::string Compiler::FindProject(const std::string& project_name, const std::string& desired_version)
{
auto projects = GetProjectList();
for (auto ii : projects)
{
//todo also check version
if (ii.name == project_name)
{
return ii.path;
}
}
return "";
}
void Compiler::UpdateProjectList(JetProject* project)
{
char curpath[500];
getcwd(curpath, 500);//todo escape our filename and project name and make parser above able to read it out
std::string db_filename = GetProjectDatabasePath();
//ok, lets scan through the database to see if we are in it
//todo: break this search out into a function
std::ifstream file(db_filename, std::ios_base::binary);
bool found = false;
std::string line;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::string name, path, version;
//there is three parts, name, path and version separated by | and delimited by lines
int first = line.find_first_of('|');
int last = line.find_last_of('|');
if (first == -1 || first == last)
continue;//invalid line
name = line.substr(0, first);
path = line.substr(first + 1, last - 1 - first);
version = line.substr(last + 1, line.length() - last);
if (name == project->project_name)
{
if (path != curpath)
{
printf("TWO PACKAGES WITH THE SAME NAME EXIST, THIS CAN CAUSE ISSUES!\n");
}
/*if (version != project->version)
{
//if the path is right, but the version changed we need to edit the version
printf("PACKAGE VERSION MISMATCH NEED TO HANDLE THIS\n");
}*/
found = true;
break;
}
}
//if we arent in it, backup the old one, then append ourselves to the new one
if (found == false)
{
//perform copy
{
std::ifstream source(db_filename, std::ios::binary);
std::ofstream dest(db_filename + ".backup", std::ios::binary);
std::istreambuf_iterator<char> begin_source(source);
std::istreambuf_iterator<char> end_source;
std::ostreambuf_iterator<char> begin_dest(dest);
copy(begin_source, end_source, begin_dest);
source.close();
dest.close();
}
//append our name
std::ofstream file(db_filename, std::ios_base::app);
file << project->project_name << "|" << curpath << '|' << project->version << '\n';
}
}