-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
693 lines (598 loc) · 23.8 KB
/
main.c
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
// TODO automatic linking and compiling
// TODO FLAG to generate the .c files for inspection (by default generate an ELF)
// TODO FLAG to choose the C compiler
// TODO When automatically including libraries NOTE it
// TODO automatic return when there is no ";"
// TODO jade stdlib and macros like println!
// TODO The main function should automatically take arguments
// TODO Variable to define the number of newlines after the includes
// TODO defer capabilities
// TODO http use statement
// TODO LATER LLVM C level optimizations
// TODO LATER comment unused includes linting the genrated c code
// TODO LATER treat arrays as lists using HEAD and TAIL or car and cdr
// TODO LATER automatic .h file creation
// TODO LATER STNTAX double x = x*2
// TODO SYNTAX pattern matching
// FIXME Why does let add one newline between functions?
// TODO IMPORTANT FIX if
// TODO IMPORTANT Emacs jade-mode
// TODO support inline asm
// TODO jade jit REPL && client for emacs
// TODO builtin hotreloding
// TODO IMPORTANT Automatic lib linking based on the use statements
// TODO NEXT fix closing curly brace of the while
// TODO Functions that take 0 parameters should be callabale like this myarr.len without the paren
// TODO if the main() function is not present treat everything as inside the main function
// TODO IMPORTANT for each line if its commented just copy it and go to the next
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 256 // TODO Dynamic memory allocation (If needed)
size_t indentation = 4; // TODO "-i"
size_t function_spacing = 1; // TODO "-fs"
int in_function = 0;
int in_main_function = 0;
int is_first_function = 1;
int scope_level = 0;
void print_indentation(FILE *output_file, size_t level) {
for (size_t i = 0; i < level; i++) {
fprintf(output_file, " ");
}
}
#define MAX_DEFERS 100
typedef struct {
char statements[MAX_DEFERS][MAX_LINE_LENGTH];
int count;
} DeferStack;
DeferStack deferStacks[MAX_DEFERS];
void push_defer_statement(const char *line) {
const char *statement_start = line;
while (*statement_start == ' ' || *statement_start == '\t') {
statement_start++;
}
// Now find the start of the action part after "defer "
const char *action_start = strstr(statement_start, "defer ");
if (action_start) {action_start += 6; // Skip past the length of "defer "
if (deferStacks[scope_level].count < MAX_DEFERS) {
strncpy(
deferStacks[scope_level].statements[deferStacks[scope_level].count],
action_start, MAX_LINE_LENGTH - 1);
deferStacks[scope_level]
.statements[deferStacks[scope_level].count][MAX_LINE_LENGTH - 1] =
'\0';
deferStacks[scope_level].count++;
}
}
}
void pop_and_execute_defers(FILE *output_file, int level) {
int i;
// NOTE When there are multiple defers in a single block, they are executed in reverse order.
for (i = deferStacks[level].count - 1; i >= 0; i--) {
print_indentation(output_file, level * indentation);
char *statement = deferStacks[level].statements[i];
int len = strlen(statement);
fprintf(output_file, "%s", statement);
}
deferStacks[level].count = 0; // Clear the stack for the current scope level
}
//TODO IMPORTANT Automatically include stdint.h if needed
const char* map_type(const char* input_type) {
if (strcmp(input_type, "i8" ) == 0) return "int8_t";
if (strcmp(input_type, "u8" ) == 0) return "uint8_t";
if (strcmp(input_type, "i16" ) == 0) return "int16_t";
if (strcmp(input_type, "u16" ) == 0) return "uint16_t";
if (strcmp(input_type, "i32" ) == 0) return "int";
if (strcmp(input_type, "u32" ) == 0) return "uint32_t";
if (strcmp(input_type, "i64" ) == 0) return "int64_t";
if (strcmp(input_type, "u64" ) == 0) return "uint64_t";
if (strcmp(input_type, "i128" ) == 0) return "int128_t";
if (strcmp(input_type, "u128" ) == 0) return "uint128_t";
if (strcmp(input_type, "f32" ) == 0) return "float";
if (strcmp(input_type, "f64" ) == 0) return "double";
if (strcmp(input_type, "int" ) == 0) return "int";
if (strcmp(input_type, "float" ) == 0) return "float";
if (strcmp(input_type, "char" ) == 0) return "char";
if (strcmp(input_type, "str" ) == 0) return "char*";
if (strcmp(input_type, "bool" ) == 0) return "bool";
return input_type; // _->
}
void gather_prototypes(FILE *input_file, char prototypes[][MAX_LINE_LENGTH], int *prototype_count) {
char line[MAX_LINE_LENGTH];
fseek(input_file, 0, SEEK_SET);
while (fgets(line, sizeof(line), input_file)) {
// Check for function definition
if (strstr(line, "fn ") && strstr(line, "{")) {
char function_name[MAX_LINE_LENGTH];
char parameters[MAX_LINE_LENGTH];
char return_type[MAX_LINE_LENGTH] = "void";
// Parse function signature
sscanf(line, "fn %s", function_name);
char *start_params = strchr(line, '(') + 1;
char *end_params = strchr(line, ')');
strncpy(parameters, start_params, end_params - start_params);
parameters[end_params - start_params] = '\0';
// Check for return type
char *return_type_pos = strstr(line, "->");
if (return_type_pos != NULL) {
sscanf(return_type_pos, "-> %s", return_type);
strcpy(return_type, map_type(return_type));
}
// Remove the "fn " prefix and the return type part
strtok(function_name, "(");
// Translate parameters
char translated_params[MAX_LINE_LENGTH] = "";
char *param = strtok(parameters, ",");
while (param != NULL) {
char param_name[MAX_LINE_LENGTH];
char param_type[MAX_LINE_LENGTH];
sscanf(param, "%[^:]:%s", param_name, param_type);
strcat(translated_params, map_type(param_type));
strcat(translated_params, " ");
strcat(translated_params, param_name);
param = strtok(NULL, ",");
if (param != NULL) {
strcat(translated_params, ", ");
}
}
// NOTE Exclude main function from prototypes
if (strcmp(function_name, "main") != 0) {
// Store the prototype
snprintf(prototypes[*prototype_count], MAX_LINE_LENGTH, "%s %s(%s);", return_type, function_name, translated_params);
(*prototype_count)++;
}
}
}
}
void gather_includes(FILE *input_file, char includes[][MAX_LINE_LENGTH], int *include_count, int *uses_stdio) {
char line[MAX_LINE_LENGTH];
fseek(input_file, 0, SEEK_SET);
while (fgets(line, sizeof(line), input_file)) {
if (strstr(line, "use ")) {
char library[MAX_LINE_LENGTH];
int is_commented = (strstr(line, "//") == line);
sscanf(line, is_commented ? "// use %s" : "use %s", library);
if (strcmp(library, "stdio") == 0) {
snprintf(includes[*include_count], MAX_LINE_LENGTH, "%s#include <stdio.h>", is_commented ? "/* " : "");
if (!is_commented) {
(*uses_stdio) = 1;
}
} else if (strcmp(library, "stdlib") == 0) {
snprintf(includes[*include_count], MAX_LINE_LENGTH, "%s#include <stdlib.h>", is_commented ? "/* " : "");
} else {
// Replace dots with slashes for libraries like GLFW.glfw3
for (char *p = library; *p; p++) {
if (*p == '.') {
*p = '/';
}
}
snprintf(includes[*include_count], MAX_LINE_LENGTH, "%s#include <%s.h>", is_commented ? "/* " : "", library);
}
if (is_commented) {
strcat(includes[*include_count], " */");
}
(*include_count)++;
}
}
}
void handle_loop(FILE *output_file, int indentation_level) {
for (int i = 0; i < indentation_level; i++) {
fprintf(output_file, " ");
}
fprintf(output_file, "while (1) {\n");
}
void handleType(FILE *input_file, FILE *output_file, const char *line) {
char type_name[MAX_LINE_LENGTH];
char fields[MAX_LINE_LENGTH * 10]; // Assuming a maximum of 10 lines of fields for simplicity
int is_recursive = 0;
// Check if it's a recursive type
if (strstr(line, "rec type ")) {
is_recursive = 1;
sscanf(line, "rec type %s {", type_name);
} else {
sscanf(line, "type %s {", type_name);
}
// Initialize fields
fields[0] = '\0';
// Read the lines containing the fields
while (fgets(line, MAX_LINE_LENGTH, input_file)) {
// Check for the closing brace
if (strstr(line, "}")) {
break;
}
// Append the line to the fields string
strcat(fields, line);
}
// Print the typedef struct
if (is_recursive) {
fprintf(output_file, "typedef struct %s {\n", type_name);
} else {
fprintf(output_file, "typedef struct {\n");
}
// Print fields with indentation
char field_name[MAX_LINE_LENGTH];
char field_type[MAX_LINE_LENGTH];
char *field_line = strtok(fields, "\n");
while (field_line != NULL) {
if (sscanf(field_line, " %[^:]:%s", field_name, field_type) == 2) {
// Remove any trailing characters from field_type
field_type[strcspn(field_type, " \t\n\r;")] = '\0';
const char *mapped_type = map_type(field_type);
fprintf(output_file, " %s %s;\n", mapped_type, field_name);
}
field_line = strtok(NULL, "\n");
}
// Close the struct
fprintf(output_file, "} %s;\n\n", type_name);
}
const char *infer_type_from_value(const char *value) {
// STRING
if (strchr(value, '\"')) {
return "char*";
}
// CHAR
if (strchr(value, '\'')) {
return "char";
}
// FLOAT
if (strchr(value, '.')) {
return "float";
}
// INT
char *endptr;
strtol(value, &endptr, 10);
while (*endptr == ' ')
endptr++; // Skip trailing whitespace
if (*endptr == '\0' || *endptr == ';') {
return "int";
}
/* // BOOL NOTE this is the correct way to do it*/
/* if (strcmp(value, "true") == 0 || strcmp(value, "false") == 0) { */
/* return "bool"; */
/* } */
// BOOL NOTE we check bool last so we can write false or true in a comment
if (strstr(value, "true") || strstr(value, "false")) {
return "bool";
}
// _->
return "ERROR";
}
void transpile(const char* input_filename, const char* output_filename) {
FILE *input_file = fopen(input_filename, "r");
FILE *output_file = fopen(output_filename, "w");
if (!input_file) {
fprintf(stderr, "Could not open input file %s\n", input_filename);
exit(1);
}
if (!output_file) {
fprintf(stderr, "Could not open output file %s\n", output_filename);
exit(1);
}
// Gather includes
char includes[100][MAX_LINE_LENGTH]; // Assuming a maximum of 100 includes
int include_count = 0;
int uses_stdio = 0; // Flag to track usage of printf
gather_includes(input_file, includes, &include_count, &uses_stdio);
// Gather prototypes
char prototypes[100] [MAX_LINE_LENGTH]; // Assuming a maximum of 100 prototypes
int prototype_count = 0;
gather_prototypes(input_file, prototypes, &prototype_count);
// Check for usage of printf (println!) that is not commented out
fseek(input_file, 0, SEEK_SET);
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), input_file)) {
char* trimmed_line = line;
while (*trimmed_line == ' ' || *trimmed_line == '\t') {
trimmed_line++;
}
if (strstr(trimmed_line, "println!(") && !strstr(trimmed_line, "//")) {
uses_stdio = 1;
break;
}
}
// Write the necessary includes at the top of the file
for (int i = 0; i < include_count; i++) {
fprintf(output_file, "%s\n", includes[i]);
}
if (uses_stdio) {
int already_included = 0;
for (int i = 0; i < include_count; i++) {
if (strstr(includes[i], "#include <stdio.h>") && !strstr(includes[i], "/*")) {
already_included = 1;
break;
}
}
if (!already_included) {
fprintf(output_file, "#include <stdio.h>\n");
}
}
if (prototype_count > 0 || uses_stdio) {
fprintf(output_file, "\n");
}
// Write the prototypes at the top of the file
for (int i = 0; i < prototype_count; i++) {
fprintf(output_file, "%s\n", prototypes[i]);
}
if (prototype_count > 0) {
for (size_t i = 0; i < function_spacing; i++) {
fprintf(output_file, "\n");
}
}
// Transpile the actual code
fseek(input_file, 0, SEEK_SET);
/* int in_function = 0; */
/* int in_main_function = 0; */
/* int is_first_function = 1; */
/* int scope_level = 0; */
while (fgets(line, sizeof(line), input_file)) {
// Skip the commented "use" lines
if (strstr(line, "use ")) {
continue;
}
if (strstr(line, "defer ")) {
// Capture the action following the 'defer' keyword
char *action = strchr(line, ' ') + 1;
push_defer_statement(action);
continue; // Skip writing the defer line to the output
}
// Handle type definitions
if (strstr(line, "type ")) {
handleType(input_file, output_file, line);
continue;
}
// Check for function definition
if (strstr(line, "fn ") && strstr(line, "{")) {
char function_name[MAX_LINE_LENGTH];
char parameters[MAX_LINE_LENGTH];
char return_type[MAX_LINE_LENGTH] = "void"; // NOTE for functions
// Parse function signature
sscanf(line, "fn %s", function_name);
char *start_params = strchr(line, '(') + 1;
char *end_params = strchr(line, ')');
strncpy(parameters, start_params, end_params - start_params);
parameters[end_params - start_params] = '\0';
// Check for return type
char *return_type_pos = strstr(line, "->");
if (return_type_pos != NULL) {
sscanf(return_type_pos, "-> %s", return_type);
strcpy(return_type, map_type(return_type));
}
// Remove the "fn " prefix and the return type part
strtok(function_name, "(");
// Translate parameters
char translated_params[MAX_LINE_LENGTH] = "";
char *param = strtok(parameters, ",");
while (param != NULL) {
char param_name[MAX_LINE_LENGTH];
char param_type[MAX_LINE_LENGTH];
sscanf(param, "%[^:]:%s", param_name, param_type);
strcat(translated_params, map_type(param_type));
strcat(translated_params, " ");
strcat(translated_params, param_name);
param = strtok(NULL, ",");
if (param != NULL) {
strcat(translated_params, ", ");
}
}
if (!is_first_function) {
for (size_t i = 0; i < function_spacing; i++) {
fprintf(output_file, "\n");
}
}
is_first_function = 0;
fprintf(output_file, "%s %s(%s) {\n", return_type, function_name, translated_params);
in_function = 1;
scope_level = 1; // Reset scope level for a new function
// Check if this is the main function
if (strcmp(function_name, "main") == 0) {
in_main_function = 1;
}
continue;
}
/* Check for end of function or scope */
if (in_function && strstr(line, "}")) {
pop_and_execute_defers(output_file, scope_level);
scope_level--;
if (scope_level == 0) { // End of function
fprintf(output_file, "}\n");
in_function = 0;
if (in_main_function) {
in_main_function = 0;
}
} else {
print_indentation(output_file, scope_level * indentation);
fprintf(output_file, "}\n");
}
continue;
}
// Replace macros with their C equivalents
if (strstr(line, "println!(")) {
// Check if the line is commented
char* trimmed_line = line;
while (*trimmed_line == ' ' || *trimmed_line == '\t') {
trimmed_line++;
}
int is_commented = strstr(trimmed_line, "//") && (strstr(trimmed_line, "//") < strstr(trimmed_line, "println!("));
// Find the start and end of the macro content
char* start_content = strchr(line, '(') + 1;
char* end_content = strrchr(line, ')');
if (start_content && end_content && start_content < end_content) {
char content[MAX_LINE_LENGTH];
strncpy(content, start_content, end_content - start_content);
content[end_content - start_content] = '\0';
// Remove surrounding double quotes from content if present
if (content[0] == '"' && content[strlen(content) - 1] == '"') {
content[strlen(content) - 1] = '\0';
memmove(content, content + 1, strlen(content));
}
// Write the translated printf statement, commented if necessary
print_indentation(output_file, scope_level * indentation);
if (is_commented) {
fprintf(output_file, "// ");
}
fprintf(output_file, "printf(\"%s\\n\");\n", content);
}
continue;
}
// Transpile variable declarations
char *trimmed_line = line;
while (*trimmed_line == ' ' || *trimmed_line == '\t') {
trimmed_line++;
}
if (strstr(trimmed_line, "let ")) {
char var_name[MAX_LINE_LENGTH];
char var_type[MAX_LINE_LENGTH] = ""; // Initialize empty in case type is inferred
char var_value[MAX_LINE_LENGTH] = "";
// Check if an explicit type is provided
if (strstr(trimmed_line, ":")) {
sscanf(trimmed_line, "let %[^:]:%s = %[^\n]", var_name, var_type, var_value);
} else {
sscanf(trimmed_line, "let %s = %[^\n]", var_name, var_value);
strcpy(var_type, infer_type_from_value(var_value)); // Infer the type from the value
}
// Remove any trailing semicolon from the original code
char *end_ptr = var_value + strlen(var_value) - 1;
if (*end_ptr == ';') {
*end_ptr = '\0';
}
// Map custom types or use inferred types
const char *c_type = strlen(var_type) > 0
? map_type(var_type)
: infer_type_from_value(var_value);
if (in_function) {
print_indentation(output_file, trimmed_line - line);
}
if (strlen(var_value) > 0) {
fprintf(output_file, "%s %s = %s;\n", c_type, var_name, var_value);
} else {
fprintf(output_file, "%s %s;\n", c_type, var_name);
}
continue;
}
// Transpile if statements
if (strstr(trimmed_line, "if ")) {
int is_commented = strstr(line, "//") != NULL;
char condition[MAX_LINE_LENGTH];
sscanf(trimmed_line, "if %[^\n]", condition);
// Remove any trailing brace from the condition
char* brace_ptr = strrchr(condition, '{');
if (brace_ptr) {
*brace_ptr = '\0';
}
// Add parentheses around the condition if not present
if (condition[0] != '(') {
char temp[MAX_LINE_LENGTH];
snprintf(temp, MAX_LINE_LENGTH, "(%s)", condition);
strcpy(condition, temp);
}
// Remove trailing space before the closing parenthesis
char* space_ptr = strrchr(condition, ' ');
if (space_ptr && *(space_ptr + 1) == ')') {
*space_ptr = ')';
*(space_ptr + 1) = '\0';
}
// Translate the if statement
if (in_function) {
print_indentation(output_file, trimmed_line - line);
}
if (is_commented) {
fprintf(output_file, "// if %s {\n", condition);
scope_level++;
while (fgets(line, sizeof(line), input_file)) {
trimmed_line = line;
while (*trimmed_line == ' ' || *trimmed_line == '\t') {
trimmed_line++;
}
if (strstr(trimmed_line, "//")) {
print_indentation(output_file, trimmed_line - line);
fprintf(output_file, "%s", trimmed_line);
if (strstr(trimmed_line, "}")) {
scope_level--;
break;
}
} else {
break;
}
}
} else {
fprintf(output_file, "if %s {\n", condition);
scope_level++;
}
continue;
}
// Transpile loop keyword
if (strstr(trimmed_line, "loop {")) {
handle_loop(output_file, scope_level * indentation);
scope_level++;
continue;
}
// Copy comments directly
if (strstr(trimmed_line, "//")) {
if (in_function) {
print_indentation(output_file, trimmed_line - line);
}
fprintf(output_file, "%s", trimmed_line);
continue;
}
// Copy function body lines if inside any function
if (in_function) {
print_indentation(output_file, trimmed_line - line);
fprintf(output_file, "%s", trimmed_line);
} else {
// Copy lines outside of any function without indentation
fprintf(output_file, "%s", line);
}
}
fclose(input_file);
fclose(output_file);
}
char* replace_extension(const char* filename, const char* new_extension) {
char *new_filename = malloc(strlen(filename) + strlen(new_extension) + 1);
strcpy(new_filename, filename);
char *dot = strrchr(new_filename, '.');
if (dot) {
*dot = '\0';
}
strcat(new_filename, new_extension);
return new_filename;
}
#include <sys/stat.h>
void jadeInit(const char *project_name) {
char path[256];
mkdir(project_name, 0777); // Create directory with read/write/execute for all
// Create and write main.jade
sprintf(path, "%s/main.jade", project_name);
FILE *file = fopen(path, "w");
if (file != NULL) {
fprintf(file, "fn main() -> int {\n return 0;\n}\n");
fclose(file);
}
// Create and write build.jade
sprintf(path, "%s/build.jade", project_name);
file = fopen(path, "w");
if (file != NULL) {
fprintf(file, "// Build script for the project\n");
fclose(file);
}
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <command> [<args>]\n", argv[0]);
return 1;
}
if (strcmp(argv[1], "init") == 0) {
if (argc != 3) {
fprintf(stderr, "Usage: %s init <project_name>\n", argv[0]);
return 1;
}
jadeInit(argv[2]);
printf("Project %s initialized.\n", argv[2]);
} else {
char *input_filename = argv[1];
char *output_filename = replace_extension(input_filename, ".c");
transpile(input_filename, output_filename);
printf("Transpiled %s to %s\n", input_filename, output_filename);
free(output_filename);
}
return 0;
}