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"
34 #include "libpspp/string-map.h"
35 #include "libpspp/stringi-set.h"
37 #include "gl/c-ctype.h"
38 #include "gl/ftoastr.h"
41 #define _(msgid) gettext (msgid)
44 macro_token_copy (struct macro_token *dst, const struct macro_token *src)
46 token_copy (&dst->token, &src->token);
47 ss_alloc_substring (&dst->representation, src->representation);
51 macro_token_uninit (struct macro_token *mt)
53 token_uninit (&mt->token);
54 ss_dealloc (&mt->representation);
58 macro_token_to_representation (struct macro_token *mt, struct string *s)
60 ds_put_substring (s, mt->representation);
64 is_macro_keyword (struct substring s)
66 static struct stringi_set keywords = STRINGI_SET_INITIALIZER (keywords);
67 if (stringi_set_is_empty (&keywords))
69 static const char *kws[] = {
90 for (size_t i = 0; i < sizeof kws / sizeof *kws; i++)
91 stringi_set_insert (&keywords, kws[i]);
94 ss_ltrim (&s, ss_cstr ("!"));
95 return stringi_set_contains_len (&keywords, s.string, s.length);
99 macro_tokens_copy (struct macro_tokens *dst, const struct macro_tokens *src)
101 *dst = (struct macro_tokens) {
102 .mts = xmalloc (src->n * sizeof *dst->mts),
106 for (size_t i = 0; i < src->n; i++)
107 macro_token_copy (&dst->mts[i], &src->mts[i]);
111 macro_tokens_uninit (struct macro_tokens *mts)
113 for (size_t i = 0; i < mts->n; i++)
114 macro_token_uninit (&mts->mts[i]);
119 macro_tokens_add_uninit (struct macro_tokens *mts)
121 if (mts->n >= mts->allocated)
122 mts->mts = x2nrealloc (mts->mts, &mts->allocated, sizeof *mts->mts);
123 return &mts->mts[mts->n++];
127 macro_tokens_add (struct macro_tokens *mts, const struct macro_token *mt)
129 macro_token_copy (macro_tokens_add_uninit (mts), mt);
133 macro_tokens_from_string (struct macro_tokens *mts, const struct substring src,
134 enum segmenter_mode mode)
138 struct segmenter segmenter;
139 struct substring body;
142 struct state state = {
143 .segmenter = segmenter_init (mode, true),
146 struct state saved = state;
148 while (state.body.length > 0)
150 struct macro_token mt = {
151 .token = { .type = T_STOP },
152 .representation = { .string = state.body.string },
154 struct token *token = &mt.token;
156 struct scanner scanner;
157 scanner_init (&scanner, token);
161 enum segment_type type;
162 int seg_len = segmenter_push (&state.segmenter, state.body.string,
163 state.body.length, true, &type);
164 assert (seg_len >= 0);
166 struct substring segment = ss_head (state.body, seg_len);
167 ss_advance (&state.body, seg_len);
169 enum scan_result result = scanner_push (&scanner, type, segment, token);
170 if (result == SCAN_SAVE)
172 else if (result == SCAN_BACK)
177 else if (result == SCAN_DONE)
181 /* We have a token in 'token'. */
182 if (is_scan_type (token->type))
184 if (token->type != SCAN_SKIP)
187 /* XXX report error */
192 mt.representation.length = state.body.string - mt.representation.string;
193 macro_tokens_add (mts, &mt);
195 token_uninit (token);
200 macro_tokens_print (const struct macro_tokens *mts, FILE *stream)
202 for (size_t i = 0; i < mts->n; i++)
203 token_print (&mts->mts[i].token, stream);
208 TC_ENDCMD, /* No space before or after (new-line after). */
209 TC_BINOP, /* Space on both sides. */
210 TC_COMMA, /* Space afterward. */
211 TC_ID, /* Don't need spaces except sequentially. */
212 TC_PUNCT, /* Don't need spaces except sequentially. */
216 needs_space (enum token_class prev, enum token_class next)
218 /* Don't need a space before or after the end of a command.
219 (A new-line is needed afterward as a special case.) */
220 if (prev == TC_ENDCMD || next == TC_ENDCMD)
223 /* Binary operators always have a space on both sides. */
224 if (prev == TC_BINOP || next == TC_BINOP)
227 /* A comma always has a space afterward. */
228 if (prev == TC_COMMA)
231 /* Otherwise, PREV is TC_ID or TC_PUNCT, which only need a space if there are
232 two or them in a row. */
236 static enum token_class
237 classify_token (enum token_type type)
290 macro_tokens_to_representation (struct macro_tokens *mts, struct string *s)
295 macro_token_to_representation (&mts->mts[0], s);
296 for (size_t i = 1; i < mts->n; i++)
298 enum token_type prev = mts->mts[i - 1].token.type;
299 enum token_type next = mts->mts[i].token.type;
301 if (prev == T_ENDCMD)
302 ds_put_byte (s, '\n');
305 enum token_class pc = classify_token (prev);
306 enum token_class nc = classify_token (next);
307 if (needs_space (pc, nc))
308 ds_put_byte (s, ' ');
311 macro_token_to_representation (&mts->mts[i], s);
316 macro_destroy (struct macro *m)
322 for (size_t i = 0; i < m->n_params; i++)
324 struct macro_param *p = &m->params[i];
327 macro_tokens_uninit (&p->def);
335 token_uninit (&p->charend);
339 token_uninit (&p->enclose[0]);
340 token_uninit (&p->enclose[1]);
348 macro_tokens_uninit (&m->body);
353 macro_set_create (void)
355 struct macro_set *set = xmalloc (sizeof *set);
356 *set = (struct macro_set) {
357 .macros = HMAP_INITIALIZER (set->macros),
363 macro_set_destroy (struct macro_set *set)
368 struct macro *macro, *next;
369 HMAP_FOR_EACH_SAFE (macro, next, struct macro, hmap_node, &set->macros)
371 hmap_delete (&set->macros, ¯o->hmap_node);
372 macro_destroy (macro);
374 hmap_destroy (&set->macros);
379 hash_macro_name (const char *name)
381 return utf8_hash_case_string (name, 0);
384 static struct macro *
385 macro_set_find__ (struct macro_set *set, const char *name)
388 HMAP_FOR_EACH_WITH_HASH (macro, struct macro, hmap_node,
389 hash_macro_name (name), &set->macros)
390 if (!utf8_strcasecmp (macro->name, name))
397 macro_set_find (const struct macro_set *set, const char *name)
399 return macro_set_find__ (CONST_CAST (struct macro_set *, set), name);
402 /* Adds M to SET. M replaces any existing macro with the same name. Takes
405 macro_set_add (struct macro_set *set, struct macro *m)
407 struct macro *victim = macro_set_find__ (set, m->name);
410 hmap_delete (&set->macros, &victim->hmap_node);
411 macro_destroy (victim);
414 hmap_insert (&set->macros, &m->hmap_node, hash_macro_name (m->name));
422 /* Accumulating tokens in me->params toward the end of any type of
426 /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
429 /* Expecting a keyword for a keyword argument. */
432 /* Expecting an equal sign for a keyword argument. */
437 struct macro_expander
439 const struct macro_set *macros;
444 const struct macro *macro;
445 struct macro_tokens **args;
446 const struct macro_param *param;
450 me_finished (struct macro_expander *me)
452 for (size_t i = 0; i < me->macro->n_params; i++)
455 me->args[i] = xmalloc (sizeof *me->args[i]);
456 macro_tokens_copy (me->args[i], &me->macro->params[i].def);
462 me_next_arg (struct macro_expander *me)
466 assert (!me->macro->n_params);
467 return me_finished (me);
469 else if (me->param->positional)
472 if (me->param >= &me->macro->params[me->macro->n_params])
473 return me_finished (me);
476 me->state = (!me->param->positional ? ME_KEYWORD
477 : me->param->arg_type == ARG_ENCLOSE ? ME_ENCLOSE
484 for (size_t i = 0; i < me->macro->n_params; i++)
487 me->state = ME_KEYWORD;
490 return me_finished (me);
495 me_error (struct macro_expander *me)
497 me->state = ME_ERROR;
502 me_add_arg (struct macro_expander *me, const struct macro_token *mt)
504 const struct macro_param *p = me->param;
506 const struct token *token = &mt->token;
507 if ((token->type == T_ENDCMD || token->type == T_STOP)
508 && p->arg_type != ARG_CMDEND)
510 msg (SE, _("Unexpected end of command reading argument %s "
511 "to macro %s."), me->param->name, me->macro->name);
513 return me_error (me);
518 struct macro_tokens **argp = &me->args[p - me->macro->params];
520 *argp = xzalloc (sizeof **argp);
521 struct macro_tokens *arg = *argp;
522 if (p->arg_type == ARG_N_TOKENS)
524 macro_tokens_add (arg, mt);
525 if (arg->n >= p->n_tokens)
526 return me_next_arg (me);
529 else if (p->arg_type == ARG_CMDEND)
531 if (token->type == T_ENDCMD || token->type == T_STOP)
532 return me_next_arg (me);
533 macro_tokens_add (arg, mt);
538 const struct token *end
539 = p->arg_type == ARG_CHAREND ? &p->charend : &p->enclose[1];
540 if (token_equal (token, end))
541 return me_next_arg (me);
542 macro_tokens_add (arg, mt);
548 me_expected (struct macro_expander *me, const struct macro_token *actual,
549 const struct token *expected)
551 const struct substring actual_s
552 = (actual->representation.length ? actual->representation
553 : ss_cstr (_("<end of input>")));
554 char *expected_s = token_to_string (expected);
555 msg (SE, _("Found `%.*s' while expecting `%s' reading argument %s "
557 (int) actual_s.length, actual_s.string, expected_s,
558 me->param->name, me->macro->name);
561 return me_error (me);
565 me_enclose (struct macro_expander *me, const struct macro_token *mt)
567 const struct token *token = &mt->token;
570 if (token_equal (&me->param->enclose[0], token))
576 return me_expected (me, mt, &me->param->enclose[0]);
579 static const struct macro_param *
580 macro_find_parameter_by_name (const struct macro *m, struct substring name)
582 ss_ltrim (&name, ss_cstr ("!"));
584 for (size_t i = 0; i < m->n_params; i++)
586 const struct macro_param *p = &m->params[i];
587 struct substring p_name = ss_cstr (p->name + 1);
588 if (!utf8_strncasecmp (p_name.string, p_name.length,
589 name.string, name.length))
596 me_keyword (struct macro_expander *me, const struct macro_token *mt)
598 const struct token *token = &mt->token;
599 if (token->type != T_ID)
600 return me_finished (me);
602 const struct macro_param *p = macro_find_parameter_by_name (me->macro,
606 size_t arg_index = p - me->macro->params;
608 if (me->args[arg_index])
611 _("Argument %s multiply specified in call to macro %s."),
612 p->name, me->macro->name);
613 return me_error (me);
617 me->state = ME_EQUALS;
621 return me_finished (me);
625 me_equals (struct macro_expander *me, const struct macro_token *mt)
627 const struct token *token = &mt->token;
630 if (token->type == T_EQUALS)
636 return me_expected (me, mt, &(struct token) { .type = T_EQUALS });
640 macro_expander_create (const struct macro_set *macros,
641 const struct token *token,
642 struct macro_expander **mep)
645 if (macro_set_is_empty (macros))
647 if (token->type != T_ID && token->type != T_MACRO_ID)
650 const struct macro *macro = macro_set_find (macros, token->string.string);
654 struct macro_expander *me = xmalloc (sizeof *me);
655 *me = (struct macro_expander) {
662 if (!macro->n_params)
666 me->state = (!macro->params[0].positional ? ME_KEYWORD
667 : macro->params[0].arg_type == ARG_ENCLOSE ? ME_ENCLOSE
669 me->args = xcalloc (macro->n_params, sizeof *me->args);
670 me->param = macro->params;
676 macro_expander_destroy (struct macro_expander *me)
681 for (size_t i = 0; i < me->macro->n_params; i++)
684 macro_tokens_uninit (me->args[i]);
691 /* Adds TOKEN to the collection of tokens in ME that potentially need to be
694 Returns -1 if the tokens added do not actually invoke a macro. The caller
695 should consume the first token without expanding it.
697 Returns 0 if the macro expander needs more tokens, for macro arguments or to
698 decide whether this is actually a macro invocation. The caller should call
699 macro_expander_add() again with the next token.
701 Returns a positive number to indicate that the returned number of tokens
702 invoke a macro. The number returned might be less than the number of tokens
703 added because it can take a few tokens of lookahead to determine whether the
704 macro invocation is finished. The caller should call
705 macro_expander_get_expansion() to obtain the expansion. */
707 macro_expander_add (struct macro_expander *me, const struct macro_token *mt)
715 return me_add_arg (me, mt);
718 return me_enclose (me, mt);
721 return me_keyword (me, mt);
724 return me_equals (me, mt);
731 /* Each argument to a macro function is one of:
733 - A quoted string or other single literal token.
735 - An argument to the macro being expanded, e.g. !1 or a named argument.
739 - A function invocation.
741 Each function invocation yields a character sequence to be turned into a
742 sequence of tokens. The case where that character sequence is a single
743 quoted string is an important special case.
745 struct parse_macro_function_ctx
747 const struct macro_token *input;
749 int nesting_countdown;
750 const struct macro_set *macros;
751 const struct macro_expander *me;
752 struct string_map *vars;
757 macro_expand (const struct macro_tokens *,
758 int nesting_countdown, const struct macro_set *,
759 const struct macro_expander *, struct string_map *vars,
760 bool *expand, bool *break_, struct macro_tokens *exp);
763 expand_macro_function (struct parse_macro_function_ctx *ctx,
764 struct string *output, size_t *input_consumed);
766 /* Returns true if the pair of tokens starting at offset OFS within MTS are !*,
769 is_bang_star (const struct macro_token *mts, size_t n, size_t ofs)
772 && mts[ofs].token.type == T_MACRO_ID
773 && ss_equals (mts[ofs].token.string, ss_cstr ("!"))
774 && mts[ofs + 1].token.type == T_ASTERISK);
778 parse_function_arg (struct parse_macro_function_ctx *ctx,
779 size_t i, struct string *farg)
781 const struct macro_token *tokens = ctx->input;
782 const struct token *token = &tokens[i].token;
783 if (token->type == T_MACRO_ID)
785 const struct macro_param *param = macro_find_parameter_by_name (
786 ctx->me->macro, token->string);
789 size_t param_idx = param - ctx->me->macro->params;
790 const struct macro_tokens *marg = ctx->me->args[param_idx];
791 for (size_t i = 0; i < marg->n; i++)
794 ds_put_byte (farg, ' ');
795 ds_put_substring (farg, marg->mts[i].representation);
800 if (is_bang_star (ctx->input, ctx->n_input, i))
802 for (size_t i = 0; i < ctx->me->macro->n_params; i++)
804 if (!ctx->me->macro->params[i].positional)
807 const struct macro_tokens *marg = ctx->me->args[i];
808 for (size_t j = 0; j < marg->n; j++)
811 ds_put_byte (farg, ' ');
812 ds_put_substring (farg, marg->mts[j].representation);
820 const char *value = string_map_find__ (ctx->vars,
821 token->string.string,
822 token->string.length);
825 ds_put_cstr (farg, value);
830 struct parse_macro_function_ctx subctx = {
831 .input = &ctx->input[i],
832 .n_input = ctx->n_input - i,
833 .nesting_countdown = ctx->nesting_countdown,
834 .macros = ctx->macros,
837 .expand = ctx->expand,
839 size_t subinput_consumed;
840 if (expand_macro_function (&subctx, farg, &subinput_consumed))
841 return subinput_consumed;
844 ds_put_substring (farg, tokens[i].representation);
849 parse_macro_function (struct parse_macro_function_ctx *ctx,
850 struct string_array *args,
851 struct substring function,
852 int min_args, int max_args,
853 size_t *input_consumed)
855 const struct macro_token *tokens = ctx->input;
856 size_t n_tokens = ctx->n_input;
859 || tokens[0].token.type != T_MACRO_ID
860 || !ss_equals_case (tokens[0].token.string, function)) /* XXX abbrevs allowed */
863 if (n_tokens < 2 || tokens[1].token.type != T_LPAREN)
865 printf ("`(' expected following %s'\n", function.string);
869 string_array_init (args);
871 for (size_t i = 2;; )
875 if (tokens[i].token.type == T_RPAREN)
877 *input_consumed = i + 1;
878 if (args->n < min_args || args->n > max_args)
880 printf ("Wrong number of arguments to %s.\n", function.string);
886 struct string s = DS_EMPTY_INITIALIZER;
887 i += parse_function_arg (ctx, i, &s);
893 string_array_append_nocopy (args, ds_steal_cstr (&s));
895 if (tokens[i].token.type == T_COMMA)
897 else if (tokens[i].token.type != T_RPAREN)
899 printf ("Expecting `,' or `)' in %s invocation.", function.string);
905 printf ("Missing closing parenthesis in arguments to %s.\n",
909 string_array_destroy (args);
914 unquote_string (const char *s, struct string *content)
916 struct string_lexer slex;
917 string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE /* XXX */,
921 if (!string_lexer_next (&slex, &token1))
924 if (token1.type != T_STRING)
926 token_uninit (&token1);
931 if (string_lexer_next (&slex, &token2))
933 token_uninit (&token1);
934 token_uninit (&token2);
938 ds_put_substring (content, token1.string);
939 token_uninit (&token1);
944 unquote_string_in_place (const char *s, struct string *tmp)
947 return unquote_string (s, tmp) ? ds_cstr (tmp) : s;
951 parse_integer (const char *s, int *np)
956 long int n = strtol (s, &tail, 10);
957 *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
958 tail += strspn (tail, CC_SPACES);
959 return *tail == '\0' && errno != ERANGE && n == *np;
963 expand_macro_function (struct parse_macro_function_ctx *ctx,
964 struct string *output,
965 size_t *input_consumed)
967 struct string_array args;
969 if (parse_macro_function (ctx, &args, ss_cstr ("!length"), 1, 1,
971 ds_put_format (output, "%zu", strlen (args.strings[0]));
972 else if (parse_macro_function (ctx, &args, ss_cstr ("!blanks"), 1, 1,
976 if (!parse_integer (args.strings[0], &n))
978 printf ("argument to !BLANKS must be non-negative integer (not \"%s\")\n", args.strings[0]);
979 string_array_destroy (&args);
983 ds_put_byte_multiple (output, ' ', n);
985 else if (parse_macro_function (ctx, &args, ss_cstr ("!concat"), 1, INT_MAX,
988 for (size_t i = 0; i < args.n; i++)
989 if (!unquote_string (args.strings[i], output))
990 ds_put_cstr (output, args.strings[i]);
992 else if (parse_macro_function (ctx, &args, ss_cstr ("!head"), 1, 1,
996 const char *s = unquote_string_in_place (args.strings[0], &tmp);
998 struct macro_tokens mts = { .n = 0 };
999 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1001 ds_put_substring (output, mts.mts[0].representation);
1002 macro_tokens_uninit (&mts);
1005 else if (parse_macro_function (ctx, &args, ss_cstr ("!index"), 2, 2,
1008 const char *haystack = args.strings[0];
1009 const char *needle = strstr (haystack, args.strings[1]);
1010 ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1012 else if (parse_macro_function (ctx, &args, ss_cstr ("!quote"), 1, 1,
1015 if (unquote_string (args.strings[0], NULL))
1016 ds_put_cstr (output, args.strings[0]);
1019 ds_extend (output, strlen (args.strings[0]) + 2);
1020 ds_put_byte (output, '\'');
1021 for (const char *p = args.strings[0]; *p; p++)
1024 ds_put_byte (output, '\'');
1025 ds_put_byte (output, *p);
1027 ds_put_byte (output, '\'');
1030 else if (parse_macro_function (ctx, &args, ss_cstr ("!substr"), 2, 3,
1034 if (!parse_integer (args.strings[1], &start) || start < 1)
1036 printf ("second argument to !SUBSTR must be positive integer (not \"%s\")\n", args.strings[1]);
1037 string_array_destroy (&args);
1041 int count = INT_MAX;
1042 if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1044 printf ("third argument to !SUBSTR must be non-negative integer (not \"%s\")\n", args.strings[1]);
1045 string_array_destroy (&args);
1049 struct substring s = ss_cstr (args.strings[0]);
1050 ds_put_substring (output, ss_substr (s, start - 1, count));
1052 else if (parse_macro_function (ctx, &args, ss_cstr ("!tail"), 1, 1,
1056 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1058 struct macro_tokens mts = { .n = 0 };
1059 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1062 struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1063 macro_tokens_to_representation (&tail, output);
1065 macro_tokens_uninit (&mts);
1068 else if (parse_macro_function (ctx, &args, ss_cstr ("!unquote"), 1, 1,
1071 if (!unquote_string (args.strings[0], output))
1072 ds_put_cstr (output, args.strings[0]);
1074 else if (parse_macro_function (ctx, &args, ss_cstr ("!upcase"), 1, 1,
1078 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1079 char *upper = utf8_to_upper (s);
1080 ds_put_cstr (output, upper);
1084 else if (parse_macro_function (ctx, &args, ss_cstr ("!eval"), 1, 1,
1087 struct macro_tokens mts = { .n = 0 };
1088 macro_tokens_from_string (&mts, ss_cstr (args.strings[0]),
1089 SEG_MODE_INTERACTIVE /* XXX */);
1090 struct macro_tokens exp = { .n = 0 };
1091 macro_expand (&mts, ctx->nesting_countdown - 1, ctx->macros, ctx->me,
1092 ctx->vars, ctx->expand, NULL, &exp);
1093 macro_tokens_to_representation (&exp, output);
1094 macro_tokens_uninit (&exp);
1095 macro_tokens_uninit (&mts);
1097 else if (ctx->n_input > 0
1098 && ctx->input[0].token.type == T_MACRO_ID
1099 && ss_equals_case (ctx->input[0].token.string, ss_cstr ("!null")))
1101 *input_consumed = 1;
1107 string_array_destroy (&args);
1113 int nesting_countdown;
1114 const struct macro_set *macros;
1115 const struct macro_expander *me;
1116 struct string_map *vars;
1120 static char *macro_evaluate_or (const struct expr_context *ctx,
1121 const struct macro_token **tokens,
1122 const struct macro_token *end);
1125 macro_evaluate_literal (const struct expr_context *ctx,
1126 const struct macro_token **tokens,
1127 const struct macro_token *end)
1129 const struct macro_token *p = *tokens;
1132 if (p->token.type == T_LPAREN)
1135 char *value = macro_evaluate_or (ctx, &p, end);
1138 if (p >= end || p->token.type != T_RPAREN)
1141 printf ("expecting ')' in macro expression\n");
1149 struct parse_macro_function_ctx fctx = {
1152 .nesting_countdown = ctx->nesting_countdown,
1153 .macros = ctx->macros,
1156 .expand = ctx->expand,
1158 struct string function_output = DS_EMPTY_INITIALIZER;
1159 size_t function_consumed = parse_function_arg (&fctx, 0, &function_output);
1160 struct string unquoted = DS_EMPTY_INITIALIZER;
1161 if (unquote_string (ds_cstr (&function_output), &unquoted))
1163 ds_swap (&function_output, &unquoted);
1164 ds_destroy (&unquoted);
1166 *tokens = p + function_consumed;
1167 return ds_steal_cstr (&function_output);
1170 /* Returns true if MT is valid as a macro operator. Only operators written as
1171 symbols (e.g. <>) are usable in macro expressions, not operator written as
1172 letters (e.g. EQ). */
1174 is_macro_operator (const struct macro_token *mt)
1176 return (mt->representation.length > 0
1177 && !c_isalpha (mt->representation.string[0]));
1180 static enum token_type
1181 parse_relational_op (const struct macro_token *mt)
1183 switch (mt->token.type)
1193 return is_macro_operator (mt) ? mt->token.type : T_STOP;
1196 return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1197 : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1198 : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1199 : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1200 : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1201 : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1210 macro_evaluate_relational (const struct expr_context *ctx,
1211 const struct macro_token **tokens,
1212 const struct macro_token *end)
1214 const struct macro_token *p = *tokens;
1215 char *lhs = macro_evaluate_literal (ctx, &p, end);
1219 enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1227 char *rhs = macro_evaluate_literal (ctx, &p, end);
1234 struct string lhs_tmp, rhs_tmp;
1235 int cmp = strcmp/*XXX*/ (unquote_string_in_place (lhs, &lhs_tmp),
1236 unquote_string_in_place (rhs, &rhs_tmp));
1237 ds_destroy (&lhs_tmp);
1238 ds_destroy (&rhs_tmp);
1243 bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1245 : op == T_LT ? cmp < 0
1246 : op == T_GT ? cmp > 0
1247 : op == T_LE ? cmp <= 0
1248 :/*op == T_GE*/cmp >= 0);
1251 return xstrdup (b ? "1" : "0");
1255 macro_evaluate_not (const struct expr_context *ctx,
1256 const struct macro_token **tokens,
1257 const struct macro_token *end)
1259 const struct macro_token *p = *tokens;
1261 unsigned int negations = 0;
1263 && (ss_equals_case (p->representation, ss_cstr ("!NOT"))
1264 || ss_equals (p->representation, ss_cstr ("~"))))
1270 char *operand = macro_evaluate_relational (ctx, &p, end);
1271 if (!operand || !negations)
1277 bool b = strcmp (operand, "0") ^ (negations & 1);
1280 return xstrdup (b ? "1" : "0");
1284 macro_evaluate_and (const struct expr_context *ctx,
1285 const struct macro_token **tokens,
1286 const struct macro_token *end)
1288 const struct macro_token *p = *tokens;
1289 char *lhs = macro_evaluate_not (ctx, &p, end);
1294 && (ss_equals_case (p->representation, ss_cstr ("!AND"))
1295 || ss_equals (p->representation, ss_cstr ("&"))))
1298 char *rhs = macro_evaluate_not (ctx, &p, end);
1305 bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1308 lhs = xstrdup (b ? "1" : "0");
1315 macro_evaluate_or (const struct expr_context *ctx,
1316 const struct macro_token **tokens,
1317 const struct macro_token *end)
1319 const struct macro_token *p = *tokens;
1320 char *lhs = macro_evaluate_and (ctx, &p, end);
1325 && (ss_equals_case (p->representation, ss_cstr ("!OR"))
1326 || ss_equals (p->representation, ss_cstr ("|"))))
1329 char *rhs = macro_evaluate_and (ctx, &p, end);
1336 bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1339 lhs = xstrdup (b ? "1" : "0");
1346 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1347 int nesting_countdown, const struct macro_set *macros,
1348 const struct macro_expander *me, struct string_map *vars,
1351 const struct expr_context ctx = {
1352 .nesting_countdown = nesting_countdown,
1358 return macro_evaluate_or (&ctx, tokens, *tokens + n_tokens);
1362 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1363 int nesting_countdown, const struct macro_set *macros,
1364 const struct macro_expander *me, struct string_map *vars,
1365 bool *expand, double *number)
1367 char *s = macro_evaluate_expression (tokens, n_tokens, nesting_countdown,
1368 macros, me, vars, expand);
1372 struct macro_tokens mts = { .n = 0 };
1373 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1374 if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1376 macro_tokens_print (&mts, stdout);
1377 printf ("expression must evaluate to a number (not %s)\n", s);
1379 macro_tokens_uninit (&mts);
1383 *number = token_number (&mts.mts[0].token);
1385 macro_tokens_uninit (&mts);
1389 static const struct macro_token *
1390 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1393 for (; p < end; p++)
1395 if (p->token.type != T_MACRO_ID)
1398 if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1400 else if (ss_equals_case (p->token.string, ss_cstr ("!IFEND")))
1406 else if (ss_equals_case (p->token.string, ss_cstr ("!ELSE")) && !nesting)
1413 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1414 int nesting_countdown, const struct macro_set *macros,
1415 const struct macro_expander *me, struct string_map *vars,
1416 bool *expand, bool *break_, struct macro_tokens *exp)
1418 const struct macro_token *p = tokens;
1419 const struct macro_token *end = tokens + n_tokens;
1421 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1425 char *result = macro_evaluate_expression (&p, end - p,
1426 nesting_countdown, macros, me, vars,
1430 bool b = strcmp (result, "0");
1434 || p->token.type != T_MACRO_ID
1435 || !ss_equals_case (p->token.string, ss_cstr ("!THEN")))
1437 printf ("!THEN expected\n");
1441 const struct macro_token *start_then = p + 1;
1442 const struct macro_token *end_then = find_ifend_clause (start_then, end);
1445 printf ("!ELSE or !IFEND expected\n");
1449 const struct macro_token *start_else, *end_if;
1450 if (ss_equals_case (end_then->token.string, ss_cstr ("!ELSE")))
1452 start_else = end_then + 1;
1453 end_if = find_ifend_clause (start_else, end);
1455 || !ss_equals_case (end_if->token.string, ss_cstr ("!IFEND")))
1457 printf ("!IFEND expected\n");
1467 const struct macro_token *start;
1472 n = end_then - start_then;
1474 else if (start_else)
1477 n = end_if - start_else;
1487 struct macro_tokens mts = {
1488 .mts = CONST_CAST (struct macro_token *, start),
1491 macro_expand (&mts, nesting_countdown, macros, me, vars, expand,
1494 return (end_if + 1) - tokens;
1498 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1499 int nesting_countdown, const struct macro_set *macros,
1500 const struct macro_expander *me, struct string_map *vars,
1503 const struct macro_token *p = tokens;
1504 const struct macro_token *end = tokens + n_tokens;
1506 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1510 if (p >= end || p->token.type != T_MACRO_ID)
1512 printf ("expected macro variable name following !LET\n");
1515 const struct substring var_name = p->token.string;
1516 if (is_macro_keyword (var_name)
1517 || macro_find_parameter_by_name (me->macro, var_name))
1519 printf ("cannot use argument name or macro keyword as !LET variable\n");
1524 if (p >= end || p->token.type != T_EQUALS)
1526 printf ("expected = following !LET\n");
1531 char *value = macro_evaluate_expression (&p, end - p,
1532 nesting_countdown, macros, me, vars,
1537 string_map_replace_nocopy (vars, ss_xstrdup (var_name), value);
1541 static const struct macro_token *
1542 find_doend (const struct macro_token *p, const struct macro_token *end)
1545 for (; p < end; p++)
1547 if (p->token.type != T_MACRO_ID)
1550 if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1552 else if (ss_equals_case (p->token.string, ss_cstr ("!DOEND")))
1559 printf ("missing !DOEND\n");
1564 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1565 int nesting_countdown, const struct macro_set *macros,
1566 const struct macro_expander *me, struct string_map *vars,
1567 bool *expand, struct macro_tokens *exp)
1569 const struct macro_token *p = tokens;
1570 const struct macro_token *end = tokens + n_tokens;
1572 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1576 if (p >= end || p->token.type != T_MACRO_ID)
1578 printf ("expected macro variable name following !DO\n");
1581 const struct substring var_name = p->token.string;
1582 if (is_macro_keyword (var_name)
1583 || macro_find_parameter_by_name (me->macro, var_name))
1585 printf ("cannot use argument name or macro keyword as !DO variable\n");
1590 int miterate = settings_get_miterate ();
1591 if (p < end && p->token.type == T_MACRO_ID
1592 && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1595 char *list = macro_evaluate_expression (&p, end - p,
1596 nesting_countdown, macros, me, vars,
1601 struct macro_tokens items = { .n = 0 };
1602 macro_tokens_from_string (&items, ss_cstr (list),
1603 SEG_MODE_INTERACTIVE /* XXX */);
1606 const struct macro_token *do_end = find_doend (p, end);
1609 macro_tokens_uninit (&items);
1613 const struct macro_tokens inner = {
1614 .mts = CONST_CAST (struct macro_token *, p),
1617 for (size_t i = 0; i < items.n; i++)
1621 printf ("exceeded maximum number of iterations %d\n", miterate);
1624 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1625 ss_xstrdup (items.mts[i].representation));
1627 bool break_ = false;
1628 macro_expand (&inner, nesting_countdown, macros,
1629 me, vars, expand, &break_, exp);
1633 return do_end - tokens + 1;
1635 else if (p < end && p->token.type == T_EQUALS)
1639 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1640 vars, expand, &first))
1643 if (p >= end || p->token.type != T_MACRO_ID
1644 || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1646 printf ("expecting !TO\n");
1652 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1653 vars, expand, &last))
1657 if (p < end && p->token.type == T_MACRO_ID
1658 && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1661 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1667 printf ("!BY value cannot be zero\n");
1672 const struct macro_token *do_end = find_doend (p, end);
1675 const struct macro_tokens inner = {
1676 .mts = CONST_CAST (struct macro_token *, p),
1680 if ((by > 0 && first <= last) || (by < 0 && first >= last))
1683 for (double index = first;
1684 by > 0 ? (index <= last) : (index >= last);
1689 printf ("exceeded maximum number of iterations %d\n",
1694 char index_s[DBL_BUFSIZE_BOUND];
1695 c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1696 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1699 bool break_ = false;
1700 macro_expand (&inner, nesting_countdown, macros,
1701 me, vars, expand, &break_, exp);
1707 return do_end - tokens + 1;
1711 printf ("expecting = or !IN in !DO loop\n");
1717 macro_expand (const struct macro_tokens *mts,
1718 int nesting_countdown, const struct macro_set *macros,
1719 const struct macro_expander *me, struct string_map *vars,
1720 bool *expand, bool *break_, struct macro_tokens *exp)
1722 if (nesting_countdown <= 0)
1724 printf ("maximum nesting level exceeded\n");
1725 for (size_t i = 0; i < mts->n; i++)
1726 macro_tokens_add (exp, &mts->mts[i]);
1730 struct string_map own_vars = STRING_MAP_INITIALIZER (own_vars);
1734 for (size_t i = 0; i < mts->n && (!break_ || !*break_); i++)
1736 const struct macro_token *mt = &mts->mts[i];
1737 const struct token *token = &mt->token;
1738 if (token->type == T_MACRO_ID && me)
1740 const struct macro_param *param = macro_find_parameter_by_name (
1741 me->macro, token->string);
1744 const struct macro_tokens *arg = me->args[param - me->macro->params];
1745 //macro_tokens_print (arg, stdout);
1746 if (*expand && param->expand_arg)
1747 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1748 expand, break_, exp);
1750 for (size_t i = 0; i < arg->n; i++)
1751 macro_tokens_add (exp, &arg->mts[i]);
1755 if (is_bang_star (mts->mts, mts->n, i))
1757 for (size_t j = 0; j < me->macro->n_params; j++)
1759 const struct macro_param *param = &me->macro->params[j];
1760 if (!param->positional)
1763 const struct macro_tokens *arg = me->args[j];
1764 if (*expand && param->expand_arg)
1765 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1766 expand, break_, exp);
1768 for (size_t k = 0; k < arg->n; k++)
1769 macro_tokens_add (exp, &arg->mts[k]);
1775 size_t n = macro_expand_if (&mts->mts[i], mts->n - i,
1776 nesting_countdown, macros, me, vars,
1777 expand, break_, exp);
1785 if (token->type == T_MACRO_ID && vars)
1787 const char *value = string_map_find__ (vars, token->string.string,
1788 token->string.length);
1791 macro_tokens_from_string (exp, ss_cstr (value),
1792 SEG_MODE_INTERACTIVE /* XXX */);
1799 struct macro_expander *subme;
1800 int retval = macro_expander_create (macros, token, &subme);
1801 for (size_t j = 1; !retval; j++)
1803 const struct macro_token endcmd = { .token = { .type = T_ENDCMD } };
1804 retval = macro_expander_add (
1805 subme, i + j < mts->n ? &mts->mts[i + j] : &endcmd);
1810 macro_expand (&subme->macro->body, nesting_countdown - 1, macros,
1811 subme, NULL, expand, break_, exp);
1812 macro_expander_destroy (subme);
1816 macro_expander_destroy (subme);
1819 if (token->type != T_MACRO_ID)
1821 macro_tokens_add (exp, mt);
1825 if (ss_equals_case (token->string, ss_cstr ("!break")))
1828 printf ("!BREAK outside !DO\n");
1836 struct parse_macro_function_ctx ctx = {
1837 .input = &mts->mts[i],
1838 .n_input = mts->n - i,
1839 .nesting_countdown = nesting_countdown,
1845 struct string function_output = DS_EMPTY_INITIALIZER;
1846 size_t function_consumed;
1847 if (expand_macro_function (&ctx, &function_output, &function_consumed))
1849 i += function_consumed - 1;
1851 macro_tokens_from_string (exp, function_output.ss,
1852 SEG_MODE_INTERACTIVE /* XXX */);
1853 ds_destroy (&function_output);
1858 size_t n = macro_parse_let (&mts->mts[i], mts->n - i,
1859 nesting_countdown, macros, me, vars,
1867 n = macro_expand_do (&mts->mts[i], mts->n - i,
1868 nesting_countdown, macros, me, vars,
1876 if (ss_equals_case (token->string, ss_cstr ("!onexpand")))
1878 else if (ss_equals_case (token->string, ss_cstr ("!offexpand")))
1881 macro_tokens_add (exp, mt);
1883 if (vars == &own_vars)
1884 string_map_destroy (&own_vars);
1888 macro_expander_get_expansion (struct macro_expander *me, struct macro_tokens *exp)
1891 for (size_t i = 0; i < me->macro->n_params; i++)
1893 printf ("%s:\n", me->macro->params[i].name);
1894 macro_tokens_print (me->args[i], stdout);
1899 macro_expand (&me->macro->body, settings_get_mnest (),
1900 me->macros, me, NULL, &expand, NULL, exp);
1903 printf ("expansion:\n");
1904 macro_tokens_print (exp, stdout);