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));
426 struct macro_expansion_stack
428 const struct macro_expansion_stack *next;
438 /* Accumulating tokens in me->params toward the end of any type of
442 /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
445 /* Expecting a keyword for a keyword argument. */
448 /* Expecting an equal sign for a keyword argument. */
453 struct macro_expander
455 const struct macro_set *macros;
460 const struct macro *macro;
461 struct macro_tokens **args;
462 const struct macro_param *param;
466 me_finished (struct macro_expander *me)
468 for (size_t i = 0; i < me->macro->n_params; i++)
471 me->args[i] = xmalloc (sizeof *me->args[i]);
472 macro_tokens_copy (me->args[i], &me->macro->params[i].def);
478 me_next_arg (struct macro_expander *me)
482 assert (!me->macro->n_params);
483 return me_finished (me);
485 else if (me->param->positional)
488 if (me->param >= &me->macro->params[me->macro->n_params])
489 return me_finished (me);
492 me->state = (!me->param->positional ? ME_KEYWORD
493 : me->param->arg_type == ARG_ENCLOSE ? ME_ENCLOSE
500 for (size_t i = 0; i < me->macro->n_params; i++)
503 me->state = ME_KEYWORD;
506 return me_finished (me);
511 me_error (struct macro_expander *me)
513 me->state = ME_ERROR;
518 me_add_arg (struct macro_expander *me, const struct macro_token *mt)
520 const struct macro_param *p = me->param;
522 const struct token *token = &mt->token;
523 if ((token->type == T_ENDCMD || token->type == T_STOP)
524 && p->arg_type != ARG_CMDEND)
526 msg (SE, _("Unexpected end of command reading argument %s "
527 "to macro %s."), me->param->name, me->macro->name);
529 return me_error (me);
534 struct macro_tokens **argp = &me->args[p - me->macro->params];
536 *argp = xzalloc (sizeof **argp);
537 struct macro_tokens *arg = *argp;
538 if (p->arg_type == ARG_N_TOKENS)
540 macro_tokens_add (arg, mt);
541 if (arg->n >= p->n_tokens)
542 return me_next_arg (me);
545 else if (p->arg_type == ARG_CMDEND)
547 if (token->type == T_ENDCMD || token->type == T_STOP)
548 return me_next_arg (me);
549 macro_tokens_add (arg, mt);
554 const struct token *end
555 = p->arg_type == ARG_CHAREND ? &p->charend : &p->enclose[1];
556 if (token_equal (token, end))
557 return me_next_arg (me);
558 macro_tokens_add (arg, mt);
564 me_expected (struct macro_expander *me, const struct macro_token *actual,
565 const struct token *expected)
567 const struct substring actual_s
568 = (actual->representation.length ? actual->representation
569 : ss_cstr (_("<end of input>")));
570 char *expected_s = token_to_string (expected);
571 msg (SE, _("Found `%.*s' while expecting `%s' reading argument %s "
573 (int) actual_s.length, actual_s.string, expected_s,
574 me->param->name, me->macro->name);
577 return me_error (me);
581 me_enclose (struct macro_expander *me, const struct macro_token *mt)
583 const struct token *token = &mt->token;
586 if (token_equal (&me->param->enclose[0], token))
592 return me_expected (me, mt, &me->param->enclose[0]);
595 static const struct macro_param *
596 macro_find_parameter_by_name (const struct macro *m, struct substring name)
598 ss_ltrim (&name, ss_cstr ("!"));
600 for (size_t i = 0; i < m->n_params; i++)
602 const struct macro_param *p = &m->params[i];
603 struct substring p_name = ss_cstr (p->name + 1);
604 if (!utf8_strncasecmp (p_name.string, p_name.length,
605 name.string, name.length))
612 me_keyword (struct macro_expander *me, const struct macro_token *mt)
614 const struct token *token = &mt->token;
615 if (token->type != T_ID)
616 return me_finished (me);
618 const struct macro_param *p = macro_find_parameter_by_name (me->macro,
622 size_t arg_index = p - me->macro->params;
624 if (me->args[arg_index])
627 _("Argument %s multiply specified in call to macro %s."),
628 p->name, me->macro->name);
629 return me_error (me);
633 me->state = ME_EQUALS;
637 return me_finished (me);
641 me_equals (struct macro_expander *me, const struct macro_token *mt)
643 const struct token *token = &mt->token;
646 if (token->type == T_EQUALS)
652 return me_expected (me, mt, &(struct token) { .type = T_EQUALS });
656 macro_expander_create (const struct macro_set *macros,
657 const struct token *token,
658 struct macro_expander **mep)
661 if (macro_set_is_empty (macros))
663 if (token->type != T_ID && token->type != T_MACRO_ID)
666 const struct macro *macro = macro_set_find (macros, token->string.string);
670 struct macro_expander *me = xmalloc (sizeof *me);
671 *me = (struct macro_expander) {
678 if (!macro->n_params)
682 me->state = (!macro->params[0].positional ? ME_KEYWORD
683 : macro->params[0].arg_type == ARG_ENCLOSE ? ME_ENCLOSE
685 me->args = xcalloc (macro->n_params, sizeof *me->args);
686 me->param = macro->params;
692 macro_expander_destroy (struct macro_expander *me)
697 for (size_t i = 0; i < me->macro->n_params; i++)
700 macro_tokens_uninit (me->args[i]);
707 /* Adds TOKEN to the collection of tokens in ME that potentially need to be
710 Returns -1 if the tokens added do not actually invoke a macro. The caller
711 should consume the first token without expanding it.
713 Returns 0 if the macro expander needs more tokens, for macro arguments or to
714 decide whether this is actually a macro invocation. The caller should call
715 macro_expander_add() again with the next token.
717 Returns a positive number to indicate that the returned number of tokens
718 invoke a macro. The number returned might be less than the number of tokens
719 added because it can take a few tokens of lookahead to determine whether the
720 macro invocation is finished. The caller should call
721 macro_expander_get_expansion() to obtain the expansion. */
723 macro_expander_add (struct macro_expander *me, const struct macro_token *mt)
731 return me_add_arg (me, mt);
734 return me_enclose (me, mt);
737 return me_keyword (me, mt);
740 return me_equals (me, mt);
747 /* Each argument to a macro function is one of:
749 - A quoted string or other single literal token.
751 - An argument to the macro being expanded, e.g. !1 or a named argument.
755 - A function invocation.
757 Each function invocation yields a character sequence to be turned into a
758 sequence of tokens. The case where that character sequence is a single
759 quoted string is an important special case.
761 struct parse_macro_function_ctx
763 const struct macro_token *input;
765 int nesting_countdown;
766 const struct macro_set *macros;
767 const struct macro_expander *me;
768 const struct macro_expansion_stack *stack;
769 struct string_map *vars;
774 macro_expand (const struct macro_tokens *,
775 int nesting_countdown, const struct macro_set *,
776 const struct macro_expander *, struct string_map *vars,
777 const struct macro_expansion_stack *stack,
778 bool *expand, bool *break_,
779 struct macro_tokens *exp);
782 expand_macro_function (struct parse_macro_function_ctx *ctx,
783 struct string *output, size_t *input_consumed);
785 /* Returns true if the pair of tokens starting at offset OFS within MTS are !*,
788 is_bang_star (const struct macro_token *mts, size_t n, size_t ofs)
791 && mts[ofs].token.type == T_MACRO_ID
792 && ss_equals (mts[ofs].token.string, ss_cstr ("!"))
793 && mts[ofs + 1].token.type == T_ASTERISK);
797 parse_function_arg (struct parse_macro_function_ctx *ctx,
798 size_t i, struct string *farg)
800 const struct macro_token *tokens = ctx->input;
801 const struct token *token = &tokens[i].token;
802 if (token->type == T_MACRO_ID)
804 const struct macro_param *param = macro_find_parameter_by_name (
805 ctx->me->macro, token->string);
808 size_t param_idx = param - ctx->me->macro->params;
809 const struct macro_tokens *marg = ctx->me->args[param_idx];
810 for (size_t i = 0; i < marg->n; i++)
813 ds_put_byte (farg, ' ');
814 ds_put_substring (farg, marg->mts[i].representation);
819 if (is_bang_star (ctx->input, ctx->n_input, i))
821 for (size_t i = 0; i < ctx->me->macro->n_params; i++)
823 if (!ctx->me->macro->params[i].positional)
826 const struct macro_tokens *marg = ctx->me->args[i];
827 for (size_t j = 0; j < marg->n; j++)
830 ds_put_byte (farg, ' ');
831 ds_put_substring (farg, marg->mts[j].representation);
839 const char *value = string_map_find__ (ctx->vars,
840 token->string.string,
841 token->string.length);
844 ds_put_cstr (farg, value);
849 struct parse_macro_function_ctx subctx = {
850 .input = &ctx->input[i],
851 .n_input = ctx->n_input - i,
852 .nesting_countdown = ctx->nesting_countdown,
853 .macros = ctx->macros,
857 .expand = ctx->expand,
859 size_t subinput_consumed;
860 if (expand_macro_function (&subctx, farg, &subinput_consumed))
861 return subinput_consumed;
864 ds_put_substring (farg, tokens[i].representation);
869 parse_macro_function (struct parse_macro_function_ctx *ctx,
870 struct string_array *args,
871 struct substring function,
872 int min_args, int max_args,
873 size_t *input_consumed)
875 const struct macro_token *tokens = ctx->input;
876 size_t n_tokens = ctx->n_input;
879 || tokens[0].token.type != T_MACRO_ID
880 || !ss_equals_case (tokens[0].token.string, function)) /* XXX abbrevs allowed */
883 if (n_tokens < 2 || tokens[1].token.type != T_LPAREN)
885 printf ("`(' expected following %s'\n", function.string);
889 string_array_init (args);
891 for (size_t i = 2;; )
895 if (tokens[i].token.type == T_RPAREN)
897 *input_consumed = i + 1;
898 if (args->n < min_args || args->n > max_args)
900 printf ("Wrong number of arguments to %s.\n", function.string);
906 struct string s = DS_EMPTY_INITIALIZER;
907 i += parse_function_arg (ctx, i, &s);
913 string_array_append_nocopy (args, ds_steal_cstr (&s));
915 if (tokens[i].token.type == T_COMMA)
917 else if (tokens[i].token.type != T_RPAREN)
919 printf ("Expecting `,' or `)' in %s invocation.", function.string);
925 printf ("Missing closing parenthesis in arguments to %s.\n",
929 string_array_destroy (args);
934 unquote_string (const char *s, struct string *content)
936 struct string_lexer slex;
937 string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE /* XXX */,
941 if (!string_lexer_next (&slex, &token1))
944 if (token1.type != T_STRING)
946 token_uninit (&token1);
951 if (string_lexer_next (&slex, &token2))
953 token_uninit (&token1);
954 token_uninit (&token2);
958 ds_put_substring (content, token1.string);
959 token_uninit (&token1);
964 unquote_string_in_place (const char *s, struct string *tmp)
967 return unquote_string (s, tmp) ? ds_cstr (tmp) : s;
971 parse_integer (const char *s, int *np)
976 long int n = strtol (s, &tail, 10);
977 *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
978 tail += strspn (tail, CC_SPACES);
979 return *tail == '\0' && errno != ERANGE && n == *np;
983 expand_macro_function (struct parse_macro_function_ctx *ctx,
984 struct string *output,
985 size_t *input_consumed)
987 struct string_array args;
989 if (parse_macro_function (ctx, &args, ss_cstr ("!length"), 1, 1,
991 ds_put_format (output, "%zu", strlen (args.strings[0]));
992 else if (parse_macro_function (ctx, &args, ss_cstr ("!blanks"), 1, 1,
996 if (!parse_integer (args.strings[0], &n))
998 printf ("argument to !BLANKS must be non-negative integer (not \"%s\")\n", args.strings[0]);
999 string_array_destroy (&args);
1003 ds_put_byte_multiple (output, ' ', n);
1005 else if (parse_macro_function (ctx, &args, ss_cstr ("!concat"), 1, INT_MAX,
1008 for (size_t i = 0; i < args.n; i++)
1009 if (!unquote_string (args.strings[i], output))
1010 ds_put_cstr (output, args.strings[i]);
1012 else if (parse_macro_function (ctx, &args, ss_cstr ("!head"), 1, 1,
1016 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1018 struct macro_tokens mts = { .n = 0 };
1019 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1021 ds_put_substring (output, mts.mts[0].representation);
1022 macro_tokens_uninit (&mts);
1025 else if (parse_macro_function (ctx, &args, ss_cstr ("!index"), 2, 2,
1028 const char *haystack = args.strings[0];
1029 const char *needle = strstr (haystack, args.strings[1]);
1030 ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1032 else if (parse_macro_function (ctx, &args, ss_cstr ("!quote"), 1, 1,
1035 if (unquote_string (args.strings[0], NULL))
1036 ds_put_cstr (output, args.strings[0]);
1039 ds_extend (output, strlen (args.strings[0]) + 2);
1040 ds_put_byte (output, '\'');
1041 for (const char *p = args.strings[0]; *p; p++)
1044 ds_put_byte (output, '\'');
1045 ds_put_byte (output, *p);
1047 ds_put_byte (output, '\'');
1050 else if (parse_macro_function (ctx, &args, ss_cstr ("!substr"), 2, 3,
1054 if (!parse_integer (args.strings[1], &start) || start < 1)
1056 printf ("second argument to !SUBSTR must be positive integer (not \"%s\")\n", args.strings[1]);
1057 string_array_destroy (&args);
1061 int count = INT_MAX;
1062 if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1064 printf ("third argument to !SUBSTR must be non-negative integer (not \"%s\")\n", args.strings[1]);
1065 string_array_destroy (&args);
1069 struct substring s = ss_cstr (args.strings[0]);
1070 ds_put_substring (output, ss_substr (s, start - 1, count));
1072 else if (parse_macro_function (ctx, &args, ss_cstr ("!tail"), 1, 1,
1076 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1078 struct macro_tokens mts = { .n = 0 };
1079 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1082 struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1083 macro_tokens_to_representation (&tail, output, NULL, NULL);
1085 macro_tokens_uninit (&mts);
1088 else if (parse_macro_function (ctx, &args, ss_cstr ("!unquote"), 1, 1,
1091 if (!unquote_string (args.strings[0], output))
1092 ds_put_cstr (output, args.strings[0]);
1094 else if (parse_macro_function (ctx, &args, ss_cstr ("!upcase"), 1, 1,
1098 const char *s = unquote_string_in_place (args.strings[0], &tmp);
1099 char *upper = utf8_to_upper (s);
1100 ds_put_cstr (output, upper);
1104 else if (parse_macro_function (ctx, &args, ss_cstr ("!eval"), 1, 1,
1107 struct macro_tokens mts = { .n = 0 };
1108 macro_tokens_from_string (&mts, ss_cstr (args.strings[0]),
1109 SEG_MODE_INTERACTIVE /* XXX */);
1110 struct macro_tokens exp = { .n = 0 };
1111 macro_expand (&mts, ctx->nesting_countdown - 1, ctx->macros, ctx->me,
1113 &(struct macro_expansion_stack) {
1116 }, ctx->expand, NULL, &exp);
1117 macro_tokens_to_representation (&exp, output, NULL, NULL);
1118 macro_tokens_uninit (&exp);
1119 macro_tokens_uninit (&mts);
1121 else if (ctx->n_input > 0
1122 && ctx->input[0].token.type == T_MACRO_ID
1123 && ss_equals_case (ctx->input[0].token.string, ss_cstr ("!null")))
1125 *input_consumed = 1;
1131 string_array_destroy (&args);
1137 int nesting_countdown;
1138 const struct macro_set *macros;
1139 const struct macro_expander *me;
1140 const struct macro_expansion_stack *stack;
1141 struct string_map *vars;
1145 static char *macro_evaluate_or (const struct expr_context *ctx,
1146 const struct macro_token **tokens,
1147 const struct macro_token *end);
1150 macro_evaluate_literal (const struct expr_context *ctx,
1151 const struct macro_token **tokens,
1152 const struct macro_token *end)
1154 const struct macro_token *p = *tokens;
1157 if (p->token.type == T_LPAREN)
1160 char *value = macro_evaluate_or (ctx, &p, end);
1163 if (p >= end || p->token.type != T_RPAREN)
1166 printf ("expecting ')' in macro expression\n");
1174 struct parse_macro_function_ctx fctx = {
1177 .nesting_countdown = ctx->nesting_countdown,
1178 .macros = ctx->macros,
1180 .stack = ctx->stack,
1182 .expand = ctx->expand,
1184 struct string function_output = DS_EMPTY_INITIALIZER;
1185 size_t function_consumed = parse_function_arg (&fctx, 0, &function_output);
1186 struct string unquoted = DS_EMPTY_INITIALIZER;
1187 if (unquote_string (ds_cstr (&function_output), &unquoted))
1189 ds_swap (&function_output, &unquoted);
1190 ds_destroy (&unquoted);
1192 *tokens = p + function_consumed;
1193 return ds_steal_cstr (&function_output);
1196 /* Returns true if MT is valid as a macro operator. Only operators written as
1197 symbols (e.g. <>) are usable in macro expressions, not operator written as
1198 letters (e.g. EQ). */
1200 is_macro_operator (const struct macro_token *mt)
1202 return (mt->representation.length > 0
1203 && !c_isalpha (mt->representation.string[0]));
1206 static enum token_type
1207 parse_relational_op (const struct macro_token *mt)
1209 switch (mt->token.type)
1219 return is_macro_operator (mt) ? mt->token.type : T_STOP;
1222 return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1223 : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1224 : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1225 : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1226 : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1227 : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1236 macro_evaluate_relational (const struct expr_context *ctx,
1237 const struct macro_token **tokens,
1238 const struct macro_token *end)
1240 const struct macro_token *p = *tokens;
1241 char *lhs = macro_evaluate_literal (ctx, &p, end);
1245 enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1253 char *rhs = macro_evaluate_literal (ctx, &p, end);
1260 struct string lhs_tmp, rhs_tmp;
1261 int cmp = strcmp/*XXX*/ (unquote_string_in_place (lhs, &lhs_tmp),
1262 unquote_string_in_place (rhs, &rhs_tmp));
1263 ds_destroy (&lhs_tmp);
1264 ds_destroy (&rhs_tmp);
1269 bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1271 : op == T_LT ? cmp < 0
1272 : op == T_GT ? cmp > 0
1273 : op == T_LE ? cmp <= 0
1274 :/*op == T_GE*/cmp >= 0);
1277 return xstrdup (b ? "1" : "0");
1281 macro_evaluate_not (const struct expr_context *ctx,
1282 const struct macro_token **tokens,
1283 const struct macro_token *end)
1285 const struct macro_token *p = *tokens;
1287 unsigned int negations = 0;
1289 && (ss_equals_case (p->representation, ss_cstr ("!NOT"))
1290 || ss_equals (p->representation, ss_cstr ("~"))))
1296 char *operand = macro_evaluate_relational (ctx, &p, end);
1297 if (!operand || !negations)
1303 bool b = strcmp (operand, "0") ^ (negations & 1);
1306 return xstrdup (b ? "1" : "0");
1310 macro_evaluate_and (const struct expr_context *ctx,
1311 const struct macro_token **tokens,
1312 const struct macro_token *end)
1314 const struct macro_token *p = *tokens;
1315 char *lhs = macro_evaluate_not (ctx, &p, end);
1320 && (ss_equals_case (p->representation, ss_cstr ("!AND"))
1321 || ss_equals (p->representation, ss_cstr ("&"))))
1324 char *rhs = macro_evaluate_not (ctx, &p, end);
1331 bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1334 lhs = xstrdup (b ? "1" : "0");
1341 macro_evaluate_or (const struct expr_context *ctx,
1342 const struct macro_token **tokens,
1343 const struct macro_token *end)
1345 const struct macro_token *p = *tokens;
1346 char *lhs = macro_evaluate_and (ctx, &p, end);
1351 && (ss_equals_case (p->representation, ss_cstr ("!OR"))
1352 || ss_equals (p->representation, ss_cstr ("|"))))
1355 char *rhs = macro_evaluate_and (ctx, &p, end);
1362 bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1365 lhs = xstrdup (b ? "1" : "0");
1372 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1373 int nesting_countdown, const struct macro_set *macros,
1374 const struct macro_expander *me,
1375 const struct macro_expansion_stack *stack,
1376 struct string_map *vars, bool *expand)
1378 const struct expr_context ctx = {
1379 .nesting_countdown = nesting_countdown,
1386 return macro_evaluate_or (&ctx, tokens, *tokens + n_tokens);
1390 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1391 int nesting_countdown, const struct macro_set *macros,
1392 const struct macro_expander *me,
1393 const struct macro_expansion_stack *stack,
1394 struct string_map *vars,
1395 bool *expand, double *number)
1397 char *s = macro_evaluate_expression (tokens, n_tokens, nesting_countdown,
1398 macros, me, stack, vars, expand);
1402 struct macro_tokens mts = { .n = 0 };
1403 macro_tokens_from_string (&mts, ss_cstr (s), SEG_MODE_INTERACTIVE /* XXX */);
1404 if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1406 macro_tokens_print (&mts, stdout);
1407 printf ("expression must evaluate to a number (not %s)\n", s);
1409 macro_tokens_uninit (&mts);
1413 *number = token_number (&mts.mts[0].token);
1415 macro_tokens_uninit (&mts);
1419 static const struct macro_token *
1420 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1423 for (; p < end; p++)
1425 if (p->token.type != T_MACRO_ID)
1428 if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1430 else if (ss_equals_case (p->token.string, ss_cstr ("!IFEND")))
1436 else if (ss_equals_case (p->token.string, ss_cstr ("!ELSE")) && !nesting)
1443 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1444 int nesting_countdown, const struct macro_set *macros,
1445 const struct macro_expander *me,
1446 const struct macro_expansion_stack *stack,
1447 struct string_map *vars,
1448 bool *expand, bool *break_, struct macro_tokens *exp)
1450 const struct macro_token *p = tokens;
1451 const struct macro_token *end = tokens + n_tokens;
1453 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1457 char *result = macro_evaluate_expression (&p, end - p,
1458 nesting_countdown, macros, me,
1459 stack, vars, expand);
1462 bool b = strcmp (result, "0");
1466 || p->token.type != T_MACRO_ID
1467 || !ss_equals_case (p->token.string, ss_cstr ("!THEN")))
1469 printf ("!THEN expected\n");
1473 const struct macro_token *start_then = p + 1;
1474 const struct macro_token *end_then = find_ifend_clause (start_then, end);
1477 printf ("!ELSE or !IFEND expected\n");
1481 const struct macro_token *start_else, *end_if;
1482 if (ss_equals_case (end_then->token.string, ss_cstr ("!ELSE")))
1484 start_else = end_then + 1;
1485 end_if = find_ifend_clause (start_else, end);
1487 || !ss_equals_case (end_if->token.string, ss_cstr ("!IFEND")))
1489 printf ("!IFEND expected\n");
1499 const struct macro_token *start;
1504 n = end_then - start_then;
1506 else if (start_else)
1509 n = end_if - start_else;
1519 struct macro_tokens mts = {
1520 .mts = CONST_CAST (struct macro_token *, start),
1523 macro_expand (&mts, nesting_countdown, macros, me, vars,
1524 &(struct macro_expansion_stack) {
1528 expand, break_, exp);
1530 return (end_if + 1) - tokens;
1533 static void PRINTF_FORMAT (2, 3)
1534 macro_error (const struct macro_expansion_stack *stack,
1535 const char *format, ...)
1538 va_start (args, format);
1539 char *s = xvasprintf (format, args);
1542 /* foo.sps:12: While expanding macro 'innermost',
1543 foo.sps:23: inside expansion of 'next_inner',
1544 foo.sps:34: inside expansion of 'next_inner2',
1545 foo.sps:45: inside expansion of 'outermost':
1547 struct string header = DS_EMPTY_INITIALIZER;
1548 ds_put_format (&header, "While expanding \"%s\"", stack->name);
1549 while ((stack = stack->next) != NULL)
1550 ds_put_format (&header, ", inside expansion of \"%s\"", stack->name);
1552 msg (SE, "%s: %s", ds_cstr (&header), s);
1554 ds_destroy (&header);
1559 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1560 int nesting_countdown, const struct macro_set *macros,
1561 const struct macro_expander *me,
1562 const struct macro_expansion_stack *stack,
1563 struct string_map *vars, bool *expand)
1565 const struct macro_token *p = tokens;
1566 const struct macro_token *end = tokens + n_tokens;
1568 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1572 if (p >= end || p->token.type != T_MACRO_ID)
1574 macro_error (stack, "expected macro variable name following !LET");
1577 const struct substring var_name = p->token.string;
1578 if (is_macro_keyword (var_name)
1579 || macro_find_parameter_by_name (me->macro, var_name))
1581 printf ("cannot use argument name or macro keyword %.*s as !LET variable\n", (int) var_name.length, var_name.string);
1586 if (p >= end || p->token.type != T_EQUALS)
1588 printf ("expected = following !LET\n");
1593 char *value = macro_evaluate_expression (&p, end - p,
1594 nesting_countdown, macros, me, stack,
1599 string_map_replace_nocopy (vars, ss_xstrdup (var_name), value);
1603 static const struct macro_token *
1604 find_doend (const struct macro_token *p, const struct macro_token *end)
1607 for (; p < end; p++)
1609 if (p->token.type != T_MACRO_ID)
1612 if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1614 else if (ss_equals_case (p->token.string, ss_cstr ("!DOEND")))
1621 printf ("missing !DOEND\n");
1626 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1627 int nesting_countdown, const struct macro_set *macros,
1628 const struct macro_expander *me,
1629 const struct macro_expansion_stack *stack,
1630 struct string_map *vars,
1631 bool *expand, struct macro_tokens *exp)
1633 const struct macro_token *p = tokens;
1634 const struct macro_token *end = tokens + n_tokens;
1636 if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1640 if (p >= end || p->token.type != T_MACRO_ID)
1642 printf ("expected macro variable name following !DO\n");
1645 const struct substring var_name = p->token.string;
1646 if (is_macro_keyword (var_name)
1647 || macro_find_parameter_by_name (me->macro, var_name))
1649 printf ("cannot use argument name or macro keyword %.*s as !DO variable\n", (int) var_name.length, var_name.string);
1654 struct macro_expansion_stack next_stack = {
1655 .name = "!DO", .next = stack,
1657 int miterate = settings_get_miterate ();
1658 if (p < end && p->token.type == T_MACRO_ID
1659 && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1662 char *list = macro_evaluate_expression (&p, end - p,
1663 nesting_countdown, macros, me,
1664 &next_stack, vars, expand);
1668 struct macro_tokens items = { .n = 0 };
1669 macro_tokens_from_string (&items, ss_cstr (list),
1670 SEG_MODE_INTERACTIVE /* XXX */);
1673 const struct macro_token *do_end = find_doend (p, end);
1676 macro_tokens_uninit (&items);
1680 const struct macro_tokens inner = {
1681 .mts = CONST_CAST (struct macro_token *, p),
1684 for (size_t i = 0; i < items.n; i++)
1688 printf ("exceeded maximum number of iterations %d\n", miterate);
1691 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1692 ss_xstrdup (items.mts[i].representation));
1694 bool break_ = false;
1695 macro_expand (&inner, nesting_countdown, macros,
1696 me, vars, &next_stack, expand, &break_, exp);
1700 return do_end - tokens + 1;
1702 else if (p < end && p->token.type == T_EQUALS)
1706 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1707 &next_stack, vars, expand, &first))
1710 if (p >= end || p->token.type != T_MACRO_ID
1711 || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1713 printf ("expecting !TO\n");
1719 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1720 &next_stack, vars, expand, &last))
1724 if (p < end && p->token.type == T_MACRO_ID
1725 && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1728 if (!macro_evaluate_number (&p, end - p, nesting_countdown, macros, me,
1729 &next_stack, vars, expand, &by))
1734 printf ("!BY value cannot be zero\n");
1739 const struct macro_token *do_end = find_doend (p, end);
1742 const struct macro_tokens inner = {
1743 .mts = CONST_CAST (struct macro_token *, p),
1747 if ((by > 0 && first <= last) || (by < 0 && first >= last))
1750 for (double index = first;
1751 by > 0 ? (index <= last) : (index >= last);
1756 printf ("exceeded maximum number of iterations %d\n",
1761 char index_s[DBL_BUFSIZE_BOUND];
1762 c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1763 string_map_replace_nocopy (vars, ss_xstrdup (var_name),
1766 bool break_ = false;
1767 macro_expand (&inner, nesting_countdown, macros,
1768 me, vars, &next_stack, expand, &break_, exp);
1774 return do_end - tokens + 1;
1778 printf ("expecting = or !IN in !DO loop\n");
1784 macro_expand (const struct macro_tokens *mts,
1785 int nesting_countdown, const struct macro_set *macros,
1786 const struct macro_expander *me, struct string_map *vars,
1787 const struct macro_expansion_stack *stack,
1788 bool *expand, bool *break_, struct macro_tokens *exp)
1790 if (nesting_countdown <= 0)
1792 printf ("maximum nesting level exceeded\n");
1793 for (size_t i = 0; i < mts->n; i++)
1794 macro_tokens_add (exp, &mts->mts[i]);
1798 struct string_map own_vars = STRING_MAP_INITIALIZER (own_vars);
1802 for (size_t i = 0; i < mts->n && (!break_ || !*break_); i++)
1804 const struct macro_token *mt = &mts->mts[i];
1805 const struct token *token = &mt->token;
1806 if (token->type == T_MACRO_ID && me)
1808 const struct macro_param *param = macro_find_parameter_by_name (
1809 me->macro, token->string);
1812 const struct macro_tokens *arg = me->args[param - me->macro->params];
1813 //macro_tokens_print (arg, stdout);
1814 if (*expand && param->expand_arg)
1815 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1816 &(struct macro_expansion_stack) {
1817 .name = param->name,
1819 }, expand, break_, exp);
1821 for (size_t i = 0; i < arg->n; i++)
1822 macro_tokens_add (exp, &arg->mts[i]);
1826 if (is_bang_star (mts->mts, mts->n, i))
1828 for (size_t j = 0; j < me->macro->n_params; j++)
1830 const struct macro_param *param = &me->macro->params[j];
1831 if (!param->positional)
1834 const struct macro_tokens *arg = me->args[j];
1835 if (*expand && param->expand_arg)
1836 macro_expand (arg, nesting_countdown, macros, NULL, NULL,
1837 &(struct macro_expansion_stack) {
1840 }, expand, break_, exp);
1842 for (size_t k = 0; k < arg->n; k++)
1843 macro_tokens_add (exp, &arg->mts[k]);
1849 size_t n = macro_expand_if (&mts->mts[i], mts->n - i,
1850 nesting_countdown, macros, me, stack,
1851 vars, expand, break_, exp);
1859 if (token->type == T_MACRO_ID && vars)
1861 const char *value = string_map_find__ (vars, token->string.string,
1862 token->string.length);
1865 macro_tokens_from_string (exp, ss_cstr (value),
1866 SEG_MODE_INTERACTIVE /* XXX */);
1873 struct macro_expander *subme;
1874 int retval = macro_expander_create (macros, token, &subme);
1875 for (size_t j = 1; !retval; j++)
1877 const struct macro_token endcmd = { .token = { .type = T_ENDCMD } };
1878 retval = macro_expander_add (
1879 subme, i + j < mts->n ? &mts->mts[i + j] : &endcmd);
1884 macro_expand (&subme->macro->body, nesting_countdown - 1, macros,
1886 &(struct macro_expansion_stack) {
1887 .name = subme->macro->name,
1889 }, expand, break_, exp);
1890 macro_expander_destroy (subme);
1894 macro_expander_destroy (subme);
1897 if (token->type != T_MACRO_ID)
1899 macro_tokens_add (exp, mt);
1903 if (ss_equals_case (token->string, ss_cstr ("!break")))
1906 printf ("!BREAK outside !DO\n");
1914 struct parse_macro_function_ctx ctx = {
1915 .input = &mts->mts[i],
1916 .n_input = mts->n - i,
1917 .nesting_countdown = nesting_countdown,
1924 struct string function_output = DS_EMPTY_INITIALIZER;
1925 size_t function_consumed;
1926 if (expand_macro_function (&ctx, &function_output, &function_consumed))
1928 i += function_consumed - 1;
1930 macro_tokens_from_string (exp, function_output.ss,
1931 SEG_MODE_INTERACTIVE /* XXX */);
1932 ds_destroy (&function_output);
1937 size_t n = macro_parse_let (&mts->mts[i], mts->n - i,
1938 nesting_countdown, macros, me, stack,
1946 n = macro_expand_do (&mts->mts[i], mts->n - i,
1947 nesting_countdown, macros, me, stack, vars,
1955 if (ss_equals_case (token->string, ss_cstr ("!onexpand")))
1957 else if (ss_equals_case (token->string, ss_cstr ("!offexpand")))
1960 macro_tokens_add (exp, mt);
1962 if (vars == &own_vars)
1963 string_map_destroy (&own_vars);
1967 macro_expander_get_expansion (struct macro_expander *me, struct macro_tokens *exp)
1970 struct macro_expansion_stack stack = { .name = me->macro->name };
1971 macro_expand (&me->macro->body, settings_get_mnest (),
1972 me->macros, me, NULL, &stack, &expand, NULL, exp);