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 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 bool subscript = false;
412 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
413 subscript = !!(ftepp_next(ftepp) == '#');
415 if (subscript && ftepp_next(ftepp) != '#') {
416 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
418 } else if (subscript) {
419 if (ftepp_next(ftepp) == '[') {
420 if (ftepp_next(ftepp) != TOKEN_INTCONST) {
421 ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
425 index = atoi(ftepp_tokval(ftepp));
427 if (ftepp_next(ftepp) != ']') {
428 ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
433 * mark it as an array to be handled later as such and not
434 * as traditional __VA_ARGS__
436 ftepp->token = TOKEN_VA_ARGS_ARRAY;
437 ptok = pptoken_make(ftepp);
438 ptok->constval.i = index;
439 vec_push(macro->output, ptok);
442 ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
446 int old = ftepp->token;
447 ftepp->token = TOKEN_VA_ARGS;
448 ptok = pptoken_make(ftepp);
449 vec_push(macro->output, ptok);
453 else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
454 ftepp->token = TOKEN_VA_COUNT;
455 ptok = pptoken_make(ftepp);
456 vec_push(macro->output, ptok);
459 ptok = pptoken_make(ftepp);
460 vec_push(macro->output, ptok);
464 /* recursive expansion can cause EOFs here */
465 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
466 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
472 static bool ftepp_define(ftepp_t *ftepp)
475 size_t l = ftepp_ctx(ftepp).line;
477 (void)ftepp_next(ftepp);
478 if (!ftepp_skipspace(ftepp))
481 switch (ftepp->token) {
485 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
486 if (macro && ftepp->output_on) {
487 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
489 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
491 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
494 ftepp_error(ftepp, "expected macro name");
498 (void)ftepp_next(ftepp);
500 if (ftepp->token == '(') {
501 macro->has_params = true;
502 if (!ftepp_define_params(ftepp, macro))
506 if (!ftepp_skipspace(ftepp))
509 if (!ftepp_define_body(ftepp, macro))
512 if (ftepp->output_on)
513 vec_push(ftepp->macros, macro);
515 ppmacro_delete(macro);
518 for (; l < ftepp_ctx(ftepp).line; ++l)
519 ftepp_out(ftepp, "\n", true);
524 * When a macro is used we have to handle parameters as well
525 * as special-concatenation via ## or stringification via #
527 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
528 * this kind of parens. Curly braces or [] don't count towards the
535 static void macroparam_clean(macroparam *self)
538 for (i = 0; i < vec_size(self->tokens); ++i)
539 pptoken_delete(self->tokens[i]);
540 vec_free(self->tokens);
543 /* need to leave the last token up */
544 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
546 macroparam *params = NULL;
552 if (!ftepp_skipallwhite(ftepp))
554 while (ftepp->token != ')') {
556 if (!ftepp_skipallwhite(ftepp))
558 while (parens || ftepp->token != ',') {
559 if (ftepp->token == '(')
561 else if (ftepp->token == ')') {
566 ptok = pptoken_make(ftepp);
567 vec_push(mp.tokens, ptok);
568 if (ftepp_next(ftepp) >= TOKEN_EOF) {
569 ftepp_error(ftepp, "unexpected EOF in macro call");
573 vec_push(params, mp);
575 if (ftepp->token == ')')
577 if (ftepp->token != ',') {
578 ftepp_error(ftepp, "expected closing paren or comma in macro call");
581 if (ftepp_next(ftepp) >= TOKEN_EOF) {
582 ftepp_error(ftepp, "unexpected EOF in macro call");
586 /* need to leave that up
587 if (ftepp_next(ftepp) >= TOKEN_EOF) {
588 ftepp_error(ftepp, "unexpected EOF in macro call");
592 *out_params = params;
597 macroparam_clean(&mp);
598 for (i = 0; i < vec_size(params); ++i)
599 macroparam_clean(¶ms[i]);
604 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
607 for (i = 0; i < vec_size(macro->params); ++i) {
608 if (!strcmp(macro->params[i], name)) {
616 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
621 switch (token->token) {
622 case TOKEN_STRINGCONST:
625 /* in preprocessor mode strings already are string,
626 * so we don't get actual newline bytes here.
627 * Still need to escape backslashes and quotes.
630 case '\\': ftepp_out(ftepp, "\\\\", false); break;
631 case '"': ftepp_out(ftepp, "\\\"", false); break;
634 ftepp_out(ftepp, chs, false);
641 ftepp_out(ftepp, " ", false);
644 ftepp_out(ftepp, "\\n", false);
647 ftepp_out(ftepp, token->value, false);
652 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
655 ftepp_out(ftepp, "\"", false);
656 for (i = 0; i < vec_size(param->tokens); ++i)
657 ftepp_stringify_token(ftepp, param->tokens[i]);
658 ftepp_out(ftepp, "\"", false);
661 static void ftepp_recursion_header(ftepp_t *ftepp)
663 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
666 static void ftepp_recursion_footer(ftepp_t *ftepp)
668 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
671 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
675 for (i = 0; i < vec_size(param->tokens); ++i) {
676 out = param->tokens[i];
677 if (out->token == TOKEN_EOL)
678 ftepp_out(ftepp, "\n", false);
680 ftepp_out(ftepp, out->value, false);
684 static bool ftepp_preprocess(ftepp_t *ftepp);
685 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
688 char *old_string = ftepp->output_string;
690 lex_file *old_lexer = ftepp->lex;
691 size_t vararg_start = vec_size(macro->params);
703 if (vararg_start < vec_size(params))
704 varargs = vec_size(params) - vararg_start;
709 if (!vec_size(macro->output))
712 ftepp->output_string = NULL;
713 for (o = 0; o < vec_size(macro->output); ++o) {
714 pptoken *out = macro->output[o];
715 switch (out->token) {
717 if (!macro->variadic) {
718 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
719 vec_free(old_string);
726 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
727 for (++pi; pi < varargs; ++pi) {
728 ftepp_out(ftepp, ", ", false);
729 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
733 case TOKEN_VA_ARGS_ARRAY:
734 if ((size_t)out->constval.i >= varargs) {
735 ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
736 vec_free(old_string);
740 ftepp_param_out(ftepp, ¶ms[out->constval.i + vararg_start]);
744 util_asprintf(&buffer, "%d", varargs);
745 ftepp_out(ftepp, buffer, false);
752 if (!macro_params_find(macro, out->value, &pi)) {
753 ftepp_out(ftepp, out->value, false);
756 ftepp_param_out(ftepp, ¶ms[pi]);
759 if (o + 1 < vec_size(macro->output)) {
760 nextok = macro->output[o+1]->token;
762 /* raw concatenation */
766 if ( (nextok == TOKEN_IDENT ||
767 nextok == TOKEN_KEYWORD ||
768 nextok == TOKEN_TYPENAME) &&
769 macro_params_find(macro, macro->output[o+1]->value, &pi))
772 ftepp_stringify(ftepp, ¶ms[pi]);
776 ftepp_out(ftepp, "#", false);
779 ftepp_out(ftepp, "\n", false);
782 ftepp_out(ftepp, out->value, false);
786 vec_push(ftepp->output_string, 0);
787 /* Now run the preprocessor recursively on this string buffer */
789 printf("__________\n%s\n=========\n", ftepp->output_string);
791 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
793 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
798 inlex->line = ftepp->lex->line;
799 inlex->sline = ftepp->lex->sline;
802 old_inmacro = ftepp->in_macro;
803 ftepp->in_macro = true;
804 ftepp->output_string = NULL;
805 if (!ftepp_preprocess(ftepp)) {
806 ftepp->in_macro = old_inmacro;
807 vec_free(ftepp->lex->open_string);
808 vec_free(ftepp->output_string);
809 lex_close(ftepp->lex);
813 ftepp->in_macro = old_inmacro;
814 vec_free(ftepp->lex->open_string);
815 lex_close(ftepp->lex);
817 inner_string = ftepp->output_string;
818 ftepp->output_string = old_string;
820 has_newlines = (strchr(inner_string, '\n') != NULL);
822 if (has_newlines && !old_inmacro)
823 ftepp_recursion_header(ftepp);
825 vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
826 vec_free(inner_string);
828 if (has_newlines && !old_inmacro)
829 ftepp_recursion_footer(ftepp);
831 if (resetline && !ftepp->in_macro) {
833 sprintf(lineno, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
834 ftepp_out(ftepp, lineno, false);
837 old_string = ftepp->output_string;
839 ftepp->lex = old_lexer;
840 ftepp->output_string = old_string;
844 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
847 macroparam *params = NULL;
851 if (!macro->has_params) {
852 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
859 if (!ftepp_skipallwhite(ftepp))
862 if (ftepp->token != '(') {
863 ftepp_error(ftepp, "expected macro parameters in parenthesis");
868 paramline = ftepp->lex->sline;
869 if (!ftepp_macro_call_params(ftepp, ¶ms))
872 if ( vec_size(params) < vec_size(macro->params) ||
873 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
875 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
876 (macro->variadic ? " at least" : ""),
877 (unsigned int)vec_size(macro->params),
878 (unsigned int)vec_size(params));
883 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
888 for (o = 0; o < vec_size(params); ++o)
889 macroparam_clean(¶ms[o]);
895 * #if - the FTEQCC way:
896 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
897 * <numbers> => True if the number is not 0
898 * !<factor> => True if the factor yields false
899 * !!<factor> => ERROR on 2 or more unary nots
900 * <macro> => becomes the macro's FIRST token regardless of parameters
901 * <e> && <e> => True if both expressions are true
902 * <e> || <e> => True if either expression is true
904 * <ident> => False (remember for macros the <macro> rule applies instead)
905 * Unary + and - are weird and wrong in fteqcc so we don't allow them
906 * parenthesis in expressions are allowed
907 * parameter lists on macros are errors
908 * No mathematical calculations are executed
910 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
911 static bool ftepp_if_op(ftepp_t *ftepp)
913 ftepp->lex->flags.noops = false;
915 if (!ftepp_skipspace(ftepp))
917 ftepp->lex->flags.noops = true;
920 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
926 if (!ftepp_skipspace(ftepp))
929 while (ftepp->token == '!') {
932 if (!ftepp_skipspace(ftepp))
936 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
940 if (!ftepp_skipspace(ftepp))
944 switch (ftepp->token) {
948 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
950 if (!ftepp_skipspace(ftepp))
952 if (ftepp->token != '(') {
953 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
957 if (!ftepp_skipspace(ftepp))
959 if (ftepp->token != TOKEN_IDENT &&
960 ftepp->token != TOKEN_TYPENAME &&
961 ftepp->token != TOKEN_KEYWORD)
963 ftepp_error(ftepp, "defined() used on an unexpected token type");
966 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
969 if (!ftepp_skipspace(ftepp))
971 if (ftepp->token != ')') {
972 ftepp_error(ftepp, "expected closing paren");
978 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
979 if (!macro || !vec_size(macro->output)) {
983 /* This does not expand recursively! */
984 switch (macro->output[0]->token) {
986 *value_out = macro->output[0]->constval.i;
987 *out = !!(macro->output[0]->constval.i);
989 case TOKEN_FLOATCONST:
990 *value_out = macro->output[0]->constval.f;
991 *out = !!(macro->output[0]->constval.f);
999 case TOKEN_STRINGCONST:
1003 case TOKEN_INTCONST:
1004 *value_out = ftepp->lex->tok.constval.i;
1005 *out = !!(ftepp->lex->tok.constval.i);
1007 case TOKEN_FLOATCONST:
1008 *value_out = ftepp->lex->tok.constval.f;
1009 *out = !!(ftepp->lex->tok.constval.f);
1014 if (!ftepp_if_expr(ftepp, out, value_out))
1016 if (ftepp->token != ')') {
1017 ftepp_error(ftepp, "expected closing paren in #if expression");
1023 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1024 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1025 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1029 *value_out = -*value_out;
1032 *value_out = (*out ? 1 : 0);
1038 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1040 if (!ftepp_next(ftepp))
1042 return ftepp_if_value(ftepp, out, value_out);
1046 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1048 if (!ftepp_if_value(ftepp, out, value_out))
1051 if (!ftepp_if_op(ftepp))
1054 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1057 /* FTEQCC is all right-associative and no precedence here */
1058 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1059 !strcmp(ftepp_tokval(ftepp), "||"))
1062 char opc = ftepp_tokval(ftepp)[0];
1066 if (!ftepp_next(ftepp))
1068 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1072 *out = *out && next;
1074 *out = *out || next;
1076 *value_out = (*out ? 1 : 0);
1079 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1080 !strcmp(ftepp_tokval(ftepp), "!=") ||
1081 !strcmp(ftepp_tokval(ftepp), ">=") ||
1082 !strcmp(ftepp_tokval(ftepp), "<=") ||
1083 !strcmp(ftepp_tokval(ftepp), ">") ||
1084 !strcmp(ftepp_tokval(ftepp), "<"))
1087 const char opc0 = ftepp_tokval(ftepp)[0];
1088 const char opc1 = ftepp_tokval(ftepp)[1];
1091 if (!ftepp_next(ftepp))
1093 if (!ftepp_if_expr(ftepp, &next, &other))
1097 *out = (*value_out == other);
1098 else if (opc0 == '!')
1099 *out = (*value_out != other);
1100 else if (opc0 == '>') {
1101 if (opc1 == '=') *out = (*value_out >= other);
1102 else *out = (*value_out > other);
1104 else if (opc0 == '<') {
1105 if (opc1 == '=') *out = (*value_out <= other);
1106 else *out = (*value_out < other);
1108 *value_out = (*out ? 1 : 0);
1113 ftepp_error(ftepp, "junk after #if");
1118 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1120 bool result = false;
1123 memset(cond, 0, sizeof(*cond));
1124 (void)ftepp_next(ftepp);
1126 if (!ftepp_skipspace(ftepp))
1128 if (ftepp->token == TOKEN_EOL) {
1129 ftepp_error(ftepp, "expected expression for #if-directive");
1133 if (!ftepp_if_expr(ftepp, &result, &dummy))
1141 * ifdef is rather simple
1143 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1146 memset(cond, 0, sizeof(*cond));
1147 (void)ftepp_next(ftepp);
1148 if (!ftepp_skipspace(ftepp))
1151 switch (ftepp->token) {
1153 case TOKEN_TYPENAME:
1155 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1158 ftepp_error(ftepp, "expected macro name");
1162 (void)ftepp_next(ftepp);
1163 if (!ftepp_skipspace(ftepp))
1165 /* relaxing this condition
1166 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1167 ftepp_error(ftepp, "stray tokens after #ifdef");
1176 * undef is also simple
1178 static bool ftepp_undef(ftepp_t *ftepp)
1180 (void)ftepp_next(ftepp);
1181 if (!ftepp_skipspace(ftepp))
1184 if (ftepp->output_on) {
1185 switch (ftepp->token) {
1187 case TOKEN_TYPENAME:
1189 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1192 ftepp_error(ftepp, "expected macro name");
1197 (void)ftepp_next(ftepp);
1198 if (!ftepp_skipspace(ftepp))
1200 /* relaxing this condition
1201 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1202 ftepp_error(ftepp, "stray tokens after #ifdef");
1209 /* Special unescape-string function which skips a leading quote
1210 * and stops at a quote, not just at \0
1212 static void unescape(const char *str, char *out) {
1214 while (*str && *str != '"') {
1218 case '\\': *out++ = *str; break;
1219 case '"': *out++ = *str; break;
1220 case 'a': *out++ = '\a'; break;
1221 case 'b': *out++ = '\b'; break;
1222 case 'r': *out++ = '\r'; break;
1223 case 'n': *out++ = '\n'; break;
1224 case 't': *out++ = '\t'; break;
1225 case 'f': *out++ = '\f'; break;
1226 case 'v': *out++ = '\v'; break;
1241 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1244 char *filename = NULL;
1245 const char *last_slash;
1251 last_slash = strrchr(pathfile, '/');
1254 len = last_slash - pathfile;
1255 memcpy(vec_add(filename, len), pathfile, len);
1256 vec_push(filename, '/');
1260 memcpy(vec_add(filename, len+1), file, len);
1261 vec_last(filename) = 0;
1263 fp = fs_file_open(filename, "rb");
1272 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1274 char *filename = NULL;
1276 filename = ftepp_include_find_path(file, ftepp->includename);
1278 filename = ftepp_include_find_path(file, ftepp->itemname);
1282 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1283 char *message = NULL;
1285 if (!ftepp_skipspace(ftepp))
1288 /* handle the odd non string constant case so it works like C */
1289 if (ftepp->token != TOKEN_STRINGCONST) {
1291 vec_upload(message, "#warning", 8);
1293 while (ftepp->token != TOKEN_EOL) {
1294 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1297 vec_push(message, '\0');
1298 if (ftepp->output_on)
1299 store = ftepp_warn(ftepp, WARN_CPP, message);
1306 if (!ftepp->output_on)
1309 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1310 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1313 static void ftepp_directive_error(ftepp_t *ftepp) {
1314 char *message = NULL;
1316 if (!ftepp_skipspace(ftepp))
1319 /* handle the odd non string constant case so it works like C */
1320 if (ftepp->token != TOKEN_STRINGCONST) {
1321 vec_upload(message, "#error", 6);
1323 while (ftepp->token != TOKEN_EOL) {
1324 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1327 vec_push(message, '\0');
1328 if (ftepp->output_on)
1329 ftepp_error(ftepp, message);
1334 if (!ftepp->output_on)
1337 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1338 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1341 static void ftepp_directive_message(ftepp_t *ftepp) {
1342 char *message = NULL;
1344 if (!ftepp_skipspace(ftepp))
1347 /* handle the odd non string constant case so it works like C */
1348 if (ftepp->token != TOKEN_STRINGCONST) {
1349 vec_upload(message, "#message", 8);
1351 while (ftepp->token != TOKEN_EOL) {
1352 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1355 vec_push(message, '\0');
1356 if (ftepp->output_on)
1357 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1362 if (!ftepp->output_on)
1365 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1366 con_cprintmsg(&ftepp->lex->tok.ctx, LVL_MSG, "message", ftepp_tokval(ftepp));
1371 * FIXME: do we need/want a -I option?
1372 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1374 static bool ftepp_include(ftepp_t *ftepp)
1376 lex_file *old_lexer = ftepp->lex;
1381 char *old_includename;
1383 (void)ftepp_next(ftepp);
1384 if (!ftepp_skipspace(ftepp))
1387 if (ftepp->token != TOKEN_STRINGCONST) {
1388 ftepp_error(ftepp, "expected filename to include");
1392 if (!ftepp->output_on) {
1397 ctx = ftepp_ctx(ftepp);
1399 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1401 ftepp_out(ftepp, "\n#pragma file(", false);
1402 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1403 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1405 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1407 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1410 inlex = lex_open(filename);
1412 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1417 old_includename = ftepp->includename;
1418 ftepp->includename = filename;
1419 if (!ftepp_preprocess(ftepp)) {
1420 vec_free(ftepp->includename);
1421 ftepp->includename = old_includename;
1422 lex_close(ftepp->lex);
1423 ftepp->lex = old_lexer;
1426 vec_free(ftepp->includename);
1427 ftepp->includename = old_includename;
1428 lex_close(ftepp->lex);
1429 ftepp->lex = old_lexer;
1431 ftepp_out(ftepp, "\n#pragma file(", false);
1432 ftepp_out(ftepp, ctx.file, false);
1433 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1434 ftepp_out(ftepp, lineno, false);
1437 (void)ftepp_next(ftepp);
1438 if (!ftepp_skipspace(ftepp))
1440 if (ftepp->token != TOKEN_EOL) {
1441 ftepp_error(ftepp, "stray tokens after #include");
1444 (void)ftepp_next(ftepp);
1449 /* Basic structure handlers */
1450 static bool ftepp_else_allowed(ftepp_t *ftepp)
1452 if (!vec_size(ftepp->conditions)) {
1453 ftepp_error(ftepp, "#else without #if");
1456 if (vec_last(ftepp->conditions).had_else) {
1457 ftepp_error(ftepp, "multiple #else for a single #if");
1463 static bool ftepp_hash(ftepp_t *ftepp)
1468 lex_ctx ctx = ftepp_ctx(ftepp);
1470 if (!ftepp_skipspace(ftepp))
1473 switch (ftepp->token) {
1476 case TOKEN_TYPENAME:
1477 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1478 return ftepp_define(ftepp);
1480 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1481 return ftepp_undef(ftepp);
1483 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1484 if (!ftepp_ifdef(ftepp, &cond))
1486 cond.was_on = cond.on;
1487 vec_push(ftepp->conditions, cond);
1488 ftepp->output_on = ftepp->output_on && cond.on;
1491 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1492 if (!ftepp_ifdef(ftepp, &cond))
1495 cond.was_on = cond.on;
1496 vec_push(ftepp->conditions, cond);
1497 ftepp->output_on = ftepp->output_on && cond.on;
1500 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1501 if (!ftepp_else_allowed(ftepp))
1503 if (!ftepp_ifdef(ftepp, &cond))
1505 pc = &vec_last(ftepp->conditions);
1506 pc->on = !pc->was_on && cond.on;
1507 pc->was_on = pc->was_on || pc->on;
1508 ftepp_update_output_condition(ftepp);
1511 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1512 if (!ftepp_else_allowed(ftepp))
1514 if (!ftepp_ifdef(ftepp, &cond))
1517 pc = &vec_last(ftepp->conditions);
1518 pc->on = !pc->was_on && cond.on;
1519 pc->was_on = pc->was_on || pc->on;
1520 ftepp_update_output_condition(ftepp);
1523 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1524 if (!ftepp_else_allowed(ftepp))
1526 if (!ftepp_if(ftepp, &cond))
1528 pc = &vec_last(ftepp->conditions);
1529 pc->on = !pc->was_on && cond.on;
1530 pc->was_on = pc->was_on || pc->on;
1531 ftepp_update_output_condition(ftepp);
1534 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1535 if (!ftepp_if(ftepp, &cond))
1537 cond.was_on = cond.on;
1538 vec_push(ftepp->conditions, cond);
1539 ftepp->output_on = ftepp->output_on && cond.on;
1542 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1543 if (!ftepp_else_allowed(ftepp))
1545 pc = &vec_last(ftepp->conditions);
1546 pc->on = !pc->was_on;
1547 pc->had_else = true;
1549 ftepp_update_output_condition(ftepp);
1552 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1553 if (!vec_size(ftepp->conditions)) {
1554 ftepp_error(ftepp, "#endif without #if");
1557 vec_pop(ftepp->conditions);
1559 ftepp_update_output_condition(ftepp);
1562 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1563 return ftepp_include(ftepp);
1565 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1566 ftepp_out(ftepp, "#", false);
1569 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1570 ftepp_directive_warning(ftepp);
1573 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1574 ftepp_directive_error(ftepp);
1577 else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1578 ftepp_directive_message(ftepp);
1582 if (ftepp->output_on) {
1583 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1590 /* break; never reached */
1592 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1595 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1598 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1601 /* Builtins! Don't forget the builtins! */
1602 case TOKEN_INTCONST:
1603 case TOKEN_FLOATCONST:
1604 ftepp_out(ftepp, "#", false);
1607 if (!ftepp_skipspace(ftepp))
1612 static bool ftepp_preprocess(ftepp_t *ftepp)
1615 bool newline = true;
1618 char *expand = NULL;
1621 ftepp->lex->flags.preprocessing = true;
1622 ftepp->lex->flags.mergelines = false;
1623 ftepp->lex->flags.noops = true;
1628 if (ftepp->token >= TOKEN_EOF)
1634 switch (ftepp->token) {
1637 case TOKEN_TYPENAME:
1638 /* is it a predef? */
1639 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1640 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1641 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1642 expand = ftepp_predefs[i].func(ftepp->lex);
1643 ftepp_out(ftepp, expand, false);
1644 ftepp_next(ftepp); /* skip */
1646 mem_d(expand); /* free memory */
1652 if (ftepp->output_on)
1653 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1658 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1662 if (!ftepp_macro_call(ftepp, macro))
1663 ftepp->token = TOKEN_ERROR;
1667 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1671 ftepp->lex->flags.mergelines = true;
1672 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1673 ftepp_error(ftepp, "error in preprocessor directive");
1674 ftepp->token = TOKEN_ERROR;
1677 if (!ftepp_hash(ftepp))
1678 ftepp->token = TOKEN_ERROR;
1679 ftepp->lex->flags.mergelines = false;
1683 ftepp_out(ftepp, "\n", true);
1687 /* same as default but don't set newline=false */
1688 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1693 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1697 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1699 /* force a 0 at the end but don't count it as added to the output */
1700 vec_push(ftepp->output_string, 0);
1701 vec_shrinkby(ftepp->output_string, 1);
1703 return (ftepp->token == TOKEN_EOF);
1706 /* Like in parser.c - files keep the previous state so we have one global
1707 * preprocessor. Except here we will want to warn about dangling #ifs.
1709 static ftepp_t *ftepp;
1711 static bool ftepp_preprocess_done()
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(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();
1740 bool ftepp_preprocess_string(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();
1754 void ftepp_add_macro(const char *name, const char *value) {
1755 char *create = NULL;
1757 /* use saner path for empty macros */
1759 ftepp_add_define("__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("__builtin__", create);
1778 ftepp = ftepp_new();
1782 memset(minor, 0, sizeof(minor));
1783 memset(major, 0, sizeof(major));
1785 /* set the right macro based on the selected standard */
1786 ftepp_add_define(NULL, "GMQCC");
1787 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1788 ftepp_add_define(NULL, "__STD_FTEQCC__");
1797 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1798 ftepp_add_define(NULL, "__STD_GMQCC__");
1799 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1800 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1801 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1802 ftepp_add_define(NULL, "__STD_QCCX__");
1803 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1804 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1805 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1806 ftepp_add_define(NULL, "__STD_QCC__");
1817 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1818 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1823 void ftepp_add_define(const char *source, const char *name)
1826 lex_ctx ctx = { "__builtin__", 0 };
1828 macro = ppmacro_new(ctx, name);
1829 vec_push(ftepp->macros, macro);
1832 const char *ftepp_get()
1834 return ftepp->output_string;
1839 ftepp_flush_do(ftepp);
1846 ftepp_delete(ftepp);