2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #define HT_MACROS 1024
39 /* a copy from the lexer */
53 /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
60 typedef struct ftepp_s {
66 ppcondition *conditions;
68 ht macros; /* hashtable<string, ppmacro*> */
77 * Implement the predef subsystem now. We can do this safely with the
78 * help of lexer contexts.
80 static uint32_t ftepp_predef_countval = 0;
81 static uint32_t ftepp_predef_randval = 0;
84 static char *ftepp_predef_date(lex_file *context) {
85 struct tm *itime = NULL;
87 char *value = (char*)mem_a(82);
88 /* 82 is enough for strftime but we also have " " in our string */
96 localtime_s(itime, &rtime);
98 itime = localtime(&rtime);
101 strftime(value, 82, "\"%b %d %Y\"", itime);
107 static char *ftepp_predef_time(lex_file *context) {
108 struct tm *itime = NULL;
110 char *value = (char*)mem_a(82);
111 /* 82 is enough for strftime but we also have " " in our string */
119 localtime_s(itime, &rtime);
121 itime = localtime(&rtime);
124 strftime(value, 82, "\"%X\"", itime);
130 static char *ftepp_predef_line(lex_file *context) {
132 util_asprintf(&value, "%d", (int)context->line);
136 static char *ftepp_predef_file(lex_file *context) {
137 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
138 char *value = (char*)mem_a(length);
139 util_snprintf(value, length, "\"%s\"", context->name);
143 /* __COUNTER_LAST__ */
144 static char *ftepp_predef_counterlast(lex_file *context) {
146 util_asprintf(&value, "%u", ftepp_predef_countval);
152 static char *ftepp_predef_counter(lex_file *context) {
154 ftepp_predef_countval ++;
155 util_asprintf(&value, "%u", ftepp_predef_countval);
161 static char *ftepp_predef_random(lex_file *context) {
163 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
164 util_asprintf(&value, "%u", ftepp_predef_randval);
169 /* __RANDOM_LAST__ */
170 static char *ftepp_predef_randomlast(lex_file *context) {
172 util_asprintf(&value, "%u", ftepp_predef_randval);
178 static char *ftepp_predef_timestamp(lex_file *context) {
183 if (stat(context->name, &finfo))
184 return util_strdup("\"<failed to determine timestamp>\"");
187 * ctime and its fucking annoying newline char, no worries, we're
188 * professionals here.
190 find = ctime(&finfo.st_mtime);
191 value = (char*)mem_a(strlen(find) + 1);
192 memcpy(&value[1], find, (size = strlen(find)) - 1);
202 char *(*func)(lex_file *);
205 static const ftepp_predef_t ftepp_predefs[] = {
206 { "__LINE__", &ftepp_predef_line },
207 { "__FILE__", &ftepp_predef_file },
208 { "__COUNTER__", &ftepp_predef_counter },
209 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
210 { "__RANDOM__", &ftepp_predef_random },
211 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
212 { "__DATE__", &ftepp_predef_date },
213 { "__TIME__", &ftepp_predef_time },
214 { "__TIME_STAMP__", &ftepp_predef_timestamp }
217 static GMQCC_INLINE int ftepp_predef_index(const char *name) {
218 /* no hashtable here, we simply check for one to exist the naive way */
220 for(i = 0; i < (int)(sizeof(ftepp_predefs)/sizeof(*ftepp_predefs)); i++)
221 if (!strcmp(ftepp_predefs[i].name, name))
226 bool ftepp_predef_exists(const char *name) {
227 return ftepp_predef_index(name) != -1;
230 /* singleton because we're allowed */
231 static GMQCC_INLINE char *(*ftepp_predef(const char *name))(lex_file *context) {
232 int i = ftepp_predef_index(name);
233 return (i != -1) ? ftepp_predefs[i].func : NULL;
236 #define ftepp_tokval(f) ((f)->lex->tok.value)
237 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
239 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
246 con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
250 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
257 con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
261 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
267 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
272 static pptoken *pptoken_make(ftepp_t *ftepp)
274 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
275 token->token = ftepp->token;
277 if (token->token == TOKEN_WHITE)
278 token->value = util_strdup(" ");
281 token->value = util_strdup(ftepp_tokval(ftepp));
283 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
287 static GMQCC_INLINE void pptoken_delete(pptoken *self)
293 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
295 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
298 memset(macro, 0, sizeof(*macro));
299 macro->name = util_strdup(name);
303 static void ppmacro_delete(ppmacro *self)
306 for (i = 0; i < vec_size(self->params); ++i)
307 mem_d(self->params[i]);
308 vec_free(self->params);
309 for (i = 0; i < vec_size(self->output); ++i)
310 pptoken_delete(self->output[i]);
311 vec_free(self->output);
316 static ftepp_t* ftepp_new()
320 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
321 memset(ftepp, 0, sizeof(*ftepp));
323 ftepp->macros = util_htnew(HT_MACROS);
324 ftepp->output_on = true;
329 static GMQCC_INLINE void ftepp_flush_do(ftepp_t *self)
331 vec_free(self->output_string);
334 static void ftepp_delete(ftepp_t *self)
336 ftepp_flush_do(self);
338 mem_d(self->itemname);
339 if (self->includename)
340 vec_free(self->includename);
342 util_htrem(self->macros, (void (*)(void*))&ppmacro_delete);
344 vec_free(self->conditions);
346 lex_close(self->lex);
350 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
352 if (ignore_cond || ftepp->output_on)
357 data = vec_add(ftepp->output_string, len);
358 memcpy(data, str, len);
362 static GMQCC_INLINE void ftepp_update_output_condition(ftepp_t *ftepp)
365 ftepp->output_on = true;
366 for (i = 0; i < vec_size(ftepp->conditions); ++i)
367 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
370 static GMQCC_INLINE ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
372 return (ppmacro*)util_htget(ftepp->macros, name);
375 static GMQCC_INLINE void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
377 util_htrm(ftepp->macros, name, (void (*)(void*))&ppmacro_delete);
380 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
382 return (ftepp->token = lex_do(ftepp->lex));
385 /* Important: this does not skip newlines! */
386 static bool ftepp_skipspace(ftepp_t *ftepp)
388 if (ftepp->token != TOKEN_WHITE)
390 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
391 if (ftepp->token >= TOKEN_EOF) {
392 ftepp_error(ftepp, "unexpected end of preprocessor directive");
398 /* this one skips EOLs as well */
399 static bool ftepp_skipallwhite(ftepp_t *ftepp)
401 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
405 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
406 if (ftepp->token >= TOKEN_EOF) {
407 ftepp_error(ftepp, "unexpected end of preprocessor directive");
414 * The huge macro parsing code...
416 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
420 if (!ftepp_skipspace(ftepp))
422 if (ftepp->token == ')')
424 switch (ftepp->token) {
428 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
431 macro->variadic = true;
434 ftepp_error(ftepp, "unexpected token in parameter list");
438 if (!ftepp_skipspace(ftepp))
440 if (macro->variadic && ftepp->token != ')') {
441 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
444 } while (ftepp->token == ',');
446 if (ftepp->token != ')') {
447 ftepp_error(ftepp, "expected closing paren after macro parameter list");
451 /* skipspace happens in ftepp_define */
455 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
458 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
459 bool subscript = false;
461 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
462 subscript = !!(ftepp_next(ftepp) == '#');
464 if (subscript && ftepp_next(ftepp) != '#') {
465 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
467 } else if (subscript) {
468 if (ftepp_next(ftepp) == '[') {
469 if (ftepp_next(ftepp) != TOKEN_INTCONST) {
470 ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
474 index = (int)strtol(ftepp_tokval(ftepp), NULL, 10);
476 if (ftepp_next(ftepp) != ']') {
477 ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
482 * mark it as an array to be handled later as such and not
483 * as traditional __VA_ARGS__
485 ftepp->token = TOKEN_VA_ARGS_ARRAY;
486 ptok = pptoken_make(ftepp);
487 ptok->constval.i = index;
488 vec_push(macro->output, ptok);
491 ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
495 int old = ftepp->token;
496 ftepp->token = TOKEN_VA_ARGS;
497 ptok = pptoken_make(ftepp);
498 vec_push(macro->output, ptok);
502 else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
503 ftepp->token = TOKEN_VA_COUNT;
504 ptok = pptoken_make(ftepp);
505 vec_push(macro->output, ptok);
508 ptok = pptoken_make(ftepp);
509 vec_push(macro->output, ptok);
513 /* recursive expansion can cause EOFs here */
514 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
515 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
521 static bool ftepp_define(ftepp_t *ftepp)
523 ppmacro *macro = NULL;
524 size_t l = ftepp_ctx(ftepp).line;
526 (void)ftepp_next(ftepp);
527 if (!ftepp_skipspace(ftepp))
530 switch (ftepp->token) {
534 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
535 if (macro && ftepp->output_on) {
536 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
538 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
540 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
543 ftepp_error(ftepp, "expected macro name");
547 (void)ftepp_next(ftepp);
549 if (ftepp->token == '(') {
550 macro->has_params = true;
551 if (!ftepp_define_params(ftepp, macro)) {
552 ppmacro_delete(macro);
557 if (!ftepp_skipspace(ftepp)) {
558 ppmacro_delete(macro);
562 if (!ftepp_define_body(ftepp, macro)) {
563 ppmacro_delete(macro);
567 if (ftepp->output_on)
568 util_htset(ftepp->macros, macro->name, (void*)macro);
570 ppmacro_delete(macro);
573 for (; l < ftepp_ctx(ftepp).line; ++l)
574 ftepp_out(ftepp, "\n", true);
579 * When a macro is used we have to handle parameters as well
580 * as special-concatenation via ## or stringification via #
582 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
583 * this kind of parens. Curly braces or [] don't count towards the
590 static void macroparam_clean(macroparam *self)
593 for (i = 0; i < vec_size(self->tokens); ++i)
594 pptoken_delete(self->tokens[i]);
595 vec_free(self->tokens);
598 /* need to leave the last token up */
599 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
601 macroparam *params = NULL;
607 if (!ftepp_skipallwhite(ftepp))
609 while (ftepp->token != ')') {
611 if (!ftepp_skipallwhite(ftepp))
613 while (parens || ftepp->token != ',') {
614 if (ftepp->token == '(')
616 else if (ftepp->token == ')') {
621 ptok = pptoken_make(ftepp);
622 vec_push(mp.tokens, ptok);
623 if (ftepp_next(ftepp) >= TOKEN_EOF) {
624 ftepp_error(ftepp, "unexpected EOF in macro call");
628 vec_push(params, mp);
630 if (ftepp->token == ')')
632 if (ftepp->token != ',') {
633 ftepp_error(ftepp, "expected closing paren or comma in macro call");
636 if (ftepp_next(ftepp) >= TOKEN_EOF) {
637 ftepp_error(ftepp, "unexpected EOF in macro call");
641 /* need to leave that up
642 if (ftepp_next(ftepp) >= TOKEN_EOF) {
643 ftepp_error(ftepp, "unexpected EOF in macro call");
647 *out_params = params;
652 macroparam_clean(&mp);
653 for (i = 0; i < vec_size(params); ++i)
654 macroparam_clean(¶ms[i]);
659 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
662 for (i = 0; i < vec_size(macro->params); ++i) {
663 if (!strcmp(macro->params[i], name)) {
671 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
676 switch (token->token) {
677 case TOKEN_STRINGCONST:
680 /* in preprocessor mode strings already are string,
681 * so we don't get actual newline bytes here.
682 * Still need to escape backslashes and quotes.
685 case '\\': ftepp_out(ftepp, "\\\\", false); break;
686 case '"': ftepp_out(ftepp, "\\\"", false); break;
689 ftepp_out(ftepp, chs, false);
696 ftepp_out(ftepp, " ", false);
699 ftepp_out(ftepp, "\\n", false);
702 ftepp_out(ftepp, token->value, false);
707 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
710 ftepp_out(ftepp, "\"", false);
711 for (i = 0; i < vec_size(param->tokens); ++i)
712 ftepp_stringify_token(ftepp, param->tokens[i]);
713 ftepp_out(ftepp, "\"", false);
716 static void ftepp_recursion_header(ftepp_t *ftepp)
718 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
721 static void ftepp_recursion_footer(ftepp_t *ftepp)
723 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
726 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
730 for (i = 0; i < vec_size(param->tokens); ++i) {
731 out = param->tokens[i];
732 if (out->token == TOKEN_EOL)
733 ftepp_out(ftepp, "\n", false);
735 ftepp_out(ftepp, out->value, false);
739 static bool ftepp_preprocess(ftepp_t *ftepp);
740 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
743 char *old_string = ftepp->output_string;
745 lex_file *old_lexer = ftepp->lex;
746 size_t vararg_start = vec_size(macro->params);
758 if (vararg_start < vec_size(params))
759 varargs = vec_size(params) - vararg_start;
764 if (!vec_size(macro->output))
767 ftepp->output_string = NULL;
768 for (o = 0; o < vec_size(macro->output); ++o) {
769 pptoken *out = macro->output[o];
770 switch (out->token) {
772 if (!macro->variadic) {
773 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
774 vec_free(old_string);
781 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
782 for (++pi; pi < varargs; ++pi) {
783 ftepp_out(ftepp, ", ", false);
784 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
788 case TOKEN_VA_ARGS_ARRAY:
789 if ((size_t)out->constval.i >= varargs) {
790 ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
791 vec_free(old_string);
795 ftepp_param_out(ftepp, ¶ms[out->constval.i + vararg_start]);
799 util_asprintf(&buffer, "%d", varargs);
800 ftepp_out(ftepp, buffer, false);
807 if (!macro_params_find(macro, out->value, &pi)) {
808 ftepp_out(ftepp, out->value, false);
811 ftepp_param_out(ftepp, ¶ms[pi]);
814 if (o + 1 < vec_size(macro->output)) {
815 nextok = macro->output[o+1]->token;
817 /* raw concatenation */
821 if ( (nextok == TOKEN_IDENT ||
822 nextok == TOKEN_KEYWORD ||
823 nextok == TOKEN_TYPENAME) &&
824 macro_params_find(macro, macro->output[o+1]->value, &pi))
827 ftepp_stringify(ftepp, ¶ms[pi]);
831 ftepp_out(ftepp, "#", false);
834 ftepp_out(ftepp, "\n", false);
837 ftepp_out(ftepp, out->value, false);
841 vec_push(ftepp->output_string, 0);
842 /* Now run the preprocessor recursively on this string buffer */
844 printf("__________\n%s\n=========\n", ftepp->output_string);
846 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
848 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
853 inlex->line = ftepp->lex->line;
854 inlex->sline = ftepp->lex->sline;
857 old_inmacro = ftepp->in_macro;
858 ftepp->in_macro = true;
859 ftepp->output_string = NULL;
860 if (!ftepp_preprocess(ftepp)) {
861 ftepp->in_macro = old_inmacro;
862 vec_free(ftepp->lex->open_string);
863 vec_free(ftepp->output_string);
864 lex_close(ftepp->lex);
868 ftepp->in_macro = old_inmacro;
869 vec_free(ftepp->lex->open_string);
870 lex_close(ftepp->lex);
872 inner_string = ftepp->output_string;
873 ftepp->output_string = old_string;
875 has_newlines = (strchr(inner_string, '\n') != NULL);
877 if (has_newlines && !old_inmacro)
878 ftepp_recursion_header(ftepp);
880 vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
881 vec_free(inner_string);
883 if (has_newlines && !old_inmacro)
884 ftepp_recursion_footer(ftepp);
886 if (resetline && !ftepp->in_macro) {
888 util_snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
889 ftepp_out(ftepp, lineno, false);
892 old_string = ftepp->output_string;
894 ftepp->lex = old_lexer;
895 ftepp->output_string = old_string;
899 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
902 macroparam *params = NULL;
906 if (!macro->has_params) {
907 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
914 if (!ftepp_skipallwhite(ftepp))
917 if (ftepp->token != '(') {
918 ftepp_error(ftepp, "expected macro parameters in parenthesis");
923 paramline = ftepp->lex->sline;
924 if (!ftepp_macro_call_params(ftepp, ¶ms))
927 if ( vec_size(params) < vec_size(macro->params) ||
928 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
930 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
931 (macro->variadic ? " at least" : ""),
932 (unsigned int)vec_size(macro->params),
933 (unsigned int)vec_size(params));
938 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
943 for (o = 0; o < vec_size(params); ++o)
944 macroparam_clean(¶ms[o]);
950 * #if - the FTEQCC way:
951 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
952 * <numbers> => True if the number is not 0
953 * !<factor> => True if the factor yields false
954 * !!<factor> => ERROR on 2 or more unary nots
955 * <macro> => becomes the macro's FIRST token regardless of parameters
956 * <e> && <e> => True if both expressions are true
957 * <e> || <e> => True if either expression is true
959 * <ident> => False (remember for macros the <macro> rule applies instead)
960 * Unary + and - are weird and wrong in fteqcc so we don't allow them
961 * parenthesis in expressions are allowed
962 * parameter lists on macros are errors
963 * No mathematical calculations are executed
965 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
966 static bool ftepp_if_op(ftepp_t *ftepp)
968 ftepp->lex->flags.noops = false;
970 if (!ftepp_skipspace(ftepp))
972 ftepp->lex->flags.noops = true;
975 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
981 if (!ftepp_skipspace(ftepp))
984 while (ftepp->token == '!') {
987 if (!ftepp_skipspace(ftepp))
991 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
995 if (!ftepp_skipspace(ftepp))
999 switch (ftepp->token) {
1001 case TOKEN_TYPENAME:
1003 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
1005 if (!ftepp_skipspace(ftepp))
1007 if (ftepp->token != '(') {
1008 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
1012 if (!ftepp_skipspace(ftepp))
1014 if (ftepp->token != TOKEN_IDENT &&
1015 ftepp->token != TOKEN_TYPENAME &&
1016 ftepp->token != TOKEN_KEYWORD)
1018 ftepp_error(ftepp, "defined() used on an unexpected token type");
1021 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1024 if (!ftepp_skipspace(ftepp))
1026 if (ftepp->token != ')') {
1027 ftepp_error(ftepp, "expected closing paren");
1033 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1034 if (!macro || !vec_size(macro->output)) {
1038 /* This does not expand recursively! */
1039 switch (macro->output[0]->token) {
1040 case TOKEN_INTCONST:
1041 *value_out = macro->output[0]->constval.i;
1042 *out = !!(macro->output[0]->constval.i);
1044 case TOKEN_FLOATCONST:
1045 *value_out = macro->output[0]->constval.f;
1046 *out = !!(macro->output[0]->constval.f);
1054 case TOKEN_STRINGCONST:
1058 case TOKEN_INTCONST:
1059 *value_out = ftepp->lex->tok.constval.i;
1060 *out = !!(ftepp->lex->tok.constval.i);
1062 case TOKEN_FLOATCONST:
1063 *value_out = ftepp->lex->tok.constval.f;
1064 *out = !!(ftepp->lex->tok.constval.f);
1069 if (!ftepp_if_expr(ftepp, out, value_out))
1071 if (ftepp->token != ')') {
1072 ftepp_error(ftepp, "expected closing paren in #if expression");
1078 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1079 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1080 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1084 *value_out = -*value_out;
1087 *value_out = (*out ? 1 : 0);
1093 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1095 if (!ftepp_next(ftepp))
1097 return ftepp_if_value(ftepp, out, value_out);
1101 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1103 if (!ftepp_if_value(ftepp, out, value_out))
1106 if (!ftepp_if_op(ftepp))
1109 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1112 /* FTEQCC is all right-associative and no precedence here */
1113 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1114 !strcmp(ftepp_tokval(ftepp), "||"))
1117 char opc = ftepp_tokval(ftepp)[0];
1121 if (!ftepp_next(ftepp))
1123 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1127 *out = *out && next;
1129 *out = *out || next;
1131 *value_out = (*out ? 1 : 0);
1134 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1135 !strcmp(ftepp_tokval(ftepp), "!=") ||
1136 !strcmp(ftepp_tokval(ftepp), ">=") ||
1137 !strcmp(ftepp_tokval(ftepp), "<=") ||
1138 !strcmp(ftepp_tokval(ftepp), ">") ||
1139 !strcmp(ftepp_tokval(ftepp), "<"))
1142 const char opc0 = ftepp_tokval(ftepp)[0];
1143 const char opc1 = ftepp_tokval(ftepp)[1];
1146 if (!ftepp_next(ftepp))
1148 if (!ftepp_if_expr(ftepp, &next, &other))
1152 *out = (*value_out == other);
1153 else if (opc0 == '!')
1154 *out = (*value_out != other);
1155 else if (opc0 == '>') {
1156 if (opc1 == '=') *out = (*value_out >= other);
1157 else *out = (*value_out > other);
1159 else if (opc0 == '<') {
1160 if (opc1 == '=') *out = (*value_out <= other);
1161 else *out = (*value_out < other);
1163 *value_out = (*out ? 1 : 0);
1168 ftepp_error(ftepp, "junk after #if");
1173 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1175 bool result = false;
1178 memset(cond, 0, sizeof(*cond));
1179 (void)ftepp_next(ftepp);
1181 if (!ftepp_skipspace(ftepp))
1183 if (ftepp->token == TOKEN_EOL) {
1184 ftepp_error(ftepp, "expected expression for #if-directive");
1188 if (!ftepp_if_expr(ftepp, &result, &dummy))
1196 * ifdef is rather simple
1198 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1201 memset(cond, 0, sizeof(*cond));
1202 (void)ftepp_next(ftepp);
1203 if (!ftepp_skipspace(ftepp))
1206 switch (ftepp->token) {
1208 case TOKEN_TYPENAME:
1210 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1213 ftepp_error(ftepp, "expected macro name");
1217 (void)ftepp_next(ftepp);
1218 if (!ftepp_skipspace(ftepp))
1220 /* relaxing this condition
1221 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1222 ftepp_error(ftepp, "stray tokens after #ifdef");
1231 * undef is also simple
1233 static bool ftepp_undef(ftepp_t *ftepp)
1235 (void)ftepp_next(ftepp);
1236 if (!ftepp_skipspace(ftepp))
1239 if (ftepp->output_on) {
1240 switch (ftepp->token) {
1242 case TOKEN_TYPENAME:
1244 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1247 ftepp_error(ftepp, "expected macro name");
1252 (void)ftepp_next(ftepp);
1253 if (!ftepp_skipspace(ftepp))
1255 /* relaxing this condition
1256 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1257 ftepp_error(ftepp, "stray tokens after #ifdef");
1264 /* Special unescape-string function which skips a leading quote
1265 * and stops at a quote, not just at \0
1267 static void unescape(const char *str, char *out) {
1269 while (*str && *str != '"') {
1273 case '\\': *out++ = *str; break;
1274 case '"': *out++ = *str; break;
1275 case 'a': *out++ = '\a'; break;
1276 case 'b': *out++ = '\b'; break;
1277 case 'r': *out++ = '\r'; break;
1278 case 'n': *out++ = '\n'; break;
1279 case 't': *out++ = '\t'; break;
1280 case 'f': *out++ = '\f'; break;
1281 case 'v': *out++ = '\v'; break;
1296 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1299 char *filename = NULL;
1300 const char *last_slash;
1306 last_slash = strrchr(pathfile, '/');
1309 len = last_slash - pathfile;
1310 memcpy(vec_add(filename, len), pathfile, len);
1311 vec_push(filename, '/');
1315 memcpy(vec_add(filename, len+1), file, len);
1316 vec_last(filename) = 0;
1318 fp = fs_file_open(filename, "rb");
1327 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1329 char *filename = NULL;
1331 filename = ftepp_include_find_path(file, ftepp->includename);
1333 filename = ftepp_include_find_path(file, ftepp->itemname);
1337 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1338 char *message = NULL;
1340 if (!ftepp_skipspace(ftepp))
1343 /* handle the odd non string constant case so it works like C */
1344 if (ftepp->token != TOKEN_STRINGCONST) {
1346 vec_upload(message, "#warning", 8);
1348 while (ftepp->token != TOKEN_EOL) {
1349 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1352 vec_push(message, '\0');
1353 if (ftepp->output_on)
1354 store = ftepp_warn(ftepp, WARN_CPP, message);
1361 if (!ftepp->output_on)
1364 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1365 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1368 static void ftepp_directive_error(ftepp_t *ftepp) {
1369 char *message = NULL;
1371 if (!ftepp_skipspace(ftepp))
1374 /* handle the odd non string constant case so it works like C */
1375 if (ftepp->token != TOKEN_STRINGCONST) {
1376 vec_upload(message, "#error", 6);
1378 while (ftepp->token != TOKEN_EOL) {
1379 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1382 vec_push(message, '\0');
1383 if (ftepp->output_on)
1384 ftepp_error(ftepp, message);
1389 if (!ftepp->output_on)
1392 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1393 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1396 static void ftepp_directive_message(ftepp_t *ftepp) {
1397 char *message = NULL;
1399 if (!ftepp_skipspace(ftepp))
1402 /* handle the odd non string constant case so it works like C */
1403 if (ftepp->token != TOKEN_STRINGCONST) {
1404 vec_upload(message, "#message", 8);
1406 while (ftepp->token != TOKEN_EOL) {
1407 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1410 vec_push(message, '\0');
1411 if (ftepp->output_on)
1412 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1417 if (!ftepp->output_on)
1420 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1421 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", ftepp_tokval(ftepp));
1426 * FIXME: do we need/want a -I option?
1427 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1429 static bool ftepp_include(ftepp_t *ftepp)
1431 lex_file *old_lexer = ftepp->lex;
1436 char *old_includename;
1438 (void)ftepp_next(ftepp);
1439 if (!ftepp_skipspace(ftepp))
1442 if (ftepp->token != TOKEN_STRINGCONST) {
1443 ftepp_error(ftepp, "expected filename to include");
1447 if (!ftepp->output_on) {
1452 ctx = ftepp_ctx(ftepp);
1454 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1456 ftepp_out(ftepp, "\n#pragma file(", false);
1457 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1458 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1460 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1462 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1465 inlex = lex_open(filename);
1467 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1472 old_includename = ftepp->includename;
1473 ftepp->includename = filename;
1474 if (!ftepp_preprocess(ftepp)) {
1475 vec_free(ftepp->includename);
1476 ftepp->includename = old_includename;
1477 lex_close(ftepp->lex);
1478 ftepp->lex = old_lexer;
1481 vec_free(ftepp->includename);
1482 ftepp->includename = old_includename;
1483 lex_close(ftepp->lex);
1484 ftepp->lex = old_lexer;
1486 ftepp_out(ftepp, "\n#pragma file(", false);
1487 ftepp_out(ftepp, ctx.file, false);
1488 util_snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1489 ftepp_out(ftepp, lineno, false);
1492 (void)ftepp_next(ftepp);
1493 if (!ftepp_skipspace(ftepp))
1495 if (ftepp->token != TOKEN_EOL) {
1496 ftepp_error(ftepp, "stray tokens after #include");
1499 (void)ftepp_next(ftepp);
1504 /* Basic structure handlers */
1505 static bool ftepp_else_allowed(ftepp_t *ftepp)
1507 if (!vec_size(ftepp->conditions)) {
1508 ftepp_error(ftepp, "#else without #if");
1511 if (vec_last(ftepp->conditions).had_else) {
1512 ftepp_error(ftepp, "multiple #else for a single #if");
1518 static bool ftepp_hash(ftepp_t *ftepp)
1523 lex_ctx ctx = ftepp_ctx(ftepp);
1525 if (!ftepp_skipspace(ftepp))
1528 switch (ftepp->token) {
1531 case TOKEN_TYPENAME:
1532 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1533 return ftepp_define(ftepp);
1535 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1536 return ftepp_undef(ftepp);
1538 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1539 if (!ftepp_ifdef(ftepp, &cond))
1541 cond.was_on = cond.on;
1542 vec_push(ftepp->conditions, cond);
1543 ftepp->output_on = ftepp->output_on && cond.on;
1546 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1547 if (!ftepp_ifdef(ftepp, &cond))
1550 cond.was_on = cond.on;
1551 vec_push(ftepp->conditions, cond);
1552 ftepp->output_on = ftepp->output_on && cond.on;
1555 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1556 if (!ftepp_else_allowed(ftepp))
1558 if (!ftepp_ifdef(ftepp, &cond))
1560 pc = &vec_last(ftepp->conditions);
1561 pc->on = !pc->was_on && cond.on;
1562 pc->was_on = pc->was_on || pc->on;
1563 ftepp_update_output_condition(ftepp);
1566 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1567 if (!ftepp_else_allowed(ftepp))
1569 if (!ftepp_ifdef(ftepp, &cond))
1572 pc = &vec_last(ftepp->conditions);
1573 pc->on = !pc->was_on && cond.on;
1574 pc->was_on = pc->was_on || pc->on;
1575 ftepp_update_output_condition(ftepp);
1578 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1579 if (!ftepp_else_allowed(ftepp))
1581 if (!ftepp_if(ftepp, &cond))
1583 pc = &vec_last(ftepp->conditions);
1584 pc->on = !pc->was_on && cond.on;
1585 pc->was_on = pc->was_on || pc->on;
1586 ftepp_update_output_condition(ftepp);
1589 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1590 if (!ftepp_if(ftepp, &cond))
1592 cond.was_on = cond.on;
1593 vec_push(ftepp->conditions, cond);
1594 ftepp->output_on = ftepp->output_on && cond.on;
1597 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1598 if (!ftepp_else_allowed(ftepp))
1600 pc = &vec_last(ftepp->conditions);
1601 pc->on = !pc->was_on;
1602 pc->had_else = true;
1604 ftepp_update_output_condition(ftepp);
1607 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1608 if (!vec_size(ftepp->conditions)) {
1609 ftepp_error(ftepp, "#endif without #if");
1612 vec_pop(ftepp->conditions);
1614 ftepp_update_output_condition(ftepp);
1617 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1618 return ftepp_include(ftepp);
1620 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1621 ftepp_out(ftepp, "#", false);
1624 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1625 ftepp_directive_warning(ftepp);
1628 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1629 ftepp_directive_error(ftepp);
1632 else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1633 ftepp_directive_message(ftepp);
1637 if (ftepp->output_on) {
1638 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1645 /* break; never reached */
1647 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1650 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1653 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1656 /* Builtins! Don't forget the builtins! */
1657 case TOKEN_INTCONST:
1658 case TOKEN_FLOATCONST:
1659 ftepp_out(ftepp, "#", false);
1662 if (!ftepp_skipspace(ftepp))
1667 static bool ftepp_preprocess(ftepp_t *ftepp)
1670 bool newline = true;
1673 char *expand = NULL;
1675 ftepp->lex->flags.preprocessing = true;
1676 ftepp->lex->flags.mergelines = false;
1677 ftepp->lex->flags.noops = true;
1682 if (ftepp->token >= TOKEN_EOF)
1688 switch (ftepp->token) {
1691 case TOKEN_TYPENAME:
1692 /* is it a predef? */
1693 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1694 char *(*predef)(lex_file*) = ftepp_predef(ftepp_tokval(ftepp));
1696 expand = predef(ftepp->lex);
1697 ftepp_out (ftepp, expand, false);
1705 if (ftepp->output_on)
1706 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1711 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1715 if (!ftepp_macro_call(ftepp, macro))
1716 ftepp->token = TOKEN_ERROR;
1720 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1724 ftepp->lex->flags.mergelines = true;
1725 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1726 ftepp_error(ftepp, "error in preprocessor directive");
1727 ftepp->token = TOKEN_ERROR;
1730 if (!ftepp_hash(ftepp))
1731 ftepp->token = TOKEN_ERROR;
1732 ftepp->lex->flags.mergelines = false;
1736 ftepp_out(ftepp, "\n", true);
1740 /* same as default but don't set newline=false */
1741 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1746 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1750 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1752 /* force a 0 at the end but don't count it as added to the output */
1753 vec_push(ftepp->output_string, 0);
1754 vec_shrinkby(ftepp->output_string, 1);
1756 return (ftepp->token == TOKEN_EOF);
1759 /* Like in parser.c - files keep the previous state so we have one global
1760 * preprocessor. Except here we will want to warn about dangling #ifs.
1762 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1765 if (vec_size(ftepp->conditions)) {
1766 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1769 lex_close(ftepp->lex);
1771 if (ftepp->itemname) {
1772 mem_d(ftepp->itemname);
1773 ftepp->itemname = NULL;
1778 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1780 ftepp->lex = lex_open(filename);
1781 ftepp->itemname = util_strdup(filename);
1783 con_out("failed to open file \"%s\"\n", filename);
1786 if (!ftepp_preprocess(ftepp))
1788 return ftepp_preprocess_done(ftepp);
1791 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1793 ftepp->lex = lex_open_string(str, strlen(str), name);
1794 ftepp->itemname = util_strdup(name);
1796 con_out("failed to create lexer for string \"%s\"\n", name);
1799 if (!ftepp_preprocess(ftepp))
1801 return ftepp_preprocess_done(ftepp);
1805 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1806 char *create = NULL;
1808 /* use saner path for empty macros */
1810 ftepp_add_define(ftepp, "__builtin__", name);
1814 vec_upload(create, "#define ", 8);
1815 vec_upload(create, name, strlen(name));
1816 vec_push (create, ' ');
1817 vec_upload(create, value, strlen(value));
1818 vec_push (create, 0);
1820 ftepp_preprocess_string(ftepp, "__builtin__", create);
1824 ftepp_t *ftepp_create()
1830 ftepp = ftepp_new();
1834 memset(minor, 0, sizeof(minor));
1835 memset(major, 0, sizeof(major));
1837 /* set the right macro based on the selected standard */
1838 ftepp_add_define(ftepp, NULL, "GMQCC");
1839 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1840 ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1849 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1850 ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1851 util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1852 util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1853 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1854 ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1855 util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1856 util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1857 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1858 ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1869 ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1870 ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1873 * We're going to just make __NULL__ nil, which works for 60% of the
1874 * cases of __NULL_ for fteqcc.
1876 ftepp_add_macro(ftepp, "__NULL__", "nil");
1881 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1884 lex_ctx ctx = { "__builtin__", 0, 0 };
1886 macro = ppmacro_new(ctx, name);
1887 /*vec_push(ftepp->macros, macro);*/
1888 util_htset(ftepp->macros, name, macro);
1891 const char *ftepp_get(ftepp_t *ftepp)
1893 return ftepp->output_string;
1896 void ftepp_flush(ftepp_t *ftepp)
1898 ftepp_flush_do(ftepp);
1901 void ftepp_finish(ftepp_t *ftepp)
1905 ftepp_delete(ftepp);