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