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