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