1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2021 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 #include "language/lexer/macro.h"
25 #include "data/settings.h"
26 #include "language/lexer/segment.h"
27 #include "language/lexer/scan.h"
28 #include "libpspp/assertion.h"
29 #include "libpspp/cast.h"
30 #include "libpspp/i18n.h"
31 #include "libpspp/message.h"
32 #include "libpspp/str.h"
33 #include "libpspp/string-array.h"
36 #define _(msgid) gettext (msgid)
39 macro_token_copy (struct macro_token *dst, const struct macro_token *src)
41 token_copy (&dst->token, &src->token);
42 ss_alloc_substring (&dst->representation, src->representation);
46 macro_token_uninit (struct macro_token *mt)
48 token_uninit (&mt->token);
49 ss_dealloc (&mt->representation);
53 macro_token_to_representation (struct macro_token *mt, struct string *s)
55 ds_put_substring (s, mt->representation);
59 macro_tokens_copy (struct macro_tokens *dst, const struct macro_tokens *src)
61 *dst = (struct macro_tokens) {
62 .mts = xmalloc (src->n * sizeof *dst->mts),
66 for (size_t i = 0; i < src->n; i++)
67 macro_token_copy (&dst->mts[i], &src->mts[i]);
71 macro_tokens_uninit (struct macro_tokens *mts)
73 for (size_t i = 0; i < mts->n; i++)
74 macro_token_uninit (&mts->mts[i]);
79 macro_tokens_add_uninit (struct macro_tokens *mts)
81 if (mts->n >= mts->allocated)
82 mts->mts = x2nrealloc (mts->mts, &mts->allocated, sizeof *mts->mts);
83 return &mts->mts[mts->n++];
87 macro_tokens_add (struct macro_tokens *mts, const struct macro_token *mt)
89 macro_token_copy (macro_tokens_add_uninit (mts), mt);
93 macro_tokens_from_string (struct macro_tokens *mts, const struct substring src,
94 enum segmenter_mode mode)
98 struct segmenter segmenter;
99 struct substring body;
102 struct state state = {
103 .segmenter = SEGMENTER_INIT (mode),
106 struct state saved = state;
108 while (state.body.length > 0)
110 struct macro_token mt = {
111 .token = { .type = T_STOP },
112 .representation = { .string = state.body.string },
114 struct token *token = &mt.token;
116 struct scanner scanner;
117 scanner_init (&scanner, token);
121 enum segment_type type;
122 int seg_len = segmenter_push (&state.segmenter, state.body.string,
123 state.body.length, true, &type);
124 assert (seg_len >= 0);
126 struct substring segment = ss_head (state.body, seg_len);
127 ss_advance (&state.body, seg_len);
129 enum scan_result result = scanner_push (&scanner, type, segment, token);
130 if (result == SCAN_SAVE)
132 else if (result == SCAN_BACK)
137 else if (result == SCAN_DONE)
141 /* We have a token in 'token'. */
142 if (is_scan_type (token->type))
144 if (token->type != SCAN_SKIP)
147 /* XXX report error */
152 mt.representation.length = state.body.string - mt.representation.string;
153 macro_tokens_add (mts, &mt);
155 token_uninit (token);
160 macro_tokens_print (const struct macro_tokens *mts, FILE *stream)
162 for (size_t i = 0; i < mts->n; i++)
163 token_print (&mts->mts[i].token, stream);
168 TC_ENDCMD, /* No space before or after (new-line after). */
169 TC_BINOP, /* Space on both sides. */
170 TC_COMMA, /* Space afterward. */
171 TC_ID, /* Don't need spaces except sequentially. */
172 TC_PUNCT, /* Don't need spaces except sequentially. */
176 needs_space (enum token_class prev, enum token_class next)
178 /* Don't need a space before or after the end of a command.
179 (A new-line is needed afterward as a special case.) */
180 if (prev == TC_ENDCMD || next == TC_ENDCMD)
183 /* Binary operators always have a space on both sides. */
184 if (prev == TC_BINOP || next == TC_BINOP)
187 /* A comma always has a space afterward. */
188 if (prev == TC_COMMA)
191 /* Otherwise, PREV is TC_ID or TC_PUNCT, which only need a space if there are
192 two or them in a row. */
196 static enum token_class
197 classify_token (enum token_type type)
250 macro_tokens_to_representation (struct macro_tokens *mts, struct string *s)
255 macro_token_to_representation (&mts->mts[0], s);
256 for (size_t i = 1; i < mts->n; i++)
258 enum token_type prev = mts->mts[i - 1].token.type;
259 enum token_type next = mts->mts[i].token.type;
261 if (prev == T_ENDCMD)
262 ds_put_byte (s, '\n');
265 enum token_class pc = classify_token (prev);
266 enum token_class nc = classify_token (next);
267 if (needs_space (pc, nc))
268 ds_put_byte (s, ' ');
271 macro_token_to_representation (&mts->mts[i], s);
276 macro_destroy (struct macro *m)
282 for (size_t i = 0; i < m->n_params; i++)
284 struct macro_param *p = &m->params[i];
287 macro_tokens_uninit (&p->def);
295 token_uninit (&p->charend);
299 token_uninit (&p->enclose[0]);
300 token_uninit (&p->enclose[1]);
308 macro_tokens_uninit (&m->body);
313 macro_set_create (void)
315 struct macro_set *set = xmalloc (sizeof *set);
316 *set = (struct macro_set) {
317 .macros = HMAP_INITIALIZER (set->macros),
323 macro_set_destroy (struct macro_set *set)
328 struct macro *macro, *next;
329 HMAP_FOR_EACH_SAFE (macro, next, struct macro, hmap_node, &set->macros)
331 hmap_delete (&set->macros, ¯o->hmap_node);
332 macro_destroy (macro);
334 hmap_destroy (&set->macros);
339 hash_macro_name (const char *name)
341 return utf8_hash_case_string (name, 0);
344 static struct macro *
345 macro_set_find__ (struct macro_set *set, const char *name)
348 HMAP_FOR_EACH_WITH_HASH (macro, struct macro, hmap_node,
349 hash_macro_name (name), &set->macros)
350 if (!utf8_strcasecmp (macro->name, name))
357 macro_set_find (const struct macro_set *set, const char *name)
359 return macro_set_find__ (CONST_CAST (struct macro_set *, set), name);
362 /* Adds M to SET. M replaces any existing macro with the same name. Takes
365 macro_set_add (struct macro_set *set, struct macro *m)
367 struct macro *victim = macro_set_find__ (set, m->name);
370 hmap_delete (&set->macros, &victim->hmap_node);
371 macro_destroy (victim);
374 hmap_insert (&set->macros, &m->hmap_node, hash_macro_name (m->name));
382 /* Accumulating tokens in me->params toward the end of any type of
386 /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
389 /* Expecting a keyword for a keyword argument. */
392 /* Expecting an equal sign for a keyword argument. */
397 struct macro_expander
399 const struct macro_set *macros;
404 const struct macro *macro;
405 struct macro_tokens **args;
406 const struct macro_param *param;
410 me_finished (struct macro_expander *me)
412 for (size_t i = 0; i < me->macro->n_params; i++)
415 me->args[i] = xmalloc (sizeof *me->args[i]);
416 macro_tokens_copy (me->args[i], &me->macro->params[i].def);
422 me_next_arg (struct macro_expander *me)
426 assert (!me->macro->n_params);
427 return me_finished (me);
429 else if (me->param->positional)
432 if (me->param >= &me->macro->params[me->macro->n_params])
433 return me_finished (me);
436 me->state = (!me->param->positional ? ME_KEYWORD
437 : me->param->arg_type == ARG_ENCLOSE ? ME_ENCLOSE
444 for (size_t i = 0; i < me->macro->n_params; i++)
447 me->state = ME_KEYWORD;
450 return me_finished (me);
455 me_error (struct macro_expander *me)
457 me->state = ME_ERROR;
462 me_add_arg (struct macro_expander *me, const struct macro_token *mt)
464 const struct macro_param *p = me->param;
466 const struct token *token = &mt->token;
467 if ((token->type == T_ENDCMD || token->type == T_STOP)
468 && p->arg_type != ARG_CMDEND)
470 msg (SE, _("Unexpected end of command reading argument %s "
471 "to macro %s."), me->param->name, me->macro->name);
473 return me_error (me);
478 struct macro_tokens **argp = &me->args[p - me->macro->params];
480 *argp = xzalloc (sizeof **argp);
481 struct macro_tokens *arg = *argp;
482 if (p->arg_type == ARG_N_TOKENS)
484 macro_tokens_add (arg, mt);
485 if (arg->n >= p->n_tokens)
486 return me_next_arg (me);
489 else if (p->arg_type == ARG_CMDEND)
491 if (token->type == T_ENDCMD || token->type == T_STOP)
492 return me_next_arg (me);
493 macro_tokens_add (arg, mt);
498 const struct token *end
499 = p->arg_type == ARG_CHAREND ? &p->charend : &p->enclose[1];
500 if (token_equal (token, end))
501 return me_next_arg (me);
502 macro_tokens_add (arg, mt);
508 me_expected (struct macro_expander *me, const struct macro_token *actual,
509 const struct token *expected)
511 const struct substring actual_s
512 = (actual->representation.length ? actual->representation
513 : ss_cstr (_("<end of input>")));
514 char *expected_s = token_to_string (expected);
515 msg (SE, _("Found `%.*s' while expecting `%s' reading argument %s "
517 (int) actual_s.length, actual_s.string, expected_s,
518 me->param->name, me->macro->name);
521 return me_error (me);
525 me_enclose (struct macro_expander *me, const struct macro_token *mt)
527 const struct token *token = &mt->token;
530 if (token_equal (&me->param->enclose[0], token))
536 return me_expected (me, mt, &me->param->enclose[0]);
539 static const struct macro_param *
540 macro_find_parameter_by_name (const struct macro *m, struct substring name)
542 if (ss_first (name) == '!')
543 ss_advance (&name, 1);
545 for (size_t i = 0; i < m->n_params; i++)
547 const struct macro_param *p = &m->params[i];
548 struct substring p_name = ss_cstr (p->name + 1);
549 if (!utf8_strncasecmp (p_name.string, p_name.length,
550 name.string, name.length))
557 me_keyword (struct macro_expander *me, const struct macro_token *mt)
559 const struct token *token = &mt->token;
560 if (token->type != T_ID)
561 return me_finished (me);
563 const struct macro_param *p = macro_find_parameter_by_name (me->macro,
567 size_t arg_index = p - me->macro->params;
569 if (me->args[arg_index])
572 _("Argument %s multiply specified in call to macro %s."),
573 p->name, me->macro->name);
574 return me_error (me);
578 me->state = ME_EQUALS;
582 return me_finished (me);
586 me_equals (struct macro_expander *me, const struct macro_token *mt)
588 const struct token *token = &mt->token;
591 if (token->type == T_EQUALS)
597 return me_expected (me, mt, &(struct token) { .type = T_EQUALS });
601 macro_expander_create (const struct macro_set *macros,
602 const struct token *token,
603 struct macro_expander **mep)
606 if (macro_set_is_empty (macros))
608 if (token->type != T_ID && token->type != T_MACRO_ID)
611 const struct macro *macro = macro_set_find (macros, token->string.string);
615 struct macro_expander *me = xmalloc (sizeof *me);
616 *me = (struct macro_expander) {
623 if (!macro->n_params)
627 me->state = (!macro->params[0].positional ? ME_KEYWORD
628 : macro->params[0].arg_type == ARG_ENCLOSE ? ME_ENCLOSE
630 me->args = xcalloc (macro->n_params, sizeof *me->args);
631 me->param = macro->params;
637 macro_expander_destroy (struct macro_expander *me)
642 for (size_t i = 0; i < me->macro->n_params; i++)
645 macro_tokens_uninit (me->args[i]);
652 /* Adds TOKEN to the collection of tokens in ME that potentially need to be
655 Returns -1 if the tokens added do not actually invoke a macro. The caller
656 should consume the first token without expanding it.
658 Returns 0 if the macro expander needs more tokens, for macro arguments or to
659 decide whether this is actually a macro invocation. The caller should call
660 macro_expander_add() again with the next token.
662 Returns a positive number to indicate that the returned number of tokens
663 invoke a macro. The number returned might be less than the number of tokens
664 added because it can take a few tokens of lookahead to determine whether the
665 macro invocation is finished. The caller should call
666 macro_expander_get_expansion() to obtain the expansion. */
668 macro_expander_add (struct macro_expander *me, const struct macro_token *mt)
676 return me_add_arg (me, mt);
679 return me_enclose (me, mt);
682 return me_keyword (me, mt);
685 return me_equals (me, mt);
692 /* Each argument to a macro function is one of:
694 - A quoted string or other single literal token.
696 - An argument to the macro being expanded, e.g. !1 or a named argument.
700 - A function invocation.
702 Each function invocation yields a character sequence to be turned into a
703 sequence of tokens. The case where that character sequence is a single
704 quoted string is an important special case.
706 struct parse_macro_function_ctx
708 const struct macro_token *input;
710 int nesting_countdown;
711 const struct macro_set *macros;
712 const struct macro_expander *me;
717 macro_expand (const struct macro_tokens *,
718 int nesting_countdown, const struct macro_set *,
719 const struct macro_expander *, bool *expand, struct macro_tokens *exp);
722 expand_macro_function (struct parse_macro_function_ctx *ctx,
723 struct string *output, size_t *input_consumed);
725 /* Returns true if the pair of tokens starting at offset OFS within MTS are !*,
728 is_bang_star (const struct macro_token *mts, size_t n, size_t ofs)
731 && mts[ofs].token.type == T_MACRO_ID
732 && ss_equals (mts[ofs].token.string, ss_cstr ("!"))
733 && mts[ofs + 1].token.type == T_ASTERISK);
737 parse_function_arg (struct parse_macro_function_ctx *ctx,
738 size_t i, struct string *farg)
740 const struct macro_token *tokens = ctx->input;
741 const struct token *token = &tokens[i].token;
742 if (token->type == T_MACRO_ID)
744 const struct macro_param *param = macro_find_parameter_by_name (
745 ctx->me->macro, token->string);
748 size_t param_idx = param - ctx->me->macro->params;
749 const struct macro_tokens *marg = ctx->me->args[param_idx];
750 for (size_t i = 0; i < marg->n; i++)
753 ds_put_byte (farg, ' ');
754 ds_put_substring (farg, marg->mts[i].representation);
759 if (is_bang_star (ctx->input, ctx->n_input, i))
761 for (size_t i = 0; i < ctx->me->macro->n_params; i++)
763 if (!ctx->me->macro->params[i].positional)
766 const struct macro_tokens *marg = ctx->me->args[i];
767 for (size_t j = 0; j < marg->n; j++)
770 ds_put_byte (farg, ' ');
771 ds_put_substring (farg, marg->mts[j].representation);
777 struct parse_macro_function_ctx subctx = {
778 .input = &ctx->input[i],
779 .n_input = ctx->n_input - i,
780 .nesting_countdown = ctx->nesting_countdown,
781 .macros = ctx->macros,
783 .expand = ctx->expand,
785 size_t subinput_consumed;
786 if (expand_macro_function (&subctx, farg, &subinput_consumed))
787 return subinput_consumed;
790 ds_put_substring (farg, tokens[i].representation);
795 parse_macro_function (struct parse_macro_function_ctx *ctx,
796 struct string_array *args,
797 struct substring function,
798 int min_args, int max_args,
799 size_t *input_consumed)
801 const struct macro_token *tokens = ctx->input;
802 size_t n_tokens = ctx->n_input;
805 || tokens[0].token.type != T_MACRO_ID
806 || !ss_equals_case (tokens[0].token.string, function))
809 if (n_tokens < 2 || tokens[1].token.type != T_LPAREN)
811 printf ("`(' expected following %s'\n", function.string);
815 string_array_init (args);
817 for (size_t i = 2;; )
821 if (tokens[i].token.type == T_RPAREN)
823 *input_consumed = i + 1;
824 if (args->n < min_args || args->n > max_args)
826 printf ("Wrong number of arguments to %s.\n", function.string);
832 struct string s = DS_EMPTY_INITIALIZER;
833 i += parse_function_arg (ctx, i, &s);
839 string_array_append_nocopy (args, ds_steal_cstr (&s));
841 if (tokens[i].token.type == T_COMMA)
843 else if (tokens[i].token.type != T_RPAREN)
845 printf ("Expecting `,' or `)' in %s invocation.", function.string);
851 printf ("Missing closing parenthesis in arguments to %s.\n",
855 string_array_destroy (args);
860 unquote_string (const char *s, struct string *content)
862 struct string_lexer slex;
863 string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE /* XXX */);
866 if (!string_lexer_next (&slex, &token1))
869 if (token1.type != T_STRING)
871 token_uninit (&token1);
876 if (string_lexer_next (&slex, &token2))
878 token_uninit (&token1);
879 token_uninit (&token2);
883 ds_put_substring (content, token1.string);
884 token_uninit (&token1);
889 unquote_string_in_place (const char *s, struct string *tmp)
892 return unquote_string (s, tmp) ? ds_cstr (tmp) : s;
896 parse_integer (const char *s, int *np)
901 long int n = strtol (s, &tail, 10);
902 *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
903 tail += strspn (tail, CC_SPACES);
904 return *tail == '\0' && errno != ERANGE && n == *np;
908 expand_macro_function (struct parse_macro_function_ctx *ctx,
909 struct string *output,
910 size_t *input_consumed)
912 struct string_array args;
914 if (parse_macro_function (ctx, &args, ss_cstr ("!length"), 1, 1,
916 ds_put_format (output, "%zu", strlen (args.strings[0]));
917 else if (parse_macro_function (ctx, &args, ss_cstr ("!blanks"), 1, 1,
921 if (!parse_integer (args.strings[0], &n))
923 printf ("argument to !BLANKS must be non-negative integer (not \"%s\")\n", args.strings[0]);
924 string_array_destroy (&args);
928 ds_put_byte_multiple (output, ' ', n);
930 else if (parse_macro_function (ctx, &args, ss_cstr ("!concat"), 1, INT_MAX,
933 for (size_t i = 0; i < args.n; i++)
934 if (!unquote_string (args.strings[i], output))
935 ds_put_cstr (output, args.strings[i]);
937 else if (parse_macro_function (ctx, &args, ss_cstr ("!head"), 1, 1,
941 const char *s = unquote_string_in_place (args.strings[0], &tmp);
943 struct macro_tokens mts = { .n = 0 };
944 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
946 ds_put_substring (output, mts.mts[0].representation);
947 macro_tokens_uninit (&mts);
950 else if (parse_macro_function (ctx, &args, ss_cstr ("!index"), 2, 2,
953 const char *haystack = args.strings[0];
954 const char *needle = strstr (haystack, args.strings[1]);
955 ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
957 else if (parse_macro_function (ctx, &args, ss_cstr ("!quote"), 1, 1,
960 if (unquote_string (args.strings[0], NULL))
961 ds_put_cstr (output, args.strings[0]);
964 ds_extend (output, strlen (args.strings[0]) + 2);
965 ds_put_byte (output, '\'');
966 for (const char *p = args.strings[0]; *p; p++)
969 ds_put_byte (output, '\'');
970 ds_put_byte (output, *p);
972 ds_put_byte (output, '\'');
975 else if (parse_macro_function (ctx, &args, ss_cstr ("!substr"), 2, 3,
979 if (!parse_integer (args.strings[1], &start) || start < 1)
981 printf ("second argument to !SUBSTR must be positive integer (not \"%s\")\n", args.strings[1]);
982 string_array_destroy (&args);
987 if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
989 printf ("third argument to !SUBSTR must be non-negative integer (not \"%s\")\n", args.strings[1]);
990 string_array_destroy (&args);
994 struct substring s = ss_cstr (args.strings[0]);
995 ds_put_substring (output, ss_substr (s, start - 1, count));
997 else if (parse_macro_function (ctx, &args, ss_cstr ("!tail"), 1, 1,
1001 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1003 struct macro_tokens mts = { .n = 0 };
1004 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1007 struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1008 macro_tokens_to_representation (&tail, output);
1010 macro_tokens_uninit (&mts);
1013 else if (parse_macro_function (ctx, &args, ss_cstr ("!unquote"), 1, 1,
1016 if (!unquote_string (args.strings[0], output))
1017 ds_put_cstr (output, args.strings[0]);
1019 else if (parse_macro_function (ctx, &args, ss_cstr ("!upcase"), 1, 1,
1023 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1024 char *upper = utf8_to_upper (s);
1025 ds_put_cstr (output, upper);
1029 else if (parse_macro_function (ctx, &args, ss_cstr ("!eval"), 1, 1,
1032 struct macro_tokens mts = { .n = 0 };
1033 macro_tokens_from_string (&mts, ss_cstr (args.strings[0]),
1034 SEG_MODE_INTERACTIVE /* XXX */);
1035 struct macro_tokens exp = { .n = 0 };
1036 macro_expand (&mts, ctx->nesting_countdown - 1, ctx->macros,
1037 ctx->me, ctx->expand, &exp);
1038 macro_tokens_to_representation (&exp, output);
1039 macro_tokens_uninit (&exp);
1040 macro_tokens_uninit (&mts);
1042 else if (ctx->n_input > 0
1043 && ctx->input[0].token.type == T_MACRO_ID
1044 && ss_equals_case (ctx->input[0].token.string, ss_cstr ("!null")))
1046 *input_consumed = 1;
1052 string_array_destroy (&args);
1058 int nesting_countdown;
1059 const struct macro_set *macros;
1060 const struct macro_expander *me;
1064 static char *macro_evaluate_or (const struct expr_context *ctx,
1065 const struct macro_token **tokens,
1066 const struct macro_token *end);
1069 macro_evaluate_literal (const struct expr_context *ctx,
1070 const struct macro_token **tokens,
1071 const struct macro_token *end)
1073 const struct macro_token *p = *tokens;
1076 if (p->token.type == T_LPAREN)
1079 char *value = macro_evaluate_or (ctx, &p, end);
1082 if (p >= end || p->token.type != T_RPAREN)
1085 printf ("expecting ')' in macro expression\n");
1093 struct parse_macro_function_ctx fctx = {
1096 .nesting_countdown = ctx->nesting_countdown,
1097 .macros = ctx->macros,
1099 .expand = ctx->expand,
1101 struct string function_output = DS_EMPTY_INITIALIZER;
1102 size_t function_consumed;
1103 if (expand_macro_function (&fctx, &function_output, &function_consumed))
1105 *tokens = p + function_consumed;
1106 return ds_steal_cstr (&function_output);
1110 return ss_xstrdup (p->representation);
1114 macro_evaluate_logical (const struct expr_context *ctx,
1115 const struct macro_token **tokens,
1116 const struct macro_token *end)
1118 const struct macro_token *p = *tokens;
1119 char *lhs = macro_evaluate_literal (ctx, &p, end);
1123 enum token_type op = p < end ? p->token.type : T_STOP;
1124 if (op != T_EQUALS && op != T_EQ && op != T_NE && op != T_LT
1125 && op != T_GT && op != T_LE && op != T_GE)
1132 char *rhs = macro_evaluate_literal (ctx, &p, end);
1139 struct string lhs_tmp, rhs_tmp;
1140 int cmp = strcmp/*XXX*/ (unquote_string_in_place (lhs, &lhs_tmp),
1141 unquote_string_in_place (rhs, &rhs_tmp));
1142 ds_destroy (&lhs_tmp);
1143 ds_destroy (&rhs_tmp);
1148 bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1150 : op == T_LT ? cmp < 0
1151 : op == T_GT ? cmp > 0
1152 : op == T_LE ? cmp <= 0
1153 :/*op == T_GE*/cmp >= 0);
1156 return xstrdup (b ? "1" : "0");
1160 macro_evaluate_not (const struct expr_context *ctx,
1161 const struct macro_token **tokens,
1162 const struct macro_token *end)
1164 const struct macro_token *p = *tokens;
1166 unsigned int negations = 0;
1167 while (p < end && p->token.type == T_NOT)
1173 char *operand = macro_evaluate_logical (ctx, &p, end);
1174 if (!operand || !negations)
1180 bool b = strcmp (operand, "0") ^ (negations & 1);
1183 return xstrdup (b ? "1" : "0");
1187 macro_evaluate_and (const struct expr_context *ctx,
1188 const struct macro_token **tokens,
1189 const struct macro_token *end)
1191 const struct macro_token *p = *tokens;
1192 char *lhs = macro_evaluate_not (ctx, &p, end);
1196 while (p < end && p->token.type == T_AND)
1199 char *rhs = macro_evaluate_not (ctx, &p, end);
1206 bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1209 lhs = xstrdup (b ? "1" : "0");
1216 macro_evaluate_or (const struct expr_context *ctx,
1217 const struct macro_token **tokens,
1218 const struct macro_token *end)
1220 const struct macro_token *p = *tokens;
1221 char *lhs = macro_evaluate_and (ctx, &p, end);
1225 while (p < end && p->token.type == T_OR)
1228 char *rhs = macro_evaluate_and (ctx, &p, end);
1235 bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1238 lhs = xstrdup (b ? "1" : "0");
1245 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1246 int nesting_countdown, const struct macro_set *macros,
1247 const struct macro_expander *me, bool *expand)
1249 const struct expr_context ctx = {
1250 .nesting_countdown = nesting_countdown,
1255 return macro_evaluate_or (&ctx, tokens, *tokens + n_tokens);
1258 static const struct macro_token *
1259 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1262 for (; p < end; p++)
1264 if (p->token.type != T_MACRO_ID)
1267 if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1269 else if (ss_equals_case (p->token.string, ss_cstr ("!IFEND")))
1275 else if (ss_equals_case (p->token.string, ss_cstr ("!ELSE")) && !nesting)
1282 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1283 int nesting_countdown, const struct macro_set *macros,
1284 const struct macro_expander *me, bool *expand,
1285 struct macro_tokens *exp)
1287 const struct macro_token *p = tokens;
1288 const struct macro_token *end = tokens + n_tokens;
1290 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1294 char *result = macro_evaluate_expression (&p, end - p,
1295 nesting_countdown, macros, me, expand);
1298 bool b = strcmp (result, "0");
1302 || p->token.type != T_MACRO_ID
1303 || !ss_equals_case (p->token.string, ss_cstr ("!THEN")))
1305 printf ("!THEN expected\n");
1309 const struct macro_token *start_then = p + 1;
1310 const struct macro_token *end_then = find_ifend_clause (start_then, end);
1313 printf ("!ELSE or !IFEND expected\n");
1317 const struct macro_token *start_else, *end_if;
1318 if (ss_equals_case (end_then->token.string, ss_cstr ("!ELSE")))
1320 start_else = end_then + 1;
1321 end_if = find_ifend_clause (start_else, end);
1323 || !ss_equals_case (end_if->token.string, ss_cstr ("!IFEND")))
1325 printf ("!IFEND expected\n");
1335 const struct macro_token *start;
1340 n = end_then - start_then;
1342 else if (start_else)
1345 n = end_if - start_else;
1355 struct macro_tokens mts = {
1356 .mts = CONST_CAST (struct macro_token *, start),
1359 macro_expand (&mts, nesting_countdown, macros, me, expand, exp);
1361 return (end_if + 1) - tokens;
1365 macro_expand (const struct macro_tokens *mts,
1366 int nesting_countdown, const struct macro_set *macros,
1367 const struct macro_expander *me, bool *expand,
1368 struct macro_tokens *exp)
1370 if (nesting_countdown <= 0)
1372 printf ("maximum nesting level exceeded\n");
1373 for (size_t i = 0; i < mts->n; i++)
1374 macro_tokens_add (exp, &mts->mts[i]);
1378 for (size_t i = 0; i < mts->n; i++)
1380 const struct macro_token *mt = &mts->mts[i];
1381 const struct token *token = &mt->token;
1382 if (token->type == T_MACRO_ID && me)
1384 const struct macro_param *param = macro_find_parameter_by_name (
1385 me->macro, token->string);
1388 const struct macro_tokens *arg = me->args[param - me->macro->params];
1389 //macro_tokens_print (arg, stdout);
1390 if (*expand && param->expand_arg)
1391 macro_expand (arg, nesting_countdown, macros, NULL, expand, exp);
1393 for (size_t i = 0; i < arg->n; i++)
1394 macro_tokens_add (exp, &arg->mts[i]);
1398 if (is_bang_star (mts->mts, mts->n, i))
1400 for (size_t j = 0; j < me->macro->n_params; j++)
1402 const struct macro_param *param = &me->macro->params[j];
1403 if (!param->positional)
1406 const struct macro_tokens *arg = me->args[j];
1407 if (*expand && param->expand_arg)
1408 macro_expand (arg, nesting_countdown, macros, NULL, expand, exp);
1410 for (size_t k = 0; k < arg->n; k++)
1411 macro_tokens_add (exp, &arg->mts[k]);
1417 size_t n = macro_expand_if (&mts->mts[i], mts->n - i,
1418 nesting_countdown, macros, me, expand,
1429 struct macro_expander *subme;
1430 int retval = macro_expander_create (macros, token, &subme);
1431 for (size_t j = 1; !retval; j++)
1433 const struct macro_token endcmd = { .token = { .type = T_ENDCMD } };
1434 retval = macro_expander_add (
1435 subme, i + j < mts->n ? &mts->mts[i + j] : &endcmd);
1440 macro_expand (&subme->macro->body, nesting_countdown - 1, macros,
1441 subme, expand, exp);
1442 macro_expander_destroy (subme);
1446 macro_expander_destroy (subme);
1449 if (token->type != T_MACRO_ID)
1451 macro_tokens_add (exp, mt);
1455 struct parse_macro_function_ctx ctx = {
1456 .input = &mts->mts[i],
1457 .n_input = mts->n - i,
1458 .nesting_countdown = nesting_countdown,
1463 struct string function_output = DS_EMPTY_INITIALIZER;
1464 size_t function_consumed;
1465 if (expand_macro_function (&ctx, &function_output, &function_consumed))
1467 i += function_consumed - 1;
1469 macro_tokens_from_string (exp, function_output.ss,
1470 SEG_MODE_INTERACTIVE /* XXX */);
1471 ds_destroy (&function_output);
1476 if (ss_equals_case (token->string, ss_cstr ("!onexpand")))
1478 else if (ss_equals_case (token->string, ss_cstr ("!offexpand")))
1481 macro_tokens_add (exp, mt);
1486 macro_expander_get_expansion (struct macro_expander *me, struct macro_tokens *exp)
1489 for (size_t i = 0; i < me->macro->n_params; i++)
1491 printf ("%s:\n", me->macro->params[i].name);
1492 macro_tokens_print (me->args[i], stdout);
1497 macro_expand (&me->macro->body, settings_get_mnest (),
1498 me->macros, me, &expand, exp);
1501 printf ("expansion:\n");
1502 macro_tokens_print (exp, stdout);