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