Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit d86dd23

Browse files
committedMar 23, 2024·
feat: implement -c flag
1 parent 5f42e1f commit d86dd23

File tree

1 file changed

+39
-21
lines changed

1 file changed

+39
-21
lines changed
 

‎src/main.c

+39-21
Original file line numberDiff line numberDiff line change
@@ -78,28 +78,47 @@ int main(int argc, char **argv)
7878
}
7979

8080
int exit_code;
81-
char *file_path = argv[1];
81+
size_t input_size;
82+
char *input;
83+
84+
/* -c flag executes next argv as source code */
85+
if (strcmp(argv[1], "-c") == 0) {
86+
if (argc == 2) {
87+
fprintf(stderr, "Argument expected for the -c flag\n");
88+
return 2;
89+
}
8290

83-
struct stat st;
84-
if (stat(file_path, &st) != 0) {
85-
REPORT_IMPL("Could not stat file '%s'\n", file_path);
86-
return 1;
91+
input_size = strlen(argv[2]);
92+
input = malloc(sizeof(char) * (input_size + 2));
93+
memcpy(input, argv[2], input_size);
94+
input[input_size] = '\n';
95+
input[input_size + 1] = 0;
96+
} else {
97+
/* Treat next agument as a filename */
98+
char *file_path = argv[1];
99+
100+
struct stat st;
101+
if (stat(file_path, &st) != 0) {
102+
REPORT_IMPL("Could not stat file '%s'\n", file_path);
103+
return 1;
104+
}
105+
input_size = st.st_size;
106+
input = malloc(sizeof(char) * (input_size + 1));
107+
input[input_size] = 0;
108+
FILE *fp = fopen(file_path, "r");
109+
if (fp == NULL) {
110+
REPORT_IMPL("Could not open file '%s'\n", file_path);
111+
exit_code = 1;
112+
goto defer_input;
113+
}
114+
if (fread(input, sizeof(char), st.st_size, fp) != input_size) {
115+
REPORT_IMPL("Could not read file '%s'\n", file_path);
116+
exit_code = 1;
117+
goto defer_input;
118+
}
119+
fclose(fp);
87120
}
88-
size_t file_size = st.st_size;
89121

90-
char *input = malloc(sizeof(char) * (file_size + 1));
91-
FILE *fp = fopen(file_path, "r");
92-
if (fp == NULL) {
93-
REPORT_IMPL("Could not open file '%s'\n", file_path);
94-
exit_code = 1;
95-
goto defer_input;
96-
}
97-
if (fread(input, sizeof(char), st.st_size, fp) != file_size) {
98-
REPORT_IMPL("Could not read file '%s'\n", file_path);
99-
exit_code = 1;
100-
goto defer_input;
101-
}
102-
input[file_size] = 0;
103122

104123
#ifdef DEBUG_PERF
105124
double lex_elapsed, parse_elapsed, interpret_elapsed;
@@ -108,7 +127,7 @@ int main(int argc, char **argv)
108127
#endif /* DEBUG_PERF */
109128

110129
/* lex */
111-
Lexer lex_result = lex(input, file_size);
130+
Lexer lex_result = lex(input, input_size);
112131
if (lex_result.had_error) {
113132
exit_code = 1;
114133
goto defer_tokens;
@@ -171,7 +190,6 @@ int main(int argc, char **argv)
171190
defer_tokens:
172191
arraylist_free(&lex_result.tokens);
173192

174-
fclose(fp);
175193
defer_input:
176194
free(input);
177195

0 commit comments

Comments
 (0)
Please sign in to comment.