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,
291 size_t *ofs, size_t *len)
293 assert ((ofs != NULL) == (len != NULL));
298 for (size_t i = 0; i < mts->n; i++)
302 enum token_type prev = mts->mts[i - 1].token.type;
303 enum token_type next = mts->mts[i].token.type;
305 if (prev == T_ENDCMD)
306 ds_put_byte (s, '\n');
309 enum token_class pc = classify_token (prev);
310 enum token_class nc = classify_token (next);
311 if (needs_space (pc, nc))
312 ds_put_byte (s, ' ');
317 ofs[i] = s->ss.length;
318 macro_token_to_representation (&mts->mts[i], s);
320 len[i] = s->ss.length - ofs[i];
325 macro_destroy (struct macro *m)
331 for (size_t i = 0; i < m->n_params; i++)
333 struct macro_param *p = &m->params[i];
336 macro_tokens_uninit (&p->def);
344 token_uninit (&p->charend);
348 token_uninit (&p->enclose[0]);
349 token_uninit (&p->enclose[1]);
357 macro_tokens_uninit (&m->body);
362 macro_set_create (void)
364 struct macro_set *set = xmalloc (sizeof *set);
365 *set = (struct macro_set) {
366 .macros = HMAP_INITIALIZER (set->macros),
372 macro_set_destroy (struct macro_set *set)
377 struct macro *macro, *next;
378 HMAP_FOR_EACH_SAFE (macro, next, struct macro, hmap_node, &set->macros)
380 hmap_delete (&set->macros, ¯o->hmap_node);
381 macro_destroy (macro);
383 hmap_destroy (&set->macros);
388 hash_macro_name (const char *name)
390 return utf8_hash_case_string (name, 0);
393 static struct macro *
394 macro_set_find__ (struct macro_set *set, const char *name)
397 HMAP_FOR_EACH_WITH_HASH (macro, struct macro, hmap_node,
398 hash_macro_name (name), &set->macros)
399 if (!utf8_strcasecmp (macro->name, name))
406 macro_set_find (const struct macro_set *set, const char *name)
408 return macro_set_find__ (CONST_CAST (struct macro_set *, set), name);
411 /* Adds M to SET. M replaces any existing macro with the same name. Takes
414 macro_set_add (struct macro_set *set, struct macro *m)
416 struct macro *victim = macro_set_find__ (set, m->name);
419 hmap_delete (&set->macros, &victim->hmap_node);
420 macro_destroy (victim);
423 hmap_insert (&set->macros, &m->hmap_node, hash_macro_name (m->name));
431 /* Accumulating tokens in me->params toward the end of any type of
435 /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
438 /* Expecting a keyword for a keyword argument. */
441 /* Expecting an equal sign for a keyword argument. */
446 struct macro_expander
448 const struct macro_set *macros;
453 const struct macro *macro;
454 struct macro_tokens **args;
455 const struct macro_param *param;
459 me_finished (struct macro_expander *me)
461 for (size_t i = 0; i < me->macro->n_params; i++)
464 me->args[i] = xmalloc (sizeof *me->args[i]);
465 macro_tokens_copy (me->args[i], &me->macro->params[i].def);
471 me_next_arg (struct macro_expander *me)
475 assert (!me->macro->n_params);
476 return me_finished (me);
478 else if (me->param->positional)
481 if (me->param >= &me->macro->params[me->macro->n_params])
482 return me_finished (me);
485 me->state = (!me->param->positional ? ME_KEYWORD
486 : me->param->arg_type == ARG_ENCLOSE ? ME_ENCLOSE
493 for (size_t i = 0; i < me->macro->n_params; i++)
496 me->state = ME_KEYWORD;
499 return me_finished (me);
504 me_error (struct macro_expander *me)
506 me->state = ME_ERROR;
511 me_add_arg (struct macro_expander *me, const struct macro_token *mt)
513 const struct macro_param *p = me->param;
515 const struct token *token = &mt->token;
516 if ((token->type == T_ENDCMD || token->type == T_STOP)
517 && p->arg_type != ARG_CMDEND)
519 msg (SE, _("Unexpected end of command reading argument %s "
520 "to macro %s."), me->param->name, me->macro->name);
522 return me_error (me);
527 struct macro_tokens **argp = &me->args[p - me->macro->params];
529 *argp = xzalloc (sizeof **argp);
530 struct macro_tokens *arg = *argp;
531 if (p->arg_type == ARG_N_TOKENS)
533 macro_tokens_add (arg, mt);
534 if (arg->n >= p->n_tokens)
535 return me_next_arg (me);
538 else if (p->arg_type == ARG_CMDEND)
540 if (token->type == T_ENDCMD || token->type == T_STOP)
541 return me_next_arg (me);
542 macro_tokens_add (arg, mt);
547 const struct token *end
548 = p->arg_type == ARG_CHAREND ? &p->charend : &p->enclose[1];
549 if (token_equal (token, end))
550 return me_next_arg (me);
551 macro_tokens_add (arg, mt);
557 me_expected (struct macro_expander *me, const struct macro_token *actual,
558 const struct token *expected)
560 const struct substring actual_s
561 = (actual->representation.length ? actual->representation
562 : ss_cstr (_("<end of input>")));
563 char *expected_s = token_to_string (expected);
564 msg (SE, _("Found `%.*s' while expecting `%s' reading argument %s "
566 (int) actual_s.length, actual_s.string, expected_s,
567 me->param->name, me->macro->name);
570 return me_error (me);
574 me_enclose (struct macro_expander *me, const struct macro_token *mt)
576 const struct token *token = &mt->token;
579 if (token_equal (&me->param->enclose[0], token))
585 return me_expected (me, mt, &me->param->enclose[0]);
588 static const struct macro_param *
589 macro_find_parameter_by_name (const struct macro *m, struct substring name)
591 ss_ltrim (&name, ss_cstr ("!"));
593 for (size_t i = 0; i < m->n_params; i++)
595 const struct macro_param *p = &m->params[i];
596 struct substring p_name = ss_cstr (p->name + 1);
597 if (!utf8_strncasecmp (p_name.string, p_name.length,
598 name.string, name.length))
605 me_keyword (struct macro_expander *me, const struct macro_token *mt)
607 const struct token *token = &mt->token;
608 if (token->type != T_ID)
609 return me_finished (me);
611 const struct macro_param *p = macro_find_parameter_by_name (me->macro,
615 size_t arg_index = p - me->macro->params;
617 if (me->args[arg_index])
620 _("Argument %s multiply specified in call to macro %s."),
621 p->name, me->macro->name);
622 return me_error (me);
626 me->state = ME_EQUALS;
630 return me_finished (me);
634 me_equals (struct macro_expander *me, const struct macro_token *mt)
636 const struct token *token = &mt->token;
639 if (token->type == T_EQUALS)
645 return me_expected (me, mt, &(struct token) { .type = T_EQUALS });
649 macro_expander_create (const struct macro_set *macros,
650 const struct token *token,
651 struct macro_expander **mep)
654 if (macro_set_is_empty (macros))
656 if (token->type != T_ID && token->type != T_MACRO_ID)
659 const struct macro *macro = macro_set_find (macros, token->string.string);
663 struct macro_expander *me = xmalloc (sizeof *me);
664 *me = (struct macro_expander) {
671 if (!macro->n_params)
675 me->state = (!macro->params[0].positional ? ME_KEYWORD
676 : macro->params[0].arg_type == ARG_ENCLOSE ? ME_ENCLOSE
678 me->args = xcalloc (macro->n_params, sizeof *me->args);
679 me->param = macro->params;
685 macro_expander_destroy (struct macro_expander *me)
690 for (size_t i = 0; i < me->macro->n_params; i++)
693 macro_tokens_uninit (me->args[i]);
700 /* Adds TOKEN to the collection of tokens in ME that potentially need to be
703 Returns -1 if the tokens added do not actually invoke a macro. The caller
704 should consume the first token without expanding it.
706 Returns 0 if the macro expander needs more tokens, for macro arguments or to
707 decide whether this is actually a macro invocation. The caller should call
708 macro_expander_add() again with the next token.
710 Returns a positive number to indicate that the returned number of tokens
711 invoke a macro. The number returned might be less than the number of tokens
712 added because it can take a few tokens of lookahead to determine whether the
713 macro invocation is finished. The caller should call
714 macro_expander_get_expansion() to obtain the expansion. */
716 macro_expander_add (struct macro_expander *me, const struct macro_token *mt)
724 return me_add_arg (me, mt);
727 return me_enclose (me, mt);
730 return me_keyword (me, mt);
733 return me_equals (me, mt);
740 /* Each argument to a macro function is one of:
742 - A quoted string or other single literal token.
744 - An argument to the macro being expanded, e.g. !1 or a named argument.
748 - A function invocation.
750 Each function invocation yields a character sequence to be turned into a
751 sequence of tokens. The case where that character sequence is a single
752 quoted string is an important special case.
754 struct parse_macro_function_ctx
756 const struct macro_token *input;
758 int nesting_countdown;
759 const struct macro_set *macros;
760 const struct macro_expander *me;
761 struct string_map *vars;
766 macro_expand (const struct macro_tokens *,
767 int nesting_countdown, const struct macro_set *,
768 const struct macro_expander *, struct string_map *vars,
769 bool *expand, bool *break_, struct macro_tokens *exp);
772 expand_macro_function (struct parse_macro_function_ctx *ctx,
773 struct string *output, size_t *input_consumed);
775 /* Returns true if the pair of tokens starting at offset OFS within MTS are !*,
778 is_bang_star (const struct macro_token *mts, size_t n, size_t ofs)
781 && mts[ofs].token.type == T_MACRO_ID
782 && ss_equals (mts[ofs].token.string, ss_cstr ("!"))
783 && mts[ofs + 1].token.type == T_ASTERISK);
787 parse_function_arg (struct parse_macro_function_ctx *ctx,
788 size_t i, struct string *farg)
790 const struct macro_token *tokens = ctx->input;
791 const struct token *token = &tokens[i].token;
792 if (token->type == T_MACRO_ID)
794 const struct macro_param *param = macro_find_parameter_by_name (
795 ctx->me->macro, token->string);
798 size_t param_idx = param - ctx->me->macro->params;
799 const struct macro_tokens *marg = ctx->me->args[param_idx];
800 for (size_t i = 0; i < marg->n; i++)
803 ds_put_byte (farg, ' ');
804 ds_put_substring (farg, marg->mts[i].representation);
809 if (is_bang_star (ctx->input, ctx->n_input, i))
811 for (size_t i = 0; i < ctx->me->macro->n_params; i++)
813 if (!ctx->me->macro->params[i].positional)
816 const struct macro_tokens *marg = ctx->me->args[i];
817 for (size_t j = 0; j < marg->n; j++)
820 ds_put_byte (farg, ' ');
821 ds_put_substring (farg, marg->mts[j].representation);
829 const char *value = string_map_find__ (ctx->vars,
830 token->string.string,
831 token->string.length);
834 ds_put_cstr (farg, value);
839 struct parse_macro_function_ctx subctx = {
840 .input = &ctx->input[i],
841 .n_input = ctx->n_input - i,
842 .nesting_countdown = ctx->nesting_countdown,
843 .macros = ctx->macros,
846 .expand = ctx->expand,
848 size_t subinput_consumed;
849 if (expand_macro_function (&subctx, farg, &subinput_consumed))
850 return subinput_consumed;
853 ds_put_substring (farg, tokens[i].representation);
858 parse_macro_function (struct parse_macro_function_ctx *ctx,
859 struct string_array *args,
860 struct substring function,
861 int min_args, int max_args,
862 size_t *input_consumed)
864 const struct macro_token *tokens = ctx->input;
865 size_t n_tokens = ctx->n_input;
868 || tokens[0].token.type != T_MACRO_ID
869 || !ss_equals_case (tokens[0].token.string, function)) /* XXX abbrevs allowed */
872 if (n_tokens < 2 || tokens[1].token.type != T_LPAREN)
874 printf ("`(' expected following %s'\n", function.string);
878 string_array_init (args);
880 for (size_t i = 2;; )
884 if (tokens[i].token.type == T_RPAREN)
886 *input_consumed = i + 1;
887 if (args->n < min_args || args->n > max_args)
889 printf ("Wrong number of arguments to %s.\n", function.string);
895 struct string s = DS_EMPTY_INITIALIZER;
896 i += parse_function_arg (ctx, i, &s);
902 string_array_append_nocopy (args, ds_steal_cstr (&s));
904 if (tokens[i].token.type == T_COMMA)
906 else if (tokens[i].token.type != T_RPAREN)
908 printf ("Expecting `,' or `)' in %s invocation.", function.string);
914 printf ("Missing closing parenthesis in arguments to %s.\n",
918 string_array_destroy (args);
923 unquote_string (const char *s, struct string *content)
925 struct string_lexer slex;
926 string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE /* XXX */,
930 if (!string_lexer_next (&slex, &token1))
933 if (token1.type != T_STRING)
935 token_uninit (&token1);
940 if (string_lexer_next (&slex, &token2))
942 token_uninit (&token1);
943 token_uninit (&token2);
947 ds_put_substring (content, token1.string);
948 token_uninit (&token1);
953 unquote_string_in_place (const char *s, struct string *tmp)
956 return unquote_string (s, tmp) ? ds_cstr (tmp) : s;
960 parse_integer (const char *s, int *np)
965 long int n = strtol (s, &tail, 10);
966 *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
967 tail += strspn (tail, CC_SPACES);
968 return *tail == '\0' && errno != ERANGE && n == *np;
972 expand_macro_function (struct parse_macro_function_ctx *ctx,
973 struct string *output,
974 size_t *input_consumed)
976 struct string_array args;
978 if (parse_macro_function (ctx, &args, ss_cstr ("!length"), 1, 1,
980 ds_put_format (output, "%zu", strlen (args.strings[0]));
981 else if (parse_macro_function (ctx, &args, ss_cstr ("!blanks"), 1, 1,
985 if (!parse_integer (args.strings[0], &n))
987 printf ("argument to !BLANKS must be non-negative integer (not \"%s\")\n", args.strings[0]);
988 string_array_destroy (&args);
992 ds_put_byte_multiple (output, ' ', n);
994 else if (parse_macro_function (ctx, &args, ss_cstr ("!concat"), 1, INT_MAX,
997 for (size_t i = 0; i < args.n; i++)
998 if (!unquote_string (args.strings[i], output))
999 ds_put_cstr (output, args.strings[i]);
1001 else if (parse_macro_function (ctx, &args, ss_cstr ("!head"), 1, 1,
1005 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1007 struct macro_tokens mts = { .n = 0 };
1008 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1010 ds_put_substring (output, mts.mts[0].representation);
1011 macro_tokens_uninit (&mts);
1014 else if (parse_macro_function (ctx, &args, ss_cstr ("!index"), 2, 2,
1017 const char *haystack = args.strings[0];
1018 const char *needle = strstr (haystack, args.strings[1]);
1019 ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1021 else if (parse_macro_function (ctx, &args, ss_cstr ("!quote"), 1, 1,
1024 if (unquote_string (args.strings[0], NULL))
1025 ds_put_cstr (output, args.strings[0]);
1028 ds_extend (output, strlen (args.strings[0]) + 2);
1029 ds_put_byte (output, '\'');
1030 for (const char *p = args.strings[0]; *p; p++)
1033 ds_put_byte (output, '\'');
1034 ds_put_byte (output, *p);
1036 ds_put_byte (output, '\'');
1039 else if (parse_macro_function (ctx, &args, ss_cstr ("!substr"), 2, 3,
1043 if (!parse_integer (args.strings[1], &start) || start < 1)
1045 printf ("second argument to !SUBSTR must be positive integer (not \"%s\")\n", args.strings[1]);
1046 string_array_destroy (&args);
1050 int count = INT_MAX;
1051 if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1053 printf ("third argument to !SUBSTR must be non-negative integer (not \"%s\")\n", args.strings[1]);
1054 string_array_destroy (&args);
1058 struct substring s = ss_cstr (args.strings[0]);
1059 ds_put_substring (output, ss_substr (s, start - 1, count));
1061 else if (parse_macro_function (ctx, &args, ss_cstr ("!tail"), 1, 1,
1065 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1067 struct macro_tokens mts = { .n = 0 };
1068 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1071 struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1072 macro_tokens_to_representation (&tail, output, NULL, NULL);
1074 macro_tokens_uninit (&mts);
1077 else if (parse_macro_function (ctx, &args, ss_cstr ("!unquote"), 1, 1,
1080 if (!unquote_string (args.strings[0], output))
1081 ds_put_cstr (output, args.strings[0]);
1083 else if (parse_macro_function (ctx, &args, ss_cstr ("!upcase"), 1, 1,
1087 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1088 char *upper = utf8_to_upper (s);
1089 ds_put_cstr (output, upper);
1093 else if (parse_macro_function (ctx, &args, ss_cstr ("!eval"), 1, 1,
1096 struct macro_tokens mts = { .n = 0 };
1097 macro_tokens_from_string (&mts, ss_cstr (args.strings[0]),
1098 SEG_MODE_INTERACTIVE /* XXX */);
1099 struct macro_tokens exp = { .n = 0 };
1100 macro_expand (&mts, ctx->nesting_countdown - 1, ctx->macros, ctx->me,
1101 ctx->vars, ctx->expand, NULL, &exp);
1102 macro_tokens_to_representation (&exp, output, NULL, NULL);
1103 macro_tokens_uninit (&exp);
1104 macro_tokens_uninit (&mts);
1106 else if (ctx->n_input > 0
1107 && ctx->input[0].token.type == T_MACRO_ID
1108 && ss_equals_case (ctx->input[0].token.string, ss_cstr ("!null")))
1110 *input_consumed = 1;
1116 string_array_destroy (&args);
1122 int nesting_countdown;
1123 const struct macro_set *macros;
1124 const struct macro_expander *me;
1125 struct string_map *vars;
1129 static char *macro_evaluate_or (const struct expr_context *ctx,
1130 const struct macro_token **tokens,
1131 const struct macro_token *end);
1134 macro_evaluate_literal (const struct expr_context *ctx,
1135 const struct macro_token **tokens,
1136 const struct macro_token *end)
1138 const struct macro_token *p = *tokens;
1141 if (p->token.type == T_LPAREN)
1144 char *value = macro_evaluate_or (ctx, &p, end);
1147 if (p >= end || p->token.type != T_RPAREN)
1150 printf ("expecting ')' in macro expression\n");
1158 struct parse_macro_function_ctx fctx = {
1161 .nesting_countdown = ctx->nesting_countdown,
1162 .macros = ctx->macros,
1165 .expand = ctx->expand,
1167 struct string function_output = DS_EMPTY_INITIALIZER;
1168 size_t function_consumed = parse_function_arg (&fctx, 0, &function_output);
1169 struct string unquoted = DS_EMPTY_INITIALIZER;
1170 if (unquote_string (ds_cstr (&function_output), &unquoted))
1172 ds_swap (&function_output, &unquoted);
1173 ds_destroy (&unquoted);
1175 *tokens = p + function_consumed;
1176 return ds_steal_cstr (&function_output);
1179 /* Returns true if MT is valid as a macro operator. Only operators written as
1180 symbols (e.g. <>) are usable in macro expressions, not operator written as
1181 letters (e.g. EQ). */
1183 is_macro_operator (const struct macro_token *mt)
1185 return (mt->representation.length > 0
1186 && !c_isalpha (mt->representation.string[0]));
1189 static enum token_type
1190 parse_relational_op (const struct macro_token *mt)
1192 switch (mt->token.type)
1202 return is_macro_operator (mt) ? mt->token.type : T_STOP;
1205 return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1206 : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1207 : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1208 : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1209 : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1210 : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1219 macro_evaluate_relational (const struct expr_context *ctx,
1220 const struct macro_token **tokens,
1221 const struct macro_token *end)
1223 const struct macro_token *p = *tokens;
1224 char *lhs = macro_evaluate_literal (ctx, &p, end);
1228 enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1236 char *rhs = macro_evaluate_literal (ctx, &p, end);
1243 struct string lhs_tmp, rhs_tmp;
1244 int cmp = strcmp/*XXX*/ (unquote_string_in_place (lhs, &lhs_tmp),
1245 unquote_string_in_place (rhs, &rhs_tmp));
1246 ds_destroy (&lhs_tmp);
1247 ds_destroy (&rhs_tmp);
1252 bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1254 : op == T_LT ? cmp < 0
1255 : op == T_GT ? cmp > 0
1256 : op == T_LE ? cmp <= 0
1257 :/*op == T_GE*/cmp >= 0);
1260 return xstrdup (b ? "1" : "0");
1264 macro_evaluate_not (const struct expr_context *ctx,
1265 const struct macro_token **tokens,
1266 const struct macro_token *end)
1268 const struct macro_token *p = *tokens;
1270 unsigned int negations = 0;
1272 && (ss_equals_case (p->representation, ss_cstr ("!NOT"))
1273 || ss_equals (p->representation, ss_cstr ("~"))))
1279 char *operand = macro_evaluate_relational (ctx, &p, end);
1280 if (!operand || !negations)
1286 bool b = strcmp (operand, "0") ^ (negations & 1);
1289 return xstrdup (b ? "1" : "0");
1293 macro_evaluate_and (const struct expr_context *ctx,
1294 const struct macro_token **tokens,
1295 const struct macro_token *end)
1297 const struct macro_token *p = *tokens;
1298 char *lhs = macro_evaluate_not (ctx, &p, end);
1303 && (ss_equals_case (p->representation, ss_cstr ("!AND"))
1304 || ss_equals (p->representation, ss_cstr ("&"))))
1307 char *rhs = macro_evaluate_not (ctx, &p, end);
1314 bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1317 lhs = xstrdup (b ? "1" : "0");
1324 macro_evaluate_or (const struct expr_context *ctx,
1325 const struct macro_token **tokens,
1326 const struct macro_token *end)
1328 const struct macro_token *p = *tokens;
1329 char *lhs = macro_evaluate_and (ctx, &p, end);
1334 && (ss_equals_case (p->representation, ss_cstr ("!OR"))
1335 || ss_equals (p->representation, ss_cstr ("|"))))
1338 char *rhs = macro_evaluate_and (ctx, &p, end);
1345 bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1348 lhs = xstrdup (b ? "1" : "0");
1355 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1356 int nesting_countdown, const struct macro_set *macros,
1357 const struct macro_expander *me, struct string_map *vars,
1360 const struct expr_context ctx = {
1361 .nesting_countdown = nesting_countdown,
1367 return macro_evaluate_or (&ctx, tokens, *tokens + n_tokens);
1371 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1372 int nesting_countdown, const struct macro_set *macros,
1373 const struct macro_expander *me, struct string_map *vars,
1374 bool *expand, double *number)
1376 char *s = macro_evaluate_expression (tokens, n_tokens, nesting_countdown,
1377 macros, me, vars, expand);
1381 struct macro_tokens mts = { .n = 0 };
1382 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1383 if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1385 macro_tokens_print (&mts, stdout);
1386 printf ("expression must evaluate to a number (not %s)\n", s);
1388 macro_tokens_uninit (&mts);
1392 *number = token_number (&mts.mts[0].token);
1394 macro_tokens_uninit (&mts);
1398 static const struct macro_token *
1399 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1402 for (; p < end; p++)
1404 if (p->token.type != T_MACRO_ID)
1407 if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1409 else if (ss_equals_case (p->token.string, ss_cstr ("!IFEND")))
1415 else if (ss_equals_case (p->token.string, ss_cstr ("!ELSE")) && !nesting)
1422 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1423 int nesting_countdown, const struct macro_set *macros,
1424 const struct macro_expander *me, struct string_map *vars,
1425 bool *expand, bool *break_, struct macro_tokens *exp)
1427 const struct macro_token *p = tokens;
1428 const struct macro_token *end = tokens + n_tokens;
1430 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1434 char *result = macro_evaluate_expression (&p, end - p,
1435 nesting_countdown, macros, me, vars,
1439 bool b = strcmp (result, "0");
1443 || p->token.type != T_MACRO_ID
1444 || !ss_equals_case (p->token.string, ss_cstr ("!THEN")))
1446 printf ("!THEN expected\n");
1450 const struct macro_token *start_then = p + 1;
1451 const struct macro_token *end_then = find_ifend_clause (start_then, end);
1454 printf ("!ELSE or !IFEND expected\n");
1458 const struct macro_token *start_else, *end_if;
1459 if (ss_equals_case (end_then->token.string, ss_cstr ("!ELSE")))
1461 start_else = end_then + 1;
1462 end_if = find_ifend_clause (start_else, end);
1464 || !ss_equals_case (end_if->token.string, ss_cstr ("!IFEND")))
1466 printf ("!IFEND expected\n");
1476 const struct macro_token *start;
1481 n = end_then - start_then;
1483 else if (start_else)
1486 n = end_if - start_else;
1496 struct macro_tokens mts = {
1497 .mts = CONST_CAST (struct macro_token *, start),
1500 macro_expand (&mts, nesting_countdown, macros, me, vars, expand,
1503 return (end_if + 1) - tokens;
1507 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1508 int nesting_countdown, const struct macro_set *macros,
1509 const struct macro_expander *me, struct string_map *vars,
1512 const struct macro_token *p = tokens;
1513 const struct macro_token *end = tokens + n_tokens;
1515 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1519 if (p >= end || p->token.type != T_MACRO_ID)
1521 printf ("expected macro variable name following !LET\n");
1524 const struct substring var_name = p->token.string;
1525 if (is_macro_keyword (var_name)
1526 || macro_find_parameter_by_name (me->macro, var_name))
1528 printf ("cannot use argument name or macro keyword as !LET variable\n");
1533 if (p >= end || p->token.type != T_EQUALS)
1535 printf ("expected = following !LET\n");
1540 char *value = macro_evaluate_expression (&p, end - p,
1541 nesting_countdown, macros, me, vars,
1546 string_map_replace_nocopy (vars, ss_xstrdup (var_name), value);
1550 static const struct macro_token *
1551 find_doend (const struct macro_token *p, const struct macro_token *end)
1554 for (; p < end; p++)
1556 if (p->token.type != T_MACRO_ID)
1559 if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1561 else if (ss_equals_case (p->token.string, ss_cstr ("!DOEND")))
1568 printf ("missing !DOEND\n");
1573 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1574 int nesting_countdown, const struct macro_set *macros,
1575 const struct macro_expander *me, struct string_map *vars,
1576 bool *expand, struct macro_tokens *exp)
1578 const struct macro_token *p = tokens;
1579 const struct macro_token *end = tokens + n_tokens;
1581 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1585 if (p >= end || p->token.type != T_MACRO_ID)
1587 printf ("expected macro variable name following !DO\n");
1590 const struct substring var_name = p->token.string;
1591 if (is_macro_keyword (var_name)
1592 || macro_find_parameter_by_name (me->macro, var_name))
1594 printf ("cannot use argument name or macro keyword as !DO variable\n");
1599 int miterate = settings_get_miterate ();
1600 if (p < end && p->token.type == T_MACRO_ID
1601 && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1604 char *list = macro_evaluate_expression (&p, end - p,
1605 nesting_countdown, macros, me, vars,
1610 struct macro_tokens items = { .n = 0 };
1611 macro_tokens_from_string (&items, ss_cstr (list),
1612 SEG_MODE_INTERACTIVE /* XXX */);
1615 const struct macro_token *do_end = find_doend (p, end);
1618 macro_tokens_uninit (&items);
1622 const struct macro_tokens inner = {
1623 .mts = CONST_CAST (struct macro_token *, p),
1626 for (size_t i = 0; i < items.n; i++)
1630 printf ("exceeded maximum number of iterations %d\n", miterate);
1633 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1634 ss_xstrdup (items.mts[i].representation));
1636 bool break_ = false;
1637 macro_expand (&inner, nesting_countdown, macros,
1638 me, vars, expand, &break_, exp);
1642 return do_end - tokens + 1;
1644 else if (p < end && p->token.type == T_EQUALS)
1648 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1649 vars, expand, &first))
1652 if (p >= end || p->token.type != T_MACRO_ID
1653 || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1655 printf ("expecting !TO\n");
1661 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1662 vars, expand, &last))
1666 if (p < end && p->token.type == T_MACRO_ID
1667 && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1670 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1676 printf ("!BY value cannot be zero\n");
1681 const struct macro_token *do_end = find_doend (p, end);
1684 const struct macro_tokens inner = {
1685 .mts = CONST_CAST (struct macro_token *, p),
1689 if ((by > 0 && first <= last) || (by < 0 && first >= last))
1692 for (double index = first;
1693 by > 0 ? (index <= last) : (index >= last);
1698 printf ("exceeded maximum number of iterations %d\n",
1703 char index_s[DBL_BUFSIZE_BOUND];
1704 c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1705 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1708 bool break_ = false;
1709 macro_expand (&inner, nesting_countdown, macros,
1710 me, vars, expand, &break_, exp);
1716 return do_end - tokens + 1;
1720 printf ("expecting = or !IN in !DO loop\n");
1726 macro_expand (const struct macro_tokens *mts,
1727 int nesting_countdown, const struct macro_set *macros,
1728 const struct macro_expander *me, struct string_map *vars,
1729 bool *expand, bool *break_, struct macro_tokens *exp)
1731 if (nesting_countdown <= 0)
1733 printf ("maximum nesting level exceeded\n");
1734 for (size_t i = 0; i < mts->n; i++)
1735 macro_tokens_add (exp, &mts->mts[i]);
1739 struct string_map own_vars = STRING_MAP_INITIALIZER (own_vars);
1743 for (size_t i = 0; i < mts->n && (!break_ || !*break_); i++)
1745 const struct macro_token *mt = &mts->mts[i];
1746 const struct token *token = &mt->token;
1747 if (token->type == T_MACRO_ID && me)
1749 const struct macro_param *param = macro_find_parameter_by_name (
1750 me->macro, token->string);
1753 const struct macro_tokens *arg = me->args[param - me->macro->params];
1754 //macro_tokens_print (arg, stdout);
1755 if (*expand && param->expand_arg)
1756 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1757 expand, break_, exp);
1759 for (size_t i = 0; i < arg->n; i++)
1760 macro_tokens_add (exp, &arg->mts[i]);
1764 if (is_bang_star (mts->mts, mts->n, i))
1766 for (size_t j = 0; j < me->macro->n_params; j++)
1768 const struct macro_param *param = &me->macro->params[j];
1769 if (!param->positional)
1772 const struct macro_tokens *arg = me->args[j];
1773 if (*expand && param->expand_arg)
1774 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1775 expand, break_, exp);
1777 for (size_t k = 0; k < arg->n; k++)
1778 macro_tokens_add (exp, &arg->mts[k]);
1784 size_t n = macro_expand_if (&mts->mts[i], mts->n - i,
1785 nesting_countdown, macros, me, vars,
1786 expand, break_, exp);
1794 if (token->type == T_MACRO_ID && vars)
1796 const char *value = string_map_find__ (vars, token->string.string,
1797 token->string.length);
1800 macro_tokens_from_string (exp, ss_cstr (value),
1801 SEG_MODE_INTERACTIVE /* XXX */);
1808 struct macro_expander *subme;
1809 int retval = macro_expander_create (macros, token, &subme);
1810 for (size_t j = 1; !retval; j++)
1812 const struct macro_token endcmd = { .token = { .type = T_ENDCMD } };
1813 retval = macro_expander_add (
1814 subme, i + j < mts->n ? &mts->mts[i + j] : &endcmd);
1819 macro_expand (&subme->macro->body, nesting_countdown - 1, macros,
1820 subme, NULL, expand, break_, exp);
1821 macro_expander_destroy (subme);
1825 macro_expander_destroy (subme);
1828 if (token->type != T_MACRO_ID)
1830 macro_tokens_add (exp, mt);
1834 if (ss_equals_case (token->string, ss_cstr ("!break")))
1837 printf ("!BREAK outside !DO\n");
1845 struct parse_macro_function_ctx ctx = {
1846 .input = &mts->mts[i],
1847 .n_input = mts->n - i,
1848 .nesting_countdown = nesting_countdown,
1854 struct string function_output = DS_EMPTY_INITIALIZER;
1855 size_t function_consumed;
1856 if (expand_macro_function (&ctx, &function_output, &function_consumed))
1858 i += function_consumed - 1;
1860 macro_tokens_from_string (exp, function_output.ss,
1861 SEG_MODE_INTERACTIVE /* XXX */);
1862 ds_destroy (&function_output);
1867 size_t n = macro_parse_let (&mts->mts[i], mts->n - i,
1868 nesting_countdown, macros, me, vars,
1876 n = macro_expand_do (&mts->mts[i], mts->n - i,
1877 nesting_countdown, macros, me, vars,
1885 if (ss_equals_case (token->string, ss_cstr ("!onexpand")))
1887 else if (ss_equals_case (token->string, ss_cstr ("!offexpand")))
1890 macro_tokens_add (exp, mt);
1892 if (vars == &own_vars)
1893 string_map_destroy (&own_vars);
1897 macro_expander_get_expansion (struct macro_expander *me, struct macro_tokens *exp)
1900 for (size_t i = 0; i < me->macro->n_params; i++)
1902 printf ("%s:\n", me->macro->params[i].name);
1903 macro_tokens_print (me->args[i], stdout);
1908 macro_expand (&me->macro->body, settings_get_mnest (),
1909 me->macros, me, NULL, &expand, NULL, exp);
1912 printf ("expansion:\n");
1913 macro_tokens_print (exp, stdout);