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
36 /* a copy from the lexer */
50 /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
63 ppcondition *conditions;
74 char *(*func)(lex_file *);
78 * Implement the predef subsystem now. We can do this safely with the
79 * help of lexer contexts.
81 static uint32_t ftepp_predef_countval = 0;
82 static uint32_t ftepp_predef_randval = 0;
85 char *ftepp_predef_line(lex_file *context) {
87 util_asprintf(&value, "%d", (int)context->line);
91 char *ftepp_predef_file(lex_file *context) {
92 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
93 char *value = (char*)mem_a(length);
94 memset (value, 0, length);
95 sprintf(value, "\"%s\"", context->name);
99 /* __COUNTER_LAST__ */
100 char *ftepp_predef_counterlast(lex_file *context) {
102 util_asprintf(&value, "%u", ftepp_predef_countval);
108 char *ftepp_predef_counter(lex_file *context) {
110 ftepp_predef_countval ++;
111 util_asprintf(&value, "%u", ftepp_predef_countval);
117 char *ftepp_predef_random(lex_file *context) {
119 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
120 util_asprintf(&value, "%u", ftepp_predef_randval);
125 /* __RANDOM_LAST__ */
126 char *ftepp_predef_randomlast(lex_file *context) {
128 util_asprintf(&value, "%u", ftepp_predef_randval);
134 static const predef_t ftepp_predefs[] = {
135 { "__LINE__", &ftepp_predef_line },
136 { "__FILE__", &ftepp_predef_file },
137 { "__COUNTER__", &ftepp_predef_counter },
138 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
139 { "__RANDOM__", &ftepp_predef_random },
140 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
143 #define ftepp_tokval(f) ((f)->lex->tok.value)
144 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
146 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx ctx, const char *fmt, ...)
153 con_cvprintmsg((void*)&ctx, LVL_ERROR, "error", fmt, ap);
157 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
164 con_cvprintmsg((void*)&ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
168 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
174 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
179 static pptoken *pptoken_make(ftepp_t *ftepp)
181 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
182 token->token = ftepp->token;
184 if (token->token == TOKEN_WHITE)
185 token->value = util_strdup(" ");
188 token->value = util_strdup(ftepp_tokval(ftepp));
190 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
194 static void pptoken_delete(pptoken *self)
200 static ppmacro *ppmacro_new(lex_ctx ctx, const char *name)
202 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
205 memset(macro, 0, sizeof(*macro));
206 macro->name = util_strdup(name);
210 static void ppmacro_delete(ppmacro *self)
213 for (i = 0; i < vec_size(self->params); ++i)
214 mem_d(self->params[i]);
215 vec_free(self->params);
216 for (i = 0; i < vec_size(self->output); ++i)
217 pptoken_delete(self->output[i]);
218 vec_free(self->output);
223 static ftepp_t* ftepp_new()
227 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
228 memset(ftepp, 0, sizeof(*ftepp));
230 ftepp->output_on = true;
235 static void ftepp_flush_do(ftepp_t *self)
237 vec_free(self->output_string);
240 static void ftepp_delete(ftepp_t *self)
243 ftepp_flush_do(self);
245 mem_d(self->itemname);
246 if (self->includename)
247 vec_free(self->includename);
248 for (i = 0; i < vec_size(self->macros); ++i)
249 ppmacro_delete(self->macros[i]);
250 vec_free(self->macros);
251 vec_free(self->conditions);
253 lex_close(self->lex);
257 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
259 if (ignore_cond || ftepp->output_on)
264 data = vec_add(ftepp->output_string, len);
265 memcpy(data, str, len);
269 static void ftepp_update_output_condition(ftepp_t *ftepp)
272 ftepp->output_on = true;
273 for (i = 0; i < vec_size(ftepp->conditions); ++i)
274 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
277 static ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
280 for (i = 0; i < vec_size(ftepp->macros); ++i) {
281 if (!strcmp(name, ftepp->macros[i]->name))
282 return ftepp->macros[i];
287 static void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
290 for (i = 0; i < vec_size(ftepp->macros); ++i) {
291 if (!strcmp(name, ftepp->macros[i]->name)) {
292 vec_remove(ftepp->macros, i, 1);
298 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
300 return (ftepp->token = lex_do(ftepp->lex));
303 /* Important: this does not skip newlines! */
304 static bool ftepp_skipspace(ftepp_t *ftepp)
306 if (ftepp->token != TOKEN_WHITE)
308 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
309 if (ftepp->token >= TOKEN_EOF) {
310 ftepp_error(ftepp, "unexpected end of preprocessor directive");
316 /* this one skips EOLs as well */
317 static bool ftepp_skipallwhite(ftepp_t *ftepp)
319 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
323 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
324 if (ftepp->token >= TOKEN_EOF) {
325 ftepp_error(ftepp, "unexpected end of preprocessor directive");
332 * The huge macro parsing code...
334 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
338 if (!ftepp_skipspace(ftepp))
340 if (ftepp->token == ')')
342 switch (ftepp->token) {
346 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
349 macro->variadic = true;
352 ftepp_error(ftepp, "unexpected token in parameter list");
356 if (!ftepp_skipspace(ftepp))
358 if (macro->variadic && ftepp->token != ')') {
359 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
362 } while (ftepp->token == ',');
363 if (ftepp->token != ')') {
364 ftepp_error(ftepp, "expected closing paren after macro parameter list");
368 /* skipspace happens in ftepp_define */
372 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
375 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
376 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__"))
377 ftepp->token = TOKEN_VA_ARGS;
378 ptok = pptoken_make(ftepp);
379 vec_push(macro->output, ptok);
382 /* recursive expansion can cause EOFs here */
383 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
384 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
390 static bool ftepp_define(ftepp_t *ftepp)
393 size_t l = ftepp_ctx(ftepp).line;
395 (void)ftepp_next(ftepp);
396 if (!ftepp_skipspace(ftepp))
399 switch (ftepp->token) {
403 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
404 if (macro && ftepp->output_on) {
405 if (ftepp_warn(ftepp, WARN_PREPROCESSOR, "redefining `%s`", ftepp_tokval(ftepp)))
407 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
409 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
412 ftepp_error(ftepp, "expected macro name");
416 (void)ftepp_next(ftepp);
418 if (ftepp->token == '(') {
419 macro->has_params = true;
420 if (!ftepp_define_params(ftepp, macro))
424 if (!ftepp_skipspace(ftepp))
427 if (!ftepp_define_body(ftepp, macro))
430 if (ftepp->output_on)
431 vec_push(ftepp->macros, macro);
433 ppmacro_delete(macro);
436 for (; l < ftepp_ctx(ftepp).line; ++l)
437 ftepp_out(ftepp, "\n", true);
442 * When a macro is used we have to handle parameters as well
443 * as special-concatenation via ## or stringification via #
445 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
446 * this kind of parens. Curly braces or [] don't count towards the
453 static void macroparam_clean(macroparam *self)
456 for (i = 0; i < vec_size(self->tokens); ++i)
457 pptoken_delete(self->tokens[i]);
458 vec_free(self->tokens);
461 /* need to leave the last token up */
462 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
464 macroparam *params = NULL;
470 if (!ftepp_skipallwhite(ftepp))
472 while (ftepp->token != ')') {
474 if (!ftepp_skipallwhite(ftepp))
476 while (parens || ftepp->token != ',') {
477 if (ftepp->token == '(')
479 else if (ftepp->token == ')') {
484 ptok = pptoken_make(ftepp);
485 vec_push(mp.tokens, ptok);
486 if (ftepp_next(ftepp) >= TOKEN_EOF) {
487 ftepp_error(ftepp, "unexpected EOF in macro call");
491 vec_push(params, mp);
493 if (ftepp->token == ')')
495 if (ftepp->token != ',') {
496 ftepp_error(ftepp, "expected closing paren or comma in macro call");
499 if (ftepp_next(ftepp) >= TOKEN_EOF) {
500 ftepp_error(ftepp, "unexpected EOF in macro call");
504 /* need to leave that up
505 if (ftepp_next(ftepp) >= TOKEN_EOF) {
506 ftepp_error(ftepp, "unexpected EOF in macro call");
510 *out_params = params;
515 macroparam_clean(&mp);
516 for (i = 0; i < vec_size(params); ++i)
517 macroparam_clean(¶ms[i]);
522 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
525 for (i = 0; i < vec_size(macro->params); ++i) {
526 if (!strcmp(macro->params[i], name)) {
534 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
539 switch (token->token) {
540 case TOKEN_STRINGCONST:
543 /* in preprocessor mode strings already are string,
544 * so we don't get actual newline bytes here.
545 * Still need to escape backslashes and quotes.
548 case '\\': ftepp_out(ftepp, "\\\\", false); break;
549 case '"': ftepp_out(ftepp, "\\\"", false); break;
552 ftepp_out(ftepp, chs, false);
559 ftepp_out(ftepp, " ", false);
562 ftepp_out(ftepp, "\\n", false);
565 ftepp_out(ftepp, token->value, false);
570 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
573 ftepp_out(ftepp, "\"", false);
574 for (i = 0; i < vec_size(param->tokens); ++i)
575 ftepp_stringify_token(ftepp, param->tokens[i]);
576 ftepp_out(ftepp, "\"", false);
579 static void ftepp_recursion_header(ftepp_t *ftepp)
581 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
584 static void ftepp_recursion_footer(ftepp_t *ftepp)
586 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
589 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
593 for (i = 0; i < vec_size(param->tokens); ++i) {
594 out = param->tokens[i];
595 if (out->token == TOKEN_EOL)
596 ftepp_out(ftepp, "\n", false);
598 ftepp_out(ftepp, out->value, false);
602 static bool ftepp_preprocess(ftepp_t *ftepp);
603 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params)
605 char *old_string = ftepp->output_string;
606 lex_file *old_lexer = ftepp->lex;
607 size_t vararg_start = vec_size(macro->params);
616 if (vararg_start < vec_size(params))
617 varargs = vec_size(params) - vararg_start;
622 if (!vec_size(macro->output))
625 ftepp->output_string = NULL;
626 for (o = 0; o < vec_size(macro->output); ++o) {
627 pptoken *out = macro->output[o];
628 switch (out->token) {
630 if (!macro->variadic) {
631 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
637 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
638 for (++pi; pi < varargs; ++pi) {
639 ftepp_out(ftepp, ", ", false);
640 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
646 if (!macro_params_find(macro, out->value, &pi)) {
647 ftepp_out(ftepp, out->value, false);
650 ftepp_param_out(ftepp, ¶ms[pi]);
653 if (o + 1 < vec_size(macro->output)) {
654 nextok = macro->output[o+1]->token;
656 /* raw concatenation */
660 if ( (nextok == TOKEN_IDENT ||
661 nextok == TOKEN_KEYWORD ||
662 nextok == TOKEN_TYPENAME) &&
663 macro_params_find(macro, macro->output[o+1]->value, &pi))
666 ftepp_stringify(ftepp, ¶ms[pi]);
670 ftepp_out(ftepp, "#", false);
673 ftepp_out(ftepp, "\n", false);
676 ftepp_out(ftepp, out->value, false);
680 vec_push(ftepp->output_string, 0);
681 /* Now run the preprocessor recursively on this string buffer */
683 printf("__________\n%s\n=========\n", ftepp->output_string);
685 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
687 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
691 ftepp->output_string = old_string;
692 inlex->line = ftepp->lex->line;
693 inlex->sline = ftepp->lex->sline;
695 ftepp_recursion_header(ftepp);
696 if (!ftepp_preprocess(ftepp)) {
697 vec_free(ftepp->lex->open_string);
698 old_string = ftepp->output_string;
699 lex_close(ftepp->lex);
703 vec_free(ftepp->lex->open_string);
704 ftepp_recursion_footer(ftepp);
705 old_string = ftepp->output_string;
708 ftepp->lex = old_lexer;
709 ftepp->output_string = old_string;
713 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
716 macroparam *params = NULL;
719 if (!macro->has_params) {
720 if (!ftepp_macro_expand(ftepp, macro, NULL))
727 if (!ftepp_skipallwhite(ftepp))
730 if (ftepp->token != '(') {
731 ftepp_error(ftepp, "expected macro parameters in parenthesis");
736 if (!ftepp_macro_call_params(ftepp, ¶ms))
739 if ( vec_size(params) < vec_size(macro->params) ||
740 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
742 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
743 (macro->variadic ? " at least" : ""),
744 (unsigned int)vec_size(macro->params),
745 (unsigned int)vec_size(params));
750 if (!ftepp_macro_expand(ftepp, macro, params))
755 for (o = 0; o < vec_size(params); ++o)
756 macroparam_clean(¶ms[o]);
762 * #if - the FTEQCC way:
763 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
764 * <numbers> => True if the number is not 0
765 * !<factor> => True if the factor yields false
766 * !!<factor> => ERROR on 2 or more unary nots
767 * <macro> => becomes the macro's FIRST token regardless of parameters
768 * <e> && <e> => True if both expressions are true
769 * <e> || <e> => True if either expression is true
771 * <ident> => False (remember for macros the <macro> rule applies instead)
772 * Unary + and - are weird and wrong in fteqcc so we don't allow them
773 * parenthesis in expressions are allowed
774 * parameter lists on macros are errors
775 * No mathematical calculations are executed
777 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
778 static bool ftepp_if_op(ftepp_t *ftepp)
780 ftepp->lex->flags.noops = false;
782 if (!ftepp_skipspace(ftepp))
784 ftepp->lex->flags.noops = true;
787 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
792 if (!ftepp_skipspace(ftepp))
795 while (ftepp->token == '!') {
798 if (!ftepp_skipspace(ftepp))
802 switch (ftepp->token) {
806 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
808 if (!ftepp_skipspace(ftepp))
810 if (ftepp->token != '(') {
811 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
815 if (!ftepp_skipspace(ftepp))
817 if (ftepp->token != TOKEN_IDENT &&
818 ftepp->token != TOKEN_TYPENAME &&
819 ftepp->token != TOKEN_KEYWORD)
821 ftepp_error(ftepp, "defined() used on an unexpected token type");
824 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
827 if (!ftepp_skipspace(ftepp))
829 if (ftepp->token != ')') {
830 ftepp_error(ftepp, "expected closing paren");
836 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
837 if (!macro || !vec_size(macro->output)) {
841 /* This does not expand recursively! */
842 switch (macro->output[0]->token) {
844 *value_out = macro->output[0]->constval.i;
845 *out = !!(macro->output[0]->constval.i);
847 case TOKEN_FLOATCONST:
848 *value_out = macro->output[0]->constval.f;
849 *out = !!(macro->output[0]->constval.f);
857 case TOKEN_STRINGCONST:
861 *value_out = ftepp->lex->tok.constval.i;
862 *out = !!(ftepp->lex->tok.constval.i);
864 case TOKEN_FLOATCONST:
865 *value_out = ftepp->lex->tok.constval.f;
866 *out = !!(ftepp->lex->tok.constval.f);
871 if (!ftepp_if_expr(ftepp, out, value_out))
873 if (ftepp->token != ')') {
874 ftepp_error(ftepp, "expected closing paren in #if expression");
880 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
885 *value_out = (*out ? 1 : 0);
891 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
893 if (!ftepp_next(ftepp))
895 return ftepp_if_value(ftepp, out, value_out);
899 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
901 if (!ftepp_if_value(ftepp, out, value_out))
904 if (!ftepp_if_op(ftepp))
907 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
910 /* FTEQCC is all right-associative and no precedence here */
911 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
912 !strcmp(ftepp_tokval(ftepp), "||"))
915 char opc = ftepp_tokval(ftepp)[0];
919 if (!ftepp_next(ftepp))
921 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
929 *value_out = (*out ? 1 : 0);
932 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
933 !strcmp(ftepp_tokval(ftepp), "!=") ||
934 !strcmp(ftepp_tokval(ftepp), ">=") ||
935 !strcmp(ftepp_tokval(ftepp), "<=") ||
936 !strcmp(ftepp_tokval(ftepp), ">") ||
937 !strcmp(ftepp_tokval(ftepp), "<"))
940 const char opc0 = ftepp_tokval(ftepp)[0];
941 const char opc1 = ftepp_tokval(ftepp)[1];
944 if (!ftepp_next(ftepp))
946 if (!ftepp_if_expr(ftepp, &next, &other))
950 *out = (*value_out == other);
951 else if (opc0 == '!')
952 *out = (*value_out != other);
953 else if (opc0 == '>') {
954 if (opc1 == '=') *out = (*value_out >= other);
955 else *out = (*value_out > other);
957 else if (opc0 == '<') {
958 if (opc1 == '=') *out = (*value_out <= other);
959 else *out = (*value_out < other);
961 *value_out = (*out ? 1 : 0);
966 ftepp_error(ftepp, "junk after #if");
971 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
976 memset(cond, 0, sizeof(*cond));
977 (void)ftepp_next(ftepp);
979 if (!ftepp_skipspace(ftepp))
981 if (ftepp->token == TOKEN_EOL) {
982 ftepp_error(ftepp, "expected expression for #if-directive");
986 if (!ftepp_if_expr(ftepp, &result, &dummy))
994 * ifdef is rather simple
996 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
999 memset(cond, 0, sizeof(*cond));
1000 (void)ftepp_next(ftepp);
1001 if (!ftepp_skipspace(ftepp))
1004 switch (ftepp->token) {
1006 case TOKEN_TYPENAME:
1008 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1011 ftepp_error(ftepp, "expected macro name");
1015 (void)ftepp_next(ftepp);
1016 if (!ftepp_skipspace(ftepp))
1018 /* relaxing this condition
1019 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1020 ftepp_error(ftepp, "stray tokens after #ifdef");
1029 * undef is also simple
1031 static bool ftepp_undef(ftepp_t *ftepp)
1033 (void)ftepp_next(ftepp);
1034 if (!ftepp_skipspace(ftepp))
1037 if (ftepp->output_on) {
1038 switch (ftepp->token) {
1040 case TOKEN_TYPENAME:
1042 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1045 ftepp_error(ftepp, "expected macro name");
1050 (void)ftepp_next(ftepp);
1051 if (!ftepp_skipspace(ftepp))
1053 /* relaxing this condition
1054 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1055 ftepp_error(ftepp, "stray tokens after #ifdef");
1062 /* Special unescape-string function which skips a leading quote
1063 * and stops at a quote, not just at \0
1065 static void unescape(const char *str, char *out) {
1067 while (*str && *str != '"') {
1071 case '\\': *out++ = *str; break;
1072 case '"': *out++ = *str; break;
1073 case 'a': *out++ = '\a'; break;
1074 case 'b': *out++ = '\b'; break;
1075 case 'r': *out++ = '\r'; break;
1076 case 'n': *out++ = '\n'; break;
1077 case 't': *out++ = '\t'; break;
1078 case 'f': *out++ = '\f'; break;
1079 case 'v': *out++ = '\v'; break;
1094 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1097 char *filename = NULL;
1098 const char *last_slash;
1104 last_slash = strrchr(pathfile, '/');
1107 len = last_slash - pathfile;
1108 memcpy(vec_add(filename, len), pathfile, len);
1109 vec_push(filename, '/');
1113 memcpy(vec_add(filename, len+1), file, len);
1114 vec_last(filename) = 0;
1116 fp = file_open(filename, "rb");
1125 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1127 char *filename = NULL;
1129 filename = ftepp_include_find_path(file, ftepp->includename);
1131 filename = ftepp_include_find_path(file, ftepp->itemname);
1135 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1136 char *message = NULL;
1138 if (!ftepp_skipspace(ftepp))
1141 /* handle the odd non string constant case so it works like C */
1142 if (ftepp->token != TOKEN_STRINGCONST) {
1144 vec_upload(message, "#warning", 8);
1146 while (ftepp->token != TOKEN_EOL) {
1147 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1150 vec_push(message, '\0');
1151 store = ftepp_warn(ftepp, WARN_CPP, message);
1156 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1157 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1160 static void ftepp_directive_error(ftepp_t *ftepp) {
1161 char *message = NULL;
1163 if (!ftepp_skipspace(ftepp))
1166 /* handle the odd non string constant case so it works like C */
1167 if (ftepp->token != TOKEN_STRINGCONST) {
1168 vec_upload(message, "#error", 6);
1170 while (ftepp->token != TOKEN_EOL) {
1171 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1174 vec_push(message, '\0');
1175 ftepp_error(ftepp, message);
1180 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1181 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1186 * FIXME: do we need/want a -I option?
1187 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1189 static bool ftepp_include(ftepp_t *ftepp)
1191 lex_file *old_lexer = ftepp->lex;
1196 char *old_includename;
1198 (void)ftepp_next(ftepp);
1199 if (!ftepp_skipspace(ftepp))
1202 if (ftepp->token != TOKEN_STRINGCONST) {
1203 ftepp_error(ftepp, "expected filename to include");
1207 ctx = ftepp_ctx(ftepp);
1209 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1211 ftepp_out(ftepp, "\n#pragma file(", false);
1212 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1213 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1215 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1217 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1220 inlex = lex_open(filename);
1222 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1227 old_includename = ftepp->includename;
1228 ftepp->includename = filename;
1229 if (!ftepp_preprocess(ftepp)) {
1230 vec_free(ftepp->includename);
1231 ftepp->includename = old_includename;
1232 lex_close(ftepp->lex);
1233 ftepp->lex = old_lexer;
1236 vec_free(ftepp->includename);
1237 ftepp->includename = old_includename;
1238 lex_close(ftepp->lex);
1239 ftepp->lex = old_lexer;
1241 ftepp_out(ftepp, "\n#pragma file(", false);
1242 ftepp_out(ftepp, ctx.file, false);
1243 snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1244 ftepp_out(ftepp, lineno, false);
1247 (void)ftepp_next(ftepp);
1248 if (!ftepp_skipspace(ftepp))
1250 if (ftepp->token != TOKEN_EOL) {
1251 ftepp_error(ftepp, "stray tokens after #include");
1254 (void)ftepp_next(ftepp);
1259 /* Basic structure handlers */
1260 static bool ftepp_else_allowed(ftepp_t *ftepp)
1262 if (!vec_size(ftepp->conditions)) {
1263 ftepp_error(ftepp, "#else without #if");
1266 if (vec_last(ftepp->conditions).had_else) {
1267 ftepp_error(ftepp, "multiple #else for a single #if");
1273 static bool ftepp_hash(ftepp_t *ftepp)
1278 lex_ctx ctx = ftepp_ctx(ftepp);
1280 if (!ftepp_skipspace(ftepp))
1283 switch (ftepp->token) {
1286 case TOKEN_TYPENAME:
1287 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1288 return ftepp_define(ftepp);
1290 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1291 return ftepp_undef(ftepp);
1293 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1294 if (!ftepp_ifdef(ftepp, &cond))
1296 cond.was_on = cond.on;
1297 vec_push(ftepp->conditions, cond);
1298 ftepp->output_on = ftepp->output_on && cond.on;
1301 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1302 if (!ftepp_ifdef(ftepp, &cond))
1305 cond.was_on = cond.on;
1306 vec_push(ftepp->conditions, cond);
1307 ftepp->output_on = ftepp->output_on && cond.on;
1310 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1311 if (!ftepp_else_allowed(ftepp))
1313 if (!ftepp_ifdef(ftepp, &cond))
1315 pc = &vec_last(ftepp->conditions);
1316 pc->on = !pc->was_on && cond.on;
1317 pc->was_on = pc->was_on || pc->on;
1318 ftepp_update_output_condition(ftepp);
1321 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1322 if (!ftepp_else_allowed(ftepp))
1324 if (!ftepp_ifdef(ftepp, &cond))
1327 pc = &vec_last(ftepp->conditions);
1328 pc->on = !pc->was_on && cond.on;
1329 pc->was_on = pc->was_on || pc->on;
1330 ftepp_update_output_condition(ftepp);
1333 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1334 if (!ftepp_else_allowed(ftepp))
1336 if (!ftepp_if(ftepp, &cond))
1338 pc = &vec_last(ftepp->conditions);
1339 pc->on = !pc->was_on && cond.on;
1340 pc->was_on = pc->was_on || pc->on;
1341 ftepp_update_output_condition(ftepp);
1344 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1345 if (!ftepp_if(ftepp, &cond))
1347 cond.was_on = cond.on;
1348 vec_push(ftepp->conditions, cond);
1349 ftepp->output_on = ftepp->output_on && cond.on;
1352 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1353 if (!ftepp_else_allowed(ftepp))
1355 pc = &vec_last(ftepp->conditions);
1356 pc->on = !pc->was_on;
1357 pc->had_else = true;
1359 ftepp_update_output_condition(ftepp);
1362 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1363 if (!vec_size(ftepp->conditions)) {
1364 ftepp_error(ftepp, "#endif without #if");
1367 vec_pop(ftepp->conditions);
1369 ftepp_update_output_condition(ftepp);
1372 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1373 return ftepp_include(ftepp);
1375 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1376 ftepp_out(ftepp, "#", false);
1379 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1380 ftepp_directive_warning(ftepp);
1383 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1384 ftepp_directive_error(ftepp);
1388 if (ftepp->output_on) {
1389 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1396 /* break; never reached */
1398 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1401 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1404 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1407 /* Builtins! Don't forget the builtins! */
1408 case TOKEN_INTCONST:
1409 case TOKEN_FLOATCONST:
1410 ftepp_out(ftepp, "#", false);
1413 if (!ftepp_skipspace(ftepp))
1418 static bool ftepp_preprocess(ftepp_t *ftepp)
1421 bool newline = true;
1424 char *expand = NULL;
1427 ftepp->lex->flags.preprocessing = true;
1428 ftepp->lex->flags.mergelines = false;
1429 ftepp->lex->flags.noops = true;
1434 if (ftepp->token >= TOKEN_EOF)
1440 switch (ftepp->token) {
1443 case TOKEN_TYPENAME:
1444 /* is it a predef? */
1445 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1446 for (i = 0; i < sizeof(ftepp_predefs) / sizeof (*ftepp_predefs); i++) {
1447 if (!strcmp(ftepp_predefs[i].name, ftepp_tokval(ftepp))) {
1448 expand = ftepp_predefs[i].func(ftepp->lex);
1449 ftepp_out(ftepp, expand, false);
1450 ftepp_next(ftepp); /* skip */
1452 mem_d(expand); /* free memory */
1458 if (ftepp->output_on)
1459 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1464 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1468 if (!ftepp_macro_call(ftepp, macro))
1469 ftepp->token = TOKEN_ERROR;
1473 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1477 ftepp->lex->flags.mergelines = true;
1478 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1479 ftepp_error(ftepp, "error in preprocessor directive");
1480 ftepp->token = TOKEN_ERROR;
1483 if (!ftepp_hash(ftepp))
1484 ftepp->token = TOKEN_ERROR;
1485 ftepp->lex->flags.mergelines = false;
1489 ftepp_out(ftepp, "\n", true);
1493 /* same as default but don't set newline=false */
1494 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1499 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1503 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1505 /* force a 0 at the end but don't count it as added to the output */
1506 vec_push(ftepp->output_string, 0);
1507 vec_shrinkby(ftepp->output_string, 1);
1509 return (ftepp->token == TOKEN_EOF);
1512 /* Like in parser.c - files keep the previous state so we have one global
1513 * preprocessor. Except here we will want to warn about dangling #ifs.
1515 static ftepp_t *ftepp;
1517 static bool ftepp_preprocess_done()
1520 if (vec_size(ftepp->conditions)) {
1521 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1524 lex_close(ftepp->lex);
1526 if (ftepp->itemname) {
1527 mem_d(ftepp->itemname);
1528 ftepp->itemname = NULL;
1533 bool ftepp_preprocess_file(const char *filename)
1535 ftepp->lex = lex_open(filename);
1536 ftepp->itemname = util_strdup(filename);
1538 con_out("failed to open file \"%s\"\n", filename);
1541 if (!ftepp_preprocess(ftepp))
1543 return ftepp_preprocess_done();
1546 bool ftepp_preprocess_string(const char *name, const char *str)
1548 ftepp->lex = lex_open_string(str, strlen(str), name);
1549 ftepp->itemname = util_strdup(name);
1551 con_out("failed to create lexer for string \"%s\"\n", name);
1554 if (!ftepp_preprocess(ftepp))
1556 return ftepp_preprocess_done();
1560 void ftepp_add_macro(const char *name, const char *value) {
1561 char *create = NULL;
1563 /* use saner path for empty macros */
1565 ftepp_add_define("__builtin__", name);
1569 vec_upload(create, "#define ", 8);
1570 vec_upload(create, name, strlen(name));
1571 vec_push (create, ' ');
1572 vec_upload(create, value, strlen(value));
1573 vec_push (create, 0);
1575 ftepp_preprocess_string("__builtin__", create);
1584 ftepp = ftepp_new();
1588 memset(minor, 0, sizeof(minor));
1589 memset(major, 0, sizeof(major));
1591 /* set the right macro based on the selected standard */
1592 ftepp_add_define(NULL, "GMQCC");
1593 if (opts.standard == COMPILER_FTEQCC) {
1594 ftepp_add_define(NULL, "__STD_FTEQCC__");
1603 } else if (opts.standard == COMPILER_GMQCC) {
1604 ftepp_add_define(NULL, "__STD_GMQCC__");
1605 sprintf(major, "\"%d\"", GMQCC_VERSION_MAJOR);
1606 sprintf(minor, "\"%d\"", GMQCC_VERSION_MINOR);
1607 } else if (opts.standard == COMPILER_QCC) {
1608 ftepp_add_define(NULL, "__STD_QCC__");
1619 ftepp_add_macro("__STD_VERSION_MINOR__", minor);
1620 ftepp_add_macro("__STD_VERSION_MAJOR__", major);
1625 void ftepp_add_define(const char *source, const char *name)
1628 lex_ctx ctx = { "__builtin__", 0 };
1630 macro = ppmacro_new(ctx, name);
1631 vec_push(ftepp->macros, macro);
1634 const char *ftepp_get()
1636 return ftepp->output_string;
1641 ftepp_flush_do(ftepp);
1648 ftepp_delete(ftepp);