1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2013, 2016 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include "language/lexer/lexer.h"
33 #include "language/command.h"
34 #include "language/lexer/scan.h"
35 #include "language/lexer/segment.h"
36 #include "language/lexer/token.h"
37 #include "libpspp/assertion.h"
38 #include "libpspp/cast.h"
39 #include "libpspp/deque.h"
40 #include "libpspp/i18n.h"
41 #include "libpspp/ll.h"
42 #include "libpspp/message.h"
43 #include "libpspp/misc.h"
44 #include "libpspp/str.h"
45 #include "libpspp/u8-istream.h"
46 #include "output/journal.h"
47 #include "output/output-item.h"
49 #include "gl/c-ctype.h"
50 #include "gl/minmax.h"
51 #include "gl/xalloc.h"
52 #include "gl/xmemdup0.h"
55 #define _(msgid) gettext (msgid)
56 #define N_(msgid) msgid
58 /* A token within a lex_source. */
61 /* The regular token information. */
64 /* Location of token in terms of the lex_source's buffer.
65 src->tail <= line_pos <= token_pos <= src->head. */
66 size_t token_pos; /* Start of token. */
67 size_t token_len; /* Length of source for token in bytes. */
68 size_t line_pos; /* Start of line containing token_pos. */
69 int first_line; /* Line number at token_pos. */
72 /* A source of tokens, corresponding to a syntax file.
74 This is conceptually a lex_reader wrapped with everything needed to convert
75 its UTF-8 bytes into tokens. */
78 struct ll ll; /* In lexer's list of sources. */
79 struct lex_reader *reader;
80 struct segmenter segmenter;
81 bool eof; /* True if T_STOP was read from 'reader'. */
83 /* Buffer of UTF-8 bytes. */
85 size_t allocated; /* Number of bytes allocated. */
86 size_t tail; /* &buffer[0] offset into UTF-8 source. */
87 size_t head; /* &buffer[head - tail] offset into source. */
89 /* Positions in source file, tail <= pos <= head for each member here. */
90 size_t journal_pos; /* First byte not yet output to journal. */
91 size_t seg_pos; /* First byte not yet scanned as token. */
92 size_t line_pos; /* First byte of line containing seg_pos. */
94 int n_newlines; /* Number of new-lines up to seg_pos. */
95 bool suppress_next_newline;
98 struct deque deque; /* Indexes into 'tokens'. */
99 struct lex_token *tokens; /* Lookahead tokens for parser. */
102 static struct lex_source *lex_source_create (struct lex_reader *);
103 static void lex_source_destroy (struct lex_source *);
108 struct ll_list sources; /* Contains "struct lex_source"s. */
111 static struct lex_source *lex_source__ (const struct lexer *);
112 static const struct lex_token *lex_next__ (const struct lexer *, int n);
113 static void lex_source_push_endcmd__ (struct lex_source *);
115 static void lex_source_pop__ (struct lex_source *);
116 static bool lex_source_get__ (const struct lex_source *);
117 static void lex_source_error_valist (struct lex_source *, int n0, int n1,
118 const char *format, va_list)
119 PRINTF_FORMAT (4, 0);
120 static const struct lex_token *lex_source_next__ (const struct lex_source *,
123 /* Initializes READER with the specified CLASS and otherwise some reasonable
124 defaults. The caller should fill in the others members as desired. */
126 lex_reader_init (struct lex_reader *reader,
127 const struct lex_reader_class *class)
129 reader->class = class;
130 reader->syntax = SEG_MODE_AUTO;
131 reader->error = LEX_ERROR_CONTINUE;
132 reader->file_name = NULL;
133 reader->encoding = NULL;
134 reader->line_number = 0;
138 /* Frees any file name already in READER and replaces it by a copy of
139 FILE_NAME, or if FILE_NAME is null then clears any existing name. */
141 lex_reader_set_file_name (struct lex_reader *reader, const char *file_name)
143 free (reader->file_name);
144 reader->file_name = xstrdup_if_nonnull (file_name);
147 /* Creates and returns a new lexer. */
151 struct lexer *lexer = xzalloc (sizeof *lexer);
152 ll_init (&lexer->sources);
156 /* Destroys LEXER. */
158 lex_destroy (struct lexer *lexer)
162 struct lex_source *source, *next;
164 ll_for_each_safe (source, next, struct lex_source, ll, &lexer->sources)
165 lex_source_destroy (source);
170 /* Inserts READER into LEXER so that the next token read by LEXER comes from
171 READER. Before the caller, LEXER must either be empty or at a T_ENDCMD
174 lex_include (struct lexer *lexer, struct lex_reader *reader)
176 assert (ll_is_empty (&lexer->sources) || lex_token (lexer) == T_ENDCMD);
177 ll_push_head (&lexer->sources, &lex_source_create (reader)->ll);
180 /* Appends READER to LEXER, so that it will be read after all other current
181 readers have already been read. */
183 lex_append (struct lexer *lexer, struct lex_reader *reader)
185 ll_push_tail (&lexer->sources, &lex_source_create (reader)->ll);
190 static struct lex_token *
191 lex_push_token__ (struct lex_source *src)
193 struct lex_token *token;
195 if (deque_is_full (&src->deque))
196 src->tokens = deque_expand (&src->deque, src->tokens, sizeof *src->tokens);
198 token = &src->tokens[deque_push_front (&src->deque)];
199 token->token = (struct token) { .type = T_STOP };
204 lex_source_pop__ (struct lex_source *src)
206 token_uninit (&src->tokens[deque_pop_back (&src->deque)].token);
210 lex_source_pop_front (struct lex_source *src)
212 token_uninit (&src->tokens[deque_pop_front (&src->deque)].token);
215 /* Advances LEXER to the next token, consuming the current token. */
217 lex_get (struct lexer *lexer)
219 struct lex_source *src;
221 src = lex_source__ (lexer);
225 if (!deque_is_empty (&src->deque))
226 lex_source_pop__ (src);
228 while (deque_is_empty (&src->deque))
229 if (!lex_source_get__ (src))
231 lex_source_destroy (src);
232 src = lex_source__ (lexer);
238 /* Issuing errors. */
240 /* Prints a syntax error message containing the current token and
241 given message MESSAGE (if non-null). */
243 lex_error (struct lexer *lexer, const char *format, ...)
247 va_start (args, format);
248 lex_next_error_valist (lexer, 0, 0, format, args);
252 /* Prints a syntax error message containing the current token and
253 given message MESSAGE (if non-null). */
255 lex_error_valist (struct lexer *lexer, const char *format, va_list args)
257 lex_next_error_valist (lexer, 0, 0, format, args);
260 /* Prints a syntax error message containing the current token and
261 given message MESSAGE (if non-null). */
263 lex_next_error (struct lexer *lexer, int n0, int n1, const char *format, ...)
267 va_start (args, format);
268 lex_next_error_valist (lexer, n0, n1, format, args);
272 /* Prints a syntax error message saying that one of the strings provided as
273 varargs, up to the first NULL, is expected. */
275 (lex_error_expecting) (struct lexer *lexer, ...)
279 va_start (args, lexer);
280 lex_error_expecting_valist (lexer, args);
284 /* Prints a syntax error message saying that one of the options provided in
285 ARGS, up to the first NULL, is expected. */
287 lex_error_expecting_valist (struct lexer *lexer, va_list args)
289 enum { MAX_OPTIONS = 9 };
290 const char *options[MAX_OPTIONS];
292 while (n < MAX_OPTIONS)
294 const char *option = va_arg (args, const char *);
298 options[n++] = option;
300 lex_error_expecting_array (lexer, options, n);
304 lex_error_expecting_array (struct lexer *lexer, const char **options, size_t n)
309 lex_error (lexer, NULL);
313 lex_error (lexer, _("expecting %s"), options[0]);
317 lex_error (lexer, _("expecting %s or %s"), options[0], options[1]);
321 lex_error (lexer, _("expecting %s, %s, or %s"), options[0], options[1],
326 lex_error (lexer, _("expecting %s, %s, %s, or %s"),
327 options[0], options[1], options[2], options[3]);
331 lex_error (lexer, _("expecting %s, %s, %s, %s, or %s"),
332 options[0], options[1], options[2], options[3], options[4]);
336 lex_error (lexer, _("expecting %s, %s, %s, %s, %s, or %s"),
337 options[0], options[1], options[2], options[3], options[4],
342 lex_error (lexer, _("expecting %s, %s, %s, %s, %s, %s, or %s"),
343 options[0], options[1], options[2], options[3], options[4],
344 options[5], options[6]);
348 lex_error (lexer, _("expecting %s, %s, %s, %s, %s, %s, %s, or %s"),
349 options[0], options[1], options[2], options[3], options[4],
350 options[5], options[6], options[7]);
354 lex_error (lexer, NULL);
358 /* Reports an error to the effect that subcommand SBC may only be specified
361 This function does not take a lexer as an argument or use lex_error(),
362 because the result would ordinarily just be redundant: "Syntax error at
363 SUBCOMMAND: Subcommand SUBCOMMAND may only be specified once.", which does
364 not help the user find the error. */
366 lex_sbc_only_once (const char *sbc)
368 msg (SE, _("Subcommand %s may only be specified once."), sbc);
371 /* Reports an error to the effect that subcommand SBC is missing.
373 This function does not take a lexer as an argument or use lex_error(),
374 because a missing subcommand can normally be detected only after the whole
375 command has been parsed, and so lex_error() would always report "Syntax
376 error at end of command", which does not help the user find the error. */
378 lex_sbc_missing (const char *sbc)
380 msg (SE, _("Required subcommand %s was not specified."), sbc);
383 /* Reports an error to the effect that specification SPEC may only be specified
384 once within subcommand SBC. */
386 lex_spec_only_once (struct lexer *lexer, const char *sbc, const char *spec)
388 lex_error (lexer, _("%s may only be specified once within subcommand %s"),
392 /* Reports an error to the effect that specification SPEC is missing within
395 lex_spec_missing (struct lexer *lexer, const char *sbc, const char *spec)
397 lex_error (lexer, _("Required %s specification missing from %s subcommand"),
401 /* Prints a syntax error message containing the current token and
402 given message MESSAGE (if non-null). */
404 lex_next_error_valist (struct lexer *lexer, int n0, int n1,
405 const char *format, va_list args)
407 struct lex_source *src = lex_source__ (lexer);
410 lex_source_error_valist (src, n0, n1, format, args);
416 ds_put_format (&s, _("Syntax error at end of input"));
419 ds_put_cstr (&s, ": ");
420 ds_put_vformat (&s, format, args);
422 ds_put_byte (&s, '.');
423 msg (SE, "%s", ds_cstr (&s));
428 /* Checks that we're at end of command.
429 If so, returns a successful command completion code.
430 If not, flags a syntax error and returns an error command
433 lex_end_of_command (struct lexer *lexer)
435 if (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_STOP)
437 lex_error (lexer, _("expecting end of command"));
444 /* Token testing functions. */
446 /* Returns true if the current token is a number. */
448 lex_is_number (const struct lexer *lexer)
450 return lex_next_is_number (lexer, 0);
453 /* Returns true if the current token is a string. */
455 lex_is_string (const struct lexer *lexer)
457 return lex_next_is_string (lexer, 0);
460 /* Returns the value of the current token, which must be a
461 floating point number. */
463 lex_number (const struct lexer *lexer)
465 return lex_next_number (lexer, 0);
468 /* Returns true iff the current token is an integer. */
470 lex_is_integer (const struct lexer *lexer)
472 return lex_next_is_integer (lexer, 0);
475 /* Returns the value of the current token, which must be an
478 lex_integer (const struct lexer *lexer)
480 return lex_next_integer (lexer, 0);
483 /* Token testing functions with lookahead.
485 A value of 0 for N as an argument to any of these functions refers to the
486 current token. Lookahead is limited to the current command. Any N greater
487 than the number of tokens remaining in the current command will be treated
488 as referring to a T_ENDCMD token. */
490 /* Returns true if the token N ahead of the current token is a number. */
492 lex_next_is_number (const struct lexer *lexer, int n)
494 enum token_type next_token = lex_next_token (lexer, n);
495 return next_token == T_POS_NUM || next_token == T_NEG_NUM;
498 /* Returns true if the token N ahead of the current token is a string. */
500 lex_next_is_string (const struct lexer *lexer, int n)
502 return lex_next_token (lexer, n) == T_STRING;
505 /* Returns the value of the token N ahead of the current token, which must be a
506 floating point number. */
508 lex_next_number (const struct lexer *lexer, int n)
510 assert (lex_next_is_number (lexer, n));
511 return lex_next_tokval (lexer, n);
514 /* Returns true if the token N ahead of the current token is an integer. */
516 lex_next_is_integer (const struct lexer *lexer, int n)
520 if (!lex_next_is_number (lexer, n))
523 value = lex_next_tokval (lexer, n);
524 return value > LONG_MIN && value <= LONG_MAX && floor (value) == value;
527 /* Returns the value of the token N ahead of the current token, which must be
530 lex_next_integer (const struct lexer *lexer, int n)
532 assert (lex_next_is_integer (lexer, n));
533 return lex_next_tokval (lexer, n);
536 /* Token matching functions. */
538 /* If the current token has the specified TYPE, skips it and returns true.
539 Otherwise, returns false. */
541 lex_match (struct lexer *lexer, enum token_type type)
543 if (lex_token (lexer) == type)
552 /* If the current token matches IDENTIFIER, skips it and returns true.
553 IDENTIFIER may be abbreviated to its first three letters. Otherwise,
556 IDENTIFIER must be an ASCII string. */
558 lex_match_id (struct lexer *lexer, const char *identifier)
560 return lex_match_id_n (lexer, identifier, 3);
563 /* If the current token is IDENTIFIER, skips it and returns true. IDENTIFIER
564 may be abbreviated to its first N letters. Otherwise, returns false.
566 IDENTIFIER must be an ASCII string. */
568 lex_match_id_n (struct lexer *lexer, const char *identifier, size_t n)
570 if (lex_token (lexer) == T_ID
571 && lex_id_match_n (ss_cstr (identifier), lex_tokss (lexer), n))
580 /* If the current token is integer X, skips it and returns true. Otherwise,
583 lex_match_int (struct lexer *lexer, int x)
585 if (lex_is_integer (lexer) && lex_integer (lexer) == x)
594 /* Forced matches. */
596 /* If this token is IDENTIFIER, skips it and returns true. IDENTIFIER may be
597 abbreviated to its first 3 letters. Otherwise, reports an error and returns
600 IDENTIFIER must be an ASCII string. */
602 lex_force_match_id (struct lexer *lexer, const char *identifier)
604 if (lex_match_id (lexer, identifier))
608 lex_error_expecting (lexer, identifier);
613 /* If the current token has the specified TYPE, skips it and returns true.
614 Otherwise, reports an error and returns false. */
616 lex_force_match (struct lexer *lexer, enum token_type type)
618 if (lex_token (lexer) == type)
625 const char *type_string = token_type_to_string (type);
628 char *s = xasprintf ("`%s'", type_string);
629 lex_error_expecting (lexer, s);
633 lex_error_expecting (lexer, token_type_to_name (type));
639 /* If the current token is a string, does nothing and returns true.
640 Otherwise, reports an error and returns false. */
642 lex_force_string (struct lexer *lexer)
644 if (lex_is_string (lexer))
648 lex_error (lexer, _("expecting string"));
653 /* If the current token is a string or an identifier, does nothing and returns
654 true. Otherwise, reports an error and returns false.
656 This is meant for use in syntactic situations where we want to encourage the
657 user to supply a quoted string, but for compatibility we also accept
658 identifiers. (One example of such a situation is file names.) Therefore,
659 the error message issued when the current token is wrong only says that a
660 string is expected and doesn't mention that an identifier would also be
663 lex_force_string_or_id (struct lexer *lexer)
665 return lex_token (lexer) == T_ID || lex_force_string (lexer);
668 /* If the current token is an integer, does nothing and returns true.
669 Otherwise, reports an error and returns false. */
671 lex_force_int (struct lexer *lexer)
673 if (lex_is_integer (lexer))
677 lex_error (lexer, _("expecting integer"));
682 /* If the current token is an integer in the range MIN...MAX (inclusive), does
683 nothing and returns true. Otherwise, reports an error and returns false.
684 If NAME is nonnull, then it is used in the error message. */
686 lex_force_int_range (struct lexer *lexer, const char *name, long min, long max)
688 bool is_integer = lex_is_integer (lexer);
689 bool too_small = is_integer && lex_integer (lexer) < min;
690 bool too_big = is_integer && lex_integer (lexer) > max;
691 if (is_integer && !too_small && !too_big)
696 /* Weird, maybe a bug in the caller. Just report that we needed an
699 lex_error (lexer, _("Integer expected for %s."), name);
701 lex_error (lexer, _("Integer expected."));
706 lex_error (lexer, _("Expected %ld for %s."), min, name);
708 lex_error (lexer, _("Expected %ld."), min);
710 else if (min + 1 == max)
713 lex_error (lexer, _("Expected %ld or %ld for %s."), min, min + 1, name);
715 lex_error (lexer, _("Expected %ld or %ld."), min, min + 1);
719 bool report_lower_bound = (min > INT_MIN / 2) || too_small;
720 bool report_upper_bound = (max < INT_MAX / 2) || too_big;
722 if (report_lower_bound && report_upper_bound)
726 _("Expected integer between %ld and %ld for %s."),
729 lex_error (lexer, _("Expected integer between %ld and %ld."),
732 else if (report_lower_bound)
737 lex_error (lexer, _("Expected non-negative integer for %s."),
740 lex_error (lexer, _("Expected non-negative integer."));
745 lex_error (lexer, _("Expected positive integer for %s."),
748 lex_error (lexer, _("Expected positive integer."));
751 else if (report_upper_bound)
755 _("Expected integer less than or equal to %ld for %s."),
758 lex_error (lexer, _("Expected integer less than or equal to %ld."),
764 lex_error (lexer, _("Integer expected for %s."), name);
766 lex_error (lexer, _("Integer expected."));
772 /* If the current token is a number, does nothing and returns true.
773 Otherwise, reports an error and returns false. */
775 lex_force_num (struct lexer *lexer)
777 if (lex_is_number (lexer))
780 lex_error (lexer, _("expecting number"));
784 /* If the current token is an identifier, does nothing and returns true.
785 Otherwise, reports an error and returns false. */
787 lex_force_id (struct lexer *lexer)
789 if (lex_token (lexer) == T_ID)
792 lex_error (lexer, _("expecting identifier"));
796 /* Token accessors. */
798 /* Returns the type of LEXER's current token. */
800 lex_token (const struct lexer *lexer)
802 return lex_next_token (lexer, 0);
805 /* Returns the number in LEXER's current token.
807 Only T_NEG_NUM and T_POS_NUM tokens have meaningful values. For other
808 tokens this function will always return zero. */
810 lex_tokval (const struct lexer *lexer)
812 return lex_next_tokval (lexer, 0);
815 /* Returns the null-terminated string in LEXER's current token, UTF-8 encoded.
817 Only T_ID and T_STRING tokens have meaningful strings. For other tokens
818 this functions this function will always return NULL.
820 The UTF-8 encoding of the returned string is correct for variable names and
821 other identifiers. Use filename_to_utf8() to use it as a filename. Use
822 data_in() to use it in a "union value". */
824 lex_tokcstr (const struct lexer *lexer)
826 return lex_next_tokcstr (lexer, 0);
829 /* Returns the string in LEXER's current token, UTF-8 encoded. The string is
830 null-terminated (but the null terminator is not included in the returned
831 substring's 'length').
833 Only T_ID and T_STRING tokens have meaningful strings. For other tokens
834 this functions this function will always return NULL.
836 The UTF-8 encoding of the returned string is correct for variable names and
837 other identifiers. Use filename_to_utf8() to use it as a filename. Use
838 data_in() to use it in a "union value". */
840 lex_tokss (const struct lexer *lexer)
842 return lex_next_tokss (lexer, 0);
847 A value of 0 for N as an argument to any of these functions refers to the
848 current token. Lookahead is limited to the current command. Any N greater
849 than the number of tokens remaining in the current command will be treated
850 as referring to a T_ENDCMD token. */
852 static const struct lex_token *
853 lex_next__ (const struct lexer *lexer_, int n)
855 struct lexer *lexer = CONST_CAST (struct lexer *, lexer_);
856 struct lex_source *src = lex_source__ (lexer);
859 return lex_source_next__ (src, n);
862 static const struct lex_token stop_token = { .token = { .type = T_STOP } };
867 static const struct lex_token *
868 lex_source_next__ (const struct lex_source *src, int n)
870 while (deque_count (&src->deque) <= n)
872 if (!deque_is_empty (&src->deque))
874 struct lex_token *front;
876 front = &src->tokens[deque_front (&src->deque, 0)];
877 if (front->token.type == T_STOP || front->token.type == T_ENDCMD)
881 lex_source_get__ (src);
884 return &src->tokens[deque_back (&src->deque, n)];
887 /* Returns the "struct token" of the token N after the current one in LEXER.
888 The returned pointer can be invalidated by pretty much any succeeding call
889 into the lexer, although the string pointer within the returned token is
890 only invalidated by consuming the token (e.g. with lex_get()). */
892 lex_next (const struct lexer *lexer, int n)
894 return &lex_next__ (lexer, n)->token;
897 /* Returns the type of the token N after the current one in LEXER. */
899 lex_next_token (const struct lexer *lexer, int n)
901 return lex_next (lexer, n)->type;
904 /* Returns the number in the tokn N after the current one in LEXER.
906 Only T_NEG_NUM and T_POS_NUM tokens have meaningful values. For other
907 tokens this function will always return zero. */
909 lex_next_tokval (const struct lexer *lexer, int n)
911 const struct token *token = lex_next (lexer, n);
912 return token->number;
915 /* Returns the null-terminated string in the token N after the current one, in
918 Only T_ID and T_STRING tokens have meaningful strings. For other tokens
919 this functions this function will always return NULL.
921 The UTF-8 encoding of the returned string is correct for variable names and
922 other identifiers. Use filename_to_utf8() to use it as a filename. Use
923 data_in() to use it in a "union value". */
925 lex_next_tokcstr (const struct lexer *lexer, int n)
927 return lex_next_tokss (lexer, n).string;
930 /* Returns the string in the token N after the current one, in UTF-8 encoding.
931 The string is null-terminated (but the null terminator is not included in
932 the returned substring's 'length').
934 Only T_ID, T_MACRO_ID, T_STRING tokens have meaningful strings. For other
935 tokens this functions this function will always return NULL.
937 The UTF-8 encoding of the returned string is correct for variable names and
938 other identifiers. Use filename_to_utf8() to use it as a filename. Use
939 data_in() to use it in a "union value". */
941 lex_next_tokss (const struct lexer *lexer, int n)
943 return lex_next (lexer, n)->string;
947 lex_tokens_match (const struct token *actual, const struct token *expected)
949 if (actual->type != expected->type)
952 switch (actual->type)
956 return actual->number == expected->number;
959 return lex_id_match (expected->string, actual->string);
962 return (actual->string.length == expected->string.length
963 && !memcmp (actual->string.string, expected->string.string,
964 actual->string.length));
971 /* If LEXER is positioned at the sequence of tokens that may be parsed from S,
972 skips it and returns true. Otherwise, returns false.
974 S may consist of an arbitrary sequence of tokens, e.g. "KRUSKAL-WALLIS",
975 "2SLS", or "END INPUT PROGRAM". Identifiers may be abbreviated to their
976 first three letters. */
978 lex_match_phrase (struct lexer *lexer, const char *s)
980 struct string_lexer slex;
985 string_lexer_init (&slex, s, strlen (s), SEG_MODE_INTERACTIVE);
986 while (string_lexer_next (&slex, &token))
987 if (token.type != SCAN_SKIP)
989 bool match = lex_tokens_match (lex_next (lexer, i++), &token);
990 token_uninit (&token);
1001 lex_source_get_first_line_number (const struct lex_source *src, int n)
1003 return lex_source_next__ (src, n)->first_line;
1007 count_newlines (char *s, size_t length)
1012 while ((newline = memchr (s, '\n', length)) != NULL)
1015 length -= (newline + 1) - s;
1023 lex_source_get_last_line_number (const struct lex_source *src, int n)
1025 const struct lex_token *token = lex_source_next__ (src, n);
1027 if (token->first_line == 0)
1031 char *token_str = &src->buffer[token->token_pos - src->tail];
1032 return token->first_line + count_newlines (token_str, token->token_len) + 1;
1037 count_columns (const char *s_, size_t length)
1039 const uint8_t *s = CHAR_CAST (const uint8_t *, s_);
1045 for (ofs = 0; ofs < length; ofs += mblen)
1049 mblen = u8_mbtouc (&uc, s + ofs, length - ofs);
1052 int width = uc_width (uc, "UTF-8");
1057 columns = ROUND_UP (columns + 1, 8);
1064 lex_source_get_first_column (const struct lex_source *src, int n)
1066 const struct lex_token *token = lex_source_next__ (src, n);
1067 return count_columns (&src->buffer[token->line_pos - src->tail],
1068 token->token_pos - token->line_pos);
1072 lex_source_get_last_column (const struct lex_source *src, int n)
1074 const struct lex_token *token = lex_source_next__ (src, n);
1075 char *start, *end, *newline;
1077 start = &src->buffer[token->line_pos - src->tail];
1078 end = &src->buffer[(token->token_pos + token->token_len) - src->tail];
1079 newline = memrchr (start, '\n', end - start);
1080 if (newline != NULL)
1081 start = newline + 1;
1082 return count_columns (start, end - start);
1085 /* Returns the 1-based line number of the start of the syntax that represents
1086 the token N after the current one in LEXER. Returns 0 for a T_STOP token or
1087 if the token is drawn from a source that does not have line numbers. */
1089 lex_get_first_line_number (const struct lexer *lexer, int n)
1091 const struct lex_source *src = lex_source__ (lexer);
1092 return src != NULL ? lex_source_get_first_line_number (src, n) : 0;
1095 /* Returns the 1-based line number of the end of the syntax that represents the
1096 token N after the current one in LEXER, plus 1. Returns 0 for a T_STOP
1097 token or if the token is drawn from a source that does not have line
1100 Most of the time, a single token is wholly within a single line of syntax,
1101 but there are two exceptions: a T_STRING token can be made up of multiple
1102 segments on adjacent lines connected with "+" punctuators, and a T_NEG_NUM
1103 token can consist of a "-" on one line followed by the number on the next.
1106 lex_get_last_line_number (const struct lexer *lexer, int n)
1108 const struct lex_source *src = lex_source__ (lexer);
1109 return src != NULL ? lex_source_get_last_line_number (src, n) : 0;
1112 /* Returns the 1-based column number of the start of the syntax that represents
1113 the token N after the current one in LEXER. Returns 0 for a T_STOP
1116 Column numbers are measured according to the width of characters as shown in
1117 a typical fixed-width font, in which CJK characters have width 2 and
1118 combining characters have width 0. */
1120 lex_get_first_column (const struct lexer *lexer, int n)
1122 const struct lex_source *src = lex_source__ (lexer);
1123 return src != NULL ? lex_source_get_first_column (src, n) : 0;
1126 /* Returns the 1-based column number of the end of the syntax that represents
1127 the token N after the current one in LEXER, plus 1. Returns 0 for a T_STOP
1130 Column numbers are measured according to the width of characters as shown in
1131 a typical fixed-width font, in which CJK characters have width 2 and
1132 combining characters have width 0. */
1134 lex_get_last_column (const struct lexer *lexer, int n)
1136 const struct lex_source *src = lex_source__ (lexer);
1137 return src != NULL ? lex_source_get_last_column (src, n) : 0;
1140 /* Returns the name of the syntax file from which the current command is drawn.
1141 Returns NULL for a T_STOP token or if the command's source does not have
1144 There is no version of this function that takes an N argument because
1145 lookahead only works to the end of a command and any given command is always
1146 within a single syntax file. */
1148 lex_get_file_name (const struct lexer *lexer)
1150 struct lex_source *src = lex_source__ (lexer);
1151 return src == NULL ? NULL : src->reader->file_name;
1155 lex_get_encoding (const struct lexer *lexer)
1157 struct lex_source *src = lex_source__ (lexer);
1158 return src == NULL ? NULL : src->reader->encoding;
1162 /* Returns the syntax mode for the syntax file from which the current drawn is
1163 drawn. Returns SEG_MODE_AUTO for a T_STOP token or if the command's source
1164 does not have line numbers.
1166 There is no version of this function that takes an N argument because
1167 lookahead only works to the end of a command and any given command is always
1168 within a single syntax file. */
1170 lex_get_syntax_mode (const struct lexer *lexer)
1172 struct lex_source *src = lex_source__ (lexer);
1173 return src == NULL ? SEG_MODE_AUTO : src->reader->syntax;
1176 /* Returns the error mode for the syntax file from which the current drawn is
1177 drawn. Returns LEX_ERROR_TERMINAL for a T_STOP token or if the command's
1178 source does not have line numbers.
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. */
1184 lex_get_error_mode (const struct lexer *lexer)
1186 struct lex_source *src = lex_source__ (lexer);
1187 return src == NULL ? LEX_ERROR_TERMINAL : src->reader->error;
1190 /* If the source that LEXER is currently reading has error mode
1191 LEX_ERROR_TERMINAL, discards all buffered input and tokens, so that the next
1192 token to be read comes directly from whatever is next read from the stream.
1194 It makes sense to call this function after encountering an error in a
1195 command entered on the console, because usually the user would prefer not to
1196 have cascading errors. */
1198 lex_interactive_reset (struct lexer *lexer)
1200 struct lex_source *src = lex_source__ (lexer);
1201 if (src != NULL && src->reader->error == LEX_ERROR_TERMINAL)
1203 src->head = src->tail = 0;
1204 src->journal_pos = src->seg_pos = src->line_pos = 0;
1205 src->n_newlines = 0;
1206 src->suppress_next_newline = false;
1207 segmenter_init (&src->segmenter, segmenter_get_mode (&src->segmenter));
1208 while (!deque_is_empty (&src->deque))
1209 lex_source_pop__ (src);
1210 lex_source_push_endcmd__ (src);
1214 /* Advances past any tokens in LEXER up to a T_ENDCMD or T_STOP. */
1216 lex_discard_rest_of_command (struct lexer *lexer)
1218 while (lex_token (lexer) != T_STOP && lex_token (lexer) != T_ENDCMD)
1222 /* Discards all lookahead tokens in LEXER, then discards all input sources
1223 until it encounters one with error mode LEX_ERROR_TERMINAL or until it
1224 runs out of input sources. */
1226 lex_discard_noninteractive (struct lexer *lexer)
1228 struct lex_source *src = lex_source__ (lexer);
1232 while (!deque_is_empty (&src->deque))
1233 lex_source_pop__ (src);
1235 for (; src != NULL && src->reader->error != LEX_ERROR_TERMINAL;
1236 src = lex_source__ (lexer))
1237 lex_source_destroy (src);
1242 lex_source_max_tail__ (const struct lex_source *src)
1244 const struct lex_token *token;
1247 assert (src->seg_pos >= src->line_pos);
1248 max_tail = MIN (src->journal_pos, src->line_pos);
1250 /* Use the oldest token also. (We know that src->deque cannot be empty
1251 because we are in the process of adding a new token, which is already
1252 initialized enough to use here.) */
1253 token = &src->tokens[deque_back (&src->deque, 0)];
1254 assert (token->token_pos >= token->line_pos);
1255 max_tail = MIN (max_tail, token->line_pos);
1261 lex_source_expand__ (struct lex_source *src)
1263 if (src->head - src->tail >= src->allocated)
1265 size_t max_tail = lex_source_max_tail__ (src);
1266 if (max_tail > src->tail)
1268 /* Advance the tail, freeing up room at the head. */
1269 memmove (src->buffer, src->buffer + (max_tail - src->tail),
1270 src->head - max_tail);
1271 src->tail = max_tail;
1275 /* Buffer is completely full. Expand it. */
1276 src->buffer = x2realloc (src->buffer, &src->allocated);
1281 /* There's space available at the head of the buffer. Nothing to do. */
1286 lex_source_read__ (struct lex_source *src)
1290 lex_source_expand__ (src);
1292 size_t head_ofs = src->head - src->tail;
1293 size_t space = src->allocated - head_ofs;
1294 enum prompt_style prompt = segmenter_get_prompt (&src->segmenter);
1295 size_t n = src->reader->class->read (src->reader, &src->buffer[head_ofs],
1297 assert (n <= space);
1302 src->reader->eof = true;
1303 lex_source_expand__ (src);
1309 while (!memchr (&src->buffer[src->seg_pos - src->tail], '\n',
1310 src->head - src->seg_pos));
1313 static struct lex_source *
1314 lex_source__ (const struct lexer *lexer)
1316 return (ll_is_empty (&lexer->sources) ? NULL
1317 : ll_data (ll_head (&lexer->sources), struct lex_source, ll));
1320 static struct substring
1321 lex_source_get_syntax__ (const struct lex_source *src, int n0, int n1)
1323 const struct lex_token *token0 = lex_source_next__ (src, n0);
1324 const struct lex_token *token1 = lex_source_next__ (src, MAX (n0, n1));
1325 size_t start = token0->token_pos;
1326 size_t end = token1->token_pos + token1->token_len;
1328 return ss_buffer (&src->buffer[start - src->tail], end - start);
1332 lex_ellipsize__ (struct substring in, char *out, size_t out_size)
1338 assert (out_size >= 16);
1339 out_maxlen = out_size - 1;
1340 if (in.length > out_maxlen - 3)
1343 for (out_len = 0; out_len < in.length; out_len += mblen)
1345 if (in.string[out_len] == '\n'
1346 || in.string[out_len] == '\0'
1347 || (in.string[out_len] == '\r'
1348 && out_len + 1 < in.length
1349 && in.string[out_len + 1] == '\n'))
1352 mblen = u8_mblen (CHAR_CAST (const uint8_t *, in.string + out_len),
1353 in.length - out_len);
1358 if (out_len + mblen > out_maxlen)
1362 memcpy (out, in.string, out_len);
1363 strcpy (&out[out_len], out_len < in.length ? "..." : "");
1367 lex_source_error_valist (struct lex_source *src, int n0, int n1,
1368 const char *format, va_list args)
1370 const struct lex_token *token;
1375 token = lex_source_next__ (src, n0);
1376 if (token->token.type == T_ENDCMD)
1377 ds_put_cstr (&s, _("Syntax error at end of command"));
1380 struct substring syntax = lex_source_get_syntax__ (src, n0, n1);
1381 if (!ss_is_empty (syntax))
1383 char syntax_cstr[64];
1385 lex_ellipsize__ (syntax, syntax_cstr, sizeof syntax_cstr);
1386 ds_put_format (&s, _("Syntax error at `%s'"), syntax_cstr);
1389 ds_put_cstr (&s, _("Syntax error"));
1394 ds_put_cstr (&s, ": ");
1395 ds_put_vformat (&s, format, args);
1397 if (ds_last (&s) != '.')
1398 ds_put_byte (&s, '.');
1401 .category = MSG_C_SYNTAX,
1402 .severity = MSG_S_ERROR,
1403 .file_name = src->reader->file_name,
1404 .first_line = lex_source_get_first_line_number (src, n0),
1405 .last_line = lex_source_get_last_line_number (src, n1),
1406 .first_column = lex_source_get_first_column (src, n0),
1407 .last_column = lex_source_get_last_column (src, n1),
1408 .text = ds_steal_cstr (&s),
1413 static void PRINTF_FORMAT (2, 3)
1414 lex_get_error (struct lex_source *src, const char *format, ...)
1419 va_start (args, format);
1421 n = deque_count (&src->deque) - 1;
1422 lex_source_error_valist (src, n, n, format, args);
1423 lex_source_pop_front (src);
1428 /* Attempts to append an additional token into SRC's deque, reading more from
1429 the underlying lex_reader if necessary. Returns true if successful, false
1430 if the deque already represents (a suffix of) the whole lex_reader's
1433 lex_source_get__ (const struct lex_source *src_)
1435 struct lex_source *src = CONST_CAST (struct lex_source *, src_);
1439 /* State maintained while scanning tokens. Usually we only need a single
1440 state, but scanner_push() can return SCAN_SAVE to indicate that the state
1441 needs to be saved and possibly restored later with SCAN_BACK. */
1444 struct segmenter segmenter;
1445 enum segment_type last_segment;
1446 int newlines; /* Number of newlines encountered so far. */
1447 /* Maintained here so we can update lex_source's similar members when we
1453 /* Initialize state. */
1454 struct state state =
1456 .segmenter = src->segmenter,
1458 .seg_pos = src->seg_pos,
1459 .line_pos = src->line_pos,
1461 struct state saved = state;
1463 /* Append a new token to SRC and initialize it. */
1464 struct lex_token *token = lex_push_token__ (src);
1465 struct scanner scanner;
1466 scanner_init (&scanner, &token->token);
1467 token->line_pos = src->line_pos;
1468 token->token_pos = src->seg_pos;
1469 if (src->reader->line_number > 0)
1470 token->first_line = src->reader->line_number + src->n_newlines;
1472 token->first_line = 0;
1474 /* Extract segments and pass them through the scanner until we obtain a
1478 /* Extract a segment. */
1479 const char *segment = &src->buffer[state.seg_pos - src->tail];
1480 size_t seg_maxlen = src->head - state.seg_pos;
1481 enum segment_type type;
1482 int seg_len = segmenter_push (&state.segmenter, segment, seg_maxlen,
1483 src->reader->eof, &type);
1486 /* The segmenter needs more input to produce a segment. */
1487 assert (!src->reader->eof);
1488 lex_source_read__ (src);
1492 /* Update state based on the segment. */
1493 state.last_segment = type;
1494 state.seg_pos += seg_len;
1495 if (type == SEG_NEWLINE)
1498 state.line_pos = state.seg_pos;
1501 /* Pass the segment into the scanner and try to get a token out. */
1502 enum scan_result result = scanner_push (&scanner, type,
1503 ss_buffer (segment, seg_len),
1505 if (result == SCAN_SAVE)
1507 else if (result == SCAN_BACK)
1512 else if (result == SCAN_DONE)
1516 /* If we've reached the end of a line, or the end of a command, then pass
1517 the line to the output engine as a syntax text item. */
1518 int n_lines = state.newlines;
1519 if (state.last_segment == SEG_END_COMMAND && !src->suppress_next_newline)
1522 src->suppress_next_newline = true;
1524 else if (n_lines > 0 && src->suppress_next_newline)
1527 src->suppress_next_newline = false;
1529 for (int i = 0; i < n_lines; i++)
1531 /* Beginning of line. */
1532 const char *line = &src->buffer[src->journal_pos - src->tail];
1534 /* Calculate line length, including \n or \r\n end-of-line if present.
1536 We use src->head even though that may be beyond what we've actually
1537 converted to tokens (which is only through state.line_pos). That's
1538 because, if we're emitting the line due to SEG_END_COMMAND, we want to
1539 take the whole line through the newline, not just through the '.'. */
1540 size_t max_len = src->head - src->journal_pos;
1541 const char *newline = memchr (line, '\n', max_len);
1542 size_t line_len = newline ? newline - line + 1 : max_len;
1544 /* Calculate line length excluding end-of-line. */
1545 size_t copy_len = line_len;
1546 if (copy_len > 0 && line[copy_len - 1] == '\n')
1548 if (copy_len > 0 && line[copy_len - 1] == '\r')
1551 /* Submit the line as syntax. */
1552 output_item_submit (text_item_create_nocopy (TEXT_ITEM_SYNTAX,
1553 xmemdup0 (line, copy_len),
1556 src->journal_pos += line_len;
1559 token->token_len = state.seg_pos - src->seg_pos;
1561 src->segmenter = state.segmenter;
1562 src->seg_pos = state.seg_pos;
1563 src->line_pos = state.line_pos;
1564 src->n_newlines += state.newlines;
1566 switch (token->token.type)
1572 token->token.type = T_ENDCMD;
1576 case SCAN_BAD_HEX_LENGTH:
1577 lex_get_error (src, _("String of hex digits has %d characters, which "
1578 "is not a multiple of 2"),
1579 (int) token->token.number);
1582 case SCAN_BAD_HEX_DIGIT:
1583 case SCAN_BAD_UNICODE_DIGIT:
1584 lex_get_error (src, _("`%c' is not a valid hex digit"),
1585 (int) token->token.number);
1588 case SCAN_BAD_UNICODE_LENGTH:
1589 lex_get_error (src, _("Unicode string contains %d bytes, which is "
1590 "not in the valid range of 1 to 8 bytes"),
1591 (int) token->token.number);
1594 case SCAN_BAD_UNICODE_CODE_POINT:
1595 lex_get_error (src, _("U+%04X is not a valid Unicode code point"),
1596 (int) token->token.number);
1599 case SCAN_EXPECTED_QUOTE:
1600 lex_get_error (src, _("Unterminated string constant"));
1603 case SCAN_EXPECTED_EXPONENT:
1604 lex_get_error (src, _("Missing exponent following `%s'"),
1605 token->token.string.string);
1608 case SCAN_UNEXPECTED_CHAR:
1611 lex_get_error (src, _("Bad character %s in input"),
1612 uc_name (token->token.number, c_name));
1617 lex_source_pop_front (src);
1625 lex_source_push_endcmd__ (struct lex_source *src)
1627 struct lex_token *token = lex_push_token__ (src);
1628 token->token.type = T_ENDCMD;
1629 token->token_pos = 0;
1630 token->token_len = 0;
1631 token->line_pos = 0;
1632 token->first_line = 0;
1635 static struct lex_source *
1636 lex_source_create (struct lex_reader *reader)
1638 struct lex_source *src;
1640 src = xzalloc (sizeof *src);
1641 src->reader = reader;
1642 segmenter_init (&src->segmenter, reader->syntax);
1643 src->tokens = deque_init (&src->deque, 4, sizeof *src->tokens);
1645 lex_source_push_endcmd__ (src);
1651 lex_source_destroy (struct lex_source *src)
1653 char *file_name = src->reader->file_name;
1654 char *encoding = src->reader->encoding;
1655 if (src->reader->class->destroy != NULL)
1656 src->reader->class->destroy (src->reader);
1660 while (!deque_is_empty (&src->deque))
1661 lex_source_pop__ (src);
1663 ll_remove (&src->ll);
1667 struct lex_file_reader
1669 struct lex_reader reader;
1670 struct u8_istream *istream;
1673 static struct lex_reader_class lex_file_reader_class;
1675 /* Creates and returns a new lex_reader that will read from file FILE_NAME (or
1676 from stdin if FILE_NAME is "-"). The file is expected to be encoded with
1677 ENCODING, which should take one of the forms accepted by
1678 u8_istream_for_file(). SYNTAX and ERROR become the syntax mode and error
1679 mode of the new reader, respectively.
1681 Returns a null pointer if FILE_NAME cannot be opened. */
1683 lex_reader_for_file (const char *file_name, const char *encoding,
1684 enum segmenter_mode syntax,
1685 enum lex_error_mode error)
1687 struct lex_file_reader *r;
1688 struct u8_istream *istream;
1690 istream = (!strcmp(file_name, "-")
1691 ? u8_istream_for_fd (encoding, STDIN_FILENO)
1692 : u8_istream_for_file (encoding, file_name, O_RDONLY));
1693 if (istream == NULL)
1695 msg (ME, _("Opening `%s': %s."), file_name, strerror (errno));
1699 r = xmalloc (sizeof *r);
1700 lex_reader_init (&r->reader, &lex_file_reader_class);
1701 r->reader.syntax = syntax;
1702 r->reader.error = error;
1703 r->reader.file_name = xstrdup (file_name);
1704 r->reader.encoding = xstrdup_if_nonnull (encoding);
1705 r->reader.line_number = 1;
1706 r->istream = istream;
1711 static struct lex_file_reader *
1712 lex_file_reader_cast (struct lex_reader *r)
1714 return UP_CAST (r, struct lex_file_reader, reader);
1718 lex_file_read (struct lex_reader *r_, char *buf, size_t n,
1719 enum prompt_style prompt_style UNUSED)
1721 struct lex_file_reader *r = lex_file_reader_cast (r_);
1722 ssize_t n_read = u8_istream_read (r->istream, buf, n);
1725 msg (ME, _("Error reading `%s': %s."), r_->file_name, strerror (errno));
1732 lex_file_close (struct lex_reader *r_)
1734 struct lex_file_reader *r = lex_file_reader_cast (r_);
1736 if (u8_istream_fileno (r->istream) != STDIN_FILENO)
1738 if (u8_istream_close (r->istream) != 0)
1739 msg (ME, _("Error closing `%s': %s."), r_->file_name, strerror (errno));
1742 u8_istream_free (r->istream);
1747 static struct lex_reader_class lex_file_reader_class =
1753 struct lex_string_reader
1755 struct lex_reader reader;
1760 static struct lex_reader_class lex_string_reader_class;
1762 /* Creates and returns a new lex_reader for the contents of S, which must be
1763 encoded in the given ENCODING. The new reader takes ownership of S and will free it
1764 with ss_dealloc() when it is closed. */
1766 lex_reader_for_substring_nocopy (struct substring s, const char *encoding)
1768 struct lex_string_reader *r;
1770 r = xmalloc (sizeof *r);
1771 lex_reader_init (&r->reader, &lex_string_reader_class);
1772 r->reader.syntax = SEG_MODE_AUTO;
1773 r->reader.encoding = xstrdup_if_nonnull (encoding);
1780 /* Creates and returns a new lex_reader for a copy of null-terminated string S,
1781 which must be encoded in ENCODING. The caller retains ownership of S. */
1783 lex_reader_for_string (const char *s, const char *encoding)
1785 struct substring ss;
1786 ss_alloc_substring (&ss, ss_cstr (s));
1787 return lex_reader_for_substring_nocopy (ss, encoding);
1790 /* Formats FORMAT as a printf()-like format string and creates and returns a
1791 new lex_reader for the formatted result. */
1793 lex_reader_for_format (const char *format, const char *encoding, ...)
1795 struct lex_reader *r;
1798 va_start (args, encoding);
1799 r = lex_reader_for_substring_nocopy (ss_cstr (xvasprintf (format, args)), encoding);
1805 static struct lex_string_reader *
1806 lex_string_reader_cast (struct lex_reader *r)
1808 return UP_CAST (r, struct lex_string_reader, reader);
1812 lex_string_read (struct lex_reader *r_, char *buf, size_t n,
1813 enum prompt_style prompt_style UNUSED)
1815 struct lex_string_reader *r = lex_string_reader_cast (r_);
1818 chunk = MIN (n, r->s.length - r->offset);
1819 memcpy (buf, r->s.string + r->offset, chunk);
1826 lex_string_close (struct lex_reader *r_)
1828 struct lex_string_reader *r = lex_string_reader_cast (r_);
1834 static struct lex_reader_class lex_string_reader_class =