macro: Fix crash for !QUOTE of a quoted string.
[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       *argp = xzalloc (sizeof **argp);
711       mc->state = MC_ARG;
712       return 0;
713     }
714   else if (p->positional && (token->type == T_ENDCMD || token->type == T_STOP))
715     return mc_finished (mc);
716   else
717     return mc_expected (mc, mt, loc, &p->start);
718 }
719
720 static const struct macro_param *
721 macro_find_parameter_by_name (const struct macro *m, struct substring name)
722 {
723   if (!m)
724     return NULL;
725
726   ss_ltrim (&name, ss_cstr ("!"));
727
728   for (size_t i = 0; i < m->n_params; i++)
729     {
730       const struct macro_param *p = &m->params[i];
731       struct substring p_name = ss_cstr (p->name + 1);
732       if (!utf8_strncasecmp (p_name.string, p_name.length,
733                              name.string, name.length))
734         return p;
735     }
736   return NULL;
737 }
738
739 static int
740 mc_keyword (struct macro_call *mc, const struct macro_token *mt,
741             const struct msg_location *loc)
742 {
743   const struct token *token = &mt->token;
744   if (token->type != T_ID)
745     return mc_finished (mc);
746
747   const struct macro_param *p = macro_find_parameter_by_name (mc->macro,
748                                                               token->string);
749   if (p)
750     {
751       struct macro_tokens **argp = &mc->args[p - mc->macro->params];
752       if (*argp)
753         mc_error (mc, loc,
754                   _("Argument %s multiply specified in call to macro %s."),
755                   p->name, mc->macro->name);
756
757       *argp = xzalloc (sizeof **argp);
758       mc->param = p;
759       mc->n_tokens++;
760       mc->state = MC_EQUALS;
761       return 0;
762     }
763
764   return mc_finished (mc);
765 }
766
767 static int
768 mc_equals (struct macro_call *mc, const struct macro_token *mt,
769            const struct msg_location *loc)
770 {
771   if (mt->token.type == T_EQUALS)
772     {
773       mc->n_tokens++;
774       mc->state = mc->param->arg_type == ARG_ENCLOSE ? MC_ENCLOSE : MC_ARG;
775       return 0;
776     }
777
778   return mc_expected (mc, mt, loc, &(struct token) { .type = T_EQUALS });
779 }
780
781 static int
782 macro_call_create__ (const struct macro_set *macros,
783                      const struct macro_expansion_stack *stack,
784                      const struct macro_expander *me,
785                      const struct token *token,
786                      struct macro_call **mcp)
787 {
788   const struct macro *macro = (token->type == T_ID || token->type == T_MACRO_ID
789                                ? macro_set_find (macros, token->string.string)
790                                : NULL);
791   if (!macro)
792     {
793       *mcp = NULL;
794       return -1;
795     }
796
797   struct macro_call *mc = xmalloc (sizeof *mc);
798   *mc = (struct macro_call) {
799     .macros = macros,
800     .macro = macro,
801     .n_tokens = 1,
802     .state = (!macro->n_params ? MC_FINISHED
803               : !macro->params[0].positional ? MC_KEYWORD
804               : macro->params[0].arg_type == ARG_ENCLOSE ? MC_ENCLOSE
805               : MC_ARG),
806     .args = macro->n_params ? xcalloc (macro->n_params, sizeof *mc->args) : NULL,
807     .param = macro->params,
808     .stack = stack,
809     .me = me,
810   };
811   *mcp = mc;
812
813   return mc->state == MC_FINISHED ? 1 : 0;
814 }
815
816 /* If TOKEN is the first token of a call to a macro in MACROS, create a new
817    macro expander, initializes *MCP to it.  Returns 0 if more tokens are needed
818    and should be added via macro_call_add() or 1 if the caller should next call
819    macro_call_get_expansion().
820
821    If TOKEN is not the first token of a macro call, returns -1 and sets *MCP to
822    NULL. */
823 int
824 macro_call_create (const struct macro_set *macros,
825                    const struct token *token,
826                    struct macro_call **mcp)
827 {
828   return macro_call_create__ (macros, NULL, NULL, token, mcp);
829 }
830
831 void
832 macro_call_destroy (struct macro_call *mc)
833 {
834   if (!mc)
835     return;
836
837   for (size_t i = 0; i < mc->macro->n_params; i++)
838     {
839       struct macro_tokens *a = mc->args[i];
840       if (a && a != &mc->macro->params[i].def)
841         {
842           macro_tokens_uninit (a);
843           free (a);
844         }
845     }
846   free (mc->args);
847   free (mc);
848 }
849
850 /* Adds TOKEN to the collection of tokens in MC that potentially need to be
851    macro expanded.
852
853    Returns -1 if the tokens added do not actually invoke a macro.  The caller
854    should consume the first token without expanding it.  (Later tokens might
855    invoke a macro so it's best to feed the second token into a new expander.)
856
857    Returns 0 if the macro expander needs more tokens, for macro arguments or to
858    decide whether this is actually a macro invocation.  The caller should call
859    macro_call_add() again with the next token.
860
861    Returns a positive number to indicate that the returned number of tokens
862    invoke a macro.  The number returned might be less than the number of tokens
863    added because it can take a few tokens of lookahead to determine whether the
864    macro invocation is finished.  The caller should call
865    macro_call_get_expansion() to obtain the expansion. */
866 int
867 macro_call_add (struct macro_call *mc, const struct macro_token *mt,
868                 const struct msg_location *loc)
869 {
870   switch (mc->state)
871     {
872     case MC_ARG:
873       return mc_add_arg (mc, mt, loc);
874
875     case MC_ENCLOSE:
876       return mc_enclose (mc, mt, loc);
877
878     case MC_KEYWORD:
879       return mc_keyword (mc, mt, loc);
880
881     case MC_EQUALS:
882       return mc_equals (mc, mt, loc);
883
884     default:
885       NOT_REACHED ();
886     }
887 }
888 \f
889 /* Macro expansion. */
890
891 struct macro_expander
892   {
893     /* Always available. */
894     const struct macro_set *macros;     /* Macros to expand recursively. */
895     enum segmenter_mode segmenter_mode; /* Mode for tokenization. */
896     int nesting_countdown;              /* Remaining nesting levels. */
897     const struct macro_expansion_stack *stack; /* Stack for error reporting. */
898     bool *expand;                       /* May macro calls be expanded? */
899     struct stringi_map *vars;           /* Variables from !do and !let. */
900
901     /* Only nonnull if inside a !DO loop. */
902     bool *break_;                       /* Set to true to break out of loop. */
903
904     /* Only nonnull if expanding a macro (and not, say, a macro argument). */
905     const struct macro *macro;
906     struct macro_tokens **args;
907   };
908
909 static void
910 macro_expand (const struct macro_token *mts, size_t n_mts,
911               const struct macro_expander *, struct macro_tokens *);
912
913 static size_t
914 expand_macro_function (const struct macro_expander *me,
915                        const struct macro_token *input, size_t n_input,
916                        struct string *output);
917
918 /* Parses one function argument from the N_INPUT tokens in INPUT
919    Each argument to a macro function is one of:
920
921        - A quoted string or other single literal token.
922
923        - An argument to the macro being expanded, e.g. !1 or a named argument.
924
925        - !*.
926
927        - A function invocation.
928
929    Each function invocation yields a character sequence to be turned into a
930    sequence of tokens.  The case where that character sequence is a single
931    quoted string is an important special case.
932 */
933 static size_t
934 parse_function_arg (const struct macro_expander *me,
935                     const struct macro_token *input, size_t n_input,
936                     struct string *farg)
937 {
938   assert (n_input > 0);
939
940   const struct token *token = &input[0].token;
941   if (token->type == T_MACRO_ID && me->macro)
942     {
943       const struct macro_param *param = macro_find_parameter_by_name (
944         me->macro, token->string);
945       if (param)
946         {
947           size_t param_idx = param - me->macro->params;
948           macro_tokens_to_syntax (me->args[param_idx], farg, NULL, NULL);
949           return 1;
950         }
951
952       if (ss_equals (token->string, ss_cstr ("!*")))
953         {
954           for (size_t i = 0; i < me->macro->n_params; i++)
955             {
956               if (!me->macro->params[i].positional)
957                 break;
958               if (i)
959                 ds_put_byte (farg, ' ');
960               macro_tokens_to_syntax (me->args[i], farg, NULL, NULL);
961             }
962           return 1;
963         }
964
965       const char *var = stringi_map_find__ (me->vars,
966                                             token->string.string,
967                                             token->string.length);
968       if (var)
969         {
970           ds_put_cstr (farg, var);
971           return 1;
972         }
973
974       size_t n_function = expand_macro_function (me, input, n_input, farg);
975       if (n_function)
976         return n_function;
977     }
978
979   ds_put_substring (farg, input[0].syntax);
980   return 1;
981 }
982
983 static size_t
984 parse_function_args (const struct macro_expander *me,
985                      const struct macro_token *mts, size_t n,
986                      const char *function,
987                      struct string_array *args)
988 {
989   assert (n >= 2 && mts[1].token.type == T_LPAREN);
990
991   for (size_t i = 2; i < n; )
992     {
993       if (mts[i].token.type == T_RPAREN)
994         return i + 1;
995
996       struct string s = DS_EMPTY_INITIALIZER;
997       i += parse_function_arg (me, mts + i, n - i, &s);
998       string_array_append_nocopy (args, ds_steal_cstr (&s));
999
1000       if (i >= n)
1001         break;
1002       else if (mts[i].token.type == T_COMMA)
1003         i++;
1004       else if (mts[i].token.type != T_RPAREN)
1005         {
1006           macro_error (me->stack, &mts[i],
1007                        _("`,' or `)' expected in call to macro function %s."),
1008                        function);
1009           return 0;
1010         }
1011     }
1012
1013   macro_error (me->stack, NULL, _("Missing `)' in call to macro function %s."),
1014                function);
1015   return 0;
1016 }
1017
1018 static bool
1019 unquote_string (const char *s, enum segmenter_mode segmenter_mode,
1020                 struct string *content)
1021 {
1022   struct string_lexer slex;
1023   string_lexer_init (&slex, s, strlen (s), segmenter_mode, true);
1024
1025   struct token token1;
1026   if (string_lexer_next (&slex, &token1) != SLR_TOKEN
1027       || token1.type != T_STRING)
1028     {
1029       token_uninit (&token1);
1030       return false;
1031     }
1032
1033   struct token token2;
1034   if (string_lexer_next (&slex, &token2) != SLR_END)
1035     {
1036       token_uninit (&token1);
1037       token_uninit (&token2);
1038       return false;
1039     }
1040
1041   if (content)
1042     ds_put_substring (content, token1.string);
1043   token_uninit (&token1);
1044   return true;
1045 }
1046
1047 static const char *
1048 unquote_string_in_place (const char *s, enum segmenter_mode segmenter_mode,
1049                          struct string *tmp)
1050 {
1051   ds_init_empty (tmp);
1052   return unquote_string (s, segmenter_mode, tmp) ? ds_cstr (tmp) : s;
1053 }
1054
1055 static bool
1056 parse_integer (const char *s, int *np)
1057 {
1058   errno = 0;
1059
1060   char *tail;
1061   long int n = strtol (s, &tail, 10);
1062   *np = n < INT_MIN ? INT_MIN : n > INT_MAX ? INT_MAX : n;
1063   tail += strspn (tail, CC_SPACES);
1064   return *tail == '\0' && errno != ERANGE && n == *np;
1065 }
1066
1067 static size_t
1068 expand_macro_function (const struct macro_expander *me,
1069                        const struct macro_token *input, size_t n_input,
1070                        struct string *output)
1071 {
1072   if (!n_input || input[0].token.type != T_MACRO_ID)
1073     return 0;
1074
1075   struct macro_function
1076     {
1077       const char *name;
1078       int min_args;
1079       int max_args;
1080     };
1081   enum macro_function_id
1082     {
1083       MF_BLANKS,
1084       MF_CONCAT,
1085       MF_EVAL,
1086       MF_HEAD,
1087       MF_INDEX,
1088       MF_LENGTH,
1089       MF_QUOTE,
1090       MF_SUBSTR,
1091       MF_TAIL,
1092       MF_UNQUOTE,
1093       MF_UPCASE,
1094     };
1095   static const struct macro_function mfs[] = {
1096     [MF_BLANKS]  = { "!BLANKS",  1, 1 },
1097     [MF_CONCAT]  = { "!CONCAT",  1, INT_MAX },
1098     [MF_EVAL]    = { "!EVAL",    1, 1 },
1099     [MF_HEAD]    = { "!HEAD",    1, 1 },
1100     [MF_INDEX]   = { "!INDEX",   2, 2 },
1101     [MF_LENGTH]  = { "!LENGTH",  1, 1 },
1102     [MF_QUOTE]   = { "!QUOTE",   1, 1 },
1103     [MF_SUBSTR]  = { "!SUBSTR",  2, 3 },
1104     [MF_TAIL]    = { "!TAIL",    1, 1 },
1105     [MF_UNQUOTE] = { "!UNQUOTE", 1, 1 },
1106     [MF_UPCASE]  = { "!UPCASE",  1, 1 },
1107   };
1108
1109   if (lex_id_match_n (ss_cstr ("!NULL"), input[0].token.string, 4))
1110     return 1;
1111
1112   if (n_input < 2 || input[1].token.type != T_LPAREN)
1113     {
1114       /* Only consider macro functions when the name is followed by '('. */
1115       return 0;
1116     }
1117
1118   /* Is this a macro function name? */
1119   const struct macro_function *mf;
1120   for (mf = mfs; ; mf++)
1121     {
1122       if (mf >= mfs + sizeof mfs / sizeof *mfs)
1123         {
1124           /* Not a macro function. */
1125           return 0;
1126         }
1127
1128       if (lex_id_match_n (ss_cstr (mf->name), input[0].token.string, 4))
1129         break;
1130     }
1131
1132   enum macro_function_id id = mf - mfs;
1133
1134   struct string_array args = STRING_ARRAY_INITIALIZER;
1135   size_t n_consumed = parse_function_args (me, input, n_input, mf->name, &args);
1136   if (!n_consumed)
1137     return 0;
1138
1139   if (args.n < mf->min_args || args.n > mf->max_args)
1140     {
1141       if (mf->min_args == 1 && mf->max_args == 1)
1142         macro_error (me->stack, NULL,
1143                      _("Macro function %s takes one argument (not %zu)."),
1144                      mf->name, args.n);
1145       else if (mf->min_args == 2 && mf->max_args == 2)
1146         macro_error (me->stack, NULL,
1147                      _("Macro function %s takes two arguments (not %zu)."),
1148                      mf->name, args.n);
1149       else if (mf->min_args == 2 && mf->max_args == 3)
1150         macro_error (me->stack, NULL,
1151                      _("Macro function %s takes two or three arguments "
1152                        "(not %zu)."),
1153                      mf->name, args.n);
1154       else if (mf->min_args == 1 && mf->max_args == INT_MAX)
1155         macro_error (me->stack, NULL,
1156                      _("Macro function %s needs at least one argument."),
1157                      mf->name);
1158       else
1159         NOT_REACHED ();
1160       return 0;
1161     }
1162
1163   switch (id)
1164     {
1165     case MF_LENGTH:
1166       ds_put_format (output, "%zu", strlen (args.strings[0]));
1167       break;
1168
1169     case MF_BLANKS:
1170       {
1171         int n;
1172         if (!parse_integer (args.strings[0], &n))
1173           {
1174             macro_error (me->stack, NULL,
1175                          _("Argument to !BLANKS must be non-negative integer "
1176                            "(not \"%s\")."), args.strings[0]);
1177             string_array_destroy (&args);
1178             return 0;
1179           }
1180
1181         ds_put_byte_multiple (output, ' ', n);
1182       }
1183       break;
1184
1185     case MF_CONCAT:
1186       for (size_t i = 0; i < args.n; i++)
1187         if (!unquote_string (args.strings[i], me->segmenter_mode, output))
1188           ds_put_cstr (output, args.strings[i]);
1189       break;
1190
1191     case MF_HEAD:
1192       {
1193         struct string tmp;
1194         const char *s = unquote_string_in_place (args.strings[0],
1195                                                  me->segmenter_mode, &tmp);
1196
1197         struct macro_tokens mts = { .n = 0 };
1198         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1199                                     me->stack);
1200         if (mts.n > 0)
1201           ds_put_substring (output, mts.mts[0].syntax);
1202         macro_tokens_uninit (&mts);
1203         ds_destroy (&tmp);
1204       }
1205       break;
1206
1207     case MF_INDEX:
1208       {
1209         const char *haystack = args.strings[0];
1210         const char *needle = strstr (haystack, args.strings[1]);
1211         ds_put_format (output, "%zu", needle ? needle - haystack + 1 : 0);
1212       }
1213       break;
1214
1215     case MF_QUOTE:
1216       if (unquote_string (args.strings[0], me->segmenter_mode, NULL))
1217         ds_put_cstr (output, args.strings[0]);
1218       else
1219         {
1220           ds_extend (output, strlen (args.strings[0]) + 2);
1221           ds_put_byte (output, '\'');
1222           for (const char *p = args.strings[0]; *p; p++)
1223             {
1224               if (*p == '\'')
1225                 ds_put_byte (output, '\'');
1226               ds_put_byte (output, *p);
1227             }
1228           ds_put_byte (output, '\'');
1229         }
1230       break;
1231
1232     case MF_SUBSTR:
1233       {
1234         int start;
1235         if (!parse_integer (args.strings[1], &start) || start < 1)
1236           {
1237             macro_error (me->stack, NULL,
1238                          _("Second argument of !SUBSTR must be "
1239                            "positive integer (not \"%s\")."),
1240                          args.strings[1]);
1241             string_array_destroy (&args);
1242             return 0;
1243           }
1244
1245         int count = INT_MAX;
1246         if (args.n > 2 && (!parse_integer (args.strings[2], &count) || count < 0))
1247           {
1248             macro_error (me->stack, NULL,
1249                          _("Third argument of !SUBSTR must be "
1250                            "non-negative integer (not \"%s\")."),
1251                          args.strings[2]);
1252             string_array_destroy (&args);
1253             return 0;
1254           }
1255
1256         struct substring s = ss_cstr (args.strings[0]);
1257         ds_put_substring (output, ss_substr (s, start - 1, count));
1258       }
1259       break;
1260
1261     case MF_TAIL:
1262       {
1263         struct string tmp;
1264         const char *s = unquote_string_in_place (args.strings[0],
1265                                                  me->segmenter_mode, &tmp);
1266
1267         struct macro_tokens mts = { .n = 0 };
1268         macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode,
1269                                     me->stack);
1270         if (mts.n > 1)
1271           {
1272             struct macro_tokens tail = { .mts = mts.mts + 1, .n = mts.n - 1 };
1273             macro_tokens_to_syntax (&tail, output, NULL, NULL);
1274           }
1275         macro_tokens_uninit (&mts);
1276         ds_destroy (&tmp);
1277       }
1278       break;
1279
1280     case MF_UNQUOTE:
1281       if (!unquote_string (args.strings[0], me->segmenter_mode, output))
1282         ds_put_cstr (output, args.strings[0]);
1283       break;
1284
1285     case MF_UPCASE:
1286       {
1287         struct string tmp;
1288         const char *s = unquote_string_in_place (args.strings[0],
1289                                                  me->segmenter_mode, &tmp);
1290         char *upper = utf8_to_upper (s);
1291         ds_put_cstr (output, upper);
1292         free (upper);
1293         ds_destroy (&tmp);
1294       }
1295       break;
1296
1297     case MF_EVAL:
1298       {
1299         struct macro_tokens mts = { .n = 0 };
1300         macro_tokens_from_string__ (&mts, ss_cstr (args.strings[0]),
1301                                     me->segmenter_mode, me->stack);
1302         struct macro_tokens exp = { .n = 0 };
1303         struct macro_expansion_stack stack = {
1304           .name = "!EVAL",
1305           .next = me->stack
1306         };
1307         struct macro_expander subme = *me;
1308         subme.break_ = NULL;
1309         subme.stack = &stack;
1310
1311         macro_expand (mts.mts, mts.n, &subme, &exp);
1312         macro_tokens_to_syntax (&exp, output, NULL, NULL);
1313         macro_tokens_uninit (&exp);
1314         macro_tokens_uninit (&mts);
1315       }
1316       break;
1317
1318     default:
1319       NOT_REACHED ();
1320     }
1321
1322   string_array_destroy (&args);
1323   return n_consumed;
1324 }
1325
1326 static char *macro_evaluate_or (const struct macro_expander *me,
1327                                 const struct macro_token **tokens,
1328                                 const struct macro_token *end);
1329
1330 static char *
1331 macro_evaluate_literal (const struct macro_expander *me,
1332                         const struct macro_token **tokens,
1333                         const struct macro_token *end)
1334 {
1335   const struct macro_token *p = *tokens;
1336   if (p >= end)
1337     return NULL;
1338   if (p->token.type == T_LPAREN)
1339     {
1340       p++;
1341       char *value = macro_evaluate_or (me, &p, end);
1342       if (!value)
1343         return NULL;
1344       if (p >= end || p->token.type != T_RPAREN)
1345         {
1346           free (value);
1347           macro_error (me->stack, p < end ? p : NULL,
1348                        _("Expecting ')' in macro expression."));
1349           return NULL;
1350         }
1351       p++;
1352       *tokens = p;
1353       return value;
1354     }
1355   else if (p->token.type == T_RPAREN)
1356     {
1357       macro_error (me->stack, p, _("Expecting literal or function invocation "
1358                                    "in macro expression."));
1359       return NULL;
1360     }
1361
1362   struct string function_output = DS_EMPTY_INITIALIZER;
1363   size_t function_consumed = parse_function_arg (me, p, end - p,
1364                                                  &function_output);
1365   struct string unquoted = DS_EMPTY_INITIALIZER;
1366   if (unquote_string (ds_cstr (&function_output), me->segmenter_mode,
1367                       &unquoted))
1368     {
1369       ds_swap (&function_output, &unquoted);
1370       ds_destroy (&unquoted);
1371     }
1372   *tokens = p + function_consumed;
1373   return ds_steal_cstr (&function_output);
1374 }
1375
1376 /* Returns true if MT is valid as a macro operator.  Only operators written as
1377    symbols (e.g. <>) are usable in macro expressions, not operator written as
1378    letters (e.g. EQ). */
1379 static bool
1380 is_macro_operator (const struct macro_token *mt)
1381 {
1382   return mt->syntax.length > 0 && !c_isalpha (mt->syntax.string[0]);
1383 }
1384
1385 static enum token_type
1386 parse_relational_op (const struct macro_token *mt)
1387 {
1388   switch (mt->token.type)
1389     {
1390     case T_EQUALS:
1391       return T_EQ;
1392
1393     case T_NE:
1394     case T_LT:
1395     case T_GT:
1396     case T_LE:
1397     case T_GE:
1398       return is_macro_operator (mt) ? mt->token.type : T_STOP;
1399
1400     case T_MACRO_ID:
1401       return (ss_equals_case (mt->token.string, ss_cstr ("!EQ")) ? T_EQ
1402               : ss_equals_case (mt->token.string, ss_cstr ("!NE")) ? T_NE
1403               : ss_equals_case (mt->token.string, ss_cstr ("!LT")) ? T_LT
1404               : ss_equals_case (mt->token.string, ss_cstr ("!GT")) ? T_GT
1405               : ss_equals_case (mt->token.string, ss_cstr ("!LE")) ? T_LE
1406               : ss_equals_case (mt->token.string, ss_cstr ("!GE")) ? T_GE
1407               : T_STOP);
1408
1409     default:
1410       return T_STOP;
1411     }
1412 }
1413
1414 static char *
1415 macro_evaluate_relational (const struct macro_expander *me,
1416                            const struct macro_token **tokens,
1417                            const struct macro_token *end)
1418 {
1419   const struct macro_token *p = *tokens;
1420   char *lhs = macro_evaluate_literal (me, &p, end);
1421   if (!lhs)
1422     return NULL;
1423
1424   enum token_type op = p >= end ? T_STOP : parse_relational_op (p);
1425   if (op == T_STOP)
1426     {
1427       *tokens = p;
1428       return lhs;
1429     }
1430   p++;
1431
1432   char *rhs = macro_evaluate_literal (me, &p, end);
1433   if (!rhs)
1434     {
1435       free (lhs);
1436       return NULL;
1437     }
1438
1439   struct string lhs_tmp, rhs_tmp;
1440   int cmp = strcmp (unquote_string_in_place (lhs, me->segmenter_mode,
1441                                              &lhs_tmp),
1442                     unquote_string_in_place (rhs, me->segmenter_mode,
1443                                              &rhs_tmp));
1444   ds_destroy (&lhs_tmp);
1445   ds_destroy (&rhs_tmp);
1446
1447   free (lhs);
1448   free (rhs);
1449
1450   bool b = (op == T_EQUALS || op == T_EQ ? !cmp
1451             : op == T_NE ? cmp
1452             : op == T_LT ? cmp < 0
1453             : op == T_GT ? cmp > 0
1454             : op == T_LE ? cmp <= 0
1455             : /* T_GE */ cmp >= 0);
1456
1457   *tokens = p;
1458   return xstrdup (b ? "1" : "0");
1459 }
1460
1461 static char *
1462 macro_evaluate_not (const struct macro_expander *me,
1463                     const struct macro_token **tokens,
1464                     const struct macro_token *end)
1465 {
1466   const struct macro_token *p = *tokens;
1467
1468   unsigned int negations = 0;
1469   while (p < end
1470          && (ss_equals_case (p->syntax, ss_cstr ("!NOT"))
1471              || ss_equals (p->syntax, ss_cstr ("~"))))
1472     {
1473       p++;
1474       negations++;
1475     }
1476
1477   char *operand = macro_evaluate_relational (me, &p, end);
1478   if (!operand || !negations)
1479     {
1480       *tokens = p;
1481       return operand;
1482     }
1483
1484   bool b = strcmp (operand, "0") ^ (negations & 1);
1485   free (operand);
1486   *tokens = p;
1487   return xstrdup (b ? "1" : "0");
1488 }
1489
1490 static char *
1491 macro_evaluate_and (const struct macro_expander *me,
1492                     const struct macro_token **tokens,
1493                     const struct macro_token *end)
1494 {
1495   const struct macro_token *p = *tokens;
1496   char *lhs = macro_evaluate_not (me, &p, end);
1497   if (!lhs)
1498     return NULL;
1499
1500   while (p < end
1501          && (ss_equals_case (p->syntax, ss_cstr ("!AND"))
1502              || ss_equals (p->syntax, ss_cstr ("&"))))
1503     {
1504       p++;
1505       char *rhs = macro_evaluate_not (me, &p, end);
1506       if (!rhs)
1507         {
1508           free (lhs);
1509           return NULL;
1510         }
1511
1512       bool b = strcmp (lhs, "0") && strcmp (rhs, "0");
1513       free (lhs);
1514       free (rhs);
1515       lhs = xstrdup (b ? "1" : "0");
1516     }
1517   *tokens = p;
1518   return lhs;
1519 }
1520
1521 static char *
1522 macro_evaluate_or (const struct macro_expander *me,
1523                    const struct macro_token **tokens,
1524                    const struct macro_token *end)
1525 {
1526   const struct macro_token *p = *tokens;
1527   char *lhs = macro_evaluate_and (me, &p, end);
1528   if (!lhs)
1529     return NULL;
1530
1531   while (p < end
1532          && (ss_equals_case (p->syntax, ss_cstr ("!OR"))
1533              || ss_equals (p->syntax, ss_cstr ("|"))))
1534     {
1535       p++;
1536       char *rhs = macro_evaluate_and (me, &p, end);
1537       if (!rhs)
1538         {
1539           free (lhs);
1540           return NULL;
1541         }
1542
1543       bool b = strcmp (lhs, "0") || strcmp (rhs, "0");
1544       free (lhs);
1545       free (rhs);
1546       lhs = xstrdup (b ? "1" : "0");
1547     }
1548   *tokens = p;
1549   return lhs;
1550 }
1551
1552 static char *
1553 macro_evaluate_expression (const struct macro_token **tokens, size_t n_tokens,
1554                            const struct macro_expander *me)
1555 {
1556   return macro_evaluate_or (me, tokens, *tokens + n_tokens);
1557 }
1558
1559 static bool
1560 macro_evaluate_number (const struct macro_token **tokens, size_t n_tokens,
1561                        const struct macro_expander *me,
1562                        double *number)
1563 {
1564   char *s = macro_evaluate_expression (tokens, n_tokens, me);
1565   if (!s)
1566     return false;
1567
1568   struct macro_tokens mts = { .n = 0 };
1569   macro_tokens_from_string__ (&mts, ss_cstr (s), me->segmenter_mode, me->stack);
1570   if (mts.n != 1 || !token_is_number (&mts.mts[0].token))
1571     {
1572       macro_error (me->stack, mts.n > 0 ? &mts.mts[0] : NULL,
1573                    _("Macro expression must evaluate to "
1574                      "a number (not \"%s\")."), s);
1575       free (s);
1576       macro_tokens_uninit (&mts);
1577       return false;
1578     }
1579
1580   *number = token_number (&mts.mts[0].token);
1581   free (s);
1582   macro_tokens_uninit (&mts);
1583   return true;
1584 }
1585
1586 static const struct macro_token *
1587 find_ifend_clause (const struct macro_token *p, const struct macro_token *end)
1588 {
1589   size_t nesting = 0;
1590   for (; p < end; p++)
1591     {
1592       if (p->token.type != T_MACRO_ID)
1593         continue;
1594
1595       if (ss_equals_case (p->token.string, ss_cstr ("!IF")))
1596         nesting++;
1597       else if (lex_id_match_n (p->token.string, ss_cstr ("!IFEND"), 4))
1598         {
1599           if (!nesting)
1600             return p;
1601           nesting--;
1602         }
1603       else if (lex_id_match_n (p->token.string, ss_cstr ("!ELSE"), 4)
1604                && !nesting)
1605         return p;
1606     }
1607   return NULL;
1608 }
1609
1610 static size_t
1611 macro_expand_if (const struct macro_token *tokens, size_t n_tokens,
1612                  const struct macro_expander *me,
1613                  struct macro_tokens *exp)
1614 {
1615   const struct macro_token *p = tokens;
1616   const struct macro_token *end = tokens + n_tokens;
1617
1618   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!IF")))
1619     return 0;
1620
1621   p++;
1622   char *result = macro_evaluate_expression (&p, end - p, me);
1623   if (!result)
1624     return 0;
1625   bool b = strcmp (result, "0");
1626   free (result);
1627
1628   if (p >= end
1629       || p->token.type != T_MACRO_ID
1630       || !lex_id_match_n (p->token.string, ss_cstr ("!THEN"), 4))
1631     {
1632       macro_error (me->stack, p < end ? p : NULL,
1633                    _("!THEN expected in macro !IF construct."));
1634       return 0;
1635     }
1636
1637   const struct macro_token *start_then = p + 1;
1638   const struct macro_token *end_then = find_ifend_clause (start_then, end);
1639   if (!end_then)
1640     {
1641       macro_error (me->stack, NULL,
1642                    _("!ELSE or !IFEND expected in macro !IF construct."));
1643       return 0;
1644     }
1645
1646   const struct macro_token *start_else, *end_if;
1647   if (lex_id_match_n (end_then->token.string, ss_cstr ("!ELSE"), 4))
1648     {
1649       start_else = end_then + 1;
1650       end_if = find_ifend_clause (start_else, end);
1651       if (!end_if
1652           || !lex_id_match_n (end_if->token.string, ss_cstr ("!IFEND"), 4))
1653         {
1654           macro_error (me->stack, end_if ? end_if : NULL,
1655                        _("!IFEND expected in macro !IF construct."));
1656           return 0;
1657         }
1658     }
1659   else
1660     {
1661       start_else = NULL;
1662       end_if = end_then;
1663     }
1664
1665   const struct macro_token *start;
1666   size_t n;
1667   if (b)
1668     {
1669       start = start_then;
1670       n = end_then - start_then;
1671     }
1672   else if (start_else)
1673     {
1674       start = start_else;
1675       n = end_if - start_else;
1676     }
1677   else
1678     {
1679       start = NULL;
1680       n = 0;
1681     }
1682
1683   if (n)
1684     {
1685       struct macro_expansion_stack stack = {
1686         .name = "!IF",
1687         .next = me->stack,
1688       };
1689       struct macro_expander subme = *me;
1690       subme.stack = &stack;
1691       macro_expand (start, n, &subme, exp);
1692     }
1693   return (end_if + 1) - tokens;
1694 }
1695
1696 static size_t
1697 macro_parse_let (const struct macro_token *tokens, size_t n_tokens,
1698                  const struct macro_expander *me)
1699 {
1700   const struct macro_token *p = tokens;
1701   const struct macro_token *end = tokens + n_tokens;
1702
1703   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!LET")))
1704     return 0;
1705   p++;
1706
1707   if (p >= end || p->token.type != T_MACRO_ID)
1708     {
1709       macro_error (me->stack, p < end ? p : NULL,
1710                    _("Expected macro variable name following !LET."));
1711       return 0;
1712     }
1713   const struct substring var_name = p->token.string;
1714   if (is_macro_keyword (var_name)
1715       || macro_find_parameter_by_name (me->macro, var_name))
1716     {
1717       macro_error (me->stack, p < end ? p : NULL,
1718                    _("Cannot use argument name or macro keyword "
1719                      "\"%.*s\" as !LET variable."),
1720                    (int) var_name.length, var_name.string);
1721       return 0;
1722     }
1723   p++;
1724
1725   if (p >= end || p->token.type != T_EQUALS)
1726     {
1727       macro_error (me->stack, p < end ? p : NULL,
1728                    _("Expected `=' following !LET."));
1729       return 0;
1730     }
1731   p++;
1732
1733   char *value = macro_evaluate_expression (&p, end - p, me);
1734   if (!value)
1735     return 0;
1736
1737   stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name), value);
1738   return p - tokens;
1739 }
1740
1741 static const struct macro_token *
1742 find_doend (const struct macro_expansion_stack *stack,
1743             const struct macro_token *p, const struct macro_token *end)
1744 {
1745   size_t nesting = 0;
1746   for (; p < end; p++)
1747     {
1748       if (p->token.type != T_MACRO_ID)
1749         continue;
1750
1751       if (ss_equals_case (p->token.string, ss_cstr ("!DO")))
1752         nesting++;
1753       else if (lex_id_match_n (p->token.string, ss_cstr ("!DOEND"), 4))
1754         {
1755           if (!nesting)
1756             return p;
1757           nesting--;
1758         }
1759     }
1760   macro_error (stack, NULL, _("Missing !DOEND."));
1761   return NULL;
1762 }
1763
1764 static size_t
1765 macro_expand_do (const struct macro_token *tokens, size_t n_tokens,
1766                  const struct macro_expander *me,
1767                  struct macro_tokens *exp)
1768 {
1769   const struct macro_token *p = tokens;
1770   const struct macro_token *end = tokens + n_tokens;
1771
1772   if (p >= end || !ss_equals_case (p->token.string, ss_cstr ("!DO")))
1773     return 0;
1774   p++;
1775
1776   if (p >= end || p->token.type != T_MACRO_ID)
1777     {
1778       macro_error (me->stack, p < end ? p : NULL,
1779                    _("Expected macro variable name following !DO."));
1780       return 0;
1781     }
1782   const struct substring var_name = p->token.string;
1783   if (is_macro_keyword (var_name)
1784       || macro_find_parameter_by_name (me->macro, var_name))
1785     {
1786       macro_error (me->stack, p, _("Cannot use argument name or macro "
1787                                    "keyword as !DO variable."));
1788       return 0;
1789     }
1790   p++;
1791
1792   struct macro_expansion_stack substack = {
1793     .name = "!DO",
1794     .next = me->stack,
1795   };
1796   bool break_ = false;
1797   struct macro_expander subme = *me;
1798   subme.break_ = &break_;
1799   subme.stack = &substack;
1800
1801   int miterate = settings_get_miterate ();
1802   if (p < end && p->token.type == T_MACRO_ID
1803       && ss_equals_case (p->token.string, ss_cstr ("!IN")))
1804     {
1805       p++;
1806       char *list = macro_evaluate_expression (&p, end - p, &subme);
1807       if (!list)
1808         return 0;
1809
1810       struct macro_tokens items = { .n = 0 };
1811       macro_tokens_from_string__ (&items, ss_cstr (list), me->segmenter_mode,
1812                                   me->stack);
1813       free (list);
1814
1815       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1816       if (!do_end)
1817         {
1818           macro_tokens_uninit (&items);
1819           return 0;
1820         }
1821
1822       for (size_t i = 0; i < items.n && !break_; i++)
1823         {
1824           if (i >= miterate)
1825             {
1826               macro_error (&substack, NULL,
1827                            _("!DO loop over list exceeded "
1828                              "maximum number of iterations %d.  "
1829                              "(Use SET MITERATE to change the limit.)"),
1830                            miterate);
1831               break;
1832             }
1833           stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1834                                       ss_xstrdup (items.mts[i].syntax));
1835
1836           macro_expand (p, do_end - p, &subme, exp);
1837         }
1838       return do_end - tokens + 1;
1839     }
1840   else if (p < end && p->token.type == T_EQUALS)
1841     {
1842       p++;
1843       double first;
1844       if (!macro_evaluate_number (&p, end - p, &subme, &first))
1845         return 0;
1846
1847       if (p >= end || p->token.type != T_MACRO_ID
1848           || !ss_equals_case (p->token.string, ss_cstr ("!TO")))
1849         {
1850           macro_error (subme.stack, p < end ? p : NULL,
1851                        _("Expected !TO in numerical !DO loop."));
1852           return 0;
1853         }
1854       p++;
1855
1856       double last;
1857       if (!macro_evaluate_number (&p, end - p, &subme, &last))
1858         return 0;
1859
1860       double by = 1.0;
1861       if (p < end && p->token.type == T_MACRO_ID
1862           && ss_equals_case (p->token.string, ss_cstr ("!BY")))
1863         {
1864           p++;
1865           if (!macro_evaluate_number (&p, end - p, &subme, &by))
1866             return 0;
1867
1868           if (by == 0.0)
1869             {
1870               macro_error (subme.stack, NULL, _("!BY value cannot be zero."));
1871               return 0;
1872             }
1873         }
1874
1875       const struct macro_token *do_end = find_doend (subme.stack, p, end);
1876       if (!do_end)
1877         return 0;
1878       if ((by > 0 && first <= last) || (by < 0 && first >= last))
1879         {
1880           int i = 0;
1881           for (double index = first;
1882                by > 0 ? (index <= last) : (index >= last) && !break_;
1883                index += by)
1884             {
1885               if (i++ > miterate)
1886                 {
1887                   macro_error (subme.stack, NULL,
1888                                _("Numerical !DO loop exceeded "
1889                                  "maximum number of iterations %d.  "
1890                                  "(Use SET MITERATE to change the limit.)"),
1891                                miterate);
1892                   break;
1893                 }
1894
1895               char index_s[DBL_BUFSIZE_BOUND];
1896               c_dtoastr (index_s, sizeof index_s, 0, 0, index);
1897               stringi_map_replace_nocopy (me->vars, ss_xstrdup (var_name),
1898                                           xstrdup (index_s));
1899
1900               macro_expand (p, do_end - p, &subme, exp);
1901             }
1902         }
1903
1904       return do_end - tokens + 1;
1905     }
1906   else
1907     {
1908       macro_error (me->stack, p < end ? p : NULL,
1909                    _("Expected `=' or !IN in !DO loop."));
1910       return 0;
1911     }
1912 }
1913
1914 static void
1915 macro_expand_arg__ (const struct macro_expander *me, size_t idx,
1916                   struct macro_tokens *exp)
1917 {
1918   const struct macro_param *param = &me->macro->params[idx];
1919   const struct macro_tokens *arg = me->args[idx];
1920
1921   if (*me->expand && param->expand_arg)
1922     {
1923       struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
1924       struct macro_expansion_stack stack = {
1925         .name = param->name,
1926         .next = me->stack,
1927       };
1928       struct macro_expander subme = {
1929         .macros = me->macros,
1930         .macro = NULL,
1931         .args = NULL,
1932         .segmenter_mode = me->segmenter_mode,
1933         .expand = me->expand,
1934         .break_ = NULL,
1935         .vars = &vars,
1936         .nesting_countdown = me->nesting_countdown,
1937         .stack = &stack,
1938       };
1939       macro_expand (arg->mts, arg->n, &subme, exp);
1940       stringi_map_destroy (&vars);
1941     }
1942   else
1943     for (size_t i = 0; i < arg->n; i++)
1944       macro_tokens_add (exp, &arg->mts[i]);
1945 }
1946
1947 static bool
1948 macro_expand_arg (const struct token *token, const struct macro_expander *me,
1949                   struct macro_tokens *exp)
1950 {
1951   if (!me || token->type != T_MACRO_ID)
1952     return false;
1953
1954   /* Macro arguments. */
1955   if (me->macro)
1956     {
1957       const struct macro_param *param = macro_find_parameter_by_name (
1958         me->macro, token->string);
1959       if (param)
1960         {
1961           macro_expand_arg__ (me, param - me->macro->params, exp);
1962           return true;
1963         }
1964       else if (ss_equals (token->string, ss_cstr ("!*")))
1965         {
1966           for (size_t j = 0; j < me->macro->n_params; j++)
1967             macro_expand_arg__ (me, j, exp);
1968           return true;
1969         }
1970     }
1971
1972   /* Variables set by !DO or !LET. */
1973   const char *var = stringi_map_find__ (me->vars, token->string.string,
1974                                         token->string.length);
1975   if (var)
1976     {
1977       macro_tokens_from_string__ (exp, ss_cstr (var),
1978                                   me->segmenter_mode, me->stack);
1979       return true;
1980     }
1981
1982   return false;
1983 }
1984
1985 static size_t
1986 macro_expand__ (const struct macro_token *mts, size_t n,
1987                 const struct macro_expander *me,
1988                 struct macro_tokens *exp)
1989 {
1990   const struct token *token = &mts[0].token;
1991
1992   /* Recursive macro calls. */
1993   if (*me->expand)
1994     {
1995       struct macro_call *submc;
1996       int n_call = macro_call_create__ (me->macros, me->stack, me,
1997                                         token, &submc);
1998       for (size_t j = 1; !n_call; j++)
1999         {
2000           const struct macro_token endcmd
2001             = { .token = { .type = T_ENDCMD } };
2002           n_call = macro_call_add (submc, j < n ? &mts[j] : &endcmd, NULL);
2003         }
2004       if (n_call > 0)
2005         {
2006           struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2007           struct macro_expansion_stack stack = {
2008             .name = submc->macro->name,
2009             .location = submc->macro->location,
2010             .next = me->stack,
2011           };
2012           struct macro_expander subme = {
2013             .macros = submc->macros,
2014             .macro = submc->macro,
2015             .args = submc->args,
2016             .segmenter_mode = me->segmenter_mode,
2017             .expand = me->expand,
2018             .break_ = NULL,
2019             .vars = &vars,
2020             .nesting_countdown = me->nesting_countdown - 1,
2021             .stack = &stack,
2022           };
2023           const struct macro_tokens *body = &submc->macro->body;
2024           macro_expand (body->mts, body->n, &subme, exp);
2025           macro_call_destroy (submc);
2026           stringi_map_destroy (&vars);
2027           return n_call;
2028         }
2029
2030       macro_call_destroy (submc);
2031     }
2032
2033   if (token->type != T_MACRO_ID)
2034     {
2035       macro_tokens_add (exp, &mts[0]);
2036       return 1;
2037     }
2038
2039   /* Parameters and macro variables. */
2040   if (macro_expand_arg (token, me, exp))
2041     return 1;
2042
2043   /* Macro functions. */
2044   struct string function_output = DS_EMPTY_INITIALIZER;
2045   size_t n_function = expand_macro_function (me, mts, n, &function_output);
2046   if (n_function)
2047     {
2048       macro_tokens_from_string__ (exp, function_output.ss,
2049                                   me->segmenter_mode, me->stack);
2050       ds_destroy (&function_output);
2051
2052       return n_function;
2053     }
2054
2055   size_t n_if = macro_expand_if (mts, n, me, exp);
2056   if (n_if > 0)
2057     return n_if;
2058
2059   size_t n_let = macro_parse_let (mts, n, me);
2060   if (n_let > 0)
2061     return n_let;
2062
2063   size_t n_do = macro_expand_do (mts, n, me, exp);
2064   if (n_do > 0)
2065     return n_do;
2066
2067   if (lex_id_match_n (token->string, ss_cstr ("!break"), 4))
2068     {
2069       if (me->break_)
2070         *me->break_ = true;
2071       else
2072         macro_error (me->stack, &mts[0], _("!BREAK outside !DO."));
2073     }
2074   else if (lex_id_match_n (token->string, ss_cstr ("!onexpand"), 4))
2075     *me->expand = true;
2076   else if (lex_id_match_n (token->string, ss_cstr ("!offexpand"), 4))
2077     *me->expand = false;
2078   else
2079     macro_tokens_add (exp, &mts[0]);
2080   return 1;
2081 }
2082
2083 static void
2084 macro_expand (const struct macro_token *mts, size_t n,
2085               const struct macro_expander *me,
2086               struct macro_tokens *exp)
2087 {
2088   if (me->nesting_countdown <= 0)
2089     {
2090       macro_error (me->stack, NULL, _("Maximum nesting level %d exceeded.  "
2091                                       "(Use SET MNEST to change the limit.)"),
2092                    settings_get_mnest ());
2093       for (size_t i = 0; i < n; i++)
2094         macro_tokens_add (exp, &mts[i]);
2095       return;
2096     }
2097
2098   for (size_t i = 0; i < n; )
2099     {
2100       if (me->break_ && *me->break_)
2101         break;
2102
2103       size_t consumed = macro_expand__ (&mts[i], n - i, me, exp);
2104       assert (consumed > 0 && i + consumed <= n);
2105       i += consumed;
2106     }
2107 }
2108
2109 void
2110 macro_call_expand (struct macro_call *mc, enum segmenter_mode segmenter_mode,
2111                    const struct msg_location *call_loc,
2112                    struct macro_tokens *exp)
2113 {
2114   assert (mc->state == MC_FINISHED);
2115
2116   bool expand = true;
2117   struct stringi_map vars = STRINGI_MAP_INITIALIZER (vars);
2118   struct macro_expansion_stack stack0 = {
2119     .location = call_loc,
2120   };
2121   struct macro_expansion_stack stack1 = {
2122     .next = &stack0,
2123     .name = mc->macro->name,
2124     .location = mc->macro->location,
2125   };
2126   struct macro_expander me = {
2127     .macros = mc->macros,
2128     .macro = mc->macro,
2129     .args = mc->args,
2130     .segmenter_mode = segmenter_mode,
2131     .expand = &expand,
2132     .break_ = NULL,
2133     .vars = &vars,
2134     .nesting_countdown = settings_get_mnest (),
2135     .stack = &stack1,
2136   };
2137
2138   const struct macro_tokens *body = &mc->macro->body;
2139   macro_expand (body->mts, body->n, &me, exp);
2140
2141   stringi_map_destroy (&vars);
2142 }
2143