lexer: Simplify lex_get_error().
[pspp] / src / language / lexer / lexer.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2013, 2016 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/lexer.h"
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <math.h>
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unictype.h>
29 #include <unistd.h>
30 #include <unistr.h>
31
32 #include "language/command.h"
33 #include "language/lexer/macro.h"
34 #include "language/lexer/scan.h"
35 #include "language/lexer/segment.h"
36 #include "language/lexer/token.h"
37 #include "libpspp/assertion.h"
38 #include "libpspp/cast.h"
39 #include "libpspp/deque.h"
40 #include "libpspp/i18n.h"
41 #include "libpspp/intern.h"
42 #include "libpspp/ll.h"
43 #include "libpspp/message.h"
44 #include "libpspp/misc.h"
45 #include "libpspp/str.h"
46 #include "libpspp/u8-istream.h"
47 #include "output/journal.h"
48 #include "output/output-item.h"
49
50 #include "gl/c-ctype.h"
51 #include "gl/minmax.h"
52 #include "gl/xalloc.h"
53 #include "gl/xmemdup0.h"
54
55 #include "gettext.h"
56 #define _(msgid) gettext (msgid)
57 #define N_(msgid) msgid
58
59 /* A token within a lex_source. */
60 struct lex_token
61   {
62     /* The regular token information. */
63     struct token token;
64
65     /* For a token obtained through the lexer in an ordinary way, this is the
66        location of the token in terms of the lex_source's buffer.
67
68        For a token produced through macro expansion, this is the entire macro
69        call. */
70     size_t token_pos;           /* Offset into src->buffer of token start. */
71     size_t token_len;           /* Length of source for token in bytes. */
72
73     /* For a token obtained through macro expansion, this is just this token.
74
75        For a token obtained through the lexer in an ordinary way, these are
76        nulls and zeros. */
77     char *macro_rep;        /* The whole macro expansion. */
78     size_t ofs;             /* Offset of this token in macro_rep. */
79     size_t len;             /* Length of this token in macro_rep. */
80     size_t *ref_cnt;        /* Number of lex_tokens that refer to macro_rep. */
81   };
82
83 static struct msg_point lex_token_start_point (const struct lex_source *,
84                                                const struct lex_token *);
85 static struct msg_point lex_token_end_point (const struct lex_source *,
86                                              const struct lex_token *);
87
88 static bool lex_ofs_at_phrase__ (struct lexer *, int ofs, const char *s,
89                                  size_t *n_matchedp);
90
91 /* Source offset of the last byte in TOKEN. */
92 static size_t
93 lex_token_end (const struct lex_token *token)
94 {
95   return token->token_pos + MAX (token->token_len, 1) - 1;
96 }
97
98 static void
99 lex_token_destroy (struct lex_token *t)
100 {
101   token_uninit (&t->token);
102   if (t->ref_cnt)
103     {
104       assert (*t->ref_cnt > 0);
105       if (!--*t->ref_cnt)
106         {
107           free (t->macro_rep);
108           free (t->ref_cnt);
109         }
110     }
111   free (t);
112 }
113 \f
114 /* A deque of lex_tokens that comprises one stage in the token pipeline in a
115    lex_source. */
116 struct lex_stage
117   {
118     struct deque deque;
119     struct lex_token **tokens;
120   };
121
122 static void lex_stage_clear (struct lex_stage *);
123 static void lex_stage_uninit (struct lex_stage *);
124
125 static size_t lex_stage_count (const struct lex_stage *);
126 static bool lex_stage_is_empty (const struct lex_stage *);
127
128 static struct lex_token *lex_stage_first (struct lex_stage *);
129 static struct lex_token *lex_stage_nth (struct lex_stage *, size_t ofs);
130
131 static void lex_stage_push_last (struct lex_stage *, struct lex_token *);
132 static void lex_stage_pop_first (struct lex_stage *);
133
134 static void lex_stage_shift (struct lex_stage *dst, struct lex_stage *src,
135                              size_t n);
136
137 /* Deletes all the tokens from STAGE. */
138 static void
139 lex_stage_clear (struct lex_stage *stage)
140 {
141   while (!deque_is_empty (&stage->deque))
142     lex_stage_pop_first (stage);
143 }
144
145 /* Deletes all the tokens from STAGE and frees storage for the deque. */
146 static void
147 lex_stage_uninit (struct lex_stage *stage)
148 {
149   lex_stage_clear (stage);
150   free (stage->tokens);
151 }
152
153 /* Returns true if STAGE contains no tokens, otherwise false. */
154 static bool
155 lex_stage_is_empty (const struct lex_stage *stage)
156 {
157   return deque_is_empty (&stage->deque);
158 }
159
160 /* Returns the number of tokens in STAGE. */
161 static size_t
162 lex_stage_count (const struct lex_stage *stage)
163 {
164   return deque_count (&stage->deque);
165 }
166
167 /* Returns the first token in STAGE, which must be nonempty.
168    The first token is the one accessed with the least lookahead. */
169 static struct lex_token *
170 lex_stage_first (struct lex_stage *stage)
171 {
172   return lex_stage_nth (stage, 0);
173 }
174
175 /* Returns the token the given INDEX in STAGE.  The first token (with the least
176    lookahead) is 0, the second token is 1, and so on.  There must be at least
177    INDEX + 1 tokens in STAGE. */
178 static struct lex_token *
179 lex_stage_nth (struct lex_stage *stage, size_t index)
180 {
181   return stage->tokens[deque_back (&stage->deque, index)];
182 }
183
184 /* Adds TOKEN so that it becomes the last token in STAGE. */
185 static void
186 lex_stage_push_last (struct lex_stage *stage, struct lex_token *token)
187 {
188   if (deque_is_full (&stage->deque))
189     stage->tokens = deque_expand (&stage->deque, stage->tokens,
190                                   sizeof *stage->tokens);
191   stage->tokens[deque_push_front (&stage->deque)] = token;
192 }
193
194 /* Removes and returns the first token from STAGE. */
195 static struct lex_token *
196 lex_stage_take_first (struct lex_stage *stage)
197 {
198   return stage->tokens[deque_pop_back (&stage->deque)];
199 }
200
201 /* Removes the first token from STAGE and uninitializes it. */
202 static void
203 lex_stage_pop_first (struct lex_stage *stage)
204 {
205   lex_token_destroy (lex_stage_take_first (stage));
206 }
207
208 /* Removes the first N tokens from SRC, appending them to DST as the last
209    tokens. */
210 static void
211 lex_stage_shift (struct lex_stage *dst, struct lex_stage *src, size_t n)
212 {
213   for (size_t i = 0; i < n; i++)
214     lex_stage_push_last (dst, lex_stage_take_first (src));
215 }
216
217 /* A source of tokens, corresponding to a syntax file.
218
219    This is conceptually a lex_reader wrapped with everything needed to convert
220    its UTF-8 bytes into tokens. */
221 struct lex_source
222   {
223     struct ll ll;               /* In lexer's list of sources. */
224
225     /* Reference count:
226
227        - One for struct lexer.
228
229        - One for each struct msg_location that references this source. */
230     size_t n_refs;
231
232     struct lex_reader *reader;
233     struct lexer *lexer;
234     struct segmenter segmenter;
235     bool eof;                   /* True if T_STOP was read from 'reader'. */
236
237     /* Buffer of UTF-8 bytes. */
238     char *buffer;               /* Source file contents. */
239     size_t length;              /* Number of bytes filled. */
240     size_t allocated;           /* Number of bytes allocated. */
241
242     /* Offsets into 'buffer'. */
243     size_t journal_pos;         /* First byte not yet output to journal. */
244     size_t seg_pos;             /* First byte not yet scanned as token. */
245
246     /* Offset into 'buffer' of starts of lines. */
247     size_t *lines;
248     size_t n_lines, allocated_lines;
249
250     bool suppress_next_newline;
251
252     /* Tokens.
253
254        This is a pipeline with the following stages.  Each token eventually
255        made available to the parser passes through of these stages.  The stages
256        are named after the processing that happens in each one.
257
258        Initially, tokens come from the segmenter and scanner to 'pp':
259
260        - pp: Tokens that need to pass through the macro preprocessor to end up
261          in 'merge'.
262
263        - merge: Tokens that need to pass through scan_merge() to end up in
264          'parse'.
265
266        - parse: Tokens available to the client for parsing.
267
268       'pp' and 'merge' store tokens only temporarily until they pass into
269       'parse'.  Tokens then live in 'parse' until the command is fully
270       consumed, at which time they are freed together. */
271     struct lex_stage pp;
272     struct lex_stage merge;
273     struct lex_token **parse;
274     size_t n_parse, allocated_parse, parse_ofs;
275   };
276
277 static struct lex_source *lex_source_create (struct lexer *,
278                                              struct lex_reader *);
279
280 /* Lexer. */
281 struct lexer
282   {
283     struct ll_list sources;     /* Contains "struct lex_source"s. */
284     struct macro_set *macros;
285   };
286
287 static struct lex_source *lex_source__ (const struct lexer *);
288 static char *lex_source_syntax__ (const struct lex_source *,
289                                   int ofs0, int ofs1);
290 static const struct lex_token *lex_next__ (const struct lexer *, int n);
291 static void lex_source_push_endcmd__ (struct lex_source *);
292 static void lex_source_push_parse (struct lex_source *, struct lex_token *);
293 static void lex_source_clear_parse (struct lex_source *);
294
295 static bool lex_source_get_parse (struct lex_source *);
296 static void lex_source_msg_valist (struct lex_source *, enum msg_class,
297                                    int ofs0, int ofs1,
298                                    const char *format, va_list)
299    PRINTF_FORMAT (5, 0);
300 static const struct lex_token *lex_source_next__ (const struct lex_source *,
301                                                   int n);
302 \f
303 /* Initializes READER with the specified CLASS and otherwise some reasonable
304    defaults.  The caller should fill in the others members as desired. */
305 void
306 lex_reader_init (struct lex_reader *reader,
307                  const struct lex_reader_class *class)
308 {
309   reader->class = class;
310   reader->syntax = SEG_MODE_AUTO;
311   reader->error = LEX_ERROR_CONTINUE;
312   reader->file_name = NULL;
313   reader->encoding = NULL;
314   reader->line_number = 0;
315   reader->eof = false;
316 }
317
318 /* Frees any file name already in READER and replaces it by a copy of
319    FILE_NAME, or if FILE_NAME is null then clears any existing name. */
320 void
321 lex_reader_set_file_name (struct lex_reader *reader, const char *file_name)
322 {
323   free (reader->file_name);
324   reader->file_name = xstrdup_if_nonnull (file_name);
325 }
326 \f
327 /* Creates and returns a new lexer. */
328 struct lexer *
329 lex_create (void)
330 {
331   struct lexer *lexer = xmalloc (sizeof *lexer);
332   *lexer = (struct lexer) {
333     .sources = LL_INITIALIZER (lexer->sources),
334     .macros = macro_set_create (),
335   };
336   return lexer;
337 }
338
339 /* Destroys LEXER. */
340 void
341 lex_destroy (struct lexer *lexer)
342 {
343   if (lexer != NULL)
344     {
345       struct lex_source *source, *next;
346
347       ll_for_each_safe (source, next, struct lex_source, ll, &lexer->sources)
348         {
349           ll_remove (&source->ll);
350           lex_source_unref (source);
351         }
352       macro_set_destroy (lexer->macros);
353       free (lexer);
354     }
355 }
356
357 /* Adds M to LEXER's set of macros.  M replaces any existing macro with the
358    same name.  Takes ownership of M. */
359 void
360 lex_define_macro (struct lexer *lexer, struct macro *m)
361 {
362   macro_set_add (lexer->macros, m);
363 }
364
365 /* Returns LEXER's macro set.  The caller should not modify it. */
366 const struct macro_set *
367 lex_get_macros (const struct lexer *lexer)
368 {
369   return lexer->macros;
370 }
371
372 /* Inserts READER into LEXER so that the next token read by LEXER comes from
373    READER.  Before the caller, LEXER must either be empty or at a T_ENDCMD
374    token. */
375 void
376 lex_include (struct lexer *lexer, struct lex_reader *reader)
377 {
378   assert (ll_is_empty (&lexer->sources) || lex_token (lexer) == T_ENDCMD);
379   ll_push_head (&lexer->sources, &lex_source_create (lexer, reader)->ll);
380 }
381
382 /* Appends READER to LEXER, so that it will be read after all other current
383    readers have already been read. */
384 void
385 lex_append (struct lexer *lexer, struct lex_reader *reader)
386 {
387   ll_push_tail (&lexer->sources, &lex_source_create (lexer, reader)->ll);
388 }
389 \f
390 /* Advancing. */
391
392 /* Advances LEXER to the next token, consuming the current token. */
393 void
394 lex_get (struct lexer *lexer)
395 {
396   struct lex_source *src;
397
398   src = lex_source__ (lexer);
399   if (src == NULL)
400     return;
401
402   if (src->parse_ofs < src->n_parse)
403     {
404       if (src->parse[src->parse_ofs]->token.type == T_ENDCMD)
405         lex_source_clear_parse (src);
406       else
407         src->parse_ofs++;
408     }
409
410   while (src->parse_ofs == src->n_parse)
411     if (!lex_source_get_parse (src))
412       {
413         ll_remove (&src->ll);
414         lex_source_unref (src);
415         src = lex_source__ (lexer);
416         if (src == NULL)
417           return;
418       }
419 }
420
421 /* Advances LEXER by N tokens. */
422 void
423 lex_get_n (struct lexer *lexer, size_t n)
424 {
425   while (n-- > 0)
426     lex_get (lexer);
427 }
428 \f
429 /* Issuing errors. */
430
431 /* Prints a syntax error message containing the current token and
432    given message MESSAGE (if non-null). */
433 void
434 lex_error (struct lexer *lexer, const char *format, ...)
435 {
436   va_list args;
437
438   va_start (args, format);
439   lex_ofs_msg_valist (lexer, SE, lex_ofs (lexer), lex_ofs (lexer),
440                       format, args);
441   va_end (args);
442 }
443
444 /* Prints a syntax error message for the span of tokens N0 through N1,
445    inclusive, from the current token in LEXER, adding message MESSAGE (if
446    non-null). */
447 void
448 lex_next_error (struct lexer *lexer, int n0, int n1, const char *format, ...)
449 {
450   va_list args;
451
452   va_start (args, format);
453   int ofs = lex_ofs (lexer);
454   lex_ofs_msg_valist (lexer, SE, n0 + ofs, n1 + ofs, format, args);
455   va_end (args);
456 }
457
458 /* Prints a syntax error message for the span of tokens with offsets OFS0
459    through OFS1, inclusive, within the current command in LEXER, adding message
460    MESSAGE (if non-null). */
461 void
462 lex_ofs_error (struct lexer *lexer, int ofs0, int ofs1, const char *format, ...)
463 {
464   va_list args;
465
466   va_start (args, format);
467   lex_ofs_msg_valist (lexer, SE, ofs0, ofs1, format, args);
468   va_end (args);
469 }
470
471 /* Prints a message of the given CLASS containing the current token and given
472    message MESSAGE (if non-null). */
473 void
474 lex_msg (struct lexer *lexer, enum msg_class class, const char *format, ...)
475 {
476   va_list args;
477
478   va_start (args, format);
479   lex_ofs_msg_valist (lexer, class, lex_ofs (lexer), lex_ofs (lexer),
480                       format, args);
481   va_end (args);
482 }
483
484 /* Prints a syntax error message for the span of tokens N0 through N1,
485    inclusive, from the current token in LEXER, adding message MESSAGE (if
486    non-null). */
487 void
488 lex_next_msg (struct lexer *lexer, enum msg_class class, int n0, int n1,
489               const char *format, ...)
490 {
491   va_list args;
492
493   va_start (args, format);
494   int ofs = lex_ofs (lexer);
495   lex_ofs_msg_valist (lexer, class, n0 + ofs, n1 + ofs, format, args);
496   va_end (args);
497 }
498
499 /* Prints a message of the given CLASS for the span of tokens with offsets OFS0
500    through OFS1, inclusive, within the current command in LEXER, adding message
501    MESSAGE (if non-null). */
502 void
503 lex_ofs_msg (struct lexer *lexer, enum msg_class class, int ofs0, int ofs1,
504              const char *format, ...)
505 {
506   va_list args;
507
508   va_start (args, format);
509   lex_ofs_msg_valist (lexer, class, ofs0, ofs1, format, args);
510   va_end (args);
511 }
512
513 /* Prints a syntax error message saying that one of the strings provided as
514    varargs, up to the first NULL, is expected. */
515 void
516 (lex_error_expecting) (struct lexer *lexer, ...)
517 {
518   va_list args;
519
520   va_start (args, lexer);
521   lex_error_expecting_valist (lexer, args);
522   va_end (args);
523 }
524
525 /* Prints a syntax error message saying that one of the options provided in
526    ARGS, up to the first NULL, is expected. */
527 void
528 lex_error_expecting_valist (struct lexer *lexer, va_list args)
529 {
530   const char **options = NULL;
531   size_t allocated = 0;
532   size_t n = 0;
533
534   for (;;)
535     {
536       const char *option = va_arg (args, const char *);
537       if (!option)
538         break;
539
540       if (n >= allocated)
541         options = x2nrealloc (options, &allocated, sizeof *options);
542       options[n++] = option;
543     }
544   lex_error_expecting_array (lexer, options, n);
545   free (options);
546 }
547
548 void
549 lex_error_expecting_array (struct lexer *lexer, const char **options, size_t n)
550 {
551   switch (n)
552     {
553     case 0:
554       lex_error (lexer, NULL);
555       break;
556
557     case 1:
558       lex_error (lexer, _("Syntax error expecting %s."), options[0]);
559       break;
560
561     case 2:
562       lex_error (lexer, _("Syntax error expecting %s or %s."),
563                  options[0], options[1]);
564       break;
565
566     case 3:
567       lex_error (lexer, _("Syntax error expecting %s, %s, or %s."),
568                  options[0], options[1], options[2]);
569       break;
570
571     case 4:
572       lex_error (lexer, _("Syntax error expecting %s, %s, %s, or %s."),
573                  options[0], options[1], options[2], options[3]);
574       break;
575
576     case 5:
577       lex_error (lexer, _("Syntax error expecting %s, %s, %s, %s, or %s."),
578                  options[0], options[1], options[2], options[3], options[4]);
579       break;
580
581     case 6:
582       lex_error (lexer, _("Syntax error expecting %s, %s, %s, %s, %s, or %s."),
583                  options[0], options[1], options[2], options[3], options[4],
584                  options[5]);
585       break;
586
587     case 7:
588       lex_error (lexer, _("Syntax error expecting %s, %s, %s, %s, %s, %s, "
589                           "or %s."),
590                  options[0], options[1], options[2], options[3], options[4],
591                  options[5], options[6]);
592       break;
593
594     case 8:
595       lex_error (lexer, _("Syntax error expecting %s, %s, %s, %s, %s, %s, %s, "
596                           "or %s."),
597                  options[0], options[1], options[2], options[3], options[4],
598                  options[5], options[6], options[7]);
599       break;
600
601     default:
602       {
603         struct string s = DS_EMPTY_INITIALIZER;
604         for (size_t i = 0; i < n; i++)
605           {
606             if (i > 0)
607               ds_put_cstr (&s, ", ");
608             ds_put_cstr (&s, options[i]);
609           }
610         lex_error (lexer, _("Syntax error expecting one of the following: %s."),
611                    ds_cstr (&s));
612         ds_destroy (&s);
613       }
614       break;
615     }
616 }
617
618 /* Reports an error to the effect that subcommand SBC may only be specified
619    once. */
620 void
621 lex_sbc_only_once (struct lexer *lexer, const char *sbc)
622 {
623   int ofs = lex_ofs (lexer) - 1;
624   if (lex_ofs_token (lexer, ofs)->type == T_EQUALS)
625     ofs--;
626
627   /* lex_ofs_at_phrase__() handles subcommand names that are keywords, such as
628      BY. */
629   if (lex_ofs_at_phrase__ (lexer, ofs, sbc, NULL))
630     lex_ofs_error (lexer, ofs, ofs,
631                    _("Subcommand %s may only be specified once."), sbc);
632   else
633     msg (SE, _("Subcommand %s may only be specified once."), sbc);
634 }
635
636 /* Reports an error to the effect that subcommand SBC is missing.
637
638    This function does not take a lexer as an argument or use lex_error(),
639    because a missing subcommand can normally be detected only after the whole
640    command has been parsed, and so lex_error() would always report "Syntax
641    error at end of command", which does not help the user find the error. */
642 void
643 lex_sbc_missing (struct lexer *lexer, const char *sbc)
644 {
645   lex_ofs_error (lexer, 0, lex_max_ofs (lexer),
646                  _("Required subcommand %s was not specified."), sbc);
647 }
648
649 /* Reports an error to the effect that specification SPEC may only be specified
650    once within subcommand SBC. */
651 void
652 lex_spec_only_once (struct lexer *lexer, const char *sbc, const char *spec)
653 {
654   lex_error (lexer, _("%s may only be specified once within subcommand %s."),
655              spec, sbc);
656 }
657
658 /* Reports an error to the effect that specification SPEC is missing within
659    subcommand SBC. */
660 void
661 lex_spec_missing (struct lexer *lexer, const char *sbc, const char *spec)
662 {
663   lex_error (lexer, _("Required %s specification missing from %s subcommand."),
664              spec, sbc);
665 }
666
667 /* Prints a syntax error message for the span of tokens with offsets OFS0
668    through OFS1, inclusive, within the current command in LEXER, adding message
669    MESSAGE (if non-null) with the given ARGS. */
670 void
671 lex_ofs_msg_valist (struct lexer *lexer, enum msg_class class,
672                     int ofs0, int ofs1, const char *format, va_list args)
673 {
674   lex_source_msg_valist (lex_source__ (lexer), class, ofs0, ofs1, format, args);
675 }
676
677 /* Checks that we're at end of command.
678    If so, returns a successful command completion code.
679    If not, flags a syntax error and returns an error command
680    completion code. */
681 int
682 lex_end_of_command (struct lexer *lexer)
683 {
684   if (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_STOP)
685     {
686       lex_error (lexer, _("Syntax error expecting end of command."));
687       return CMD_FAILURE;
688     }
689   else
690     return CMD_SUCCESS;
691 }
692 \f
693 /* Token testing functions. */
694
695 /* Returns true if the current token is a number. */
696 bool
697 lex_is_number (const struct lexer *lexer)
698 {
699   return lex_next_is_number (lexer, 0);
700 }
701
702 /* Returns true if the current token is a string. */
703 bool
704 lex_is_string (const struct lexer *lexer)
705 {
706   return lex_next_is_string (lexer, 0);
707 }
708
709 /* Returns the value of the current token, which must be a
710    floating point number. */
711 double
712 lex_number (const struct lexer *lexer)
713 {
714   return lex_next_number (lexer, 0);
715 }
716
717 /* Returns true iff the current token is an integer. */
718 bool
719 lex_is_integer (const struct lexer *lexer)
720 {
721   return lex_next_is_integer (lexer, 0);
722 }
723
724 /* Returns the value of the current token, which must be an
725    integer. */
726 long
727 lex_integer (const struct lexer *lexer)
728 {
729   return lex_next_integer (lexer, 0);
730 }
731 \f
732 /* Token testing functions with lookahead.
733
734    A value of 0 for N as an argument to any of these functions refers to the
735    current token.  Lookahead is limited to the current command.  Any N greater
736    than the number of tokens remaining in the current command will be treated
737    as referring to a T_ENDCMD token. */
738
739 /* Returns true if the token N ahead of the current token is a number. */
740 bool
741 lex_next_is_number (const struct lexer *lexer, int n)
742 {
743   return token_is_number (lex_next (lexer, n));
744 }
745
746 /* Returns true if the token N ahead of the current token is a string. */
747 bool
748 lex_next_is_string (const struct lexer *lexer, int n)
749 {
750   return token_is_string (lex_next (lexer, n));
751 }
752
753 /* Returns the value of the token N ahead of the current token, which must be a
754    floating point number. */
755 double
756 lex_next_number (const struct lexer *lexer, int n)
757 {
758   return token_number (lex_next (lexer, n));
759 }
760
761 /* Returns true if the token N ahead of the current token is an integer. */
762 bool
763 lex_next_is_integer (const struct lexer *lexer, int n)
764 {
765   return token_is_integer (lex_next (lexer, n));
766 }
767
768 /* Returns the value of the token N ahead of the current token, which must be
769    an integer. */
770 long
771 lex_next_integer (const struct lexer *lexer, int n)
772 {
773   return token_integer (lex_next (lexer, n));
774 }
775 \f
776 /* Token matching functions. */
777
778 /* If the current token has the specified TYPE, skips it and returns true.
779    Otherwise, returns false. */
780 bool
781 lex_match (struct lexer *lexer, enum token_type type)
782 {
783   if (lex_token (lexer) == type)
784     {
785       lex_get (lexer);
786       return true;
787     }
788   else
789     return false;
790 }
791
792 /* If the current token matches IDENTIFIER, skips it and returns true.
793    IDENTIFIER may be abbreviated to its first three letters.  Otherwise,
794    returns false.
795
796    IDENTIFIER must be an ASCII string. */
797 bool
798 lex_match_id (struct lexer *lexer, const char *identifier)
799 {
800   return lex_match_id_n (lexer, identifier, 3);
801 }
802
803 /* If the current token is IDENTIFIER, skips it and returns true.  IDENTIFIER
804    may be abbreviated to its first N letters.  Otherwise, returns false.
805
806    IDENTIFIER must be an ASCII string. */
807 bool
808 lex_match_id_n (struct lexer *lexer, const char *identifier, size_t n)
809 {
810   if (lex_token (lexer) == T_ID
811       && lex_id_match_n (ss_cstr (identifier), lex_tokss (lexer), n))
812     {
813       lex_get (lexer);
814       return true;
815     }
816   else
817     return false;
818 }
819
820 /* If the current token is integer X, skips it and returns true.  Otherwise,
821    returns false. */
822 bool
823 lex_match_int (struct lexer *lexer, int x)
824 {
825   if (lex_is_integer (lexer) && lex_integer (lexer) == x)
826     {
827       lex_get (lexer);
828       return true;
829     }
830   else
831     return false;
832 }
833 \f
834 /* Forced matches. */
835
836 /* If this token is IDENTIFIER, skips it and returns true.  IDENTIFIER may be
837    abbreviated to its first 3 letters.  Otherwise, reports an error and returns
838    false.
839
840    IDENTIFIER must be an ASCII string. */
841 bool
842 lex_force_match_id (struct lexer *lexer, const char *identifier)
843 {
844   if (lex_match_id (lexer, identifier))
845     return true;
846   else
847     {
848       lex_error_expecting (lexer, identifier);
849       return false;
850     }
851 }
852
853 /* If the current token has the specified TYPE, skips it and returns true.
854    Otherwise, reports an error and returns false. */
855 bool
856 lex_force_match (struct lexer *lexer, enum token_type type)
857 {
858   if (lex_token (lexer) == type)
859     {
860       lex_get (lexer);
861       return true;
862     }
863   else
864     {
865       const char *type_string = token_type_to_string (type);
866       if (type_string)
867         {
868           char *s = xasprintf ("`%s'", type_string);
869           lex_error_expecting (lexer, s);
870           free (s);
871         }
872       else
873         lex_error_expecting (lexer, token_type_to_name (type));
874
875       return false;
876     }
877 }
878
879 /* If the current token is a string, does nothing and returns true.
880    Otherwise, reports an error and returns false. */
881 bool
882 lex_force_string (struct lexer *lexer)
883 {
884   if (lex_is_string (lexer))
885     return true;
886   else
887     {
888       lex_error (lexer, _("Syntax error expecting string."));
889       return false;
890     }
891 }
892
893 /* If the current token is a string or an identifier, does nothing and returns
894    true.  Otherwise, reports an error and returns false.
895
896    This is meant for use in syntactic situations where we want to encourage the
897    user to supply a quoted string, but for compatibility we also accept
898    identifiers.  (One example of such a situation is file names.)  Therefore,
899    the error message issued when the current token is wrong only says that a
900    string is expected and doesn't mention that an identifier would also be
901    accepted. */
902 bool
903 lex_force_string_or_id (struct lexer *lexer)
904 {
905   return lex_token (lexer) == T_ID || lex_force_string (lexer);
906 }
907
908 /* If the current token is an integer, does nothing and returns true.
909    Otherwise, reports an error and returns false. */
910 bool
911 lex_force_int (struct lexer *lexer)
912 {
913   if (lex_is_integer (lexer))
914     return true;
915   else
916     {
917       lex_error (lexer, _("Syntax error expecting integer."));
918       return false;
919     }
920 }
921
922 /* If the current token is an integer in the range MIN...MAX (inclusive), does
923    nothing and returns true.  Otherwise, reports an error and returns false.
924    If NAME is nonnull, then it is used in the error message. */
925 bool
926 lex_force_int_range (struct lexer *lexer, const char *name, long min, long max)
927 {
928   bool is_number = lex_is_number (lexer);
929   bool is_integer = lex_is_integer (lexer);
930   bool too_small = (is_integer ? lex_integer (lexer) < min
931                     : is_number ? lex_number (lexer) < min
932                     : false);
933   bool too_big = (is_integer ? lex_integer (lexer) > max
934                   : is_number ? lex_number (lexer) > max
935                   : false);
936   if (is_integer && !too_small && !too_big)
937     return true;
938
939   if (min > max)
940     {
941       /* Weird, maybe a bug in the caller.  Just report that we needed an
942          integer. */
943       if (name)
944         lex_error (lexer, _("Syntax error expecting integer for %s."), name);
945       else
946         lex_error (lexer, _("Syntax error expecting integer."));
947     }
948   else if (min == max)
949     {
950       if (name)
951         lex_error (lexer, _("Syntax error expecting %ld for %s."), min, name);
952       else
953         lex_error (lexer, _("Syntax error expecting %ld."), min);
954     }
955   else if (min + 1 == max)
956     {
957       if (name)
958         lex_error (lexer, _("Syntax error expecting %ld or %ld for %s."),
959                    min, min + 1, name);
960       else
961         lex_error (lexer, _("Syntax error expecting %ld or %ld."),
962                    min, min + 1);
963     }
964   else
965     {
966       bool report_lower_bound = (min > INT_MIN / 2) || too_small;
967       bool report_upper_bound = (max < INT_MAX / 2) || too_big;
968
969       if (report_lower_bound && report_upper_bound)
970         {
971           if (name)
972             lex_error (lexer,
973                        _("Syntax error expecting integer "
974                          "between %ld and %ld for %s."),
975                        min, max, name);
976           else
977             lex_error (lexer, _("Syntax error expecting integer "
978                                 "between %ld and %ld."),
979                        min, max);
980         }
981       else if (report_lower_bound)
982         {
983           if (min == 0)
984             {
985               if (name)
986                 lex_error (lexer, _("Syntax error expecting "
987                                     "non-negative integer for %s."),
988                            name);
989               else
990                 lex_error (lexer, _("Syntax error expecting "
991                                     "non-negative integer."));
992             }
993           else if (min == 1)
994             {
995               if (name)
996                 lex_error (lexer, _("Syntax error expecting "
997                                     "positive integer for %s."),
998                            name);
999               else
1000                 lex_error (lexer, _("Syntax error expecting "
1001                                     "positive integer."));
1002             }
1003           else
1004             {
1005               if (name)
1006                 lex_error (lexer, _("Syntax error expecting "
1007                                     "integer %ld or greater for %s."),
1008                            min, name);
1009               else
1010                 lex_error (lexer, _("Syntax error expecting "
1011                                     "integer %ld or greater."), min);
1012             }
1013         }
1014       else if (report_upper_bound)
1015         {
1016           if (name)
1017             lex_error (lexer,
1018                        _("Syntax error expecting integer less than or equal "
1019                          "to %ld for %s."),
1020                        max, name);
1021           else
1022             lex_error (lexer, _("Syntax error expecting integer less than or "
1023                                 "equal to %ld."),
1024                        max);
1025         }
1026       else
1027         {
1028           if (name)
1029             lex_error (lexer, _("Syntax error expecting integer for %s."),
1030                        name);
1031           else
1032             lex_error (lexer, _("Syntax error expecting integer."));
1033         }
1034     }
1035   return false;
1036 }
1037
1038 /* If the current token is a number, does nothing and returns true.
1039    Otherwise, reports an error and returns false. */
1040 bool
1041 lex_force_num (struct lexer *lexer)
1042 {
1043   if (lex_is_number (lexer))
1044     return true;
1045
1046   lex_error (lexer, _("Syntax error expecting number."));
1047   return false;
1048 }
1049
1050 /* If the current token is an number in the closed range [MIN,MAX], does
1051    nothing and returns true.  Otherwise, reports an error and returns false.
1052    If NAME is nonnull, then it is used in the error message. */
1053 bool
1054 lex_force_num_range_closed (struct lexer *lexer, const char *name,
1055                             double min, double max)
1056 {
1057   bool is_number = lex_is_number (lexer);
1058   bool too_small = is_number && lex_number (lexer) < min;
1059   bool too_big = is_number && lex_number (lexer) > max;
1060   if (is_number && !too_small && !too_big)
1061     return true;
1062
1063   if (min > max)
1064     {
1065       /* Weird, maybe a bug in the caller.  Just report that we needed an
1066          number. */
1067       if (name)
1068         lex_error (lexer, _("Syntax error expecting number for %s."), name);
1069       else
1070         lex_error (lexer, _("Syntax error expecting number."));
1071     }
1072   else if (min == max)
1073     {
1074       if (name)
1075         lex_error (lexer, _("Syntax error expecting number %g for %s."),
1076                    min, name);
1077       else
1078         lex_error (lexer, _("Syntax error expecting number %g."), min);
1079     }
1080   else
1081     {
1082       bool report_lower_bound = min > -DBL_MAX || too_small;
1083       bool report_upper_bound = max < DBL_MAX || too_big;
1084
1085       if (report_lower_bound && report_upper_bound)
1086         {
1087           if (name)
1088             lex_error (lexer,
1089                        _("Syntax error expecting number "
1090                          "between %g and %g for %s."),
1091                        min, max, name);
1092           else
1093             lex_error (lexer, _("Syntax error expecting number "
1094                                 "between %g and %g."),
1095                        min, max);
1096         }
1097       else if (report_lower_bound)
1098         {
1099           if (min == 0)
1100             {
1101               if (name)
1102                 lex_error (lexer, _("Syntax error expecting "
1103                                     "non-negative number for %s."),
1104                            name);
1105               else
1106                 lex_error (lexer, _("Syntax error expecting "
1107                                     "non-negative number."));
1108             }
1109           else
1110             {
1111               if (name)
1112                 lex_error (lexer, _("Syntax error expecting number "
1113                                     "%g or greater for %s."),
1114                            min, name);
1115               else
1116                 lex_error (lexer, _("Syntax error expecting number "
1117                                     "%g or greater."), min);
1118             }
1119         }
1120       else if (report_upper_bound)
1121         {
1122           if (name)
1123             lex_error (lexer,
1124                        _("Syntax error expecting number "
1125                          "less than or equal to %g for %s."),
1126                        max, name);
1127           else
1128             lex_error (lexer, _("Syntax error expecting number "
1129                                 "less than or equal to %g."),
1130                        max);
1131         }
1132       else
1133         {
1134           if (name)
1135             lex_error (lexer, _("Syntax error expecting number for %s."), name);
1136           else
1137             lex_error (lexer, _("Syntax error expecting number."));
1138         }
1139     }
1140   return false;
1141 }
1142
1143 /* If the current token is an number in the half-open range [MIN,MAX), does
1144    nothing and returns true.  Otherwise, reports an error and returns false.
1145    If NAME is nonnull, then it is used in the error message. */
1146 bool
1147 lex_force_num_range_halfopen (struct lexer *lexer, const char *name,
1148                               double min, double max)
1149 {
1150   bool is_number = lex_is_number (lexer);
1151   bool too_small = is_number && lex_number (lexer) < min;
1152   bool too_big = is_number && lex_number (lexer) >= max;
1153   if (is_number && !too_small && !too_big)
1154     return true;
1155
1156   if (min >= max)
1157     {
1158       /* Weird, maybe a bug in the caller.  Just report that we needed an
1159          number. */
1160       if (name)
1161         lex_error (lexer, _("Syntax error expecting number for %s."), name);
1162       else
1163         lex_error (lexer, _("Syntax error expecting number."));
1164     }
1165   else
1166     {
1167       bool report_lower_bound = min > -DBL_MAX || too_small;
1168       bool report_upper_bound = max < DBL_MAX || too_big;
1169
1170       if (report_lower_bound && report_upper_bound)
1171         {
1172           if (name)
1173             lex_error (lexer, _("Syntax error expecting number "
1174                                 "in [%g,%g) for %s."),
1175                        min, max, name);
1176           else
1177             lex_error (lexer, _("Syntax error expecting number in [%g,%g)."),
1178                        min, max);
1179         }
1180       else if (report_lower_bound)
1181         {
1182           if (min == 0)
1183             {
1184               if (name)
1185                 lex_error (lexer, _("Syntax error expecting "
1186                                     "non-negative number for %s."),
1187                            name);
1188               else
1189                 lex_error (lexer, _("Syntax error expecting "
1190                                     "non-negative number."));
1191             }
1192           else
1193             {
1194               if (name)
1195                 lex_error (lexer, _("Syntax error expecting "
1196                                     "number %g or greater for %s."),
1197                            min, name);
1198               else
1199                 lex_error (lexer, _("Syntax error expecting "
1200                                     "number %g or greater."), min);
1201             }
1202         }
1203       else if (report_upper_bound)
1204         {
1205           if (name)
1206             lex_error (lexer,
1207                        _("Syntax error expecting "
1208                          "number less than %g for %s."), max, name);
1209           else
1210             lex_error (lexer, _("Syntax error expecting "
1211                                 "number less than %g."), max);
1212         }
1213       else
1214         {
1215           if (name)
1216             lex_error (lexer, _("Syntax error expecting number for %s."), name);
1217           else
1218             lex_error (lexer, _("Syntax error expecting number."));
1219         }
1220     }
1221   return false;
1222 }
1223
1224 /* If the current token is an number in the open range (MIN,MAX), does
1225    nothing and returns true.  Otherwise, reports an error and returns false.
1226    If NAME is nonnull, then it is used in the error message. */
1227 bool
1228 lex_force_num_range_open (struct lexer *lexer, const char *name,
1229                           double min, double max)
1230 {
1231   bool is_number = lex_is_number (lexer);
1232   bool too_small = is_number && lex_number (lexer) <= min;
1233   bool too_big = is_number && lex_number (lexer) >= max;
1234   if (is_number && !too_small && !too_big)
1235     return true;
1236
1237   if (min >= max)
1238     {
1239       /* Weird, maybe a bug in the caller.  Just report that we needed an
1240          number. */
1241       if (name)
1242         lex_error (lexer, _("Syntax error expecting number for %s."), name);
1243       else
1244         lex_error (lexer, _("Syntax error expecting number."));
1245     }
1246   else
1247     {
1248       bool report_lower_bound = min > -DBL_MAX || too_small;
1249       bool report_upper_bound = max < DBL_MAX || too_big;
1250
1251       if (report_lower_bound && report_upper_bound)
1252         {
1253           if (name)
1254             lex_error (lexer, _("Syntax error expecting number "
1255                                 "in (%g,%g) for %s."),
1256                        min, max, name);
1257           else
1258             lex_error (lexer, _("Syntax error expecting number "
1259                                 "in (%g,%g)."), min, max);
1260         }
1261       else if (report_lower_bound)
1262         {
1263           if (min == 0)
1264             {
1265               if (name)
1266                 lex_error (lexer, _("Syntax error expecting "
1267                                     "positive number for %s."), name);
1268               else
1269                 lex_error (lexer, _("Syntax error expecting "
1270                                     "positive number."));
1271             }
1272           else
1273             {
1274               if (name)
1275                 lex_error (lexer, _("Syntax error expecting number "
1276                                     "greater than %g for %s."),
1277                            min, name);
1278               else
1279                 lex_error (lexer, _("Syntax error expecting number "
1280                                     "greater than %g."), min);
1281             }
1282         }
1283       else if (report_upper_bound)
1284         {
1285           if (name)
1286             lex_error (lexer, _("Syntax error expecting number "
1287                                 "less than %g for %s."),
1288                        max, name);
1289           else
1290             lex_error (lexer, _("Syntax error expecting number "
1291                                 "less than %g."), max);
1292         }
1293       else
1294         {
1295           if (name)
1296             lex_error (lexer, _("Syntax error expecting number "
1297                                 "for %s."), name);
1298           else
1299             lex_error (lexer, _("Syntax error expecting number."));
1300         }
1301     }
1302   return false;
1303 }
1304
1305 /* If the current token is an identifier, does nothing and returns true.
1306    Otherwise, reports an error and returns false. */
1307 bool
1308 lex_force_id (struct lexer *lexer)
1309 {
1310   if (lex_token (lexer) == T_ID)
1311     return true;
1312
1313   lex_error (lexer, _("Syntax error expecting identifier."));
1314   return false;
1315 }
1316 \f
1317 /* Token accessors. */
1318
1319 /* Returns the type of LEXER's current token. */
1320 enum token_type
1321 lex_token (const struct lexer *lexer)
1322 {
1323   return lex_next_token (lexer, 0);
1324 }
1325
1326 /* Returns the number in LEXER's current token.
1327
1328    Only T_NEG_NUM and T_POS_NUM tokens have meaningful values.  For other
1329    tokens this function will always return zero. */
1330 double
1331 lex_tokval (const struct lexer *lexer)
1332 {
1333   return lex_next_tokval (lexer, 0);
1334 }
1335
1336 /* Returns the null-terminated string in LEXER's current token, UTF-8 encoded.
1337
1338    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
1339    this functions this function will always return NULL.
1340
1341    The UTF-8 encoding of the returned string is correct for variable names and
1342    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
1343    data_in() to use it in a "union value".  */
1344 const char *
1345 lex_tokcstr (const struct lexer *lexer)
1346 {
1347   return lex_next_tokcstr (lexer, 0);
1348 }
1349
1350 /* Returns the string in LEXER's current token, UTF-8 encoded.  The string is
1351    null-terminated (but the null terminator is not included in the returned
1352    substring's 'length').
1353
1354    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
1355    this functions this function will always return NULL.
1356
1357    The UTF-8 encoding of the returned string is correct for variable names and
1358    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
1359    data_in() to use it in a "union value".  */
1360 struct substring
1361 lex_tokss (const struct lexer *lexer)
1362 {
1363   return lex_next_tokss (lexer, 0);
1364 }
1365 \f
1366 /* Looking ahead.
1367
1368    A value of 0 for N as an argument to any of these functions refers to the
1369    current token.  Lookahead is limited to the current command.  Any N greater
1370    than the number of tokens remaining in the current command will be treated
1371    as referring to a T_ENDCMD token. */
1372
1373 static const struct lex_token *
1374 lex_next__ (const struct lexer *lexer_, int n)
1375 {
1376   struct lexer *lexer = CONST_CAST (struct lexer *, lexer_);
1377   struct lex_source *src = lex_source__ (lexer);
1378
1379   if (src != NULL)
1380     return lex_source_next__ (src, n);
1381   else
1382     {
1383       static const struct lex_token stop_token = { .token = { .type = T_STOP } };
1384       return &stop_token;
1385     }
1386 }
1387
1388 static const struct lex_token *
1389 lex_source_ofs__ (const struct lex_source *src_, int ofs)
1390 {
1391   struct lex_source *src = CONST_CAST (struct lex_source *, src_);
1392
1393   if (ofs < 0)
1394     {
1395       static const struct lex_token endcmd_token
1396         = { .token = { .type = T_ENDCMD } };
1397       return &endcmd_token;
1398     }
1399
1400   while (ofs >= src->n_parse)
1401     {
1402       if (src->n_parse > 0)
1403         {
1404           const struct lex_token *t = src->parse[src->n_parse - 1];
1405           if (t->token.type == T_STOP || t->token.type == T_ENDCMD)
1406             return t;
1407         }
1408
1409       lex_source_get_parse (src);
1410     }
1411
1412   return src->parse[ofs];
1413 }
1414
1415 static const struct lex_token *
1416 lex_source_next__ (const struct lex_source *src, int n)
1417 {
1418   return lex_source_ofs__ (src, n + src->parse_ofs);
1419 }
1420
1421 /* Returns the "struct token" of the token N after the current one in LEXER.
1422    The returned pointer can be invalidated by pretty much any succeeding call
1423    into the lexer, although the string pointer within the returned token is
1424    only invalidated by consuming the token (e.g. with lex_get()). */
1425 const struct token *
1426 lex_next (const struct lexer *lexer, int n)
1427 {
1428   return &lex_next__ (lexer, n)->token;
1429 }
1430
1431 /* Returns the type of the token N after the current one in LEXER. */
1432 enum token_type
1433 lex_next_token (const struct lexer *lexer, int n)
1434 {
1435   return lex_next (lexer, n)->type;
1436 }
1437
1438 /* Returns the number in the tokn N after the current one in LEXER.
1439
1440    Only T_NEG_NUM and T_POS_NUM tokens have meaningful values.  For other
1441    tokens this function will always return zero. */
1442 double
1443 lex_next_tokval (const struct lexer *lexer, int n)
1444 {
1445   return token_number (lex_next (lexer, n));
1446 }
1447
1448 /* Returns the null-terminated string in the token N after the current one, in
1449    UTF-8 encoding.
1450
1451    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
1452    this functions this function will always return NULL.
1453
1454    The UTF-8 encoding of the returned string is correct for variable names and
1455    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
1456    data_in() to use it in a "union value".  */
1457 const char *
1458 lex_next_tokcstr (const struct lexer *lexer, int n)
1459 {
1460   return lex_next_tokss (lexer, n).string;
1461 }
1462
1463 /* Returns the string in the token N after the current one, in UTF-8 encoding.
1464    The string is null-terminated (but the null terminator is not included in
1465    the returned substring's 'length').
1466
1467    Only T_ID, T_MACRO_ID, T_STRING tokens have meaningful strings.  For other
1468    tokens this functions this function will always return NULL.
1469
1470    The UTF-8 encoding of the returned string is correct for variable names and
1471    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
1472    data_in() to use it in a "union value".  */
1473 struct substring
1474 lex_next_tokss (const struct lexer *lexer, int n)
1475 {
1476   return lex_next (lexer, n)->string;
1477 }
1478
1479 /* Returns the offset of the current token within the command being parsed in
1480    LEXER.  This is 0 for the first token in a command, 1 for the second, and so
1481    on.  The return value is useful later for referring to this token in calls
1482    to lex_ofs_*(). */
1483 int
1484 lex_ofs (const struct lexer *lexer)
1485 {
1486   struct lex_source *src = lex_source__ (lexer);
1487   return src ? src->parse_ofs : 0;
1488 }
1489
1490 /* Returns the offset of the last token in the current command. */
1491 int
1492 lex_max_ofs (const struct lexer *lexer)
1493 {
1494   struct lex_source *src = lex_source__ (lexer);
1495   if (!src)
1496     return 0;
1497
1498   int ofs = MAX (1, src->n_parse) - 1;
1499   for (;;)
1500     {
1501       enum token_type type = lex_source_ofs__ (src, ofs)->token.type;
1502       if (type == T_ENDCMD || type == T_STOP)
1503         return ofs;
1504
1505       ofs++;
1506     }
1507 }
1508
1509 /* Returns the token within LEXER's current command with offset OFS.  Use
1510    lex_ofs() to find out the offset of the current token. */
1511 const struct token *
1512 lex_ofs_token (const struct lexer *lexer_, int ofs)
1513 {
1514   struct lexer *lexer = CONST_CAST (struct lexer *, lexer_);
1515   struct lex_source *src = lex_source__ (lexer);
1516
1517   if (src != NULL)
1518     return &lex_source_next__ (src, ofs - src->parse_ofs)->token;
1519   else
1520     {
1521       static const struct token stop_token = { .type = T_STOP };
1522       return &stop_token;
1523     }
1524 }
1525
1526 /* Allocates and returns a new struct msg_location that spans tokens with
1527    offsets OFS0 through OFS1, inclusive, within the current command in
1528    LEXER.  See lex_ofs() for an explanation of token offsets.
1529
1530    The caller owns and must eventually free the returned object. */
1531 struct msg_location *
1532 lex_ofs_location (const struct lexer *lexer, int ofs0, int ofs1)
1533 {
1534   int ofs = lex_ofs (lexer);
1535   return lex_get_location (lexer, ofs0 - ofs, ofs1 - ofs);
1536 }
1537
1538 /* Returns a msg_point for the first character in the token with offset OFS,
1539    where offset 0 is the first token in the command currently being parsed, 1
1540    the second token, and so on.  These are absolute offsets, not relative to
1541    the token currently being parsed within the command.
1542
1543    Returns zeros for a T_STOP token.
1544  */
1545 struct msg_point
1546 lex_ofs_start_point (const struct lexer *lexer, int ofs)
1547 {
1548   const struct lex_source *src = lex_source__ (lexer);
1549   return (src
1550           ? lex_token_start_point (src, lex_source_ofs__ (src, ofs))
1551           : (struct msg_point) { 0, 0 });
1552 }
1553
1554 /* Returns a msg_point for the last character, inclusive, in the token with
1555    offset OFS, where offset 0 is the first token in the command currently being
1556    parsed, 1 the second token, and so on.  These are absolute offsets, not
1557    relative to the token currently being parsed within the command.
1558
1559    Returns zeros for a T_STOP token.
1560
1561    Most of the time, a single token is wholly within a single line of syntax,
1562    so that the start and end point for a given offset have the same line
1563    number.  There are two exceptions: a T_STRING token can be made up of
1564    multiple segments on adjacent lines connected with "+" punctuators, and a
1565    T_NEG_NUM token can consist of a "-" on one line followed by the number on
1566    the next.
1567  */
1568 struct msg_point
1569 lex_ofs_end_point (const struct lexer *lexer, int ofs)
1570 {
1571   const struct lex_source *src = lex_source__ (lexer);
1572   return (src
1573           ? lex_token_end_point (src, lex_source_ofs__ (src, ofs))
1574           : (struct msg_point) { 0, 0 });
1575 }
1576
1577 /* Returns the text of the syntax in tokens N0 ahead of the current one,
1578    through N1 ahead of the current one, inclusive.  (For example, if N0 and N1
1579    are both zero, this requests the syntax for the current token.)
1580
1581    The caller must eventually free the returned string (with free()).  The
1582    syntax is encoded in UTF-8 and in the original form supplied to the lexer so
1583    that, for example, it may include comments, spaces, and new-lines if it
1584    spans multiple tokens.  Macro expansion, however, has already been
1585    performed. */
1586 char *
1587 lex_next_representation (const struct lexer *lexer, int n0, int n1)
1588 {
1589   const struct lex_source *src = lex_source__ (lexer);
1590   return (src
1591           ? lex_source_syntax__ (src, n0 + src->parse_ofs, n1 + src->parse_ofs)
1592           : xstrdup (""));
1593 }
1594
1595
1596 /* Returns the text of the syntax in tokens with offsets OFS0 to OFS1,
1597    inclusive.  (For example, if OFS0 and OFS1 are both zero, this requests the
1598    syntax for the first token in the current command.)
1599
1600    The caller must eventually free the returned string (with free()).  The
1601    syntax is encoded in UTF-8 and in the original form supplied to the lexer so
1602    that, for example, it may include comments, spaces, and new-lines if it
1603    spans multiple tokens.  Macro expansion, however, has already been
1604    performed. */
1605 char *
1606 lex_ofs_representation (const struct lexer *lexer, int ofs0, int ofs1)
1607 {
1608   const struct lex_source *src = lex_source__ (lexer);
1609   return src ? lex_source_syntax__ (src, ofs0, ofs1) : xstrdup ("");
1610 }
1611
1612 /* Returns true if the token N ahead of the current one was produced by macro
1613    expansion, false otherwise. */
1614 bool
1615 lex_next_is_from_macro (const struct lexer *lexer, int n)
1616 {
1617   return lex_next__ (lexer, n)->macro_rep != NULL;
1618 }
1619
1620 static bool
1621 lex_tokens_match (const struct token *actual, const struct token *expected)
1622 {
1623   if (actual->type != expected->type)
1624     return false;
1625
1626   switch (actual->type)
1627     {
1628     case T_POS_NUM:
1629     case T_NEG_NUM:
1630       return actual->number == expected->number;
1631
1632     case T_ID:
1633       return lex_id_match (expected->string, actual->string);
1634
1635     case T_STRING:
1636       return (actual->string.length == expected->string.length
1637               && !memcmp (actual->string.string, expected->string.string,
1638                           actual->string.length));
1639
1640     default:
1641       return true;
1642     }
1643 }
1644
1645 static bool
1646 lex_ofs_at_phrase__ (struct lexer *lexer, int ofs, const char *s,
1647                      size_t *n_matchedp)
1648 {
1649   struct string_lexer slex;
1650   struct token token;
1651
1652   size_t n_matched = 0;
1653   bool all_matched = true;
1654   string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE, true);
1655   while (string_lexer_next (&slex, &token))
1656     {
1657       bool match = lex_tokens_match (lex_ofs_token (lexer, ofs + n_matched),
1658                                      &token);
1659       token_uninit (&token);
1660       if (!match)
1661         {
1662           all_matched = false;
1663           break;
1664         }
1665       n_matched++;
1666     }
1667   if (n_matchedp)
1668     *n_matchedp = n_matched;
1669   return all_matched;
1670 }
1671
1672 /* If LEXER is positioned at the sequence of tokens that may be parsed from S,
1673    returns true.  Otherwise, returns false.
1674
1675    S may consist of an arbitrary sequence of tokens, e.g. "KRUSKAL-WALLIS",
1676    "2SLS", or "END INPUT PROGRAM".  Identifiers may be abbreviated to their
1677    first three letters. */
1678 bool
1679 lex_at_phrase (struct lexer *lexer, const char *s)
1680 {
1681   return lex_ofs_at_phrase__ (lexer, lex_ofs (lexer), s, NULL);
1682 }
1683
1684 /* If LEXER is positioned at the sequence of tokens that may be parsed from S,
1685    skips it and returns true.  Otherwise, returns false.
1686
1687    S may consist of an arbitrary sequence of tokens, e.g. "KRUSKAL-WALLIS",
1688    "2SLS", or "END INPUT PROGRAM".  Identifiers may be abbreviated to their
1689    first three letters. */
1690 bool
1691 lex_match_phrase (struct lexer *lexer, const char *s)
1692 {
1693   size_t n_matched;
1694   if (!lex_ofs_at_phrase__ (lexer, lex_ofs (lexer), s, &n_matched))
1695     return false;
1696   lex_get_n (lexer, n_matched);
1697   return true;
1698 }
1699
1700 /* If LEXER is positioned at the sequence of tokens that may be parsed from S,
1701    skips it and returns true.  Otherwise, issues an error and returns false.
1702
1703    S may consist of an arbitrary sequence of tokens, e.g. "KRUSKAL-WALLIS",
1704    "2SLS", or "END INPUT PROGRAM".  Identifiers may be abbreviated to their
1705    first three letters. */
1706 bool
1707 lex_force_match_phrase (struct lexer *lexer, const char *s)
1708 {
1709   size_t n_matched;
1710   bool ok = lex_ofs_at_phrase__ (lexer, lex_ofs (lexer), s, &n_matched);
1711   if (ok)
1712     lex_get_n (lexer, n_matched);
1713   else
1714     lex_next_error (lexer, 0, n_matched, _("Syntax error expecting `%s'."), s);
1715   return ok;
1716 }
1717
1718 /* Returns the 1-based line number of the source text at the byte OFFSET in
1719    SRC. */
1720 static int
1721 lex_source_ofs_to_line_number (const struct lex_source *src, size_t offset)
1722 {
1723   size_t lo = 0;
1724   size_t hi = src->n_lines;
1725   for (;;)
1726     {
1727       size_t mid = (lo + hi) / 2;
1728       if (mid + 1 >= src->n_lines)
1729         return src->n_lines;
1730       else if (offset >= src->lines[mid + 1])
1731         lo = mid;
1732       else if (offset < src->lines[mid])
1733         hi = mid;
1734       else
1735         return mid + 1;
1736     }
1737 }
1738
1739 /* Returns the 1-based column number of the source text at the byte OFFSET in
1740    SRC. */
1741 static int
1742 lex_source_ofs_to_column_number (const struct lex_source *src, size_t offset)
1743 {
1744   const char *newline = memrchr (src->buffer, '\n', offset);
1745   size_t line_ofs = newline ? newline - src->buffer + 1 : 0;
1746   return utf8_count_columns (&src->buffer[line_ofs], offset - line_ofs) + 1;
1747 }
1748
1749 static struct msg_point
1750 lex_source_ofs_to_point__ (const struct lex_source *src, size_t offset)
1751 {
1752   return (struct msg_point) {
1753     .line = lex_source_ofs_to_line_number (src, offset),
1754     .column = lex_source_ofs_to_column_number (src, offset),
1755   };
1756 }
1757
1758 static struct msg_point
1759 lex_token_start_point (const struct lex_source *src,
1760                        const struct lex_token *token)
1761 {
1762   return lex_source_ofs_to_point__ (src, token->token_pos);
1763 }
1764
1765 static struct msg_point
1766 lex_token_end_point (const struct lex_source *src,
1767                      const struct lex_token *token)
1768 {
1769   return lex_source_ofs_to_point__ (src, lex_token_end (token));
1770 }
1771
1772 static struct msg_location
1773 lex_token_location (const struct lex_source *src,
1774                     const struct lex_token *t0,
1775                     const struct lex_token *t1)
1776 {
1777   return (struct msg_location) {
1778     .file_name = intern_new_if_nonnull (src->reader->file_name),
1779     .start = lex_token_start_point (src, t0),
1780     .end = lex_token_end_point (src, t1),
1781     .src = CONST_CAST (struct lex_source *, src),
1782   };
1783 }
1784
1785 static struct msg_location *
1786 lex_token_location_rw (const struct lex_source *src,
1787                        const struct lex_token *t0,
1788                        const struct lex_token *t1)
1789 {
1790   struct msg_location location = lex_token_location (src, t0, t1);
1791   return msg_location_dup (&location);
1792 }
1793
1794 static struct msg_location *
1795 lex_source_get_location (const struct lex_source *src, int ofs0, int ofs1)
1796 {
1797   return lex_token_location_rw (src,
1798                                 lex_source_ofs__ (src, ofs0),
1799                                 lex_source_ofs__ (src, ofs1));
1800 }
1801
1802 /* Returns the name of the syntax file from which the current command is drawn.
1803    Returns NULL for a T_STOP token or if the command's source does not have
1804    line numbers.
1805
1806    There is no version of this function that takes an N argument because
1807    lookahead only works to the end of a command and any given command is always
1808    within a single syntax file. */
1809 const char *
1810 lex_get_file_name (const struct lexer *lexer)
1811 {
1812   struct lex_source *src = lex_source__ (lexer);
1813   return src == NULL ? NULL : src->reader->file_name;
1814 }
1815
1816 /* Returns a newly allocated msg_location for the syntax that represents tokens
1817    with 0-based offsets N0...N1, inclusive, from the current token.  The caller
1818    must eventually free the location (with msg_location_destroy()). */
1819 struct msg_location *
1820 lex_get_location (const struct lexer *lexer, int n0, int n1)
1821 {
1822   struct msg_location *loc = xmalloc (sizeof *loc);
1823   *loc = (struct msg_location) {
1824     .file_name = intern_new_if_nonnull (lex_get_file_name (lexer)),
1825     .start = lex_ofs_start_point (lexer, n0 + lex_ofs (lexer)),
1826     .end = lex_ofs_end_point (lexer, n1 + lex_ofs (lexer)),
1827     .src = lex_source__ (lexer),
1828   };
1829   lex_source_ref (loc->src);
1830   return loc;
1831 }
1832
1833 const char *
1834 lex_get_encoding (const struct lexer *lexer)
1835 {
1836   struct lex_source *src = lex_source__ (lexer);
1837   return src == NULL ? NULL : src->reader->encoding;
1838 }
1839
1840 /* Returns the syntax mode for the syntax file from which the current drawn is
1841    drawn.  Returns SEG_MODE_AUTO for a T_STOP token or if the command's source
1842    does not have line numbers.
1843
1844    There is no version of this function that takes an N argument because
1845    lookahead only works to the end of a command and any given command is always
1846    within a single syntax file. */
1847 enum segmenter_mode
1848 lex_get_syntax_mode (const struct lexer *lexer)
1849 {
1850   struct lex_source *src = lex_source__ (lexer);
1851   return src == NULL ? SEG_MODE_AUTO : src->reader->syntax;
1852 }
1853
1854 /* Returns the error mode for the syntax file from which the current drawn is
1855    drawn.  Returns LEX_ERROR_TERMINAL for a T_STOP token or if the command's
1856    source does not have line numbers.
1857
1858    There is no version of this function that takes an N argument because
1859    lookahead only works to the end of a command and any given command is always
1860    within a single syntax file. */
1861 enum lex_error_mode
1862 lex_get_error_mode (const struct lexer *lexer)
1863 {
1864   struct lex_source *src = lex_source__ (lexer);
1865   return src == NULL ? LEX_ERROR_TERMINAL : src->reader->error;
1866 }
1867
1868 /* If the source that LEXER is currently reading has error mode
1869    LEX_ERROR_TERMINAL, discards all buffered input and tokens, so that the next
1870    token to be read comes directly from whatever is next read from the stream.
1871
1872    It makes sense to call this function after encountering an error in a
1873    command entered on the console, because usually the user would prefer not to
1874    have cascading errors. */
1875 void
1876 lex_interactive_reset (struct lexer *lexer)
1877 {
1878   struct lex_source *src = lex_source__ (lexer);
1879   if (src != NULL && src->reader->error == LEX_ERROR_TERMINAL)
1880     {
1881       src->length = 0;
1882       src->journal_pos = src->seg_pos = 0;
1883       src->n_lines = 0;
1884       src->suppress_next_newline = false;
1885       src->segmenter = segmenter_init (segmenter_get_mode (&src->segmenter),
1886                                        false);
1887       lex_stage_clear (&src->pp);
1888       lex_stage_clear (&src->merge);
1889       lex_source_clear_parse (src);
1890       lex_source_push_endcmd__ (src);
1891     }
1892 }
1893
1894 /* Advances past any tokens in LEXER up to a T_ENDCMD or T_STOP. */
1895 void
1896 lex_discard_rest_of_command (struct lexer *lexer)
1897 {
1898   while (lex_token (lexer) != T_STOP && lex_token (lexer) != T_ENDCMD)
1899     lex_get (lexer);
1900 }
1901
1902 /* Discards all lookahead tokens in LEXER, then discards all input sources
1903    until it encounters one with error mode LEX_ERROR_TERMINAL or until it
1904    runs out of input sources. */
1905 void
1906 lex_discard_noninteractive (struct lexer *lexer)
1907 {
1908   struct lex_source *src = lex_source__ (lexer);
1909   if (src != NULL)
1910     {
1911       if (src->reader->error == LEX_ERROR_IGNORE)
1912         return;
1913
1914       lex_stage_clear (&src->pp);
1915       lex_stage_clear (&src->merge);
1916       lex_source_clear_parse (src);
1917
1918       for (; src != NULL && src->reader->error != LEX_ERROR_TERMINAL;
1919            src = lex_source__ (lexer))
1920         {
1921           ll_remove (&src->ll);
1922           lex_source_unref (src);
1923         }
1924     }
1925 }
1926 \f
1927 static void
1928 lex_source_expand__ (struct lex_source *src)
1929 {
1930   if (src->length >= src->allocated)
1931     src->buffer = x2realloc (src->buffer, &src->allocated);
1932 }
1933
1934 static void
1935 lex_source_read__ (struct lex_source *src)
1936 {
1937   do
1938     {
1939       lex_source_expand__ (src);
1940
1941       size_t space = src->allocated - src->length;
1942       enum prompt_style prompt = segmenter_get_prompt (&src->segmenter);
1943       size_t n = src->reader->class->read (src->reader,
1944                                            &src->buffer[src->length],
1945                                            space, prompt);
1946       assert (n <= space);
1947
1948       if (n == 0)
1949         {
1950           /* End of input. */
1951           src->reader->eof = true;
1952           return;
1953         }
1954
1955       src->length += n;
1956     }
1957   while (!memchr (&src->buffer[src->seg_pos], '\n',
1958                   src->length - src->seg_pos));
1959 }
1960
1961 static struct lex_source *
1962 lex_source__ (const struct lexer *lexer)
1963 {
1964   return (ll_is_empty (&lexer->sources) ? NULL
1965           : ll_data (ll_head (&lexer->sources), struct lex_source, ll));
1966 }
1967
1968 const struct lex_source *
1969 lex_source (const struct lexer *lexer)
1970 {
1971   return lex_source__ (lexer);
1972 }
1973
1974 /* Returns the text of the syntax in SRC for tokens with offsets OFS0 through
1975    OFS1 in the current command, inclusive.  (For example, if OFS0 and OFS1 are
1976    both zero, this requests the syntax for the first token in the current
1977    command.)  The caller must eventually free the returned string (with
1978    free()).  The syntax is encoded in UTF-8 and in the original form supplied
1979    to the lexer so that, for example, it may include comments, spaces, and
1980    new-lines if it spans multiple tokens.  Macro expansion, however, has
1981    already been performed. */
1982 static char *
1983 lex_source_syntax__ (const struct lex_source *src, int ofs0, int ofs1)
1984 {
1985   struct string s = DS_EMPTY_INITIALIZER;
1986   for (size_t i = ofs0; i <= ofs1; )
1987     {
1988       /* Find [I,J) as the longest sequence of tokens not produced by macro
1989          expansion, or otherwise the longest sequence expanded from a single
1990          macro call. */
1991       const struct lex_token *first = lex_source_ofs__ (src, i);
1992       size_t j;
1993       for (j = i + 1; j <= ofs1; j++)
1994         {
1995           const struct lex_token *cur = lex_source_ofs__ (src, j);
1996           if ((first->macro_rep != NULL) != (cur->macro_rep != NULL)
1997               || first->macro_rep != cur->macro_rep)
1998             break;
1999         }
2000       const struct lex_token *last = lex_source_ofs__ (src, j - 1);
2001
2002       /* Now add the syntax for this sequence of tokens to SRC. */
2003       if (!ds_is_empty (&s))
2004         ds_put_byte (&s, ' ');
2005       if (!first->macro_rep)
2006         {
2007           size_t start = first->token_pos;
2008           size_t end = last->token_pos + last->token_len;
2009           ds_put_substring (&s, ss_buffer (&src->buffer[start], end - start));
2010         }
2011       else
2012         {
2013           size_t start = first->ofs;
2014           size_t end = last->ofs + last->len;
2015           ds_put_substring (&s, ss_buffer (first->macro_rep + start,
2016                                            end - start));
2017         }
2018
2019       i = j;
2020     }
2021   return ds_steal_cstr (&s);
2022 }
2023
2024 static bool
2025 lex_source_contains_macro_call (struct lex_source *src, int ofs0, int ofs1)
2026 {
2027   for (int i = ofs0; i <= ofs1; i++)
2028     if (lex_source_ofs__ (src, i)->macro_rep)
2029       return true;
2030   return false;
2031 }
2032
2033 /* If tokens N0...N1 (inclusive) in SRC contains a macro call, this returns the
2034    raw UTF-8 syntax for the macro call (not for the expansion) and for any
2035    other tokens included in that range.  The syntax is encoded in UTF-8 and in
2036    the original form supplied to the lexer so that, for example, it may include
2037    comments, spaces, and new-lines if it spans multiple tokens.
2038
2039    Returns an empty string if the token range doesn't include a macro call.
2040
2041    The caller must not modify or free the returned string. */
2042 static struct substring
2043 lex_source_get_macro_call (struct lex_source *src, int ofs0, int ofs1)
2044 {
2045   if (!lex_source_contains_macro_call (src, ofs0, ofs1))
2046     return ss_empty ();
2047
2048   const struct lex_token *token0 = lex_source_ofs__ (src, ofs0);
2049   const struct lex_token *token1 = lex_source_ofs__ (src, MAX (ofs0, ofs1));
2050   size_t start = token0->token_pos;
2051   size_t end = token1->token_pos + token1->token_len;
2052
2053   return ss_buffer (&src->buffer[start], end - start);
2054 }
2055
2056 static void
2057 lex_source_msg_valist (struct lex_source *src, enum msg_class class,
2058                        int ofs0, int ofs1, const char *format, va_list args)
2059 {
2060   struct string s = DS_EMPTY_INITIALIZER;
2061
2062   if (src)
2063     {
2064       /* Get the macro call(s) that expanded to the syntax that caused the
2065          error. */
2066       char call[64];
2067       str_ellipsize (lex_source_get_macro_call (src, ofs0, ofs1),
2068                      call, sizeof call);
2069       if (call[0])
2070         ds_put_format (&s, _("In syntax expanded from `%s'"), call);
2071     }
2072   else
2073     ds_put_cstr (&s, _("At end of input"));
2074
2075   if (!ds_is_empty (&s))
2076     ds_put_cstr (&s, ": ");
2077   if (format)
2078     ds_put_vformat (&s, format, args);
2079   else
2080     ds_put_cstr (&s, _("Syntax error."));
2081
2082   if (ds_last (&s) != '.')
2083     ds_put_byte (&s, '.');
2084
2085   struct msg *m = xmalloc (sizeof *m);
2086   *m = (struct msg) {
2087     .category = msg_class_to_category (class),
2088     .severity = msg_class_to_severity (class),
2089     .location = src ? lex_source_get_location (src, ofs0, ofs1) : NULL,
2090     .text = ds_steal_cstr (&s),
2091   };
2092   msg_emit (m);
2093 }
2094
2095 static void
2096 lex_get_error (struct lex_source *src, const struct lex_token *token)
2097 {
2098   struct msg *m = xmalloc (sizeof *m);
2099   *m = (struct msg) {
2100     .category = MSG_C_SYNTAX,
2101     .severity = MSG_S_ERROR,
2102     .location = lex_token_location_rw (src, token, token),
2103     .text = ss_xstrdup (token->token.string),
2104   };
2105   msg_emit (m);
2106 }
2107
2108 /* Attempts to append an additional token to 'pp' in SRC, reading more from the
2109    underlying lex_reader if necessary.  Returns true if a new token was added
2110    to SRC's deque, false otherwise.  The caller should retry failures unless
2111    SRC's 'eof' marker was set to true indicating that there will be no more
2112    tokens from this source. */
2113 static bool
2114 lex_source_try_get_pp (struct lex_source *src)
2115 {
2116   /* Append a new token to SRC and initialize it. */
2117   struct lex_token *token = xmalloc (sizeof *token);
2118   token->token = (struct token) { .type = T_STOP };
2119   token->macro_rep = NULL;
2120   token->ref_cnt = NULL;
2121   token->token_pos = src->seg_pos;
2122
2123   /* Extract a segment. */
2124   const char *segment;
2125   enum segment_type seg_type;
2126   int seg_len;
2127   for (;;)
2128     {
2129       segment = &src->buffer[src->seg_pos];
2130       seg_len = segmenter_push (&src->segmenter, segment,
2131                                 src->length - src->seg_pos,
2132                                 src->reader->eof, &seg_type);
2133       if (seg_len >= 0)
2134         break;
2135
2136       /* The segmenter needs more input to produce a segment. */
2137       assert (!src->reader->eof);
2138       lex_source_read__ (src);
2139     }
2140
2141   /* Update state based on the segment. */
2142   token->token_len = seg_len;
2143   src->seg_pos += seg_len;
2144   if (seg_type == SEG_NEWLINE)
2145     {
2146       if (src->n_lines >= src->allocated_lines)
2147         src->lines = x2nrealloc (src->lines, &src->allocated_lines,
2148                                  sizeof *src->lines);
2149       src->lines[src->n_lines++] = src->seg_pos;
2150     }
2151
2152   /* Get a token from the segment. */
2153   enum tokenize_result result = token_from_segment (
2154     seg_type, ss_buffer (segment, seg_len), &token->token);
2155
2156   /* If we've reached the end of a line, or the end of a command, then pass
2157      the line to the output engine as a syntax text item.  */
2158   int n_lines = seg_type == SEG_NEWLINE;
2159   if (seg_type == SEG_END_COMMAND && !src->suppress_next_newline)
2160     {
2161       n_lines++;
2162       src->suppress_next_newline = true;
2163     }
2164   else if (n_lines > 0 && src->suppress_next_newline)
2165     {
2166       n_lines--;
2167       src->suppress_next_newline = false;
2168     }
2169   for (int i = 0; i < n_lines; i++)
2170     {
2171       /* Beginning of line. */
2172       const char *line = &src->buffer[src->journal_pos];
2173
2174       /* Calculate line length, including \n or \r\n end-of-line if present.
2175
2176          We use src->length even though that may be beyond what we've actually
2177          converted to tokens.  That's because, if we're emitting the line due
2178          to SEG_END_COMMAND, we want to take the whole line through the
2179          newline, not just through the '.'. */
2180       size_t max_len = src->length - src->journal_pos;
2181       const char *newline = memchr (line, '\n', max_len);
2182       size_t line_len = newline ? newline - line + 1 : max_len;
2183
2184       /* Calculate line length excluding end-of-line. */
2185       size_t copy_len = line_len;
2186       if (copy_len > 0 && line[copy_len - 1] == '\n')
2187         copy_len--;
2188       if (copy_len > 0 && line[copy_len - 1] == '\r')
2189         copy_len--;
2190
2191       /* Submit the line as syntax. */
2192       output_item_submit (text_item_create_nocopy (TEXT_ITEM_SYNTAX,
2193                                                    xmemdup0 (line, copy_len),
2194                                                    NULL));
2195
2196       src->journal_pos += line_len;
2197     }
2198
2199   switch (result)
2200     {
2201     case TOKENIZE_ERROR:
2202       lex_get_error (src, token);
2203       /* Fall through. */
2204     case TOKENIZE_EMPTY:
2205       lex_token_destroy (token);
2206       return false;
2207
2208     case TOKENIZE_TOKEN:
2209       if (token->token.type == T_STOP)
2210         {
2211           token->token.type = T_ENDCMD;
2212           src->eof = true;
2213         }
2214       lex_stage_push_last (&src->pp, token);
2215       return true;
2216     }
2217   NOT_REACHED ();
2218 }
2219
2220 /* Attempts to append a new token to SRC.  Returns true if successful, false on
2221    failure.  On failure, the end of SRC has been reached and no more tokens
2222    will be forthcoming from it.
2223
2224    Does not make the new token available for lookahead yet; the caller must
2225    adjust SRC's 'middle' pointer to do so. */
2226 static bool
2227 lex_source_get_pp (struct lex_source *src)
2228 {
2229   while (!src->eof)
2230     if (lex_source_try_get_pp (src))
2231       return true;
2232   return false;
2233 }
2234
2235 static bool
2236 lex_source_try_get_merge (const struct lex_source *src_)
2237 {
2238   struct lex_source *src = CONST_CAST (struct lex_source *, src_);
2239
2240   if (lex_stage_is_empty (&src->pp) && !lex_source_get_pp (src))
2241     return false;
2242
2243   if (!settings_get_mexpand ())
2244     {
2245       lex_stage_shift (&src->merge, &src->pp, lex_stage_count (&src->pp));
2246       return true;
2247     }
2248
2249   /* Now pass tokens one-by-one to the macro expander.
2250
2251      In the common case where there is no macro to expand, the loop is not
2252      entered.  */
2253   struct macro_call *mc;
2254   int n_call = macro_call_create (src->lexer->macros,
2255                                   &lex_stage_first (&src->pp)->token, &mc);
2256   for (int ofs = 1; !n_call; ofs++)
2257     {
2258       if (lex_stage_count (&src->pp) <= ofs && !lex_source_get_pp (src))
2259         {
2260           /* This should not be reachable because we always get a T_ENDCMD at
2261              the end of an input file (transformed from T_STOP by
2262              lex_source_try_get_pp()) and the macro_expander should always
2263              terminate expansion on T_ENDCMD. */
2264           NOT_REACHED ();
2265         }
2266
2267       const struct lex_token *t = lex_stage_nth (&src->pp, ofs);
2268       const struct macro_token mt = {
2269         .token = t->token,
2270         .syntax = ss_buffer (&src->buffer[t->token_pos], t->token_len),
2271       };
2272       const struct msg_location loc = lex_token_location (src, t, t);
2273       n_call = macro_call_add (mc, &mt, &loc);
2274     }
2275   if (n_call < 0)
2276     {
2277       /* False alarm: no macro expansion after all.  Use first token as
2278          lookahead.  We'll retry macro expansion from the second token next
2279          time around. */
2280       macro_call_destroy (mc);
2281       lex_stage_shift (&src->merge, &src->pp, 1);
2282       return true;
2283     }
2284
2285   /* The first 'n_call' tokens in 'pp', which we bracket as C0...C1, inclusive,
2286      are a macro call.  (These are likely to be the only tokens in 'pp'.)
2287      Expand them.  */
2288   const struct lex_token *c0 = lex_stage_first (&src->pp);
2289   const struct lex_token *c1 = lex_stage_nth (&src->pp, n_call - 1);
2290   struct macro_tokens expansion = { .n = 0 };
2291   struct msg_location loc = lex_token_location (src, c0, c1);
2292   macro_call_expand (mc, src->reader->syntax, &loc, &expansion);
2293   macro_call_destroy (mc);
2294
2295   /* Convert the macro expansion into syntax for possible error messages
2296      later. */
2297   size_t *ofs = xnmalloc (expansion.n, sizeof *ofs);
2298   size_t *len = xnmalloc (expansion.n, sizeof *len);
2299   struct string s = DS_EMPTY_INITIALIZER;
2300   macro_tokens_to_syntax (&expansion, &s, ofs, len);
2301
2302   if (settings_get_mprint ())
2303     output_item_submit (text_item_create (TEXT_ITEM_LOG, ds_cstr (&s),
2304                                           _("Macro Expansion")));
2305
2306   /* Append the macro expansion tokens to the lookahead. */
2307   if (expansion.n > 0)
2308     {
2309       char *macro_rep = ds_steal_cstr (&s);
2310       size_t *ref_cnt = xmalloc (sizeof *ref_cnt);
2311       *ref_cnt = expansion.n;
2312       for (size_t i = 0; i < expansion.n; i++)
2313         {
2314           struct lex_token *token = xmalloc (sizeof *token);
2315           *token = (struct lex_token) {
2316             .token = expansion.mts[i].token,
2317             .token_pos = c0->token_pos,
2318             .token_len = (c1->token_pos + c1->token_len) - c0->token_pos,
2319             .macro_rep = macro_rep,
2320             .ofs = ofs[i],
2321             .len = len[i],
2322             .ref_cnt = ref_cnt,
2323           };
2324           lex_stage_push_last (&src->merge, token);
2325
2326           ss_dealloc (&expansion.mts[i].syntax);
2327         }
2328     }
2329   else
2330     ds_destroy (&s);
2331   free (expansion.mts);
2332   free (ofs);
2333   free (len);
2334
2335   /* Destroy the tokens for the call. */
2336   for (size_t i = 0; i < n_call; i++)
2337     lex_stage_pop_first (&src->pp);
2338
2339   return expansion.n > 0;
2340 }
2341
2342 /* Attempts to obtain at least one new token into 'merge' in SRC.
2343
2344    Returns true if successful, false on failure.  In the latter case, SRC is
2345    exhausted and 'src->eof' is now true. */
2346 static bool
2347 lex_source_get_merge (struct lex_source *src)
2348 {
2349   while (!src->eof)
2350     if (lex_source_try_get_merge (src))
2351       return true;
2352   return false;
2353 }
2354
2355 /* Attempts to obtain at least one new token into 'lookahead' in SRC.
2356
2357    Returns true if successful, false on failure.  In the latter case, SRC is
2358    exhausted and 'src->eof' is now true. */
2359 static bool
2360 lex_source_get_parse (struct lex_source *src)
2361 {
2362   struct merger m = MERGER_INIT;
2363   struct token out;
2364   for (size_t i = 0; ; i++)
2365     {
2366       while (lex_stage_count (&src->merge) <= i && !lex_source_get_merge (src))
2367         {
2368           /* We always get a T_ENDCMD at the end of an input file
2369              (transformed from T_STOP by lex_source_try_get_pp()) and
2370              merger_add() should never return -1 on T_ENDCMD. */
2371           assert (lex_stage_is_empty (&src->merge));
2372           return false;
2373         }
2374
2375       int retval = merger_add (&m, &lex_stage_nth (&src->merge, i)->token,
2376                                &out);
2377       if (!retval)
2378         {
2379           lex_source_push_parse (src, lex_stage_take_first (&src->merge));
2380           return true;
2381         }
2382       else if (retval > 0)
2383         {
2384           /* Add a token that merges all the tokens together. */
2385           const struct lex_token *first = lex_stage_first (&src->merge);
2386           const struct lex_token *last = lex_stage_nth (&src->merge,
2387                                                         retval - 1);
2388           bool macro = first->macro_rep && first->macro_rep == last->macro_rep;
2389           struct lex_token *t = xmalloc (sizeof *t);
2390           *t = (struct lex_token) {
2391             .token = out,
2392             .token_pos = first->token_pos,
2393             .token_len = (last->token_pos - first->token_pos) + last->token_len,
2394
2395             /* This works well if all the tokens were not expanded from macros,
2396                or if they came from the same macro expansion.  It just gives up
2397                in the other (corner) cases. */
2398             .macro_rep = macro ? first->macro_rep : NULL,
2399             .ofs = macro ? first->ofs : 0,
2400             .len = macro ? (last->ofs - first->ofs) + last->len : 0,
2401             .ref_cnt = macro ? first->ref_cnt : NULL,
2402           };
2403           if (t->ref_cnt)
2404             ++*t->ref_cnt;
2405           lex_source_push_parse (src, t);
2406
2407           for (int i = 0; i < retval; i++)
2408             lex_stage_pop_first (&src->merge);
2409           return true;
2410         }
2411     }
2412 }
2413 \f
2414 static void
2415 lex_source_push_endcmd__ (struct lex_source *src)
2416 {
2417   assert (src->n_parse == 0);
2418
2419   struct lex_token *token = xmalloc (sizeof *token);
2420   *token = (struct lex_token) { .token = { .type = T_ENDCMD } };
2421   lex_source_push_parse (src, token);
2422 }
2423
2424 static void
2425 lex_source_push_parse (struct lex_source *src, struct lex_token *token)
2426 {
2427   if (src->n_parse >= src->allocated_parse)
2428     src->parse = x2nrealloc (src->parse, &src->allocated_parse,
2429                              sizeof *src->parse);
2430   src->parse[src->n_parse++] = token;
2431 }
2432
2433 static void
2434 lex_source_clear_parse (struct lex_source *src)
2435 {
2436   for (size_t i = 0; i < src->n_parse; i++)
2437     lex_token_destroy (src->parse[i]);
2438   src->n_parse = src->parse_ofs = 0;
2439 }
2440
2441 static struct lex_source *
2442 lex_source_create (struct lexer *lexer, struct lex_reader *reader)
2443 {
2444   size_t allocated_lines = 4;
2445   size_t *lines = xmalloc (allocated_lines * sizeof *lines);
2446   *lines = 0;
2447
2448   struct lex_source *src = xmalloc (sizeof *src);
2449   *src = (struct lex_source) {
2450     .n_refs = 1,
2451     .reader = reader,
2452     .segmenter = segmenter_init (reader->syntax, false),
2453     .lexer = lexer,
2454     .lines = lines,
2455     .n_lines = 1,
2456     .allocated_lines = allocated_lines,
2457   };
2458
2459   lex_source_push_endcmd__ (src);
2460
2461   return src;
2462 }
2463
2464 void
2465 lex_set_message_handler (struct lexer *lexer,
2466                          void (*output_msg) (const struct msg *,
2467                                              struct lexer *))
2468 {
2469   struct msg_handler msg_handler = {
2470     .output_msg = (void (*)(const struct msg *, void *)) output_msg,
2471     .aux = lexer,
2472     .lex_source_ref = lex_source_ref,
2473     .lex_source_unref = lex_source_unref,
2474     .lex_source_get_line = lex_source_get_line,
2475   };
2476   msg_set_handler (&msg_handler);
2477 }
2478
2479 struct lex_source *
2480 lex_source_ref (const struct lex_source *src_)
2481 {
2482   struct lex_source *src = CONST_CAST (struct lex_source *, src_);
2483   if (src)
2484     {
2485       assert (src->n_refs > 0);
2486       src->n_refs++;
2487     }
2488   return src;
2489 }
2490
2491 void
2492 lex_source_unref (struct lex_source *src)
2493 {
2494   if (!src)
2495     return;
2496
2497   assert (src->n_refs > 0);
2498   if (--src->n_refs > 0)
2499     return;
2500
2501   char *file_name = src->reader->file_name;
2502   char *encoding = src->reader->encoding;
2503   if (src->reader->class->destroy != NULL)
2504     src->reader->class->destroy (src->reader);
2505   free (file_name);
2506   free (encoding);
2507   free (src->buffer);
2508   free (src->lines);
2509   lex_stage_uninit (&src->pp);
2510   lex_stage_uninit (&src->merge);
2511   lex_source_clear_parse (src);
2512   free (src->parse);
2513   free (src);
2514 }
2515 \f
2516 struct lex_file_reader
2517   {
2518     struct lex_reader reader;
2519     struct u8_istream *istream;
2520   };
2521
2522 static struct lex_reader_class lex_file_reader_class;
2523
2524 /* Creates and returns a new lex_reader that will read from file FILE_NAME (or
2525    from stdin if FILE_NAME is "-").  The file is expected to be encoded with
2526    ENCODING, which should take one of the forms accepted by
2527    u8_istream_for_file().  SYNTAX and ERROR become the syntax mode and error
2528    mode of the new reader, respectively.
2529
2530    Returns a null pointer if FILE_NAME cannot be opened. */
2531 struct lex_reader *
2532 lex_reader_for_file (const char *file_name, const char *encoding,
2533                      enum segmenter_mode syntax,
2534                      enum lex_error_mode error)
2535 {
2536   struct lex_file_reader *r;
2537   struct u8_istream *istream;
2538
2539   istream = (!strcmp(file_name, "-")
2540              ? u8_istream_for_fd (encoding, STDIN_FILENO)
2541              : u8_istream_for_file (encoding, file_name, O_RDONLY));
2542   if (istream == NULL)
2543     {
2544       msg (ME, _("Opening `%s': %s."), file_name, strerror (errno));
2545       return NULL;
2546     }
2547
2548   r = xmalloc (sizeof *r);
2549   lex_reader_init (&r->reader, &lex_file_reader_class);
2550   r->reader.syntax = syntax;
2551   r->reader.error = error;
2552   r->reader.file_name = xstrdup (file_name);
2553   r->reader.encoding = xstrdup_if_nonnull (encoding);
2554   r->reader.line_number = 1;
2555   r->istream = istream;
2556
2557   return &r->reader;
2558 }
2559
2560 static struct lex_file_reader *
2561 lex_file_reader_cast (struct lex_reader *r)
2562 {
2563   return UP_CAST (r, struct lex_file_reader, reader);
2564 }
2565
2566 static size_t
2567 lex_file_read (struct lex_reader *r_, char *buf, size_t n,
2568                enum prompt_style prompt_style UNUSED)
2569 {
2570   struct lex_file_reader *r = lex_file_reader_cast (r_);
2571   ssize_t n_read = u8_istream_read (r->istream, buf, n);
2572   if (n_read < 0)
2573     {
2574       msg (ME, _("Error reading `%s': %s."), r_->file_name, strerror (errno));
2575       return 0;
2576     }
2577   return n_read;
2578 }
2579
2580 static void
2581 lex_file_close (struct lex_reader *r_)
2582 {
2583   struct lex_file_reader *r = lex_file_reader_cast (r_);
2584
2585   if (u8_istream_fileno (r->istream) != STDIN_FILENO)
2586     {
2587       if (u8_istream_close (r->istream) != 0)
2588         msg (ME, _("Error closing `%s': %s."), r_->file_name, strerror (errno));
2589     }
2590   else
2591     u8_istream_free (r->istream);
2592
2593   free (r);
2594 }
2595
2596 static struct lex_reader_class lex_file_reader_class =
2597   {
2598     lex_file_read,
2599     lex_file_close
2600   };
2601 \f
2602 struct lex_string_reader
2603   {
2604     struct lex_reader reader;
2605     struct substring s;
2606     size_t offset;
2607   };
2608
2609 static struct lex_reader_class lex_string_reader_class;
2610
2611 /* Creates and returns a new lex_reader for the contents of S, which must be
2612    encoded in the given ENCODING.  The new reader takes ownership of S and will free it
2613    with ss_dealloc() when it is closed. */
2614 struct lex_reader *
2615 lex_reader_for_substring_nocopy (struct substring s, const char *encoding)
2616 {
2617   struct lex_string_reader *r;
2618
2619   r = xmalloc (sizeof *r);
2620   lex_reader_init (&r->reader, &lex_string_reader_class);
2621   r->reader.syntax = SEG_MODE_AUTO;
2622   r->reader.encoding = xstrdup_if_nonnull (encoding);
2623   r->s = s;
2624   r->offset = 0;
2625
2626   return &r->reader;
2627 }
2628
2629 /* Creates and returns a new lex_reader for a copy of null-terminated string S,
2630    which must be encoded in ENCODING.  The caller retains ownership of S. */
2631 struct lex_reader *
2632 lex_reader_for_string (const char *s, const char *encoding)
2633 {
2634   return lex_reader_for_substring_nocopy (ss_clone (ss_cstr (s)), encoding);
2635 }
2636
2637 /* Formats FORMAT as a printf()-like format string and creates and returns a
2638    new lex_reader for the formatted result.  */
2639 struct lex_reader *
2640 lex_reader_for_format (const char *format, const char *encoding, ...)
2641 {
2642   struct lex_reader *r;
2643   va_list args;
2644
2645   va_start (args, encoding);
2646   r = lex_reader_for_substring_nocopy (ss_cstr (xvasprintf (format, args)), encoding);
2647   va_end (args);
2648
2649   return r;
2650 }
2651
2652 static struct lex_string_reader *
2653 lex_string_reader_cast (struct lex_reader *r)
2654 {
2655   return UP_CAST (r, struct lex_string_reader, reader);
2656 }
2657
2658 static size_t
2659 lex_string_read (struct lex_reader *r_, char *buf, size_t n,
2660                  enum prompt_style prompt_style UNUSED)
2661 {
2662   struct lex_string_reader *r = lex_string_reader_cast (r_);
2663   size_t chunk;
2664
2665   chunk = MIN (n, r->s.length - r->offset);
2666   memcpy (buf, r->s.string + r->offset, chunk);
2667   r->offset += chunk;
2668
2669   return chunk;
2670 }
2671
2672 static void
2673 lex_string_close (struct lex_reader *r_)
2674 {
2675   struct lex_string_reader *r = lex_string_reader_cast (r_);
2676
2677   ss_dealloc (&r->s);
2678   free (r);
2679 }
2680
2681 static struct lex_reader_class lex_string_reader_class =
2682   {
2683     lex_string_read,
2684     lex_string_close
2685   };
2686 \f
2687 struct substring
2688 lex_source_get_line (const struct lex_source *src, int line)
2689 {
2690   if (line < 1 || line > src->n_lines)
2691     return ss_empty ();
2692
2693   size_t ofs = src->lines[line - 1];
2694   size_t end;
2695   if (line < src->n_lines)
2696     end = src->lines[line];
2697   else
2698     {
2699       const char *newline = memchr (src->buffer + ofs, '\n', src->length - ofs);
2700       end = newline ? newline - src->buffer : src->length;
2701     }
2702   return ss_buffer (&src->buffer[ofs], end - ofs);
2703 }