1b5ba2244f02c71245a649dd9d42a4bfacccd950
[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 #include <uniwidth.h>
32
33 #include "language/command.h"
34 #include "language/lexer/macro.h"
35 #include "language/lexer/scan.h"
36 #include "language/lexer/segment.h"
37 #include "language/lexer/token.h"
38 #include "libpspp/assertion.h"
39 #include "libpspp/cast.h"
40 #include "libpspp/deque.h"
41 #include "libpspp/i18n.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     /* Location of token in terms of the lex_source's buffer.
66        src->tail <= line_pos <= token_pos <= src->head. */
67     size_t token_pos;           /* Start of token. */
68     size_t token_len;           /* Length of source for token in bytes. */
69     size_t line_pos;            /* Start of line containing token_pos. */
70     int first_line;             /* Line number at token_pos. */
71     bool from_macro;
72   };
73
74 /* A source of tokens, corresponding to a syntax file.
75
76    This is conceptually a lex_reader wrapped with everything needed to convert
77    its UTF-8 bytes into tokens. */
78 struct lex_source
79   {
80     struct ll ll;               /* In lexer's list of sources. */
81     struct lex_reader *reader;
82     struct lexer *lexer;
83     struct segmenter segmenter;
84     bool eof;                   /* True if T_STOP was read from 'reader'. */
85
86     /* Buffer of UTF-8 bytes. */
87     char *buffer;
88     size_t allocated;           /* Number of bytes allocated. */
89     size_t tail;                /* &buffer[0] offset into UTF-8 source. */
90     size_t head;                /* &buffer[head - tail] offset into source. */
91
92     /* Positions in source file, tail <= pos <= head for each member here. */
93     size_t journal_pos;         /* First byte not yet output to journal. */
94     size_t seg_pos;             /* First byte not yet scanned as token. */
95     size_t line_pos;            /* First byte of line containing seg_pos. */
96
97     int n_newlines;             /* Number of new-lines up to seg_pos. */
98     bool suppress_next_newline;
99
100     /* Tokens. */
101     struct deque deque;         /* Indexes into 'tokens'. */
102     struct lex_token *tokens;   /* Lookahead tokens for parser. */
103   };
104
105 static struct lex_source *lex_source_create (struct lexer *,
106                                              struct lex_reader *);
107 static void lex_source_destroy (struct lex_source *);
108
109 /* Lexer. */
110 struct lexer
111   {
112     struct ll_list sources;     /* Contains "struct lex_source"s. */
113     struct macro_set *macros;
114   };
115
116 static struct lex_source *lex_source__ (const struct lexer *);
117 static const struct lex_token *lex_next__ (const struct lexer *, int n);
118 static void lex_source_push_endcmd__ (struct lex_source *);
119
120 static void lex_source_pop__ (struct lex_source *);
121 static bool lex_source_get (const struct lex_source *);
122 static void lex_source_error_valist (struct lex_source *, int n0, int n1,
123                                      const char *format, va_list)
124    PRINTF_FORMAT (4, 0);
125 static const struct lex_token *lex_source_next__ (const struct lex_source *,
126                                                   int n);
127 \f
128 /* Initializes READER with the specified CLASS and otherwise some reasonable
129    defaults.  The caller should fill in the others members as desired. */
130 void
131 lex_reader_init (struct lex_reader *reader,
132                  const struct lex_reader_class *class)
133 {
134   reader->class = class;
135   reader->syntax = SEG_MODE_AUTO;
136   reader->error = LEX_ERROR_CONTINUE;
137   reader->file_name = NULL;
138   reader->encoding = NULL;
139   reader->line_number = 0;
140   reader->eof = false;
141 }
142
143 /* Frees any file name already in READER and replaces it by a copy of
144    FILE_NAME, or if FILE_NAME is null then clears any existing name. */
145 void
146 lex_reader_set_file_name (struct lex_reader *reader, const char *file_name)
147 {
148   free (reader->file_name);
149   reader->file_name = xstrdup_if_nonnull (file_name);
150 }
151 \f
152 /* Creates and returns a new lexer. */
153 struct lexer *
154 lex_create (void)
155 {
156   struct lexer *lexer = xmalloc (sizeof *lexer);
157   *lexer = (struct lexer) {
158     .sources = LL_INITIALIZER (lexer->sources),
159     .macros = macro_set_create (),
160   };
161   return lexer;
162 }
163
164 /* Destroys LEXER. */
165 void
166 lex_destroy (struct lexer *lexer)
167 {
168   if (lexer != NULL)
169     {
170       struct lex_source *source, *next;
171
172       ll_for_each_safe (source, next, struct lex_source, ll, &lexer->sources)
173         lex_source_destroy (source);
174       macro_set_destroy (lexer->macros);
175       free (lexer);
176     }
177 }
178
179 /* Adds M to LEXER's set of macros.  M replaces any existing macro with the
180    same name.  Takes ownership of M. */
181 void
182 lex_define_macro (struct lexer *lexer, struct macro *m)
183 {
184   macro_set_add (lexer->macros, m);
185 }
186
187 /* Inserts READER into LEXER so that the next token read by LEXER comes from
188    READER.  Before the caller, LEXER must either be empty or at a T_ENDCMD
189    token. */
190 void
191 lex_include (struct lexer *lexer, struct lex_reader *reader)
192 {
193   assert (ll_is_empty (&lexer->sources) || lex_token (lexer) == T_ENDCMD);
194   ll_push_head (&lexer->sources, &lex_source_create (lexer, reader)->ll);
195 }
196
197 /* Appends READER to LEXER, so that it will be read after all other current
198    readers have already been read. */
199 void
200 lex_append (struct lexer *lexer, struct lex_reader *reader)
201 {
202   ll_push_tail (&lexer->sources, &lex_source_create (lexer, reader)->ll);
203 }
204 \f
205 /* Advancing. */
206
207 static struct lex_token *
208 lex_push_token__ (struct lex_source *src)
209 {
210   struct lex_token *token;
211
212   if (deque_is_full (&src->deque))
213     src->tokens = deque_expand (&src->deque, src->tokens, sizeof *src->tokens);
214
215   token = &src->tokens[deque_push_front (&src->deque)];
216   token->token = (struct token) { .type = T_STOP };
217   return token;
218 }
219
220 static void
221 lex_source_pop__ (struct lex_source *src)
222 {
223   token_uninit (&src->tokens[deque_pop_back (&src->deque)].token);
224 }
225
226 static void
227 lex_source_pop_front (struct lex_source *src)
228 {
229   token_uninit (&src->tokens[deque_pop_front (&src->deque)].token);
230 }
231
232 /* Advances LEXER to the next token, consuming the current token. */
233 void
234 lex_get (struct lexer *lexer)
235 {
236   struct lex_source *src;
237
238   src = lex_source__ (lexer);
239   if (src == NULL)
240     return;
241
242   if (!deque_is_empty (&src->deque))
243     lex_source_pop__ (src);
244
245   while (deque_is_empty (&src->deque))
246     if (!lex_source_get (src))
247       {
248         lex_source_destroy (src);
249         src = lex_source__ (lexer);
250         if (src == NULL)
251           return;
252       }
253 }
254 \f
255 /* Issuing errors. */
256
257 /* Prints a syntax error message containing the current token and
258    given message MESSAGE (if non-null). */
259 void
260 lex_error (struct lexer *lexer, const char *format, ...)
261 {
262   va_list args;
263
264   va_start (args, format);
265   lex_next_error_valist (lexer, 0, 0, format, args);
266   va_end (args);
267 }
268
269 /* Prints a syntax error message containing the current token and
270    given message MESSAGE (if non-null). */
271 void
272 lex_error_valist (struct lexer *lexer, const char *format, va_list args)
273 {
274   lex_next_error_valist (lexer, 0, 0, format, args);
275 }
276
277 /* Prints a syntax error message containing the current token and
278    given message MESSAGE (if non-null). */
279 void
280 lex_next_error (struct lexer *lexer, int n0, int n1, const char *format, ...)
281 {
282   va_list args;
283
284   va_start (args, format);
285   lex_next_error_valist (lexer, n0, n1, format, args);
286   va_end (args);
287 }
288
289 /* Prints a syntax error message saying that one of the strings provided as
290    varargs, up to the first NULL, is expected. */
291 void
292 (lex_error_expecting) (struct lexer *lexer, ...)
293 {
294   va_list args;
295
296   va_start (args, lexer);
297   lex_error_expecting_valist (lexer, args);
298   va_end (args);
299 }
300
301 /* Prints a syntax error message saying that one of the options provided in
302    ARGS, up to the first NULL, is expected. */
303 void
304 lex_error_expecting_valist (struct lexer *lexer, va_list args)
305 {
306   enum { MAX_OPTIONS = 9 };
307   const char *options[MAX_OPTIONS];
308   int n = 0;
309   while (n < MAX_OPTIONS)
310     {
311       const char *option = va_arg (args, const char *);
312       if (!option)
313         break;
314
315       options[n++] = option;
316     }
317   lex_error_expecting_array (lexer, options, n);
318 }
319
320 void
321 lex_error_expecting_array (struct lexer *lexer, const char **options, size_t n)
322 {
323   switch (n)
324     {
325     case 0:
326       lex_error (lexer, NULL);
327       break;
328
329     case 1:
330       lex_error (lexer, _("expecting %s"), options[0]);
331       break;
332
333     case 2:
334       lex_error (lexer, _("expecting %s or %s"), options[0], options[1]);
335       break;
336
337     case 3:
338       lex_error (lexer, _("expecting %s, %s, or %s"), options[0], options[1],
339                  options[2]);
340       break;
341
342     case 4:
343       lex_error (lexer, _("expecting %s, %s, %s, or %s"),
344                  options[0], options[1], options[2], options[3]);
345       break;
346
347     case 5:
348       lex_error (lexer, _("expecting %s, %s, %s, %s, or %s"),
349                  options[0], options[1], options[2], options[3], options[4]);
350       break;
351
352     case 6:
353       lex_error (lexer, _("expecting %s, %s, %s, %s, %s, or %s"),
354                  options[0], options[1], options[2], options[3], options[4],
355                  options[5]);
356       break;
357
358     case 7:
359       lex_error (lexer, _("expecting %s, %s, %s, %s, %s, %s, or %s"),
360                  options[0], options[1], options[2], options[3], options[4],
361                  options[5], options[6]);
362       break;
363
364     case 8:
365       lex_error (lexer, _("expecting %s, %s, %s, %s, %s, %s, %s, or %s"),
366                  options[0], options[1], options[2], options[3], options[4],
367                  options[5], options[6], options[7]);
368       break;
369
370     default:
371       lex_error (lexer, NULL);
372     }
373 }
374
375 /* Reports an error to the effect that subcommand SBC may only be specified
376    once.
377
378    This function does not take a lexer as an argument or use lex_error(),
379    because the result would ordinarily just be redundant: "Syntax error at
380    SUBCOMMAND: Subcommand SUBCOMMAND may only be specified once.", which does
381    not help the user find the error. */
382 void
383 lex_sbc_only_once (const char *sbc)
384 {
385   msg (SE, _("Subcommand %s may only be specified once."), sbc);
386 }
387
388 /* Reports an error to the effect that subcommand SBC is missing.
389
390    This function does not take a lexer as an argument or use lex_error(),
391    because a missing subcommand can normally be detected only after the whole
392    command has been parsed, and so lex_error() would always report "Syntax
393    error at end of command", which does not help the user find the error. */
394 void
395 lex_sbc_missing (const char *sbc)
396 {
397   msg (SE, _("Required subcommand %s was not specified."), sbc);
398 }
399
400 /* Reports an error to the effect that specification SPEC may only be specified
401    once within subcommand SBC. */
402 void
403 lex_spec_only_once (struct lexer *lexer, const char *sbc, const char *spec)
404 {
405   lex_error (lexer, _("%s may only be specified once within subcommand %s"),
406              spec, sbc);
407 }
408
409 /* Reports an error to the effect that specification SPEC is missing within
410    subcommand SBC. */
411 void
412 lex_spec_missing (struct lexer *lexer, const char *sbc, const char *spec)
413 {
414   lex_error (lexer, _("Required %s specification missing from %s subcommand"),
415              sbc, spec);
416 }
417
418 /* Prints a syntax error message containing the current token and
419    given message MESSAGE (if non-null). */
420 void
421 lex_next_error_valist (struct lexer *lexer, int n0, int n1,
422                        const char *format, va_list args)
423 {
424   struct lex_source *src = lex_source__ (lexer);
425
426   if (src != NULL)
427     lex_source_error_valist (src, n0, n1, format, args);
428   else
429     {
430       struct string s;
431
432       ds_init_empty (&s);
433       ds_put_format (&s, _("Syntax error at end of input"));
434       if (format != NULL)
435         {
436           ds_put_cstr (&s, ": ");
437           ds_put_vformat (&s, format, args);
438         }
439       ds_put_byte (&s, '.');
440       msg (SE, "%s", ds_cstr (&s));
441       ds_destroy (&s);
442     }
443 }
444
445 /* Checks that we're at end of command.
446    If so, returns a successful command completion code.
447    If not, flags a syntax error and returns an error command
448    completion code. */
449 int
450 lex_end_of_command (struct lexer *lexer)
451 {
452   if (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_STOP)
453     {
454       lex_error (lexer, _("expecting end of command"));
455       return CMD_FAILURE;
456     }
457   else
458     return CMD_SUCCESS;
459 }
460 \f
461 /* Token testing functions. */
462
463 /* Returns true if the current token is a number. */
464 bool
465 lex_is_number (const struct lexer *lexer)
466 {
467   return lex_next_is_number (lexer, 0);
468 }
469
470 /* Returns true if the current token is a string. */
471 bool
472 lex_is_string (const struct lexer *lexer)
473 {
474   return lex_next_is_string (lexer, 0);
475 }
476
477 /* Returns the value of the current token, which must be a
478    floating point number. */
479 double
480 lex_number (const struct lexer *lexer)
481 {
482   return lex_next_number (lexer, 0);
483 }
484
485 /* Returns true iff the current token is an integer. */
486 bool
487 lex_is_integer (const struct lexer *lexer)
488 {
489   return lex_next_is_integer (lexer, 0);
490 }
491
492 /* Returns the value of the current token, which must be an
493    integer. */
494 long
495 lex_integer (const struct lexer *lexer)
496 {
497   return lex_next_integer (lexer, 0);
498 }
499 \f
500 /* Token testing functions with lookahead.
501
502    A value of 0 for N as an argument to any of these functions refers to the
503    current token.  Lookahead is limited to the current command.  Any N greater
504    than the number of tokens remaining in the current command will be treated
505    as referring to a T_ENDCMD token. */
506
507 /* Returns true if the token N ahead of the current token is a number. */
508 bool
509 lex_next_is_number (const struct lexer *lexer, int n)
510 {
511   enum token_type next_token = lex_next_token (lexer, n);
512   return next_token == T_POS_NUM || next_token == T_NEG_NUM;
513 }
514
515 /* Returns true if the token N ahead of the current token is a string. */
516 bool
517 lex_next_is_string (const struct lexer *lexer, int n)
518 {
519   return lex_next_token (lexer, n) == T_STRING;
520 }
521
522 /* Returns the value of the token N ahead of the current token, which must be a
523    floating point number. */
524 double
525 lex_next_number (const struct lexer *lexer, int n)
526 {
527   assert (lex_next_is_number (lexer, n));
528   return lex_next_tokval (lexer, n);
529 }
530
531 /* Returns true if the token N ahead of the current token is an integer. */
532 bool
533 lex_next_is_integer (const struct lexer *lexer, int n)
534 {
535   double value;
536
537   if (!lex_next_is_number (lexer, n))
538     return false;
539
540   value = lex_next_tokval (lexer, n);
541   return value > LONG_MIN && value <= LONG_MAX && floor (value) == value;
542 }
543
544 /* Returns the value of the token N ahead of the current token, which must be
545    an integer. */
546 long
547 lex_next_integer (const struct lexer *lexer, int n)
548 {
549   assert (lex_next_is_integer (lexer, n));
550   return lex_next_tokval (lexer, n);
551 }
552 \f
553 /* Token matching functions. */
554
555 /* If the current token has the specified TYPE, skips it and returns true.
556    Otherwise, returns false. */
557 bool
558 lex_match (struct lexer *lexer, enum token_type type)
559 {
560   if (lex_token (lexer) == type)
561     {
562       lex_get (lexer);
563       return true;
564     }
565   else
566     return false;
567 }
568
569 /* If the current token matches IDENTIFIER, skips it and returns true.
570    IDENTIFIER may be abbreviated to its first three letters.  Otherwise,
571    returns false.
572
573    IDENTIFIER must be an ASCII string. */
574 bool
575 lex_match_id (struct lexer *lexer, const char *identifier)
576 {
577   return lex_match_id_n (lexer, identifier, 3);
578 }
579
580 /* If the current token is IDENTIFIER, skips it and returns true.  IDENTIFIER
581    may be abbreviated to its first N letters.  Otherwise, returns false.
582
583    IDENTIFIER must be an ASCII string. */
584 bool
585 lex_match_id_n (struct lexer *lexer, const char *identifier, size_t n)
586 {
587   if (lex_token (lexer) == T_ID
588       && lex_id_match_n (ss_cstr (identifier), lex_tokss (lexer), n))
589     {
590       lex_get (lexer);
591       return true;
592     }
593   else
594     return false;
595 }
596
597 /* If the current token is integer X, skips it and returns true.  Otherwise,
598    returns false. */
599 bool
600 lex_match_int (struct lexer *lexer, int x)
601 {
602   if (lex_is_integer (lexer) && lex_integer (lexer) == x)
603     {
604       lex_get (lexer);
605       return true;
606     }
607   else
608     return false;
609 }
610 \f
611 /* Forced matches. */
612
613 /* If this token is IDENTIFIER, skips it and returns true.  IDENTIFIER may be
614    abbreviated to its first 3 letters.  Otherwise, reports an error and returns
615    false.
616
617    IDENTIFIER must be an ASCII string. */
618 bool
619 lex_force_match_id (struct lexer *lexer, const char *identifier)
620 {
621   if (lex_match_id (lexer, identifier))
622     return true;
623   else
624     {
625       lex_error_expecting (lexer, identifier);
626       return false;
627     }
628 }
629
630 /* If the current token has the specified TYPE, skips it and returns true.
631    Otherwise, reports an error and returns false. */
632 bool
633 lex_force_match (struct lexer *lexer, enum token_type type)
634 {
635   if (lex_token (lexer) == type)
636     {
637       lex_get (lexer);
638       return true;
639     }
640   else
641     {
642       const char *type_string = token_type_to_string (type);
643       if (type_string)
644         {
645           char *s = xasprintf ("`%s'", type_string);
646           lex_error_expecting (lexer, s);
647           free (s);
648         }
649       else
650         lex_error_expecting (lexer, token_type_to_name (type));
651
652       return false;
653     }
654 }
655
656 /* If the current token is a string, does nothing and returns true.
657    Otherwise, reports an error and returns false. */
658 bool
659 lex_force_string (struct lexer *lexer)
660 {
661   if (lex_is_string (lexer))
662     return true;
663   else
664     {
665       lex_error (lexer, _("expecting string"));
666       return false;
667     }
668 }
669
670 /* If the current token is a string or an identifier, does nothing and returns
671    true.  Otherwise, reports an error and returns false.
672
673    This is meant for use in syntactic situations where we want to encourage the
674    user to supply a quoted string, but for compatibility we also accept
675    identifiers.  (One example of such a situation is file names.)  Therefore,
676    the error message issued when the current token is wrong only says that a
677    string is expected and doesn't mention that an identifier would also be
678    accepted. */
679 bool
680 lex_force_string_or_id (struct lexer *lexer)
681 {
682   return lex_token (lexer) == T_ID || lex_force_string (lexer);
683 }
684
685 /* If the current token is an integer, does nothing and returns true.
686    Otherwise, reports an error and returns false. */
687 bool
688 lex_force_int (struct lexer *lexer)
689 {
690   if (lex_is_integer (lexer))
691     return true;
692   else
693     {
694       lex_error (lexer, _("expecting integer"));
695       return false;
696     }
697 }
698
699 /* If the current token is an integer in the range MIN...MAX (inclusive), does
700    nothing and returns true.  Otherwise, reports an error and returns false.
701    If NAME is nonnull, then it is used in the error message. */
702 bool
703 lex_force_int_range (struct lexer *lexer, const char *name, long min, long max)
704 {
705   bool is_integer = lex_is_integer (lexer);
706   bool too_small = is_integer && lex_integer (lexer) < min;
707   bool too_big = is_integer && lex_integer (lexer) > max;
708   if (is_integer && !too_small && !too_big)
709     return true;
710
711   if (min > max)
712     {
713       /* Weird, maybe a bug in the caller.  Just report that we needed an
714          integer. */
715       if (name)
716         lex_error (lexer, _("Integer expected for %s."), name);
717       else
718         lex_error (lexer, _("Integer expected."));
719     }
720   else if (min == max)
721     {
722       if (name)
723         lex_error (lexer, _("Expected %ld for %s."), min, name);
724       else
725         lex_error (lexer, _("Expected %ld."), min);
726     }
727   else if (min + 1 == max)
728     {
729       if (name)
730         lex_error (lexer, _("Expected %ld or %ld for %s."), min, min + 1, name);
731       else
732         lex_error (lexer, _("Expected %ld or %ld."), min, min + 1);
733     }
734   else
735     {
736       bool report_lower_bound = (min > INT_MIN / 2) || too_small;
737       bool report_upper_bound = (max < INT_MAX / 2) || too_big;
738
739       if (report_lower_bound && report_upper_bound)
740         {
741           if (name)
742             lex_error (lexer,
743                        _("Expected integer between %ld and %ld for %s."),
744                        min, max, name);
745           else
746             lex_error (lexer, _("Expected integer between %ld and %ld."),
747                        min, max);
748         }
749       else if (report_lower_bound)
750         {
751           if (min == 0)
752             {
753               if (name)
754                 lex_error (lexer, _("Expected non-negative integer for %s."),
755                            name);
756               else
757                 lex_error (lexer, _("Expected non-negative integer."));
758             }
759           else if (min == 1)
760             {
761               if (name)
762                 lex_error (lexer, _("Expected positive integer for %s."),
763                            name);
764               else
765                 lex_error (lexer, _("Expected positive integer."));
766             }
767         }
768       else if (report_upper_bound)
769         {
770           if (name)
771             lex_error (lexer,
772                        _("Expected integer less than or equal to %ld for %s."),
773                        max, name);
774           else
775             lex_error (lexer, _("Expected integer less than or equal to %ld."),
776                        max);
777         }
778       else
779         {
780           if (name)
781             lex_error (lexer, _("Integer expected for %s."), name);
782           else
783             lex_error (lexer, _("Integer expected."));
784         }
785     }
786   return false;
787 }
788
789 /* If the current token is a number, does nothing and returns true.
790    Otherwise, reports an error and returns false. */
791 bool
792 lex_force_num (struct lexer *lexer)
793 {
794   if (lex_is_number (lexer))
795     return true;
796
797   lex_error (lexer, _("expecting number"));
798   return false;
799 }
800
801 /* If the current token is an identifier, does nothing and returns true.
802    Otherwise, reports an error and returns false. */
803 bool
804 lex_force_id (struct lexer *lexer)
805 {
806   if (lex_token (lexer) == T_ID)
807     return true;
808
809   lex_error (lexer, _("expecting identifier"));
810   return false;
811 }
812 \f
813 /* Token accessors. */
814
815 /* Returns the type of LEXER's current token. */
816 enum token_type
817 lex_token (const struct lexer *lexer)
818 {
819   return lex_next_token (lexer, 0);
820 }
821
822 /* Returns the number in LEXER's current token.
823
824    Only T_NEG_NUM and T_POS_NUM tokens have meaningful values.  For other
825    tokens this function will always return zero. */
826 double
827 lex_tokval (const struct lexer *lexer)
828 {
829   return lex_next_tokval (lexer, 0);
830 }
831
832 /* Returns the null-terminated string in LEXER's current token, UTF-8 encoded.
833
834    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
835    this functions this function will always return NULL.
836
837    The UTF-8 encoding of the returned string is correct for variable names and
838    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
839    data_in() to use it in a "union value".  */
840 const char *
841 lex_tokcstr (const struct lexer *lexer)
842 {
843   return lex_next_tokcstr (lexer, 0);
844 }
845
846 /* Returns the string in LEXER's current token, UTF-8 encoded.  The string is
847    null-terminated (but the null terminator is not included in the returned
848    substring's 'length').
849
850    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
851    this functions this function will always return NULL.
852
853    The UTF-8 encoding of the returned string is correct for variable names and
854    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
855    data_in() to use it in a "union value".  */
856 struct substring
857 lex_tokss (const struct lexer *lexer)
858 {
859   return lex_next_tokss (lexer, 0);
860 }
861 \f
862 /* Looking ahead.
863
864    A value of 0 for N as an argument to any of these functions refers to the
865    current token.  Lookahead is limited to the current command.  Any N greater
866    than the number of tokens remaining in the current command will be treated
867    as referring to a T_ENDCMD token. */
868
869 static const struct lex_token *
870 lex_next__ (const struct lexer *lexer_, int n)
871 {
872   struct lexer *lexer = CONST_CAST (struct lexer *, lexer_);
873   struct lex_source *src = lex_source__ (lexer);
874
875   if (src != NULL)
876     return lex_source_next__ (src, n);
877   else
878     {
879       static const struct lex_token stop_token = { .token = { .type = T_STOP } };
880       return &stop_token;
881     }
882 }
883
884 static const struct lex_token *
885 lex_source_front (const struct lex_source *src)
886 {
887   return &src->tokens[deque_front (&src->deque, 0)];
888 }
889
890 static const struct lex_token *
891 lex_source_next__ (const struct lex_source *src, int n)
892 {
893   while (deque_count (&src->deque) <= n)
894     {
895       if (!deque_is_empty (&src->deque))
896         {
897           const struct lex_token *front = lex_source_front (src);
898           if (front->token.type == T_STOP || front->token.type == T_ENDCMD)
899             return front;
900         }
901
902       lex_source_get (src);
903     }
904
905   return &src->tokens[deque_back (&src->deque, n)];
906 }
907
908 /* Returns the "struct token" of the token N after the current one in LEXER.
909    The returned pointer can be invalidated by pretty much any succeeding call
910    into the lexer, although the string pointer within the returned token is
911    only invalidated by consuming the token (e.g. with lex_get()). */
912 const struct token *
913 lex_next (const struct lexer *lexer, int n)
914 {
915   return &lex_next__ (lexer, n)->token;
916 }
917
918 /* Returns the type of the token N after the current one in LEXER. */
919 enum token_type
920 lex_next_token (const struct lexer *lexer, int n)
921 {
922   return lex_next (lexer, n)->type;
923 }
924
925 /* Returns the number in the tokn N after the current one in LEXER.
926
927    Only T_NEG_NUM and T_POS_NUM tokens have meaningful values.  For other
928    tokens this function will always return zero. */
929 double
930 lex_next_tokval (const struct lexer *lexer, int n)
931 {
932   const struct token *token = lex_next (lexer, n);
933   return token->number;
934 }
935
936 /* Returns the null-terminated string in the token N after the current one, in
937    UTF-8 encoding.
938
939    Only T_ID and T_STRING tokens have meaningful strings.  For other tokens
940    this functions this function will always return NULL.
941
942    The UTF-8 encoding of the returned string is correct for variable names and
943    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
944    data_in() to use it in a "union value".  */
945 const char *
946 lex_next_tokcstr (const struct lexer *lexer, int n)
947 {
948   return lex_next_tokss (lexer, n).string;
949 }
950
951 /* Returns the string in the token N after the current one, in UTF-8 encoding.
952    The string is null-terminated (but the null terminator is not included in
953    the returned substring's 'length').
954
955    Only T_ID, T_MACRO_ID, T_STRING tokens have meaningful strings.  For other
956    tokens this functions this function will always return NULL.
957
958    The UTF-8 encoding of the returned string is correct for variable names and
959    other identifiers.  Use filename_to_utf8() to use it as a filename.  Use
960    data_in() to use it in a "union value".  */
961 struct substring
962 lex_next_tokss (const struct lexer *lexer, int n)
963 {
964   return lex_next (lexer, n)->string;
965 }
966
967 static bool
968 lex_tokens_match (const struct token *actual, const struct token *expected)
969 {
970   if (actual->type != expected->type)
971     return false;
972
973   switch (actual->type)
974     {
975     case T_POS_NUM:
976     case T_NEG_NUM:
977       return actual->number == expected->number;
978
979     case T_ID:
980       return lex_id_match (expected->string, actual->string);
981
982     case T_STRING:
983       return (actual->string.length == expected->string.length
984               && !memcmp (actual->string.string, expected->string.string,
985                           actual->string.length));
986
987     default:
988       return true;
989     }
990 }
991
992 /* If LEXER is positioned at the sequence of tokens that may be parsed from S,
993    skips it and returns true.  Otherwise, returns false.
994
995    S may consist of an arbitrary sequence of tokens, e.g. "KRUSKAL-WALLIS",
996    "2SLS", or "END INPUT PROGRAM".  Identifiers may be abbreviated to their
997    first three letters. */
998 bool
999 lex_match_phrase (struct lexer *lexer, const char *s)
1000 {
1001   struct string_lexer slex;
1002   struct token token;
1003   int i;
1004
1005   i = 0;
1006   string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE);
1007   while (string_lexer_next (&slex, &token))
1008     if (token.type != SCAN_SKIP)
1009       {
1010         bool match = lex_tokens_match (lex_next (lexer, i++), &token);
1011         token_uninit (&token);
1012         if (!match)
1013           return false;
1014       }
1015
1016   while (i-- > 0)
1017     lex_get (lexer);
1018   return true;
1019 }
1020
1021 static int
1022 lex_source_get_first_line_number (const struct lex_source *src, int n)
1023 {
1024   return lex_source_next__ (src, n)->first_line;
1025 }
1026
1027 static int
1028 count_newlines (char *s, size_t length)
1029 {
1030   int n_newlines = 0;
1031   char *newline;
1032
1033   while ((newline = memchr (s, '\n', length)) != NULL)
1034     {
1035       n_newlines++;
1036       length -= (newline + 1) - s;
1037       s = newline + 1;
1038     }
1039
1040   return n_newlines;
1041 }
1042
1043 static int
1044 lex_source_get_last_line_number (const struct lex_source *src, int n)
1045 {
1046   const struct lex_token *token = lex_source_next__ (src, n);
1047
1048   if (token->first_line == 0)
1049     return 0;
1050   else
1051     {
1052       char *token_str = &src->buffer[token->token_pos - src->tail];
1053       return token->first_line + count_newlines (token_str, token->token_len) + 1;
1054     }
1055 }
1056
1057 static int
1058 count_columns (const char *s_, size_t length)
1059 {
1060   const uint8_t *s = CHAR_CAST (const uint8_t *, s_);
1061   int columns;
1062   size_t ofs;
1063   int mblen;
1064
1065   columns = 0;
1066   for (ofs = 0; ofs < length; ofs += mblen)
1067     {
1068       ucs4_t uc;
1069
1070       mblen = u8_mbtouc (&uc, s + ofs, length - ofs);
1071       if (uc != '\t')
1072         {
1073           int width = uc_width (uc, "UTF-8");
1074           if (width > 0)
1075             columns += width;
1076         }
1077       else
1078         columns = ROUND_UP (columns + 1, 8);
1079     }
1080
1081   return columns + 1;
1082 }
1083
1084 static int
1085 lex_source_get_first_column (const struct lex_source *src, int n)
1086 {
1087   const struct lex_token *token = lex_source_next__ (src, n);
1088   return count_columns (&src->buffer[token->line_pos - src->tail],
1089                         token->token_pos - token->line_pos);
1090 }
1091
1092 static int
1093 lex_source_get_last_column (const struct lex_source *src, int n)
1094 {
1095   const struct lex_token *token = lex_source_next__ (src, n);
1096   char *start, *end, *newline;
1097
1098   start = &src->buffer[token->line_pos - src->tail];
1099   end = &src->buffer[(token->token_pos + token->token_len) - src->tail];
1100   newline = memrchr (start, '\n', end - start);
1101   if (newline != NULL)
1102     start = newline + 1;
1103   return count_columns (start, end - start);
1104 }
1105
1106 /* Returns the 1-based line number of the start of the syntax that represents
1107    the token N after the current one in LEXER.  Returns 0 for a T_STOP token or
1108    if the token is drawn from a source that does not have line numbers. */
1109 int
1110 lex_get_first_line_number (const struct lexer *lexer, int n)
1111 {
1112   const struct lex_source *src = lex_source__ (lexer);
1113   return src != NULL ? lex_source_get_first_line_number (src, n) : 0;
1114 }
1115
1116 /* Returns the 1-based line number of the end of the syntax that represents the
1117    token N after the current one in LEXER, plus 1.  Returns 0 for a T_STOP
1118    token or if the token is drawn from a source that does not have line
1119    numbers.
1120
1121    Most of the time, a single token is wholly within a single line of syntax,
1122    but there are two exceptions: a T_STRING token can be made up of multiple
1123    segments on adjacent lines connected with "+" punctuators, and a T_NEG_NUM
1124    token can consist of a "-" on one line followed by the number on the next.
1125  */
1126 int
1127 lex_get_last_line_number (const struct lexer *lexer, int n)
1128 {
1129   const struct lex_source *src = lex_source__ (lexer);
1130   return src != NULL ? lex_source_get_last_line_number (src, n) : 0;
1131 }
1132
1133 /* Returns the 1-based column number of the start of the syntax that represents
1134    the token N after the current one in LEXER.  Returns 0 for a T_STOP
1135    token.
1136
1137    Column numbers are measured according to the width of characters as shown in
1138    a typical fixed-width font, in which CJK characters have width 2 and
1139    combining characters have width 0.  */
1140 int
1141 lex_get_first_column (const struct lexer *lexer, int n)
1142 {
1143   const struct lex_source *src = lex_source__ (lexer);
1144   return src != NULL ? lex_source_get_first_column (src, n) : 0;
1145 }
1146
1147 /* Returns the 1-based column number of the end of the syntax that represents
1148    the token N after the current one in LEXER, plus 1.  Returns 0 for a T_STOP
1149    token.
1150
1151    Column numbers are measured according to the width of characters as shown in
1152    a typical fixed-width font, in which CJK characters have width 2 and
1153    combining characters have width 0.  */
1154 int
1155 lex_get_last_column (const struct lexer *lexer, int n)
1156 {
1157   const struct lex_source *src = lex_source__ (lexer);
1158   return src != NULL ? lex_source_get_last_column (src, n) : 0;
1159 }
1160
1161 /* Returns the name of the syntax file from which the current command is drawn.
1162    Returns NULL for a T_STOP token or if the command's source does not have
1163    line numbers.
1164
1165    There is no version of this function that takes an N argument because
1166    lookahead only works to the end of a command and any given command is always
1167    within a single syntax file. */
1168 const char *
1169 lex_get_file_name (const struct lexer *lexer)
1170 {
1171   struct lex_source *src = lex_source__ (lexer);
1172   return src == NULL ? NULL : src->reader->file_name;
1173 }
1174
1175 const char *
1176 lex_get_encoding (const struct lexer *lexer)
1177 {
1178   struct lex_source *src = lex_source__ (lexer);
1179   return src == NULL ? NULL : src->reader->encoding;
1180 }
1181
1182
1183 /* Returns the syntax mode for the syntax file from which the current drawn is
1184    drawn.  Returns SEG_MODE_AUTO for a T_STOP token or if the command's source
1185    does not have line numbers.
1186
1187    There is no version of this function that takes an N argument because
1188    lookahead only works to the end of a command and any given command is always
1189    within a single syntax file. */
1190 enum segmenter_mode
1191 lex_get_syntax_mode (const struct lexer *lexer)
1192 {
1193   struct lex_source *src = lex_source__ (lexer);
1194   return src == NULL ? SEG_MODE_AUTO : src->reader->syntax;
1195 }
1196
1197 /* Returns the error mode for the syntax file from which the current drawn is
1198    drawn.  Returns LEX_ERROR_TERMINAL for a T_STOP token or if the command's
1199    source does not have line numbers.
1200
1201    There is no version of this function that takes an N argument because
1202    lookahead only works to the end of a command and any given command is always
1203    within a single syntax file. */
1204 enum lex_error_mode
1205 lex_get_error_mode (const struct lexer *lexer)
1206 {
1207   struct lex_source *src = lex_source__ (lexer);
1208   return src == NULL ? LEX_ERROR_TERMINAL : src->reader->error;
1209 }
1210
1211 /* If the source that LEXER is currently reading has error mode
1212    LEX_ERROR_TERMINAL, discards all buffered input and tokens, so that the next
1213    token to be read comes directly from whatever is next read from the stream.
1214
1215    It makes sense to call this function after encountering an error in a
1216    command entered on the console, because usually the user would prefer not to
1217    have cascading errors. */
1218 void
1219 lex_interactive_reset (struct lexer *lexer)
1220 {
1221   struct lex_source *src = lex_source__ (lexer);
1222   if (src != NULL && src->reader->error == LEX_ERROR_TERMINAL)
1223     {
1224       src->head = src->tail = 0;
1225       src->journal_pos = src->seg_pos = src->line_pos = 0;
1226       src->n_newlines = 0;
1227       src->suppress_next_newline = false;
1228       segmenter_init (&src->segmenter, segmenter_get_mode (&src->segmenter));
1229       while (!deque_is_empty (&src->deque))
1230         lex_source_pop__ (src);
1231       lex_source_push_endcmd__ (src);
1232     }
1233 }
1234
1235 /* Advances past any tokens in LEXER up to a T_ENDCMD or T_STOP. */
1236 void
1237 lex_discard_rest_of_command (struct lexer *lexer)
1238 {
1239   while (lex_token (lexer) != T_STOP && lex_token (lexer) != T_ENDCMD)
1240     lex_get (lexer);
1241 }
1242
1243 /* Discards all lookahead tokens in LEXER, then discards all input sources
1244    until it encounters one with error mode LEX_ERROR_TERMINAL or until it
1245    runs out of input sources. */
1246 void
1247 lex_discard_noninteractive (struct lexer *lexer)
1248 {
1249   struct lex_source *src = lex_source__ (lexer);
1250
1251   if (src != NULL)
1252     {
1253       while (!deque_is_empty (&src->deque))
1254         lex_source_pop__ (src);
1255
1256       for (; src != NULL && src->reader->error != LEX_ERROR_TERMINAL;
1257            src = lex_source__ (lexer))
1258         lex_source_destroy (src);
1259     }
1260 }
1261 \f
1262 static size_t
1263 lex_source_max_tail__ (const struct lex_source *src)
1264 {
1265   const struct lex_token *token;
1266   size_t max_tail;
1267
1268   assert (src->seg_pos >= src->line_pos);
1269   max_tail = MIN (src->journal_pos, src->line_pos);
1270
1271   /* Use the oldest token also.  (We know that src->deque cannot be empty
1272      because we are in the process of adding a new token, which is already
1273      initialized enough to use here.) */
1274   token = &src->tokens[deque_back (&src->deque, 0)];
1275   assert (token->token_pos >= token->line_pos);
1276   max_tail = MIN (max_tail, token->line_pos);
1277
1278   return max_tail;
1279 }
1280
1281 static void
1282 lex_source_expand__ (struct lex_source *src)
1283 {
1284   if (src->head - src->tail >= src->allocated)
1285     {
1286       size_t max_tail = lex_source_max_tail__ (src);
1287       if (max_tail > src->tail)
1288         {
1289           /* Advance the tail, freeing up room at the head. */
1290           memmove (src->buffer, src->buffer + (max_tail - src->tail),
1291                    src->head - max_tail);
1292           src->tail = max_tail;
1293         }
1294       else
1295         {
1296           /* Buffer is completely full.  Expand it. */
1297           src->buffer = x2realloc (src->buffer, &src->allocated);
1298         }
1299     }
1300   else
1301     {
1302       /* There's space available at the head of the buffer.  Nothing to do. */
1303     }
1304 }
1305
1306 static void
1307 lex_source_read__ (struct lex_source *src)
1308 {
1309   do
1310     {
1311       lex_source_expand__ (src);
1312
1313       size_t head_ofs = src->head - src->tail;
1314       size_t space = src->allocated - head_ofs;
1315       enum prompt_style prompt = segmenter_get_prompt (&src->segmenter);
1316       size_t n = src->reader->class->read (src->reader, &src->buffer[head_ofs],
1317                                            space, prompt);
1318       assert (n <= space);
1319
1320       if (n == 0)
1321         {
1322           /* End of input. */
1323           src->reader->eof = true;
1324           lex_source_expand__ (src);
1325           return;
1326         }
1327
1328       src->head += n;
1329     }
1330   while (!memchr (&src->buffer[src->seg_pos - src->tail], '\n',
1331                   src->head - src->seg_pos));
1332 }
1333
1334 static struct lex_source *
1335 lex_source__ (const struct lexer *lexer)
1336 {
1337   return (ll_is_empty (&lexer->sources) ? NULL
1338           : ll_data (ll_head (&lexer->sources), struct lex_source, ll));
1339 }
1340
1341 static struct substring
1342 lex_source_get_syntax__ (const struct lex_source *src, int n0, int n1)
1343 {
1344   const struct lex_token *token0 = lex_source_next__ (src, n0);
1345   const struct lex_token *token1 = lex_source_next__ (src, MAX (n0, n1));
1346   size_t start = token0->token_pos;
1347   size_t end = token1->token_pos + token1->token_len;
1348
1349   return ss_buffer (&src->buffer[start - src->tail], end - start);
1350 }
1351
1352 static void
1353 lex_ellipsize__ (struct substring in, char *out, size_t out_size)
1354 {
1355   size_t out_maxlen;
1356   size_t out_len;
1357   int mblen;
1358
1359   assert (out_size >= 16);
1360   out_maxlen = out_size - 1;
1361   if (in.length > out_maxlen - 3)
1362     out_maxlen -= 3;
1363
1364   for (out_len = 0; out_len < in.length; out_len += mblen)
1365     {
1366       if (in.string[out_len] == '\n'
1367           || in.string[out_len] == '\0'
1368           || (in.string[out_len] == '\r'
1369               && out_len + 1 < in.length
1370               && in.string[out_len + 1] == '\n'))
1371         break;
1372
1373       mblen = u8_mblen (CHAR_CAST (const uint8_t *, in.string + out_len),
1374                         in.length - out_len);
1375
1376       if (mblen < 0)
1377         break;
1378
1379       if (out_len + mblen > out_maxlen)
1380         break;
1381     }
1382
1383   memcpy (out, in.string, out_len);
1384   strcpy (&out[out_len], out_len < in.length ? "..." : "");
1385 }
1386
1387 static void
1388 lex_source_error_valist (struct lex_source *src, int n0, int n1,
1389                          const char *format, va_list args)
1390 {
1391   const struct lex_token *token;
1392   struct string s;
1393
1394   ds_init_empty (&s);
1395
1396   token = lex_source_next__ (src, n0);
1397   if (token->token.type == T_ENDCMD)
1398     ds_put_cstr (&s, _("Syntax error at end of command"));
1399   else if (token->from_macro)
1400     {
1401       /* XXX this isn't ideal, we should get the actual syntax */
1402       char *syntax = token_to_string (&token->token);
1403       if (syntax)
1404         ds_put_format (&s, _("Syntax error at `%s'"), syntax);
1405       else
1406         ds_put_cstr (&s, _("Syntax error"));
1407       free (syntax);
1408     }
1409   else
1410     {
1411       struct substring syntax = lex_source_get_syntax__ (src, n0, n1);
1412       if (!ss_is_empty (syntax))
1413         {
1414           char syntax_cstr[64];
1415
1416           lex_ellipsize__ (syntax, syntax_cstr, sizeof syntax_cstr);
1417           ds_put_format (&s, _("Syntax error at `%s'"), syntax_cstr);
1418         }
1419       else
1420         ds_put_cstr (&s, _("Syntax error"));
1421     }
1422
1423   if (format)
1424     {
1425       ds_put_cstr (&s, ": ");
1426       ds_put_vformat (&s, format, args);
1427     }
1428   if (ds_last (&s) != '.')
1429     ds_put_byte (&s, '.');
1430
1431   struct msg m = {
1432     .category = MSG_C_SYNTAX,
1433     .severity = MSG_S_ERROR,
1434     .file_name = src->reader->file_name,
1435     .first_line = lex_source_get_first_line_number (src, n0),
1436     .last_line = lex_source_get_last_line_number (src, n1),
1437     .first_column = lex_source_get_first_column (src, n0),
1438     .last_column = lex_source_get_last_column (src, n1),
1439     .text = ds_steal_cstr (&s),
1440   };
1441   msg_emit (&m);
1442 }
1443
1444 static void PRINTF_FORMAT (2, 3)
1445 lex_get_error (struct lex_source *src, const char *format, ...)
1446 {
1447   va_list args;
1448   int n;
1449
1450   va_start (args, format);
1451
1452   n = deque_count (&src->deque) - 1;
1453   lex_source_error_valist (src, n, n, format, args);
1454   lex_source_pop_front (src);
1455
1456   va_end (args);
1457 }
1458
1459 /* Attempts to append an additional token into SRC's deque, reading more from
1460    the underlying lex_reader if necessary.  Returns true if a new token was
1461    added to SRC's deque, false otherwise. */
1462 static bool
1463 lex_source_try_get (struct lex_source *src)
1464 {
1465   /* State maintained while scanning tokens.  Usually we only need a single
1466      state, but scanner_push() can return SCAN_SAVE to indicate that the state
1467      needs to be saved and possibly restored later with SCAN_BACK. */
1468   struct state
1469     {
1470       struct segmenter segmenter;
1471       enum segment_type last_segment;
1472       int newlines;             /* Number of newlines encountered so far. */
1473       /* Maintained here so we can update lex_source's similar members when we
1474          finish. */
1475       size_t line_pos;
1476       size_t seg_pos;
1477     };
1478
1479   /* Initialize state. */
1480   struct state state =
1481     {
1482       .segmenter = src->segmenter,
1483       .newlines = 0,
1484       .seg_pos = src->seg_pos,
1485       .line_pos = src->line_pos,
1486     };
1487   struct state saved = state;
1488
1489   /* Append a new token to SRC and initialize it. */
1490   struct lex_token *token = lex_push_token__ (src);
1491   struct scanner scanner;
1492   scanner_init (&scanner, &token->token);
1493   token->line_pos = src->line_pos;
1494   token->token_pos = src->seg_pos;
1495   if (src->reader->line_number > 0)
1496     token->first_line = src->reader->line_number + src->n_newlines;
1497   else
1498     token->first_line = 0;
1499
1500   /* Extract segments and pass them through the scanner until we obtain a
1501      token. */
1502   for (;;)
1503     {
1504       /* Extract a segment. */
1505       const char *segment = &src->buffer[state.seg_pos - src->tail];
1506       size_t seg_maxlen = src->head - state.seg_pos;
1507       enum segment_type type;
1508       int seg_len = segmenter_push (&state.segmenter, segment, seg_maxlen,
1509                                     src->reader->eof, &type);
1510       if (seg_len < 0)
1511         {
1512           /* The segmenter needs more input to produce a segment. */
1513           assert (!src->reader->eof);
1514           lex_source_read__ (src);
1515           continue;
1516         }
1517
1518       /* Update state based on the segment. */
1519       state.last_segment = type;
1520       state.seg_pos += seg_len;
1521       if (type == SEG_NEWLINE)
1522         {
1523           state.newlines++;
1524           state.line_pos = state.seg_pos;
1525         }
1526
1527       /* Pass the segment into the scanner and try to get a token out. */
1528       enum scan_result result = scanner_push (&scanner, type,
1529                                               ss_buffer (segment, seg_len),
1530                                               &token->token);
1531       if (result == SCAN_SAVE)
1532         saved = state;
1533       else if (result == SCAN_BACK)
1534         {
1535           state = saved;
1536           break;
1537         }
1538       else if (result == SCAN_DONE)
1539         break;
1540     }
1541
1542   /* If we've reached the end of a line, or the end of a command, then pass
1543      the line to the output engine as a syntax text item.  */
1544   int n_lines = state.newlines;
1545   if (state.last_segment == SEG_END_COMMAND && !src->suppress_next_newline)
1546     {
1547       n_lines++;
1548       src->suppress_next_newline = true;
1549     }
1550   else if (n_lines > 0 && src->suppress_next_newline)
1551     {
1552       n_lines--;
1553       src->suppress_next_newline = false;
1554     }
1555   for (int i = 0; i < n_lines; i++)
1556     {
1557       /* Beginning of line. */
1558       const char *line = &src->buffer[src->journal_pos - src->tail];
1559
1560       /* Calculate line length, including \n or \r\n end-of-line if present.
1561
1562          We use src->head even though that may be beyond what we've actually
1563          converted to tokens (which is only through state.line_pos).  That's
1564          because, if we're emitting the line due to SEG_END_COMMAND, we want to
1565          take the whole line through the newline, not just through the '.'. */
1566       size_t max_len = src->head - src->journal_pos;
1567       const char *newline = memchr (line, '\n', max_len);
1568       size_t line_len = newline ? newline - line + 1 : max_len;
1569
1570       /* Calculate line length excluding end-of-line. */
1571       size_t copy_len = line_len;
1572       if (copy_len > 0 && line[copy_len - 1] == '\n')
1573         copy_len--;
1574       if (copy_len > 0 && line[copy_len - 1] == '\r')
1575         copy_len--;
1576
1577       /* Submit the line as syntax. */
1578       output_item_submit (text_item_create_nocopy (TEXT_ITEM_SYNTAX,
1579                                                    xmemdup0 (line, copy_len),
1580                                                    NULL));
1581
1582       src->journal_pos += line_len;
1583     }
1584
1585   token->token_len = state.seg_pos - src->seg_pos;
1586
1587   src->segmenter = state.segmenter;
1588   src->seg_pos = state.seg_pos;
1589   src->line_pos = state.line_pos;
1590   src->n_newlines += state.newlines;
1591
1592   switch (token->token.type)
1593     {
1594     default:
1595       return true;
1596
1597     case T_STOP:
1598       token->token.type = T_ENDCMD;
1599       src->eof = true;
1600       return true;
1601
1602     case SCAN_BAD_HEX_LENGTH:
1603       lex_get_error (src, _("String of hex digits has %d characters, which "
1604                             "is not a multiple of 2"),
1605                      (int) token->token.number);
1606       return false;
1607
1608     case SCAN_BAD_HEX_DIGIT:
1609     case SCAN_BAD_UNICODE_DIGIT:
1610       lex_get_error (src, _("`%c' is not a valid hex digit"),
1611                      (int) token->token.number);
1612       return false;
1613
1614     case SCAN_BAD_UNICODE_LENGTH:
1615       lex_get_error (src, _("Unicode string contains %d bytes, which is "
1616                             "not in the valid range of 1 to 8 bytes"),
1617                      (int) token->token.number);
1618       return false;
1619
1620     case SCAN_BAD_UNICODE_CODE_POINT:
1621       lex_get_error (src, _("U+%04X is not a valid Unicode code point"),
1622                      (int) token->token.number);
1623       return false;
1624
1625     case SCAN_EXPECTED_QUOTE:
1626       lex_get_error (src, _("Unterminated string constant"));
1627       return false;
1628
1629     case SCAN_EXPECTED_EXPONENT:
1630       lex_get_error (src, _("Missing exponent following `%s'"),
1631                      token->token.string.string);
1632       return false;
1633
1634     case SCAN_UNEXPECTED_CHAR:
1635       {
1636         char c_name[16];
1637         lex_get_error (src, _("Bad character %s in input"),
1638                        uc_name (token->token.number, c_name));
1639         return false;
1640       }
1641
1642     case SCAN_SKIP:
1643       lex_source_pop_front (src);
1644       return false;
1645     }
1646
1647   NOT_REACHED ();
1648 }
1649
1650 static bool
1651 lex_source_get__ (struct lex_source *src)
1652 {
1653   for (;;)
1654     {
1655       if (src->eof)
1656         return false;
1657       else if (lex_source_try_get (src))
1658         return true;
1659     }
1660 }
1661
1662 static bool
1663 lex_source_get (const struct lex_source *src_)
1664 {
1665   struct lex_source *src = CONST_CAST (struct lex_source *, src_);
1666
1667   size_t old_count = deque_count (&src->deque);
1668   if (!lex_source_get__ (src))
1669     return false;
1670
1671   struct macro_expander *me;
1672   int retval = macro_expander_create (src->lexer->macros,
1673                                       &lex_source_front (src)->token, &me);
1674   while (!retval)
1675     {
1676       if (!lex_source_get__ (src))
1677         {
1678           /* This should not be reachable because we always get a T_STOP at the
1679              end of input and the macro_expander should always terminate
1680              expansion on T_STOP. */
1681           NOT_REACHED ();
1682         }
1683
1684       retval = macro_expander_add (me, &lex_source_front (src)->token);
1685     }
1686   if (retval < 0)
1687     {
1688       /* XXX handle case where there's a macro invocation starting from some
1689          later token we've already obtained */
1690       macro_expander_destroy (me);
1691       return true;
1692     }
1693
1694   /* XXX handle case where the macro invocation doesn't use all the tokens */
1695   while (deque_count (&src->deque) > old_count)
1696     lex_source_pop_front (src);
1697
1698   struct tokens expansion = { .tokens = NULL };
1699   macro_expander_get_expansion (me, &expansion);
1700   macro_expander_destroy (me);
1701
1702   for (size_t i = 0; i < expansion.n; i++)
1703     {
1704       *lex_push_token__ (src) = (struct lex_token) {
1705         .token = expansion.tokens[i],
1706         .from_macro = true,
1707         /* XXX the rest */
1708       };
1709     }
1710   free (expansion.tokens);
1711
1712   return true;
1713 }
1714 \f
1715 static void
1716 lex_source_push_endcmd__ (struct lex_source *src)
1717 {
1718   struct lex_token *token = lex_push_token__ (src);
1719   token->token.type = T_ENDCMD;
1720   token->token_pos = 0;
1721   token->token_len = 0;
1722   token->line_pos = 0;
1723   token->first_line = 0;
1724 }
1725
1726 static struct lex_source *
1727 lex_source_create (struct lexer *lexer, struct lex_reader *reader)
1728 {
1729   struct lex_source *src;
1730
1731   src = xzalloc (sizeof *src);
1732   src->reader = reader;
1733   segmenter_init (&src->segmenter, reader->syntax);
1734   src->lexer = lexer;
1735   src->tokens = deque_init (&src->deque, 4, sizeof *src->tokens);
1736
1737   lex_source_push_endcmd__ (src);
1738
1739   return src;
1740 }
1741
1742 static void
1743 lex_source_destroy (struct lex_source *src)
1744 {
1745   char *file_name = src->reader->file_name;
1746   char *encoding = src->reader->encoding;
1747   if (src->reader->class->destroy != NULL)
1748     src->reader->class->destroy (src->reader);
1749   free (file_name);
1750   free (encoding);
1751   free (src->buffer);
1752   while (!deque_is_empty (&src->deque))
1753     lex_source_pop__ (src);
1754   free (src->tokens);
1755   ll_remove (&src->ll);
1756   free (src);
1757 }
1758 \f
1759 struct lex_file_reader
1760   {
1761     struct lex_reader reader;
1762     struct u8_istream *istream;
1763   };
1764
1765 static struct lex_reader_class lex_file_reader_class;
1766
1767 /* Creates and returns a new lex_reader that will read from file FILE_NAME (or
1768    from stdin if FILE_NAME is "-").  The file is expected to be encoded with
1769    ENCODING, which should take one of the forms accepted by
1770    u8_istream_for_file().  SYNTAX and ERROR become the syntax mode and error
1771    mode of the new reader, respectively.
1772
1773    Returns a null pointer if FILE_NAME cannot be opened. */
1774 struct lex_reader *
1775 lex_reader_for_file (const char *file_name, const char *encoding,
1776                      enum segmenter_mode syntax,
1777                      enum lex_error_mode error)
1778 {
1779   struct lex_file_reader *r;
1780   struct u8_istream *istream;
1781
1782   istream = (!strcmp(file_name, "-")
1783              ? u8_istream_for_fd (encoding, STDIN_FILENO)
1784              : u8_istream_for_file (encoding, file_name, O_RDONLY));
1785   if (istream == NULL)
1786     {
1787       msg (ME, _("Opening `%s': %s."), file_name, strerror (errno));
1788       return NULL;
1789     }
1790
1791   r = xmalloc (sizeof *r);
1792   lex_reader_init (&r->reader, &lex_file_reader_class);
1793   r->reader.syntax = syntax;
1794   r->reader.error = error;
1795   r->reader.file_name = xstrdup (file_name);
1796   r->reader.encoding = xstrdup_if_nonnull (encoding);
1797   r->reader.line_number = 1;
1798   r->istream = istream;
1799
1800   return &r->reader;
1801 }
1802
1803 static struct lex_file_reader *
1804 lex_file_reader_cast (struct lex_reader *r)
1805 {
1806   return UP_CAST (r, struct lex_file_reader, reader);
1807 }
1808
1809 static size_t
1810 lex_file_read (struct lex_reader *r_, char *buf, size_t n,
1811                enum prompt_style prompt_style UNUSED)
1812 {
1813   struct lex_file_reader *r = lex_file_reader_cast (r_);
1814   ssize_t n_read = u8_istream_read (r->istream, buf, n);
1815   if (n_read < 0)
1816     {
1817       msg (ME, _("Error reading `%s': %s."), r_->file_name, strerror (errno));
1818       return 0;
1819     }
1820   return n_read;
1821 }
1822
1823 static void
1824 lex_file_close (struct lex_reader *r_)
1825 {
1826   struct lex_file_reader *r = lex_file_reader_cast (r_);
1827
1828   if (u8_istream_fileno (r->istream) != STDIN_FILENO)
1829     {
1830       if (u8_istream_close (r->istream) != 0)
1831         msg (ME, _("Error closing `%s': %s."), r_->file_name, strerror (errno));
1832     }
1833   else
1834     u8_istream_free (r->istream);
1835
1836   free (r);
1837 }
1838
1839 static struct lex_reader_class lex_file_reader_class =
1840   {
1841     lex_file_read,
1842     lex_file_close
1843   };
1844 \f
1845 struct lex_string_reader
1846   {
1847     struct lex_reader reader;
1848     struct substring s;
1849     size_t offset;
1850   };
1851
1852 static struct lex_reader_class lex_string_reader_class;
1853
1854 /* Creates and returns a new lex_reader for the contents of S, which must be
1855    encoded in the given ENCODING.  The new reader takes ownership of S and will free it
1856    with ss_dealloc() when it is closed. */
1857 struct lex_reader *
1858 lex_reader_for_substring_nocopy (struct substring s, const char *encoding)
1859 {
1860   struct lex_string_reader *r;
1861
1862   r = xmalloc (sizeof *r);
1863   lex_reader_init (&r->reader, &lex_string_reader_class);
1864   r->reader.syntax = SEG_MODE_AUTO;
1865   r->reader.encoding = xstrdup_if_nonnull (encoding);
1866   r->s = s;
1867   r->offset = 0;
1868
1869   return &r->reader;
1870 }
1871
1872 /* Creates and returns a new lex_reader for a copy of null-terminated string S,
1873    which must be encoded in ENCODING.  The caller retains ownership of S. */
1874 struct lex_reader *
1875 lex_reader_for_string (const char *s, const char *encoding)
1876 {
1877   struct substring ss;
1878   ss_alloc_substring (&ss, ss_cstr (s));
1879   return lex_reader_for_substring_nocopy (ss, encoding);
1880 }
1881
1882 /* Formats FORMAT as a printf()-like format string and creates and returns a
1883    new lex_reader for the formatted result.  */
1884 struct lex_reader *
1885 lex_reader_for_format (const char *format, const char *encoding, ...)
1886 {
1887   struct lex_reader *r;
1888   va_list args;
1889
1890   va_start (args, encoding);
1891   r = lex_reader_for_substring_nocopy (ss_cstr (xvasprintf (format, args)), encoding);
1892   va_end (args);
1893
1894   return r;
1895 }
1896
1897 static struct lex_string_reader *
1898 lex_string_reader_cast (struct lex_reader *r)
1899 {
1900   return UP_CAST (r, struct lex_string_reader, reader);
1901 }
1902
1903 static size_t
1904 lex_string_read (struct lex_reader *r_, char *buf, size_t n,
1905                  enum prompt_style prompt_style UNUSED)
1906 {
1907   struct lex_string_reader *r = lex_string_reader_cast (r_);
1908   size_t chunk;
1909
1910   chunk = MIN (n, r->s.length - r->offset);
1911   memcpy (buf, r->s.string + r->offset, chunk);
1912   r->offset += chunk;
1913
1914   return chunk;
1915 }
1916
1917 static void
1918 lex_string_close (struct lex_reader *r_)
1919 {
1920   struct lex_string_reader *r = lex_string_reader_cast (r_);
1921
1922   ss_dealloc (&r->s);
1923   free (r);
1924 }
1925
1926 static struct lex_reader_class lex_string_reader_class =
1927   {
1928     lex_string_read,
1929     lex_string_close
1930   };