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;
75 * Implement the predef subsystem now. We can do this safely with the
76 * help of lexer contexts.
78 static uint32_t ftepp_predef_countval = 0;
79 static uint32_t ftepp_predef_randval = 0;
82 char *ftepp_predef_date(lex_file *context) {
85 char *value = (char*)mem_a(82);
86 /* 82 is enough for strftime but we also have " " in our string */
92 itime = localtime(&rtime);
94 strftime(value, 82, "\"%b %d %Y\"", itime);
100 char *ftepp_predef_time(lex_file *context) {
103 char *value = (char*)mem_a(82);
104 /* 82 is enough for strftime but we also have " " in our string */
110 itime = localtime(&rtime);
112 strftime(value, 82, "\"%X\"", itime);
118 char *ftepp_predef_line(lex_file *context) {
120 util_asprintf(&value, "%d", (int)context->line);
124 char *ftepp_predef_file(lex_file *context) {
125 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
126 char *value = (char*)mem_a(length);
127 memset (value, 0, length);
128 sprintf(value, "\"%s\"", context->name);
132 /* __COUNTER_LAST__ */
133 char *ftepp_predef_counterlast(lex_file *context) {
135 util_asprintf(&value, "%u", ftepp_predef_countval);
141 char *ftepp_predef_counter(lex_file *context) {
143 ftepp_predef_countval ++;
144 util_asprintf(&value, "%u", ftepp_predef_countval);
150 char *ftepp_predef_random(lex_file *context) {
152 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
153 util_asprintf(&value, "%u", ftepp_predef_randval);
158 /* __RANDOM_LAST__ */
159 char *ftepp_predef_randomlast(lex_file *context) {
161 util_asprintf(&value, "%u", ftepp_predef_randval);
167 const ftepp_predef_t ftepp_predefs[FTEPP_PREDEF_COUNT] = {
168 { "__LINE__", &ftepp_predef_line },
169 { "__FILE__", &ftepp_predef_file },
170 { "__COUNTER__", &ftepp_predef_counter },
171 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
172 { "__RANDOM__", &ftepp_predef_random },
173 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
174 { "__DATE__", &ftepp_predef_date },
175 { "__TIME__", &ftepp_predef_time }
178 #define ftepp_tokval(f) ((f)->lex->tok.value)
179 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
181 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
188 con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
192 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
199 con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
203 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
209 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
214 static pptoken *pptoken_make(ftepp_t *ftepp)
216 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
217 token->token = ftepp->token;
219 if (token->token == TOKEN_WHITE)
220 token->value = util_strdup(" ");
223 token->value = util_strdup(ftepp_tokval(ftepp));
225 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
229 static void pptoken_delete(pptoken *self)
235 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
237 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
240 memset(macro, 0, sizeof(*macro));
241 macro->name = util_strdup(name);
245 static void ppmacro_delete(ppmacro *self)
248 for (i = 0; i < vec_size(self->params); ++i)
249 mem_d(self->params[i]);
250 vec_free(self->params);
251 for (i = 0; i < vec_size(self->output); ++i)
252 pptoken_delete(self->output[i]);
253 vec_free(self->output);
258 static ftepp_t* ftepp_new()
262 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
263 memset(ftepp, 0, sizeof(*ftepp));
265 ftepp->output_on = true;
270 static void ftepp_flush_do(ftepp_t *self)
272 vec_free(self->output_string);
275 static void ftepp_delete(ftepp_t *self)
278 ftepp_flush_do(self);
280 mem_d(self->itemname);
281 if (self->includename)
282 vec_free(self->includename);
283 for (i = 0; i < vec_size(self->macros); ++i)
284 ppmacro_delete(self->macros[i]);
285 vec_free(self->macros);
286 vec_free(self->conditions);
288 lex_close(self->lex);
292 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
294 if (ignore_cond || ftepp->output_on)
299 data = vec_add(ftepp->output_string, len);
300 memcpy(data, str, len);
304 static void ftepp_update_output_condition(ftepp_t *ftepp)
307 ftepp->output_on = true;
308 for (i = 0; i < vec_size(ftepp->conditions); ++i)
309 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
312 static ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
315 for (i = 0; i < vec_size(ftepp->macros); ++i) {
316 if (!strcmp(name, ftepp->macros[i]->name))
317 return ftepp->macros[i];
322 static void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
325 for (i = 0; i < vec_size(ftepp->macros); ++i) {
326 if (!strcmp(name, ftepp->macros[i]->name)) {
327 vec_remove(ftepp->macros, i, 1);
333 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
335 return (ftepp->token = lex_do(ftepp->lex));
338 /* Important: this does not skip newlines! */
339 static bool ftepp_skipspace(ftepp_t *ftepp)
341 if (ftepp->token != TOKEN_WHITE)
343 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
344 if (ftepp->token >= TOKEN_EOF) {
345 ftepp_error(ftepp, "unexpected end of preprocessor directive");
351 /* this one skips EOLs as well */
352 static bool ftepp_skipallwhite(ftepp_t *ftepp)
354 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
358 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
359 if (ftepp->token >= TOKEN_EOF) {
360 ftepp_error(ftepp, "unexpected end of preprocessor directive");
367 * The huge macro parsing code...
369 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
373 if (!ftepp_skipspace(ftepp))
375 if (ftepp->token == ')')
377 switch (ftepp->token) {
381 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
384 macro->variadic = true;
387 ftepp_error(ftepp, "unexpected token in parameter list");
391 if (!ftepp_skipspace(ftepp))
393 if (macro->variadic && ftepp->token != ')') {
394 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
397 } while (ftepp->token == ',');
398 if (ftepp->token != ')') {
399 ftepp_error(ftepp, "expected closing paren after macro parameter list");
403 /* skipspace happens in ftepp_define */
407 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
410 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
411 bool subscript = false;
413 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
414 subscript = !!(ftepp_next(ftepp) == '#');
416 if (subscript && ftepp_next(ftepp) != '#') {
417 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
419 } else if (subscript) {
420 if (ftepp_next(ftepp) == '[') {
421 if (ftepp_next(ftepp) != TOKEN_INTCONST) {
422 ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
426 index = atoi(ftepp_tokval(ftepp));
428 if (ftepp_next(ftepp) != ']') {
429 ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
434 * mark it as an array to be handled later as such and not
435 * as traditional __VA_ARGS__
437 ftepp->token = TOKEN_VA_ARGS_ARRAY;
438 ptok = pptoken_make(ftepp);
439 ptok->constval.i = index;
440 vec_push(macro->output, ptok);
443 ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
447 int old = ftepp->token;
448 ftepp->token = TOKEN_VA_ARGS;
449 ptok = pptoken_make(ftepp);
450 vec_push(macro->output, ptok);
456 ptok = pptoken_make(ftepp);
457 vec_push(macro->output, ptok);
461 /* recursive expansion can cause EOFs here */
462 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
463 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
469 static bool ftepp_define(ftepp_t *ftepp)
472 size_t l = ftepp_ctx(ftepp).line;
474 (void)ftepp_next(ftepp);
475 if (!ftepp_skipspace(ftepp))
478 switch (ftepp->token) {
482 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
483 if (macro && ftepp->output_on) {
484 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
486 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
488 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
491 ftepp_error(ftepp, "expected macro name");
495 (void)ftepp_next(ftepp);
497 if (ftepp->token == '(') {
498 macro->has_params = true;
499 if (!ftepp_define_params(ftepp, macro))
503 if (!ftepp_skipspace(ftepp))
506 if (!ftepp_define_body(ftepp, macro))
509 if (ftepp->output_on)
510 vec_push(ftepp->macros, macro);
512 ppmacro_delete(macro);
515 for (; l < ftepp_ctx(ftepp).line; ++l)
516 ftepp_out(ftepp, "\n", true);
521 * When a macro is used we have to handle parameters as well
522 * as special-concatenation via ## or stringification via #
524 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
525 * this kind of parens. Curly braces or [] don't count towards the
532 static void macroparam_clean(macroparam *self)
535 for (i = 0; i < vec_size(self->tokens); ++i)
536 pptoken_delete(self->tokens[i]);
537 vec_free(self->tokens);
540 /* need to leave the last token up */
541 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
543 macroparam *params = NULL;
549 if (!ftepp_skipallwhite(ftepp))
551 while (ftepp->token != ')') {
553 if (!ftepp_skipallwhite(ftepp))
555 while (parens || ftepp->token != ',') {
556 if (ftepp->token == '(')
558 else if (ftepp->token == ')') {
563 ptok = pptoken_make(ftepp);
564 vec_push(mp.tokens, ptok);
565 if (ftepp_next(ftepp) >= TOKEN_EOF) {
566 ftepp_error(ftepp, "unexpected EOF in macro call");
570 vec_push(params, mp);
572 if (ftepp->token == ')')
574 if (ftepp->token != ',') {
575 ftepp_error(ftepp, "expected closing paren or comma in macro call");
578 if (ftepp_next(ftepp) >= TOKEN_EOF) {
579 ftepp_error(ftepp, "unexpected EOF in macro call");
583 /* need to leave that up
584 if (ftepp_next(ftepp) >= TOKEN_EOF) {
585 ftepp_error(ftepp, "unexpected EOF in macro call");
589 *out_params = params;
594 macroparam_clean(&mp);
595 for (i = 0; i < vec_size(params); ++i)
596 macroparam_clean(¶ms[i]);
601 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
604 for (i = 0; i < vec_size(macro->params); ++i) {
605 if (!strcmp(macro->params[i], name)) {
613 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
618 switch (token->token) {
619 case TOKEN_STRINGCONST:
622 /* in preprocessor mode strings already are string,
623 * so we don't get actual newline bytes here.
624 * Still need to escape backslashes and quotes.
627 case '\\': ftepp_out(ftepp, "\\\\", false); break;
628 case '"': ftepp_out(ftepp, "\\\"", false); break;
631 ftepp_out(ftepp, chs, false);
638 ftepp_out(ftepp, " ", false);
641 ftepp_out(ftepp, "\\n", false);
644 ftepp_out(ftepp, token->value, false);
649 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
652 ftepp_out(ftepp, "\"", false);
653 for (i = 0; i < vec_size(param->tokens); ++i)
654 ftepp_stringify_token(ftepp, param->tokens[i]);
655 ftepp_out(ftepp, "\"", false);
658 static void ftepp_recursion_header(ftepp_t *ftepp)
660 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
663 static void ftepp_recursion_footer(ftepp_t *ftepp)
665 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
668 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
672 for (i = 0; i < vec_size(param->tokens); ++i) {
673 out = param->tokens[i];
674 if (out->token == TOKEN_EOL)
675 ftepp_out(ftepp, "\n", false);
677 ftepp_out(ftepp, out->value, false);
681 static bool ftepp_preprocess(ftepp_t *ftepp);
682 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
684 char *old_string = ftepp->output_string;
686 lex_file *old_lexer = ftepp->lex;
687 size_t vararg_start = vec_size(macro->params);
699 if (vararg_start < vec_size(params))
700 varargs = vec_size(params) - vararg_start;
705 if (!vec_size(macro->output))
708 ftepp->output_string = NULL;
709 for (o = 0; o < vec_size(macro->output); ++o) {
710 pptoken *out = macro->output[o];
711 switch (out->token) {
713 if (!macro->variadic) {
714 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
715 vec_free(old_string);
722 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
723 for (++pi; pi < varargs; ++pi) {
724 ftepp_out(ftepp, ", ", false);
725 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
729 case TOKEN_VA_ARGS_ARRAY:
730 if ((size_t)out->constval.i >= varargs) {
731 ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
732 vec_free(old_string);
736 ftepp_param_out(ftepp, ¶ms[out->constval.i + vararg_start]);
742 if (!macro_params_find(macro, out->value, &pi)) {
743 ftepp_out(ftepp, out->value, false);
746 ftepp_param_out(ftepp, ¶ms[pi]);
749 if (o + 1 < vec_size(macro->output)) {
750 nextok = macro->output[o+1]->token;
752 /* raw concatenation */
756 if ( (nextok == TOKEN_IDENT ||
757 nextok == TOKEN_KEYWORD ||
758 nextok == TOKEN_TYPENAME) &&
759 macro_params_find(macro, macro->output[o+1]->value, &pi))
762 ftepp_stringify(ftepp, ¶ms[pi]);
766 ftepp_out(ftepp, "#", false);
769 ftepp_out(ftepp, "\n", false);
772 ftepp_out(ftepp, out->value, false);
776 vec_push(ftepp->output_string, 0);
777 /* Now run the preprocessor recursively on this string buffer */
779 printf("__________\n%s\n=========\n", ftepp->output_string);
781 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
783 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
788 inlex->line = ftepp->lex->line;
789 inlex->sline = ftepp->lex->sline;
792 old_inmacro = ftepp->in_macro;
793 ftepp->in_macro = true;
794 ftepp->output_string = NULL;
795 if (!ftepp_preprocess(ftepp)) {
796 ftepp->in_macro = old_inmacro;
797 vec_free(ftepp->lex->open_string);
798 vec_free(ftepp->output_string);
799 lex_close(ftepp->lex);
803 ftepp->in_macro = old_inmacro;
804 vec_free(ftepp->lex->open_string);
805 lex_close(ftepp->lex);
807 inner_string = ftepp->output_string;
808 ftepp->output_string = old_string;
810 has_newlines = (strchr(inner_string, '\n') != NULL);
812 if (has_newlines && !old_inmacro)
813 ftepp_recursion_header(ftepp);
815 vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
816 vec_free(inner_string);
818 if (has_newlines && !old_inmacro)
819 ftepp_recursion_footer(ftepp);
821 if (resetline && !ftepp->in_macro) {
823 sprintf(lineno, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
824 ftepp_out(ftepp, lineno, false);
827 old_string = ftepp->output_string;
829 ftepp->lex = old_lexer;
830 ftepp->output_string = old_string;
834 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
837 macroparam *params = NULL;
841 if (!macro->has_params) {
842 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
849 if (!ftepp_skipallwhite(ftepp))
852 if (ftepp->token != '(') {
853 ftepp_error(ftepp, "expected macro parameters in parenthesis");
858 paramline = ftepp->lex->sline;
859 if (!ftepp_macro_call_params(ftepp, ¶ms))
862 if ( vec_size(params) < vec_size(macro->params) ||
863 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
865 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
866 (macro->variadic ? " at least" : ""),
867 (unsigned int)vec_size(macro->params),
868 (unsigned int)vec_size(params));
873 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
878 for (o = 0; o < vec_size(params); ++o)
879 macroparam_clean(¶ms[o]);
885 * #if - the FTEQCC way:
886 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
887 * <numbers> => True if the number is not 0
888 * !<factor> => True if the factor yields false
889 * !!<factor> => ERROR on 2 or more unary nots
890 * <macro> => becomes the macro's FIRST token regardless of parameters
891 * <e> && <e> => True if both expressions are true
892 * <e> || <e> => True if either expression is true
894 * <ident> => False (remember for macros the <macro> rule applies instead)
895 * Unary + and - are weird and wrong in fteqcc so we don't allow them
896 * parenthesis in expressions are allowed
897 * parameter lists on macros are errors
898 * No mathematical calculations are executed
900 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
901 static bool ftepp_if_op(ftepp_t *ftepp)
903 ftepp->lex->flags.noops = false;
905 if (!ftepp_skipspace(ftepp))
907 ftepp->lex->flags.noops = true;
910 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
916 if (!ftepp_skipspace(ftepp))
919 while (ftepp->token == '!') {
922 if (!ftepp_skipspace(ftepp))
926 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
930 if (!ftepp_skipspace(ftepp))
934 switch (ftepp->token) {
938 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
940 if (!ftepp_skipspace(ftepp))
942 if (ftepp->token != '(') {
943 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
947 if (!ftepp_skipspace(ftepp))
949 if (ftepp->token != TOKEN_IDENT &&
950 ftepp->token != TOKEN_TYPENAME &&
951 ftepp->token != TOKEN_KEYWORD)
953 ftepp_error(ftepp, "defined() used on an unexpected token type");
956 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
959 if (!ftepp_skipspace(ftepp))
961 if (ftepp->token != ')') {
962 ftepp_error(ftepp, "expected closing paren");
968 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
969 if (!macro || !vec_size(macro->output)) {
973 /* This does not expand recursively! */
974 switch (macro->output[0]->token) {
976 *value_out = macro->output[0]->constval.i;
977 *out = !!(macro->output[0]->constval.i);
979 case TOKEN_FLOATCONST:
980 *value_out = macro->output[0]->constval.f;
981 *out = !!(macro->output[0]->constval.f);
989 case TOKEN_STRINGCONST:
994 *value_out = ftepp->lex->tok.constval.i;
995 *out = !!(ftepp->lex->tok.constval.i);
997 case TOKEN_FLOATCONST:
998 *value_out = ftepp->lex->tok.constval.f;
999 *out = !!(ftepp->lex->tok.constval.f);
1004 if (!ftepp_if_expr(ftepp, out, value_out))
1006 if (ftepp->token != ')') {
1007 ftepp_error(ftepp, "expected closing paren in #if expression");
1013 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1014 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1015 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1019 *value_out = -*value_out;
1022 *value_out = (*out ? 1 : 0);
1028 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1030 if (!ftepp_next(ftepp))
1032 return ftepp_if_value(ftepp, out, value_out);
1036 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1038 if (!ftepp_if_value(ftepp, out, value_out))
1041 if (!ftepp_if_op(ftepp))
1044 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1047 /* FTEQCC is all right-associative and no precedence here */
1048 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1049 !strcmp(ftepp_tokval(ftepp), "||"))
1052 char opc = ftepp_tokval(ftepp)[0];
1056 if (!ftepp_next(ftepp))
1058 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1062 *out = *out && next;
1064 *out = *out || next;
1066 *value_out = (*out ? 1 : 0);
1069 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1070 !strcmp(ftepp_tokval(ftepp), "!=") ||
1071 !strcmp(ftepp_tokval(ftepp), ">=") ||
1072 !strcmp(ftepp_tokval(ftepp), "<=") ||
1073 !strcmp(ftepp_tokval(ftepp), ">") ||
1074 !strcmp(ftepp_tokval(ftepp), "<"))
1077 const char opc0 = ftepp_tokval(ftepp)[0];
1078 const char opc1 = ftepp_tokval(ftepp)[1];
1081 if (!ftepp_next(ftepp))
1083 if (!ftepp_if_expr(ftepp, &next, &other))
1087 *out = (*value_out == other);
1088 else if (opc0 == '!')
1089 *out = (*value_out != other);
1090 else if (opc0 == '>') {
1091 if (opc1 == '=') *out = (*value_out >= other);
1092 else *out = (*value_out > other);
1094 else if (opc0 == '<') {
1095 if (opc1 == '=') *out = (*value_out <= other);
1096 else *out = (*value_out < other);
1098 *value_out = (*out ? 1 : 0);
1103 ftepp_error(ftepp, "junk after #if");
1108 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1110 bool result = false;
1113 memset(cond, 0, sizeof(*cond));
1114 (void)ftepp_next(ftepp);
1116 if (!ftepp_skipspace(ftepp))
1118 if (ftepp->token == TOKEN_EOL) {
1119 ftepp_error(ftepp, "expected expression for #if-directive");
1123 if (!ftepp_if_expr(ftepp, &result, &dummy))
1131 * ifdef is rather simple
1133 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1136 memset(cond, 0, sizeof(*cond));
1137 (void)ftepp_next(ftepp);
1138 if (!ftepp_skipspace(ftepp))
1141 switch (ftepp->token) {
1143 case TOKEN_TYPENAME:
1145 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1148 ftepp_error(ftepp, "expected macro name");
1152 (void)ftepp_next(ftepp);
1153 if (!ftepp_skipspace(ftepp))
1155 /* relaxing this condition
1156 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1157 ftepp_error(ftepp, "stray tokens after #ifdef");
1166 * undef is also simple
1168 static bool ftepp_undef(ftepp_t *ftepp)
1170 (void)ftepp_next(ftepp);
1171 if (!ftepp_skipspace(ftepp))
1174 if (ftepp->output_on) {
1175 switch (ftepp->token) {
1177 case TOKEN_TYPENAME:
1179 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1182 ftepp_error(ftepp, "expected macro name");
1187 (void)ftepp_next(ftepp);
1188 if (!ftepp_skipspace(ftepp))
1190 /* relaxing this condition
1191 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1192 ftepp_error(ftepp, "stray tokens after #ifdef");
1199 /* Special unescape-string function which skips a leading quote
1200 * and stops at a quote, not just at \0
1202 static void unescape(const char *str, char *out) {
1204 while (*str && *str != '"') {
1208 case '\\': *out++ = *str; break;
1209 case '"': *out++ = *str; break;
1210 case 'a': *out++ = '\a'; break;
1211 case 'b': *out++ = '\b'; break;
1212 case 'r': *out++ = '\r'; break;
1213 case 'n': *out++ = '\n'; break;
1214 case 't': *out++ = '\t'; break;
1215 case 'f': *out++ = '\f'; break;
1216 case 'v': *out++ = '\v'; break;
1231 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1234 char *filename = NULL;
1235 const char *last_slash;
1241 last_slash = strrchr(pathfile, '/');
1244 len = last_slash - pathfile;
1245 memcpy(vec_add(filename, len), pathfile, len);
1246 vec_push(filename, '/');
1250 memcpy(vec_add(filename, len+1), file, len);
1251 vec_last(filename) = 0;
1253 fp = fs_file_open(filename, "rb");
1262 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1264 char *filename = NULL;
1266 filename = ftepp_include_find_path(file, ftepp->includename);
1268 filename = ftepp_include_find_path(file, ftepp->itemname);
1272 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1273 char *message = NULL;
1275 if (!ftepp_skipspace(ftepp))
1278 /* handle the odd non string constant case so it works like C */
1279 if (ftepp->token != TOKEN_STRINGCONST) {
1281 vec_upload(message, "#warning", 8);
1283 while (ftepp->token != TOKEN_EOL) {
1284 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1287 vec_push(message, '\0');
1288 if (ftepp->output_on)
1289 store = ftepp_warn(ftepp, WARN_CPP, message);
1296 if (!ftepp->output_on)
1299 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1300 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1303 static void ftepp_directive_error(ftepp_t *ftepp) {
1304 char *message = NULL;
1306 if (!ftepp_skipspace(ftepp))
1309 /* handle the odd non string constant case so it works like C */
1310 if (ftepp->token != TOKEN_STRINGCONST) {
1311 vec_upload(message, "#error", 6);
1313 while (ftepp->token != TOKEN_EOL) {
1314 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1317 vec_push(message, '\0');
1318 if (ftepp->output_on)
1319 ftepp_error(ftepp, message);
1324 if (!ftepp->output_on)
1327 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1328 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1331 static void ftepp_directive_message(ftepp_t *ftepp) {
1332 char *message = NULL;
1334 if (!ftepp_skipspace(ftepp))
1337 /* handle the odd non string constant case so it works like C */
1338 if (ftepp->token != TOKEN_STRINGCONST) {
1339 vec_upload(message, "#message", 8);
1341 while (ftepp->token != TOKEN_EOL) {
1342 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1345 vec_push(message, '\0');
1346 if (ftepp->output_on)
1347 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1352 if (!ftepp->output_on)
1355 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1356 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", ftepp_tokval(ftepp));
1361 * FIXME: do we need/want a -I option?
1362 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1364 static bool ftepp_include(ftepp_t *ftepp)
1366 lex_file *old_lexer = ftepp->lex;
1371 char *old_includename;
1373 (void)ftepp_next(ftepp);
1374 if (!ftepp_skipspace(ftepp))
1377 if (ftepp->token != TOKEN_STRINGCONST) {
1378 ftepp_error(ftepp, "expected filename to include");
1382 ctx = ftepp_ctx(ftepp);
1384 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1386 ftepp_out(ftepp, "\n#pragma file(", false);
1387 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1388 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1390 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1392 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1395 inlex = lex_open(filename);
1397 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1402 old_includename = ftepp->includename;
1403 ftepp->includename = filename;
1404 if (!ftepp_preprocess(ftepp)) {
1405 vec_free(ftepp->includename);
1406 ftepp->includename = old_includename;
1407 lex_close(ftepp->lex);
1408 ftepp->lex = old_lexer;
1411 vec_free(ftepp->includename);
1412 ftepp->includename = old_includename;
1413 lex_close(ftepp->lex);
1414 ftepp->lex = old_lexer;
1416 ftepp_out(ftepp, "\n#pragma file(", false);
1417 ftepp_out(ftepp, ctx.file, false);
1418 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1419 ftepp_out(ftepp, lineno, false);
1422 (void)ftepp_next(ftepp);
1423 if (!ftepp_skipspace(ftepp))
1425 if (ftepp->token != TOKEN_EOL) {
1426 ftepp_error(ftepp, "stray tokens after #include");
1429 (void)ftepp_next(ftepp);
1434 /* Basic structure handlers */
1435 static bool ftepp_else_allowed(ftepp_t *ftepp)
1437 if (!vec_size(ftepp->conditions)) {
1438 ftepp_error(ftepp, "#else without #if");
1441 if (vec_last(ftepp->conditions).had_else) {
1442 ftepp_error(ftepp, "multiple #else for a single #if");
1448 static bool ftepp_hash(ftepp_t *ftepp)
1453 lex_ctx ctx = ftepp_ctx(ftepp);
1455 if (!ftepp_skipspace(ftepp))
1458 switch (ftepp->token) {
1461 case TOKEN_TYPENAME:
1462 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1463 return ftepp_define(ftepp);
1465 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1466 return ftepp_undef(ftepp);
1468 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1469 if (!ftepp_ifdef(ftepp, &cond))
1471 cond.was_on = cond.on;
1472 vec_push(ftepp->conditions, cond);
1473 ftepp->output_on = ftepp->output_on && cond.on;
1476 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1477 if (!ftepp_ifdef(ftepp, &cond))
1480 cond.was_on = cond.on;
1481 vec_push(ftepp->conditions, cond);
1482 ftepp->output_on = ftepp->output_on && cond.on;
1485 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1486 if (!ftepp_else_allowed(ftepp))
1488 if (!ftepp_ifdef(ftepp, &cond))
1490 pc = &vec_last(ftepp->conditions);
1491 pc->on = !pc->was_on && cond.on;
1492 pc->was_on = pc->was_on || pc->on;
1493 ftepp_update_output_condition(ftepp);
1496 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1497 if (!ftepp_else_allowed(ftepp))
1499 if (!ftepp_ifdef(ftepp, &cond))
1502 pc = &vec_last(ftepp->conditions);
1503 pc->on = !pc->was_on && cond.on;
1504 pc->was_on = pc->was_on || pc->on;
1505 ftepp_update_output_condition(ftepp);
1508 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1509 if (!ftepp_else_allowed(ftepp))
1511 if (!ftepp_if(ftepp, &cond))
1513 pc = &vec_last(ftepp->conditions);
1514 pc->on = !pc->was_on && cond.on;
1515 pc->was_on = pc->was_on || pc->on;
1516 ftepp_update_output_condition(ftepp);
1519 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1520 if (!ftepp_if(ftepp, &cond))
1522 cond.was_on = cond.on;
1523 vec_push(ftepp->conditions, cond);
1524 ftepp->output_on = ftepp->output_on && cond.on;
1527 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1528 if (!ftepp_else_allowed(ftepp))
1530 pc = &vec_last(ftepp->conditions);
1531 pc->on = !pc->was_on;
1532 pc->had_else = true;
1534 ftepp_update_output_condition(ftepp);
1537 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1538 if (!vec_size(ftepp->conditions)) {
1539 ftepp_error(ftepp, "#endif without #if");
1542 vec_pop(ftepp->conditions);
1544 ftepp_update_output_condition(ftepp);
1547 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1548 return ftepp_include(ftepp);
1550 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1551 ftepp_out(ftepp, "#", false);
1554 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1555 ftepp_directive_warning(ftepp);
1558 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1559 ftepp_directive_error(ftepp);
1562 else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1563 ftepp_directive_message(ftepp);
1567 if (ftepp->output_on) {
1568 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1575 /* break; never reached */
1577 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1580 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1583 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1586 /* Builtins! Don't forget the builtins! */
1587 case TOKEN_INTCONST:
1588 case TOKEN_FLOATCONST:
1589 ftepp_out(ftepp, "#", false);
1592 if (!ftepp_skipspace(ftepp))
1597 static bool ftepp_preprocess(ftepp_t *ftepp)
1600 bool newline = true;
1603 char *expand = NULL;
1606 ftepp->lex->flags.preprocessing = true;
1607 ftepp->lex->flags.mergelines = false;
1608 ftepp->lex->flags.noops = true;
1613 if (ftepp->token >= TOKEN_EOF)
1619 switch (ftepp->token) {
1622 case TOKEN_TYPENAME:
1623 /* is it a predef? */
1624 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1625 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1626 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1627 expand = ftepp_predefs[i].func(ftepp->lex);
1628 ftepp_out(ftepp, expand, false);
1629 ftepp_next(ftepp); /* skip */
1631 mem_d(expand); /* free memory */
1637 if (ftepp->output_on)
1638 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1643 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1647 if (!ftepp_macro_call(ftepp, macro))
1648 ftepp->token = TOKEN_ERROR;
1652 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1656 ftepp->lex->flags.mergelines = true;
1657 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1658 ftepp_error(ftepp, "error in preprocessor directive");
1659 ftepp->token = TOKEN_ERROR;
1662 if (!ftepp_hash(ftepp))
1663 ftepp->token = TOKEN_ERROR;
1664 ftepp->lex->flags.mergelines = false;
1668 ftepp_out(ftepp, "\n", true);
1672 /* same as default but don't set newline=false */
1673 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1678 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1682 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1684 /* force a 0 at the end but don't count it as added to the output */
1685 vec_push(ftepp->output_string, 0);
1686 vec_shrinkby(ftepp->output_string, 1);
1688 return (ftepp->token == TOKEN_EOF);
1691 /* Like in parser.c - files keep the previous state so we have one global
1692 * preprocessor. Except here we will want to warn about dangling #ifs.
1694 static ftepp_t *ftepp;
1696 static bool ftepp_preprocess_done()
1699 if (vec_size(ftepp->conditions)) {
1700 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1703 lex_close(ftepp->lex);
1705 if (ftepp->itemname) {
1706 mem_d(ftepp->itemname);
1707 ftepp->itemname = NULL;
1712 bool ftepp_preprocess_file(const char *filename)
1714 ftepp->lex = lex_open(filename);
1715 ftepp->itemname = util_strdup(filename);
1717 con_out("failed to open file \"%s\"\n", filename);
1720 if (!ftepp_preprocess(ftepp))
1722 return ftepp_preprocess_done();
1725 bool ftepp_preprocess_string(const char *name, const char *str)
1727 ftepp->lex = lex_open_string(str, strlen(str), name);
1728 ftepp->itemname = util_strdup(name);
1730 con_out("failed to create lexer for string \"%s\"\n", name);
1733 if (!ftepp_preprocess(ftepp))
1735 return ftepp_preprocess_done();
1739 void ftepp_add_macro(const char *name, const char *value) {
1740 char *create = NULL;
1742 /* use saner path for empty macros */
1744 ftepp_add_define("__builtin__", name);
1748 vec_upload(create, "#define ", 8);
1749 vec_upload(create, name, strlen(name));
1750 vec_push (create, ' ');
1751 vec_upload(create, value, strlen(value));
1752 vec_push (create, 0);
1754 ftepp_preprocess_string("__builtin__", create);
1763 ftepp = ftepp_new();
1767 memset(minor, 0, sizeof(minor));
1768 memset(major, 0, sizeof(major));
1770 /* set the right macro based on the selected standard */
1771 ftepp_add_define(NULL, "GMQCC");
1772 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1773 ftepp_add_define(NULL, "__STD_FTEQCC__");
1782 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1783 ftepp_add_define(NULL, "__STD_GMQCC__");
1784 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1785 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1786 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1787 ftepp_add_define(NULL, "__STD_QCCX__");
1788 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1789 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1790 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1791 ftepp_add_define(NULL, "__STD_QCC__");
1802 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1803 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1808 void ftepp_add_define(const char *source, const char *name)
1811 lex_ctx ctx = { "__builtin__", 0 };
1813 macro = ppmacro_new(ctx, name);
1814 vec_push(ftepp->macros, macro);
1817 const char *ftepp_get()
1819 return ftepp->output_string;
1824 ftepp_flush_do(ftepp);
1831 ftepp_delete(ftepp);