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"
24 #include "data/settings.h"
25 #include "language/lexer/segment.h"
26 #include "language/lexer/scan.h"
27 #include "libpspp/assertion.h"
28 #include "libpspp/i18n.h"
29 #include "libpspp/message.h"
30 #include "libpspp/str.h"
33 #define _(msgid) gettext (msgid)
36 macro_token_copy (struct macro_token *dst, const struct macro_token *src)
38 token_copy (&dst->token, &src->token);
39 ss_alloc_substring (&dst->representation, src->representation);
43 macro_token_uninit (struct macro_token *mt)
45 token_uninit (&mt->token);
46 ss_dealloc (&mt->representation);
50 macro_tokens_copy (struct macro_tokens *dst, const struct macro_tokens *src)
52 *dst = (struct macro_tokens) {
53 .mts = xmalloc (src->n * sizeof *dst->mts),
57 for (size_t i = 0; i < src->n; i++)
58 macro_token_copy (&dst->mts[i], &src->mts[i]);
62 macro_tokens_uninit (struct macro_tokens *mts)
64 for (size_t i = 0; i < mts->n; i++)
65 macro_token_uninit (&mts->mts[i]);
70 macro_tokens_add_uninit (struct macro_tokens *mts)
72 if (mts->n >= mts->allocated)
73 mts->mts = x2nrealloc (mts->mts, &mts->allocated, sizeof *mts->mts);
74 return &mts->mts[mts->n++];
78 macro_tokens_add (struct macro_tokens *mts, const struct macro_token *mt)
80 macro_token_copy (macro_tokens_add_uninit (mts), mt);
84 macro_tokens_from_string (struct macro_tokens *mts, const struct substring src,
85 enum segmenter_mode mode)
89 struct segmenter segmenter;
90 struct substring body;
93 struct state state = {
94 .segmenter = SEGMENTER_INIT (mode),
97 struct state saved = state;
99 while (state.body.length > 0)
101 struct macro_token mt = {
102 .token = { .type = T_STOP },
103 .representation = { .string = state.body.string },
105 struct token *token = &mt.token;
107 struct scanner scanner;
108 scanner_init (&scanner, token);
112 enum segment_type type;
113 int seg_len = segmenter_push (&state.segmenter, state.body.string,
114 state.body.length, true, &type);
115 assert (seg_len >= 0);
117 struct substring segment = ss_head (state.body, seg_len);
118 ss_advance (&state.body, seg_len);
120 enum scan_result result = scanner_push (&scanner, type, segment, token);
121 if (result == SCAN_SAVE)
123 else if (result == SCAN_BACK)
128 else if (result == SCAN_DONE)
132 /* We have a token in 'token'. */
133 if (is_scan_type (token->type))
135 if (token->type != SCAN_SKIP)
137 /* XXX report error */
142 mt.representation.length = state.body.string - mt.representation.string;
143 macro_tokens_add (mts, &mt);
145 token_uninit (token);
150 macro_tokens_print (const struct macro_tokens *mts, FILE *stream)
152 for (size_t i = 0; i < mts->n; i++)
153 token_print (&mts->mts[i].token, stream);
157 macro_destroy (struct macro *m)
163 for (size_t i = 0; i < m->n_params; i++)
165 struct macro_param *p = &m->params[i];
168 macro_tokens_uninit (&p->def);
176 token_uninit (&p->charend);
180 token_uninit (&p->enclose[0]);
181 token_uninit (&p->enclose[1]);
189 macro_tokens_uninit (&m->body);
194 macro_set_create (void)
196 struct macro_set *set = xmalloc (sizeof *set);
197 *set = (struct macro_set) {
198 .macros = HMAP_INITIALIZER (set->macros),
204 macro_set_destroy (struct macro_set *set)
209 struct macro *macro, *next;
210 HMAP_FOR_EACH_SAFE (macro, next, struct macro, hmap_node, &set->macros)
212 hmap_delete (&set->macros, ¯o->hmap_node);
213 macro_destroy (macro);
215 hmap_destroy (&set->macros);
220 hash_macro_name (const char *name)
222 return utf8_hash_case_string (name, 0);
225 static struct macro *
226 macro_set_find__ (struct macro_set *set, const char *name)
229 HMAP_FOR_EACH_WITH_HASH (macro, struct macro, hmap_node,
230 hash_macro_name (name), &set->macros)
231 if (!utf8_strcasecmp (macro->name, name))
238 macro_set_find (const struct macro_set *set, const char *name)
240 return macro_set_find__ (CONST_CAST (struct macro_set *, set), name);
243 /* Adds M to SET. M replaces any existing macro with the same name. Takes
246 macro_set_add (struct macro_set *set, struct macro *m)
248 struct macro *victim = macro_set_find__ (set, m->name);
251 hmap_delete (&set->macros, &victim->hmap_node);
252 macro_destroy (victim);
255 hmap_insert (&set->macros, &m->hmap_node, hash_macro_name (m->name));
263 /* Accumulating tokens in me->params toward the end of any type of
267 /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
270 /* Expecting a keyword for a keyword argument. */
273 /* Expecting an equal sign for a keyword argument. */
278 struct macro_expander
280 const struct macro_set *macros;
285 const struct macro *macro;
286 struct macro_tokens **args;
287 const struct macro_param *param;
291 me_finished (struct macro_expander *me)
293 for (size_t i = 0; i < me->macro->n_params; i++)
296 me->args[i] = xmalloc (sizeof *me->args[i]);
297 macro_tokens_copy (me->args[i], &me->macro->params[i].def);
303 me_next_arg (struct macro_expander *me)
307 assert (!me->macro->n_params);
308 return me_finished (me);
310 else if (me->param->positional)
313 if (me->param >= &me->macro->params[me->macro->n_params])
314 return me_finished (me);
317 me->state = me->param->positional ? ME_ARG : ME_KEYWORD;
323 for (size_t i = 0; i < me->macro->n_params; i++)
326 me->state = ME_KEYWORD;
329 return me_finished (me);
334 me_error (struct macro_expander *me)
336 me->state = ME_ERROR;
341 me_add_arg (struct macro_expander *me, const struct macro_token *mt)
343 const struct token *token = &mt->token;
344 if (token->type == T_STOP)
346 msg (SE, _("Unexpected end of file reading argument %s "
347 "to macro %s."), me->param->name, me->macro->name);
349 return me_error (me);
354 const struct macro_param *p = me->param;
355 struct macro_tokens **argp = &me->args[p - me->macro->params];
357 *argp = xzalloc (sizeof **argp);
358 struct macro_tokens *arg = *argp;
359 if (p->arg_type == ARG_N_TOKENS)
361 macro_tokens_add (arg, mt);
362 if (arg->n >= p->n_tokens)
363 return me_next_arg (me);
366 else if (p->arg_type == ARG_CMDEND)
368 if (token->type == T_ENDCMD || token->type == T_STOP)
369 return me_next_arg (me);
370 macro_tokens_add (arg, mt);
375 const struct token *end
376 = p->arg_type == ARG_CMDEND ? &p->charend : &p->enclose[1];
377 if (token_equal (token, end))
378 return me_next_arg (me);
379 macro_tokens_add (arg, mt);
385 me_expected (struct macro_expander *me, const struct macro_token *actual,
386 const struct token *expected)
388 const struct substring actual_s
389 = (actual->representation.length ? actual->representation
390 : ss_cstr (_("<end of input>")));
391 char *expected_s = token_to_string (expected);
392 msg (SE, _("Found `%.*s' while expecting `%s' reading argument %s "
394 (int) actual_s.length, actual_s.string, expected_s,
395 me->param->name, me->macro->name);
398 return me_error (me);
402 me_enclose (struct macro_expander *me, const struct macro_token *mt)
404 const struct token *token = &mt->token;
407 if (token_equal (&me->param->enclose[0], token))
413 return me_expected (me, mt, &me->param->enclose[0]);
416 static const struct macro_param *
417 macro_find_parameter_by_name (const struct macro *m, struct substring name)
419 for (size_t i = 0; i < m->n_params; i++)
421 const struct macro_param *p = &m->params[i];
422 struct substring p_name = ss_cstr (p->name);
423 if (!utf8_strncasecmp (p_name.string, p_name.length,
424 name.string, name.length))
431 me_keyword (struct macro_expander *me, const struct macro_token *mt)
433 const struct token *token = &mt->token;
434 if (token->type != T_ID)
435 return me_finished (me);
437 const struct macro_param *p = macro_find_parameter_by_name (me->macro,
441 size_t arg_index = p - me->macro->params;
443 if (me->args[arg_index])
446 _("Argument %s multiply specified in call to macro %s."),
447 p->name, me->macro->name);
448 return me_error (me);
452 me->state = ME_EQUALS;
456 return me_finished (me);
460 me_equals (struct macro_expander *me, const struct macro_token *mt)
462 const struct token *token = &mt->token;
465 if (token->type == T_EQUALS)
471 return me_expected (me, mt, &(struct token) { .type = T_EQUALS });
475 macro_expander_create (const struct macro_set *macros,
476 const struct token *token,
477 struct macro_expander **mep)
480 if (macro_set_is_empty (macros))
482 if (token->type != T_ID && token->type != T_MACRO_ID)
485 const struct macro *macro = macro_set_find (macros, token->string.string);
489 struct macro_expander *me = xmalloc (sizeof *me);
490 *me = (struct macro_expander) {
497 if (!macro->n_params)
501 me->state = macro->params[0].positional ? ME_ARG : ME_KEYWORD;
502 me->args = xcalloc (macro->n_params, sizeof *me->args);
503 me->param = macro->params;
509 macro_expander_destroy (struct macro_expander *me)
514 for (size_t i = 0; i < me->macro->n_params; i++)
517 macro_tokens_uninit (me->args[i]);
524 /* Adds TOKEN to the collection of tokens in ME that potentially need to be
527 Returns -1 if the tokens added do not actually invoke a macro. The caller
528 should consume the first token without expanding it.
530 Returns 0 if the macro expander needs more tokens, for macro arguments or to
531 decide whether this is actually a macro invocation. The caller should call
532 macro_expander_add() again with the next token.
534 Returns a positive number to indicate that the returned number of tokens
535 invoke a macro. The number returned might be less than the number of tokens
536 added because it can take a few tokens of lookahead to determine whether the
537 macro invocation is finished. The caller should call
538 macro_expander_get_expansion() to obtain the expansion. */
540 macro_expander_add (struct macro_expander *me, const struct macro_token *mt)
548 return me_add_arg (me, mt);
551 return me_enclose (me, mt);
554 return me_keyword (me, mt);
557 return me_equals (me, mt);
564 /* Each argument to a macro function is one of:
566 - A quoted string or other single literal token.
568 - An argument to the macro being expanded, e.g. !1 or a named argument.
572 - A function invocation.
574 Each function invocation yields a character sequence to be turned into a
575 sequence of tokens. The case where that character sequence is a single
576 quoted string is an important special case.
578 struct parse_macro_function_ctx
580 struct macro_token *input;
582 int nesting_countdown;
583 const struct macro_set *macros;
584 const struct macro_expander *me;
589 macro_expand (const struct macro_tokens *,
590 int nesting_countdown, const struct macro_set *,
591 const struct macro_expander *, bool *expand, struct macro_tokens *exp);
594 expand_macro_function (struct parse_macro_function_ctx *ctx,
595 struct macro_token *output,
596 size_t *input_consumed);
599 parse_function_arg (struct parse_macro_function_ctx *ctx,
600 size_t i, struct macro_token *farg)
602 struct macro_token *tokens = ctx->input;
603 const struct token *token = &tokens[i].token;
604 if (token->type == T_MACRO_ID)
606 const struct macro_param *param = macro_find_parameter_by_name (
607 ctx->me->macro, token->string);
610 size_t param_idx = param - ctx->me->macro->params;
611 const struct macro_tokens *marg = ctx->me->args[param_idx];
613 macro_token_copy (farg, &marg->mts[0]);
616 struct string s = DS_EMPTY_INITIALIZER;
617 for (size_t i = 0; i < marg->n; i++)
620 ds_put_byte (&s, ' ');
621 ds_put_substring (&s, marg->mts[i].representation);
624 struct substring s_copy;
625 ss_alloc_substring (&s_copy, s.ss);
627 *farg = (struct macro_token) {
628 .token = { .type = T_MACRO_ID, .string = s.ss },
629 .representation = s_copy,
635 struct parse_macro_function_ctx subctx = {
636 .input = &ctx->input[i],
637 .n_input = ctx->n_input - i,
638 .nesting_countdown = ctx->nesting_countdown,
639 .macros = ctx->macros,
641 .expand = ctx->expand,
643 size_t subinput_consumed;
644 if (expand_macro_function (&subctx, farg, &subinput_consumed))
645 return subinput_consumed;
648 macro_token_copy (farg, &tokens[i]);
653 parse_macro_function (struct parse_macro_function_ctx *ctx,
654 struct macro_tokens *args,
655 struct substring function,
656 int min_args, int max_args,
657 size_t *input_consumed)
659 struct macro_token *tokens = ctx->input;
660 size_t n_tokens = ctx->n_input;
663 || tokens[0].token.type != T_MACRO_ID
664 || !ss_equals_case (tokens[0].token.string, function))
667 if (n_tokens < 2 || tokens[1].token.type != T_LPAREN)
669 printf ("`(' expected following %s'\n", function.string);
673 *args = (struct macro_tokens) { .n = 0 };
675 for (size_t i = 2;; )
679 if (tokens[i].token.type == T_RPAREN)
681 *input_consumed = i + 1;
682 if (args->n < min_args || args->n > max_args)
684 printf ("Wrong number of arguments to %s.\n", function.string);
690 i += parse_function_arg (ctx, i, macro_tokens_add_uninit (args));
694 if (tokens[i].token.type == T_COMMA)
696 else if (tokens[i].token.type != T_RPAREN)
698 printf ("Expecting `,' or `)' in %s invocation.", function.string);
704 printf ("Missing closing parenthesis in arguments to %s.\n",
708 macro_tokens_uninit (args);
713 expand_macro_function (struct parse_macro_function_ctx *ctx,
714 struct macro_token *output,
715 size_t *input_consumed)
717 struct macro_tokens args;
719 if (parse_macro_function (ctx, &args, ss_cstr ("!length"), 1, 1,
722 size_t length = args.mts[0].representation.length;
723 *output = (struct macro_token) {
724 .token = { .type = T_POS_NUM, .number = length },
725 .representation = ss_cstr (xasprintf ("%zu", length)),
728 else if (parse_macro_function (ctx, &args, ss_cstr ("!blanks"), 1, 1,
731 /* XXX this isn't right, it might be a character string containing a
732 positive integer, e.g. via !CONCAT. */
733 if (args.mts[0].token.type != T_POS_NUM)
735 printf ("argument to !BLANKS must be positive integer\n");
736 macro_tokens_uninit (&args);
740 struct string s = DS_EMPTY_INITIALIZER;
741 ds_put_byte_multiple (&s, ' ', args.mts[0].token.number);
743 struct substring s_copy;
744 ss_alloc_substring (&s_copy, s.ss);
746 *output = (struct macro_token) {
747 .token = { .type = T_ID, .string = s.ss },
748 .representation = s_copy,
751 else if (parse_macro_function (ctx, &args, ss_cstr ("!concat"), 1, INT_MAX,
755 bool all_strings = true;
756 for (size_t i = 0; i < args.n; i++)
758 if (args.mts[i].token.type == T_STRING)
759 ds_put_substring (&s, args.mts[i].token.string);
763 ds_put_substring (&s, args.mts[i].representation);
769 *output = (struct macro_token) {
770 .token = { .type = T_STRING, .string = s.ss },
772 output->representation = ss_cstr (token_to_string (&output->token));
776 *output = (struct macro_token) {
777 .token = { .type = T_MACRO_ID /*XXX*/, .string = s.ss },
779 ss_alloc_substring (&output->representation, s.ss);
782 else if (parse_macro_function (ctx, &args, ss_cstr ("!quote"), 1, 1,
785 if (args.mts[0].token.type == T_STRING)
786 macro_token_copy (output, &args.mts[0]);
789 *output = (struct macro_token) { .token = { .type = T_STRING } };
790 ss_alloc_substring (&output->token.string, args.mts[0].representation);
791 output->representation = ss_cstr (token_to_string (&output->token));
794 else if (parse_macro_function (ctx, &args, ss_cstr ("!unquote"), 1, 1,
797 if (args.mts[0].token.type == T_STRING)
799 *output = (struct macro_token) { .token = { .type = T_MACRO_ID } };
800 ss_alloc_substring (&output->token.string, args.mts[0].token.string);
801 output->representation = ss_cstr (token_to_string (&output->token));
804 macro_token_copy (output, &args.mts[0]);
809 macro_tokens_uninit (&args);
814 macro_expand (const struct macro_tokens *mts,
815 int nesting_countdown, const struct macro_set *macros,
816 const struct macro_expander *me, bool *expand,
817 struct macro_tokens *exp)
819 if (nesting_countdown <= 0)
821 printf ("maximum nesting level exceeded\n");
822 for (size_t i = 0; i < mts->n; i++)
823 macro_tokens_add (exp, &mts->mts[i]);
827 for (size_t i = 0; i < mts->n; i++)
829 const struct macro_token *mt = &mts->mts[i];
830 const struct token *token = &mt->token;
831 if (token->type == T_MACRO_ID && me)
833 const struct macro_param *param = macro_find_parameter_by_name (
834 me->macro, token->string);
837 const struct macro_tokens *arg = me->args[param - me->macro->params];
838 //macro_tokens_print (arg, stdout);
839 if (*expand && param->expand_arg)
840 macro_expand (arg, nesting_countdown, macros, NULL, expand, exp);
842 for (size_t i = 0; i < arg->n; i++)
843 macro_tokens_add (exp, &arg->mts[i]);
850 struct macro_expander *subme;
851 int retval = macro_expander_create (macros, token, &subme);
852 for (size_t j = 1; !retval; j++)
854 const struct macro_token stop = { .token = { .type = T_STOP } };
855 retval = macro_expander_add (
856 subme, i + j < mts->n ? &mts->mts[i + j] : &stop);
861 macro_expand (&subme->macro->body, nesting_countdown - 1, macros,
863 macro_expander_destroy (subme);
867 macro_expander_destroy (subme);
870 if (token->type != T_MACRO_ID)
872 macro_tokens_add (exp, mt);
876 /* Maybe each arg should just be a string, either a quoted string or a
877 non-quoted string containing tokens. */
878 struct parse_macro_function_ctx ctx = {
879 .input = &mts->mts[i],
880 .n_input = mts->n - i,
881 .nesting_countdown = nesting_countdown,
886 struct macro_token function_output;
887 size_t function_consumed;
888 if (expand_macro_function (&ctx, &function_output, &function_consumed))
890 i += function_consumed - 1;
892 if (function_output.token.type == T_MACRO_ID)
893 macro_tokens_from_string (exp, function_output.token.string,
894 SEG_MODE_INTERACTIVE /* XXX */);
896 macro_tokens_add (exp, &function_output);
897 macro_token_uninit (&function_output);
902 if (ss_equals_case (token->string, ss_cstr ("!onexpand")))
904 else if (ss_equals_case (token->string, ss_cstr ("!offexpand")))
907 macro_tokens_add (exp, mt);
912 macro_expander_get_expansion (struct macro_expander *me, struct macro_tokens *exp)
915 for (size_t i = 0; i < me->macro->n_params; i++)
917 printf ("%s:\n", me->macro->params[i].name);
918 macro_tokens_print (me->args[i], stdout);
923 macro_expand (&me->macro->body, settings_get_mnest (),
924 me->macros, me, &expand, exp);
927 printf ("expansion:\n");
928 macro_tokens_print (exp, stdout);