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