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)
827 if (!ftepp_skipspace(ftepp))
830 while (ftepp->token == '!') {
833 if (!ftepp_skipspace(ftepp))
837 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
841 if (!ftepp_skipspace(ftepp))
845 switch (ftepp->token) {
849 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
851 if (!ftepp_skipspace(ftepp))
853 if (ftepp->token != '(') {
854 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
858 if (!ftepp_skipspace(ftepp))
860 if (ftepp->token != TOKEN_IDENT &&
861 ftepp->token != TOKEN_TYPENAME &&
862 ftepp->token != TOKEN_KEYWORD)
864 ftepp_error(ftepp, "defined() used on an unexpected token type");
867 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
870 if (!ftepp_skipspace(ftepp))
872 if (ftepp->token != ')') {
873 ftepp_error(ftepp, "expected closing paren");
879 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
880 if (!macro || !vec_size(macro->output)) {
884 /* This does not expand recursively! */
885 switch (macro->output[0]->token) {
887 *value_out = macro->output[0]->constval.i;
888 *out = !!(macro->output[0]->constval.i);
890 case TOKEN_FLOATCONST:
891 *value_out = macro->output[0]->constval.f;
892 *out = !!(macro->output[0]->constval.f);
900 case TOKEN_STRINGCONST:
905 *value_out = ftepp->lex->tok.constval.i;
906 *out = !!(ftepp->lex->tok.constval.i);
908 case TOKEN_FLOATCONST:
909 *value_out = ftepp->lex->tok.constval.f;
910 *out = !!(ftepp->lex->tok.constval.f);
915 if (!ftepp_if_expr(ftepp, out, value_out))
917 if (ftepp->token != ')') {
918 ftepp_error(ftepp, "expected closing paren in #if expression");
924 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
926 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
930 *value_out = -*value_out;
933 *value_out = (*out ? 1 : 0);
939 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
941 if (!ftepp_next(ftepp))
943 return ftepp_if_value(ftepp, out, value_out);
947 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
949 if (!ftepp_if_value(ftepp, out, value_out))
952 if (!ftepp_if_op(ftepp))
955 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
958 /* FTEQCC is all right-associative and no precedence here */
959 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
960 !strcmp(ftepp_tokval(ftepp), "||"))
963 char opc = ftepp_tokval(ftepp)[0];
967 if (!ftepp_next(ftepp))
969 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
977 *value_out = (*out ? 1 : 0);
980 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
981 !strcmp(ftepp_tokval(ftepp), "!=") ||
982 !strcmp(ftepp_tokval(ftepp), ">=") ||
983 !strcmp(ftepp_tokval(ftepp), "<=") ||
984 !strcmp(ftepp_tokval(ftepp), ">") ||
985 !strcmp(ftepp_tokval(ftepp), "<"))
988 const char opc0 = ftepp_tokval(ftepp)[0];
989 const char opc1 = ftepp_tokval(ftepp)[1];
992 if (!ftepp_next(ftepp))
994 if (!ftepp_if_expr(ftepp, &next, &other))
998 *out = (*value_out == other);
999 else if (opc0 == '!')
1000 *out = (*value_out != other);
1001 else if (opc0 == '>') {
1002 if (opc1 == '=') *out = (*value_out >= other);
1003 else *out = (*value_out > other);
1005 else if (opc0 == '<') {
1006 if (opc1 == '=') *out = (*value_out <= other);
1007 else *out = (*value_out < other);
1009 *value_out = (*out ? 1 : 0);
1014 ftepp_error(ftepp, "junk after #if");
1019 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1021 bool result = false;
1024 memset(cond, 0, sizeof(*cond));
1025 (void)ftepp_next(ftepp);
1027 if (!ftepp_skipspace(ftepp))
1029 if (ftepp->token == TOKEN_EOL) {
1030 ftepp_error(ftepp, "expected expression for #if-directive");
1034 if (!ftepp_if_expr(ftepp, &result, &dummy))
1042 * ifdef is rather simple
1044 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1047 memset(cond, 0, sizeof(*cond));
1048 (void)ftepp_next(ftepp);
1049 if (!ftepp_skipspace(ftepp))
1052 switch (ftepp->token) {
1054 case TOKEN_TYPENAME:
1056 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1059 ftepp_error(ftepp, "expected macro name");
1063 (void)ftepp_next(ftepp);
1064 if (!ftepp_skipspace(ftepp))
1066 /* relaxing this condition
1067 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1068 ftepp_error(ftepp, "stray tokens after #ifdef");
1077 * undef is also simple
1079 static bool ftepp_undef(ftepp_t *ftepp)
1081 (void)ftepp_next(ftepp);
1082 if (!ftepp_skipspace(ftepp))
1085 if (ftepp->output_on) {
1086 switch (ftepp->token) {
1088 case TOKEN_TYPENAME:
1090 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1093 ftepp_error(ftepp, "expected macro name");
1098 (void)ftepp_next(ftepp);
1099 if (!ftepp_skipspace(ftepp))
1101 /* relaxing this condition
1102 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1103 ftepp_error(ftepp, "stray tokens after #ifdef");
1110 /* Special unescape-string function which skips a leading quote
1111 * and stops at a quote, not just at \0
1113 static void unescape(const char *str, char *out) {
1115 while (*str && *str != '"') {
1119 case '\\': *out++ = *str; break;
1120 case '"': *out++ = *str; break;
1121 case 'a': *out++ = '\a'; break;
1122 case 'b': *out++ = '\b'; break;
1123 case 'r': *out++ = '\r'; break;
1124 case 'n': *out++ = '\n'; break;
1125 case 't': *out++ = '\t'; break;
1126 case 'f': *out++ = '\f'; break;
1127 case 'v': *out++ = '\v'; break;
1142 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1145 char *filename = NULL;
1146 const char *last_slash;
1152 last_slash = strrchr(pathfile, '/');
1155 len = last_slash - pathfile;
1156 memcpy(vec_add(filename, len), pathfile, len);
1157 vec_push(filename, '/');
1161 memcpy(vec_add(filename, len+1), file, len);
1162 vec_last(filename) = 0;
1164 fp = file_open(filename, "rb");
1173 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1175 char *filename = NULL;
1177 filename = ftepp_include_find_path(file, ftepp->includename);
1179 filename = ftepp_include_find_path(file, ftepp->itemname);
1183 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1184 char *message = NULL;
1186 if (!ftepp_skipspace(ftepp))
1189 /* handle the odd non string constant case so it works like C */
1190 if (ftepp->token != TOKEN_STRINGCONST) {
1192 vec_upload(message, "#warning", 8);
1194 while (ftepp->token != TOKEN_EOL) {
1195 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1198 vec_push(message, '\0');
1199 store = ftepp_warn(ftepp, WARN_CPP, message);
1204 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1205 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1208 static void ftepp_directive_error(ftepp_t *ftepp) {
1209 char *message = NULL;
1211 if (!ftepp_skipspace(ftepp))
1214 /* handle the odd non string constant case so it works like C */
1215 if (ftepp->token != TOKEN_STRINGCONST) {
1216 vec_upload(message, "#error", 6);
1218 while (ftepp->token != TOKEN_EOL) {
1219 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1222 vec_push(message, '\0');
1223 ftepp_error(ftepp, message);
1228 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1229 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1234 * FIXME: do we need/want a -I option?
1235 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1237 static bool ftepp_include(ftepp_t *ftepp)
1239 lex_file *old_lexer = ftepp->lex;
1244 char *old_includename;
1246 (void)ftepp_next(ftepp);
1247 if (!ftepp_skipspace(ftepp))
1250 if (ftepp->token != TOKEN_STRINGCONST) {
1251 ftepp_error(ftepp, "expected filename to include");
1255 ctx = ftepp_ctx(ftepp);
1257 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1259 ftepp_out(ftepp, "\n#pragma file(", false);
1260 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1261 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1263 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1265 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1268 inlex = lex_open(filename);
1270 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1275 old_includename = ftepp->includename;
1276 ftepp->includename = filename;
1277 if (!ftepp_preprocess(ftepp)) {
1278 vec_free(ftepp->includename);
1279 ftepp->includename = old_includename;
1280 lex_close(ftepp->lex);
1281 ftepp->lex = old_lexer;
1284 vec_free(ftepp->includename);
1285 ftepp->includename = old_includename;
1286 lex_close(ftepp->lex);
1287 ftepp->lex = old_lexer;
1289 ftepp_out(ftepp, "\n#pragma file(", false);
1290 ftepp_out(ftepp, ctx.file, false);
1291 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1292 ftepp_out(ftepp, lineno, false);
1295 (void)ftepp_next(ftepp);
1296 if (!ftepp_skipspace(ftepp))
1298 if (ftepp->token != TOKEN_EOL) {
1299 ftepp_error(ftepp, "stray tokens after #include");
1302 (void)ftepp_next(ftepp);
1307 /* Basic structure handlers */
1308 static bool ftepp_else_allowed(ftepp_t *ftepp)
1310 if (!vec_size(ftepp->conditions)) {
1311 ftepp_error(ftepp, "#else without #if");
1314 if (vec_last(ftepp->conditions).had_else) {
1315 ftepp_error(ftepp, "multiple #else for a single #if");
1321 static bool ftepp_hash(ftepp_t *ftepp)
1326 lex_ctx ctx = ftepp_ctx(ftepp);
1328 if (!ftepp_skipspace(ftepp))
1331 switch (ftepp->token) {
1334 case TOKEN_TYPENAME:
1335 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1336 return ftepp_define(ftepp);
1338 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1339 return ftepp_undef(ftepp);
1341 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1342 if (!ftepp_ifdef(ftepp, &cond))
1344 cond.was_on = cond.on;
1345 vec_push(ftepp->conditions, cond);
1346 ftepp->output_on = ftepp->output_on && cond.on;
1349 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1350 if (!ftepp_ifdef(ftepp, &cond))
1353 cond.was_on = cond.on;
1354 vec_push(ftepp->conditions, cond);
1355 ftepp->output_on = ftepp->output_on && cond.on;
1358 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1359 if (!ftepp_else_allowed(ftepp))
1361 if (!ftepp_ifdef(ftepp, &cond))
1363 pc = &vec_last(ftepp->conditions);
1364 pc->on = !pc->was_on && cond.on;
1365 pc->was_on = pc->was_on || pc->on;
1366 ftepp_update_output_condition(ftepp);
1369 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1370 if (!ftepp_else_allowed(ftepp))
1372 if (!ftepp_ifdef(ftepp, &cond))
1375 pc = &vec_last(ftepp->conditions);
1376 pc->on = !pc->was_on && cond.on;
1377 pc->was_on = pc->was_on || pc->on;
1378 ftepp_update_output_condition(ftepp);
1381 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1382 if (!ftepp_else_allowed(ftepp))
1384 if (!ftepp_if(ftepp, &cond))
1386 pc = &vec_last(ftepp->conditions);
1387 pc->on = !pc->was_on && cond.on;
1388 pc->was_on = pc->was_on || pc->on;
1389 ftepp_update_output_condition(ftepp);
1392 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1393 if (!ftepp_if(ftepp, &cond))
1395 cond.was_on = cond.on;
1396 vec_push(ftepp->conditions, cond);
1397 ftepp->output_on = ftepp->output_on && cond.on;
1400 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1401 if (!ftepp_else_allowed(ftepp))
1403 pc = &vec_last(ftepp->conditions);
1404 pc->on = !pc->was_on;
1405 pc->had_else = true;
1407 ftepp_update_output_condition(ftepp);
1410 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1411 if (!vec_size(ftepp->conditions)) {
1412 ftepp_error(ftepp, "#endif without #if");
1415 vec_pop(ftepp->conditions);
1417 ftepp_update_output_condition(ftepp);
1420 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1421 return ftepp_include(ftepp);
1423 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1424 ftepp_out(ftepp, "#", false);
1427 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1428 ftepp_directive_warning(ftepp);
1431 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1432 ftepp_directive_error(ftepp);
1436 if (ftepp->output_on) {
1437 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1444 /* break; never reached */
1446 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1449 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1452 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1455 /* Builtins! Don't forget the builtins! */
1456 case TOKEN_INTCONST:
1457 case TOKEN_FLOATCONST:
1458 ftepp_out(ftepp, "#", false);
1461 if (!ftepp_skipspace(ftepp))
1466 static bool ftepp_preprocess(ftepp_t *ftepp)
1469 bool newline = true;
1472 char *expand = NULL;
1475 ftepp->lex->flags.preprocessing = true;
1476 ftepp->lex->flags.mergelines = false;
1477 ftepp->lex->flags.noops = true;
1482 if (ftepp->token >= TOKEN_EOF)
1488 switch (ftepp->token) {
1491 case TOKEN_TYPENAME:
1492 /* is it a predef? */
1493 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1494 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1495 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1496 expand = ftepp_predefs[i].func(ftepp->lex);
1497 ftepp_out(ftepp, expand, false);
1498 ftepp_next(ftepp); /* skip */
1500 mem_d(expand); /* free memory */
1506 if (ftepp->output_on)
1507 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1512 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1516 if (!ftepp_macro_call(ftepp, macro))
1517 ftepp->token = TOKEN_ERROR;
1521 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1525 ftepp->lex->flags.mergelines = true;
1526 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1527 ftepp_error(ftepp, "error in preprocessor directive");
1528 ftepp->token = TOKEN_ERROR;
1531 if (!ftepp_hash(ftepp))
1532 ftepp->token = TOKEN_ERROR;
1533 ftepp->lex->flags.mergelines = false;
1537 ftepp_out(ftepp, "\n", true);
1541 /* same as default but don't set newline=false */
1542 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1547 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1551 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1553 /* force a 0 at the end but don't count it as added to the output */
1554 vec_push(ftepp->output_string, 0);
1555 vec_shrinkby(ftepp->output_string, 1);
1557 return (ftepp->token == TOKEN_EOF);
1560 /* Like in parser.c - files keep the previous state so we have one global
1561 * preprocessor. Except here we will want to warn about dangling #ifs.
1563 static ftepp_t *ftepp;
1565 static bool ftepp_preprocess_done()
1568 if (vec_size(ftepp->conditions)) {
1569 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1572 lex_close(ftepp->lex);
1574 if (ftepp->itemname) {
1575 mem_d(ftepp->itemname);
1576 ftepp->itemname = NULL;
1581 bool ftepp_preprocess_file(const char *filename)
1583 ftepp->lex = lex_open(filename);
1584 ftepp->itemname = util_strdup(filename);
1586 con_out("failed to open file \"%s\"\n", filename);
1589 if (!ftepp_preprocess(ftepp))
1591 return ftepp_preprocess_done();
1594 bool ftepp_preprocess_string(const char *name, const char *str)
1596 ftepp->lex = lex_open_string(str, strlen(str), name);
1597 ftepp->itemname = util_strdup(name);
1599 con_out("failed to create lexer for string \"%s\"\n", name);
1602 if (!ftepp_preprocess(ftepp))
1604 return ftepp_preprocess_done();
1608 void ftepp_add_macro(const char *name, const char *value) {
1609 char *create = NULL;
1611 /* use saner path for empty macros */
1613 ftepp_add_define("__builtin__", name);
1617 vec_upload(create, "#define ", 8);
1618 vec_upload(create, name, strlen(name));
1619 vec_push (create, ' ');
1620 vec_upload(create, value, strlen(value));
1621 vec_push (create, 0);
1623 ftepp_preprocess_string("__builtin__", create);
1632 ftepp = ftepp_new();
1636 memset(minor, 0, sizeof(minor));
1637 memset(major, 0, sizeof(major));
1639 /* set the right macro based on the selected standard */
1640 ftepp_add_define(NULL, "GMQCC");
1641 if (opts.standard == COMPILER_FTEQCC) {
1642 ftepp_add_define(NULL, "__STD_FTEQCC__");
1651 } else if (opts.standard == COMPILER_GMQCC) {
1652 ftepp_add_define(NULL, "__STD_GMQCC__");
1653 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1654 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1655 } else if (opts.standard == COMPILER_QCC) {
1656 ftepp_add_define(NULL, "__STD_QCC__");
1667 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1668 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1673 void ftepp_add_define(const char *source, const char *name)
1676 lex_ctx ctx = { "__builtin__", 0 };
1678 macro = ppmacro_new(ctx, name);
1679 vec_push(ftepp->macros, macro);
1682 const char *ftepp_get()
1684 return ftepp->output_string;
1689 ftepp_flush_do(ftepp);
1696 ftepp_delete(ftepp);