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 /* Makes the current token become the next token to be read; the
786 current token is set to the identifier ID. */
788 lex_put_back_id (struct lexer *lexer, const char *id)
790 assert (lex_id_to_token (ss_cstr (id)) == T_ID);
793 ds_assign_cstr (&lexer->tokstr, id);
796 /* Weird line processing functions. */
798 /* Returns the entire contents of the current line. */
800 lex_entire_line (const struct lexer *lexer)
802 return ds_cstr (&lexer->line_buffer);
805 const struct string *
806 lex_entire_line_ds (const struct lexer *lexer)
808 return &lexer->line_buffer;
811 /* As lex_entire_line(), but only returns the part of the current line
812 that hasn't already been tokenized. */
814 lex_rest_of_line (const struct lexer *lexer)
819 /* Returns true if the current line ends in a terminal dot,
822 lex_end_dot (const struct lexer *lexer)
827 /* Causes the rest of the current input line to be ignored for
828 tokenization purposes. */
830 lex_discard_line (struct lexer *lexer)
832 ds_cstr (&lexer->line_buffer); /* Ensures ds_end points to something valid */
833 lexer->prog = ds_end (&lexer->line_buffer);
835 lexer->put_token = 0;
839 /* Discards the rest of the current command.
840 When we're reading commands from a file, we skip tokens until
841 a terminal dot or EOF.
842 When we're reading commands interactively from the user,
843 that's just discarding the current line, because presumably
844 the user doesn't want to finish typing a command that will be
847 lex_discard_rest_of_command (struct lexer *lexer)
849 if (!getl_is_interactive (lexer->ss))
851 while (lexer->token != T_STOP && lexer->token != T_ENDCMD)
855 lex_discard_line (lexer);
858 /* Weird line reading functions. */
860 /* Remove C-style comments in STRING, begun by slash-star and
861 terminated by star-slash or newline. */
863 strip_comments (struct string *string)
871 for (cp = ds_cstr (string); *cp; )
873 /* If we're not in a comment, check for quote marks. */
878 else if (*cp == '\'' || *cp == '"')
882 /* If we're not inside a quotation, check for comment. */
885 if (cp[0] == '/' && cp[1] == '*')
892 else if (in_comment && cp[0] == '*' && cp[1] == '/')
901 /* Check commenting. */
908 /* Prepares LINE, which is subject to the given SYNTAX rules, for
909 tokenization by stripping comments and determining whether it
910 is the beginning or end of a command and storing into
911 *LINE_STARTS_COMMAND and *LINE_ENDS_COMMAND appropriately. */
913 lex_preprocess_line (struct string *line,
914 enum syntax_mode syntax,
915 bool *line_starts_command,
916 bool *line_ends_command)
918 strip_comments (line);
919 ds_rtrim (line, ss_cstr (CC_SPACES));
920 *line_ends_command = (ds_chomp (line, settings_get_endcmd ())
921 || (ds_is_empty (line) && settings_get_nulline ()));
922 *line_starts_command = false;
923 if (syntax == GETL_BATCH)
925 int first = ds_first (line);
926 *line_starts_command = !c_isspace (first);
927 if (first == '+' || first == '-')
928 *ds_data (line) = ' ';
932 /* Reads a line, without performing any preprocessing. */
934 lex_get_line_raw (struct lexer *lexer)
936 bool ok = getl_read_line (lexer->ss, &lexer->line_buffer);
939 const char *line = ds_cstr (&lexer->line_buffer);
940 text_item_submit (text_item_create (TEXT_ITEM_SYNTAX, line));
947 /* Reads a line for use by the tokenizer, and preprocesses it by
948 removing comments, stripping trailing whitespace and the
949 terminal dot, and removing leading indentors. */
951 lex_get_line (struct lexer *lexer)
953 bool line_starts_command;
955 if (!lex_get_line_raw (lexer))
958 lex_preprocess_line (&lexer->line_buffer,
959 lex_current_syntax_mode (lexer),
960 &line_starts_command, &lexer->dot);
962 if (line_starts_command)
963 lexer->put_token = T_ENDCMD;
965 lexer->prog = ds_cstr (&lexer->line_buffer);
971 /* Returns the name of a token. */
973 lex_token_name (enum token_type token)
1065 /* Returns an ASCII representation of the current token as a
1066 malloc()'d string. */
1068 lex_token_representation (struct lexer *lexer)
1072 switch (lexer->token)
1077 return ss_xstrdup (lex_tokss (lexer));
1081 struct substring ss;
1085 ss = lex_tokss (lexer);
1086 for (sp = ss_data (ss); sp < ss_end (ss); sp++)
1087 if (!c_isprint ((unsigned char) *sp))
1093 token_rep = xmalloc (2 + ss_length (ss) * 2 + 1 + 1);
1100 for (sp = ss_data (ss); sp < ss_end (ss); sp++)
1105 *dp++ = (unsigned char) *sp;
1109 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
1110 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
1119 return xstrdup (lex_token_name (lexer->token));
1123 /* Really weird functions. */
1125 /* Skip a COMMENT command. */
1127 lex_skip_comment (struct lexer *lexer)
1131 if (!lex_get_line (lexer))
1133 lexer->put_token = T_STOP;
1138 if (lexer->put_token == T_ENDCMD)
1141 ds_cstr (&lexer->line_buffer); /* Ensures ds_end will point to a valid char */
1142 lexer->prog = ds_end (&lexer->line_buffer);
1148 /* Private functions. */
1150 /* When invoked, tokstr contains a string of binary, octal, or
1151 hex digits, according to TYPE. The string is converted to
1152 characters having the specified values. */
1154 convert_numeric_string_to_char_string (struct lexer *lexer,
1155 enum string_type type)
1157 const char *base_name;
1167 base_name = _("binary");
1172 base_name = _("octal");
1177 base_name = _("hex");
1185 byte_cnt = ds_length (&lexer->tokstr) / chars_per_byte;
1186 if (ds_length (&lexer->tokstr) % chars_per_byte)
1187 msg (SE, _("String of %s digits has %zu characters, which is not a "
1189 base_name, ds_length (&lexer->tokstr), chars_per_byte);
1191 p = ds_cstr (&lexer->tokstr);
1192 for (i = 0; i < byte_cnt; i++)
1198 for (j = 0; j < chars_per_byte; j++, p++)
1202 if (*p >= '0' && *p <= '9')
1206 static const char alpha[] = "abcdef";
1207 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1216 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1218 value = value * base + v;
1221 ds_cstr (&lexer->tokstr)[i] = (unsigned char) value;
1224 ds_truncate (&lexer->tokstr, byte_cnt);
1227 /* Parses a string from the input buffer into tokstr. The input
1228 buffer pointer lexer->prog must point to the initial single or double
1229 quote. TYPE indicates the type of string to be parsed.
1230 Returns token type. */
1232 parse_string (struct lexer *lexer, enum string_type type)
1234 if (type != CHARACTER_STRING)
1237 /* Accumulate the entire string, joining sections indicated by +
1241 /* Single or double quote. */
1242 int c = *lexer->prog++;
1244 /* Accumulate section. */
1247 /* Check end of line. */
1248 if (*lexer->prog == '\0')
1250 msg (SE, _("Unterminated string constant."));
1254 /* Double quote characters to embed them in strings. */
1255 if (*lexer->prog == c)
1257 if (lexer->prog[1] == c)
1263 ds_put_byte (&lexer->tokstr, *lexer->prog++);
1267 /* Skip whitespace after final quote mark. */
1268 if (lexer->prog == NULL)
1272 while (c_isspace ((unsigned char) *lexer->prog))
1280 if (!lex_get_line (lexer))
1284 /* Skip plus sign. */
1285 if (*lexer->prog != '+')
1289 /* Skip whitespace after plus sign. */
1290 if (lexer->prog == NULL)
1294 while (c_isspace ((unsigned char) *lexer->prog))
1302 if (!lex_get_line (lexer))
1304 msg (SE, _("Unexpected end of file in string concatenation."));
1309 /* Ensure that a valid string follows. */
1310 if (*lexer->prog != '\'' && *lexer->prog != '"')
1312 msg (SE, _("String expected following `+'."));
1317 /* We come here when we've finished concatenating all the string sections
1318 into one large string. */
1320 if (type != CHARACTER_STRING)
1321 convert_numeric_string_to_char_string (lexer, type);
1326 /* Token Accessor Functions */
1329 lex_token (const struct lexer *lexer)
1331 return lexer->token;
1335 lex_tokval (const struct lexer *lexer)
1337 return lexer->tokval;
1340 /* Returns the null-terminated string value associated with LEXER's current
1341 token. For a T_ID token, this is the identifier, and for a T_STRING token,
1342 this is the string. For other tokens the value is undefined. */
1344 lex_tokcstr (const struct lexer *lexer)
1346 return ds_cstr (&lexer->tokstr);
1349 /* Returns the string value associated with LEXER's current token. For a T_ID
1350 token, this is the identifier, and for a T_STRING token, this is the string.
1351 For other tokens the value is undefined. */
1353 lex_tokss (const struct lexer *lexer)
1355 return ds_ss (&lexer->tokstr);
1358 /* If the lexer is positioned at the (pseudo)identifier S, which
1359 may contain a hyphen ('-'), skips it and returns true. Each
1360 half of the identifier may be abbreviated to its first three
1362 Otherwise, returns false. */
1364 lex_match_hyphenated_word (struct lexer *lexer, const char *s)
1366 const char *hyphen = strchr (s, '-');
1368 return lex_match_id (lexer, s);
1369 else if (lexer->token != T_ID
1370 || !lex_id_match (ss_buffer (s, hyphen - s), lex_tokss (lexer))
1371 || lex_look_ahead (lexer) != T_DASH)
1376 lex_force_match (lexer, T_DASH);
1377 lex_force_match_id (lexer, hyphen + 1);