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))
189 lexer->token = T_ENDCMD;
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 token by
220 if (*lexer->prog == '-')
222 ds_put_byte (&lexer->tokstr, *lexer->prog++);
223 while (c_isspace ((unsigned char) *lexer->prog))
226 if (!c_isdigit ((unsigned char) *lexer->prog) && *lexer->prog != '.')
228 lexer->token = T_DASH;
231 lexer->token = T_NEG_NUM;
234 lexer->token = T_POS_NUM;
236 /* Parse the number, copying it into tokstr. */
237 while (c_isdigit ((unsigned char) *lexer->prog))
238 ds_put_byte (&lexer->tokstr, *lexer->prog++);
239 if (*lexer->prog == '.')
241 ds_put_byte (&lexer->tokstr, *lexer->prog++);
242 while (c_isdigit ((unsigned char) *lexer->prog))
243 ds_put_byte (&lexer->tokstr, *lexer->prog++);
245 if (*lexer->prog == 'e' || *lexer->prog == 'E')
247 ds_put_byte (&lexer->tokstr, *lexer->prog++);
248 if (*lexer->prog == '+' || *lexer->prog == '-')
249 ds_put_byte (&lexer->tokstr, *lexer->prog++);
250 while (c_isdigit ((unsigned char) *lexer->prog))
251 ds_put_byte (&lexer->tokstr, *lexer->prog++);
254 /* Parse as floating point. */
255 lexer->tokval = c_strtod (ds_cstr (&lexer->tokstr), &tail);
258 msg (SE, _("%s does not form a valid number."),
259 ds_cstr (&lexer->tokstr));
262 ds_clear (&lexer->tokstr);
263 ds_put_byte (&lexer->tokstr, '0');
270 lexer->token = parse_string (lexer, CHARACTER_STRING);
274 lexer->token = T_PLUS;
279 lexer->token = T_SLASH;
284 lexer->token = T_EQUALS;
289 lexer->token = T_LPAREN;
294 lexer->token = T_RPAREN;
299 lexer->token = T_LBRACK;
304 lexer->token = T_RBRACK;
309 lexer->token = T_COMMA;
314 if (*++lexer->prog == '*')
317 lexer->token = T_EXP;
320 lexer->token = T_ASTERISK;
324 if (*++lexer->prog == '=')
329 else if (*lexer->prog == '>')
339 if (*++lexer->prog == '=')
349 if (*++lexer->prog == '=')
355 lexer->token = T_NOT;
360 lexer->token = T_AND;
369 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
370 lexer->token = parse_string (lexer, BINARY_STRING);
372 lexer->token = parse_id (lexer);
376 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
377 lexer->token = parse_string (lexer, OCTAL_STRING);
379 lexer->token = parse_id (lexer);
383 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
384 lexer->token = parse_string (lexer, HEX_STRING);
386 lexer->token = parse_id (lexer);
390 if (lex_is_id1 (*lexer->prog))
392 lexer->token = parse_id (lexer);
397 unsigned char c = *lexer->prog++;
398 char *c_name = xasprintf (c_isgraph (c) ? "%c" : "\\%o", c);
399 msg (SE, _("Bad character in input: `%s'."), c_name);
408 /* Parses an identifier at the current position into tokid and
410 Returns the correct token type. */
412 parse_id (struct lexer *lexer)
414 struct substring rest_of_line
415 = ss_substr (ds_ss (&lexer->line_buffer),
416 ds_pointer_to_position (&lexer->line_buffer, lexer->prog),
418 struct substring id = ss_head (rest_of_line,
419 lex_id_get_length (rest_of_line));
420 lexer->prog += ss_length (id);
422 ds_assign_substring (&lexer->tokstr, id);
423 str_copy_trunc (lexer->tokid, sizeof lexer->tokid, ds_cstr (&lexer->tokstr));
424 return lex_id_to_token (id);
427 /* Reports an error to the effect that subcommand SBC may only be
430 lex_sbc_only_once (const char *sbc)
432 msg (SE, _("Subcommand %s may only be specified once."), sbc);
435 /* Reports an error to the effect that subcommand SBC is
438 lex_sbc_missing (struct lexer *lexer, const char *sbc)
440 lex_error (lexer, _("missing required subcommand %s"), sbc);
443 /* Prints a syntax error message containing the current token and
444 given message MESSAGE (if non-null). */
446 lex_error (struct lexer *lexer, const char *message, ...)
452 if (lexer->token == T_STOP)
453 ds_put_cstr (&s, _("Syntax error at end of file"));
454 else if (lexer->token == T_ENDCMD)
455 ds_put_cstr (&s, _("Syntax error at end of command"));
458 char *token_rep = lex_token_representation (lexer);
459 ds_put_format (&s, _("Syntax error at `%s'"), token_rep);
467 ds_put_cstr (&s, ": ");
469 va_start (args, message);
470 ds_put_vformat (&s, message, args);
474 msg (SE, "%s.", ds_cstr (&s));
478 /* Checks that we're at end of command.
479 If so, returns a successful command completion code.
480 If not, flags a syntax error and returns an error command
483 lex_end_of_command (struct lexer *lexer)
485 if (lexer->token != T_ENDCMD)
487 lex_error (lexer, _("expecting end of command"));
494 /* Token testing functions. */
496 /* Returns true if the current token is a number. */
498 lex_is_number (struct lexer *lexer)
500 return lexer->token == T_POS_NUM || lexer->token == T_NEG_NUM;
504 /* Returns true if the current token is a string. */
506 lex_is_string (struct lexer *lexer)
508 return lexer->token == T_STRING;
512 /* Returns the value of the current token, which must be a
513 floating point number. */
515 lex_number (struct lexer *lexer)
517 assert (lex_is_number (lexer));
518 return lexer->tokval;
521 /* Returns true iff the current token is an integer. */
523 lex_is_integer (struct lexer *lexer)
525 return (lex_is_number (lexer)
526 && lexer->tokval > LONG_MIN
527 && lexer->tokval <= LONG_MAX
528 && floor (lexer->tokval) == lexer->tokval);
531 /* Returns the value of the current token, which must be an
534 lex_integer (struct lexer *lexer)
536 assert (lex_is_integer (lexer));
537 return lexer->tokval;
540 /* Token matching functions. */
542 /* If TOK is the current token, skips it and returns true
543 Otherwise, returns false. */
545 lex_match (struct lexer *lexer, enum token_type t)
547 if (lexer->token == t)
556 /* If the current token is the identifier S, skips it and returns
557 true. The identifier may be abbreviated to its first three
559 Otherwise, returns false. */
561 lex_match_id (struct lexer *lexer, const char *s)
563 return lex_match_id_n (lexer, s, 3);
566 /* If the current token is the identifier S, skips it and returns
567 true. The identifier may be abbreviated to its first N
569 Otherwise, returns false. */
571 lex_match_id_n (struct lexer *lexer, const char *s, size_t n)
573 if (lexer->token == T_ID
574 && lex_id_match_n (ss_cstr (s), ss_cstr (lexer->tokid), n))
583 /* If the current token is integer N, skips it and returns true.
584 Otherwise, returns false. */
586 lex_match_int (struct lexer *lexer, int x)
588 if (lex_is_integer (lexer) && lex_integer (lexer) == x)
597 /* Forced matches. */
599 /* If this token is identifier S, fetches the next token and returns
601 Otherwise, reports an error and returns zero. */
603 lex_force_match_id (struct lexer *lexer, const char *s)
605 if (lex_match_id (lexer, s))
609 lex_error (lexer, _("expecting `%s'"), s);
614 /* If the current token is T, skips the token. Otherwise, reports an
615 error and returns from the current function with return value false. */
617 lex_force_match (struct lexer *lexer, enum token_type t)
619 if (lexer->token == t)
626 lex_error (lexer, _("expecting `%s'"), lex_token_name (t));
631 /* If this token is a string, does nothing and returns true.
632 Otherwise, reports an error and returns false. */
634 lex_force_string (struct lexer *lexer)
636 if (lex_is_string (lexer))
640 lex_error (lexer, _("expecting string"));
645 /* If this token is an integer, does nothing and returns true.
646 Otherwise, reports an error and returns false. */
648 lex_force_int (struct lexer *lexer)
650 if (lex_is_integer (lexer))
654 lex_error (lexer, _("expecting integer"));
659 /* If this token is a number, does nothing and returns true.
660 Otherwise, reports an error and returns false. */
662 lex_force_num (struct lexer *lexer)
664 if (lex_is_number (lexer))
667 lex_error (lexer, _("expecting number"));
671 /* If this token is an identifier, does nothing and returns true.
672 Otherwise, reports an error and returns false. */
674 lex_force_id (struct lexer *lexer)
676 if (lexer->token == T_ID)
679 lex_error (lexer, _("expecting identifier"));
683 /* Weird token functions. */
685 /* Returns the likely type of the next token, or 0 if it's hard to tell. */
687 lex_look_ahead (struct lexer *lexer)
689 if (lexer->put_token)
690 return lexer->put_token;
694 if (NULL == lexer->prog && ! lex_get_line (lexer) )
699 while (c_isspace ((unsigned char) *lexer->prog))
706 else if (!lex_get_line (lexer))
709 if (lexer->put_token)
710 return lexer->put_token;
713 switch (toupper ((unsigned char) *lexer->prog))
715 case 'X': case 'B': case 'O':
716 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
724 case '0': case '1': case '2': case '3': case '4':
725 case '5': case '6': case '7': case '8': case '9':
756 return lexer->prog[1] == '*' ? T_EXP : T_ASTERISK;
759 return (lexer->prog[1] == '=' ? T_LE
760 : lexer->prog[1] == '>' ? T_NE
764 return lexer->prog[1] == '=' ? T_GE : T_GT;
767 return lexer->prog[1] == '=' ? T_NE : T_NOT;
776 if (lex_is_id1 (*lexer->prog))
783 /* Makes the current token become the next token to be read; the
784 current token is set to T. */
786 lex_put_back (struct lexer *lexer, enum token_type t)
792 /* Makes the current token become the next token to be read; the
793 current token is set to the identifier ID. */
795 lex_put_back_id (struct lexer *lexer, const char *id)
797 assert (lex_id_to_token (ss_cstr (id)) == T_ID);
800 ds_assign_cstr (&lexer->tokstr, id);
801 str_copy_trunc (lexer->tokid, sizeof lexer->tokid, ds_cstr (&lexer->tokstr));
804 /* Weird line processing functions. */
806 /* Returns the entire contents of the current line. */
808 lex_entire_line (const struct lexer *lexer)
810 return ds_cstr (&lexer->line_buffer);
813 const struct string *
814 lex_entire_line_ds (const struct lexer *lexer)
816 return &lexer->line_buffer;
819 /* As lex_entire_line(), but only returns the part of the current line
820 that hasn't already been tokenized. */
822 lex_rest_of_line (const struct lexer *lexer)
827 /* Returns true if the current line ends in a terminal dot,
830 lex_end_dot (const struct lexer *lexer)
835 /* Causes the rest of the current input line to be ignored for
836 tokenization purposes. */
838 lex_discard_line (struct lexer *lexer)
840 ds_cstr (&lexer->line_buffer); /* Ensures ds_end points to something valid */
841 lexer->prog = ds_end (&lexer->line_buffer);
843 lexer->put_token = 0;
847 /* Discards the rest of the current command.
848 When we're reading commands from a file, we skip tokens until
849 a terminal dot or EOF.
850 When we're reading commands interactively from the user,
851 that's just discarding the current line, because presumably
852 the user doesn't want to finish typing a command that will be
855 lex_discard_rest_of_command (struct lexer *lexer)
857 if (!getl_is_interactive (lexer->ss))
859 while (lexer->token != T_STOP && lexer->token != T_ENDCMD)
863 lex_discard_line (lexer);
866 /* Weird line reading functions. */
868 /* Remove C-style comments in STRING, begun by slash-star and
869 terminated by star-slash or newline. */
871 strip_comments (struct string *string)
879 for (cp = ds_cstr (string); *cp; )
881 /* If we're not in a comment, check for quote marks. */
886 else if (*cp == '\'' || *cp == '"')
890 /* If we're not inside a quotation, check for comment. */
893 if (cp[0] == '/' && cp[1] == '*')
900 else if (in_comment && cp[0] == '*' && cp[1] == '/')
909 /* Check commenting. */
916 /* Prepares LINE, which is subject to the given SYNTAX rules, for
917 tokenization by stripping comments and determining whether it
918 is the beginning or end of a command and storing into
919 *LINE_STARTS_COMMAND and *LINE_ENDS_COMMAND appropriately. */
921 lex_preprocess_line (struct string *line,
922 enum syntax_mode syntax,
923 bool *line_starts_command,
924 bool *line_ends_command)
926 strip_comments (line);
927 ds_rtrim (line, ss_cstr (CC_SPACES));
928 *line_ends_command = (ds_chomp (line, settings_get_endcmd ())
929 || (ds_is_empty (line) && settings_get_nulline ()));
930 *line_starts_command = false;
931 if (syntax == GETL_BATCH)
933 int first = ds_first (line);
934 *line_starts_command = !c_isspace (first);
935 if (first == '+' || first == '-')
936 *ds_data (line) = ' ';
940 /* Reads a line, without performing any preprocessing. */
942 lex_get_line_raw (struct lexer *lexer)
944 bool ok = getl_read_line (lexer->ss, &lexer->line_buffer);
947 const char *line = ds_cstr (&lexer->line_buffer);
948 text_item_submit (text_item_create (TEXT_ITEM_SYNTAX, line));
955 /* Reads a line for use by the tokenizer, and preprocesses it by
956 removing comments, stripping trailing whitespace and the
957 terminal dot, and removing leading indentors. */
959 lex_get_line (struct lexer *lexer)
961 bool line_starts_command;
963 if (!lex_get_line_raw (lexer))
966 lex_preprocess_line (&lexer->line_buffer,
967 lex_current_syntax_mode (lexer),
968 &line_starts_command, &lexer->dot);
970 if (line_starts_command)
971 lexer->put_token = T_ENDCMD;
973 lexer->prog = ds_cstr (&lexer->line_buffer);
979 /* Returns the name of a token. */
981 lex_token_name (enum token_type token)
1073 /* Returns an ASCII representation of the current token as a
1074 malloc()'d string. */
1076 lex_token_representation (struct lexer *lexer)
1080 switch (lexer->token)
1085 return ds_xstrdup (&lexer->tokstr);
1092 for (sp = ds_cstr (&lexer->tokstr); sp < ds_end (&lexer->tokstr); sp++)
1093 if (!c_isprint ((unsigned char) *sp))
1099 token_rep = xmalloc (2 + ds_length (&lexer->tokstr) * 2 + 1 + 1);
1107 for (sp = ds_cstr (&lexer->tokstr); *sp; )
1111 *dp++ = (unsigned char) *sp++;
1114 for (sp = ds_cstr (&lexer->tokstr); sp < ds_end (&lexer->tokstr); sp++)
1116 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
1117 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
1126 return xstrdup (lex_token_name (lexer->token));
1130 /* Really weird functions. */
1132 /* Skip a COMMENT command. */
1134 lex_skip_comment (struct lexer *lexer)
1138 if (!lex_get_line (lexer))
1140 lexer->put_token = T_STOP;
1145 if (lexer->put_token == T_ENDCMD)
1148 ds_cstr (&lexer->line_buffer); /* Ensures ds_end will point to a valid char */
1149 lexer->prog = ds_end (&lexer->line_buffer);
1155 /* Private functions. */
1157 /* When invoked, tokstr contains a string of binary, octal, or
1158 hex digits, according to TYPE. The string is converted to
1159 characters having the specified values. */
1161 convert_numeric_string_to_char_string (struct lexer *lexer,
1162 enum string_type type)
1164 const char *base_name;
1174 base_name = _("binary");
1179 base_name = _("octal");
1184 base_name = _("hex");
1192 byte_cnt = ds_length (&lexer->tokstr) / chars_per_byte;
1193 if (ds_length (&lexer->tokstr) % chars_per_byte)
1194 msg (SE, _("String of %s digits has %zu characters, which is not a "
1196 base_name, ds_length (&lexer->tokstr), chars_per_byte);
1198 p = ds_cstr (&lexer->tokstr);
1199 for (i = 0; i < byte_cnt; i++)
1205 for (j = 0; j < chars_per_byte; j++, p++)
1209 if (*p >= '0' && *p <= '9')
1213 static const char alpha[] = "abcdef";
1214 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1223 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1225 value = value * base + v;
1228 ds_cstr (&lexer->tokstr)[i] = (unsigned char) value;
1231 ds_truncate (&lexer->tokstr, byte_cnt);
1234 /* Parses a string from the input buffer into tokstr. The input
1235 buffer pointer lexer->prog must point to the initial single or double
1236 quote. TYPE indicates the type of string to be parsed.
1237 Returns token type. */
1239 parse_string (struct lexer *lexer, enum string_type type)
1241 if (type != CHARACTER_STRING)
1244 /* Accumulate the entire string, joining sections indicated by +
1248 /* Single or double quote. */
1249 int c = *lexer->prog++;
1251 /* Accumulate section. */
1254 /* Check end of line. */
1255 if (*lexer->prog == '\0')
1257 msg (SE, _("Unterminated string constant."));
1261 /* Double quote characters to embed them in strings. */
1262 if (*lexer->prog == c)
1264 if (lexer->prog[1] == c)
1270 ds_put_byte (&lexer->tokstr, *lexer->prog++);
1274 /* Skip whitespace after final quote mark. */
1275 if (lexer->prog == NULL)
1279 while (c_isspace ((unsigned char) *lexer->prog))
1287 if (!lex_get_line (lexer))
1291 /* Skip plus sign. */
1292 if (*lexer->prog != '+')
1296 /* Skip whitespace after plus sign. */
1297 if (lexer->prog == NULL)
1301 while (c_isspace ((unsigned char) *lexer->prog))
1309 if (!lex_get_line (lexer))
1311 msg (SE, _("Unexpected end of file in string concatenation."));
1316 /* Ensure that a valid string follows. */
1317 if (*lexer->prog != '\'' && *lexer->prog != '"')
1319 msg (SE, _("String expected following `+'."));
1324 /* We come here when we've finished concatenating all the string sections
1325 into one large string. */
1327 if (type != CHARACTER_STRING)
1328 convert_numeric_string_to_char_string (lexer, type);
1333 /* Token Accessor Functions */
1336 lex_token (const struct lexer *lexer)
1338 return lexer->token;
1342 lex_tokval (const struct lexer *lexer)
1344 return lexer->tokval;
1348 lex_tokid (const struct lexer *lexer)
1350 return lexer->tokid;
1353 const struct string *
1354 lex_tokstr (const struct lexer *lexer)
1356 return &lexer->tokstr;
1359 /* If the lexer is positioned at the (pseudo)identifier S, which
1360 may contain a hyphen ('-'), skips it and returns true. Each
1361 half of the identifier may be abbreviated to its first three
1363 Otherwise, returns false. */
1365 lex_match_hyphenated_word (struct lexer *lexer, const char *s)
1367 const char *hyphen = strchr (s, '-');
1369 return lex_match_id (lexer, s);
1370 else if (lexer->token != T_ID
1371 || !lex_id_match (ss_buffer (s, hyphen - s), ss_cstr (lexer->tokid))
1372 || lex_look_ahead (lexer) != T_DASH)
1377 lex_force_match (lexer, T_DASH);
1378 lex_force_match_id (lexer, hyphen + 1);