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 struct string tokstr; /* T_ID, T_STRING: token string value. */
54 char *prog; /* Pointer to next token in line_buffer. */
55 bool dot; /* True only if this line ends with a terminal dot. */
57 int put_token ; /* If nonzero, next token returned by lex_get().
58 Used only in exceptional circumstances. */
60 struct string put_tokstr;
65 static int parse_id (struct lexer *);
67 /* How a string represents its contents. */
70 CHARACTER_STRING, /* Characters. */
71 BINARY_STRING, /* Binary digits. */
72 OCTAL_STRING, /* Octal digits. */
73 HEX_STRING /* Hexadecimal digits. */
76 static int parse_string (struct lexer *, enum string_type);
80 /* Initializes the lexer. */
82 lex_create (struct source_stream *ss)
84 struct lexer *lexer = xzalloc (sizeof (*lexer));
86 ds_init_empty (&lexer->tokstr);
87 ds_init_empty (&lexer->put_tokstr);
88 ds_init_empty (&lexer->line_buffer);
94 struct source_stream *
95 lex_get_source_stream (const struct lexer *lex)
101 lex_current_syntax_mode (const struct lexer *lex)
103 return source_stream_current_syntax_mode (lex->ss);
107 lex_current_error_mode (const struct lexer *lex)
109 return source_stream_current_error_mode (lex->ss);
114 lex_destroy (struct lexer *lexer)
118 ds_destroy (&lexer->put_tokstr);
119 ds_destroy (&lexer->tokstr);
120 ds_destroy (&lexer->line_buffer);
127 /* Common functions. */
129 /* Copies put_token, lexer->put_tokstr, put_tokval into token, tokstr,
130 tokval, respectively, and sets tokid appropriately. */
132 restore_token (struct lexer *lexer)
134 assert (lexer->put_token != 0);
135 lexer->token = lexer->put_token;
136 ds_assign_string (&lexer->tokstr, &lexer->put_tokstr);
137 lexer->tokval = lexer->put_tokval;
138 lexer->put_token = 0;
141 /* Copies token, tokstr, lexer->tokval into lexer->put_token, put_tokstr,
142 put_lexer->tokval respectively. */
144 save_token (struct lexer *lexer)
146 lexer->put_token = lexer->token;
147 ds_assign_string (&lexer->put_tokstr, &lexer->tokstr);
148 lexer->put_tokval = lexer->tokval;
151 /* Parses a single token, setting appropriate global variables to
152 indicate the token's attributes. */
154 lex_get (struct lexer *lexer)
159 if (NULL == lexer->prog && ! lex_get_line (lexer) )
161 lexer->token = T_STOP;
165 /* If a token was pushed ahead, return it. */
166 if (lexer->put_token)
168 restore_token (lexer);
174 /* Skip whitespace. */
175 while (c_isspace ((unsigned char) *lexer->prog))
184 lexer->token = T_ENDCMD;
187 else if (!lex_get_line (lexer))
190 lexer->token = T_STOP;
194 if (lexer->put_token)
196 restore_token (lexer);
202 /* Actually parse the token. */
203 ds_clear (&lexer->tokstr);
205 switch (*lexer->prog)
208 case '0': case '1': case '2': case '3': case '4':
209 case '5': case '6': case '7': case '8': case '9':
213 /* `-' can introduce a negative number, or it can be a token by
215 if (*lexer->prog == '-')
217 ds_put_byte (&lexer->tokstr, *lexer->prog++);
218 while (c_isspace ((unsigned char) *lexer->prog))
221 if (!c_isdigit ((unsigned char) *lexer->prog) && *lexer->prog != '.')
223 lexer->token = T_DASH;
226 lexer->token = T_NEG_NUM;
229 lexer->token = T_POS_NUM;
231 /* Parse the number, copying it into tokstr. */
232 while (c_isdigit ((unsigned char) *lexer->prog))
233 ds_put_byte (&lexer->tokstr, *lexer->prog++);
234 if (*lexer->prog == '.')
236 ds_put_byte (&lexer->tokstr, *lexer->prog++);
237 while (c_isdigit ((unsigned char) *lexer->prog))
238 ds_put_byte (&lexer->tokstr, *lexer->prog++);
240 if (*lexer->prog == 'e' || *lexer->prog == 'E')
242 ds_put_byte (&lexer->tokstr, *lexer->prog++);
243 if (*lexer->prog == '+' || *lexer->prog == '-')
244 ds_put_byte (&lexer->tokstr, *lexer->prog++);
245 while (c_isdigit ((unsigned char) *lexer->prog))
246 ds_put_byte (&lexer->tokstr, *lexer->prog++);
249 /* Parse as floating point. */
250 lexer->tokval = c_strtod (ds_cstr (&lexer->tokstr), &tail);
253 msg (SE, _("%s does not form a valid number."),
254 ds_cstr (&lexer->tokstr));
257 ds_clear (&lexer->tokstr);
258 ds_put_byte (&lexer->tokstr, '0');
265 lexer->token = parse_string (lexer, CHARACTER_STRING);
269 lexer->token = T_PLUS;
274 lexer->token = T_SLASH;
279 lexer->token = T_EQUALS;
284 lexer->token = T_LPAREN;
289 lexer->token = T_RPAREN;
294 lexer->token = T_LBRACK;
299 lexer->token = T_RBRACK;
304 lexer->token = T_COMMA;
309 if (*++lexer->prog == '*')
312 lexer->token = T_EXP;
315 lexer->token = T_ASTERISK;
319 if (*++lexer->prog == '=')
324 else if (*lexer->prog == '>')
334 if (*++lexer->prog == '=')
344 if (*++lexer->prog == '=')
350 lexer->token = T_NOT;
355 lexer->token = T_AND;
364 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
365 lexer->token = parse_string (lexer, BINARY_STRING);
367 lexer->token = parse_id (lexer);
371 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
372 lexer->token = parse_string (lexer, OCTAL_STRING);
374 lexer->token = parse_id (lexer);
378 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
379 lexer->token = parse_string (lexer, HEX_STRING);
381 lexer->token = parse_id (lexer);
385 if (lex_is_id1 (*lexer->prog))
387 lexer->token = parse_id (lexer);
392 unsigned char c = *lexer->prog++;
393 char *c_name = xasprintf (c_isgraph (c) ? "%c" : "\\%o", c);
394 msg (SE, _("Bad character in input: `%s'."), c_name);
403 /* Parses an identifier at the current position into tokstr.
404 Returns the correct token type. */
406 parse_id (struct lexer *lexer)
408 struct substring rest_of_line
409 = ss_substr (ds_ss (&lexer->line_buffer),
410 ds_pointer_to_position (&lexer->line_buffer, lexer->prog),
412 struct substring id = ss_head (rest_of_line,
413 lex_id_get_length (rest_of_line));
414 lexer->prog += ss_length (id);
416 ds_assign_substring (&lexer->tokstr, id);
417 return lex_id_to_token (id);
420 /* Reports an error to the effect that subcommand SBC may only be
423 lex_sbc_only_once (const char *sbc)
425 msg (SE, _("Subcommand %s may only be specified once."), sbc);
428 /* Reports an error to the effect that subcommand SBC is
431 lex_sbc_missing (struct lexer *lexer, const char *sbc)
433 lex_error (lexer, _("missing required subcommand %s"), sbc);
436 /* Prints a syntax error message containing the current token and
437 given message MESSAGE (if non-null). */
439 lex_error (struct lexer *lexer, const char *message, ...)
445 if (lexer->token == T_STOP)
446 ds_put_cstr (&s, _("Syntax error at end of file"));
447 else if (lexer->token == T_ENDCMD)
448 ds_put_cstr (&s, _("Syntax error at end of command"));
451 char *token_rep = lex_token_representation (lexer);
452 ds_put_format (&s, _("Syntax error at `%s'"), token_rep);
460 ds_put_cstr (&s, ": ");
462 va_start (args, message);
463 ds_put_vformat (&s, message, args);
467 msg (SE, "%s.", ds_cstr (&s));
471 /* Checks that we're at end of command.
472 If so, returns a successful command completion code.
473 If not, flags a syntax error and returns an error command
476 lex_end_of_command (struct lexer *lexer)
478 if (lexer->token != T_ENDCMD)
480 lex_error (lexer, _("expecting end of command"));
487 /* Token testing functions. */
489 /* Returns true if the current token is a number. */
491 lex_is_number (struct lexer *lexer)
493 return lexer->token == T_POS_NUM || lexer->token == T_NEG_NUM;
497 /* Returns true if the current token is a string. */
499 lex_is_string (struct lexer *lexer)
501 return lexer->token == T_STRING;
505 /* Returns the value of the current token, which must be a
506 floating point number. */
508 lex_number (struct lexer *lexer)
510 assert (lex_is_number (lexer));
511 return lexer->tokval;
514 /* Returns true iff the current token is an integer. */
516 lex_is_integer (struct lexer *lexer)
518 return (lex_is_number (lexer)
519 && lexer->tokval > LONG_MIN
520 && lexer->tokval <= LONG_MAX
521 && floor (lexer->tokval) == lexer->tokval);
524 /* Returns the value of the current token, which must be an
527 lex_integer (struct lexer *lexer)
529 assert (lex_is_integer (lexer));
530 return lexer->tokval;
533 /* Token matching functions. */
535 /* If TOK is the current token, skips it and returns true
536 Otherwise, returns false. */
538 lex_match (struct lexer *lexer, enum token_type t)
540 if (lexer->token == t)
549 /* If the current token is the identifier S, skips it and returns
550 true. The identifier may be abbreviated to its first three
552 Otherwise, returns false. */
554 lex_match_id (struct lexer *lexer, const char *s)
556 return lex_match_id_n (lexer, s, 3);
559 /* If the current token is the identifier S, skips it and returns
560 true. The identifier may be abbreviated to its first N
562 Otherwise, returns false. */
564 lex_match_id_n (struct lexer *lexer, const char *s, size_t n)
566 if (lexer->token == T_ID
567 && lex_id_match_n (ss_cstr (s), lex_tokss (lexer), n))
576 /* If the current token is integer N, skips it and returns true.
577 Otherwise, returns false. */
579 lex_match_int (struct lexer *lexer, int x)
581 if (lex_is_integer (lexer) && lex_integer (lexer) == x)
590 /* Forced matches. */
592 /* If this token is identifier S, fetches the next token and returns
594 Otherwise, reports an error and returns zero. */
596 lex_force_match_id (struct lexer *lexer, const char *s)
598 if (lex_match_id (lexer, s))
602 lex_error (lexer, _("expecting `%s'"), s);
607 /* If the current token is T, skips the token. Otherwise, reports an
608 error and returns from the current function with return value false. */
610 lex_force_match (struct lexer *lexer, enum token_type t)
612 if (lexer->token == t)
619 lex_error (lexer, _("expecting `%s'"), lex_token_name (t));
624 /* If this token is a string, does nothing and returns true.
625 Otherwise, reports an error and returns false. */
627 lex_force_string (struct lexer *lexer)
629 if (lex_is_string (lexer))
633 lex_error (lexer, _("expecting string"));
638 /* If this token is an integer, does nothing and returns true.
639 Otherwise, reports an error and returns false. */
641 lex_force_int (struct lexer *lexer)
643 if (lex_is_integer (lexer))
647 lex_error (lexer, _("expecting integer"));
652 /* If this token is a number, does nothing and returns true.
653 Otherwise, reports an error and returns false. */
655 lex_force_num (struct lexer *lexer)
657 if (lex_is_number (lexer))
660 lex_error (lexer, _("expecting number"));
664 /* If this token is an identifier, does nothing and returns true.
665 Otherwise, reports an error and returns false. */
667 lex_force_id (struct lexer *lexer)
669 if (lexer->token == T_ID)
672 lex_error (lexer, _("expecting identifier"));
676 /* Weird token functions. */
678 /* Returns the likely type of the next token, or 0 if it's hard to tell. */
680 lex_look_ahead (struct lexer *lexer)
682 if (lexer->put_token)
683 return lexer->put_token;
687 if (NULL == lexer->prog && ! lex_get_line (lexer) )
692 while (c_isspace ((unsigned char) *lexer->prog))
699 else if (!lex_get_line (lexer))
702 if (lexer->put_token)
703 return lexer->put_token;
706 switch (toupper ((unsigned char) *lexer->prog))
708 case 'X': case 'B': case 'O':
709 if (lexer->prog[1] == '\'' || lexer->prog[1] == '"')
717 case '0': case '1': case '2': case '3': case '4':
718 case '5': case '6': case '7': case '8': case '9':
749 return lexer->prog[1] == '*' ? T_EXP : T_ASTERISK;
752 return (lexer->prog[1] == '=' ? T_LE
753 : lexer->prog[1] == '>' ? T_NE
757 return lexer->prog[1] == '=' ? T_GE : T_GT;
760 return lexer->prog[1] == '=' ? T_NE : T_NOT;
769 if (lex_is_id1 (*lexer->prog))
776 /* Makes the current token become the next token to be read; the
777 current token is set to T. */
779 lex_put_back (struct lexer *lexer, enum token_type t)
785 /* Weird line processing functions. */
787 /* Returns the entire contents of the current line. */
789 lex_entire_line (const struct lexer *lexer)
791 return ds_cstr (&lexer->line_buffer);
794 const struct string *
795 lex_entire_line_ds (const struct lexer *lexer)
797 return &lexer->line_buffer;
800 /* As lex_entire_line(), but only returns the part of the current line
801 that hasn't already been tokenized. */
803 lex_rest_of_line (const struct lexer *lexer)
808 /* Returns true if the current line ends in a terminal dot,
811 lex_end_dot (const struct lexer *lexer)
816 /* Causes the rest of the current input line to be ignored for
817 tokenization purposes. */
819 lex_discard_line (struct lexer *lexer)
821 ds_cstr (&lexer->line_buffer); /* Ensures ds_end points to something valid */
822 lexer->prog = ds_end (&lexer->line_buffer);
824 lexer->put_token = 0;
828 /* Discards the rest of the current command.
829 When we're reading commands from a file, we skip tokens until
830 a terminal dot or EOF.
831 When we're reading commands interactively from the user,
832 that's just discarding the current line, because presumably
833 the user doesn't want to finish typing a command that will be
836 lex_discard_rest_of_command (struct lexer *lexer)
838 if (!getl_is_interactive (lexer->ss))
840 while (lexer->token != T_STOP && lexer->token != T_ENDCMD)
844 lex_discard_line (lexer);
847 /* Weird line reading functions. */
849 /* Remove C-style comments in STRING, begun by slash-star and
850 terminated by star-slash or newline. */
852 strip_comments (struct string *string)
860 for (cp = ds_cstr (string); *cp; )
862 /* If we're not in a comment, check for quote marks. */
867 else if (*cp == '\'' || *cp == '"')
871 /* If we're not inside a quotation, check for comment. */
874 if (cp[0] == '/' && cp[1] == '*')
881 else if (in_comment && cp[0] == '*' && cp[1] == '/')
890 /* Check commenting. */
897 /* Prepares LINE, which is subject to the given SYNTAX rules, for
898 tokenization by stripping comments and determining whether it
899 is the beginning or end of a command and storing into
900 *LINE_STARTS_COMMAND and *LINE_ENDS_COMMAND appropriately. */
902 lex_preprocess_line (struct string *line,
903 enum syntax_mode syntax,
904 bool *line_starts_command,
905 bool *line_ends_command)
907 strip_comments (line);
908 ds_rtrim (line, ss_cstr (CC_SPACES));
909 *line_ends_command = ds_chomp (line, '.') || ds_is_empty (line);
910 *line_starts_command = false;
911 if (syntax == GETL_BATCH)
913 int first = ds_first (line);
914 *line_starts_command = !c_isspace (first);
915 if (first == '+' || first == '-')
916 *ds_data (line) = ' ';
920 /* Reads a line, without performing any preprocessing. */
922 lex_get_line_raw (struct lexer *lexer)
924 bool ok = getl_read_line (lexer->ss, &lexer->line_buffer);
927 const char *line = ds_cstr (&lexer->line_buffer);
928 text_item_submit (text_item_create (TEXT_ITEM_SYNTAX, line));
935 /* Reads a line for use by the tokenizer, and preprocesses it by
936 removing comments, stripping trailing whitespace and the
937 terminal dot, and removing leading indentors. */
939 lex_get_line (struct lexer *lexer)
941 bool line_starts_command;
943 if (!lex_get_line_raw (lexer))
946 lex_preprocess_line (&lexer->line_buffer,
947 lex_current_syntax_mode (lexer),
948 &line_starts_command, &lexer->dot);
950 if (line_starts_command)
951 lexer->put_token = T_ENDCMD;
953 lexer->prog = ds_cstr (&lexer->line_buffer);
959 /* Returns the name of a token. */
961 lex_token_name (enum token_type token)
1054 /* Returns an ASCII representation of the current token as a
1055 malloc()'d string. */
1057 lex_token_representation (struct lexer *lexer)
1061 switch (lexer->token)
1066 return ss_xstrdup (lex_tokss (lexer));
1070 struct substring ss;
1074 ss = lex_tokss (lexer);
1075 for (sp = ss_data (ss); sp < ss_end (ss); sp++)
1076 if (!c_isprint ((unsigned char) *sp))
1082 token_rep = xmalloc (2 + ss_length (ss) * 2 + 1 + 1);
1089 for (sp = ss_data (ss); sp < ss_end (ss); sp++)
1094 *dp++ = (unsigned char) *sp;
1098 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
1099 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
1108 return xstrdup (lex_token_name (lexer->token));
1112 /* Really weird functions. */
1114 /* Skip a COMMENT command. */
1116 lex_skip_comment (struct lexer *lexer)
1120 if (!lex_get_line (lexer))
1122 lexer->put_token = T_STOP;
1127 if (lexer->put_token == T_ENDCMD)
1130 ds_cstr (&lexer->line_buffer); /* Ensures ds_end will point to a valid char */
1131 lexer->prog = ds_end (&lexer->line_buffer);
1137 /* Private functions. */
1139 /* When invoked, tokstr contains a string of binary, octal, or
1140 hex digits, according to TYPE. The string is converted to
1141 characters having the specified values. */
1143 convert_numeric_string_to_char_string (struct lexer *lexer,
1144 enum string_type type)
1146 const char *base_name;
1156 base_name = _("binary");
1161 base_name = _("octal");
1166 base_name = _("hex");
1174 byte_cnt = ds_length (&lexer->tokstr) / chars_per_byte;
1175 if (ds_length (&lexer->tokstr) % chars_per_byte)
1176 msg (SE, _("String of %s digits has %zu characters, which is not a "
1178 base_name, ds_length (&lexer->tokstr), chars_per_byte);
1180 p = ds_cstr (&lexer->tokstr);
1181 for (i = 0; i < byte_cnt; i++)
1187 for (j = 0; j < chars_per_byte; j++, p++)
1191 if (*p >= '0' && *p <= '9')
1195 static const char alpha[] = "abcdef";
1196 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1205 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1207 value = value * base + v;
1210 ds_cstr (&lexer->tokstr)[i] = (unsigned char) value;
1213 ds_truncate (&lexer->tokstr, byte_cnt);
1216 /* Parses a string from the input buffer into tokstr. The input
1217 buffer pointer lexer->prog must point to the initial single or double
1218 quote. TYPE indicates the type of string to be parsed.
1219 Returns token type. */
1221 parse_string (struct lexer *lexer, enum string_type type)
1223 if (type != CHARACTER_STRING)
1226 /* Accumulate the entire string, joining sections indicated by +
1230 /* Single or double quote. */
1231 int c = *lexer->prog++;
1233 /* Accumulate section. */
1236 /* Check end of line. */
1237 if (*lexer->prog == '\0')
1239 msg (SE, _("Unterminated string constant."));
1243 /* Double quote characters to embed them in strings. */
1244 if (*lexer->prog == c)
1246 if (lexer->prog[1] == c)
1252 ds_put_byte (&lexer->tokstr, *lexer->prog++);
1256 /* Skip whitespace after final quote mark. */
1257 if (lexer->prog == NULL)
1261 while (c_isspace ((unsigned char) *lexer->prog))
1269 if (!lex_get_line (lexer))
1273 /* Skip plus sign. */
1274 if (*lexer->prog != '+')
1278 /* Skip whitespace after plus sign. */
1279 if (lexer->prog == NULL)
1283 while (c_isspace ((unsigned char) *lexer->prog))
1291 if (!lex_get_line (lexer))
1293 msg (SE, _("Unexpected end of file in string concatenation."));
1298 /* Ensure that a valid string follows. */
1299 if (*lexer->prog != '\'' && *lexer->prog != '"')
1301 msg (SE, _("String expected following `+'."));
1306 /* We come here when we've finished concatenating all the string sections
1307 into one large string. */
1309 if (type != CHARACTER_STRING)
1310 convert_numeric_string_to_char_string (lexer, type);
1315 /* Token Accessor Functions */
1318 lex_token (const struct lexer *lexer)
1320 return lexer->token;
1324 lex_tokval (const struct lexer *lexer)
1326 return lexer->tokval;
1329 /* Returns the null-terminated string value associated with LEXER's current
1330 token. For a T_ID token, this is the identifier, and for a T_STRING token,
1331 this is the string. For other tokens the value is undefined. */
1333 lex_tokcstr (const struct lexer *lexer)
1335 return ds_cstr (&lexer->tokstr);
1338 /* Returns the string value associated with LEXER's current token. For a T_ID
1339 token, this is the identifier, and for a T_STRING token, this is the string.
1340 For other tokens the value is undefined. */
1342 lex_tokss (const struct lexer *lexer)
1344 return ds_ss (&lexer->tokstr);
1347 /* If the lexer is positioned at the (pseudo)identifier S, which
1348 may contain a hyphen ('-'), skips it and returns true. Each
1349 half of the identifier may be abbreviated to its first three
1351 Otherwise, returns false. */
1353 lex_match_hyphenated_word (struct lexer *lexer, const char *s)
1355 const char *hyphen = strchr (s, '-');
1357 return lex_match_id (lexer, s);
1358 else if (lexer->token != T_ID
1359 || !lex_id_match (ss_buffer (s, hyphen - s), lex_tokss (lexer))
1360 || lex_look_ahead (lexer) != T_DASH)
1365 lex_force_match (lexer, T_DASH);
1366 lex_force_match_id (lexer, hyphen + 1);