1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
38 #define _(msgid) gettext (msgid)
39 #define N_(msgid) msgid
46 /* Global variables. */
48 extern const char *keywords[T_N_KEYWORDS + 1];
54 /* T_POS_NUM, T_NEG_NUM: the token's value. */
57 /* T_ID: the identifier. */
58 char tokid[LONG_NAME_LEN + 1];
60 /* T_ID, T_STRING: token string value.
61 For T_ID, this is not truncated as is tokid. */
64 /* Static variables. */
66 /* Pointer to next token in getl_buf. */
69 /* Nonzero only if this line ends with a terminal dot. */
72 /* Nonzero only if the last token returned was T_STOP. */
75 /* If nonzero, next token returned by lex_get().
76 Used only in exceptional circumstances. */
78 static struct string put_tokstr;
79 static double put_tokval;
81 static void unexpected_eof (void);
82 static void convert_numeric_string_to_char_string (int type);
83 static int parse_string (int type);
86 static void dump_token (void);
91 /* Initializes the lexer. */
95 ds_init (&tokstr, 64);
96 ds_init (&put_tokstr, 64);
104 ds_destroy (&put_tokstr);
105 ds_destroy (&tokstr);
109 /* Common functions. */
111 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
112 tokval, respectively, and sets tokid appropriately. */
116 assert (put_token != 0);
118 ds_replace (&tokstr, ds_c_str (&put_tokstr));
119 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
124 /* Copies token, tokstr, tokval into put_token, put_tokstr,
125 put_tokval respectively. */
130 ds_replace (&put_tokstr, ds_c_str (&tokstr));
134 /* Parses a single token, setting appropriate global variables to
135 indicate the token's attributes. */
139 /* If a token was pushed ahead, return it. */
154 /* Skip whitespace. */
160 while (isspace ((unsigned char) *prog))
174 else if (!lex_get_line ())
195 /* Actually parse the token. */
202 case '0': case '1': case '2': case '3': case '4':
203 case '5': case '6': case '7': case '8': case '9':
207 /* `-' can introduce a negative number, or it can be a
208 token by itself. If it is not followed by a digit or a
209 decimal point, it is definitely not a number.
210 Otherwise, it might be either, but most of the time we
211 want it as a number. When the syntax calls for a `-'
212 token, lex_negative_to_dash() must be used to break
213 negative numbers into two tokens. */
216 ds_putc (&tokstr, *prog++);
217 while (isspace ((unsigned char) *prog))
220 if (!isdigit ((unsigned char) *prog) && *prog != '.')
230 /* Parse the number, copying it into tokstr. */
231 while (isdigit ((unsigned char) *prog))
232 ds_putc (&tokstr, *prog++);
235 ds_putc (&tokstr, *prog++);
236 while (isdigit ((unsigned char) *prog))
237 ds_putc (&tokstr, *prog++);
239 if (*prog == 'e' || *prog == 'E')
241 ds_putc (&tokstr, *prog++);
242 if (*prog == '+' || *prog == '-')
243 ds_putc (&tokstr, *prog++);
244 while (isdigit ((unsigned char) *prog))
245 ds_putc (&tokstr, *prog++);
248 /* Parse as floating point. */
249 tokval = strtod (ds_c_str (&tokstr), &tail);
252 msg (SE, _("%s does not form a valid number."),
257 ds_putc (&tokstr, '0');
264 token = parse_string (0);
267 case '(': case ')': case ',': case '=': case '+': case '/':
287 else if (*prog == '>')
326 case 'a': case 'b': case 'c': case 'd': case 'e':
327 case 'f': case 'g': case 'h': case 'i': case 'j':
328 case 'k': case 'l': case 'm': case 'n': case 'o':
329 case 'p': case 'q': case 'r': case 's': case 't':
330 case 'u': case 'v': case 'w': case 'x': case 'y':
332 case 'A': case 'B': case 'C': case 'D': case 'E':
333 case 'F': case 'G': case 'H': case 'I': case 'J':
334 case 'K': case 'L': case 'M': case 'N': case 'O':
335 case 'P': case 'Q': case 'R': case 'S': case 'T':
336 case 'U': case 'V': case 'W': case 'X': case 'Y':
338 case '#': case '$': case '@':
339 /* Strings can be specified in binary, octal, or hex using
340 this special syntax. */
341 if (prog[1] == '\'' || prog[1] == '"')
343 static const char special[3] = "box";
346 p = strchr (special, tolower ((unsigned char) *prog));
350 token = parse_string (p - special + 1);
355 /* Copy id to tokstr. */
356 ds_putc (&tokstr, *prog++);
357 while (CHAR_IS_IDN (*prog))
358 ds_putc (&tokstr, *prog++);
360 /* Copy tokstr to tokid, possibly truncating it.*/
361 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
363 /* Determine token type. */
364 token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
368 if (isgraph ((unsigned char) *prog))
369 msg (SE, _("Bad character in input: `%c'."), *prog++);
371 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
383 /* Reports an error to the effect that subcommand SBC may only be
386 lex_sbc_only_once (const char *sbc)
388 msg (SE, _("Subcommand %s may only be specified once."), sbc);
391 /* Reports an error to the effect that subcommand SBC is
394 lex_sbc_missing (const char *sbc)
396 lex_error (_("missing required subcommand %s"), sbc);
399 /* Prints a syntax error message containing the current token and
400 given message MESSAGE (if non-null). */
402 lex_error (const char *message, ...)
407 token_rep = lex_token_representation ();
409 strcpy (where, "end of file");
410 else if (token == '.')
411 strcpy (where, "end of command");
413 snprintf (where, sizeof where, "`%s'", token_rep);
421 va_start (args, message);
422 vsnprintf (buf, 1024, message, args);
425 msg (SE, _("Syntax error %s at %s."), buf, where);
428 msg (SE, _("Syntax error at %s."), where);
431 /* Checks that we're at end of command.
432 If so, returns a successful command completion code.
433 If not, flags a syntax error and returns an error command
436 lex_end_of_command (void)
440 lex_error (_("expecting end of command"));
441 return CMD_TRAILING_GARBAGE;
447 /* Token testing functions. */
449 /* Returns true if the current token is a number. */
453 return token == T_POS_NUM || token == T_NEG_NUM;
456 /* Returns the value of the current token, which must be a
457 floating point number. */
461 assert (lex_is_number ());
465 /* Returns true iff the current token is an integer. */
467 lex_is_integer (void)
469 return (lex_is_number ()
470 && tokval != NOT_LONG
471 && tokval >= LONG_MIN
472 && tokval <= LONG_MAX
473 && floor (tokval) == tokval);
476 /* Returns the value of the current token, which must be an
481 assert (lex_is_integer ());
485 /* Token matching functions. */
487 /* If TOK is the current token, skips it and returns nonzero.
488 Otherwise, returns zero. */
501 /* If the current token is the identifier S, skips it and returns
502 nonzero. The identifier may be abbreviated to its first three
504 Otherwise, returns zero. */
506 lex_match_id (const char *s)
508 if (token == T_ID && lex_id_match (s, tokid))
517 /* If the current token is integer N, skips it and returns nonzero.
518 Otherwise, returns zero. */
520 lex_match_int (int x)
522 if (lex_is_integer () && lex_integer () == x)
531 /* Forced matches. */
533 /* If this token is identifier S, fetches the next token and returns
535 Otherwise, reports an error and returns zero. */
537 lex_force_match_id (const char *s)
539 if (token == T_ID && lex_id_match (s, tokid))
546 lex_error (_("expecting `%s'"), s);
551 /* If the current token is T, skips the token. Otherwise, reports an
552 error and returns from the current function with return value 0. */
554 lex_force_match (int t)
563 lex_error (_("expecting `%s'"), lex_token_name (t));
568 /* If this token is a string, does nothing and returns nonzero.
569 Otherwise, reports an error and returns zero. */
571 lex_force_string (void)
573 if (token == T_STRING)
577 lex_error (_("expecting string"));
582 /* If this token is an integer, does nothing and returns nonzero.
583 Otherwise, reports an error and returns zero. */
587 if (lex_is_integer ())
591 lex_error (_("expecting integer"));
596 /* If this token is a number, does nothing and returns nonzero.
597 Otherwise, reports an error and returns zero. */
601 if (lex_is_number ())
605 lex_error (_("expecting number"));
610 /* If this token is an identifier, does nothing and returns nonzero.
611 Otherwise, reports an error and returns zero. */
619 lex_error (_("expecting identifier"));
623 /* Weird token functions. */
625 /* Returns the first character of the next token, except that if the
626 next token is not an identifier, the character returned will not be
627 a character that can begin an identifier. Specifically, the
628 hexstring lead-in X' causes lookahead() to return '. Note that an
629 alphanumeric return value doesn't guarantee an ID token, it could
630 also be a reserved-word token. */
632 lex_look_ahead (void)
644 while (isspace ((unsigned char) *prog))
651 else if (!lex_get_line ())
658 if ((toupper ((unsigned char) *prog) == 'X'
659 || toupper ((unsigned char) *prog) == 'B')
660 && (prog[1] == '\'' || prog[1] == '"'))
667 /* Makes the current token become the next token to be read; the
668 current token is set to T. */
676 /* Makes the current token become the next token to be read; the
677 current token is set to the identifier ID. */
679 lex_put_back_id (const char *id)
681 assert (lex_id_to_token (id, strlen (id)) == T_ID);
684 ds_replace (&tokstr, id);
685 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
688 /* Weird line processing functions. */
690 /* Returns the entire contents of the current line. */
692 lex_entire_line (void)
694 return ds_c_str (&getl_buf);
697 /* As lex_entire_line(), but only returns the part of the current line
698 that hasn't already been tokenized.
699 If END_DOT is non-null, stores nonzero into *END_DOT if the line
700 ends with a terminal dot, or zero if it doesn't. */
702 lex_rest_of_line (int *end_dot)
709 /* Causes the rest of the current input line to be ignored for
710 tokenization purposes. */
712 lex_discard_line (void)
714 prog = ds_end (&getl_buf);
718 /* Sets the current position in the current line to P, which must be
721 lex_set_prog (char *p)
726 /* Weird line reading functions. */
728 /* Read a line for use by the tokenizer. */
732 if (!getl_read_line ())
735 lex_preprocess_line ();
739 /* Preprocesses getl_buf by removing comments, stripping trailing
740 whitespace and the terminal dot, and removing leading indentors. */
742 lex_preprocess_line (void)
744 /* Strips comments. */
746 /* getl_buf iterator. */
749 /* Nonzero inside a comment. */
752 /* Nonzero inside a quoted string. */
755 /* Remove C-style comments begun by slash-star and terminated by
756 star-slash or newline. */
758 for (cp = ds_c_str (&getl_buf); *cp; )
760 /* If we're not commented out, toggle quoting. */
765 else if (*cp == '\'' || *cp == '"')
769 /* If we're not quoting, toggle commenting. */
772 if (cp[0] == '/' && cp[1] == '*')
779 else if (cp[0] == '*' && cp[1] == '/' && comment)
788 /* Check commenting. */
796 /* Strip trailing whitespace and terminal dot. */
798 size_t len = ds_length (&getl_buf);
799 char *s = ds_c_str (&getl_buf);
801 /* Strip trailing whitespace. */
802 while (len > 0 && isspace ((unsigned char) s[len - 1]))
805 /* Check for and remove terminal dot. */
806 if (len > 0 && s[len - 1] == get_endcmd ())
811 else if (len == 0 && get_nulline ())
817 ds_truncate (&getl_buf, len);
820 /* In batch mode, strip leading indentors and insert a terminal dot
822 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
824 char *s = ds_c_str (&getl_buf);
826 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
828 else if (s[0] && !isspace ((unsigned char) s[0]))
832 prog = ds_c_str (&getl_buf);
837 /* Returns the name of a token in a static buffer. */
839 lex_token_name (int token)
841 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
842 return keywords[token - T_FIRST_KEYWORD];
854 /* Returns an ASCII representation of the current token as a
855 malloc()'d string. */
857 lex_token_representation (void)
866 return xstrdup (ds_c_str (&tokstr));
874 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
875 if (!isprint ((unsigned char) *sp))
881 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
889 for (sp = ds_c_str (&tokstr); *sp; )
893 *dp++ = (unsigned char) *sp++;
896 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
898 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
899 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
909 token_rep = xmalloc (1);
914 return xstrdup ("**");
917 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
918 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
921 token_rep = xmalloc (2);
922 token_rep[0] = token;
931 /* Really weird functions. */
933 /* Most of the time, a `-' is a lead-in to a negative number. But
934 sometimes it's actually part of the syntax. If a dash can be part
935 of syntax then this function is called to rip it off of a
938 lex_negative_to_dash (void)
940 if (token == T_NEG_NUM)
944 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
950 /* We're not at eof any more. */
957 /* Skip a COMMENT command. */
959 lex_skip_comment (void)
963 if (!lex_get_line ())
970 if (put_token == '.')
973 prog = ds_end (&getl_buf);
979 /* Private functions. */
981 /* Unexpected end of file. */
983 unexpected_eof (void)
985 msg (FE, _("Unexpected end of file."));
988 /* When invoked, tokstr contains a string of binary, octal, or hex
989 digits, for values of TYPE of 0, 1, or 2, respectively. The string
990 is converted to characters having the specified values. */
992 convert_numeric_string_to_char_string (int type)
994 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
995 static const int bases[] = {2, 8, 16};
996 static const int chars_per_byte[] = {8, 3, 2};
998 const char *const base_name = base_names[type];
999 const int base = bases[type];
1000 const int cpb = chars_per_byte[type];
1001 const int nb = ds_length (&tokstr) / cpb;
1005 assert (type >= 0 && type <= 2);
1007 if (ds_length (&tokstr) % cpb)
1008 msg (SE, _("String of %s digits has %d characters, which is not a "
1010 gettext (base_name), ds_length (&tokstr), cpb);
1012 p = ds_c_str (&tokstr);
1013 for (i = 0; i < nb; i++)
1019 for (j = 0; j < cpb; j++, p++)
1023 if (*p >= '0' && *p <= '9')
1027 static const char alpha[] = "abcdef";
1028 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1037 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1039 value = value * base + v;
1042 ds_c_str (&tokstr)[i] = (unsigned char) value;
1045 ds_truncate (&tokstr, nb);
1048 /* Parses a string from the input buffer into tokstr. The input
1049 buffer pointer prog must point to the initial single or double
1050 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1051 binary, octal, or hexstring, respectively. Returns token type. */
1053 parse_string (int type)
1055 /* Accumulate the entire string, joining sections indicated by +
1059 /* Single or double quote. */
1062 /* Accumulate section. */
1065 /* Check end of line. */
1068 msg (SE, _("Unterminated string constant."));
1072 /* Double quote characters to embed them in strings. */
1081 ds_putc (&tokstr, *prog++);
1085 /* Skip whitespace after final quote mark. */
1090 while (isspace ((unsigned char) *prog))
1098 if (!lex_get_line ())
1102 /* Skip plus sign. */
1107 /* Skip whitespace after plus sign. */
1112 while (isspace ((unsigned char) *prog))
1120 if (!lex_get_line ())
1124 /* Ensure that a valid string follows. */
1125 if (*prog != '\'' && *prog != '"')
1127 msg (SE, "String expected following `+'.");
1132 /* We come here when we've finished concatenating all the string sections
1133 into one large string. */
1136 convert_numeric_string_to_char_string (type - 1);
1138 if (ds_length (&tokstr) > 255)
1140 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1141 ds_length (&tokstr));
1142 ds_truncate (&tokstr, 255);
1150 for (i = 0; i < ds_length (&tokstr); i++)
1151 if (ds_c_str (&tokstr)[i] == 0)
1155 msg (SE, _("Sorry, literal strings may not contain null "
1156 "characters. Replacing with spaces."));
1159 ds_c_str (&tokstr)[i] = ' ';
1167 /* Reads one token from the lexer and writes a textual representation
1168 on stdout for debugging purposes. */
1176 getl_location (&curfn, &curln);
1178 fprintf (stderr, "%s:%d\t", curfn, curln);
1184 fprintf (stderr, "ID\t%s\n", tokid);
1189 fprintf (stderr, "NUM\t%f\n", tokval);
1193 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1197 fprintf (stderr, "STOP\n");
1201 fprintf (stderr, "MISC\tEXP\"");
1205 fprintf (stderr, "MISC\tEOF\n");
1209 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1210 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1212 fprintf (stderr, "PUNCT\t%c\n", token);
1216 #endif /* DUMP_TOKENS */