bced649ec3b08481e352db101bd7b8410b6b3e26
[pspp] / src / language / lexer / macro.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2021 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include "language/lexer/macro.h"
20
21 #include <errno.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include "data/settings.h"
26 #include "language/lexer/lexer.h"
27 #include "language/lexer/segment.h"
28 #include "language/lexer/scan.h"
29 #include "libpspp/assertion.h"
30 #include "libpspp/cast.h"
31 #include "libpspp/i18n.h"
32 #include "libpspp/message.h"
33 #include "libpspp/str.h"
34 #include "libpspp/string-array.h"
35 #include "libpspp/stringi-map.h"
36 #include "libpspp/stringi-set.h"
37
38 #include "gl/c-ctype.h"
39 #include "gl/ftoastr.h"
40
41 #include "gettext.h"
42 #define _(msgid) gettext (msgid)
43
44 /* An entry in the stack of macros and macro directives being expanded.  The
45    stack is maintained as a linked list.  Entries are not dynamically allocated
46    but on the program stack.
47
48    The outermost entry, where 'next' is NULL, represents the source location of
49    the call to the macro. */
50 struct macro_expansion_stack
51   {
52     const struct macro_expansion_stack *next; /* Next outer stack entry. */
53     const char *name;                    /* A macro name or !IF, !DO, etc. */
54     const struct msg_location *location; /* Source location if available. */
55   };
56
57 /* Reports an error during macro expansion.  STACK is the stack for reporting
58    the location of the error, MT is the optional token at which the error was
59    detected, and FORMAT along with the varargs is the message to report. */
60 static void PRINTF_FORMAT (3, 0)
61 macro_error_valist (const struct macro_expansion_stack *stack,
62                     const struct macro_token *mt, const char *format,
63                     va_list args)
64 {
65   struct msg_stack **ms = NULL;
66   size_t allocated_ms = 0;
67   size_t n_ms = 0;
68
69   const struct macro_expansion_stack *p;
70   for (p = stack; p && p->next; p = p->next)
71     {
72       if (n_ms >= allocated_ms)
73         ms = x2nrealloc (ms, &allocated_ms, sizeof *ms);
74
75       /* TRANSLATORS: These strings are used for explaining the context of an
76          error.  The "While expanding" message appears first, followed by zero
77          or more of the "inside expansion" messages.  `innermost',
78          `next_inner`, etc., are names of macros, and `foobar' is a piece of
79          PSPP syntax:
80
81          foo.sps:12: At `foobar' in the expansion of 'innermost',
82          foo.sps:23: inside the expansion of 'next_inner',
83          foo.sps:34: inside the expansion of 'next_inner2',
84          foo.sps:45: inside the expansion of 'outermost',
85          foo.sps:76: This is the actual error message. */
86       char *description;
87       if (p == stack)
88         {
89           if (mt && mt->syntax.length)
90             {
91               char syntax[64];
92               str_ellipsize (mt->syntax, syntax, sizeof syntax);
93               description = xasprintf (_("At `%s' in the expansion of `%s',"),
94                                        syntax, p->name);
95             }
96           else
97             description = xasprintf (_("In the expansion of `%s',"), p->name);
98         }
99       else
100         description = xasprintf (_("inside the expansion of `%s',"), p->name);
101
102       ms[n_ms] = xmalloc (sizeof *ms[n_ms]);
103       *ms[n_ms] = (struct msg_stack) {
104         .location = msg_location_dup (p->location),
105         .description = description,
106       };
107       n_ms++;
108     }
109
110   struct msg *m = xmalloc (sizeof *m);
111   *m = (struct msg) {
112     .category = MSG_C_SYNTAX,
113     .severity = MSG_S_ERROR,
114     .stack = ms,
115     .n_stack = n_ms,
116     .location = msg_location_dup (p ? p->location : NULL),
117     .text = xvasprintf (format, args),
118   };
119   msg_emit (m);
120 }
121
122 /* Reports an error during macro expansion.  STACK is the stack for reporting
123    the location of the error, MT is the optional token at which the error was
124    detected, and FORMAT along with the varargs is the message to report. */
125 static void PRINTF_FORMAT (3, 4)
126 macro_error (const struct macro_expansion_stack *stack,
127              const struct macro_token *mt, const char *format, ...)
128 {
129   va_list args;
130   va_start (args, format);
131   macro_error_valist (stack, mt, format, args);
132   va_end (args);
133 }
134
135 void
136 macro_token_copy (struct macro_token *dst, const struct macro_token *src)
137 {
138   token_copy (&dst->token, &src->token);
139   ss_alloc_substring (&dst->syntax, src->syntax);
140 }
141
142 void
143 macro_token_uninit (struct macro_token *mt)
144 {
145   token_uninit (&mt->token);
146   ss_dealloc (&mt->syntax);
147 }
148
149 void
150 macro_token_to_syntax (struct macro_token *mt, struct string *s)
151 {
152   ds_put_substring (s, mt->syntax);
153 }
154 bool
155 is_macro_keyword (struct substring s)
156 {
157   static struct stringi_set keywords = STRINGI_SET_INITIALIZER (keywords);
158   if (stringi_set_is_empty (&keywords))
159     {
160       static const char *kws[] = {
161         "BREAK",
162         "CHAREND",
163         "CMDEND",
164         "DEFAULT",
165         "DO",
166         "DOEND",
167         "ELSE",
168         "ENCLOSE",
169         "ENDDEFINE",
170         "IF",
171         "IFEND",
172         "IN",
173         "LET",
174         "NOEXPAND",
175         "OFFEXPAND",
176         "ONEXPAND",
177         "POSITIONAL",
178         "THEN",
179         "TOKENS",
180       };
181       for (size_t i = 0; i < sizeof kws / sizeof *kws; i++)
182         stringi_set_insert (&keywords, kws[i]);
183     }
184
185   ss_ltrim (&s, ss_cstr ("!"));
186   return stringi_set_contains_len (&keywords, s.string, s.length);
187 }
188 \f
189 void
190 macro_tokens_copy (struct macro_tokens *dst, const struct macro_tokens *src)
191 {
192   *dst = (struct macro_tokens) {
193     .mts = xmalloc (src->n * sizeof *dst->mts),
194     .n = src->n,
195     .allocated = src->n,
196   };
197   for (size_t i = 0; i < src->n; i++)
198     macro_token_copy (&dst->mts[i], &src->mts[i]);
199 }
200
201 void
202 macro_tokens_uninit (struct macro_tokens *mts)
203 {
204   for (size_t i = 0; i < mts->n; i++)
205     macro_token_uninit (&mts->mts[i]);
206   free (mts->mts);
207 }
208
209 struct macro_token *
210 macro_tokens_add_uninit (struct macro_tokens *mts)
211 {
212   if (mts->n >= mts->allocated)
213     mts->mts = x2nrealloc (mts->mts, &mts->allocated, sizeof *mts->mts);
214   return &mts->mts[mts->n++];
215 }
216
217 void
218 macro_tokens_add (struct macro_tokens *mts, const struct macro_token *mt)
219 {
220   macro_token_copy (macro_tokens_add_uninit (mts), mt);
221 }
222
223 /* Tokenizes SRC according to MODE and appends the tokens to MTS.  Uses STACK,
224    if nonull, for error reporting. */
225 static void
226 macro_tokens_from_string__ (struct macro_tokens *mts, const struct substring src,
227                             enum segmenter_mode mode,
228                             const struct macro_expansion_stack *stack)
229 {
230   struct segmenter segmenter = segmenter_init (mode, true);
231   struct substring body = src;
232
233   while (body.length > 0)
234     {
235       struct macro_token mt = {
236         .token = { .type = T_STOP },
237         .syntax = { .string = body.string },
238       };
239       struct token *token = &mt.token;
240
241       enum segment_type type;
242       int seg_len = segmenter_push (&segmenter, body.string,
243                                     body.length, true, &type);
244       assert (seg_len >= 0);
245
246       struct substring segment = ss_head (body, seg_len);
247       enum tokenize_result result = token_from_segment (type, segment, token);
248       ss_advance (&body, seg_len);
249
250       switch (result)
251         {
252         case TOKENIZE_EMPTY:
253           break;
254
255         case TOKENIZE_TOKEN:
256           mt.syntax.length = body.string - mt.syntax.string;
257           macro_tokens_add (mts, &mt);
258           break;
259
260         case TOKENIZE_ERROR:
261           mt.syntax.length = body.string - mt.syntax.string;
262           macro_error (stack, &mt, "%s", token->string.string);
263           break;
264         }
265
266       token_uninit (token);
267     }
268 }
269
270 /* Tokenizes SRC according to MODE and appends the tokens to MTS. */
271 void
272 macro_tokens_from_string (struct macro_tokens *mts, const struct substring src,
273                           enum segmenter_mode mode)
274 {
275   macro_tokens_from_string__ (mts, src, mode, NULL);
276 }
277
278 void
279 macro_tokens_print (const struct macro_tokens *mts, FILE *stream)
280 {
281   for (size_t i = 0; i < mts->n; i++)
282     token_print (&mts->mts[i].token, stream);
283 }
284
285 enum token_class
286   {
287     TC_ENDCMD,                  /* No space before or after (new-line after). */
288     TC_BINOP,                   /* Space on both sides. */
289     TC_COMMA,                   /* Space afterward. */
290     TC_ID,                      /* Don't need spaces except sequentially. */
291     TC_PUNCT,                   /* Don't need spaces except sequentially. */
292   };
293
294 static bool
295 needs_space (enum token_class prev, enum token_class next)
296 {
297   /* Don't need a space before or after the end of a command.
298      (A new-line is needed afterward as a special case.) */
299   if (prev == TC_ENDCMD || next == TC_ENDCMD)
300     return false;
301
302   /* Binary operators always have a space on both sides. */
303   if (prev == TC_BINOP || next == TC_BINOP)
304     return true;
305
306   /* A comma always has a space afterward. */
307   if (prev == TC_COMMA)
308     return true;
309
310   /* Otherwise, PREV is TC_ID or TC_PUNCT, which only need a space if there are
311      two or them in a row. */
312   return prev == next;
313 }
314
315 static enum token_class
316 classify_token (enum token_type type)
317 {
318   switch (type)
319     {
320     case T_ID:
321     case T_MACRO_ID:
322     case T_POS_NUM:
323     case T_NEG_NUM:
324     case T_STRING:
325       return TC_ID;
326
327     case T_STOP:
328       return TC_PUNCT;
329
330     case T_ENDCMD:
331       return TC_ENDCMD;
332
333     case T_LPAREN:
334     case T_RPAREN:
335     case T_LBRACK:
336     case T_RBRACK:
337       return TC_PUNCT;
338
339     case T_PLUS:
340     case T_DASH:
341     case T_ASTERISK:
342     case T_SLASH:
343     case T_EQUALS:
344     case T_AND:
345     case T_OR:
346     case T_NOT:
347     case T_EQ:
348     case T_GE:
349     case T_GT:
350     case T_LE:
351     case T_LT:
352     case T_NE:
353     case T_ALL:
354     case T_BY:
355     case T_TO:
356     case T_WITH:
357     case T_EXP:
358     case T_MACRO_PUNCT:
359       return TC_BINOP;
360
361     case T_COMMA:
362       return TC_COMMA;
363     }
364
365   NOT_REACHED ();
366 }
367
368 /* Appends syntax for the tokens in MTS to S.  If OFS and LEN are nonnull, sets
369    OFS[i] to the offset within S of the start of token 'i' in MTS and LEN[i] to
370    its length.  OFS[i] + LEN[i] is not necessarily OFS[i + 1] because some
371    tokens are separated by white space.  */
372 void
373 macro_tokens_to_syntax (struct macro_tokens *mts, struct string *s,
374                         size_t *ofs, size_t *len)
375 {
376   assert ((ofs != NULL) == (len != NULL));
377
378   if (!mts->n)
379     return;
380
381   for (size_t i = 0; i < mts->n; i++)
382     {
383       if (i > 0)
384         {
385           enum token_type prev = mts->mts[i - 1].token.type;
386           enum token_type next = mts->mts[i].token.type;
387
388           if (prev == T_ENDCMD)
389             ds_put_byte (s, '\n');
390           else
391             {
392               enum token_class pc = classify_token (prev);
393               enum token_class nc = classify_token (next);
394               if (needs_space (pc, nc))
395                 ds_put_byte (s, ' ');
396             }
397         }
398
399       if (ofs)
400         ofs[i] = s->ss.length;
401       macro_token_to_syntax (&mts->mts[i], s);
402       if (len)
403         len[i] = s->ss.length - ofs[i];
404     }
405 }
406
407 void
408 macro_destroy (struct macro *m)
409 {
410   if (!m)
411     return;
412
413   free (m->name);
414   msg_location_destroy (m->location);
415   for (size_t i = 0; i < m->n_params; i++)
416     {
417       struct macro_param *p = &m->params[i];
418       free (p->name);
419
420       macro_tokens_uninit (&p->def);
421       token_uninit (&p->start);
422       token_uninit (&p->end);
423     }
424   free (m->params);
425   macro_tokens_uninit (&m->body);
426   free (m);
427 }
428 \f
429 struct macro_set *
430 macro_set_create (void)
431 {
432   struct macro_set *set = xmalloc (sizeof *set);
433   *set = (struct macro_set) {
434     .macros = HMAP_INITIALIZER (set->macros),
435   };
436   return set;
437 }
438
439 void
440 macro_set_destroy (struct macro_set *set)
441 {
442   if (!set)
443     return;
444
445   struct macro *macro, *next;
446   HMAP_FOR_EACH_SAFE (macro, next, struct macro, hmap_node, &set->macros)
447     {
448       hmap_delete (&set->macros, &macro->hmap_node);
449       macro_destroy (macro);
450     }
451   hmap_destroy (&set->macros);
452   free (set);
453 }
454
455 static unsigned int
456 hash_macro_name (const char *name)
457 {
458   return utf8_hash_case_string (name, 0);
459 }
460
461 static struct macro *
462 macro_set_find__ (struct macro_set *set, const char *name)
463 {
464   if (macro_set_is_empty (set))
465     return NULL;
466
467   struct macro *macro;
468   HMAP_FOR_EACH_WITH_HASH (macro, struct macro, hmap_node,
469                            hash_macro_name (name), &set->macros)
470     if (!utf8_strcasecmp (macro->name, name))
471       return macro;
472
473   return NULL;
474 }
475
476 const struct macro *
477 macro_set_find (const struct macro_set *set, const char *name)
478 {
479   return macro_set_find__ (CONST_CAST (struct macro_set *, set), name);
480 }
481
482 /* Adds M to SET.  M replaces any existing macro with the same name.  Takes
483    ownership of M. */
484 void
485 macro_set_add (struct macro_set *set, struct macro *m)
486 {
487   struct macro *victim = macro_set_find__ (set, m->name);
488   if (victim)
489     {
490       hmap_delete (&set->macros, &victim->hmap_node);
491       macro_destroy (victim);
492     }
493
494   hmap_insert (&set->macros, &m->hmap_node, hash_macro_name (m->name));
495 }
496 \f
497 /* Macro call parsing. */
498
499 enum mc_state
500   {
501     /* Accumulating tokens in mc->params toward the end of any type of
502        argument. */
503     MC_ARG,
504
505     /* Expecting the opening delimiter of an ARG_ENCLOSE argument. */
506     MC_ENCLOSE,
507
508     /* Expecting a keyword for a keyword argument. */
509     MC_KEYWORD,
510
511     /* Expecting an equal sign for a keyword argument. */
512     MC_EQUALS,
513
514     /* Macro fully parsed and ready for expansion. */
515     MC_FINISHED,
516   };
517
518 /* Parsing macro calls.  This is a FSM driven by macro_call_create() and
519    macro_call_add() to identify the macro being called and obtain its
520    arguments.  'state' identifies the FSM state. */
521 struct macro_call
522   {
523     const struct macro_set *macros;
524     const struct macro *macro;
525     struct macro_tokens **args;
526     const struct macro_expansion_stack *stack;
527     const struct macro_expander *me;
528
529     enum mc_state state;
530     size_t n_tokens;
531     const struct macro_param *param; /* Parameter currently being parsed. */
532   };
533
534 static bool macro_expand_arg (const struct token *,
535                               const struct macro_expander *,
536                               struct macro_tokens *exp);
537
538 /* Completes macro expansion by initializing arguments that weren't supplied to
539    their defaults. */
540 static int
541 mc_finished (struct macro_call *mc)
542 {
543   mc->state = MC_FINISHED;
544   for (size_t i = 0; i < mc->macro->n_params; i++)
545     if (!mc->args[i])
546       mc->args[i] = &mc->macro->params[i].def;
547   return mc->n_tokens;
548 }
549
550 static int
551 mc_next_arg (struct macro_call *mc)
552 {
553   if (!mc->param)
554     {
555       assert (!mc->macro->n_params);
556       return mc_finished (mc);
557     }
558   else if (mc->param->positional)
559     {
560       mc->param++;
561       if (mc->param >= &mc->macro->params[mc->macro->n_params])
562         return mc_finished (mc);
563       else
564         {
565           mc->state = (!mc->param->positional ? MC_KEYWORD
566                        : mc->param->arg_type == ARG_ENCLOSE ? MC_ENCLOSE
567                        : MC_ARG);
568           return 0;
569         }
570     }
571   else
572     {
573       for (size_t i = 0; i < mc->macro->n_params; i++)
574         if (!mc->args[i])
575           {
576             mc->state = MC_KEYWORD;
577             return 0;
578           }
579       return mc_finished (mc);
580     }
581 }
582
583 static void PRINTF_FORMAT (3, 4)
584 mc_error (const struct macro_call *mc, const struct msg_location *loc,
585           const char *format, ...)
586 {
587   va_list args;
588   va_start (args, format);
589   if (!mc->stack)
590     {
591       const struct macro_expansion_stack stack = { .location = loc };
592       macro_error_valist (&stack, NULL, format, args);
593     }
594   else
595     macro_error_valist (mc->stack, NULL, format, args);
596   va_end (args);
597 }
598
599 static int
600 mc_add_arg (struct macro_call *mc, const struct macro_token *mt,
601             const struct msg_location *loc)
602 {
603   const struct macro_param *p = mc->param;
604   struct macro_tokens **argp = &mc->args[p - mc->macro->params];
605
606   const struct token *token = &mt->token;
607   if (token->type == T_ENDCMD || token->type == T_STOP)
608     {
609       if (*argp)
610         {
611           switch (p->arg_type)
612             {
613             case ARG_CMDEND:
614               /* This is OK, it's the expected way to end the argument. */
615               break;
616
617             case ARG_N_TOKENS:
618               mc_error (mc, loc,
619                         ngettext (_("Reached end of command expecting %zu "
620                                     "more token in argument %s to macro %s."),
621                                   _("Reached end of command expecting %zu "
622                                     "more tokens in argument %s to macro %s."),
623                                   p->n_tokens - (*argp)->n),
624                         p->n_tokens - (*argp)->n, p->name, mc->macro->name);
625               break;
626
627             case ARG_CHAREND:
628             case ARG_ENCLOSE:
629               {
630                 char *end = token_to_string (&p->end);
631                 mc_error (mc, loc, _("Reached end of command expecting \"%s\" "
632                                      "in argument %s to macro %s."),
633                           end, p->name, mc->macro->name);
634                 free (end);
635               }
636               break;
637             }
638         }
639
640       /* The end of a command ends the current argument, precludes any further
641          arguments, and is not itself part of the argument. */
642       return mc_finished (mc);
643     }
644
645   mc->n_tokens++;
646
647   if (!*argp)
648     *argp = xzalloc (sizeof **argp);
649
650   bool add_token;               /* Should we add 'mt' to the current arg? */
651   bool next_arg;                /* Should we advance to the next arg? */
652   switch (p->arg_type)
653     {
654     case ARG_N_TOKENS:
655       next_arg = (*argp)->n + 1 >= p->n_tokens;
656       add_token = true;
657       break;
658
659     case ARG_CHAREND:
660     case ARG_ENCLOSE:
661       next_arg = token_equal (token, &p->end);
662       add_token = !next_arg;
663       break;
664
665     case ARG_CMDEND:
666       next_arg = false;
667       add_token = true;
668       break;
669
670     default:
671       NOT_REACHED ();
672     }
673
674   if (add_token)
675     {
676       if (!macro_expand_arg (&mt->token, mc->me, *argp))
677         macro_tokens_add (*argp, mt);
678     }
679   return next_arg ? mc_next_arg (mc) : 0;
680 }
681
682 static int
683 mc_expected (struct macro_call *mc, const struct macro_token *actual,
684              const struct msg_location *loc, const struct token *expected)
685 {
686   const struct substring actual_s = (actual->syntax.length ? actual->syntax
687                                      : ss_cstr (_("<end of input>")));
688   char *expected_s = token_to_string (expected);
689   mc_error (mc, loc,
690             _("Found `%.*s' while expecting `%s' reading argument %s "
691               "to macro %s."),
692             (int) actual_s.length, actual_s.string, expected_s,
693             mc->param->name, mc->macro->name);
694   free (expected_s);
695
696   return mc_finished (mc);
697 }
698
699 static int
700 mc_enclose (struct macro_call *mc, const struct macro_token *mt,
701             const struct msg_location *loc)
702 {
703   const struct token *token = &mt->token;
704   const struct macro_param *p = mc->param;
705   if (token_equal (&p->start, token))
706     {
707       mc->n_tokens++;
708
709       struct macro_tokens **argp = &mc->args[p - mc->macro->params];
710       if (!*argp)
711         *argp = xzalloc (sizeof **argp);
712       mc->state = MC_ARG;
713       return 0;
714     }
715   else if (p->positional && (token->type == T_ENDCMD || token->type == T_STOP))
716     return mc_finished (mc);
717   else
718     return mc_expected (mc, mt, loc, &p->start);
719 }
720
721 static const struct macro_param *
722 macro_find_parameter_by_name (const struct macro *m, struct substring name)
723 {
724   if (!m)
725     return NULL;
726
727   ss_ltrim (&name, ss_cstr ("!"));
728
729   for (size_t i = 0; i < m->n_params; i++)
730     {
731       const struct macro_param *p = &m->params[i];
732       struct substring p_name = ss_cstr (p->name + 1);
733       if (!utf8_strncasecmp (p_name.string, p_name.length,
734                              name.string, name.length))
735         return p;
736     }
737   return NULL;
738 }
739
740 static int
741 mc_keyword (struct macro_call *mc, const struct macro_token *mt,
742             const struct msg_location *loc)
743 {
744   const struct token *token = &mt->token;
745   if (token->type != T_ID)
746     return mc_finished (mc);
747
748   const struct macro_param *p = macro_find_parameter_by_name (mc->macro,
749                                                               token->string);
750   if (p)
751     {
752       struct macro_tokens **argp = &mc->args[p - mc->macro->params];
753       if (*argp)
754         mc_error (mc, loc,
755                   _("Argument %s multiply specified in call to macro %s."),
756                   p->name, mc->macro->name);
757
758       *argp = xzalloc (sizeof **argp);
759       mc->param = p;
760       mc->n_tokens++;
761       mc->state = MC_EQUALS;
762       return 0;
763     }
764
765   return mc_finished (mc);
766 }
767
768 static int
769 mc_equals (struct macro_call *mc, const struct macro_token *mt,
770            const struct msg_location *loc)
771 {
772   if (mt->token.type == T_EQUALS)
773     {
774       mc->n_tokens++;
775       mc->state = mc->param->arg_type == ARG_ENCLOSE ? MC_ENCLOSE : MC_ARG;
776       return 0;
777     }
778
779   return mc_expected (mc, mt, loc, &(struct token) { .type = T_EQUALS });
780 }
781
782 static int
783 macro_call_create__ (const struct macro_set *macros,
784                      const struct macro_expansion_stack *stack,
785                      const struct macro_expander *me,
786                      const struct token *token,
787                      struct macro_call **mcp)
788 {
789   const struct macro *macro = (token->type == T_ID || token->type == T_MACRO_ID
790                                ? macro_set_find (macros, token->string.string)
791                                : NULL);
792   if (!macro)
793     {
794       *mcp = NULL;
795       return -1;
796     }
797
798   struct macro_call *mc = xmalloc (sizeof *mc);
799   *mc = (struct macro_call) {
800     .macros = macros,
801     .macro = macro,
802     .n_tokens = 1,
803     .state = (!macro->n_params ? MC_FINISHED
804               : !macro->params[0].positional ? MC_KEYWORD
805               : macro->params[0].arg_type == ARG_ENCLOSE ? MC_ENCLOSE
806               : MC_ARG),
807     .args = macro->n_params ? xcalloc (macro->n_params, sizeof *mc->args) : NULL,
808     .param = macro->params,
809     .stack = stack,
810     .me = me,
811   };
812   *mcp = mc;
813
814   return mc->state == MC_FINISHED ? 1 : 0;
815 }
816
817 /* If TOKEN is the first token of a call to a macro in MACROS, create a new
818    macro expander, initializes *MCP to it.  Returns 0 if more tokens are needed
819    and should be added via macro_call_add() or 1 if the caller should next call
820    macro_call_get_expansion().
821
822    If TOKEN is not the first token of a macro call, returns -1 and sets *MCP to
823    NULL. */
824 int
825 macro_call_create (const struct macro_set *macros,
826                    const struct token *token,
827                    struct macro_call **mcp)
828 {
829   return macro_call_create__ (macros, NULL, NULL, token, mcp);
830 }
831
832 void
833 macro_call_destroy (struct macro_call *mc)
834 {
835   if (!mc)
836     return;
837
838   for (size_t i = 0; i < mc->macro->n_params; i++)
839     {
840       struct macro_tokens *a = mc->args[i];
841       if (a && a != &mc->macro->params[i].def)
842         {
843           macro_tokens_uninit (a);
844           free (a);
845         }
846     }
847   free (mc->args);
848   free (mc);
849 }
850
851 /* Adds TOKEN to the collection of tokens in MC that potentially need to be
852    macro expanded.
853
854    Returns -1 if the tokens added do not actually invoke a macro.  The caller
855    should consume the first token without expanding it.  (Later tokens might
856    invoke a macro so it's best to feed the second token into a new expander.)
857
858    Returns 0 if the macro expander needs more tokens, for macro arguments or to
859    decide whether this is actually a macro invocation.  The caller should call
860    macro_call_add() again with the next token.
861
862    Returns a positive number to indicate that the returned number of tokens
863    invoke a macro.  The number returned might be less than the number of tokens
864    added because it can take a few tokens of lookahead to determine whether the
865    macro invocation is finished.  The caller should call
866    macro_call_get_expansion() to obtain the expansion. */
867 int
868 macro_call_add (struct macro_call *mc, const struct macro_token *mt,
869                 const struct msg_location *loc)
870 {
871   switch (mc->state)
872     {
873     case MC_ARG:
874       return mc_add_arg (mc, mt, loc);
875
876     case MC_ENCLOSE:
877       return mc_enclose (mc, mt, loc);
878
879     case MC_KEYWORD:
880       return mc_keyword (mc, mt, loc);
881
882     case MC_EQUALS:
883       return mc_equals (mc, mt, loc);
884
885     default:
886       NOT_REACHED ();
887     }
888 }
889 \f
890 /* Macro expansion. */
891
892 struct macro_expander
893   {
894     /* Always available. */
895     const struct macro_set *macros;     /* Macros to expand recursively. */
896     enum segmenter_mode segmenter_mode; /* Mode for tokenization. */
897     int nesting_countdown;              /* Remaining nesting levels. */
898     const struct macro_expansion_stack *stack; /* Stack for error reporting. */
899     bool *expand;                       /* May macro calls be expanded? */
900     struct stringi_map *vars;           /* Variables from !do and !let. */
901
902     /* Only nonnull if inside a !DO loop. */
903     bool *break_;                       /* Set to true to break out of loop. */
904
905     /* Only nonnull if expanding a macro (and not, say, a macro argument). */
906     const struct macro *macro;
907     struct macro_tokens **args;
908   };
909
910 static void
911 macro_expand (const struct macro_token *mts, size_t n_mts,
912               const struct macro_expander *, struct macro_tokens *);
913
914 static size_t
915 expand_macro_function (const struct macro_expander *me,
916                        const struct macro_token *input, size_t n_input,
917                        struct string *output);
918
919 /* Parses one function argument from the N_INPUT tokens in INPUT
920    Each argument to a macro function is one of:
921
922        - A quoted string or other single literal token.
923
924        - An argument to the macro being expanded, e.g. !1 or a named argument.
925
926        - !*.
927
928        - A function invocation.
929
930    Each function invocation yields a character sequence to be turned into a
931    sequence of tokens.  The case where that character sequence is a single
932    quoted string is an important special case.
933 */
934 static size_t
935 parse_function_arg (const struct macro_expander *me,
936                     const struct macro_token *input, size_t n_input,
937                     struct string *farg)
938 {
939   assert (n_input > 0);
940
941   const struct token *token = &input[0].token;
942   if (token->type == T_MACRO_ID && me->macro)
943     {
944       const struct macro_param *param = macro_find_parameter_by_name (
945         me->macro, token->string);
946       if (param)
947         {
948           size_t param_idx = param - me->macro->params;
949           macro_tokens_to_syntax (me->args[param_idx], farg, NULL, NULL);
950           return 1;
951         }
952
953       if (ss_equals (token->string, ss_cstr ("!*")))
954         {
955           for (size_t i = 0; i < me->macro->n_params; i++)
956             {
957               if (!me->macro->params[i].positional)
958                 break;
959               if (i)
960                 ds_put_byte (farg, ' ');
961               macro_tokens_to_syntax (me->args[i], farg, NULL, NULL);
962             }
963           return 1;
964         }
965
966       const char *var = stringi_map_find__ (me->vars,
967                                             token->string.string,
968                                             token->string.length);
969       if (var)
970         {
971           ds_put_cstr (farg, var);
972           return 1;
973         }
974
975       size_t n_function = expand_macro_function (me, input, n_input, farg);
976       if (n_function)
977         return n_function;
978     }
979
980   ds_put_substring (farg, input[0].syntax);
981   return 1;
982 }
983
984 static size_t
985 parse_function_args (const struct macro_expander *me,
986                      const struct macro_token *mts, size_t n,
987                      const char *function,
988                      struct string_array *args)
989 {
990   assert (n >= 2 && mts[1].token.type == T_LPAREN);
991
992   for (size_t i = 2; i < n; )
993     {
994       if (mts[i].token.type == T_RPAREN)
995         return i + 1;
996
997       struct string s = DS_EMPTY_INITIALIZER;
998       i += parse_function_arg (me, mts + i, n - i, &s);
999       string_array_append_nocopy (args, ds_steal_cstr (&s));
1000
1001       if (i >= n)
1002         break;
1003       else if (mts[i].token.type == T_COMMA)
1004         i++;
1005       else if (mts[i].token.type != T_RPAREN)
1006         {
1007           macro_error (me->stack, &mts[i],
1008                        _("`,' or `)' expected in call to macro function %s."),
1009                        function);
1010           return 0;
1011         }
1012     }
1013
1014   macro_error (me->stack, NULL, _("Missing `)' in call to macro function %s."),
1015                function);
1016   return 0;
1017 }
1018
1019 static bool
1020 unquote_string (const char *s, enum segmenter_mode segmenter_mode,
1021                 struct string *content)
1022 {
1023   struct string_lexer slex;
1024   string_lexer_init (&slex, s, strlen (s), segmenter_mode, true);
1025
1026   struct token token1;
1027   if (string_lexer_next (&slex, &token1) != SLR_TOKEN
1028       || token1.type != T_STRING)
1029     {
1030       token_uninit (&token1);
1031       return false;
1032     }
1033
1034   struct token token2;
1035   if (string_lexer_next (&slex, &token2) != SLR_END)
1036     {
1037       token_uninit (&token1);
1038       token_uninit (&token2);
1039       return false;
1040     }
1041
1042   if (content)
1043     ds_put_substring (content, token1.string);
1044   token_uninit (&token1);
1045   return true;
1046 }
1047
1048 static const char *
1049 unquote_string_in_place (const char *s, enum segmenter_mode segmenter_mode,
1050                          struct string *tmp)
1051 {
1052   ds_init_empty (tmp);
1053   return unquote_string (s, segmenter_mode, tmp) ? ds_cstr (tmp) : s;
1054 }
1055
1056 static bool
1057 parse_integer (const char *s, int *np)
1058 {
1059   errno = 0;
1060
1061   char *tail;
1062   long int n = strtol (s, &tail, 10);
1063   *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
1064   tail += strspn (tail, CC_SPACES);
1065   return *tail == '\0' && errno != ERANGE && n == *np;
1066 }
1067
1068 static size_t
1069 expand_macro_function (const struct macro_expander *me,
1070                        const struct macro_token *input, size_t n_input,
1071                        struct string *output)
1072 {
1073   if (!n_input || input[0].token.type != T_MACRO_ID)
1074     return 0;
1075
1076   struct macro_function
1077     {
1078       const char *name;
1079       int min_args;
1080       int max_args;
1081     };
1082   enum macro_function_id
1083     {
1084       MF_BLANKS,
1085       MF_CONCAT,
1086       MF_EVAL,
1087       MF_HEAD,
1088       MF_INDEX,
1089       MF_LENGTH,
1090       MF_QUOTE,
1091       MF_SUBSTR,
1092       MF_TAIL,
1093       MF_UNQUOTE,
1094       MF_UPCASE,
1095     };
1096   static const struct macro_function mfs[] = {
1097     [MF_BLANKS]  = { "!BLANKS",  1, 1 },
1098     [MF_CONCAT]  = { "!CONCAT",  1, INT_MAX },
1099     [MF_EVAL]    = { "!EVAL",    1, 1 },
1100     [MF_HEAD]    = { "!HEAD",    1, 1 },
1101     [MF_INDEX]   = { "!INDEX",   2, 2 },
1102     [MF_LENGTH]  = { "!LENGTH",  1, 1 },
1103     [MF_QUOTE]   = { "!QUOTE",   1, 1 },
1104     [MF_SUBSTR]  = { "!SUBSTR",  2, 3 },
1105     [MF_TAIL]    = { "!TAIL",    1, 1 },
1106     [MF_UNQUOTE] = { "!UNQUOTE", 1, 1 },
1107     [MF_UPCASE]  = { "!UPCASE",  1, 1 },
1108   };
1109
1110   if (lex_id_match_n (ss_cstr ("!NULL"), input[0].token.string, 4))
1111     return 1;
1112
1113   if (n_input < 2 || input[1].token.type != T_LPAREN)
1114     {
1115       /* Only consider macro functions when the name is followed by '('. */
1116       return 0;
1117     }
1118
1119   /* Is this a macro function name? */
1120   const struct macro_function *mf;
1121   for (mf = mfs; ; mf++)
1122     {
1123       if (mf >= mfs + sizeof mfs / sizeof *mfs)
1124         {
1125           /* Not a macro function. */
1126           return 0;
1127         }
1128
1129       if (lex_id_match_n (ss_cstr (mf->name), input[0].token.string, 4))
1130         break;
1131     }
1132
1133   enum macro_function_id id = mf - mfs;
1134
1135   struct string_array args = STRING_ARRAY_INITIALIZER;
1136   size_t n_consumed = parse_function_args (me, input, n_input, mf->name, &args);
1137   if (!n_consumed)
1138     return 0;
1139
1140   if (args.n < mf->min_args || args.n > mf->max_args)
1141     {
1142       if (mf->min_args == 1 && mf->max_args == 1)
1143         macro_error (me->stack, NULL,
1144                      _("Macro function %s takes one argument (not %zu)."),
1145                      mf->name, args.n);
1146       else if (mf->min_args == 2 && mf->max_args == 2)
1147         macro_error (me->stack, NULL,
1148                      _("Macro function %s takes two arguments (not %zu)."),
1149                      mf->name, args.n);
1150       else if (mf->min_args == 2 && mf->max_args == 3)
1151         macro_error (me->stack, NULL,
1152                      _("Macro function %s takes two or three arguments "
1153                        "(not %zu)."),
1154                      mf->name, args.n);
1155       else if (mf->min_args == 1 && mf->max_args == INT_MAX)
1156         macro_error (me->stack, NULL,
1157                      _("Macro function %s needs at least one argument."),
1158                      mf->name);
1159       else
1160         NOT_REACHED ();
1161       return 0;
1162     }
1163
1164   switch (id)
1165     {
1166     case MF_LENGTH:
1167       ds_put_format (output, "%zu", strlen (args.strings[0]));
1168       break;
1169
1170     case MF_BLANKS:
1171       {
1172         int n;
1173         if (!parse_integer (args.strings[0], &n))
1174           {
1175             macro_error (me->stack, NULL,
1176                          _("Argument to !BLANKS must be non-negative integer "
1177                            "(not \"%s\")."), args.strings[0]);
1178             string_array_destroy (&args);
1179             return 0;
1180           }
1181
1182         ds_put_byte_multiple (output, ' ', n);
1183       }
1184       break;
1185
1186     case MF_CONCAT:
1187       for (size_t i = 0; i < args.n; i++)
1188         if (!unquote_string (args.strings[i], me->segmenter_mode, output))
1189           ds_put_cstr (output, args.strings[i]);
1190       break;
1191
1192     case MF_HEAD:
1193       {
1194         struct string tmp;
1195         const char *s = unquote_string_in_place (args.strings[0],
1196                                                  me->segmenter_mode, &tmp);
1197
1198         struct macro_tokens mts = { .n = 0 };
1199         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1200                                     me->stack);
1201         if (mts.n > 0)
1202           ds_put_substring (output, mts.mts[0].syntax);
1203         macro_tokens_uninit (&mts);
1204         ds_destroy (&tmp);
1205       }
1206       break;
1207
1208     case MF_INDEX:
1209       {
1210         const char *haystack = args.strings[0];
1211         const char *needle = strstr (haystack, args.strings[1]);
1212         ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1213       }
1214       break;
1215
1216     case MF_QUOTE:
1217       if (unquote_string (args.strings[0], me->segmenter_mode, NULL))
1218         ds_put_cstr (output, args.strings[0]);
1219       else
1220         {
1221           ds_extend (output, strlen (args.strings[0]) + 2);
1222           ds_put_byte (output, '\'');
1223           for (const char *p = args.strings[0]; *p; p++)
1224             {
1225               if (*p == '\'')
1226                 ds_put_byte (output, '\'');
1227               ds_put_byte (output, *p);
1228             }
1229           ds_put_byte (output, '\'');
1230         }
1231       break;
1232
1233     case MF_SUBSTR:
1234       {
1235         int start;
1236         if (!parse_integer (args.strings[1], &start) || start < 1)
1237           {
1238             macro_error (me->stack, NULL,
1239                          _("Second argument of !SUBSTR must be "
1240                            "positive integer (not \"%s\")."),
1241                          args.strings[1]);
1242             string_array_destroy (&args);
1243             return 0;
1244           }
1245
1246         int count = INT_MAX;
1247         if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1248           {
1249             macro_error (me->stack, NULL,
1250                          _("Third argument of !SUBSTR must be "
1251                            "non-negative integer (not \"%s\")."),
1252                          args.strings[2]);
1253             string_array_destroy (&args);
1254             return 0;
1255           }
1256
1257         struct substring s = ss_cstr (args.strings[0]);
1258         ds_put_substring (output, ss_substr (s, start - 1, count));
1259       }
1260       break;
1261
1262     case MF_TAIL:
1263       {
1264         struct string tmp;
1265         const char *s = unquote_string_in_place (args.strings[0],
1266                                                  me->segmenter_mode, &tmp);
1267
1268         struct macro_tokens mts = { .n = 0 };
1269         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1270                                     me->stack);
1271         if (mts.n > 1)
1272           {
1273             struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1274             macro_tokens_to_syntax (&tail, output, NULL, NULL);
1275           }
1276         macro_tokens_uninit (&mts);
1277         ds_destroy (&tmp);
1278       }
1279       break;
1280
1281     case MF_UNQUOTE:
1282       if (!unquote_string (args.strings[0], me->segmenter_mode, output))
1283         ds_put_cstr (output, args.strings[0]);
1284       break;
1285
1286     case MF_UPCASE:
1287       {
1288         struct string tmp;
1289         const char *s = unquote_string_in_place (args.strings[0],
1290                                                  me->segmenter_mode, &tmp);
1291         char *upper = utf8_to_upper (s);
1292         ds_put_cstr (output, upper);
1293         free (upper);
1294         ds_destroy (&tmp);
1295       }
1296       break;
1297
1298     case MF_EVAL:
1299       {
1300         struct macro_tokens mts = { .n = 0 };
1301         macro_tokens_from_string__ (&mts, ss_cstr (args.strings[0]),
1302                                     me->segmenter_mode, me->stack);
1303         struct macro_tokens exp = { .n = 0 };
1304         struct macro_expansion_stack stack = {
1305           .name = "!EVAL",
1306           .next = me->stack
1307         };
1308         struct macro_expander subme = *me;
1309         subme.break_ = NULL;
1310         subme.stack = &stack;
1311
1312         macro_expand (mts.mts, mts.n, &subme, &exp);
1313         macro_tokens_to_syntax (&exp, output, NULL, NULL);
1314         macro_tokens_uninit (&exp);
1315         macro_tokens_uninit (&mts);
1316       }
1317       break;
1318
1319     default:
1320       NOT_REACHED ();
1321     }
1322
1323   string_array_destroy (&args);
1324   return n_consumed;
1325 }
1326
1327 static char *macro_evaluate_or (const struct macro_expander *me,
1328                                 const struct macro_token **tokens,
1329                                 const struct macro_token *end);
1330
1331 static char *
1332 macro_evaluate_literal (const struct macro_expander *me,
1333                         const struct macro_token **tokens,
1334                         const struct macro_token *end)
1335 {
1336   const struct macro_token *p = *tokens;
1337   if (p >= end)
1338     return NULL;
1339   if (p->token.type == T_LPAREN)
1340     {
1341       p++;
1342       char *value = macro_evaluate_or (me, &p, end);
1343       if (!value)
1344         return NULL;
1345       if (p >= end || p->token.type != T_RPAREN)
1346         {
1347           free (value);
1348           macro_error (me->stack, p < end ? p : NULL,
1349                        _("Expecting ')' in macro expression."));
1350           return NULL;
1351         }
1352       p++;
1353       *tokens = p;
1354       return value;
1355     }
1356   else if (p->token.type == T_RPAREN)
1357     {
1358       macro_error (me->stack, p, _("Expecting literal or function invocation "
1359                                    "in macro expression."));
1360       return NULL;
1361     }
1362
1363   struct string function_output = DS_EMPTY_INITIALIZER;
1364   size_t function_consumed = parse_function_arg (me, p, end - p,
1365                                                  &function_output);
1366   struct string unquoted = DS_EMPTY_INITIALIZER;
1367   if (unquote_string (ds_cstr (&function_output), me->segmenter_mode,
1368                       &unquoted))
1369     {
1370       ds_swap (&function_output, &unquoted);
1371       ds_destroy (&unquoted);
1372     }
1373   *tokens = p + function_consumed;
1374   return ds_steal_cstr (&function_output);
1375 }
1376
1377 /* Returns true if MT is valid as a macro operator.  Only operators written as
1378    symbols (e.g. <>) are usable in macro expressions, not operator written as
1379    letters (e.g. EQ). */
1380 static bool
1381 is_macro_operator (const struct macro_token *mt)
1382 {
1383   return mt->syntax.length > 0 && !c_isalpha (mt->syntax.string[0]);
1384 }
1385
1386 static enum token_type
1387 parse_relational_op (const struct macro_token *mt)
1388 {
1389   switch (mt->token.type)
1390     {
1391     case T_EQUALS:
1392       return T_EQ;
1393
1394     case T_NE:
1395     case T_LT:
1396     case T_GT:
1397     case T_LE:
1398     case T_GE:
1399       return is_macro_operator (mt) ? mt->token.type : T_STOP;
1400
1401     case T_MACRO_ID:
1402       return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1403               : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1404               : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1405               : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1406               : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1407               : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1408               : T_STOP);
1409
1410     default:
1411       return T_STOP;
1412     }
1413 }
1414
1415 static char *
1416 macro_evaluate_relational (const struct macro_expander *me,
1417                            const struct macro_token **tokens,
1418                            const struct macro_token *end)
1419 {
1420   const struct macro_token *p = *tokens;
1421   char *lhs = macro_evaluate_literal (me, &p, end);
1422   if (!lhs)
1423     return NULL;
1424
1425   enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1426   if (op == T_STOP)
1427     {
1428       *tokens = p;
1429       return lhs;
1430     }
1431   p++;
1432
1433   char *rhs = macro_evaluate_literal (me, &p, end);
1434   if (!rhs)
1435     {
1436       free (lhs);
1437       return NULL;
1438     }
1439
1440   struct string lhs_tmp, rhs_tmp;
1441   int cmp = strcmp (unquote_string_in_place (lhs, me->segmenter_mode,
1442                                              &lhs_tmp),
1443                     unquote_string_in_place (rhs, me->segmenter_mode,
1444                                              &rhs_tmp));
1445   ds_destroy (&lhs_tmp);
1446   ds_destroy (&rhs_tmp);
1447
1448   free (lhs);
1449   free (rhs);
1450
1451   bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1452             : op == T_NE ? cmp
1453             : op == T_LT ? cmp < 0
1454             : op == T_GT ? cmp > 0
1455             : op == T_LE ? cmp <= 0
1456             : /* T_GE */ cmp >= 0);
1457
1458   *tokens = p;
1459   return xstrdup (b ? "1" : "0");
1460 }
1461
1462 static char *
1463 macro_evaluate_not (const struct macro_expander *me,
1464                     const struct macro_token **tokens,
1465                     const struct macro_token *end)
1466 {
1467   const struct macro_token *p = *tokens;
1468
1469   unsigned int negations = 0;
1470   while (p < end
1471          && (ss_equals_case (p->syntax, ss_cstr ("!NOT"))
1472              || ss_equals (p->syntax, ss_cstr ("~"))))
1473     {
1474       p++;
1475       negations++;
1476     }
1477
1478   char *operand = macro_evaluate_relational (me, &p, end);
1479   if (!operand || !negations)
1480     {
1481       *tokens = p;
1482       return operand;
1483     }
1484
1485   bool b = strcmp (operand, "0") ^ (negations & 1);
1486   free (operand);
1487   *tokens = p;
1488   return xstrdup (b ? "1" : "0");
1489 }
1490
1491 static char *
1492 macro_evaluate_and (const struct macro_expander *me,
1493                     const struct macro_token **tokens,
1494                     const struct macro_token *end)
1495 {
1496   const struct macro_token *p = *tokens;
1497   char *lhs = macro_evaluate_not (me, &p, end);
1498   if (!lhs)
1499     return NULL;
1500
1501   while (p < end
1502          && (ss_equals_case (p->syntax, ss_cstr ("!AND"))
1503              || ss_equals (p->syntax, ss_cstr ("&"))))
1504     {
1505       p++;
1506       char *rhs = macro_evaluate_not (me, &p, end);
1507       if (!rhs)
1508         {
1509           free (lhs);
1510           return NULL;
1511         }
1512
1513       bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1514       free (lhs);
1515       free (rhs);
1516       lhs = xstrdup (b ? "1" : "0");
1517     }
1518   *tokens = p;
1519   return lhs;
1520 }
1521
1522 static char *
1523 macro_evaluate_or (const struct macro_expander *me,
1524                    const struct macro_token **tokens,
1525                    const struct macro_token *end)
1526 {
1527   const struct macro_token *p = *tokens;
1528   char *lhs = macro_evaluate_and (me, &p, end);
1529   if (!lhs)
1530     return NULL;
1531
1532   while (p < end
1533          && (ss_equals_case (p->syntax, ss_cstr ("!OR"))
1534              || ss_equals (p->syntax, ss_cstr ("|"))))
1535     {
1536       p++;
1537       char *rhs = macro_evaluate_and (me, &p, end);
1538       if (!rhs)
1539         {
1540           free (lhs);
1541           return NULL;
1542         }
1543
1544       bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1545       free (lhs);
1546       free (rhs);
1547       lhs = xstrdup (b ? "1" : "0");
1548     }
1549   *tokens = p;
1550   return lhs;
1551 }
1552
1553 static char *
1554 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1555                            const struct macro_expander *me)
1556 {
1557   return macro_evaluate_or (me, tokens, *tokens + n_tokens);
1558 }
1559
1560 static bool
1561 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1562                        const struct macro_expander *me,
1563                        double *number)
1564 {
1565   char *s = macro_evaluate_expression (tokens, n_tokens, me);
1566   if (!s)
1567     return false;
1568
1569   struct macro_tokens mts = { .n = 0 };
1570   macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode, me->stack);
1571   if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1572     {
1573       macro_error (me->stack, mts.n > 0 ? &mts.mts[0] : NULL,
1574                    _("Macro expression must evaluate to "
1575                      "a number (not \"%s\")."), s);
1576       free (s);
1577       macro_tokens_uninit (&mts);
1578       return false;
1579     }
1580
1581   *number = token_number (&mts.mts[0].token);
1582   free (s);
1583   macro_tokens_uninit (&mts);
1584   return true;
1585 }
1586
1587 static const struct macro_token *
1588 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1589 {
1590   size_t nesting = 0;
1591   for (; p < end; p++)
1592     {
1593       if (p->token.type != T_MACRO_ID)
1594         continue;
1595
1596       if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1597         nesting++;
1598       else if (lex_id_match_n (p->token.string, ss_cstr ("!IFEND"), 4))
1599         {
1600           if (!nesting)
1601             return p;
1602           nesting--;
1603         }
1604       else if (lex_id_match_n (p->token.string, ss_cstr ("!ELSE"), 4)
1605                && !nesting)
1606         return p;
1607     }
1608   return NULL;
1609 }
1610
1611 static size_t
1612 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1613                  const struct macro_expander *me,
1614                  struct macro_tokens *exp)
1615 {
1616   const struct macro_token *p = tokens;
1617   const struct macro_token *end = tokens + n_tokens;
1618
1619   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1620     return 0;
1621
1622   p++;
1623   char *result = macro_evaluate_expression (&p, end - p, me);
1624   if (!result)
1625     return 0;
1626   bool b = strcmp (result, "0");
1627   free (result);
1628
1629   if (p >= end
1630       || p->token.type != T_MACRO_ID
1631       || !lex_id_match_n (p->token.string, ss_cstr ("!THEN"), 4))
1632     {
1633       macro_error (me->stack, p < end ? p : NULL,
1634                    _("!THEN expected in macro !IF construct."));
1635       return 0;
1636     }
1637
1638   const struct macro_token *start_then = p + 1;
1639   const struct macro_token *end_then = find_ifend_clause (start_then, end);
1640   if (!end_then)
1641     {
1642       macro_error (me->stack, NULL,
1643                    _("!ELSE or !IFEND expected in macro !IF construct."));
1644       return 0;
1645     }
1646
1647   const struct macro_token *start_else, *end_if;
1648   if (lex_id_match_n (end_then->token.string, ss_cstr ("!ELSE"), 4))
1649     {
1650       start_else = end_then + 1;
1651       end_if = find_ifend_clause (start_else, end);
1652       if (!end_if
1653           || !lex_id_match_n (end_if->token.string, ss_cstr ("!IFEND"), 4))
1654         {
1655           macro_error (me->stack, end_if ? end_if : NULL,
1656                        _("!IFEND expected in macro !IF construct."));
1657           return 0;
1658         }
1659     }
1660   else
1661     {
1662       start_else = NULL;
1663       end_if = end_then;
1664     }
1665
1666   const struct macro_token *start;
1667   size_t n;
1668   if (b)
1669     {
1670       start = start_then;
1671       n = end_then - start_then;
1672     }
1673   else if (start_else)
1674     {
1675       start = start_else;
1676       n = end_if - start_else;
1677     }
1678   else
1679     {
1680       start = NULL;
1681       n = 0;
1682     }
1683
1684   if (n)
1685     {
1686       struct macro_expansion_stack stack = {
1687         .name = "!IF",
1688         .next = me->stack,
1689       };
1690       struct macro_expander subme = *me;
1691       subme.stack = &stack;
1692       macro_expand (start, n, &subme, exp);
1693     }
1694   return (end_if + 1) - tokens;
1695 }
1696
1697 static size_t
1698 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1699                  const struct macro_expander *me)
1700 {
1701   const struct macro_token *p = tokens;
1702   const struct macro_token *end = tokens + n_tokens;
1703
1704   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1705     return 0;
1706   p++;
1707
1708   if (p >= end || p->token.type != T_MACRO_ID)
1709     {
1710       macro_error (me->stack, p < end ? p : NULL,
1711                    _("Expected macro variable name following !LET."));
1712       return 0;
1713     }
1714   const struct substring var_name = p->token.string;
1715   if (is_macro_keyword (var_name)
1716       || macro_find_parameter_by_name (me->macro, var_name))
1717     {
1718       macro_error (me->stack, p < end ? p : NULL,
1719                    _("Cannot use argument name or macro keyword "
1720                      "\"%.*s\" as !LET variable."),
1721                    (int) var_name.length, var_name.string);
1722       return 0;
1723     }
1724   p++;
1725
1726   if (p >= end || p->token.type != T_EQUALS)
1727     {
1728       macro_error (me->stack, p < end ? p : NULL,
1729                    _("Expected `=' following !LET."));
1730       return 0;
1731     }
1732   p++;
1733
1734   char *value = macro_evaluate_expression (&p, end - p, me);
1735   if (!value)
1736     return 0;
1737
1738   stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name), value);
1739   return p - tokens;
1740 }
1741
1742 static const struct macro_token *
1743 find_doend (const struct macro_expansion_stack *stack,
1744             const struct macro_token *p, const struct macro_token *end)
1745 {
1746   size_t nesting = 0;
1747   for (; p < end; p++)
1748     {
1749       if (p->token.type != T_MACRO_ID)
1750         continue;
1751
1752       if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1753         nesting++;
1754       else if (lex_id_match_n (p->token.string, ss_cstr ("!DOEND"), 4))
1755         {
1756           if (!nesting)
1757             return p;
1758           nesting--;
1759         }
1760     }
1761   macro_error (stack, NULL, _("Missing !DOEND."));
1762   return NULL;
1763 }
1764
1765 static size_t
1766 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1767                  const struct macro_expander *me,
1768                  struct macro_tokens *exp)
1769 {
1770   const struct macro_token *p = tokens;
1771   const struct macro_token *end = tokens + n_tokens;
1772
1773   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1774     return 0;
1775   p++;
1776
1777   if (p >= end || p->token.type != T_MACRO_ID)
1778     {
1779       macro_error (me->stack, p < end ? p : NULL,
1780                    _("Expected macro variable name following !DO."));
1781       return 0;
1782     }
1783   const struct substring var_name = p->token.string;
1784   if (is_macro_keyword (var_name)
1785       || macro_find_parameter_by_name (me->macro, var_name))
1786     {
1787       macro_error (me->stack, p, _("Cannot use argument name or macro "
1788                                    "keyword as !DO variable."));
1789       return 0;
1790     }
1791   p++;
1792
1793   struct macro_expansion_stack substack = {
1794     .name = "!DO",
1795     .next = me->stack,
1796   };
1797   bool break_ = false;
1798   struct macro_expander subme = *me;
1799   subme.break_ = &break_;
1800   subme.stack = &substack;
1801
1802   int miterate = settings_get_miterate ();
1803   if (p < end && p->token.type == T_MACRO_ID
1804       && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1805     {
1806       p++;
1807       char *list = macro_evaluate_expression (&p, end - p, &subme);
1808       if (!list)
1809         return 0;
1810
1811       struct macro_tokens items = { .n = 0 };
1812       macro_tokens_from_string__ (&items, ss_cstr (list), me->segmenter_mode,
1813                                   me->stack);
1814       free (list);
1815
1816       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1817       if (!do_end)
1818         {
1819           macro_tokens_uninit (&items);
1820           return 0;
1821         }
1822
1823       for (size_t i = 0; i < items.n && !break_; i++)
1824         {
1825           if (i >= miterate)
1826             {
1827               macro_error (&substack, NULL,
1828                            _("!DO loop over list exceeded "
1829                              "maximum number of iterations %d.  "
1830                              "(Use SET MITERATE to change the limit.)"),
1831                            miterate);
1832               break;
1833             }
1834           stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1835                                       ss_xstrdup (items.mts[i].syntax));
1836
1837           macro_expand (p, do_end - p, &subme, exp);
1838         }
1839       macro_tokens_uninit (&items);
1840       return do_end - tokens + 1;
1841     }
1842   else if (p < end && p->token.type == T_EQUALS)
1843     {
1844       p++;
1845       double first;
1846       if (!macro_evaluate_number (&p, end - p, &subme, &first))
1847         return 0;
1848
1849       if (p >= end || p->token.type != T_MACRO_ID
1850           || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1851         {
1852           macro_error (subme.stack, p < end ? p : NULL,
1853                        _("Expected !TO in numerical !DO loop."));
1854           return 0;
1855         }
1856       p++;
1857
1858       double last;
1859       if (!macro_evaluate_number (&p, end - p, &subme, &last))
1860         return 0;
1861
1862       double by = 1.0;
1863       if (p < end && p->token.type == T_MACRO_ID
1864           && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1865         {
1866           p++;
1867           if (!macro_evaluate_number (&p, end - p, &subme, &by))
1868             return 0;
1869
1870           if (by == 0.0)
1871             {
1872               macro_error (subme.stack, NULL, _("!BY value cannot be zero."));
1873               return 0;
1874             }
1875         }
1876
1877       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1878       if (!do_end)
1879         return 0;
1880       if ((by > 0 && first <= last) || (by < 0 && first >= last))
1881         {
1882           int i = 0;
1883           for (double index = first;
1884                by > 0 ? (index <= last) : (index >= last) && !break_;
1885                index += by)
1886             {
1887               if (i++ > miterate)
1888                 {
1889                   macro_error (subme.stack, NULL,
1890                                _("Numerical !DO loop exceeded "
1891                                  "maximum number of iterations %d.  "
1892                                  "(Use SET MITERATE to change the limit.)"),
1893                                miterate);
1894                   break;
1895                 }
1896
1897               char index_s[DBL_BUFSIZE_BOUND];
1898               c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1899               stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1900                                           xstrdup (index_s));
1901
1902               macro_expand (p, do_end - p, &subme, exp);
1903             }
1904         }
1905
1906       return do_end - tokens + 1;
1907     }
1908   else
1909     {
1910       macro_error (me->stack, p < end ? p : NULL,
1911                    _("Expected `=' or !IN in !DO loop."));
1912       return 0;
1913     }
1914 }
1915
1916 static void
1917 macro_expand_arg__ (const struct macro_expander *me, size_t idx,
1918                   struct macro_tokens *exp)
1919 {
1920   const struct macro_param *param = &me->macro->params[idx];
1921   const struct macro_tokens *arg = me->args[idx];
1922
1923   if (*me->expand && param->expand_arg)
1924     {
1925       struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
1926       struct macro_expansion_stack stack = {
1927         .name = param->name,
1928         .next = me->stack,
1929       };
1930       struct macro_expander subme = {
1931         .macros = me->macros,
1932         .macro = NULL,
1933         .args = NULL,
1934         .segmenter_mode = me->segmenter_mode,
1935         .expand = me->expand,
1936         .break_ = NULL,
1937         .vars = &vars,
1938         .nesting_countdown = me->nesting_countdown,
1939         .stack = &stack,
1940       };
1941       macro_expand (arg->mts, arg->n, &subme, exp);
1942       stringi_map_destroy (&vars);
1943     }
1944   else
1945     for (size_t i = 0; i < arg->n; i++)
1946       macro_tokens_add (exp, &arg->mts[i]);
1947 }
1948
1949 static bool
1950 macro_expand_arg (const struct token *token, const struct macro_expander *me,
1951                   struct macro_tokens *exp)
1952 {
1953   if (!me || token->type != T_MACRO_ID)
1954     return false;
1955
1956   /* Macro arguments. */
1957   if (me->macro)
1958     {
1959       const struct macro_param *param = macro_find_parameter_by_name (
1960         me->macro, token->string);
1961       if (param)
1962         {
1963           macro_expand_arg__ (me, param - me->macro->params, exp);
1964           return true;
1965         }
1966       else if (ss_equals (token->string, ss_cstr ("!*")))
1967         {
1968           for (size_t j = 0; j < me->macro->n_params; j++)
1969             macro_expand_arg__ (me, j, exp);
1970           return true;
1971         }
1972     }
1973
1974   /* Variables set by !DO or !LET. */
1975   const char *var = stringi_map_find__ (me->vars, token->string.string,
1976                                         token->string.length);
1977   if (var)
1978     {
1979       macro_tokens_from_string__ (exp, ss_cstr (var),
1980                                   me->segmenter_mode, me->stack);
1981       return true;
1982     }
1983
1984   return false;
1985 }
1986
1987 static size_t
1988 macro_expand__ (const struct macro_token *mts, size_t n,
1989                 const struct macro_expander *me,
1990                 struct macro_tokens *exp)
1991 {
1992   const struct token *token = &mts[0].token;
1993
1994   /* Recursive macro calls. */
1995   if (*me->expand)
1996     {
1997       struct macro_call *submc;
1998       int n_call = macro_call_create__ (me->macros, me->stack, me,
1999                                         token, &submc);
2000       for (size_t j = 1; !n_call; j++)
2001         {
2002           const struct macro_token endcmd
2003             = { .token = { .type = T_ENDCMD } };
2004           n_call = macro_call_add (submc, j < n ? &mts[j] : &endcmd, NULL);
2005         }
2006       if (n_call > 0)
2007         {
2008           struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2009           struct macro_expansion_stack stack = {
2010             .name = submc->macro->name,
2011             .location = submc->macro->location,
2012             .next = me->stack,
2013           };
2014           struct macro_expander subme = {
2015             .macros = submc->macros,
2016             .macro = submc->macro,
2017             .args = submc->args,
2018             .segmenter_mode = me->segmenter_mode,
2019             .expand = me->expand,
2020             .break_ = NULL,
2021             .vars = &vars,
2022             .nesting_countdown = me->nesting_countdown - 1,
2023             .stack = &stack,
2024           };
2025           const struct macro_tokens *body = &submc->macro->body;
2026           macro_expand (body->mts, body->n, &subme, exp);
2027           macro_call_destroy (submc);
2028           stringi_map_destroy (&vars);
2029           return n_call;
2030         }
2031
2032       macro_call_destroy (submc);
2033     }
2034
2035   if (token->type != T_MACRO_ID)
2036     {
2037       macro_tokens_add (exp, &mts[0]);
2038       return 1;
2039     }
2040
2041   /* Parameters and macro variables. */
2042   if (macro_expand_arg (token, me, exp))
2043     return 1;
2044
2045   /* Macro functions. */
2046   struct string function_output = DS_EMPTY_INITIALIZER;
2047   size_t n_function = expand_macro_function (me, mts, n, &function_output);
2048   if (n_function)
2049     {
2050       macro_tokens_from_string__ (exp, function_output.ss,
2051                                   me->segmenter_mode, me->stack);
2052       ds_destroy (&function_output);
2053
2054       return n_function;
2055     }
2056
2057   size_t n_if = macro_expand_if (mts, n, me, exp);
2058   if (n_if > 0)
2059     return n_if;
2060
2061   size_t n_let = macro_parse_let (mts, n, me);
2062   if (n_let > 0)
2063     return n_let;
2064
2065   size_t n_do = macro_expand_do (mts, n, me, exp);
2066   if (n_do > 0)
2067     return n_do;
2068
2069   if (lex_id_match_n (token->string, ss_cstr ("!break"), 4))
2070     {
2071       if (me->break_)
2072         *me->break_ = true;
2073       else
2074         macro_error (me->stack, &mts[0], _("!BREAK outside !DO."));
2075     }
2076   else if (lex_id_match_n (token->string, ss_cstr ("!onexpand"), 4))
2077     *me->expand = true;
2078   else if (lex_id_match_n (token->string, ss_cstr ("!offexpand"), 4))
2079     *me->expand = false;
2080   else
2081     macro_tokens_add (exp, &mts[0]);
2082   return 1;
2083 }
2084
2085 static void
2086 macro_expand (const struct macro_token *mts, size_t n,
2087               const struct macro_expander *me,
2088               struct macro_tokens *exp)
2089 {
2090   if (me->nesting_countdown <= 0)
2091     {
2092       macro_error (me->stack, NULL, _("Maximum nesting level %d exceeded.  "
2093                                       "(Use SET MNEST to change the limit.)"),
2094                    settings_get_mnest ());
2095       for (size_t i = 0; i < n; i++)
2096         macro_tokens_add (exp, &mts[i]);
2097       return;
2098     }
2099
2100   for (size_t i = 0; i < n; )
2101     {
2102       if (me->break_ && *me->break_)
2103         break;
2104
2105       size_t consumed = macro_expand__ (&mts[i], n - i, me, exp);
2106       assert (consumed > 0 && i + consumed <= n);
2107       i += consumed;
2108     }
2109 }
2110
2111 void
2112 macro_call_expand (struct macro_call *mc, enum segmenter_mode segmenter_mode,
2113                    const struct msg_location *call_loc,
2114                    struct macro_tokens *exp)
2115 {
2116   assert (mc->state == MC_FINISHED);
2117
2118   bool expand = true;
2119   struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2120   struct macro_expansion_stack stack0 = {
2121     .location = call_loc,
2122   };
2123   struct macro_expansion_stack stack1 = {
2124     .next = &stack0,
2125     .name = mc->macro->name,
2126     .location = mc->macro->location,
2127   };
2128   struct macro_expander me = {
2129     .macros = mc->macros,
2130     .macro = mc->macro,
2131     .args = mc->args,
2132     .segmenter_mode = segmenter_mode,
2133     .expand = &expand,
2134     .break_ = NULL,
2135     .vars = &vars,
2136     .nesting_countdown = settings_get_mnest (),
2137     .stack = &stack1,
2138   };
2139
2140   const struct macro_tokens *body = &mc->macro->body;
2141   macro_expand (body->mts, body->n, &me, exp);
2142
2143   stringi_map_destroy (&vars);
2144 }
2145