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 = 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 = 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 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__"))
412 ftepp->token = TOKEN_VA_ARGS;
413 ptok = pptoken_make(ftepp);
414 vec_push(macro->output, ptok);
417 /* recursive expansion can cause EOFs here */
418 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
419 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
425 static bool ftepp_define(ftepp_t *ftepp)
428 size_t l = ftepp_ctx(ftepp).line;
430 (void)ftepp_next(ftepp);
431 if (!ftepp_skipspace(ftepp))
434 switch (ftepp->token) {
438 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
439 if (macro && ftepp->output_on) {
440 if (ftepp_warn(ftepp, WARN_PREPROCESSOR, "redefining `%s`", ftepp_tokval(ftepp)))
442 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
444 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
447 ftepp_error(ftepp, "expected macro name");
451 (void)ftepp_next(ftepp);
453 if (ftepp->token == '(') {
454 macro->has_params = true;
455 if (!ftepp_define_params(ftepp, macro))
459 if (!ftepp_skipspace(ftepp))
462 if (!ftepp_define_body(ftepp, macro))
465 if (ftepp->output_on)
466 vec_push(ftepp->macros, macro);
468 ppmacro_delete(macro);
471 for (; l < ftepp_ctx(ftepp).line; ++l)
472 ftepp_out(ftepp, "\n", true);
477 * When a macro is used we have to handle parameters as well
478 * as special-concatenation via ## or stringification via #
480 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
481 * this kind of parens. Curly braces or [] don't count towards the
488 static void macroparam_clean(macroparam *self)
491 for (i = 0; i < vec_size(self->tokens); ++i)
492 pptoken_delete(self->tokens[i]);
493 vec_free(self->tokens);
496 /* need to leave the last token up */
497 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
499 macroparam *params = NULL;
505 if (!ftepp_skipallwhite(ftepp))
507 while (ftepp->token != ')') {
509 if (!ftepp_skipallwhite(ftepp))
511 while (parens || ftepp->token != ',') {
512 if (ftepp->token == '(')
514 else if (ftepp->token == ')') {
519 ptok = pptoken_make(ftepp);
520 vec_push(mp.tokens, ptok);
521 if (ftepp_next(ftepp) >= TOKEN_EOF) {
522 ftepp_error(ftepp, "unexpected EOF in macro call");
526 vec_push(params, mp);
528 if (ftepp->token == ')')
530 if (ftepp->token != ',') {
531 ftepp_error(ftepp, "expected closing paren or comma in macro call");
534 if (ftepp_next(ftepp) >= TOKEN_EOF) {
535 ftepp_error(ftepp, "unexpected EOF in macro call");
539 /* need to leave that up
540 if (ftepp_next(ftepp) >= TOKEN_EOF) {
541 ftepp_error(ftepp, "unexpected EOF in macro call");
545 *out_params = params;
550 macroparam_clean(&mp);
551 for (i = 0; i < vec_size(params); ++i)
552 macroparam_clean(¶ms[i]);
557 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
560 for (i = 0; i < vec_size(macro->params); ++i) {
561 if (!strcmp(macro->params[i], name)) {
569 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
574 switch (token->token) {
575 case TOKEN_STRINGCONST:
578 /* in preprocessor mode strings already are string,
579 * so we don't get actual newline bytes here.
580 * Still need to escape backslashes and quotes.
583 case '\\': ftepp_out(ftepp, "\\\\", false); break;
584 case '"': ftepp_out(ftepp, "\\\"", false); break;
587 ftepp_out(ftepp, chs, false);
594 ftepp_out(ftepp, " ", false);
597 ftepp_out(ftepp, "\\n", false);
600 ftepp_out(ftepp, token->value, false);
605 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
608 ftepp_out(ftepp, "\"", false);
609 for (i = 0; i < vec_size(param->tokens); ++i)
610 ftepp_stringify_token(ftepp, param->tokens[i]);
611 ftepp_out(ftepp, "\"", false);
614 static void ftepp_recursion_header(ftepp_t *ftepp)
616 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
619 static void ftepp_recursion_footer(ftepp_t *ftepp)
621 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
624 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
628 for (i = 0; i < vec_size(param->tokens); ++i) {
629 out = param->tokens[i];
630 if (out->token == TOKEN_EOL)
631 ftepp_out(ftepp, "\n", false);
633 ftepp_out(ftepp, out->value, false);
637 static bool ftepp_preprocess(ftepp_t *ftepp);
638 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
640 char *old_string = ftepp->output_string;
641 lex_file *old_lexer = ftepp->lex;
642 size_t vararg_start = vec_size(macro->params);
654 if (vararg_start < vec_size(params))
655 varargs = vec_size(params) - vararg_start;
660 if (!vec_size(macro->output))
663 ftepp->output_string = NULL;
664 for (o = 0; o < vec_size(macro->output); ++o) {
665 pptoken *out = macro->output[o];
666 switch (out->token) {
668 if (!macro->variadic) {
669 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
675 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
676 for (++pi; pi < varargs; ++pi) {
677 ftepp_out(ftepp, ", ", false);
678 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
684 if (!macro_params_find(macro, out->value, &pi)) {
685 ftepp_out(ftepp, out->value, false);
688 ftepp_param_out(ftepp, ¶ms[pi]);
691 if (o + 1 < vec_size(macro->output)) {
692 nextok = macro->output[o+1]->token;
694 /* raw concatenation */
698 if ( (nextok == TOKEN_IDENT ||
699 nextok == TOKEN_KEYWORD ||
700 nextok == TOKEN_TYPENAME) &&
701 macro_params_find(macro, macro->output[o+1]->value, &pi))
704 ftepp_stringify(ftepp, ¶ms[pi]);
708 ftepp_out(ftepp, "#", false);
711 ftepp_out(ftepp, "\n", false);
714 ftepp_out(ftepp, out->value, false);
718 vec_push(ftepp->output_string, 0);
719 has_newlines = (strchr(ftepp->output_string, '\n') != NULL);
720 /* Now run the preprocessor recursively on this string buffer */
722 printf("__________\n%s\n=========\n", ftepp->output_string);
724 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
726 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
730 ftepp->output_string = old_string;
731 inlex->line = ftepp->lex->line;
732 inlex->sline = ftepp->lex->sline;
734 if (has_newlines && !ftepp->in_macro)
735 ftepp_recursion_header(ftepp);
736 old_inmacro = ftepp->in_macro;
737 ftepp->in_macro = true;
738 if (!ftepp_preprocess(ftepp)) {
739 ftepp->in_macro = old_inmacro;
740 vec_free(ftepp->lex->open_string);
741 old_string = ftepp->output_string;
742 lex_close(ftepp->lex);
746 ftepp->in_macro = old_inmacro;
747 vec_free(ftepp->lex->open_string);
748 if (has_newlines && !ftepp->in_macro)
749 ftepp_recursion_footer(ftepp);
750 if (resetline && !ftepp->in_macro) {
752 sprintf(lineno, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
753 ftepp_out(ftepp, lineno, false);
755 old_string = ftepp->output_string;
758 ftepp->lex = old_lexer;
759 ftepp->output_string = old_string;
763 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
766 macroparam *params = NULL;
770 if (!macro->has_params) {
771 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
778 if (!ftepp_skipallwhite(ftepp))
781 if (ftepp->token != '(') {
782 ftepp_error(ftepp, "expected macro parameters in parenthesis");
787 paramline = ftepp->lex->sline;
788 if (!ftepp_macro_call_params(ftepp, ¶ms))
791 if ( vec_size(params) < vec_size(macro->params) ||
792 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
794 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
795 (macro->variadic ? " at least" : ""),
796 (unsigned int)vec_size(macro->params),
797 (unsigned int)vec_size(params));
802 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
807 for (o = 0; o < vec_size(params); ++o)
808 macroparam_clean(¶ms[o]);
814 * #if - the FTEQCC way:
815 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
816 * <numbers> => True if the number is not 0
817 * !<factor> => True if the factor yields false
818 * !!<factor> => ERROR on 2 or more unary nots
819 * <macro> => becomes the macro's FIRST token regardless of parameters
820 * <e> && <e> => True if both expressions are true
821 * <e> || <e> => True if either expression is true
823 * <ident> => False (remember for macros the <macro> rule applies instead)
824 * Unary + and - are weird and wrong in fteqcc so we don't allow them
825 * parenthesis in expressions are allowed
826 * parameter lists on macros are errors
827 * No mathematical calculations are executed
829 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
830 static bool ftepp_if_op(ftepp_t *ftepp)
832 ftepp->lex->flags.noops = false;
834 if (!ftepp_skipspace(ftepp))
836 ftepp->lex->flags.noops = true;
839 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
845 if (!ftepp_skipspace(ftepp))
848 while (ftepp->token == '!') {
851 if (!ftepp_skipspace(ftepp))
855 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
859 if (!ftepp_skipspace(ftepp))
863 switch (ftepp->token) {
867 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
869 if (!ftepp_skipspace(ftepp))
871 if (ftepp->token != '(') {
872 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
876 if (!ftepp_skipspace(ftepp))
878 if (ftepp->token != TOKEN_IDENT &&
879 ftepp->token != TOKEN_TYPENAME &&
880 ftepp->token != TOKEN_KEYWORD)
882 ftepp_error(ftepp, "defined() used on an unexpected token type");
885 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
888 if (!ftepp_skipspace(ftepp))
890 if (ftepp->token != ')') {
891 ftepp_error(ftepp, "expected closing paren");
897 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
898 if (!macro || !vec_size(macro->output)) {
902 /* This does not expand recursively! */
903 switch (macro->output[0]->token) {
905 *value_out = macro->output[0]->constval.i;
906 *out = !!(macro->output[0]->constval.i);
908 case TOKEN_FLOATCONST:
909 *value_out = macro->output[0]->constval.f;
910 *out = !!(macro->output[0]->constval.f);
918 case TOKEN_STRINGCONST:
923 *value_out = ftepp->lex->tok.constval.i;
924 *out = !!(ftepp->lex->tok.constval.i);
926 case TOKEN_FLOATCONST:
927 *value_out = ftepp->lex->tok.constval.f;
928 *out = !!(ftepp->lex->tok.constval.f);
933 if (!ftepp_if_expr(ftepp, out, value_out))
935 if (ftepp->token != ')') {
936 ftepp_error(ftepp, "expected closing paren in #if expression");
942 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
944 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
948 *value_out = -*value_out;
951 *value_out = (*out ? 1 : 0);
957 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
959 if (!ftepp_next(ftepp))
961 return ftepp_if_value(ftepp, out, value_out);
965 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
967 if (!ftepp_if_value(ftepp, out, value_out))
970 if (!ftepp_if_op(ftepp))
973 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
976 /* FTEQCC is all right-associative and no precedence here */
977 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
978 !strcmp(ftepp_tokval(ftepp), "||"))
981 char opc = ftepp_tokval(ftepp)[0];
985 if (!ftepp_next(ftepp))
987 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
995 *value_out = (*out ? 1 : 0);
998 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
999 !strcmp(ftepp_tokval(ftepp), "!=") ||
1000 !strcmp(ftepp_tokval(ftepp), ">=") ||
1001 !strcmp(ftepp_tokval(ftepp), "<=") ||
1002 !strcmp(ftepp_tokval(ftepp), ">") ||
1003 !strcmp(ftepp_tokval(ftepp), "<"))
1006 const char opc0 = ftepp_tokval(ftepp)[0];
1007 const char opc1 = ftepp_tokval(ftepp)[1];
1010 if (!ftepp_next(ftepp))
1012 if (!ftepp_if_expr(ftepp, &next, &other))
1016 *out = (*value_out == other);
1017 else if (opc0 == '!')
1018 *out = (*value_out != other);
1019 else if (opc0 == '>') {
1020 if (opc1 == '=') *out = (*value_out >= other);
1021 else *out = (*value_out > other);
1023 else if (opc0 == '<') {
1024 if (opc1 == '=') *out = (*value_out <= other);
1025 else *out = (*value_out < other);
1027 *value_out = (*out ? 1 : 0);
1032 ftepp_error(ftepp, "junk after #if");
1037 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1039 bool result = false;
1042 memset(cond, 0, sizeof(*cond));
1043 (void)ftepp_next(ftepp);
1045 if (!ftepp_skipspace(ftepp))
1047 if (ftepp->token == TOKEN_EOL) {
1048 ftepp_error(ftepp, "expected expression for #if-directive");
1052 if (!ftepp_if_expr(ftepp, &result, &dummy))
1060 * ifdef is rather simple
1062 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1065 memset(cond, 0, sizeof(*cond));
1066 (void)ftepp_next(ftepp);
1067 if (!ftepp_skipspace(ftepp))
1070 switch (ftepp->token) {
1072 case TOKEN_TYPENAME:
1074 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1077 ftepp_error(ftepp, "expected macro name");
1081 (void)ftepp_next(ftepp);
1082 if (!ftepp_skipspace(ftepp))
1084 /* relaxing this condition
1085 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1086 ftepp_error(ftepp, "stray tokens after #ifdef");
1095 * undef is also simple
1097 static bool ftepp_undef(ftepp_t *ftepp)
1099 (void)ftepp_next(ftepp);
1100 if (!ftepp_skipspace(ftepp))
1103 if (ftepp->output_on) {
1104 switch (ftepp->token) {
1106 case TOKEN_TYPENAME:
1108 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1111 ftepp_error(ftepp, "expected macro name");
1116 (void)ftepp_next(ftepp);
1117 if (!ftepp_skipspace(ftepp))
1119 /* relaxing this condition
1120 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1121 ftepp_error(ftepp, "stray tokens after #ifdef");
1128 /* Special unescape-string function which skips a leading quote
1129 * and stops at a quote, not just at \0
1131 static void unescape(const char *str, char *out) {
1133 while (*str && *str != '"') {
1137 case '\\': *out++ = *str; break;
1138 case '"': *out++ = *str; break;
1139 case 'a': *out++ = '\a'; break;
1140 case 'b': *out++ = '\b'; break;
1141 case 'r': *out++ = '\r'; break;
1142 case 'n': *out++ = '\n'; break;
1143 case 't': *out++ = '\t'; break;
1144 case 'f': *out++ = '\f'; break;
1145 case 'v': *out++ = '\v'; break;
1160 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1163 char *filename = NULL;
1164 const char *last_slash;
1170 last_slash = strrchr(pathfile, '/');
1173 len = last_slash - pathfile;
1174 memcpy(vec_add(filename, len), pathfile, len);
1175 vec_push(filename, '/');
1179 memcpy(vec_add(filename, len+1), file, len);
1180 vec_last(filename) = 0;
1182 fp = file_open(filename, "rb");
1191 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1193 char *filename = NULL;
1195 filename = ftepp_include_find_path(file, ftepp->includename);
1197 filename = ftepp_include_find_path(file, ftepp->itemname);
1201 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1202 char *message = NULL;
1204 if (!ftepp_skipspace(ftepp))
1207 /* handle the odd non string constant case so it works like C */
1208 if (ftepp->token != TOKEN_STRINGCONST) {
1210 vec_upload(message, "#warning", 8);
1212 while (ftepp->token != TOKEN_EOL) {
1213 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1216 vec_push(message, '\0');
1217 store = ftepp_warn(ftepp, WARN_CPP, message);
1222 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1223 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1226 static void ftepp_directive_error(ftepp_t *ftepp) {
1227 char *message = NULL;
1229 if (!ftepp_skipspace(ftepp))
1232 /* handle the odd non string constant case so it works like C */
1233 if (ftepp->token != TOKEN_STRINGCONST) {
1234 vec_upload(message, "#error", 6);
1236 while (ftepp->token != TOKEN_EOL) {
1237 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1240 vec_push(message, '\0');
1241 ftepp_error(ftepp, message);
1246 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1247 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1252 * FIXME: do we need/want a -I option?
1253 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1255 static bool ftepp_include(ftepp_t *ftepp)
1257 lex_file *old_lexer = ftepp->lex;
1262 char *old_includename;
1264 (void)ftepp_next(ftepp);
1265 if (!ftepp_skipspace(ftepp))
1268 if (ftepp->token != TOKEN_STRINGCONST) {
1269 ftepp_error(ftepp, "expected filename to include");
1273 ctx = ftepp_ctx(ftepp);
1275 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1277 ftepp_out(ftepp, "\n#pragma file(", false);
1278 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1279 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1281 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1283 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1286 inlex = lex_open(filename);
1288 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1293 old_includename = ftepp->includename;
1294 ftepp->includename = filename;
1295 if (!ftepp_preprocess(ftepp)) {
1296 vec_free(ftepp->includename);
1297 ftepp->includename = old_includename;
1298 lex_close(ftepp->lex);
1299 ftepp->lex = old_lexer;
1302 vec_free(ftepp->includename);
1303 ftepp->includename = old_includename;
1304 lex_close(ftepp->lex);
1305 ftepp->lex = old_lexer;
1307 ftepp_out(ftepp, "\n#pragma file(", false);
1308 ftepp_out(ftepp, ctx.file, false);
1309 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1310 ftepp_out(ftepp, lineno, false);
1313 (void)ftepp_next(ftepp);
1314 if (!ftepp_skipspace(ftepp))
1316 if (ftepp->token != TOKEN_EOL) {
1317 ftepp_error(ftepp, "stray tokens after #include");
1320 (void)ftepp_next(ftepp);
1325 /* Basic structure handlers */
1326 static bool ftepp_else_allowed(ftepp_t *ftepp)
1328 if (!vec_size(ftepp->conditions)) {
1329 ftepp_error(ftepp, "#else without #if");
1332 if (vec_last(ftepp->conditions).had_else) {
1333 ftepp_error(ftepp, "multiple #else for a single #if");
1339 static bool ftepp_hash(ftepp_t *ftepp)
1344 lex_ctx ctx = ftepp_ctx(ftepp);
1346 if (!ftepp_skipspace(ftepp))
1349 switch (ftepp->token) {
1352 case TOKEN_TYPENAME:
1353 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1354 return ftepp_define(ftepp);
1356 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1357 return ftepp_undef(ftepp);
1359 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1360 if (!ftepp_ifdef(ftepp, &cond))
1362 cond.was_on = cond.on;
1363 vec_push(ftepp->conditions, cond);
1364 ftepp->output_on = ftepp->output_on && cond.on;
1367 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1368 if (!ftepp_ifdef(ftepp, &cond))
1371 cond.was_on = cond.on;
1372 vec_push(ftepp->conditions, cond);
1373 ftepp->output_on = ftepp->output_on && cond.on;
1376 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1377 if (!ftepp_else_allowed(ftepp))
1379 if (!ftepp_ifdef(ftepp, &cond))
1381 pc = &vec_last(ftepp->conditions);
1382 pc->on = !pc->was_on && cond.on;
1383 pc->was_on = pc->was_on || pc->on;
1384 ftepp_update_output_condition(ftepp);
1387 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1388 if (!ftepp_else_allowed(ftepp))
1390 if (!ftepp_ifdef(ftepp, &cond))
1393 pc = &vec_last(ftepp->conditions);
1394 pc->on = !pc->was_on && cond.on;
1395 pc->was_on = pc->was_on || pc->on;
1396 ftepp_update_output_condition(ftepp);
1399 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1400 if (!ftepp_else_allowed(ftepp))
1402 if (!ftepp_if(ftepp, &cond))
1404 pc = &vec_last(ftepp->conditions);
1405 pc->on = !pc->was_on && cond.on;
1406 pc->was_on = pc->was_on || pc->on;
1407 ftepp_update_output_condition(ftepp);
1410 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1411 if (!ftepp_if(ftepp, &cond))
1413 cond.was_on = cond.on;
1414 vec_push(ftepp->conditions, cond);
1415 ftepp->output_on = ftepp->output_on && cond.on;
1418 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1419 if (!ftepp_else_allowed(ftepp))
1421 pc = &vec_last(ftepp->conditions);
1422 pc->on = !pc->was_on;
1423 pc->had_else = true;
1425 ftepp_update_output_condition(ftepp);
1428 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1429 if (!vec_size(ftepp->conditions)) {
1430 ftepp_error(ftepp, "#endif without #if");
1433 vec_pop(ftepp->conditions);
1435 ftepp_update_output_condition(ftepp);
1438 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1439 return ftepp_include(ftepp);
1441 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1442 ftepp_out(ftepp, "#", false);
1445 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1446 ftepp_directive_warning(ftepp);
1449 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1450 ftepp_directive_error(ftepp);
1454 if (ftepp->output_on) {
1455 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1462 /* break; never reached */
1464 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1467 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1470 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1473 /* Builtins! Don't forget the builtins! */
1474 case TOKEN_INTCONST:
1475 case TOKEN_FLOATCONST:
1476 ftepp_out(ftepp, "#", false);
1479 if (!ftepp_skipspace(ftepp))
1484 static bool ftepp_preprocess(ftepp_t *ftepp)
1487 bool newline = true;
1490 char *expand = NULL;
1493 ftepp->lex->flags.preprocessing = true;
1494 ftepp->lex->flags.mergelines = false;
1495 ftepp->lex->flags.noops = true;
1500 if (ftepp->token >= TOKEN_EOF)
1506 switch (ftepp->token) {
1509 case TOKEN_TYPENAME:
1510 /* is it a predef? */
1511 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1512 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1513 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1514 expand = ftepp_predefs[i].func(ftepp->lex);
1515 ftepp_out(ftepp, expand, false);
1516 ftepp_next(ftepp); /* skip */
1518 mem_d(expand); /* free memory */
1524 if (ftepp->output_on)
1525 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1530 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1534 if (!ftepp_macro_call(ftepp, macro))
1535 ftepp->token = TOKEN_ERROR;
1539 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1543 ftepp->lex->flags.mergelines = true;
1544 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1545 ftepp_error(ftepp, "error in preprocessor directive");
1546 ftepp->token = TOKEN_ERROR;
1549 if (!ftepp_hash(ftepp))
1550 ftepp->token = TOKEN_ERROR;
1551 ftepp->lex->flags.mergelines = false;
1555 ftepp_out(ftepp, "\n", true);
1559 /* same as default but don't set newline=false */
1560 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1565 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1569 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1571 /* force a 0 at the end but don't count it as added to the output */
1572 vec_push(ftepp->output_string, 0);
1573 vec_shrinkby(ftepp->output_string, 1);
1575 return (ftepp->token == TOKEN_EOF);
1578 /* Like in parser.c - files keep the previous state so we have one global
1579 * preprocessor. Except here we will want to warn about dangling #ifs.
1581 static ftepp_t *ftepp;
1583 static bool ftepp_preprocess_done()
1586 if (vec_size(ftepp->conditions)) {
1587 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1590 lex_close(ftepp->lex);
1592 if (ftepp->itemname) {
1593 mem_d(ftepp->itemname);
1594 ftepp->itemname = NULL;
1599 bool ftepp_preprocess_file(const char *filename)
1601 ftepp->lex = lex_open(filename);
1602 ftepp->itemname = util_strdup(filename);
1604 con_out("failed to open file \"%s\"\n", filename);
1607 if (!ftepp_preprocess(ftepp))
1609 return ftepp_preprocess_done();
1612 bool ftepp_preprocess_string(const char *name, const char *str)
1614 ftepp->lex = lex_open_string(str, strlen(str), name);
1615 ftepp->itemname = util_strdup(name);
1617 con_out("failed to create lexer for string \"%s\"\n", name);
1620 if (!ftepp_preprocess(ftepp))
1622 return ftepp_preprocess_done();
1626 void ftepp_add_macro(const char *name, const char *value) {
1627 char *create = NULL;
1629 /* use saner path for empty macros */
1631 ftepp_add_define("__builtin__", name);
1635 vec_upload(create, "#define ", 8);
1636 vec_upload(create, name, strlen(name));
1637 vec_push (create, ' ');
1638 vec_upload(create, value, strlen(value));
1639 vec_push (create, 0);
1641 ftepp_preprocess_string("__builtin__", create);
1650 ftepp = ftepp_new();
1654 memset(minor, 0, sizeof(minor));
1655 memset(major, 0, sizeof(major));
1657 /* set the right macro based on the selected standard */
1658 ftepp_add_define(NULL, "GMQCC");
1659 if (opts.standard == COMPILER_FTEQCC) {
1660 ftepp_add_define(NULL, "__STD_FTEQCC__");
1669 } else if (opts.standard == COMPILER_GMQCC) {
1670 ftepp_add_define(NULL, "__STD_GMQCC__");
1671 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1672 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1673 } else if (opts.standard == COMPILER_QCCX) {
1674 ftepp_add_define(NULL, "__STD_QCCX__");
1675 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1676 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1677 } else if (opts.standard == COMPILER_QCC) {
1678 ftepp_add_define(NULL, "__STD_QCC__");
1689 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1690 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1695 void ftepp_add_define(const char *source, const char *name)
1698 lex_ctx ctx = { "__builtin__", 0 };
1700 macro = ppmacro_new(ctx, name);
1701 vec_push(ftepp->macros, macro);
1704 const char *ftepp_get()
1706 return ftepp->output_string;
1711 ftepp_flush_do(ftepp);
1718 ftepp_delete(ftepp);