1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009, 2010 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/>. */
28 #include <language/command.h>
29 #include <data/settings.h>
30 #include <libpspp/assertion.h>
31 #include <libpspp/getl.h>
32 #include <libpspp/message.h>
33 #include <libpspp/str.h>
34 #include <output/journal.h>
35 #include <output/text-item.h>
40 #define _(msgid) gettext (msgid)
41 #define N_(msgid) msgid
45 struct string line_buffer;
47 struct source_stream *ss;
49 int token; /* Current token. */
50 double tokval; /* T_POS_NUM, T_NEG_NUM: the token's value. */
52 char tokid [VAR_NAME_LEN + 1]; /* T_ID: the identifier. */
54 struct string tokstr; /* T_ID, T_STRING: token string value.
55 For T_ID, this is not truncated as is
58 char *prog; /* Pointer to next token in line_buffer. */
59 bool dot; /* True only if this line ends with a terminal dot. */
61 int put_token ; /* If nonzero, next token returned by lex_get().
62 Used only in exceptional circumstances. */
64 struct string put_tokstr;
69 static int parse_id (struct lexer *);
71 /* How a string represents its contents. */
74 CHARACTER_STRING, /* Characters. */
75 BINARY_STRING, /* Binary digits. */
76 OCTAL_STRING, /* Octal digits. */
77 HEX_STRING /* Hexadecimal digits. */
80 static int parse_string (struct lexer *, enum string_type);
84 /* Initializes the lexer. */
86 lex_create (struct source_stream *ss)
88 struct lexer *lexer = xzalloc (sizeof (*lexer));
90 ds_init_empty (&lexer->tokstr);
91 ds_init_empty (&lexer->put_tokstr);
92 ds_init_empty (&lexer->line_buffer);
98 struct source_stream *
99 lex_get_source_stream (const struct lexer *lex)
105 lex_current_syntax_mode (const struct lexer *lex)
107 return source_stream_current_syntax_mode (lex->ss);
111 lex_current_error_mode (const struct lexer *lex)
113 return source_stream_current_error_mode (lex->ss);
118 lex_destroy (struct lexer *lexer)
122 ds_destroy (&lexer->put_tokstr);
123 ds_destroy (&lexer->tokstr);
124 ds_destroy (&lexer->line_buffer);
131 /* Common functions. */
133 /* Copies put_token, lexer->put_tokstr, put_tokval into token, tokstr,
134 tokval, respectively, and sets tokid appropriately. */
136 restore_token (struct lexer *lexer)
138 assert (lexer->put_token != 0);
139 lexer->token = lexer->put_token;
140 ds_assign_string (&lexer->tokstr, &lexer->put_tokstr);
141 str_copy_trunc (lexer->tokid, sizeof lexer->tokid, ds_cstr (&lexer->tokstr));
142 lexer->tokval = lexer->put_tokval;
143 lexer->put_token = 0;
146 /* Copies token, tokstr, lexer->tokval into lexer->put_token, put_tokstr,
147 put_lexer->tokval respectively. */
149 save_token (struct lexer *lexer)
151 lexer->put_token = lexer->token;
152 ds_assign_string (&lexer->put_tokstr, &lexer->tokstr);
153 lexer->put_tokval = lexer->tokval;
156 /* Parses a single token, setting appropriate global variables to
157 indicate the token's attributes. */
159 lex_get (struct lexer *lexer)
164 if (NULL == lexer->prog && ! lex_get_line (lexer) )
166 lexer->token = T_STOP;
170 /* If a token was pushed ahead, return it. */
171 if (lexer->put_token)
173 restore_token (lexer);
179 /* Skip whitespace. */
180 while (c_isspace ((unsigned char) *lexer->prog))
192 else if (!lex_get_line (lexer))
195 lexer->token = T_STOP;
199 if (lexer->put_token)
201 restore_token (lexer);
207 /* Actually parse the token. */
208 ds_clear (&lexer->tokstr);
210 switch (*lexer->prog)
213 case '0': case '1': case '2': case '3': case '4':
214 case '5': case '6': case '7': case '8': case '9':
218 /* `-' can introduce a negative number, or it can be a
219 token by itself. If it is not followed by a digit or a
220 decimal point, it is definitely not a number.
221 Otherwise, it might be either, but most of the time we
222 want it as a number. When the syntax calls for a `-'
223 token, lex_negative_to_dash() must be used to break
224 negative numbers into two tokens. */
225 if (*lexer->prog == '-')
227 ds_put_char (&lexer->tokstr, *lexer->prog++);
228 while (c_isspace ((unsigned char) *lexer->prog))
231 if (!c_isdigit ((unsigned char) *lexer->prog) && *lexer->prog != '.')
236 lexer->token = T_NEG_NUM;
239 lexer->token = T_POS_NUM;
241 /* Parse the number, copying it into tokstr. */
242 while (c_isdigit ((unsigned char) *lexer->prog))
243 ds_put_char (&lexer->tokstr, *lexer->prog++);
244 if (*lexer->prog == '.')
246 ds_put_char (&lexer->tokstr, *lexer->prog++);
247 while (c_isdigit ((unsigned char) *lexer->prog))
248 ds_put_char (&lexer->tokstr, *lexer->prog++);
250 if (*lexer->prog == 'e' || *lexer->prog == 'E')
252 ds_put_char (&lexer->tokstr, *lexer->prog++);
253 if (*lexer->prog == '+' || *lexer->prog == '-')
254 ds_put_char (&lexer->tokstr, *lexer->prog++);
255 while (c_isdigit ((unsigned char) *lexer->prog))
256 ds_put_char (&lexer->tokstr, *lexer->prog++);
259 /* Parse as floating point. */
260 lexer->tokval = c_strtod (ds_cstr (&lexer->tokstr), &tail);
263 msg (SE, _("%s does not form a valid number."),
264 ds_cstr (&lexer->tokstr));
267 ds_clear (&lexer->tokstr);
268 ds_put_char (&lexer->tokstr, '0');
275 lexer->token = parse_string (lexer, CHARACTER_STRING);
278 case '(': case ')': case ',': case '=': case '+': case '/':
280 lexer->token = *lexer->prog++;
284 if (*++lexer->prog == '*')
287 lexer->token = T_EXP;
294 if (*++lexer->prog == '=')
299 else if (*lexer->prog == '>')
309 if (*++lexer->prog == '=')
319 if (*++lexer->prog == '=')
325 lexer->token = T_NOT;
330 lexer->token = T_AND;
339 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
340 lexer->token = parse_string (lexer, BINARY_STRING);
342 lexer->token = parse_id (lexer);
346 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
347 lexer->token = parse_string (lexer, OCTAL_STRING);
349 lexer->token = parse_id (lexer);
353 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
354 lexer->token = parse_string (lexer, HEX_STRING);
356 lexer->token = parse_id (lexer);
360 if (lex_is_id1 (*lexer->prog))
362 lexer->token = parse_id (lexer);
367 unsigned char c = *lexer->prog++;
368 char *c_name = xasprintf (c_isgraph (c) ? "%c" : "\\%o", c);
369 msg (SE, _("Bad character in input: `%s'."), c_name);
378 /* Parses an identifier at the current position into tokid and
380 Returns the correct token type. */
382 parse_id (struct lexer *lexer)
384 struct substring rest_of_line
385 = ss_substr (ds_ss (&lexer->line_buffer),
386 ds_pointer_to_position (&lexer->line_buffer, lexer->prog),
388 struct substring id = ss_head (rest_of_line,
389 lex_id_get_length (rest_of_line));
390 lexer->prog += ss_length (id);
392 ds_assign_substring (&lexer->tokstr, id);
393 str_copy_trunc (lexer->tokid, sizeof lexer->tokid, ds_cstr (&lexer->tokstr));
394 return lex_id_to_token (id);
397 /* Reports an error to the effect that subcommand SBC may only be
400 lex_sbc_only_once (const char *sbc)
402 msg (SE, _("Subcommand %s may only be specified once."), sbc);
405 /* Reports an error to the effect that subcommand SBC is
408 lex_sbc_missing (struct lexer *lexer, const char *sbc)
410 lex_error (lexer, _("missing required subcommand %s"), sbc);
413 /* Prints a syntax error message containing the current token and
414 given message MESSAGE (if non-null). */
416 lex_error (struct lexer *lexer, const char *message, ...)
422 if (lexer->token == T_STOP)
423 ds_put_cstr (&s, _("Syntax error at end of file"));
424 else if (lexer->token == '.')
425 ds_put_cstr (&s, _("Syntax error at end of command"));
428 char *token_rep = lex_token_representation (lexer);
429 ds_put_format (&s, _("Syntax error at `%s'"), token_rep);
437 ds_put_cstr (&s, ": ");
439 va_start (args, message);
440 ds_put_vformat (&s, message, args);
444 msg (SE, "%s.", ds_cstr (&s));
448 /* Checks that we're at end of command.
449 If so, returns a successful command completion code.
450 If not, flags a syntax error and returns an error command
453 lex_end_of_command (struct lexer *lexer)
455 if (lexer->token != '.')
457 lex_error (lexer, _("expecting end of command"));
464 /* Token testing functions. */
466 /* Returns true if the current token is a number. */
468 lex_is_number (struct lexer *lexer)
470 return lexer->token == T_POS_NUM || lexer->token == T_NEG_NUM;
474 /* Returns true if the current token is a string. */
476 lex_is_string (struct lexer *lexer)
478 return lexer->token == T_STRING;
482 /* Returns the value of the current token, which must be a
483 floating point number. */
485 lex_number (struct lexer *lexer)
487 assert (lex_is_number (lexer));
488 return lexer->tokval;
491 /* Returns true iff the current token is an integer. */
493 lex_is_integer (struct lexer *lexer)
495 return (lex_is_number (lexer)
496 && lexer->tokval > LONG_MIN
497 && lexer->tokval <= LONG_MAX
498 && floor (lexer->tokval) == lexer->tokval);
501 /* Returns the value of the current token, which must be an
504 lex_integer (struct lexer *lexer)
506 assert (lex_is_integer (lexer));
507 return lexer->tokval;
510 /* Token matching functions. */
512 /* If TOK is the current token, skips it and returns true
513 Otherwise, returns false. */
515 lex_match (struct lexer *lexer, int t)
517 if (lexer->token == t)
526 /* If the current token is the identifier S, skips it and returns
527 true. The identifier may be abbreviated to its first three
529 Otherwise, returns false. */
531 lex_match_id (struct lexer *lexer, const char *s)
533 return lex_match_id_n (lexer, s, 3);
536 /* If the current token is the identifier S, skips it and returns
537 true. The identifier may be abbreviated to its first N
539 Otherwise, returns false. */
541 lex_match_id_n (struct lexer *lexer, const char *s, size_t n)
543 if (lexer->token == T_ID
544 && lex_id_match_n (ss_cstr (s), ss_cstr (lexer->tokid), n))
553 /* If the current token is integer N, skips it and returns true.
554 Otherwise, returns false. */
556 lex_match_int (struct lexer *lexer, int x)
558 if (lex_is_integer (lexer) && lex_integer (lexer) == x)
567 /* Forced matches. */
569 /* If this token is identifier S, fetches the next token and returns
571 Otherwise, reports an error and returns zero. */
573 lex_force_match_id (struct lexer *lexer, const char *s)
575 if (lex_match_id (lexer, s))
579 lex_error (lexer, _("expecting `%s'"), s);
584 /* If the current token is T, skips the token. Otherwise, reports an
585 error and returns from the current function with return value false. */
587 lex_force_match (struct lexer *lexer, int t)
589 if (lexer->token == t)
596 lex_error (lexer, _("expecting `%s'"), lex_token_name (t));
601 /* If this token is a string, does nothing and returns true.
602 Otherwise, reports an error and returns false. */
604 lex_force_string (struct lexer *lexer)
606 if (lex_is_string (lexer))
610 lex_error (lexer, _("expecting string"));
615 /* If this token is an integer, does nothing and returns true.
616 Otherwise, reports an error and returns false. */
618 lex_force_int (struct lexer *lexer)
620 if (lex_is_integer (lexer))
624 lex_error (lexer, _("expecting integer"));
629 /* If this token is a number, does nothing and returns true.
630 Otherwise, reports an error and returns false. */
632 lex_force_num (struct lexer *lexer)
634 if (lex_is_number (lexer))
637 lex_error (lexer, _("expecting number"));
641 /* If this token is an identifier, does nothing and returns true.
642 Otherwise, reports an error and returns false. */
644 lex_force_id (struct lexer *lexer)
646 if (lexer->token == T_ID)
649 lex_error (lexer, _("expecting identifier"));
653 /* Weird token functions. */
655 /* Returns the first character of the next token, except that if the
656 next token is not an identifier, the character returned will not be
657 a character that can begin an identifier. Specifically, the
658 hexstring lead-in X' causes lookahead() to return '. Note that an
659 alphanumeric return value doesn't guarantee an ID token, it could
660 also be a reserved-word token. */
662 lex_look_ahead (struct lexer *lexer)
664 if (lexer->put_token)
665 return lexer->put_token;
669 if (NULL == lexer->prog && ! lex_get_line (lexer) )
674 while (c_isspace ((unsigned char) *lexer->prog))
681 else if (!lex_get_line (lexer))
684 if (lexer->put_token)
685 return lexer->put_token;
688 if ((toupper ((unsigned char) *lexer->prog) == 'X'
689 || toupper ((unsigned char) *lexer->prog) == 'B'
690 || toupper ((unsigned char) *lexer->prog) == 'O')
691 && (lexer->prog[1] == '\'' || lexer->prog[1] == '"'))
698 /* Makes the current token become the next token to be read; the
699 current token is set to T. */
701 lex_put_back (struct lexer *lexer, int t)
707 /* Makes the current token become the next token to be read; the
708 current token is set to the identifier ID. */
710 lex_put_back_id (struct lexer *lexer, const char *id)
712 assert (lex_id_to_token (ss_cstr (id)) == T_ID);
715 ds_assign_cstr (&lexer->tokstr, id);
716 str_copy_trunc (lexer->tokid, sizeof lexer->tokid, ds_cstr (&lexer->tokstr));
719 /* Weird line processing functions. */
721 /* Returns the entire contents of the current line. */
723 lex_entire_line (const struct lexer *lexer)
725 return ds_cstr (&lexer->line_buffer);
728 const struct string *
729 lex_entire_line_ds (const struct lexer *lexer)
731 return &lexer->line_buffer;
734 /* As lex_entire_line(), but only returns the part of the current line
735 that hasn't already been tokenized. */
737 lex_rest_of_line (const struct lexer *lexer)
742 /* Returns true if the current line ends in a terminal dot,
745 lex_end_dot (const struct lexer *lexer)
750 /* Causes the rest of the current input line to be ignored for
751 tokenization purposes. */
753 lex_discard_line (struct lexer *lexer)
755 ds_cstr (&lexer->line_buffer); /* Ensures ds_end points to something valid */
756 lexer->prog = ds_end (&lexer->line_buffer);
758 lexer->put_token = 0;
762 /* Discards the rest of the current command.
763 When we're reading commands from a file, we skip tokens until
764 a terminal dot or EOF.
765 When we're reading commands interactively from the user,
766 that's just discarding the current line, because presumably
767 the user doesn't want to finish typing a command that will be
770 lex_discard_rest_of_command (struct lexer *lexer)
772 if (!getl_is_interactive (lexer->ss))
774 while (lexer->token != T_STOP && lexer->token != '.')
778 lex_discard_line (lexer);
781 /* Weird line reading functions. */
783 /* Remove C-style comments in STRING, begun by slash-star and
784 terminated by star-slash or newline. */
786 strip_comments (struct string *string)
794 for (cp = ds_cstr (string); *cp; )
796 /* If we're not in a comment, check for quote marks. */
801 else if (*cp == '\'' || *cp == '"')
805 /* If we're not inside a quotation, check for comment. */
808 if (cp[0] == '/' && cp[1] == '*')
815 else if (in_comment && cp[0] == '*' && cp[1] == '/')
824 /* Check commenting. */
831 /* Prepares LINE, which is subject to the given SYNTAX rules, for
832 tokenization by stripping comments and determining whether it
833 is the beginning or end of a command and storing into
834 *LINE_STARTS_COMMAND and *LINE_ENDS_COMMAND appropriately. */
836 lex_preprocess_line (struct string *line,
837 enum syntax_mode syntax,
838 bool *line_starts_command,
839 bool *line_ends_command)
841 strip_comments (line);
842 ds_rtrim (line, ss_cstr (CC_SPACES));
843 *line_ends_command = (ds_chomp (line, settings_get_endcmd ())
844 || (ds_is_empty (line) && settings_get_nulline ()));
845 *line_starts_command = false;
846 if (syntax == GETL_BATCH)
848 int first = ds_first (line);
849 *line_starts_command = !c_isspace (first);
850 if (first == '+' || first == '-')
851 *ds_data (line) = ' ';
855 /* Reads a line, without performing any preprocessing. */
857 lex_get_line_raw (struct lexer *lexer)
859 bool ok = getl_read_line (lexer->ss, &lexer->line_buffer);
862 const char *line = ds_cstr (&lexer->line_buffer);
863 text_item_submit (text_item_create (TEXT_ITEM_SYNTAX, line));
870 /* Reads a line for use by the tokenizer, and preprocesses it by
871 removing comments, stripping trailing whitespace and the
872 terminal dot, and removing leading indentors. */
874 lex_get_line (struct lexer *lexer)
876 bool line_starts_command;
878 if (!lex_get_line_raw (lexer))
881 lex_preprocess_line (&lexer->line_buffer,
882 lex_current_syntax_mode (lexer),
883 &line_starts_command, &lexer->dot);
885 if (line_starts_command)
886 lexer->put_token = '.';
888 lexer->prog = ds_cstr (&lexer->line_buffer);
894 /* Returns the name of a token. */
896 lex_token_name (int token)
898 if (lex_is_keyword (token))
899 return lex_id_name (token);
900 else if (token < 256)
902 static char t[256][2];
912 /* Returns an ASCII representation of the current token as a
913 malloc()'d string. */
915 lex_token_representation (struct lexer *lexer)
919 switch (lexer->token)
924 return ds_xstrdup (&lexer->tokstr);
932 for (sp = ds_cstr (&lexer->tokstr); sp < ds_end (&lexer->tokstr); sp++)
933 if (!c_isprint ((unsigned char) *sp))
939 token_rep = xmalloc (2 + ds_length (&lexer->tokstr) * 2 + 1 + 1);
947 for (sp = ds_cstr (&lexer->tokstr); *sp; )
951 *dp++ = (unsigned char) *sp++;
954 for (sp = ds_cstr (&lexer->tokstr); sp < ds_end (&lexer->tokstr); sp++)
956 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
957 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
967 token_rep = xmalloc (1);
972 return xstrdup ("**");
975 return xstrdup (lex_token_name (lexer->token));
981 /* Really weird functions. */
983 /* Most of the time, a `-' is a lead-in to a negative number. But
984 sometimes it's actually part of the syntax. If a dash can be part
985 of syntax then this function is called to rip it off of a
988 lex_negative_to_dash (struct lexer *lexer)
990 if (lexer->token == T_NEG_NUM)
992 lexer->token = T_POS_NUM;
993 lexer->tokval = -lexer->tokval;
994 ds_assign_substring (&lexer->tokstr, ds_substr (&lexer->tokstr, 1, SIZE_MAX));
1000 /* Skip a COMMENT command. */
1002 lex_skip_comment (struct lexer *lexer)
1006 if (!lex_get_line (lexer))
1008 lexer->put_token = T_STOP;
1013 if (lexer->put_token == '.')
1016 ds_cstr (&lexer->line_buffer); /* Ensures ds_end will point to a valid char */
1017 lexer->prog = ds_end (&lexer->line_buffer);
1023 /* Private functions. */
1025 /* When invoked, tokstr contains a string of binary, octal, or
1026 hex digits, according to TYPE. The string is converted to
1027 characters having the specified values. */
1029 convert_numeric_string_to_char_string (struct lexer *lexer,
1030 enum string_type type)
1032 const char *base_name;
1042 base_name = _("binary");
1047 base_name = _("octal");
1052 base_name = _("hex");
1060 byte_cnt = ds_length (&lexer->tokstr) / chars_per_byte;
1061 if (ds_length (&lexer->tokstr) % chars_per_byte)
1062 msg (SE, _("String of %s digits has %zu characters, which is not a "
1064 base_name, ds_length (&lexer->tokstr), chars_per_byte);
1066 p = ds_cstr (&lexer->tokstr);
1067 for (i = 0; i < byte_cnt; i++)
1073 for (j = 0; j < chars_per_byte; j++, p++)
1077 if (*p >= '0' && *p <= '9')
1081 static const char alpha[] = "abcdef";
1082 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1091 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1093 value = value * base + v;
1096 ds_cstr (&lexer->tokstr)[i] = (unsigned char) value;
1099 ds_truncate (&lexer->tokstr, byte_cnt);
1102 /* Parses a string from the input buffer into tokstr. The input
1103 buffer pointer lexer->prog must point to the initial single or double
1104 quote. TYPE indicates the type of string to be parsed.
1105 Returns token type. */
1107 parse_string (struct lexer *lexer, enum string_type type)
1109 if (type != CHARACTER_STRING)
1112 /* Accumulate the entire string, joining sections indicated by +
1116 /* Single or double quote. */
1117 int c = *lexer->prog++;
1119 /* Accumulate section. */
1122 /* Check end of line. */
1123 if (*lexer->prog == '\0')
1125 msg (SE, _("Unterminated string constant."));
1129 /* Double quote characters to embed them in strings. */
1130 if (*lexer->prog == c)
1132 if (lexer->prog[1] == c)
1138 ds_put_char (&lexer->tokstr, *lexer->prog++);
1142 /* Skip whitespace after final quote mark. */
1143 if (lexer->prog == NULL)
1147 while (c_isspace ((unsigned char) *lexer->prog))
1155 if (!lex_get_line (lexer))
1159 /* Skip plus sign. */
1160 if (*lexer->prog != '+')
1164 /* Skip whitespace after plus sign. */
1165 if (lexer->prog == NULL)
1169 while (c_isspace ((unsigned char) *lexer->prog))
1177 if (!lex_get_line (lexer))
1179 msg (SE, _("Unexpected end of file in string concatenation."));
1184 /* Ensure that a valid string follows. */
1185 if (*lexer->prog != '\'' && *lexer->prog != '"')
1187 msg (SE, _("String expected following `+'."));
1192 /* We come here when we've finished concatenating all the string sections
1193 into one large string. */
1195 if (type != CHARACTER_STRING)
1196 convert_numeric_string_to_char_string (lexer, type);
1201 /* Token Accessor Functions */
1204 lex_token (const struct lexer *lexer)
1206 return lexer->token;
1210 lex_tokval (const struct lexer *lexer)
1212 return lexer->tokval;
1216 lex_tokid (const struct lexer *lexer)
1218 return lexer->tokid;
1221 const struct string *
1222 lex_tokstr (const struct lexer *lexer)
1224 return &lexer->tokstr;
1227 /* If the lexer is positioned at the (pseudo)identifier S, which
1228 may contain a hyphen ('-'), skips it and returns true. Each
1229 half of the identifier may be abbreviated to its first three
1231 Otherwise, returns false. */
1233 lex_match_hyphenated_word (struct lexer *lexer, const char *s)
1235 const char *hyphen = strchr (s, '-');
1237 return lex_match_id (lexer, s);
1238 else if (lexer->token != T_ID
1239 || !lex_id_match (ss_buffer (s, hyphen - s), ss_cstr (lexer->tokid))
1240 || lex_look_ahead (lexer) != '-')
1245 lex_force_match (lexer, '-');
1246 lex_force_match_id (lexer, hyphen + 1);