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
32 #define HT_MACROS 1024
42 /* a copy from the lexer */
56 /* yes we need an extra flag since `#define FOO x` is not the same as `#define FOO() x` */
63 typedef struct ftepp_s {
69 ppcondition *conditions;
71 ht macros; /* hashtable<string, ppmacro*> */
80 * Implement the predef subsystem now. We can do this safely with the
81 * help of lexer contexts.
83 static uint32_t ftepp_predef_countval = 0;
84 static uint32_t ftepp_predef_randval = 0;
87 static char *ftepp_predef_date(lex_file *context) {
88 struct tm *itime = NULL;
90 char *value = (char*)mem_a(82);
91 /* 82 is enough for strftime but we also have " " in our string */
99 localtime_s(itime, &rtime);
101 itime = localtime(&rtime);
104 strftime(value, 82, "\"%b %d %Y\"", itime);
110 static char *ftepp_predef_time(lex_file *context) {
111 struct tm *itime = NULL;
113 char *value = (char*)mem_a(82);
114 /* 82 is enough for strftime but we also have " " in our string */
122 localtime_s(itime, &rtime);
124 itime = localtime(&rtime);
127 strftime(value, 82, "\"%X\"", itime);
133 static char *ftepp_predef_line(lex_file *context) {
135 util_asprintf(&value, "%d", (int)context->line);
139 static char *ftepp_predef_file(lex_file *context) {
140 size_t length = strlen(context->name) + 3; /* two quotes and a terminator */
141 char *value = (char*)mem_a(length);
142 util_snprintf(value, length, "\"%s\"", context->name);
146 /* __COUNTER_LAST__ */
147 static char *ftepp_predef_counterlast(lex_file *context) {
149 util_asprintf(&value, "%u", ftepp_predef_countval);
155 static char *ftepp_predef_counter(lex_file *context) {
157 ftepp_predef_countval ++;
158 util_asprintf(&value, "%u", ftepp_predef_countval);
164 static char *ftepp_predef_random(lex_file *context) {
166 ftepp_predef_randval = (util_rand() % 0xFF) + 1;
167 util_asprintf(&value, "%u", ftepp_predef_randval);
172 /* __RANDOM_LAST__ */
173 static char *ftepp_predef_randomlast(lex_file *context) {
175 util_asprintf(&value, "%u", ftepp_predef_randval);
181 static char *ftepp_predef_timestamp(lex_file *context) {
186 if (stat(context->name, &finfo))
187 return util_strdup("\"<failed to determine timestamp>\"");
190 * ctime and its fucking annoying newline char, no worries, we're
191 * professionals here.
193 find = ctime(&finfo.st_mtime);
194 value = (char*)mem_a(strlen(find) + 1);
195 memcpy(&value[1], find, (size = strlen(find)) - 1);
205 char *(*func)(lex_file *);
208 static const ftepp_predef_t ftepp_predefs[] = {
209 { "__LINE__", &ftepp_predef_line },
210 { "__FILE__", &ftepp_predef_file },
211 { "__COUNTER__", &ftepp_predef_counter },
212 { "__COUNTER_LAST__", &ftepp_predef_counterlast },
213 { "__RANDOM__", &ftepp_predef_random },
214 { "__RANDOM_LAST__", &ftepp_predef_randomlast },
215 { "__DATE__", &ftepp_predef_date },
216 { "__TIME__", &ftepp_predef_time },
217 { "__TIME_STAMP__", &ftepp_predef_timestamp }
220 static GMQCC_INLINE int ftepp_predef_index(const char *name) {
221 /* no hashtable here, we simply check for one to exist the naive way */
223 for(i = 0; i < (int)(sizeof(ftepp_predefs)/sizeof(*ftepp_predefs)); i++)
224 if (!strcmp(ftepp_predefs[i].name, name))
229 bool ftepp_predef_exists(const char *name) {
230 return ftepp_predef_index(name) != -1;
233 /* singleton because we're allowed */
234 static GMQCC_INLINE char *(*ftepp_predef(const char *name))(lex_file *context) {
235 int i = ftepp_predef_index(name);
236 return (i != -1) ? ftepp_predefs[i].func : NULL;
239 #define ftepp_tokval(f) ((f)->lex->tok.value)
240 #define ftepp_ctx(f) ((f)->lex->tok.ctx)
242 static void ftepp_errorat(ftepp_t *ftepp, lex_ctx_t ctx, const char *fmt, ...)
249 con_cvprintmsg(ctx, LVL_ERROR, "error", fmt, ap);
253 static void ftepp_error(ftepp_t *ftepp, const char *fmt, ...)
260 con_cvprintmsg(ftepp->lex->tok.ctx, LVL_ERROR, "error", fmt, ap);
264 static bool GMQCC_WARN ftepp_warn(ftepp_t *ftepp, int warntype, const char *fmt, ...)
270 r = vcompile_warning(ftepp->lex->tok.ctx, warntype, fmt, ap);
275 static pptoken *pptoken_make(ftepp_t *ftepp)
277 pptoken *token = (pptoken*)mem_a(sizeof(pptoken));
278 token->token = ftepp->token;
280 if (token->token == TOKEN_WHITE)
281 token->value = util_strdup(" ");
284 token->value = util_strdup(ftepp_tokval(ftepp));
286 memcpy(&token->constval, &ftepp->lex->tok.constval, sizeof(token->constval));
290 static GMQCC_INLINE void pptoken_delete(pptoken *self)
296 static ppmacro *ppmacro_new(lex_ctx_t ctx, const char *name)
298 ppmacro *macro = (ppmacro*)mem_a(sizeof(ppmacro));
301 memset(macro, 0, sizeof(*macro));
302 macro->name = util_strdup(name);
306 static void ppmacro_delete(ppmacro *self)
309 for (i = 0; i < vec_size(self->params); ++i)
310 mem_d(self->params[i]);
311 vec_free(self->params);
312 for (i = 0; i < vec_size(self->output); ++i)
313 pptoken_delete(self->output[i]);
314 vec_free(self->output);
319 static ftepp_t* ftepp_new(void)
323 ftepp = (ftepp_t*)mem_a(sizeof(*ftepp));
324 memset(ftepp, 0, sizeof(*ftepp));
326 ftepp->macros = util_htnew(HT_MACROS);
327 ftepp->output_on = true;
332 static GMQCC_INLINE void ftepp_flush_do(ftepp_t *self)
334 vec_free(self->output_string);
337 static void ftepp_delete(ftepp_t *self)
339 ftepp_flush_do(self);
341 mem_d(self->itemname);
342 if (self->includename)
343 vec_free(self->includename);
345 util_htrem(self->macros, (void (*)(void*))&ppmacro_delete);
347 vec_free(self->conditions);
349 lex_close(self->lex);
353 static void ftepp_out(ftepp_t *ftepp, const char *str, bool ignore_cond)
355 if (ignore_cond || ftepp->output_on)
360 data = vec_add(ftepp->output_string, len);
361 memcpy(data, str, len);
365 static GMQCC_INLINE void ftepp_update_output_condition(ftepp_t *ftepp)
368 ftepp->output_on = true;
369 for (i = 0; i < vec_size(ftepp->conditions); ++i)
370 ftepp->output_on = ftepp->output_on && ftepp->conditions[i].on;
373 static GMQCC_INLINE ppmacro* ftepp_macro_find(ftepp_t *ftepp, const char *name)
375 return (ppmacro*)util_htget(ftepp->macros, name);
378 static GMQCC_INLINE void ftepp_macro_delete(ftepp_t *ftepp, const char *name)
380 util_htrm(ftepp->macros, name, (void (*)(void*))&ppmacro_delete);
383 static GMQCC_INLINE int ftepp_next(ftepp_t *ftepp)
385 return (ftepp->token = lex_do(ftepp->lex));
388 /* Important: this does not skip newlines! */
389 static bool ftepp_skipspace(ftepp_t *ftepp)
391 if (ftepp->token != TOKEN_WHITE)
393 while (ftepp_next(ftepp) == TOKEN_WHITE) {}
394 if (ftepp->token >= TOKEN_EOF) {
395 ftepp_error(ftepp, "unexpected end of preprocessor directive");
401 /* this one skips EOLs as well */
402 static bool ftepp_skipallwhite(ftepp_t *ftepp)
404 if (ftepp->token != TOKEN_WHITE && ftepp->token != TOKEN_EOL)
408 } while (ftepp->token == TOKEN_WHITE || ftepp->token == TOKEN_EOL);
409 if (ftepp->token >= TOKEN_EOF) {
410 ftepp_error(ftepp, "unexpected end of preprocessor directive");
417 * The huge macro parsing code...
419 static bool ftepp_define_params(ftepp_t *ftepp, ppmacro *macro)
423 if (!ftepp_skipspace(ftepp))
425 if (ftepp->token == ')')
427 switch (ftepp->token) {
431 vec_push(macro->params, util_strdup(ftepp_tokval(ftepp)));
434 macro->variadic = true;
437 ftepp_error(ftepp, "unexpected token in parameter list");
441 if (!ftepp_skipspace(ftepp))
443 if (macro->variadic && ftepp->token != ')') {
444 ftepp_error(ftepp, "cannot have parameters after the variadic parameters");
447 } while (ftepp->token == ',');
449 if (ftepp->token != ')') {
450 ftepp_error(ftepp, "expected closing paren after macro parameter list");
454 /* skipspace happens in ftepp_define */
458 static bool ftepp_define_body(ftepp_t *ftepp, ppmacro *macro)
461 while (ftepp->token != TOKEN_EOL && ftepp->token < TOKEN_EOF) {
462 bool subscript = false;
464 if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_ARGS__")) {
465 subscript = !!(ftepp_next(ftepp) == '#');
467 if (subscript && ftepp_next(ftepp) != '#') {
468 ftepp_error(ftepp, "expected `##` in __VA_ARGS__ for subscripting");
470 } else if (subscript) {
471 if (ftepp_next(ftepp) == '[') {
472 if (ftepp_next(ftepp) != TOKEN_INTCONST) {
473 ftepp_error(ftepp, "expected index for __VA_ARGS__ subscript");
477 index = (int)strtol(ftepp_tokval(ftepp), NULL, 10);
479 if (ftepp_next(ftepp) != ']') {
480 ftepp_error(ftepp, "expected `]` in __VA_ARGS__ subscript");
485 * mark it as an array to be handled later as such and not
486 * as traditional __VA_ARGS__
488 ftepp->token = TOKEN_VA_ARGS_ARRAY;
489 ptok = pptoken_make(ftepp);
490 ptok->constval.i = index;
491 vec_push(macro->output, ptok);
494 ftepp_error(ftepp, "expected `[` for subscripting of __VA_ARGS__");
498 int old = ftepp->token;
499 ftepp->token = TOKEN_VA_ARGS;
500 ptok = pptoken_make(ftepp);
501 vec_push(macro->output, ptok);
505 else if (macro->variadic && !strcmp(ftepp_tokval(ftepp), "__VA_COUNT__")) {
506 ftepp->token = TOKEN_VA_COUNT;
507 ptok = pptoken_make(ftepp);
508 vec_push(macro->output, ptok);
511 ptok = pptoken_make(ftepp);
512 vec_push(macro->output, ptok);
516 /* recursive expansion can cause EOFs here */
517 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
518 ftepp_error(ftepp, "unexpected junk after macro or unexpected end of file");
524 static bool ftepp_define(ftepp_t *ftepp)
526 ppmacro *macro = NULL;
527 size_t l = ftepp_ctx(ftepp).line;
529 (void)ftepp_next(ftepp);
530 if (!ftepp_skipspace(ftepp))
533 switch (ftepp->token) {
537 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
538 if (macro && ftepp->output_on) {
539 if (ftepp_warn(ftepp, WARN_CPP, "redefining `%s`", ftepp_tokval(ftepp)))
541 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
543 macro = ppmacro_new(ftepp_ctx(ftepp), ftepp_tokval(ftepp));
546 ftepp_error(ftepp, "expected macro name");
550 (void)ftepp_next(ftepp);
552 if (ftepp->token == '(') {
553 macro->has_params = true;
554 if (!ftepp_define_params(ftepp, macro)) {
555 ppmacro_delete(macro);
560 if (!ftepp_skipspace(ftepp)) {
561 ppmacro_delete(macro);
565 if (!ftepp_define_body(ftepp, macro)) {
566 ppmacro_delete(macro);
570 if (ftepp->output_on)
571 util_htset(ftepp->macros, macro->name, (void*)macro);
573 ppmacro_delete(macro);
576 for (; l < ftepp_ctx(ftepp).line; ++l)
577 ftepp_out(ftepp, "\n", true);
582 * When a macro is used we have to handle parameters as well
583 * as special-concatenation via ## or stringification via #
585 * Note: parenthesis can nest, so FOO((a),b) is valid, but only
586 * this kind of parens. Curly braces or [] don't count towards the
593 static void macroparam_clean(macroparam *self)
596 for (i = 0; i < vec_size(self->tokens); ++i)
597 pptoken_delete(self->tokens[i]);
598 vec_free(self->tokens);
601 /* need to leave the last token up */
602 static bool ftepp_macro_call_params(ftepp_t *ftepp, macroparam **out_params)
604 macroparam *params = NULL;
610 if (!ftepp_skipallwhite(ftepp))
612 while (ftepp->token != ')') {
614 if (!ftepp_skipallwhite(ftepp))
616 while (parens || ftepp->token != ',') {
617 if (ftepp->token == '(')
619 else if (ftepp->token == ')') {
624 ptok = pptoken_make(ftepp);
625 vec_push(mp.tokens, ptok);
626 if (ftepp_next(ftepp) >= TOKEN_EOF) {
627 ftepp_error(ftepp, "unexpected end of file in macro call");
631 vec_push(params, mp);
633 if (ftepp->token == ')')
635 if (ftepp->token != ',') {
636 ftepp_error(ftepp, "expected closing paren or comma in macro call");
639 if (ftepp_next(ftepp) >= TOKEN_EOF) {
640 ftepp_error(ftepp, "unexpected end of file in macro call");
644 *out_params = params;
649 macroparam_clean(&mp);
650 for (i = 0; i < vec_size(params); ++i)
651 macroparam_clean(¶ms[i]);
656 static bool macro_params_find(ppmacro *macro, const char *name, size_t *idx)
659 for (i = 0; i < vec_size(macro->params); ++i) {
660 if (!strcmp(macro->params[i], name)) {
668 static void ftepp_stringify_token(ftepp_t *ftepp, pptoken *token)
673 switch (token->token) {
674 case TOKEN_STRINGCONST:
677 /* in preprocessor mode strings already are string,
678 * so we don't get actual newline bytes here.
679 * Still need to escape backslashes and quotes.
682 case '\\': ftepp_out(ftepp, "\\\\", false); break;
683 case '"': ftepp_out(ftepp, "\\\"", false); break;
686 ftepp_out(ftepp, chs, false);
693 ftepp_out(ftepp, " ", false);
696 ftepp_out(ftepp, "\\n", false);
699 ftepp_out(ftepp, token->value, false);
704 static void ftepp_stringify(ftepp_t *ftepp, macroparam *param)
707 ftepp_out(ftepp, "\"", false);
708 for (i = 0; i < vec_size(param->tokens); ++i)
709 ftepp_stringify_token(ftepp, param->tokens[i]);
710 ftepp_out(ftepp, "\"", false);
713 static void ftepp_recursion_header(ftepp_t *ftepp)
715 ftepp_out(ftepp, "\n#pragma push(line)\n", false);
718 static void ftepp_recursion_footer(ftepp_t *ftepp)
720 ftepp_out(ftepp, "\n#pragma pop(line)\n", false);
723 static void ftepp_param_out(ftepp_t *ftepp, macroparam *param)
727 for (i = 0; i < vec_size(param->tokens); ++i) {
728 out = param->tokens[i];
729 if (out->token == TOKEN_EOL)
730 ftepp_out(ftepp, "\n", false);
732 ftepp_out(ftepp, out->value, false);
736 static bool ftepp_preprocess(ftepp_t *ftepp);
737 static bool ftepp_macro_expand(ftepp_t *ftepp, ppmacro *macro, macroparam *params, bool resetline)
740 char *old_string = ftepp->output_string;
742 lex_file *old_lexer = ftepp->lex;
743 size_t vararg_start = vec_size(macro->params);
755 if (vararg_start < vec_size(params))
756 varargs = vec_size(params) - vararg_start;
761 if (!vec_size(macro->output))
764 ftepp->output_string = NULL;
765 for (o = 0; o < vec_size(macro->output); ++o) {
766 pptoken *out = macro->output[o];
767 switch (out->token) {
769 if (!macro->variadic) {
770 ftepp_error(ftepp, "internal preprocessor error: TOKEN_VA_ARGS in non-variadic macro");
771 vec_free(old_string);
778 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
779 for (++pi; pi < varargs; ++pi) {
780 ftepp_out(ftepp, ", ", false);
781 ftepp_param_out(ftepp, ¶ms[pi + vararg_start]);
785 case TOKEN_VA_ARGS_ARRAY:
786 if ((size_t)out->constval.i >= varargs) {
787 ftepp_error(ftepp, "subscript of `[%u]` is out of bounds for `__VA_ARGS__`", out->constval.i);
788 vec_free(old_string);
792 ftepp_param_out(ftepp, ¶ms[out->constval.i + vararg_start]);
796 util_asprintf(&buffer, "%d", varargs);
797 ftepp_out(ftepp, buffer, false);
804 if (!macro_params_find(macro, out->value, &pi)) {
805 ftepp_out(ftepp, out->value, false);
808 ftepp_param_out(ftepp, ¶ms[pi]);
811 if (o + 1 < vec_size(macro->output)) {
812 nextok = macro->output[o+1]->token;
814 /* raw concatenation */
818 if ( (nextok == TOKEN_IDENT ||
819 nextok == TOKEN_KEYWORD ||
820 nextok == TOKEN_TYPENAME) &&
821 macro_params_find(macro, macro->output[o+1]->value, &pi))
824 ftepp_stringify(ftepp, ¶ms[pi]);
828 ftepp_out(ftepp, "#", false);
831 ftepp_out(ftepp, "\n", false);
834 ftepp_out(ftepp, out->value, false);
838 vec_push(ftepp->output_string, 0);
839 /* Now run the preprocessor recursively on this string buffer */
841 printf("__________\n%s\n=========\n", ftepp->output_string);
843 inlex = lex_open_string(ftepp->output_string, vec_size(ftepp->output_string)-1, ftepp->lex->name);
845 ftepp_error(ftepp, "internal error: failed to instantiate lexer");
850 inlex->line = ftepp->lex->line;
851 inlex->sline = ftepp->lex->sline;
854 old_inmacro = ftepp->in_macro;
855 ftepp->in_macro = true;
856 ftepp->output_string = NULL;
857 if (!ftepp_preprocess(ftepp)) {
858 ftepp->in_macro = old_inmacro;
859 vec_free(ftepp->lex->open_string);
860 vec_free(ftepp->output_string);
861 lex_close(ftepp->lex);
865 ftepp->in_macro = old_inmacro;
866 vec_free(ftepp->lex->open_string);
867 lex_close(ftepp->lex);
869 inner_string = ftepp->output_string;
870 ftepp->output_string = old_string;
872 has_newlines = (strchr(inner_string, '\n') != NULL);
874 if (has_newlines && !old_inmacro)
875 ftepp_recursion_header(ftepp);
877 vec_append(ftepp->output_string, vec_size(inner_string), inner_string);
878 vec_free(inner_string);
880 if (has_newlines && !old_inmacro)
881 ftepp_recursion_footer(ftepp);
883 if (resetline && !ftepp->in_macro) {
885 util_snprintf(lineno, 128, "\n#pragma line(%lu)\n", (unsigned long)(old_lexer->sline));
886 ftepp_out(ftepp, lineno, false);
889 old_string = ftepp->output_string;
891 ftepp->lex = old_lexer;
892 ftepp->output_string = old_string;
896 static bool ftepp_macro_call(ftepp_t *ftepp, ppmacro *macro)
899 macroparam *params = NULL;
903 if (!macro->has_params) {
904 if (!ftepp_macro_expand(ftepp, macro, NULL, false))
911 if (!ftepp_skipallwhite(ftepp))
914 if (ftepp->token != '(') {
915 ftepp_error(ftepp, "expected macro parameters in parenthesis");
920 paramline = ftepp->lex->sline;
921 if (!ftepp_macro_call_params(ftepp, ¶ms))
924 if ( vec_size(params) < vec_size(macro->params) ||
925 (vec_size(params) > vec_size(macro->params) && !macro->variadic) )
927 ftepp_error(ftepp, "macro %s expects%s %u paramteters, %u provided", macro->name,
928 (macro->variadic ? " at least" : ""),
929 (unsigned int)vec_size(macro->params),
930 (unsigned int)vec_size(params));
935 if (!ftepp_macro_expand(ftepp, macro, params, (paramline != ftepp->lex->sline)))
940 for (o = 0; o < vec_size(params); ++o)
941 macroparam_clean(¶ms[o]);
947 * #if - the FTEQCC way:
948 * defined(FOO) => true if FOO was #defined regardless of parameters or contents
949 * <numbers> => True if the number is not 0
950 * !<factor> => True if the factor yields false
951 * !!<factor> => ERROR on 2 or more unary nots
952 * <macro> => becomes the macro's FIRST token regardless of parameters
953 * <e> && <e> => True if both expressions are true
954 * <e> || <e> => True if either expression is true
956 * <ident> => False (remember for macros the <macro> rule applies instead)
957 * Unary + and - are weird and wrong in fteqcc so we don't allow them
958 * parenthesis in expressions are allowed
959 * parameter lists on macros are errors
960 * No mathematical calculations are executed
962 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out);
963 static bool ftepp_if_op(ftepp_t *ftepp)
965 ftepp->lex->flags.noops = false;
967 if (!ftepp_skipspace(ftepp))
969 ftepp->lex->flags.noops = true;
972 static bool ftepp_if_value(ftepp_t *ftepp, bool *out, double *value_out)
978 if (!ftepp_skipspace(ftepp))
981 while (ftepp->token == '!') {
984 if (!ftepp_skipspace(ftepp))
988 if (ftepp->token == TOKEN_OPERATOR && !strcmp(ftepp_tokval(ftepp), "-"))
992 if (!ftepp_skipspace(ftepp))
996 switch (ftepp->token) {
1000 if (!strcmp(ftepp_tokval(ftepp), "defined")) {
1002 if (!ftepp_skipspace(ftepp))
1004 if (ftepp->token != '(') {
1005 ftepp_error(ftepp, "`defined` keyword in #if requires a macro name in parenthesis");
1009 if (!ftepp_skipspace(ftepp))
1011 if (ftepp->token != TOKEN_IDENT &&
1012 ftepp->token != TOKEN_TYPENAME &&
1013 ftepp->token != TOKEN_KEYWORD)
1015 ftepp_error(ftepp, "defined() used on an unexpected token type");
1018 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1021 if (!ftepp_skipspace(ftepp))
1023 if (ftepp->token != ')') {
1024 ftepp_error(ftepp, "expected closing paren");
1030 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1031 if (!macro || !vec_size(macro->output)) {
1035 /* This does not expand recursively! */
1036 switch (macro->output[0]->token) {
1037 case TOKEN_INTCONST:
1038 *value_out = macro->output[0]->constval.i;
1039 *out = !!(macro->output[0]->constval.i);
1041 case TOKEN_FLOATCONST:
1042 *value_out = macro->output[0]->constval.f;
1043 *out = !!(macro->output[0]->constval.f);
1051 case TOKEN_STRINGCONST:
1055 case TOKEN_INTCONST:
1056 *value_out = ftepp->lex->tok.constval.i;
1057 *out = !!(ftepp->lex->tok.constval.i);
1059 case TOKEN_FLOATCONST:
1060 *value_out = ftepp->lex->tok.constval.f;
1061 *out = !!(ftepp->lex->tok.constval.f);
1066 if (!ftepp_if_expr(ftepp, out, value_out))
1068 if (ftepp->token != ')') {
1069 ftepp_error(ftepp, "expected closing paren in #if expression");
1075 ftepp_error(ftepp, "junk in #if: `%s` ...", ftepp_tokval(ftepp));
1076 if (OPTS_OPTION_BOOL(OPTION_DEBUG))
1077 ftepp_error(ftepp, "internal: token %i\n", ftepp->token);
1081 *value_out = -*value_out;
1084 *value_out = (*out ? 1 : 0);
1090 static bool ftepp_if_nextvalue(ftepp_t *ftepp, bool *out, double *value_out)
1092 if (!ftepp_next(ftepp))
1094 return ftepp_if_value(ftepp, out, value_out);
1098 static bool ftepp_if_expr(ftepp_t *ftepp, bool *out, double *value_out)
1100 if (!ftepp_if_value(ftepp, out, value_out))
1103 if (!ftepp_if_op(ftepp))
1106 if (ftepp->token == ')' || ftepp->token != TOKEN_OPERATOR)
1109 /* FTEQCC is all right-associative and no precedence here */
1110 if (!strcmp(ftepp_tokval(ftepp), "&&") ||
1111 !strcmp(ftepp_tokval(ftepp), "||"))
1114 char opc = ftepp_tokval(ftepp)[0];
1118 if (!ftepp_next(ftepp))
1120 if (!ftepp_if_expr(ftepp, &next, &nextvalue))
1124 *out = *out && next;
1126 *out = *out || next;
1128 *value_out = (*out ? 1 : 0);
1131 else if (!strcmp(ftepp_tokval(ftepp), "==") ||
1132 !strcmp(ftepp_tokval(ftepp), "!=") ||
1133 !strcmp(ftepp_tokval(ftepp), ">=") ||
1134 !strcmp(ftepp_tokval(ftepp), "<=") ||
1135 !strcmp(ftepp_tokval(ftepp), ">") ||
1136 !strcmp(ftepp_tokval(ftepp), "<"))
1139 const char opc0 = ftepp_tokval(ftepp)[0];
1140 const char opc1 = ftepp_tokval(ftepp)[1];
1143 if (!ftepp_next(ftepp))
1145 if (!ftepp_if_expr(ftepp, &next, &other))
1149 *out = (*value_out == other);
1150 else if (opc0 == '!')
1151 *out = (*value_out != other);
1152 else if (opc0 == '>') {
1153 if (opc1 == '=') *out = (*value_out >= other);
1154 else *out = (*value_out > other);
1156 else if (opc0 == '<') {
1157 if (opc1 == '=') *out = (*value_out <= other);
1158 else *out = (*value_out < other);
1160 *value_out = (*out ? 1 : 0);
1165 ftepp_error(ftepp, "junk after #if");
1170 static bool ftepp_if(ftepp_t *ftepp, ppcondition *cond)
1172 bool result = false;
1175 memset(cond, 0, sizeof(*cond));
1176 (void)ftepp_next(ftepp);
1178 if (!ftepp_skipspace(ftepp))
1180 if (ftepp->token == TOKEN_EOL) {
1181 ftepp_error(ftepp, "expected expression for #if-directive");
1185 if (!ftepp_if_expr(ftepp, &result, &dummy))
1193 * ifdef is rather simple
1195 static bool ftepp_ifdef(ftepp_t *ftepp, ppcondition *cond)
1198 memset(cond, 0, sizeof(*cond));
1199 (void)ftepp_next(ftepp);
1200 if (!ftepp_skipspace(ftepp))
1203 switch (ftepp->token) {
1205 case TOKEN_TYPENAME:
1207 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1210 ftepp_error(ftepp, "expected macro name");
1214 (void)ftepp_next(ftepp);
1215 if (!ftepp_skipspace(ftepp))
1217 /* relaxing this condition
1218 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1219 ftepp_error(ftepp, "stray tokens after #ifdef");
1228 * undef is also simple
1230 static bool ftepp_undef(ftepp_t *ftepp)
1232 (void)ftepp_next(ftepp);
1233 if (!ftepp_skipspace(ftepp))
1236 if (ftepp->output_on) {
1237 switch (ftepp->token) {
1239 case TOKEN_TYPENAME:
1241 ftepp_macro_delete(ftepp, ftepp_tokval(ftepp));
1244 ftepp_error(ftepp, "expected macro name");
1249 (void)ftepp_next(ftepp);
1250 if (!ftepp_skipspace(ftepp))
1252 /* relaxing this condition
1253 if (ftepp->token != TOKEN_EOL && ftepp->token != TOKEN_EOF) {
1254 ftepp_error(ftepp, "stray tokens after #ifdef");
1261 /* Special unescape-string function which skips a leading quote
1262 * and stops at a quote, not just at \0
1264 static void unescape(const char *str, char *out) {
1266 while (*str && *str != '"') {
1270 case '\\': *out++ = *str; break;
1271 case '"': *out++ = *str; break;
1272 case 'a': *out++ = '\a'; break;
1273 case 'b': *out++ = '\b'; break;
1274 case 'r': *out++ = '\r'; break;
1275 case 'n': *out++ = '\n'; break;
1276 case 't': *out++ = '\t'; break;
1277 case 'f': *out++ = '\f'; break;
1278 case 'v': *out++ = '\v'; break;
1293 static char *ftepp_include_find_path(const char *file, const char *pathfile)
1296 char *filename = NULL;
1297 const char *last_slash;
1303 last_slash = strrchr(pathfile, '/');
1306 len = last_slash - pathfile;
1307 memcpy(vec_add(filename, len), pathfile, len);
1308 vec_push(filename, '/');
1312 memcpy(vec_add(filename, len+1), file, len);
1313 vec_last(filename) = 0;
1315 fp = fs_file_open(filename, "rb");
1324 static char *ftepp_include_find(ftepp_t *ftepp, const char *file)
1326 char *filename = NULL;
1328 filename = ftepp_include_find_path(file, ftepp->includename);
1330 filename = ftepp_include_find_path(file, ftepp->itemname);
1334 static bool ftepp_directive_warning(ftepp_t *ftepp) {
1335 char *message = NULL;
1337 if (!ftepp_skipspace(ftepp))
1340 /* handle the odd non string constant case so it works like C */
1341 if (ftepp->token != TOKEN_STRINGCONST) {
1343 vec_upload(message, "#warning", 8);
1345 while (ftepp->token != TOKEN_EOL) {
1346 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1349 vec_push(message, '\0');
1350 if (ftepp->output_on)
1351 store = ftepp_warn(ftepp, WARN_CPP, message);
1358 if (!ftepp->output_on)
1361 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1362 return ftepp_warn(ftepp, WARN_CPP, "#warning %s", ftepp_tokval(ftepp));
1365 static void ftepp_directive_error(ftepp_t *ftepp) {
1366 char *message = NULL;
1368 if (!ftepp_skipspace(ftepp))
1371 /* handle the odd non string constant case so it works like C */
1372 if (ftepp->token != TOKEN_STRINGCONST) {
1373 vec_upload(message, "#error", 6);
1375 while (ftepp->token != TOKEN_EOL) {
1376 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1379 vec_push(message, '\0');
1380 if (ftepp->output_on)
1381 ftepp_error(ftepp, message);
1386 if (!ftepp->output_on)
1389 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1390 ftepp_error(ftepp, "#error %s", ftepp_tokval(ftepp));
1393 static void ftepp_directive_message(ftepp_t *ftepp) {
1394 char *message = NULL;
1396 if (!ftepp_skipspace(ftepp))
1399 /* handle the odd non string constant case so it works like C */
1400 if (ftepp->token != TOKEN_STRINGCONST) {
1401 vec_upload(message, "#message", 8);
1403 while (ftepp->token != TOKEN_EOL) {
1404 vec_upload(message, ftepp_tokval(ftepp), strlen(ftepp_tokval(ftepp)));
1407 vec_push(message, '\0');
1408 if (ftepp->output_on)
1409 con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message", message);
1414 if (!ftepp->output_on)
1417 unescape (ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1418 con_cprintmsg(ftepp->lex->tok.ctx, LVL_MSG, "message", ftepp_tokval(ftepp));
1423 * FIXME: do we need/want a -I option?
1424 * FIXME: what about when dealing with files in subdirectories coming from a progs.src?
1426 static bool ftepp_include(ftepp_t *ftepp)
1428 lex_file *old_lexer = ftepp->lex;
1433 char *old_includename;
1435 (void)ftepp_next(ftepp);
1436 if (!ftepp_skipspace(ftepp))
1439 if (ftepp->token != TOKEN_STRINGCONST) {
1440 ftepp_error(ftepp, "expected filename to include");
1444 if (!ftepp->output_on) {
1449 ctx = ftepp_ctx(ftepp);
1451 unescape(ftepp_tokval(ftepp), ftepp_tokval(ftepp));
1453 ftepp_out(ftepp, "\n#pragma file(", false);
1454 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1455 ftepp_out(ftepp, ")\n#pragma line(1)\n", false);
1457 filename = ftepp_include_find(ftepp, ftepp_tokval(ftepp));
1459 ftepp_error(ftepp, "failed to open include file `%s`", ftepp_tokval(ftepp));
1462 inlex = lex_open(filename);
1464 ftepp_error(ftepp, "open failed on include file `%s`", filename);
1469 old_includename = ftepp->includename;
1470 ftepp->includename = filename;
1471 if (!ftepp_preprocess(ftepp)) {
1472 vec_free(ftepp->includename);
1473 ftepp->includename = old_includename;
1474 lex_close(ftepp->lex);
1475 ftepp->lex = old_lexer;
1478 vec_free(ftepp->includename);
1479 ftepp->includename = old_includename;
1480 lex_close(ftepp->lex);
1481 ftepp->lex = old_lexer;
1483 ftepp_out(ftepp, "\n#pragma file(", false);
1484 ftepp_out(ftepp, ctx.file, false);
1485 util_snprintf(lineno, sizeof(lineno), ")\n#pragma line(%lu)\n", (unsigned long)(ctx.line+1));
1486 ftepp_out(ftepp, lineno, false);
1489 (void)ftepp_next(ftepp);
1490 if (!ftepp_skipspace(ftepp))
1492 if (ftepp->token != TOKEN_EOL) {
1493 ftepp_error(ftepp, "stray tokens after #include");
1496 (void)ftepp_next(ftepp);
1501 /* Basic structure handlers */
1502 static bool ftepp_else_allowed(ftepp_t *ftepp)
1504 if (!vec_size(ftepp->conditions)) {
1505 ftepp_error(ftepp, "#else without #if");
1508 if (vec_last(ftepp->conditions).had_else) {
1509 ftepp_error(ftepp, "multiple #else for a single #if");
1515 static bool ftepp_hash(ftepp_t *ftepp)
1520 lex_ctx_t ctx = ftepp_ctx(ftepp);
1522 if (!ftepp_skipspace(ftepp))
1525 switch (ftepp->token) {
1528 case TOKEN_TYPENAME:
1529 if (!strcmp(ftepp_tokval(ftepp), "define")) {
1530 return ftepp_define(ftepp);
1532 else if (!strcmp(ftepp_tokval(ftepp), "undef")) {
1533 return ftepp_undef(ftepp);
1535 else if (!strcmp(ftepp_tokval(ftepp), "ifdef")) {
1536 if (!ftepp_ifdef(ftepp, &cond))
1538 cond.was_on = cond.on;
1539 vec_push(ftepp->conditions, cond);
1540 ftepp->output_on = ftepp->output_on && cond.on;
1543 else if (!strcmp(ftepp_tokval(ftepp), "ifndef")) {
1544 if (!ftepp_ifdef(ftepp, &cond))
1547 cond.was_on = cond.on;
1548 vec_push(ftepp->conditions, cond);
1549 ftepp->output_on = ftepp->output_on && cond.on;
1552 else if (!strcmp(ftepp_tokval(ftepp), "elifdef")) {
1553 if (!ftepp_else_allowed(ftepp))
1555 if (!ftepp_ifdef(ftepp, &cond))
1557 pc = &vec_last(ftepp->conditions);
1558 pc->on = !pc->was_on && cond.on;
1559 pc->was_on = pc->was_on || pc->on;
1560 ftepp_update_output_condition(ftepp);
1563 else if (!strcmp(ftepp_tokval(ftepp), "elifndef")) {
1564 if (!ftepp_else_allowed(ftepp))
1566 if (!ftepp_ifdef(ftepp, &cond))
1569 pc = &vec_last(ftepp->conditions);
1570 pc->on = !pc->was_on && cond.on;
1571 pc->was_on = pc->was_on || pc->on;
1572 ftepp_update_output_condition(ftepp);
1575 else if (!strcmp(ftepp_tokval(ftepp), "elif")) {
1576 if (!ftepp_else_allowed(ftepp))
1578 if (!ftepp_if(ftepp, &cond))
1580 pc = &vec_last(ftepp->conditions);
1581 pc->on = !pc->was_on && cond.on;
1582 pc->was_on = pc->was_on || pc->on;
1583 ftepp_update_output_condition(ftepp);
1586 else if (!strcmp(ftepp_tokval(ftepp), "if")) {
1587 if (!ftepp_if(ftepp, &cond))
1589 cond.was_on = cond.on;
1590 vec_push(ftepp->conditions, cond);
1591 ftepp->output_on = ftepp->output_on && cond.on;
1594 else if (!strcmp(ftepp_tokval(ftepp), "else")) {
1595 if (!ftepp_else_allowed(ftepp))
1597 pc = &vec_last(ftepp->conditions);
1598 pc->on = !pc->was_on;
1599 pc->had_else = true;
1601 ftepp_update_output_condition(ftepp);
1604 else if (!strcmp(ftepp_tokval(ftepp), "endif")) {
1605 if (!vec_size(ftepp->conditions)) {
1606 ftepp_error(ftepp, "#endif without #if");
1609 vec_pop(ftepp->conditions);
1611 ftepp_update_output_condition(ftepp);
1614 else if (!strcmp(ftepp_tokval(ftepp), "include")) {
1615 return ftepp_include(ftepp);
1617 else if (!strcmp(ftepp_tokval(ftepp), "pragma")) {
1618 ftepp_out(ftepp, "#", false);
1621 else if (!strcmp(ftepp_tokval(ftepp), "warning")) {
1622 ftepp_directive_warning(ftepp);
1625 else if (!strcmp(ftepp_tokval(ftepp), "error")) {
1626 ftepp_directive_error(ftepp);
1629 else if (!strcmp(ftepp_tokval(ftepp), "message")) {
1630 ftepp_directive_message(ftepp);
1634 if (ftepp->output_on) {
1635 ftepp_error(ftepp, "unrecognized preprocessor directive: `%s`", ftepp_tokval(ftepp));
1642 /* break; never reached */
1644 ftepp_error(ftepp, "unexpected preprocessor token: `%s`", ftepp_tokval(ftepp));
1647 ftepp_errorat(ftepp, ctx, "empty preprocessor directive");
1650 ftepp_error(ftepp, "missing newline at end of file", ftepp_tokval(ftepp));
1653 /* Builtins! Don't forget the builtins! */
1654 case TOKEN_INTCONST:
1655 case TOKEN_FLOATCONST:
1656 ftepp_out(ftepp, "#", false);
1659 if (!ftepp_skipspace(ftepp))
1664 static bool ftepp_preprocess(ftepp_t *ftepp)
1667 bool newline = true;
1670 char *expand = NULL;
1672 ftepp->lex->flags.preprocessing = true;
1673 ftepp->lex->flags.mergelines = false;
1674 ftepp->lex->flags.noops = true;
1679 if (ftepp->token >= TOKEN_EOF)
1685 switch (ftepp->token) {
1688 case TOKEN_TYPENAME:
1689 /* is it a predef? */
1690 if (OPTS_FLAG(FTEPP_PREDEFS)) {
1691 char *(*predef)(lex_file*) = ftepp_predef(ftepp_tokval(ftepp));
1693 expand = predef(ftepp->lex);
1694 ftepp_out (ftepp, expand, false);
1702 if (ftepp->output_on)
1703 macro = ftepp_macro_find(ftepp, ftepp_tokval(ftepp));
1708 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1712 if (!ftepp_macro_call(ftepp, macro))
1713 ftepp->token = TOKEN_ERROR;
1717 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1721 ftepp->lex->flags.mergelines = true;
1722 if (ftepp_next(ftepp) >= TOKEN_EOF) {
1723 ftepp_error(ftepp, "error in preprocessor directive");
1724 ftepp->token = TOKEN_ERROR;
1727 if (!ftepp_hash(ftepp))
1728 ftepp->token = TOKEN_ERROR;
1729 ftepp->lex->flags.mergelines = false;
1733 ftepp_out(ftepp, "\n", true);
1737 /* same as default but don't set newline=false */
1738 ftepp_out(ftepp, ftepp_tokval(ftepp), true);
1743 ftepp_out(ftepp, ftepp_tokval(ftepp), false);
1747 } while (!ftepp->errors && ftepp->token < TOKEN_EOF);
1749 /* force a 0 at the end but don't count it as added to the output */
1750 vec_push(ftepp->output_string, 0);
1751 vec_shrinkby(ftepp->output_string, 1);
1753 return (ftepp->token == TOKEN_EOF);
1756 /* Like in parser.c - files keep the previous state so we have one global
1757 * preprocessor. Except here we will want to warn about dangling #ifs.
1759 static bool ftepp_preprocess_done(ftepp_t *ftepp)
1762 if (vec_size(ftepp->conditions)) {
1763 if (ftepp_warn(ftepp, WARN_MULTIFILE_IF, "#if spanning multiple files, is this intended?"))
1766 lex_close(ftepp->lex);
1768 if (ftepp->itemname) {
1769 mem_d(ftepp->itemname);
1770 ftepp->itemname = NULL;
1775 bool ftepp_preprocess_file(ftepp_t *ftepp, const char *filename)
1777 ftepp->lex = lex_open(filename);
1778 ftepp->itemname = util_strdup(filename);
1780 con_out("failed to open file \"%s\"\n", filename);
1783 if (!ftepp_preprocess(ftepp))
1785 return ftepp_preprocess_done(ftepp);
1788 bool ftepp_preprocess_string(ftepp_t *ftepp, const char *name, const char *str)
1790 ftepp->lex = lex_open_string(str, strlen(str), name);
1791 ftepp->itemname = util_strdup(name);
1793 con_out("failed to create lexer for string \"%s\"\n", name);
1796 if (!ftepp_preprocess(ftepp))
1798 return ftepp_preprocess_done(ftepp);
1802 void ftepp_add_macro(ftepp_t *ftepp, const char *name, const char *value) {
1803 char *create = NULL;
1805 /* use saner path for empty macros */
1807 ftepp_add_define(ftepp, "__builtin__", name);
1811 vec_upload(create, "#define ", 8);
1812 vec_upload(create, name, strlen(name));
1813 vec_push (create, ' ');
1814 vec_upload(create, value, strlen(value));
1815 vec_push (create, 0);
1817 ftepp_preprocess_string(ftepp, "__builtin__", create);
1821 ftepp_t *ftepp_create()
1827 ftepp = ftepp_new();
1831 memset(minor, 0, sizeof(minor));
1832 memset(major, 0, sizeof(major));
1834 /* set the right macro based on the selected standard */
1835 ftepp_add_define(ftepp, NULL, "GMQCC");
1836 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) {
1837 ftepp_add_define(ftepp, NULL, "__STD_FTEQCC__");
1846 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_GMQCC) {
1847 ftepp_add_define(ftepp, NULL, "__STD_GMQCC__");
1848 util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1849 util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1850 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCCX) {
1851 ftepp_add_define(ftepp, NULL, "__STD_QCCX__");
1852 util_snprintf(major, 32, "\"%d\"", GMQCC_VERSION_MAJOR);
1853 util_snprintf(minor, 32, "\"%d\"", GMQCC_VERSION_MINOR);
1854 } else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
1855 ftepp_add_define(ftepp, NULL, "__STD_QCC__");
1866 ftepp_add_macro(ftepp, "__STD_VERSION_MINOR__", minor);
1867 ftepp_add_macro(ftepp, "__STD_VERSION_MAJOR__", major);
1870 * We're going to just make __NULL__ nil, which works for 60% of the
1871 * cases of __NULL_ for fteqcc.
1873 ftepp_add_macro(ftepp, "__NULL__", "nil");
1878 void ftepp_add_define(ftepp_t *ftepp, const char *source, const char *name)
1881 lex_ctx_t ctx = { "__builtin__", 0, 0 };
1883 macro = ppmacro_new(ctx, name);
1884 /*vec_push(ftepp->macros, macro);*/
1885 util_htset(ftepp->macros, name, macro);
1888 const char *ftepp_get(ftepp_t *ftepp)
1890 return ftepp->output_string;
1893 void ftepp_flush(ftepp_t *ftepp)
1895 ftepp_flush_do(ftepp);
1898 void ftepp_finish(ftepp_t *ftepp)
1902 ftepp_delete(ftepp);