@@ -78,28 +78,47 @@ int main(int argc, char **argv)
78
78
}
79
79
80
80
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
+ }
82
90
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 );
87
120
}
88
- size_t file_size = st .st_size ;
89
121
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 ;
103
122
104
123
#ifdef DEBUG_PERF
105
124
double lex_elapsed , parse_elapsed , interpret_elapsed ;
@@ -108,7 +127,7 @@ int main(int argc, char **argv)
108
127
#endif /* DEBUG_PERF */
109
128
110
129
/* lex */
111
- Lexer lex_result = lex (input , file_size );
130
+ Lexer lex_result = lex (input , input_size );
112
131
if (lex_result .had_error ) {
113
132
exit_code = 1 ;
114
133
goto defer_tokens ;
@@ -171,7 +190,6 @@ int main(int argc, char **argv)
171
190
defer_tokens :
172
191
arraylist_free (& lex_result .tokens );
173
192
174
- fclose (fp );
175
193
defer_input :
176
194
free (input );
177
195
0 commit comments