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
28 #define HT_MACROS 1024
38 /* a copy from the lexer */
52 /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
59 typedef struct ftepp_s {
65 ppcondition *conditions;
67 ht macros; /* hashtable<string, ppmacro*> */
77 * Implement the predef subsystem now. We can do this safely with the
78 * help of lexer contexts.
80 static uint32_t ftepp_predef_countval = 0;
81 static uint32_t ftepp_predef_randval = 0;
84 char *ftepp_predef_date(lex_file *context) {
87 char *value = (char*)mem_a(82);
88 /* 82 is enough for strftime but we also have " " in our string */
94 itime = localtime(&rtime);
96 strftime(value, 82, "\"%b %d %Y\"", itime);
102 char *ftepp_predef_time(lex_file *context) {
105 char *value = (char*)mem_a(82);
106 /* 82 is enough for strftime but we also have " " in our string */
112 itime = localtime(&rtime);
114 strftime(value, 82, "\"%X\"", itime);
120 char *ftepp_predef_line(lex_file *context) {
122 util_asprintf(&value, "%d", (int)context->line);
126 char *ftepp_predef_file(lex_file *context) {
127 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
128 char *value = (char*)mem_a(length);
129 snprintf(value, length, "\"%s\"", context->name);
133 /* __COUNTER_LAST__ */
134 char *ftepp_predef_counterlast(lex_file *context) {
136 util_asprintf(&value, "%u", ftepp_predef_countval);
142 char *ftepp_predef_counter(lex_file *context) {
144 ftepp_predef_countval ++;
145 util_asprintf(&value, "%u", ftepp_predef_countval);
151 char *ftepp_predef_random(lex_file *context) {
153 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
154 util_asprintf(&value, "%u", ftepp_predef_randval);
159 /* __RANDOM_LAST__ */
160 char *ftepp_predef_randomlast(lex_file *context) {
162 util_asprintf(&value, "%u", ftepp_predef_randval);
168 const ftepp_predef_t ftepp_predefs[FTEPP_PREDEF_COUNT] = {
169 { "__LINE__", &ftepp_predef_line },
170 { "__FILE__", &ftepp_predef_file },
171 { "__COUNTER__", &ftepp_predef_counter },
172 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
173 { "__RANDOM__", &ftepp_predef_random },
174 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
175 { "__DATE__", &ftepp_predef_date },
176 { "__TIME__", &ftepp_predef_time }
179 #define ftepp_tokval(f) ((f)->lex->tok.value)
180 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
182 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
189 con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
193 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
200 con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
204 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
210 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
215 static pptoken *pptoken_make(ftepp_t *ftepp)
217 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
218 token->token = ftepp->token;
220 if (token->token == TOKEN_WHITE)
221 token->value = util_strdup(" ");
224 token->value = util_strdup(ftepp_tokval(ftepp));
226 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
230 static GMQCC_INLINE void pptoken_delete(pptoken *self)
236 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
238 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
241 memset(macro, 0, sizeof(*macro));
242 macro->name = util_strdup(name);
246 static void ppmacro_delete(ppmacro *self)
249 for (i = 0; i < vec_size(self->params); ++i)
250 mem_d(self->params[i]);
251 vec_free(self->params);
252 for (i = 0; i < vec_size(self->output); ++i)
253 pptoken_delete(self->output[i]);
254 vec_free(self->output);
259 static ftepp_t* ftepp_new()
263 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
264 memset(ftepp, 0, sizeof(*ftepp));
266 ftepp->macros = util_htnew(HT_MACROS);
267 ftepp->output_on = true;
272 static GMQCC_INLINE void ftepp_flush_do(ftepp_t *self)
274 vec_free(self->output_string);
277 static void ftepp_delete(ftepp_t *self)
279 ftepp_flush_do(self);
281 mem_d(self->itemname);
282 if (self->includename)
283 vec_free(self->includename);
285 util_htrem(self->macros, (void (*)(void*))&ppmacro_delete);
287 vec_free(self->conditions);
289 lex_close(self->lex);
293 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
295 if (ignore_cond || ftepp->output_on)
300 data = vec_add(ftepp->output_string, len);
301 memcpy(data, str, len);
305 static GMQCC_INLINE void ftepp_update_output_condition(ftepp_t *ftepp)
308 ftepp->output_on = true;
309 for (i = 0; i < vec_size(ftepp->conditions); ++i)
310 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
313 static GMQCC_INLINE ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
315 return util_htget(ftepp->macros, name);
318 static GMQCC_INLINE void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
320 util_htrm(ftepp->macros, name, NULL);
323 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
325 return (ftepp->token = lex_do(ftepp->lex));
328 /* Important: this does not skip newlines! */
329 static bool ftepp_skipspace(ftepp_t *ftepp)
331 if (ftepp->token != TOKEN_WHITE)
333 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
334 if (ftepp->token >= TOKEN_EOF) {
335 ftepp_error(ftepp, "unexpected end of preprocessor directive");
341 /* this one skips EOLs as well */
342 static bool ftepp_skipallwhite(ftepp_t *ftepp)
344 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
348 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
349 if (ftepp->token >= TOKEN_EOF) {
350 ftepp_error(ftepp, "unexpected end of preprocessor directive");
357 * The huge macro parsing code...
359 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
363 if (!ftepp_skipspace(ftepp))
365 if (ftepp->token == ')')
367 switch (ftepp->token) {
371 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
374 macro->variadic = true;
377 ftepp_error(ftepp, "unexpected token in parameter list");
381 if (!ftepp_skipspace(ftepp))
383 if (macro->variadic && ftepp->token != ')') {
384 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
387 } while (ftepp->token == ',');
389 if (ftepp->token != ')') {
390 ftepp_error(ftepp, "expected closing paren after macro parameter list");
394 /* skipspace happens in ftepp_define */
398 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
401 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
402 bool subscript = false;
404 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
405 subscript = !!(ftepp_next(ftepp) == '#');
407 if (subscript && ftepp_next(ftepp) != '#') {
408 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
410 } else if (subscript) {
411 if (ftepp_next(ftepp) == '[') {
412 if (ftepp_next(ftepp) != TOKEN_INTCONST) {
413 ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
417 index = (int)strtol(ftepp_tokval(ftepp), NULL, 10);
419 if (ftepp_next(ftepp) != ']') {
420 ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
425 * mark it as an array to be handled later as such and not
426 * as traditional __VA_ARGS__
428 ftepp->token = TOKEN_VA_ARGS_ARRAY;
429 ptok = pptoken_make(ftepp);
430 ptok->constval.i = index;
431 vec_push(macro->output, ptok);
434 ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
438 int old = ftepp->token;
439 ftepp->token = TOKEN_VA_ARGS;
440 ptok = pptoken_make(ftepp);
441 vec_push(macro->output, ptok);
445 else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
446 ftepp->token = TOKEN_VA_COUNT;
447 ptok = pptoken_make(ftepp);
448 vec_push(macro->output, ptok);
451 ptok = pptoken_make(ftepp);
452 vec_push(macro->output, ptok);
456 /* recursive expansion can cause EOFs here */
457 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
458 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
464 static bool ftepp_define(ftepp_t *ftepp)
466 ppmacro *macro = NULL;
467 size_t l = ftepp_ctx(ftepp).line;
469 (void)ftepp_next(ftepp);
470 if (!ftepp_skipspace(ftepp))
473 switch (ftepp->token) {
477 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
478 if (macro && ftepp->output_on) {
479 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
481 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
483 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
486 ftepp_error(ftepp, "expected macro name");
490 (void)ftepp_next(ftepp);
492 if (ftepp->token == '(') {
493 macro->has_params = true;
494 if (!ftepp_define_params(ftepp, macro)) {
495 ppmacro_delete(macro);
500 if (!ftepp_skipspace(ftepp)) {
501 ppmacro_delete(macro);
505 if (!ftepp_define_body(ftepp, macro)) {
506 ppmacro_delete(macro);
511 if (ftepp->output_on)
512 vec_push(ftepp->macros, macro);
514 if (ftepp->output_on)
515 util_htset(ftepp->macros, macro->name, (void*)macro);
517 ppmacro_delete(macro);
520 for (; l < ftepp_ctx(ftepp).line; ++l)
521 ftepp_out(ftepp, "\n", true);
526 * When a macro is used we have to handle parameters as well
527 * as special-concatenation via ## or stringification via #
529 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
530 * this kind of parens. Curly braces or [] don't count towards the
537 static void macroparam_clean(macroparam *self)
540 for (i = 0; i < vec_size(self->tokens); ++i)
541 pptoken_delete(self->tokens[i]);
542 vec_free(self->tokens);
545 /* need to leave the last token up */
546 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
548 macroparam *params = NULL;
554 if (!ftepp_skipallwhite(ftepp))
556 while (ftepp->token != ')') {
558 if (!ftepp_skipallwhite(ftepp))
560 while (parens || ftepp->token != ',') {
561 if (ftepp->token == '(')
563 else if (ftepp->token == ')') {
568 ptok = pptoken_make(ftepp);
569 vec_push(mp.tokens, ptok);
570 if (ftepp_next(ftepp) >= TOKEN_EOF) {
571 ftepp_error(ftepp, "unexpected EOF in macro call");
575 vec_push(params, mp);
577 if (ftepp->token == ')')
579 if (ftepp->token != ',') {
580 ftepp_error(ftepp, "expected closing paren or comma in macro call");
583 if (ftepp_next(ftepp) >= TOKEN_EOF) {
584 ftepp_error(ftepp, "unexpected EOF in macro call");
588 /* need to leave that up
589 if (ftepp_next(ftepp) >= TOKEN_EOF) {
590 ftepp_error(ftepp, "unexpected EOF in macro call");
594 *out_params = params;
599 macroparam_clean(&mp);
600 for (i = 0; i < vec_size(params); ++i)
601 macroparam_clean(¶ms[i]);
606 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
609 for (i = 0; i < vec_size(macro->params); ++i) {
610 if (!strcmp(macro->params[i], name)) {
618 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
623 switch (token->token) {
624 case TOKEN_STRINGCONST:
627 /* in preprocessor mode strings already are string,
628 * so we don't get actual newline bytes here.
629 * Still need to escape backslashes and quotes.
632 case '\\': ftepp_out(ftepp, "\\\\", false); break;
633 case '"': ftepp_out(ftepp, "\\\"", false); break;
636 ftepp_out(ftepp, chs, false);
643 ftepp_out(ftepp, " ", false);
646 ftepp_out(ftepp, "\\n", false);
649 ftepp_out(ftepp, token->value, false);
654 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
657 ftepp_out(ftepp, "\"", false);
658 for (i = 0; i < vec_size(param->tokens); ++i)
659 ftepp_stringify_token(ftepp, param->tokens[i]);
660 ftepp_out(ftepp, "\"", false);
663 static void ftepp_recursion_header(ftepp_t *ftepp)
665 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
668 static void ftepp_recursion_footer(ftepp_t *ftepp)
670 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
673 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
677 for (i = 0; i < vec_size(param->tokens); ++i) {
678 out = param->tokens[i];
679 if (out->token == TOKEN_EOL)
680 ftepp_out(ftepp, "\n", false);
682 ftepp_out(ftepp, out->value, false);
686 static bool ftepp_preprocess(ftepp_t *ftepp);
687 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
690 char *old_string = ftepp->output_string;
692 lex_file *old_lexer = ftepp->lex;
693 size_t vararg_start = vec_size(macro->params);
705 if (vararg_start < vec_size(params))
706 varargs = vec_size(params) - vararg_start;
711 if (!vec_size(macro->output))
714 ftepp->output_string = NULL;
715 for (o = 0; o < vec_size(macro->output); ++o) {
716 pptoken *out = macro->output[o];
717 switch (out->token) {
719 if (!macro->variadic) {
720 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
721 vec_free(old_string);
728 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
729 for (++pi; pi < varargs; ++pi) {
730 ftepp_out(ftepp, ", ", false);
731 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
735 case TOKEN_VA_ARGS_ARRAY:
736 if ((size_t)out->constval.i >= varargs) {
737 ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
738 vec_free(old_string);
742 ftepp_param_out(ftepp, ¶ms[out->constval.i + vararg_start]);
746 util_asprintf(&buffer, "%d", varargs);
747 ftepp_out(ftepp, buffer, false);
754 if (!macro_params_find(macro, out->value, &pi)) {
755 ftepp_out(ftepp, out->value, false);
758 ftepp_param_out(ftepp, ¶ms[pi]);
761 if (o + 1 < vec_size(macro->output)) {
762 nextok = macro->output[o+1]->token;
764 /* raw concatenation */
768 if ( (nextok == TOKEN_IDENT ||
769 nextok == TOKEN_KEYWORD ||
770 nextok == TOKEN_TYPENAME) &&
771 macro_params_find(macro, macro->output[o+1]->value, &pi))
774 ftepp_stringify(ftepp, ¶ms[pi]);
778 ftepp_out(ftepp, "#", false);
781 ftepp_out(ftepp, "\n", false);
784 ftepp_out(ftepp, out->value, false);
788 vec_push(ftepp->output_string, 0);
789 /* Now run the preprocessor recursively on this string buffer */
791 printf("__________\n%s\n=========\n", ftepp->output_string);
793 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
795 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
800 inlex->line = ftepp->lex->line;
801 inlex->sline = ftepp->lex->sline;
804 old_inmacro = ftepp->in_macro;
805 ftepp->in_macro = true;
806 ftepp->output_string = NULL;
807 if (!ftepp_preprocess(ftepp)) {
808 ftepp->in_macro = old_inmacro;
809 vec_free(ftepp->lex->open_string);
810 vec_free(ftepp->output_string);
811 lex_close(ftepp->lex);
815 ftepp->in_macro = old_inmacro;
816 vec_free(ftepp->lex->open_string);
817 lex_close(ftepp->lex);
819 inner_string = ftepp->output_string;
820 ftepp->output_string = old_string;
822 has_newlines = (strchr(inner_string, '\n') != NULL);
824 if (has_newlines && !old_inmacro)
825 ftepp_recursion_header(ftepp);
827 vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
828 vec_free(inner_string);
830 if (has_newlines && !old_inmacro)
831 ftepp_recursion_footer(ftepp);
833 if (resetline && !ftepp->in_macro) {
835 snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
836 ftepp_out(ftepp, lineno, false);
839 old_string = ftepp->output_string;
841 ftepp->lex = old_lexer;
842 ftepp->output_string = old_string;
846 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
849 macroparam *params = NULL;
853 if (!macro->has_params) {
854 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
861 if (!ftepp_skipallwhite(ftepp))
864 if (ftepp->token != '(') {
865 ftepp_error(ftepp, "expected macro parameters in parenthesis");
870 paramline = ftepp->lex->sline;
871 if (!ftepp_macro_call_params(ftepp, ¶ms))
874 if ( vec_size(params) < vec_size(macro->params) ||
875 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
877 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
878 (macro->variadic ? " at least" : ""),
879 (unsigned int)vec_size(macro->params),
880 (unsigned int)vec_size(params));
885 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
890 for (o = 0; o < vec_size(params); ++o)
891 macroparam_clean(¶ms[o]);
897 * #if - the FTEQCC way:
898 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
899 * <numbers> => True if the number is not 0
900 * !<factor> => True if the factor yields false
901 * !!<factor> => ERROR on 2 or more unary nots
902 * <macro> => becomes the macro's FIRST token regardless of parameters
903 * <e> && <e> => True if both expressions are true
904 * <e> || <e> => True if either expression is true
906 * <ident> => False (remember for macros the <macro> rule applies instead)
907 * Unary + and - are weird and wrong in fteqcc so we don't allow them
908 * parenthesis in expressions are allowed
909 * parameter lists on macros are errors
910 * No mathematical calculations are executed
912 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
913 static bool ftepp_if_op(ftepp_t *ftepp)
915 ftepp->lex->flags.noops = false;
917 if (!ftepp_skipspace(ftepp))
919 ftepp->lex->flags.noops = true;
922 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
928 if (!ftepp_skipspace(ftepp))
931 while (ftepp->token == '!') {
934 if (!ftepp_skipspace(ftepp))
938 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
942 if (!ftepp_skipspace(ftepp))
946 switch (ftepp->token) {
950 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
952 if (!ftepp_skipspace(ftepp))
954 if (ftepp->token != '(') {
955 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
959 if (!ftepp_skipspace(ftepp))
961 if (ftepp->token != TOKEN_IDENT &&
962 ftepp->token != TOKEN_TYPENAME &&
963 ftepp->token != TOKEN_KEYWORD)
965 ftepp_error(ftepp, "defined() used on an unexpected token type");
968 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
971 if (!ftepp_skipspace(ftepp))
973 if (ftepp->token != ')') {
974 ftepp_error(ftepp, "expected closing paren");
980 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
981 if (!macro || !vec_size(macro->output)) {
985 /* This does not expand recursively! */
986 switch (macro->output[0]->token) {
988 *value_out = macro->output[0]->constval.i;
989 *out = !!(macro->output[0]->constval.i);
991 case TOKEN_FLOATCONST:
992 *value_out = macro->output[0]->constval.f;
993 *out = !!(macro->output[0]->constval.f);
1001 case TOKEN_STRINGCONST:
1005 case TOKEN_INTCONST:
1006 *value_out = ftepp->lex->tok.constval.i;
1007 *out = !!(ftepp->lex->tok.constval.i);
1009 case TOKEN_FLOATCONST:
1010 *value_out = ftepp->lex->tok.constval.f;
1011 *out = !!(ftepp->lex->tok.constval.f);
1016 if (!ftepp_if_expr(ftepp, out, value_out))
1018 if (ftepp->token != ')') {
1019 ftepp_error(ftepp, "expected closing paren in #if expression");
1025 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1026 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1027 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1031 *value_out = -*value_out;
1034 *value_out = (*out ? 1 : 0);
1040 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1042 if (!ftepp_next(ftepp))
1044 return ftepp_if_value(ftepp, out, value_out);
1048 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1050 if (!ftepp_if_value(ftepp, out, value_out))
1053 if (!ftepp_if_op(ftepp))
1056 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1059 /* FTEQCC is all right-associative and no precedence here */
1060 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1061 !strcmp(ftepp_tokval(ftepp), "||"))
1064 char opc = ftepp_tokval(ftepp)[0];
1068 if (!ftepp_next(ftepp))
1070 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1074 *out = *out && next;
1076 *out = *out || next;
1078 *value_out = (*out ? 1 : 0);
1081 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1082 !strcmp(ftepp_tokval(ftepp), "!=") ||
1083 !strcmp(ftepp_tokval(ftepp), ">=") ||
1084 !strcmp(ftepp_tokval(ftepp), "<=") ||
1085 !strcmp(ftepp_tokval(ftepp), ">") ||
1086 !strcmp(ftepp_tokval(ftepp), "<"))
1089 const char opc0 = ftepp_tokval(ftepp)[0];
1090 const char opc1 = ftepp_tokval(ftepp)[1];
1093 if (!ftepp_next(ftepp))
1095 if (!ftepp_if_expr(ftepp, &next, &other))
1099 *out = (*value_out == other);
1100 else if (opc0 == '!')
1101 *out = (*value_out != other);
1102 else if (opc0 == '>') {
1103 if (opc1 == '=') *out = (*value_out >= other);
1104 else *out = (*value_out > other);
1106 else if (opc0 == '<') {
1107 if (opc1 == '=') *out = (*value_out <= other);
1108 else *out = (*value_out < other);
1110 *value_out = (*out ? 1 : 0);
1115 ftepp_error(ftepp, "junk after #if");
1120 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1122 bool result = false;
1125 memset(cond, 0, sizeof(*cond));
1126 (void)ftepp_next(ftepp);
1128 if (!ftepp_skipspace(ftepp))
1130 if (ftepp->token == TOKEN_EOL) {
1131 ftepp_error(ftepp, "expected expression for #if-directive");
1135 if (!ftepp_if_expr(ftepp, &result, &dummy))
1143 * ifdef is rather simple
1145 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1148 memset(cond, 0, sizeof(*cond));
1149 (void)ftepp_next(ftepp);
1150 if (!ftepp_skipspace(ftepp))
1153 switch (ftepp->token) {
1155 case TOKEN_TYPENAME:
1157 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1160 ftepp_error(ftepp, "expected macro name");
1164 (void)ftepp_next(ftepp);
1165 if (!ftepp_skipspace(ftepp))
1167 /* relaxing this condition
1168 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1169 ftepp_error(ftepp, "stray tokens after #ifdef");
1178 * undef is also simple
1180 static bool ftepp_undef(ftepp_t *ftepp)
1182 (void)ftepp_next(ftepp);
1183 if (!ftepp_skipspace(ftepp))
1186 if (ftepp->output_on) {
1187 switch (ftepp->token) {
1189 case TOKEN_TYPENAME:
1191 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1194 ftepp_error(ftepp, "expected macro name");
1199 (void)ftepp_next(ftepp);
1200 if (!ftepp_skipspace(ftepp))
1202 /* relaxing this condition
1203 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1204 ftepp_error(ftepp, "stray tokens after #ifdef");
1211 /* Special unescape-string function which skips a leading quote
1212 * and stops at a quote, not just at \0
1214 static void unescape(const char *str, char *out) {
1216 while (*str && *str != '"') {
1220 case '\\': *out++ = *str; break;
1221 case '"': *out++ = *str; break;
1222 case 'a': *out++ = '\a'; break;
1223 case 'b': *out++ = '\b'; break;
1224 case 'r': *out++ = '\r'; break;
1225 case 'n': *out++ = '\n'; break;
1226 case 't': *out++ = '\t'; break;
1227 case 'f': *out++ = '\f'; break;
1228 case 'v': *out++ = '\v'; break;
1243 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1246 char *filename = NULL;
1247 const char *last_slash;
1253 last_slash = strrchr(pathfile, '/');
1256 len = last_slash - pathfile;
1257 memcpy(vec_add(filename, len), pathfile, len);
1258 vec_push(filename, '/');
1262 memcpy(vec_add(filename, len+1), file, len);
1263 vec_last(filename) = 0;
1265 fp = fs_file_open(filename, "rb");
1274 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1276 char *filename = NULL;
1278 filename = ftepp_include_find_path(file, ftepp->includename);
1280 filename = ftepp_include_find_path(file, ftepp->itemname);
1284 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1285 char *message = NULL;
1287 if (!ftepp_skipspace(ftepp))
1290 /* handle the odd non string constant case so it works like C */
1291 if (ftepp->token != TOKEN_STRINGCONST) {
1293 vec_upload(message, "#warning", 8);
1295 while (ftepp->token != TOKEN_EOL) {
1296 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1299 vec_push(message, '\0');
1300 if (ftepp->output_on)
1301 store = ftepp_warn(ftepp, WARN_CPP, message);
1308 if (!ftepp->output_on)
1311 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1312 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1315 static void ftepp_directive_error(ftepp_t *ftepp) {
1316 char *message = NULL;
1318 if (!ftepp_skipspace(ftepp))
1321 /* handle the odd non string constant case so it works like C */
1322 if (ftepp->token != TOKEN_STRINGCONST) {
1323 vec_upload(message, "#error", 6);
1325 while (ftepp->token != TOKEN_EOL) {
1326 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1329 vec_push(message, '\0');
1330 if (ftepp->output_on)
1331 ftepp_error(ftepp, message);
1336 if (!ftepp->output_on)
1339 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1340 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1343 static void ftepp_directive_message(ftepp_t *ftepp) {
1344 char *message = NULL;
1346 if (!ftepp_skipspace(ftepp))
1349 /* handle the odd non string constant case so it works like C */
1350 if (ftepp->token != TOKEN_STRINGCONST) {
1351 vec_upload(message, "#message", 8);
1353 while (ftepp->token != TOKEN_EOL) {
1354 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1357 vec_push(message, '\0');
1358 if (ftepp->output_on)
1359 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1364 if (!ftepp->output_on)
1367 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1368 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", ftepp_tokval(ftepp));
1373 * FIXME: do we need/want a -I option?
1374 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1376 static bool ftepp_include(ftepp_t *ftepp)
1378 lex_file *old_lexer = ftepp->lex;
1383 char *old_includename;
1385 (void)ftepp_next(ftepp);
1386 if (!ftepp_skipspace(ftepp))
1389 if (ftepp->token != TOKEN_STRINGCONST) {
1390 ftepp_error(ftepp, "expected filename to include");
1394 if (!ftepp->output_on) {
1399 ctx = ftepp_ctx(ftepp);
1401 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1403 ftepp_out(ftepp, "\n#pragma file(", false);
1404 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1405 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1407 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1409 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1412 inlex = lex_open(filename);
1414 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1419 old_includename = ftepp->includename;
1420 ftepp->includename = filename;
1421 if (!ftepp_preprocess(ftepp)) {
1422 vec_free(ftepp->includename);
1423 ftepp->includename = old_includename;
1424 lex_close(ftepp->lex);
1425 ftepp->lex = old_lexer;
1428 vec_free(ftepp->includename);
1429 ftepp->includename = old_includename;
1430 lex_close(ftepp->lex);
1431 ftepp->lex = old_lexer;
1433 ftepp_out(ftepp, "\n#pragma file(", false);
1434 ftepp_out(ftepp, ctx.file, false);
1435 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1436 ftepp_out(ftepp, lineno, false);
1439 (void)ftepp_next(ftepp);
1440 if (!ftepp_skipspace(ftepp))
1442 if (ftepp->token != TOKEN_EOL) {
1443 ftepp_error(ftepp, "stray tokens after #include");
1446 (void)ftepp_next(ftepp);
1451 /* Basic structure handlers */
1452 static bool ftepp_else_allowed(ftepp_t *ftepp)
1454 if (!vec_size(ftepp->conditions)) {
1455 ftepp_error(ftepp, "#else without #if");
1458 if (vec_last(ftepp->conditions).had_else) {
1459 ftepp_error(ftepp, "multiple #else for a single #if");
1465 static bool ftepp_hash(ftepp_t *ftepp)
1470 lex_ctx ctx = ftepp_ctx(ftepp);
1472 if (!ftepp_skipspace(ftepp))
1475 switch (ftepp->token) {
1478 case TOKEN_TYPENAME:
1479 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1480 return ftepp_define(ftepp);
1482 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1483 return ftepp_undef(ftepp);
1485 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1486 if (!ftepp_ifdef(ftepp, &cond))
1488 cond.was_on = cond.on;
1489 vec_push(ftepp->conditions, cond);
1490 ftepp->output_on = ftepp->output_on && cond.on;
1493 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1494 if (!ftepp_ifdef(ftepp, &cond))
1497 cond.was_on = cond.on;
1498 vec_push(ftepp->conditions, cond);
1499 ftepp->output_on = ftepp->output_on && cond.on;
1502 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1503 if (!ftepp_else_allowed(ftepp))
1505 if (!ftepp_ifdef(ftepp, &cond))
1507 pc = &vec_last(ftepp->conditions);
1508 pc->on = !pc->was_on && cond.on;
1509 pc->was_on = pc->was_on || pc->on;
1510 ftepp_update_output_condition(ftepp);
1513 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1514 if (!ftepp_else_allowed(ftepp))
1516 if (!ftepp_ifdef(ftepp, &cond))
1519 pc = &vec_last(ftepp->conditions);
1520 pc->on = !pc->was_on && cond.on;
1521 pc->was_on = pc->was_on || pc->on;
1522 ftepp_update_output_condition(ftepp);
1525 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1526 if (!ftepp_else_allowed(ftepp))
1528 if (!ftepp_if(ftepp, &cond))
1530 pc = &vec_last(ftepp->conditions);
1531 pc->on = !pc->was_on && cond.on;
1532 pc->was_on = pc->was_on || pc->on;
1533 ftepp_update_output_condition(ftepp);
1536 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1537 if (!ftepp_if(ftepp, &cond))
1539 cond.was_on = cond.on;
1540 vec_push(ftepp->conditions, cond);
1541 ftepp->output_on = ftepp->output_on && cond.on;
1544 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1545 if (!ftepp_else_allowed(ftepp))
1547 pc = &vec_last(ftepp->conditions);
1548 pc->on = !pc->was_on;
1549 pc->had_else = true;
1551 ftepp_update_output_condition(ftepp);
1554 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1555 if (!vec_size(ftepp->conditions)) {
1556 ftepp_error(ftepp, "#endif without #if");
1559 vec_pop(ftepp->conditions);
1561 ftepp_update_output_condition(ftepp);
1564 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1565 return ftepp_include(ftepp);
1567 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1568 ftepp_out(ftepp, "#", false);
1571 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1572 ftepp_directive_warning(ftepp);
1575 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1576 ftepp_directive_error(ftepp);
1579 else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1580 ftepp_directive_message(ftepp);
1584 if (ftepp->output_on) {
1585 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1592 /* break; never reached */
1594 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1597 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1600 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1603 /* Builtins! Don't forget the builtins! */
1604 case TOKEN_INTCONST:
1605 case TOKEN_FLOATCONST:
1606 ftepp_out(ftepp, "#", false);
1609 if (!ftepp_skipspace(ftepp))
1614 static bool ftepp_preprocess(ftepp_t *ftepp)
1617 bool newline = true;
1620 char *expand = NULL;
1623 ftepp->lex->flags.preprocessing = true;
1624 ftepp->lex->flags.mergelines = false;
1625 ftepp->lex->flags.noops = true;
1630 if (ftepp->token >= TOKEN_EOF)
1636 switch (ftepp->token) {
1639 case TOKEN_TYPENAME:
1640 /* is it a predef? */
1641 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1642 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1643 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1644 expand = ftepp_predefs[i].func(ftepp->lex);
1645 ftepp_out(ftepp, expand, false);
1646 ftepp_next(ftepp); /* skip */
1648 mem_d(expand); /* free memory */
1654 if (ftepp->output_on)
1655 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1660 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1664 if (!ftepp_macro_call(ftepp, macro))
1665 ftepp->token = TOKEN_ERROR;
1669 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1673 ftepp->lex->flags.mergelines = true;
1674 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1675 ftepp_error(ftepp, "error in preprocessor directive");
1676 ftepp->token = TOKEN_ERROR;
1679 if (!ftepp_hash(ftepp))
1680 ftepp->token = TOKEN_ERROR;
1681 ftepp->lex->flags.mergelines = false;
1685 ftepp_out(ftepp, "\n", true);
1689 /* same as default but don't set newline=false */
1690 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1695 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1699 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1701 /* force a 0 at the end but don't count it as added to the output */
1702 vec_push(ftepp->output_string, 0);
1703 vec_shrinkby(ftepp->output_string, 1);
1705 return (ftepp->token == TOKEN_EOF);
1708 /* Like in parser.c - files keep the previous state so we have one global
1709 * preprocessor. Except here we will want to warn about dangling #ifs.
1711 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1714 if (vec_size(ftepp->conditions)) {
1715 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1718 lex_close(ftepp->lex);
1720 if (ftepp->itemname) {
1721 mem_d(ftepp->itemname);
1722 ftepp->itemname = NULL;
1727 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1729 ftepp->lex = lex_open(filename);
1730 ftepp->itemname = util_strdup(filename);
1732 con_out("failed to open file \"%s\"\n", filename);
1735 if (!ftepp_preprocess(ftepp))
1737 return ftepp_preprocess_done(ftepp);
1740 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1742 ftepp->lex = lex_open_string(str, strlen(str), name);
1743 ftepp->itemname = util_strdup(name);
1745 con_out("failed to create lexer for string \"%s\"\n", name);
1748 if (!ftepp_preprocess(ftepp))
1750 return ftepp_preprocess_done(ftepp);
1754 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1755 char *create = NULL;
1757 /* use saner path for empty macros */
1759 ftepp_add_define(ftepp, "__builtin__", name);
1763 vec_upload(create, "#define ", 8);
1764 vec_upload(create, name, strlen(name));
1765 vec_push (create, ' ');
1766 vec_upload(create, value, strlen(value));
1767 vec_push (create, 0);
1769 ftepp_preprocess_string(ftepp, "__builtin__", create);
1773 ftepp_t *ftepp_create()
1779 ftepp = ftepp_new();
1783 memset(minor, 0, sizeof(minor));
1784 memset(major, 0, sizeof(major));
1786 /* set the right macro based on the selected standard */
1787 ftepp_add_define(ftepp, NULL, "GMQCC");
1788 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1789 ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1798 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1799 ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1800 snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1801 snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1802 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1803 ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1804 snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1805 snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1806 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1807 ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1818 ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1819 ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1824 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1827 lex_ctx ctx = { "__builtin__", 0 };
1829 macro = ppmacro_new(ctx, name);
1830 /*vec_push(ftepp->macros, macro);*/
1831 util_htset(ftepp->macros, name, macro);
1834 const char *ftepp_get(ftepp_t *ftepp)
1836 return ftepp->output_string;
1839 void ftepp_flush(ftepp_t *ftepp)
1841 ftepp_flush_do(ftepp);
1844 void ftepp_finish(ftepp_t *ftepp)
1848 ftepp_delete(ftepp);