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
37 /* a copy from the lexer */
51 /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
64 ppcondition *conditions;
74 * Implement the predef subsystem now. We can do this safely with the
75 * help of lexer contexts.
77 static uint32_t ftepp_predef_countval = 0;
78 static uint32_t ftepp_predef_randval = 0;
81 char *ftepp_predef_date(lex_file *context) {
84 char *value = mem_a(82);
85 /* 82 is enough for strftime but we also have " " in our string */
91 itime = localtime(&rtime);
93 strftime(value, 82, "\"%b %d %Y\"", itime);
99 char *ftepp_predef_time(lex_file *context) {
102 char *value = mem_a(82);
103 /* 82 is enough for strftime but we also have " " in our string */
109 itime = localtime(&rtime);
111 strftime(value, 82, "\"%X\"", itime);
117 char *ftepp_predef_line(lex_file *context) {
119 util_asprintf(&value, "%d", (int)context->line);
123 char *ftepp_predef_file(lex_file *context) {
124 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
125 char *value = (char*)mem_a(length);
126 memset (value, 0, length);
127 sprintf(value, "\"%s\"", context->name);
131 /* __COUNTER_LAST__ */
132 char *ftepp_predef_counterlast(lex_file *context) {
134 util_asprintf(&value, "%u", ftepp_predef_countval);
140 char *ftepp_predef_counter(lex_file *context) {
142 ftepp_predef_countval ++;
143 util_asprintf(&value, "%u", ftepp_predef_countval);
149 char *ftepp_predef_random(lex_file *context) {
151 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
152 util_asprintf(&value, "%u", ftepp_predef_randval);
157 /* __RANDOM_LAST__ */
158 char *ftepp_predef_randomlast(lex_file *context) {
160 util_asprintf(&value, "%u", ftepp_predef_randval);
166 const ftepp_predef_t ftepp_predefs[FTEPP_PREDEF_COUNT] = {
167 { "__LINE__", &ftepp_predef_line },
168 { "__FILE__", &ftepp_predef_file },
169 { "__COUNTER__", &ftepp_predef_counter },
170 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
171 { "__RANDOM__", &ftepp_predef_random },
172 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
173 { "__DATE__", &ftepp_predef_date },
174 { "__TIME__", &ftepp_predef_time }
177 #define ftepp_tokval(f) ((f)->lex->tok.value)
178 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
180 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
187 con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
191 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
198 con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
202 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
208 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
213 static pptoken *pptoken_make(ftepp_t *ftepp)
215 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
216 token->token = ftepp->token;
218 if (token->token == TOKEN_WHITE)
219 token->value = util_strdup(" ");
222 token->value = util_strdup(ftepp_tokval(ftepp));
224 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
228 static void pptoken_delete(pptoken *self)
234 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
236 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
239 memset(macro, 0, sizeof(*macro));
240 macro->name = util_strdup(name);
244 static void ppmacro_delete(ppmacro *self)
247 for (i = 0; i < vec_size(self->params); ++i)
248 mem_d(self->params[i]);
249 vec_free(self->params);
250 for (i = 0; i < vec_size(self->output); ++i)
251 pptoken_delete(self->output[i]);
252 vec_free(self->output);
257 static ftepp_t* ftepp_new()
261 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
262 memset(ftepp, 0, sizeof(*ftepp));
264 ftepp->output_on = true;
269 static void ftepp_flush_do(ftepp_t *self)
271 vec_free(self->output_string);
274 static void ftepp_delete(ftepp_t *self)
277 ftepp_flush_do(self);
279 mem_d(self->itemname);
280 if (self->includename)
281 vec_free(self->includename);
282 for (i = 0; i < vec_size(self->macros); ++i)
283 ppmacro_delete(self->macros[i]);
284 vec_free(self->macros);
285 vec_free(self->conditions);
287 lex_close(self->lex);
291 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
293 if (ignore_cond || ftepp->output_on)
298 data = vec_add(ftepp->output_string, len);
299 memcpy(data, str, len);
303 static void ftepp_update_output_condition(ftepp_t *ftepp)
306 ftepp->output_on = true;
307 for (i = 0; i < vec_size(ftepp->conditions); ++i)
308 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
311 static ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
314 for (i = 0; i < vec_size(ftepp->macros); ++i) {
315 if (!strcmp(name, ftepp->macros[i]->name))
316 return ftepp->macros[i];
321 static void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
324 for (i = 0; i < vec_size(ftepp->macros); ++i) {
325 if (!strcmp(name, ftepp->macros[i]->name)) {
326 vec_remove(ftepp->macros, i, 1);
332 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
334 return (ftepp->token = lex_do(ftepp->lex));
337 /* Important: this does not skip newlines! */
338 static bool ftepp_skipspace(ftepp_t *ftepp)
340 if (ftepp->token != TOKEN_WHITE)
342 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
343 if (ftepp->token >= TOKEN_EOF) {
344 ftepp_error(ftepp, "unexpected end of preprocessor directive");
350 /* this one skips EOLs as well */
351 static bool ftepp_skipallwhite(ftepp_t *ftepp)
353 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
357 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
358 if (ftepp->token >= TOKEN_EOF) {
359 ftepp_error(ftepp, "unexpected end of preprocessor directive");
366 * The huge macro parsing code...
368 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
372 if (!ftepp_skipspace(ftepp))
374 if (ftepp->token == ')')
376 switch (ftepp->token) {
380 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
383 macro->variadic = true;
386 ftepp_error(ftepp, "unexpected token in parameter list");
390 if (!ftepp_skipspace(ftepp))
392 if (macro->variadic && ftepp->token != ')') {
393 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
396 } while (ftepp->token == ',');
397 if (ftepp->token != ')') {
398 ftepp_error(ftepp, "expected closing paren after macro parameter list");
402 /* skipspace happens in ftepp_define */
406 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
409 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
410 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__"))
411 ftepp->token = TOKEN_VA_ARGS;
412 ptok = pptoken_make(ftepp);
413 vec_push(macro->output, ptok);
416 /* recursive expansion can cause EOFs here */
417 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
418 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
424 static bool ftepp_define(ftepp_t *ftepp)
427 size_t l = ftepp_ctx(ftepp).line;
429 (void)ftepp_next(ftepp);
430 if (!ftepp_skipspace(ftepp))
433 switch (ftepp->token) {
437 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
438 if (macro && ftepp->output_on) {
439 if (ftepp_warn(ftepp, WARN_PREPROCESSOR, "redefining `%s`", ftepp_tokval(ftepp)))
441 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
443 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
446 ftepp_error(ftepp, "expected macro name");
450 (void)ftepp_next(ftepp);
452 if (ftepp->token == '(') {
453 macro->has_params = true;
454 if (!ftepp_define_params(ftepp, macro))
458 if (!ftepp_skipspace(ftepp))
461 if (!ftepp_define_body(ftepp, macro))
464 if (ftepp->output_on)
465 vec_push(ftepp->macros, macro);
467 ppmacro_delete(macro);
470 for (; l < ftepp_ctx(ftepp).line; ++l)
471 ftepp_out(ftepp, "\n", true);
476 * When a macro is used we have to handle parameters as well
477 * as special-concatenation via ## or stringification via #
479 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
480 * this kind of parens. Curly braces or [] don't count towards the
487 static void macroparam_clean(macroparam *self)
490 for (i = 0; i < vec_size(self->tokens); ++i)
491 pptoken_delete(self->tokens[i]);
492 vec_free(self->tokens);
495 /* need to leave the last token up */
496 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
498 macroparam *params = NULL;
504 if (!ftepp_skipallwhite(ftepp))
506 while (ftepp->token != ')') {
508 if (!ftepp_skipallwhite(ftepp))
510 while (parens || ftepp->token != ',') {
511 if (ftepp->token == '(')
513 else if (ftepp->token == ')') {
518 ptok = pptoken_make(ftepp);
519 vec_push(mp.tokens, ptok);
520 if (ftepp_next(ftepp) >= TOKEN_EOF) {
521 ftepp_error(ftepp, "unexpected EOF in macro call");
525 vec_push(params, mp);
527 if (ftepp->token == ')')
529 if (ftepp->token != ',') {
530 ftepp_error(ftepp, "expected closing paren or comma in macro call");
533 if (ftepp_next(ftepp) >= TOKEN_EOF) {
534 ftepp_error(ftepp, "unexpected EOF in macro call");
538 /* need to leave that up
539 if (ftepp_next(ftepp) >= TOKEN_EOF) {
540 ftepp_error(ftepp, "unexpected EOF in macro call");
544 *out_params = params;
549 macroparam_clean(&mp);
550 for (i = 0; i < vec_size(params); ++i)
551 macroparam_clean(¶ms[i]);
556 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
559 for (i = 0; i < vec_size(macro->params); ++i) {
560 if (!strcmp(macro->params[i], name)) {
568 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
573 switch (token->token) {
574 case TOKEN_STRINGCONST:
577 /* in preprocessor mode strings already are string,
578 * so we don't get actual newline bytes here.
579 * Still need to escape backslashes and quotes.
582 case '\\': ftepp_out(ftepp, "\\\\", false); break;
583 case '"': ftepp_out(ftepp, "\\\"", false); break;
586 ftepp_out(ftepp, chs, false);
593 ftepp_out(ftepp, " ", false);
596 ftepp_out(ftepp, "\\n", false);
599 ftepp_out(ftepp, token->value, false);
604 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
607 ftepp_out(ftepp, "\"", false);
608 for (i = 0; i < vec_size(param->tokens); ++i)
609 ftepp_stringify_token(ftepp, param->tokens[i]);
610 ftepp_out(ftepp, "\"", false);
613 static void ftepp_recursion_header(ftepp_t *ftepp)
615 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
618 static void ftepp_recursion_footer(ftepp_t *ftepp)
620 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
623 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
627 for (i = 0; i < vec_size(param->tokens); ++i) {
628 out = param->tokens[i];
629 if (out->token == TOKEN_EOL)
630 ftepp_out(ftepp, "\n", false);
632 ftepp_out(ftepp, out->value, false);
636 static bool ftepp_preprocess(ftepp_t *ftepp);
637 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params)
639 char *old_string = ftepp->output_string;
640 lex_file *old_lexer = ftepp->lex;
641 size_t vararg_start = vec_size(macro->params);
650 if (vararg_start < vec_size(params))
651 varargs = vec_size(params) - vararg_start;
656 if (!vec_size(macro->output))
659 ftepp->output_string = NULL;
660 for (o = 0; o < vec_size(macro->output); ++o) {
661 pptoken *out = macro->output[o];
662 switch (out->token) {
664 if (!macro->variadic) {
665 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
671 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
672 for (++pi; pi < varargs; ++pi) {
673 ftepp_out(ftepp, ", ", false);
674 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
680 if (!macro_params_find(macro, out->value, &pi)) {
681 ftepp_out(ftepp, out->value, false);
684 ftepp_param_out(ftepp, ¶ms[pi]);
687 if (o + 1 < vec_size(macro->output)) {
688 nextok = macro->output[o+1]->token;
690 /* raw concatenation */
694 if ( (nextok == TOKEN_IDENT ||
695 nextok == TOKEN_KEYWORD ||
696 nextok == TOKEN_TYPENAME) &&
697 macro_params_find(macro, macro->output[o+1]->value, &pi))
700 ftepp_stringify(ftepp, ¶ms[pi]);
704 ftepp_out(ftepp, "#", false);
707 ftepp_out(ftepp, "\n", false);
710 ftepp_out(ftepp, out->value, false);
714 vec_push(ftepp->output_string, 0);
715 /* Now run the preprocessor recursively on this string buffer */
717 printf("__________\n%s\n=========\n", ftepp->output_string);
719 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
721 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
725 ftepp->output_string = old_string;
726 inlex->line = ftepp->lex->line;
727 inlex->sline = ftepp->lex->sline;
729 ftepp_recursion_header(ftepp);
730 if (!ftepp_preprocess(ftepp)) {
731 vec_free(ftepp->lex->open_string);
732 old_string = ftepp->output_string;
733 lex_close(ftepp->lex);
737 vec_free(ftepp->lex->open_string);
738 ftepp_recursion_footer(ftepp);
739 old_string = ftepp->output_string;
742 ftepp->lex = old_lexer;
743 ftepp->output_string = old_string;
747 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
750 macroparam *params = NULL;
753 if (!macro->has_params) {
754 if (!ftepp_macro_expand(ftepp, macro, NULL))
761 if (!ftepp_skipallwhite(ftepp))
764 if (ftepp->token != '(') {
765 ftepp_error(ftepp, "expected macro parameters in parenthesis");
770 if (!ftepp_macro_call_params(ftepp, ¶ms))
773 if ( vec_size(params) < vec_size(macro->params) ||
774 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
776 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
777 (macro->variadic ? " at least" : ""),
778 (unsigned int)vec_size(macro->params),
779 (unsigned int)vec_size(params));
784 if (!ftepp_macro_expand(ftepp, macro, params))
789 for (o = 0; o < vec_size(params); ++o)
790 macroparam_clean(¶ms[o]);
796 * #if - the FTEQCC way:
797 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
798 * <numbers> => True if the number is not 0
799 * !<factor> => True if the factor yields false
800 * !!<factor> => ERROR on 2 or more unary nots
801 * <macro> => becomes the macro's FIRST token regardless of parameters
802 * <e> && <e> => True if both expressions are true
803 * <e> || <e> => True if either expression is true
805 * <ident> => False (remember for macros the <macro> rule applies instead)
806 * Unary + and - are weird and wrong in fteqcc so we don't allow them
807 * parenthesis in expressions are allowed
808 * parameter lists on macros are errors
809 * No mathematical calculations are executed
811 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
812 static bool ftepp_if_op(ftepp_t *ftepp)
814 ftepp->lex->flags.noops = false;
816 if (!ftepp_skipspace(ftepp))
818 ftepp->lex->flags.noops = true;
821 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
826 if (!ftepp_skipspace(ftepp))
829 while (ftepp->token == '!') {
832 if (!ftepp_skipspace(ftepp))
836 switch (ftepp->token) {
840 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
842 if (!ftepp_skipspace(ftepp))
844 if (ftepp->token != '(') {
845 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
849 if (!ftepp_skipspace(ftepp))
851 if (ftepp->token != TOKEN_IDENT &&
852 ftepp->token != TOKEN_TYPENAME &&
853 ftepp->token != TOKEN_KEYWORD)
855 ftepp_error(ftepp, "defined() used on an unexpected token type");
858 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
861 if (!ftepp_skipspace(ftepp))
863 if (ftepp->token != ')') {
864 ftepp_error(ftepp, "expected closing paren");
870 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
871 if (!macro || !vec_size(macro->output)) {
875 /* This does not expand recursively! */
876 switch (macro->output[0]->token) {
878 *value_out = macro->output[0]->constval.i;
879 *out = !!(macro->output[0]->constval.i);
881 case TOKEN_FLOATCONST:
882 *value_out = macro->output[0]->constval.f;
883 *out = !!(macro->output[0]->constval.f);
891 case TOKEN_STRINGCONST:
895 *value_out = ftepp->lex->tok.constval.i;
896 *out = !!(ftepp->lex->tok.constval.i);
898 case TOKEN_FLOATCONST:
899 *value_out = ftepp->lex->tok.constval.f;
900 *out = !!(ftepp->lex->tok.constval.f);
905 if (!ftepp_if_expr(ftepp, out, value_out))
907 if (ftepp->token != ')') {
908 ftepp_error(ftepp, "expected closing paren in #if expression");
914 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
919 *value_out = (*out ? 1 : 0);
925 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
927 if (!ftepp_next(ftepp))
929 return ftepp_if_value(ftepp, out, value_out);
933 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
935 if (!ftepp_if_value(ftepp, out, value_out))
938 if (!ftepp_if_op(ftepp))
941 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
944 /* FTEQCC is all right-associative and no precedence here */
945 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
946 !strcmp(ftepp_tokval(ftepp), "||"))
949 char opc = ftepp_tokval(ftepp)[0];
953 if (!ftepp_next(ftepp))
955 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
963 *value_out = (*out ? 1 : 0);
966 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
967 !strcmp(ftepp_tokval(ftepp), "!=") ||
968 !strcmp(ftepp_tokval(ftepp), ">=") ||
969 !strcmp(ftepp_tokval(ftepp), "<=") ||
970 !strcmp(ftepp_tokval(ftepp), ">") ||
971 !strcmp(ftepp_tokval(ftepp), "<"))
974 const char opc0 = ftepp_tokval(ftepp)[0];
975 const char opc1 = ftepp_tokval(ftepp)[1];
978 if (!ftepp_next(ftepp))
980 if (!ftepp_if_expr(ftepp, &next, &other))
984 *out = (*value_out == other);
985 else if (opc0 == '!')
986 *out = (*value_out != other);
987 else if (opc0 == '>') {
988 if (opc1 == '=') *out = (*value_out >= other);
989 else *out = (*value_out > other);
991 else if (opc0 == '<') {
992 if (opc1 == '=') *out = (*value_out <= other);
993 else *out = (*value_out < other);
995 *value_out = (*out ? 1 : 0);
1000 ftepp_error(ftepp, "junk after #if");
1005 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1007 bool result = false;
1010 memset(cond, 0, sizeof(*cond));
1011 (void)ftepp_next(ftepp);
1013 if (!ftepp_skipspace(ftepp))
1015 if (ftepp->token == TOKEN_EOL) {
1016 ftepp_error(ftepp, "expected expression for #if-directive");
1020 if (!ftepp_if_expr(ftepp, &result, &dummy))
1028 * ifdef is rather simple
1030 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1033 memset(cond, 0, sizeof(*cond));
1034 (void)ftepp_next(ftepp);
1035 if (!ftepp_skipspace(ftepp))
1038 switch (ftepp->token) {
1040 case TOKEN_TYPENAME:
1042 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1045 ftepp_error(ftepp, "expected macro name");
1049 (void)ftepp_next(ftepp);
1050 if (!ftepp_skipspace(ftepp))
1052 /* relaxing this condition
1053 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1054 ftepp_error(ftepp, "stray tokens after #ifdef");
1063 * undef is also simple
1065 static bool ftepp_undef(ftepp_t *ftepp)
1067 (void)ftepp_next(ftepp);
1068 if (!ftepp_skipspace(ftepp))
1071 if (ftepp->output_on) {
1072 switch (ftepp->token) {
1074 case TOKEN_TYPENAME:
1076 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1079 ftepp_error(ftepp, "expected macro name");
1084 (void)ftepp_next(ftepp);
1085 if (!ftepp_skipspace(ftepp))
1087 /* relaxing this condition
1088 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1089 ftepp_error(ftepp, "stray tokens after #ifdef");
1096 /* Special unescape-string function which skips a leading quote
1097 * and stops at a quote, not just at \0
1099 static void unescape(const char *str, char *out) {
1101 while (*str && *str != '"') {
1105 case '\\': *out++ = *str; break;
1106 case '"': *out++ = *str; break;
1107 case 'a': *out++ = '\a'; break;
1108 case 'b': *out++ = '\b'; break;
1109 case 'r': *out++ = '\r'; break;
1110 case 'n': *out++ = '\n'; break;
1111 case 't': *out++ = '\t'; break;
1112 case 'f': *out++ = '\f'; break;
1113 case 'v': *out++ = '\v'; break;
1128 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1131 char *filename = NULL;
1132 const char *last_slash;
1138 last_slash = strrchr(pathfile, '/');
1141 len = last_slash - pathfile;
1142 memcpy(vec_add(filename, len), pathfile, len);
1143 vec_push(filename, '/');
1147 memcpy(vec_add(filename, len+1), file, len);
1148 vec_last(filename) = 0;
1150 fp = file_open(filename, "rb");
1159 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1161 char *filename = NULL;
1163 filename = ftepp_include_find_path(file, ftepp->includename);
1165 filename = ftepp_include_find_path(file, ftepp->itemname);
1169 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1170 char *message = NULL;
1172 if (!ftepp_skipspace(ftepp))
1175 /* handle the odd non string constant case so it works like C */
1176 if (ftepp->token != TOKEN_STRINGCONST) {
1178 vec_upload(message, "#warning", 8);
1180 while (ftepp->token != TOKEN_EOL) {
1181 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1184 vec_push(message, '\0');
1185 store = ftepp_warn(ftepp, WARN_CPP, message);
1190 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1191 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1194 static void ftepp_directive_error(ftepp_t *ftepp) {
1195 char *message = NULL;
1197 if (!ftepp_skipspace(ftepp))
1200 /* handle the odd non string constant case so it works like C */
1201 if (ftepp->token != TOKEN_STRINGCONST) {
1202 vec_upload(message, "#error", 6);
1204 while (ftepp->token != TOKEN_EOL) {
1205 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1208 vec_push(message, '\0');
1209 ftepp_error(ftepp, message);
1214 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1215 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1220 * FIXME: do we need/want a -I option?
1221 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1223 static bool ftepp_include(ftepp_t *ftepp)
1225 lex_file *old_lexer = ftepp->lex;
1230 char *old_includename;
1232 (void)ftepp_next(ftepp);
1233 if (!ftepp_skipspace(ftepp))
1236 if (ftepp->token != TOKEN_STRINGCONST) {
1237 ftepp_error(ftepp, "expected filename to include");
1241 ctx = ftepp_ctx(ftepp);
1243 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1245 ftepp_out(ftepp, "\n#pragma file(", false);
1246 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1247 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1249 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1251 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1254 inlex = lex_open(filename);
1256 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1261 old_includename = ftepp->includename;
1262 ftepp->includename = filename;
1263 if (!ftepp_preprocess(ftepp)) {
1264 vec_free(ftepp->includename);
1265 ftepp->includename = old_includename;
1266 lex_close(ftepp->lex);
1267 ftepp->lex = old_lexer;
1270 vec_free(ftepp->includename);
1271 ftepp->includename = old_includename;
1272 lex_close(ftepp->lex);
1273 ftepp->lex = old_lexer;
1275 ftepp_out(ftepp, "\n#pragma file(", false);
1276 ftepp_out(ftepp, ctx.file, false);
1277 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1278 ftepp_out(ftepp, lineno, false);
1281 (void)ftepp_next(ftepp);
1282 if (!ftepp_skipspace(ftepp))
1284 if (ftepp->token != TOKEN_EOL) {
1285 ftepp_error(ftepp, "stray tokens after #include");
1288 (void)ftepp_next(ftepp);
1293 /* Basic structure handlers */
1294 static bool ftepp_else_allowed(ftepp_t *ftepp)
1296 if (!vec_size(ftepp->conditions)) {
1297 ftepp_error(ftepp, "#else without #if");
1300 if (vec_last(ftepp->conditions).had_else) {
1301 ftepp_error(ftepp, "multiple #else for a single #if");
1307 static bool ftepp_hash(ftepp_t *ftepp)
1312 lex_ctx ctx = ftepp_ctx(ftepp);
1314 if (!ftepp_skipspace(ftepp))
1317 switch (ftepp->token) {
1320 case TOKEN_TYPENAME:
1321 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1322 return ftepp_define(ftepp);
1324 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1325 return ftepp_undef(ftepp);
1327 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1328 if (!ftepp_ifdef(ftepp, &cond))
1330 cond.was_on = cond.on;
1331 vec_push(ftepp->conditions, cond);
1332 ftepp->output_on = ftepp->output_on && cond.on;
1335 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1336 if (!ftepp_ifdef(ftepp, &cond))
1339 cond.was_on = cond.on;
1340 vec_push(ftepp->conditions, cond);
1341 ftepp->output_on = ftepp->output_on && cond.on;
1344 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1345 if (!ftepp_else_allowed(ftepp))
1347 if (!ftepp_ifdef(ftepp, &cond))
1349 pc = &vec_last(ftepp->conditions);
1350 pc->on = !pc->was_on && cond.on;
1351 pc->was_on = pc->was_on || pc->on;
1352 ftepp_update_output_condition(ftepp);
1355 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1356 if (!ftepp_else_allowed(ftepp))
1358 if (!ftepp_ifdef(ftepp, &cond))
1361 pc = &vec_last(ftepp->conditions);
1362 pc->on = !pc->was_on && cond.on;
1363 pc->was_on = pc->was_on || pc->on;
1364 ftepp_update_output_condition(ftepp);
1367 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1368 if (!ftepp_else_allowed(ftepp))
1370 if (!ftepp_if(ftepp, &cond))
1372 pc = &vec_last(ftepp->conditions);
1373 pc->on = !pc->was_on && cond.on;
1374 pc->was_on = pc->was_on || pc->on;
1375 ftepp_update_output_condition(ftepp);
1378 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1379 if (!ftepp_if(ftepp, &cond))
1381 cond.was_on = cond.on;
1382 vec_push(ftepp->conditions, cond);
1383 ftepp->output_on = ftepp->output_on && cond.on;
1386 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1387 if (!ftepp_else_allowed(ftepp))
1389 pc = &vec_last(ftepp->conditions);
1390 pc->on = !pc->was_on;
1391 pc->had_else = true;
1393 ftepp_update_output_condition(ftepp);
1396 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1397 if (!vec_size(ftepp->conditions)) {
1398 ftepp_error(ftepp, "#endif without #if");
1401 vec_pop(ftepp->conditions);
1403 ftepp_update_output_condition(ftepp);
1406 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1407 return ftepp_include(ftepp);
1409 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1410 ftepp_out(ftepp, "#", false);
1413 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1414 ftepp_directive_warning(ftepp);
1417 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1418 ftepp_directive_error(ftepp);
1422 if (ftepp->output_on) {
1423 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1430 /* break; never reached */
1432 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1435 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1438 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1441 /* Builtins! Don't forget the builtins! */
1442 case TOKEN_INTCONST:
1443 case TOKEN_FLOATCONST:
1444 ftepp_out(ftepp, "#", false);
1447 if (!ftepp_skipspace(ftepp))
1452 static bool ftepp_preprocess(ftepp_t *ftepp)
1455 bool newline = true;
1458 char *expand = NULL;
1461 ftepp->lex->flags.preprocessing = true;
1462 ftepp->lex->flags.mergelines = false;
1463 ftepp->lex->flags.noops = true;
1468 if (ftepp->token >= TOKEN_EOF)
1474 switch (ftepp->token) {
1477 case TOKEN_TYPENAME:
1478 /* is it a predef? */
1479 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1480 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1481 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1482 expand = ftepp_predefs[i].func(ftepp->lex);
1483 ftepp_out(ftepp, expand, false);
1484 ftepp_next(ftepp); /* skip */
1486 mem_d(expand); /* free memory */
1492 if (ftepp->output_on)
1493 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1498 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1502 if (!ftepp_macro_call(ftepp, macro))
1503 ftepp->token = TOKEN_ERROR;
1507 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1511 ftepp->lex->flags.mergelines = true;
1512 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1513 ftepp_error(ftepp, "error in preprocessor directive");
1514 ftepp->token = TOKEN_ERROR;
1517 if (!ftepp_hash(ftepp))
1518 ftepp->token = TOKEN_ERROR;
1519 ftepp->lex->flags.mergelines = false;
1523 ftepp_out(ftepp, "\n", true);
1527 /* same as default but don't set newline=false */
1528 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1533 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1537 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1539 /* force a 0 at the end but don't count it as added to the output */
1540 vec_push(ftepp->output_string, 0);
1541 vec_shrinkby(ftepp->output_string, 1);
1543 return (ftepp->token == TOKEN_EOF);
1546 /* Like in parser.c - files keep the previous state so we have one global
1547 * preprocessor. Except here we will want to warn about dangling #ifs.
1549 static ftepp_t *ftepp;
1551 static bool ftepp_preprocess_done()
1554 if (vec_size(ftepp->conditions)) {
1555 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1558 lex_close(ftepp->lex);
1560 if (ftepp->itemname) {
1561 mem_d(ftepp->itemname);
1562 ftepp->itemname = NULL;
1567 bool ftepp_preprocess_file(const char *filename)
1569 ftepp->lex = lex_open(filename);
1570 ftepp->itemname = util_strdup(filename);
1572 con_out("failed to open file \"%s\"\n", filename);
1575 if (!ftepp_preprocess(ftepp))
1577 return ftepp_preprocess_done();
1580 bool ftepp_preprocess_string(const char *name, const char *str)
1582 ftepp->lex = lex_open_string(str, strlen(str), name);
1583 ftepp->itemname = util_strdup(name);
1585 con_out("failed to create lexer for string \"%s\"\n", name);
1588 if (!ftepp_preprocess(ftepp))
1590 return ftepp_preprocess_done();
1594 void ftepp_add_macro(const char *name, const char *value) {
1595 char *create = NULL;
1597 /* use saner path for empty macros */
1599 ftepp_add_define("__builtin__", name);
1603 vec_upload(create, "#define ", 8);
1604 vec_upload(create, name, strlen(name));
1605 vec_push (create, ' ');
1606 vec_upload(create, value, strlen(value));
1607 vec_push (create, 0);
1609 ftepp_preprocess_string("__builtin__", create);
1618 ftepp = ftepp_new();
1622 memset(minor, 0, sizeof(minor));
1623 memset(major, 0, sizeof(major));
1625 /* set the right macro based on the selected standard */
1626 ftepp_add_define(NULL, "GMQCC");
1627 if (opts.standard == COMPILER_FTEQCC) {
1628 ftepp_add_define(NULL, "__STD_FTEQCC__");
1637 } else if (opts.standard == COMPILER_GMQCC) {
1638 ftepp_add_define(NULL, "__STD_GMQCC__");
1639 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1640 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1641 } else if (opts.standard == COMPILER_QCC) {
1642 ftepp_add_define(NULL, "__STD_QCC__");
1653 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1654 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1659 void ftepp_add_define(const char *source, const char *name)
1662 lex_ctx ctx = { "__builtin__", 0 };
1664 macro = ppmacro_new(ctx, name);
1665 vec_push(ftepp->macros, macro);
1668 const char *ftepp_get()
1670 return ftepp->output_string;
1675 ftepp_flush_do(ftepp);
1682 ftepp_delete(ftepp);