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