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