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