macro: Fix memory leaks in error cases parsing function arguments.
[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     {
1139       string_array_destroy (&args);
1140       return 0;
1141     }
1142
1143   if (args.n < mf->min_args || args.n > mf->max_args)
1144     {
1145       if (mf->min_args == 1 && mf->max_args == 1)
1146         macro_error (me->stack, NULL,
1147                      _("Macro function %s takes one argument (not %zu)."),
1148                      mf->name, args.n);
1149       else if (mf->min_args == 2 && mf->max_args == 2)
1150         macro_error (me->stack, NULL,
1151                      _("Macro function %s takes two arguments (not %zu)."),
1152                      mf->name, args.n);
1153       else if (mf->min_args == 2 && mf->max_args == 3)
1154         macro_error (me->stack, NULL,
1155                      _("Macro function %s takes two or three arguments "
1156                        "(not %zu)."),
1157                      mf->name, args.n);
1158       else if (mf->min_args == 1 && mf->max_args == INT_MAX)
1159         macro_error (me->stack, NULL,
1160                      _("Macro function %s needs at least one argument."),
1161                      mf->name);
1162       else
1163         NOT_REACHED ();
1164       string_array_destroy (&args);
1165       return 0;
1166     }
1167
1168   switch (id)
1169     {
1170     case MF_LENGTH:
1171       ds_put_format (output, "%zu", strlen (args.strings[0]));
1172       break;
1173
1174     case MF_BLANKS:
1175       {
1176         int n;
1177         if (!parse_integer (args.strings[0], &n))
1178           {
1179             macro_error (me->stack, NULL,
1180                          _("Argument to !BLANKS must be non-negative integer "
1181                            "(not \"%s\")."), args.strings[0]);
1182             string_array_destroy (&args);
1183             return 0;
1184           }
1185
1186         ds_put_byte_multiple (output, ' ', n);
1187       }
1188       break;
1189
1190     case MF_CONCAT:
1191       for (size_t i = 0; i < args.n; i++)
1192         if (!unquote_string (args.strings[i], me->segmenter_mode, output))
1193           ds_put_cstr (output, args.strings[i]);
1194       break;
1195
1196     case MF_HEAD:
1197       {
1198         struct string tmp;
1199         const char *s = unquote_string_in_place (args.strings[0],
1200                                                  me->segmenter_mode, &tmp);
1201
1202         struct macro_tokens mts = { .n = 0 };
1203         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1204                                     me->stack);
1205         if (mts.n > 0)
1206           ds_put_substring (output, mts.mts[0].syntax);
1207         macro_tokens_uninit (&mts);
1208         ds_destroy (&tmp);
1209       }
1210       break;
1211
1212     case MF_INDEX:
1213       {
1214         const char *haystack = args.strings[0];
1215         const char *needle = strstr (haystack, args.strings[1]);
1216         ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1217       }
1218       break;
1219
1220     case MF_QUOTE:
1221       if (unquote_string (args.strings[0], me->segmenter_mode, NULL))
1222         ds_put_cstr (output, args.strings[0]);
1223       else
1224         {
1225           ds_extend (output, strlen (args.strings[0]) + 2);
1226           ds_put_byte (output, '\'');
1227           for (const char *p = args.strings[0]; *p; p++)
1228             {
1229               if (*p == '\'')
1230                 ds_put_byte (output, '\'');
1231               ds_put_byte (output, *p);
1232             }
1233           ds_put_byte (output, '\'');
1234         }
1235       break;
1236
1237     case MF_SUBSTR:
1238       {
1239         int start;
1240         if (!parse_integer (args.strings[1], &start) || start < 1)
1241           {
1242             macro_error (me->stack, NULL,
1243                          _("Second argument of !SUBSTR must be "
1244                            "positive integer (not \"%s\")."),
1245                          args.strings[1]);
1246             string_array_destroy (&args);
1247             return 0;
1248           }
1249
1250         int count = INT_MAX;
1251         if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1252           {
1253             macro_error (me->stack, NULL,
1254                          _("Third argument of !SUBSTR must be "
1255                            "non-negative integer (not \"%s\")."),
1256                          args.strings[2]);
1257             string_array_destroy (&args);
1258             return 0;
1259           }
1260
1261         struct substring s = ss_cstr (args.strings[0]);
1262         ds_put_substring (output, ss_substr (s, start - 1, count));
1263       }
1264       break;
1265
1266     case MF_TAIL:
1267       {
1268         struct string tmp;
1269         const char *s = unquote_string_in_place (args.strings[0],
1270                                                  me->segmenter_mode, &tmp);
1271
1272         struct macro_tokens mts = { .n = 0 };
1273         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1274                                     me->stack);
1275         if (mts.n > 1)
1276           {
1277             struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1278             macro_tokens_to_syntax (&tail, output, NULL, NULL);
1279           }
1280         macro_tokens_uninit (&mts);
1281         ds_destroy (&tmp);
1282       }
1283       break;
1284
1285     case MF_UNQUOTE:
1286       if (!unquote_string (args.strings[0], me->segmenter_mode, output))
1287         ds_put_cstr (output, args.strings[0]);
1288       break;
1289
1290     case MF_UPCASE:
1291       {
1292         struct string tmp;
1293         const char *s = unquote_string_in_place (args.strings[0],
1294                                                  me->segmenter_mode, &tmp);
1295         char *upper = utf8_to_upper (s);
1296         ds_put_cstr (output, upper);
1297         free (upper);
1298         ds_destroy (&tmp);
1299       }
1300       break;
1301
1302     case MF_EVAL:
1303       {
1304         struct macro_tokens mts = { .n = 0 };
1305         macro_tokens_from_string__ (&mts, ss_cstr (args.strings[0]),
1306                                     me->segmenter_mode, me->stack);
1307         struct macro_tokens exp = { .n = 0 };
1308         struct macro_expansion_stack stack = {
1309           .name = "!EVAL",
1310           .next = me->stack
1311         };
1312         struct macro_expander subme = *me;
1313         subme.break_ = NULL;
1314         subme.stack = &stack;
1315
1316         macro_expand (mts.mts, mts.n, &subme, &exp);
1317         macro_tokens_to_syntax (&exp, output, NULL, NULL);
1318         macro_tokens_uninit (&exp);
1319         macro_tokens_uninit (&mts);
1320       }
1321       break;
1322
1323     default:
1324       NOT_REACHED ();
1325     }
1326
1327   string_array_destroy (&args);
1328   return n_consumed;
1329 }
1330
1331 static char *macro_evaluate_or (const struct macro_expander *me,
1332                                 const struct macro_token **tokens,
1333                                 const struct macro_token *end);
1334
1335 static char *
1336 macro_evaluate_literal (const struct macro_expander *me,
1337                         const struct macro_token **tokens,
1338                         const struct macro_token *end)
1339 {
1340   const struct macro_token *p = *tokens;
1341   if (p >= end)
1342     return NULL;
1343   if (p->token.type == T_LPAREN)
1344     {
1345       p++;
1346       char *value = macro_evaluate_or (me, &p, end);
1347       if (!value)
1348         return NULL;
1349       if (p >= end || p->token.type != T_RPAREN)
1350         {
1351           free (value);
1352           macro_error (me->stack, p < end ? p : NULL,
1353                        _("Expecting ')' in macro expression."));
1354           return NULL;
1355         }
1356       p++;
1357       *tokens = p;
1358       return value;
1359     }
1360   else if (p->token.type == T_RPAREN)
1361     {
1362       macro_error (me->stack, p, _("Expecting literal or function invocation "
1363                                    "in macro expression."));
1364       return NULL;
1365     }
1366
1367   struct string function_output = DS_EMPTY_INITIALIZER;
1368   size_t function_consumed = parse_function_arg (me, p, end - p,
1369                                                  &function_output);
1370   struct string unquoted = DS_EMPTY_INITIALIZER;
1371   if (unquote_string (ds_cstr (&function_output), me->segmenter_mode,
1372                       &unquoted))
1373     {
1374       ds_swap (&function_output, &unquoted);
1375       ds_destroy (&unquoted);
1376     }
1377   *tokens = p + function_consumed;
1378   return ds_steal_cstr (&function_output);
1379 }
1380
1381 /* Returns true if MT is valid as a macro operator.  Only operators written as
1382    symbols (e.g. <>) are usable in macro expressions, not operator written as
1383    letters (e.g. EQ). */
1384 static bool
1385 is_macro_operator (const struct macro_token *mt)
1386 {
1387   return mt->syntax.length > 0 && !c_isalpha (mt->syntax.string[0]);
1388 }
1389
1390 static enum token_type
1391 parse_relational_op (const struct macro_token *mt)
1392 {
1393   switch (mt->token.type)
1394     {
1395     case T_EQUALS:
1396       return T_EQ;
1397
1398     case T_NE:
1399     case T_LT:
1400     case T_GT:
1401     case T_LE:
1402     case T_GE:
1403       return is_macro_operator (mt) ? mt->token.type : T_STOP;
1404
1405     case T_MACRO_ID:
1406       return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1407               : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1408               : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1409               : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1410               : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1411               : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1412               : T_STOP);
1413
1414     default:
1415       return T_STOP;
1416     }
1417 }
1418
1419 static char *
1420 macro_evaluate_relational (const struct macro_expander *me,
1421                            const struct macro_token **tokens,
1422                            const struct macro_token *end)
1423 {
1424   const struct macro_token *p = *tokens;
1425   char *lhs = macro_evaluate_literal (me, &p, end);
1426   if (!lhs)
1427     return NULL;
1428
1429   enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1430   if (op == T_STOP)
1431     {
1432       *tokens = p;
1433       return lhs;
1434     }
1435   p++;
1436
1437   char *rhs = macro_evaluate_literal (me, &p, end);
1438   if (!rhs)
1439     {
1440       free (lhs);
1441       return NULL;
1442     }
1443
1444   struct string lhs_tmp, rhs_tmp;
1445   int cmp = strcmp (unquote_string_in_place (lhs, me->segmenter_mode,
1446                                              &lhs_tmp),
1447                     unquote_string_in_place (rhs, me->segmenter_mode,
1448                                              &rhs_tmp));
1449   ds_destroy (&lhs_tmp);
1450   ds_destroy (&rhs_tmp);
1451
1452   free (lhs);
1453   free (rhs);
1454
1455   bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1456             : op == T_NE ? cmp
1457             : op == T_LT ? cmp < 0
1458             : op == T_GT ? cmp > 0
1459             : op == T_LE ? cmp <= 0
1460             : /* T_GE */ cmp >= 0);
1461
1462   *tokens = p;
1463   return xstrdup (b ? "1" : "0");
1464 }
1465
1466 static char *
1467 macro_evaluate_not (const struct macro_expander *me,
1468                     const struct macro_token **tokens,
1469                     const struct macro_token *end)
1470 {
1471   const struct macro_token *p = *tokens;
1472
1473   unsigned int negations = 0;
1474   while (p < end
1475          && (ss_equals_case (p->syntax, ss_cstr ("!NOT"))
1476              || ss_equals (p->syntax, ss_cstr ("~"))))
1477     {
1478       p++;
1479       negations++;
1480     }
1481
1482   char *operand = macro_evaluate_relational (me, &p, end);
1483   if (!operand || !negations)
1484     {
1485       *tokens = p;
1486       return operand;
1487     }
1488
1489   bool b = strcmp (operand, "0") ^ (negations & 1);
1490   free (operand);
1491   *tokens = p;
1492   return xstrdup (b ? "1" : "0");
1493 }
1494
1495 static char *
1496 macro_evaluate_and (const struct macro_expander *me,
1497                     const struct macro_token **tokens,
1498                     const struct macro_token *end)
1499 {
1500   const struct macro_token *p = *tokens;
1501   char *lhs = macro_evaluate_not (me, &p, end);
1502   if (!lhs)
1503     return NULL;
1504
1505   while (p < end
1506          && (ss_equals_case (p->syntax, ss_cstr ("!AND"))
1507              || ss_equals (p->syntax, ss_cstr ("&"))))
1508     {
1509       p++;
1510       char *rhs = macro_evaluate_not (me, &p, end);
1511       if (!rhs)
1512         {
1513           free (lhs);
1514           return NULL;
1515         }
1516
1517       bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1518       free (lhs);
1519       free (rhs);
1520       lhs = xstrdup (b ? "1" : "0");
1521     }
1522   *tokens = p;
1523   return lhs;
1524 }
1525
1526 static char *
1527 macro_evaluate_or (const struct macro_expander *me,
1528                    const struct macro_token **tokens,
1529                    const struct macro_token *end)
1530 {
1531   const struct macro_token *p = *tokens;
1532   char *lhs = macro_evaluate_and (me, &p, end);
1533   if (!lhs)
1534     return NULL;
1535
1536   while (p < end
1537          && (ss_equals_case (p->syntax, ss_cstr ("!OR"))
1538              || ss_equals (p->syntax, ss_cstr ("|"))))
1539     {
1540       p++;
1541       char *rhs = macro_evaluate_and (me, &p, end);
1542       if (!rhs)
1543         {
1544           free (lhs);
1545           return NULL;
1546         }
1547
1548       bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1549       free (lhs);
1550       free (rhs);
1551       lhs = xstrdup (b ? "1" : "0");
1552     }
1553   *tokens = p;
1554   return lhs;
1555 }
1556
1557 static char *
1558 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1559                            const struct macro_expander *me)
1560 {
1561   return macro_evaluate_or (me, tokens, *tokens + n_tokens);
1562 }
1563
1564 static bool
1565 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1566                        const struct macro_expander *me,
1567                        double *number)
1568 {
1569   char *s = macro_evaluate_expression (tokens, n_tokens, me);
1570   if (!s)
1571     return false;
1572
1573   struct macro_tokens mts = { .n = 0 };
1574   macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode, me->stack);
1575   if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1576     {
1577       macro_error (me->stack, mts.n > 0 ? &mts.mts[0] : NULL,
1578                    _("Macro expression must evaluate to "
1579                      "a number (not \"%s\")."), s);
1580       free (s);
1581       macro_tokens_uninit (&mts);
1582       return false;
1583     }
1584
1585   *number = token_number (&mts.mts[0].token);
1586   free (s);
1587   macro_tokens_uninit (&mts);
1588   return true;
1589 }
1590
1591 static const struct macro_token *
1592 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1593 {
1594   size_t nesting = 0;
1595   for (; p < end; p++)
1596     {
1597       if (p->token.type != T_MACRO_ID)
1598         continue;
1599
1600       if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1601         nesting++;
1602       else if (lex_id_match_n (p->token.string, ss_cstr ("!IFEND"), 4))
1603         {
1604           if (!nesting)
1605             return p;
1606           nesting--;
1607         }
1608       else if (lex_id_match_n (p->token.string, ss_cstr ("!ELSE"), 4)
1609                && !nesting)
1610         return p;
1611     }
1612   return NULL;
1613 }
1614
1615 static size_t
1616 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1617                  const struct macro_expander *me,
1618                  struct macro_tokens *exp)
1619 {
1620   const struct macro_token *p = tokens;
1621   const struct macro_token *end = tokens + n_tokens;
1622
1623   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1624     return 0;
1625
1626   p++;
1627   char *result = macro_evaluate_expression (&p, end - p, me);
1628   if (!result)
1629     return 0;
1630   bool b = strcmp (result, "0");
1631   free (result);
1632
1633   if (p >= end
1634       || p->token.type != T_MACRO_ID
1635       || !lex_id_match_n (p->token.string, ss_cstr ("!THEN"), 4))
1636     {
1637       macro_error (me->stack, p < end ? p : NULL,
1638                    _("!THEN expected in macro !IF construct."));
1639       return 0;
1640     }
1641
1642   const struct macro_token *start_then = p + 1;
1643   const struct macro_token *end_then = find_ifend_clause (start_then, end);
1644   if (!end_then)
1645     {
1646       macro_error (me->stack, NULL,
1647                    _("!ELSE or !IFEND expected in macro !IF construct."));
1648       return 0;
1649     }
1650
1651   const struct macro_token *start_else, *end_if;
1652   if (lex_id_match_n (end_then->token.string, ss_cstr ("!ELSE"), 4))
1653     {
1654       start_else = end_then + 1;
1655       end_if = find_ifend_clause (start_else, end);
1656       if (!end_if
1657           || !lex_id_match_n (end_if->token.string, ss_cstr ("!IFEND"), 4))
1658         {
1659           macro_error (me->stack, end_if ? end_if : NULL,
1660                        _("!IFEND expected in macro !IF construct."));
1661           return 0;
1662         }
1663     }
1664   else
1665     {
1666       start_else = NULL;
1667       end_if = end_then;
1668     }
1669
1670   const struct macro_token *start;
1671   size_t n;
1672   if (b)
1673     {
1674       start = start_then;
1675       n = end_then - start_then;
1676     }
1677   else if (start_else)
1678     {
1679       start = start_else;
1680       n = end_if - start_else;
1681     }
1682   else
1683     {
1684       start = NULL;
1685       n = 0;
1686     }
1687
1688   if (n)
1689     {
1690       struct macro_expansion_stack stack = {
1691         .name = "!IF",
1692         .next = me->stack,
1693       };
1694       struct macro_expander subme = *me;
1695       subme.stack = &stack;
1696       macro_expand (start, n, &subme, exp);
1697     }
1698   return (end_if + 1) - tokens;
1699 }
1700
1701 static size_t
1702 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1703                  const struct macro_expander *me)
1704 {
1705   const struct macro_token *p = tokens;
1706   const struct macro_token *end = tokens + n_tokens;
1707
1708   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1709     return 0;
1710   p++;
1711
1712   if (p >= end || p->token.type != T_MACRO_ID)
1713     {
1714       macro_error (me->stack, p < end ? p : NULL,
1715                    _("Expected macro variable name following !LET."));
1716       return 0;
1717     }
1718   const struct substring var_name = p->token.string;
1719   if (is_macro_keyword (var_name)
1720       || macro_find_parameter_by_name (me->macro, var_name))
1721     {
1722       macro_error (me->stack, p < end ? p : NULL,
1723                    _("Cannot use argument name or macro keyword "
1724                      "\"%.*s\" as !LET variable."),
1725                    (int) var_name.length, var_name.string);
1726       return 0;
1727     }
1728   p++;
1729
1730   if (p >= end || p->token.type != T_EQUALS)
1731     {
1732       macro_error (me->stack, p < end ? p : NULL,
1733                    _("Expected `=' following !LET."));
1734       return 0;
1735     }
1736   p++;
1737
1738   char *value = macro_evaluate_expression (&p, end - p, me);
1739   if (!value)
1740     return 0;
1741
1742   stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name), value);
1743   return p - tokens;
1744 }
1745
1746 static const struct macro_token *
1747 find_doend (const struct macro_expansion_stack *stack,
1748             const struct macro_token *p, const struct macro_token *end)
1749 {
1750   size_t nesting = 0;
1751   for (; p < end; p++)
1752     {
1753       if (p->token.type != T_MACRO_ID)
1754         continue;
1755
1756       if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1757         nesting++;
1758       else if (lex_id_match_n (p->token.string, ss_cstr ("!DOEND"), 4))
1759         {
1760           if (!nesting)
1761             return p;
1762           nesting--;
1763         }
1764     }
1765   macro_error (stack, NULL, _("Missing !DOEND."));
1766   return NULL;
1767 }
1768
1769 static size_t
1770 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1771                  const struct macro_expander *me,
1772                  struct macro_tokens *exp)
1773 {
1774   const struct macro_token *p = tokens;
1775   const struct macro_token *end = tokens + n_tokens;
1776
1777   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1778     return 0;
1779   p++;
1780
1781   if (p >= end || p->token.type != T_MACRO_ID)
1782     {
1783       macro_error (me->stack, p < end ? p : NULL,
1784                    _("Expected macro variable name following !DO."));
1785       return 0;
1786     }
1787   const struct substring var_name = p->token.string;
1788   if (is_macro_keyword (var_name)
1789       || macro_find_parameter_by_name (me->macro, var_name))
1790     {
1791       macro_error (me->stack, p, _("Cannot use argument name or macro "
1792                                    "keyword as !DO variable."));
1793       return 0;
1794     }
1795   p++;
1796
1797   struct macro_expansion_stack substack = {
1798     .name = "!DO",
1799     .next = me->stack,
1800   };
1801   bool break_ = false;
1802   struct macro_expander subme = *me;
1803   subme.break_ = &break_;
1804   subme.stack = &substack;
1805
1806   int miterate = settings_get_miterate ();
1807   if (p < end && p->token.type == T_MACRO_ID
1808       && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1809     {
1810       p++;
1811       char *list = macro_evaluate_expression (&p, end - p, &subme);
1812       if (!list)
1813         return 0;
1814
1815       struct macro_tokens items = { .n = 0 };
1816       macro_tokens_from_string__ (&items, ss_cstr (list), me->segmenter_mode,
1817                                   me->stack);
1818       free (list);
1819
1820       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1821       if (!do_end)
1822         {
1823           macro_tokens_uninit (&items);
1824           return 0;
1825         }
1826
1827       for (size_t i = 0; i < items.n && !break_; i++)
1828         {
1829           if (i >= miterate)
1830             {
1831               macro_error (&substack, NULL,
1832                            _("!DO loop over list exceeded "
1833                              "maximum number of iterations %d.  "
1834                              "(Use SET MITERATE to change the limit.)"),
1835                            miterate);
1836               break;
1837             }
1838           stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1839                                       ss_xstrdup (items.mts[i].syntax));
1840
1841           macro_expand (p, do_end - p, &subme, exp);
1842         }
1843       macro_tokens_uninit (&items);
1844       return do_end - tokens + 1;
1845     }
1846   else if (p < end && p->token.type == T_EQUALS)
1847     {
1848       p++;
1849       double first;
1850       if (!macro_evaluate_number (&p, end - p, &subme, &first))
1851         return 0;
1852
1853       if (p >= end || p->token.type != T_MACRO_ID
1854           || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1855         {
1856           macro_error (subme.stack, p < end ? p : NULL,
1857                        _("Expected !TO in numerical !DO loop."));
1858           return 0;
1859         }
1860       p++;
1861
1862       double last;
1863       if (!macro_evaluate_number (&p, end - p, &subme, &last))
1864         return 0;
1865
1866       double by = 1.0;
1867       if (p < end && p->token.type == T_MACRO_ID
1868           && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1869         {
1870           p++;
1871           if (!macro_evaluate_number (&p, end - p, &subme, &by))
1872             return 0;
1873
1874           if (by == 0.0)
1875             {
1876               macro_error (subme.stack, NULL, _("!BY value cannot be zero."));
1877               return 0;
1878             }
1879         }
1880
1881       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1882       if (!do_end)
1883         return 0;
1884       if ((by > 0 && first <= last) || (by < 0 && first >= last))
1885         {
1886           int i = 0;
1887           for (double index = first;
1888                by > 0 ? (index <= last) : (index >= last) && !break_;
1889                index += by)
1890             {
1891               if (i++ > miterate)
1892                 {
1893                   macro_error (subme.stack, NULL,
1894                                _("Numerical !DO loop exceeded "
1895                                  "maximum number of iterations %d.  "
1896                                  "(Use SET MITERATE to change the limit.)"),
1897                                miterate);
1898                   break;
1899                 }
1900
1901               char index_s[DBL_BUFSIZE_BOUND];
1902               c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1903               stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1904                                           xstrdup (index_s));
1905
1906               macro_expand (p, do_end - p, &subme, exp);
1907             }
1908         }
1909
1910       return do_end - tokens + 1;
1911     }
1912   else
1913     {
1914       macro_error (me->stack, p < end ? p : NULL,
1915                    _("Expected `=' or !IN in !DO loop."));
1916       return 0;
1917     }
1918 }
1919
1920 static void
1921 macro_expand_arg__ (const struct macro_expander *me, size_t idx,
1922                   struct macro_tokens *exp)
1923 {
1924   const struct macro_param *param = &me->macro->params[idx];
1925   const struct macro_tokens *arg = me->args[idx];
1926
1927   if (*me->expand && param->expand_arg)
1928     {
1929       struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
1930       struct macro_expansion_stack stack = {
1931         .name = param->name,
1932         .next = me->stack,
1933       };
1934       struct macro_expander subme = {
1935         .macros = me->macros,
1936         .macro = NULL,
1937         .args = NULL,
1938         .segmenter_mode = me->segmenter_mode,
1939         .expand = me->expand,
1940         .break_ = NULL,
1941         .vars = &vars,
1942         .nesting_countdown = me->nesting_countdown,
1943         .stack = &stack,
1944       };
1945       macro_expand (arg->mts, arg->n, &subme, exp);
1946       stringi_map_destroy (&vars);
1947     }
1948   else
1949     for (size_t i = 0; i < arg->n; i++)
1950       macro_tokens_add (exp, &arg->mts[i]);
1951 }
1952
1953 static bool
1954 macro_expand_arg (const struct token *token, const struct macro_expander *me,
1955                   struct macro_tokens *exp)
1956 {
1957   if (!me || token->type != T_MACRO_ID)
1958     return false;
1959
1960   /* Macro arguments. */
1961   if (me->macro)
1962     {
1963       const struct macro_param *param = macro_find_parameter_by_name (
1964         me->macro, token->string);
1965       if (param)
1966         {
1967           macro_expand_arg__ (me, param - me->macro->params, exp);
1968           return true;
1969         }
1970       else if (ss_equals (token->string, ss_cstr ("!*")))
1971         {
1972           for (size_t j = 0; j < me->macro->n_params; j++)
1973             macro_expand_arg__ (me, j, exp);
1974           return true;
1975         }
1976     }
1977
1978   /* Variables set by !DO or !LET. */
1979   const char *var = stringi_map_find__ (me->vars, token->string.string,
1980                                         token->string.length);
1981   if (var)
1982     {
1983       macro_tokens_from_string__ (exp, ss_cstr (var),
1984                                   me->segmenter_mode, me->stack);
1985       return true;
1986     }
1987
1988   return false;
1989 }
1990
1991 static size_t
1992 macro_expand__ (const struct macro_token *mts, size_t n,
1993                 const struct macro_expander *me,
1994                 struct macro_tokens *exp)
1995 {
1996   const struct token *token = &mts[0].token;
1997
1998   /* Recursive macro calls. */
1999   if (*me->expand)
2000     {
2001       struct macro_call *submc;
2002       int n_call = macro_call_create__ (me->macros, me->stack, me,
2003                                         token, &submc);
2004       for (size_t j = 1; !n_call; j++)
2005         {
2006           const struct macro_token endcmd
2007             = { .token = { .type = T_ENDCMD } };
2008           n_call = macro_call_add (submc, j < n ? &mts[j] : &endcmd, NULL);
2009         }
2010       if (n_call > 0)
2011         {
2012           struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2013           struct macro_expansion_stack stack = {
2014             .name = submc->macro->name,
2015             .location = submc->macro->location,
2016             .next = me->stack,
2017           };
2018           struct macro_expander subme = {
2019             .macros = submc->macros,
2020             .macro = submc->macro,
2021             .args = submc->args,
2022             .segmenter_mode = me->segmenter_mode,
2023             .expand = me->expand,
2024             .break_ = NULL,
2025             .vars = &vars,
2026             .nesting_countdown = me->nesting_countdown - 1,
2027             .stack = &stack,
2028           };
2029           const struct macro_tokens *body = &submc->macro->body;
2030           macro_expand (body->mts, body->n, &subme, exp);
2031           macro_call_destroy (submc);
2032           stringi_map_destroy (&vars);
2033           return n_call;
2034         }
2035
2036       macro_call_destroy (submc);
2037     }
2038
2039   if (token->type != T_MACRO_ID)
2040     {
2041       macro_tokens_add (exp, &mts[0]);
2042       return 1;
2043     }
2044
2045   /* Parameters and macro variables. */
2046   if (macro_expand_arg (token, me, exp))
2047     return 1;
2048
2049   /* Macro functions. */
2050   struct string function_output = DS_EMPTY_INITIALIZER;
2051   size_t n_function = expand_macro_function (me, mts, n, &function_output);
2052   if (n_function)
2053     {
2054       macro_tokens_from_string__ (exp, function_output.ss,
2055                                   me->segmenter_mode, me->stack);
2056       ds_destroy (&function_output);
2057
2058       return n_function;
2059     }
2060
2061   size_t n_if = macro_expand_if (mts, n, me, exp);
2062   if (n_if > 0)
2063     return n_if;
2064
2065   size_t n_let = macro_parse_let (mts, n, me);
2066   if (n_let > 0)
2067     return n_let;
2068
2069   size_t n_do = macro_expand_do (mts, n, me, exp);
2070   if (n_do > 0)
2071     return n_do;
2072
2073   if (lex_id_match_n (token->string, ss_cstr ("!break"), 4))
2074     {
2075       if (me->break_)
2076         *me->break_ = true;
2077       else
2078         macro_error (me->stack, &mts[0], _("!BREAK outside !DO."));
2079     }
2080   else if (lex_id_match_n (token->string, ss_cstr ("!onexpand"), 4))
2081     *me->expand = true;
2082   else if (lex_id_match_n (token->string, ss_cstr ("!offexpand"), 4))
2083     *me->expand = false;
2084   else
2085     macro_tokens_add (exp, &mts[0]);
2086   return 1;
2087 }
2088
2089 static void
2090 macro_expand (const struct macro_token *mts, size_t n,
2091               const struct macro_expander *me,
2092               struct macro_tokens *exp)
2093 {
2094   if (me->nesting_countdown <= 0)
2095     {
2096       macro_error (me->stack, NULL, _("Maximum nesting level %d exceeded.  "
2097                                       "(Use SET MNEST to change the limit.)"),
2098                    settings_get_mnest ());
2099       for (size_t i = 0; i < n; i++)
2100         macro_tokens_add (exp, &mts[i]);
2101       return;
2102     }
2103
2104   for (size_t i = 0; i < n; )
2105     {
2106       if (me->break_ && *me->break_)
2107         break;
2108
2109       size_t consumed = macro_expand__ (&mts[i], n - i, me, exp);
2110       assert (consumed > 0 && i + consumed <= n);
2111       i += consumed;
2112     }
2113 }
2114
2115 void
2116 macro_call_expand (struct macro_call *mc, enum segmenter_mode segmenter_mode,
2117                    const struct msg_location *call_loc,
2118                    struct macro_tokens *exp)
2119 {
2120   assert (mc->state == MC_FINISHED);
2121
2122   bool expand = true;
2123   struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2124   struct macro_expansion_stack stack0 = {
2125     .location = call_loc,
2126   };
2127   struct macro_expansion_stack stack1 = {
2128     .next = &stack0,
2129     .name = mc->macro->name,
2130     .location = mc->macro->location,
2131   };
2132   struct macro_expander me = {
2133     .macros = mc->macros,
2134     .macro = mc->macro,
2135     .args = mc->args,
2136     .segmenter_mode = segmenter_mode,
2137     .expand = &expand,
2138     .break_ = NULL,
2139     .vars = &vars,
2140     .nesting_countdown = settings_get_mnest (),
2141     .stack = &stack1,
2142   };
2143
2144   const struct macro_tokens *body = &mc->macro->body;
2145   macro_expand (body->mts, body->n, &me, exp);
2146
2147   stringi_map_destroy (&vars);
2148 }
2149