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, bool resetline)
639 char *old_string = ftepp->output_string;
640 lex_file *old_lexer = ftepp->lex;
641 size_t vararg_start = vec_size(macro->params);
651 if (vararg_start < vec_size(params))
652 varargs = vec_size(params) - vararg_start;
657 if (!vec_size(macro->output))
660 ftepp->output_string = NULL;
661 for (o = 0; o < vec_size(macro->output); ++o) {
662 pptoken *out = macro->output[o];
663 switch (out->token) {
665 if (!macro->variadic) {
666 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
672 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
673 for (++pi; pi < varargs; ++pi) {
674 ftepp_out(ftepp, ", ", false);
675 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
681 if (!macro_params_find(macro, out->value, &pi)) {
682 ftepp_out(ftepp, out->value, false);
685 ftepp_param_out(ftepp, ¶ms[pi]);
688 if (o + 1 < vec_size(macro->output)) {
689 nextok = macro->output[o+1]->token;
691 /* raw concatenation */
695 if ( (nextok == TOKEN_IDENT ||
696 nextok == TOKEN_KEYWORD ||
697 nextok == TOKEN_TYPENAME) &&
698 macro_params_find(macro, macro->output[o+1]->value, &pi))
701 ftepp_stringify(ftepp, ¶ms[pi]);
705 ftepp_out(ftepp, "#", false);
708 ftepp_out(ftepp, "\n", false);
711 ftepp_out(ftepp, out->value, false);
715 vec_push(ftepp->output_string, 0);
716 has_newlines = (strchr(ftepp->output_string, '\n') != NULL);
717 /* Now run the preprocessor recursively on this string buffer */
719 printf("__________\n%s\n=========\n", ftepp->output_string);
721 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
723 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
727 ftepp->output_string = old_string;
728 inlex->line = ftepp->lex->line;
729 inlex->sline = ftepp->lex->sline;
732 ftepp_recursion_header(ftepp);
733 if (!ftepp_preprocess(ftepp)) {
734 vec_free(ftepp->lex->open_string);
735 old_string = ftepp->output_string;
736 lex_close(ftepp->lex);
740 vec_free(ftepp->lex->open_string);
742 ftepp_recursion_footer(ftepp);
745 sprintf(lineno, "\n#pragma line(%lu)\n", old_lexer->sline);
746 ftepp_out(ftepp, lineno, false);
748 old_string = ftepp->output_string;
751 ftepp->lex = old_lexer;
752 ftepp->output_string = old_string;
756 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
759 macroparam *params = NULL;
763 if (!macro->has_params) {
764 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
771 if (!ftepp_skipallwhite(ftepp))
774 if (ftepp->token != '(') {
775 ftepp_error(ftepp, "expected macro parameters in parenthesis");
780 paramline = ftepp->lex->sline;
781 if (!ftepp_macro_call_params(ftepp, ¶ms))
784 if ( vec_size(params) < vec_size(macro->params) ||
785 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
787 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
788 (macro->variadic ? " at least" : ""),
789 (unsigned int)vec_size(macro->params),
790 (unsigned int)vec_size(params));
795 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
800 for (o = 0; o < vec_size(params); ++o)
801 macroparam_clean(¶ms[o]);
807 * #if - the FTEQCC way:
808 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
809 * <numbers> => True if the number is not 0
810 * !<factor> => True if the factor yields false
811 * !!<factor> => ERROR on 2 or more unary nots
812 * <macro> => becomes the macro's FIRST token regardless of parameters
813 * <e> && <e> => True if both expressions are true
814 * <e> || <e> => True if either expression is true
816 * <ident> => False (remember for macros the <macro> rule applies instead)
817 * Unary + and - are weird and wrong in fteqcc so we don't allow them
818 * parenthesis in expressions are allowed
819 * parameter lists on macros are errors
820 * No mathematical calculations are executed
822 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
823 static bool ftepp_if_op(ftepp_t *ftepp)
825 ftepp->lex->flags.noops = false;
827 if (!ftepp_skipspace(ftepp))
829 ftepp->lex->flags.noops = true;
832 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
838 if (!ftepp_skipspace(ftepp))
841 while (ftepp->token == '!') {
844 if (!ftepp_skipspace(ftepp))
848 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
852 if (!ftepp_skipspace(ftepp))
856 switch (ftepp->token) {
860 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
862 if (!ftepp_skipspace(ftepp))
864 if (ftepp->token != '(') {
865 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
869 if (!ftepp_skipspace(ftepp))
871 if (ftepp->token != TOKEN_IDENT &&
872 ftepp->token != TOKEN_TYPENAME &&
873 ftepp->token != TOKEN_KEYWORD)
875 ftepp_error(ftepp, "defined() used on an unexpected token type");
878 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
881 if (!ftepp_skipspace(ftepp))
883 if (ftepp->token != ')') {
884 ftepp_error(ftepp, "expected closing paren");
890 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
891 if (!macro || !vec_size(macro->output)) {
895 /* This does not expand recursively! */
896 switch (macro->output[0]->token) {
898 *value_out = macro->output[0]->constval.i;
899 *out = !!(macro->output[0]->constval.i);
901 case TOKEN_FLOATCONST:
902 *value_out = macro->output[0]->constval.f;
903 *out = !!(macro->output[0]->constval.f);
911 case TOKEN_STRINGCONST:
916 *value_out = ftepp->lex->tok.constval.i;
917 *out = !!(ftepp->lex->tok.constval.i);
919 case TOKEN_FLOATCONST:
920 *value_out = ftepp->lex->tok.constval.f;
921 *out = !!(ftepp->lex->tok.constval.f);
926 if (!ftepp_if_expr(ftepp, out, value_out))
928 if (ftepp->token != ')') {
929 ftepp_error(ftepp, "expected closing paren in #if expression");
935 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
937 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
941 *value_out = -*value_out;
944 *value_out = (*out ? 1 : 0);
950 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
952 if (!ftepp_next(ftepp))
954 return ftepp_if_value(ftepp, out, value_out);
958 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
960 if (!ftepp_if_value(ftepp, out, value_out))
963 if (!ftepp_if_op(ftepp))
966 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
969 /* FTEQCC is all right-associative and no precedence here */
970 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
971 !strcmp(ftepp_tokval(ftepp), "||"))
974 char opc = ftepp_tokval(ftepp)[0];
978 if (!ftepp_next(ftepp))
980 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
988 *value_out = (*out ? 1 : 0);
991 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
992 !strcmp(ftepp_tokval(ftepp), "!=") ||
993 !strcmp(ftepp_tokval(ftepp), ">=") ||
994 !strcmp(ftepp_tokval(ftepp), "<=") ||
995 !strcmp(ftepp_tokval(ftepp), ">") ||
996 !strcmp(ftepp_tokval(ftepp), "<"))
999 const char opc0 = ftepp_tokval(ftepp)[0];
1000 const char opc1 = ftepp_tokval(ftepp)[1];
1003 if (!ftepp_next(ftepp))
1005 if (!ftepp_if_expr(ftepp, &next, &other))
1009 *out = (*value_out == other);
1010 else if (opc0 == '!')
1011 *out = (*value_out != other);
1012 else if (opc0 == '>') {
1013 if (opc1 == '=') *out = (*value_out >= other);
1014 else *out = (*value_out > other);
1016 else if (opc0 == '<') {
1017 if (opc1 == '=') *out = (*value_out <= other);
1018 else *out = (*value_out < other);
1020 *value_out = (*out ? 1 : 0);
1025 ftepp_error(ftepp, "junk after #if");
1030 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1032 bool result = false;
1035 memset(cond, 0, sizeof(*cond));
1036 (void)ftepp_next(ftepp);
1038 if (!ftepp_skipspace(ftepp))
1040 if (ftepp->token == TOKEN_EOL) {
1041 ftepp_error(ftepp, "expected expression for #if-directive");
1045 if (!ftepp_if_expr(ftepp, &result, &dummy))
1053 * ifdef is rather simple
1055 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1058 memset(cond, 0, sizeof(*cond));
1059 (void)ftepp_next(ftepp);
1060 if (!ftepp_skipspace(ftepp))
1063 switch (ftepp->token) {
1065 case TOKEN_TYPENAME:
1067 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1070 ftepp_error(ftepp, "expected macro name");
1074 (void)ftepp_next(ftepp);
1075 if (!ftepp_skipspace(ftepp))
1077 /* relaxing this condition
1078 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1079 ftepp_error(ftepp, "stray tokens after #ifdef");
1088 * undef is also simple
1090 static bool ftepp_undef(ftepp_t *ftepp)
1092 (void)ftepp_next(ftepp);
1093 if (!ftepp_skipspace(ftepp))
1096 if (ftepp->output_on) {
1097 switch (ftepp->token) {
1099 case TOKEN_TYPENAME:
1101 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1104 ftepp_error(ftepp, "expected macro name");
1109 (void)ftepp_next(ftepp);
1110 if (!ftepp_skipspace(ftepp))
1112 /* relaxing this condition
1113 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1114 ftepp_error(ftepp, "stray tokens after #ifdef");
1121 /* Special unescape-string function which skips a leading quote
1122 * and stops at a quote, not just at \0
1124 static void unescape(const char *str, char *out) {
1126 while (*str && *str != '"') {
1130 case '\\': *out++ = *str; break;
1131 case '"': *out++ = *str; break;
1132 case 'a': *out++ = '\a'; break;
1133 case 'b': *out++ = '\b'; break;
1134 case 'r': *out++ = '\r'; break;
1135 case 'n': *out++ = '\n'; break;
1136 case 't': *out++ = '\t'; break;
1137 case 'f': *out++ = '\f'; break;
1138 case 'v': *out++ = '\v'; break;
1153 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1156 char *filename = NULL;
1157 const char *last_slash;
1163 last_slash = strrchr(pathfile, '/');
1166 len = last_slash - pathfile;
1167 memcpy(vec_add(filename, len), pathfile, len);
1168 vec_push(filename, '/');
1172 memcpy(vec_add(filename, len+1), file, len);
1173 vec_last(filename) = 0;
1175 fp = file_open(filename, "rb");
1184 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1186 char *filename = NULL;
1188 filename = ftepp_include_find_path(file, ftepp->includename);
1190 filename = ftepp_include_find_path(file, ftepp->itemname);
1194 static bool ftepp_directive_warning(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) {
1203 vec_upload(message, "#warning", 8);
1205 while (ftepp->token != TOKEN_EOL) {
1206 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1209 vec_push(message, '\0');
1210 store = ftepp_warn(ftepp, WARN_CPP, message);
1215 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1216 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1219 static void ftepp_directive_error(ftepp_t *ftepp) {
1220 char *message = NULL;
1222 if (!ftepp_skipspace(ftepp))
1225 /* handle the odd non string constant case so it works like C */
1226 if (ftepp->token != TOKEN_STRINGCONST) {
1227 vec_upload(message, "#error", 6);
1229 while (ftepp->token != TOKEN_EOL) {
1230 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1233 vec_push(message, '\0');
1234 ftepp_error(ftepp, message);
1239 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1240 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1245 * FIXME: do we need/want a -I option?
1246 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1248 static bool ftepp_include(ftepp_t *ftepp)
1250 lex_file *old_lexer = ftepp->lex;
1255 char *old_includename;
1257 (void)ftepp_next(ftepp);
1258 if (!ftepp_skipspace(ftepp))
1261 if (ftepp->token != TOKEN_STRINGCONST) {
1262 ftepp_error(ftepp, "expected filename to include");
1266 ctx = ftepp_ctx(ftepp);
1268 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1270 ftepp_out(ftepp, "\n#pragma file(", false);
1271 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1272 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1274 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1276 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1279 inlex = lex_open(filename);
1281 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1286 old_includename = ftepp->includename;
1287 ftepp->includename = filename;
1288 if (!ftepp_preprocess(ftepp)) {
1289 vec_free(ftepp->includename);
1290 ftepp->includename = old_includename;
1291 lex_close(ftepp->lex);
1292 ftepp->lex = old_lexer;
1295 vec_free(ftepp->includename);
1296 ftepp->includename = old_includename;
1297 lex_close(ftepp->lex);
1298 ftepp->lex = old_lexer;
1300 ftepp_out(ftepp, "\n#pragma file(", false);
1301 ftepp_out(ftepp, ctx.file, false);
1302 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1303 ftepp_out(ftepp, lineno, false);
1306 (void)ftepp_next(ftepp);
1307 if (!ftepp_skipspace(ftepp))
1309 if (ftepp->token != TOKEN_EOL) {
1310 ftepp_error(ftepp, "stray tokens after #include");
1313 (void)ftepp_next(ftepp);
1318 /* Basic structure handlers */
1319 static bool ftepp_else_allowed(ftepp_t *ftepp)
1321 if (!vec_size(ftepp->conditions)) {
1322 ftepp_error(ftepp, "#else without #if");
1325 if (vec_last(ftepp->conditions).had_else) {
1326 ftepp_error(ftepp, "multiple #else for a single #if");
1332 static bool ftepp_hash(ftepp_t *ftepp)
1337 lex_ctx ctx = ftepp_ctx(ftepp);
1339 if (!ftepp_skipspace(ftepp))
1342 switch (ftepp->token) {
1345 case TOKEN_TYPENAME:
1346 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1347 return ftepp_define(ftepp);
1349 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1350 return ftepp_undef(ftepp);
1352 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1353 if (!ftepp_ifdef(ftepp, &cond))
1355 cond.was_on = cond.on;
1356 vec_push(ftepp->conditions, cond);
1357 ftepp->output_on = ftepp->output_on && cond.on;
1360 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1361 if (!ftepp_ifdef(ftepp, &cond))
1364 cond.was_on = cond.on;
1365 vec_push(ftepp->conditions, cond);
1366 ftepp->output_on = ftepp->output_on && cond.on;
1369 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1370 if (!ftepp_else_allowed(ftepp))
1372 if (!ftepp_ifdef(ftepp, &cond))
1374 pc = &vec_last(ftepp->conditions);
1375 pc->on = !pc->was_on && cond.on;
1376 pc->was_on = pc->was_on || pc->on;
1377 ftepp_update_output_condition(ftepp);
1380 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1381 if (!ftepp_else_allowed(ftepp))
1383 if (!ftepp_ifdef(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), "elif")) {
1393 if (!ftepp_else_allowed(ftepp))
1395 if (!ftepp_if(ftepp, &cond))
1397 pc = &vec_last(ftepp->conditions);
1398 pc->on = !pc->was_on && cond.on;
1399 pc->was_on = pc->was_on || pc->on;
1400 ftepp_update_output_condition(ftepp);
1403 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1404 if (!ftepp_if(ftepp, &cond))
1406 cond.was_on = cond.on;
1407 vec_push(ftepp->conditions, cond);
1408 ftepp->output_on = ftepp->output_on && cond.on;
1411 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1412 if (!ftepp_else_allowed(ftepp))
1414 pc = &vec_last(ftepp->conditions);
1415 pc->on = !pc->was_on;
1416 pc->had_else = true;
1418 ftepp_update_output_condition(ftepp);
1421 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1422 if (!vec_size(ftepp->conditions)) {
1423 ftepp_error(ftepp, "#endif without #if");
1426 vec_pop(ftepp->conditions);
1428 ftepp_update_output_condition(ftepp);
1431 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1432 return ftepp_include(ftepp);
1434 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1435 ftepp_out(ftepp, "#", false);
1438 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1439 ftepp_directive_warning(ftepp);
1442 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1443 ftepp_directive_error(ftepp);
1447 if (ftepp->output_on) {
1448 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1455 /* break; never reached */
1457 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1460 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1463 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1466 /* Builtins! Don't forget the builtins! */
1467 case TOKEN_INTCONST:
1468 case TOKEN_FLOATCONST:
1469 ftepp_out(ftepp, "#", false);
1472 if (!ftepp_skipspace(ftepp))
1477 static bool ftepp_preprocess(ftepp_t *ftepp)
1480 bool newline = true;
1483 char *expand = NULL;
1486 ftepp->lex->flags.preprocessing = true;
1487 ftepp->lex->flags.mergelines = false;
1488 ftepp->lex->flags.noops = true;
1493 if (ftepp->token >= TOKEN_EOF)
1499 switch (ftepp->token) {
1502 case TOKEN_TYPENAME:
1503 /* is it a predef? */
1504 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1505 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1506 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1507 expand = ftepp_predefs[i].func(ftepp->lex);
1508 ftepp_out(ftepp, expand, false);
1509 ftepp_next(ftepp); /* skip */
1511 mem_d(expand); /* free memory */
1517 if (ftepp->output_on)
1518 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1523 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1527 if (!ftepp_macro_call(ftepp, macro))
1528 ftepp->token = TOKEN_ERROR;
1532 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1536 ftepp->lex->flags.mergelines = true;
1537 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1538 ftepp_error(ftepp, "error in preprocessor directive");
1539 ftepp->token = TOKEN_ERROR;
1542 if (!ftepp_hash(ftepp))
1543 ftepp->token = TOKEN_ERROR;
1544 ftepp->lex->flags.mergelines = false;
1548 ftepp_out(ftepp, "\n", true);
1552 /* same as default but don't set newline=false */
1553 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1558 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1562 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1564 /* force a 0 at the end but don't count it as added to the output */
1565 vec_push(ftepp->output_string, 0);
1566 vec_shrinkby(ftepp->output_string, 1);
1568 return (ftepp->token == TOKEN_EOF);
1571 /* Like in parser.c - files keep the previous state so we have one global
1572 * preprocessor. Except here we will want to warn about dangling #ifs.
1574 static ftepp_t *ftepp;
1576 static bool ftepp_preprocess_done()
1579 if (vec_size(ftepp->conditions)) {
1580 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1583 lex_close(ftepp->lex);
1585 if (ftepp->itemname) {
1586 mem_d(ftepp->itemname);
1587 ftepp->itemname = NULL;
1592 bool ftepp_preprocess_file(const char *filename)
1594 ftepp->lex = lex_open(filename);
1595 ftepp->itemname = util_strdup(filename);
1597 con_out("failed to open file \"%s\"\n", filename);
1600 if (!ftepp_preprocess(ftepp))
1602 return ftepp_preprocess_done();
1605 bool ftepp_preprocess_string(const char *name, const char *str)
1607 ftepp->lex = lex_open_string(str, strlen(str), name);
1608 ftepp->itemname = util_strdup(name);
1610 con_out("failed to create lexer for string \"%s\"\n", name);
1613 if (!ftepp_preprocess(ftepp))
1615 return ftepp_preprocess_done();
1619 void ftepp_add_macro(const char *name, const char *value) {
1620 char *create = NULL;
1622 /* use saner path for empty macros */
1624 ftepp_add_define("__builtin__", name);
1628 vec_upload(create, "#define ", 8);
1629 vec_upload(create, name, strlen(name));
1630 vec_push (create, ' ');
1631 vec_upload(create, value, strlen(value));
1632 vec_push (create, 0);
1634 ftepp_preprocess_string("__builtin__", create);
1643 ftepp = ftepp_new();
1647 memset(minor, 0, sizeof(minor));
1648 memset(major, 0, sizeof(major));
1650 /* set the right macro based on the selected standard */
1651 ftepp_add_define(NULL, "GMQCC");
1652 if (opts.standard == COMPILER_FTEQCC) {
1653 ftepp_add_define(NULL, "__STD_FTEQCC__");
1662 } else if (opts.standard == COMPILER_GMQCC) {
1663 ftepp_add_define(NULL, "__STD_GMQCC__");
1664 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1665 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1666 } else if (opts.standard == COMPILER_QCCX) {
1667 ftepp_add_define(NULL, "__STD_QCCX__");
1668 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1669 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1670 } else if (opts.standard == COMPILER_QCC) {
1671 ftepp_add_define(NULL, "__STD_QCC__");
1682 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1683 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1688 void ftepp_add_define(const char *source, const char *name)
1691 lex_ctx ctx = { "__builtin__", 0 };
1693 macro = ppmacro_new(ctx, name);
1694 vec_push(ftepp->macros, macro);
1697 const char *ftepp_get()
1699 return ftepp->output_string;
1704 ftepp_flush_do(ftepp);
1711 ftepp_delete(ftepp);