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. */
51 /* T_POS_NUM, T_NEG_NUM: the token's value. */
54 /* T_ID: the identifier. */
55 char tokid[LONG_NAME_LEN + 1];
57 /* T_ID, T_STRING: token string value.
58 For T_ID, this is not truncated as is tokid. */
61 /* Static variables. */
63 /* Table of keywords. */
64 static const char *keywords[T_N_KEYWORDS + 1] =
67 "EQ", "GE", "GT", "LE", "LT", "NE",
68 "ALL", "BY", "TO", "WITH",
72 /* Pointer to next token in getl_buf. */
75 /* Nonzero only if this line ends with a terminal dot. */
78 /* Nonzero only if the last token returned was T_STOP. */
81 /* If nonzero, next token returned by lex_get().
82 Used only in exceptional circumstances. */
84 static struct string put_tokstr;
85 static double put_tokval;
87 static void unexpected_eof (void);
88 static void convert_numeric_string_to_char_string (int type);
89 static int parse_string (int type);
92 static void dump_token (void);
97 /* Initializes the lexer. */
101 ds_init (&put_tokstr, 64);
102 if (!lex_get_line ())
109 ds_destroy(&put_tokstr);
113 /* Common functions. */
115 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
116 tokval, respectively, and sets tokid appropriately. */
120 assert (put_token != 0);
122 ds_replace (&tokstr, ds_c_str (&put_tokstr));
123 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
128 /* Copies token, tokstr, tokval into put_token, put_tokstr,
129 put_tokval respectively. */
134 ds_replace (&put_tokstr, ds_c_str (&tokstr));
138 /* Parses a single token, setting appropriate global variables to
139 indicate the token's attributes. */
143 /* If a token was pushed ahead, return it. */
158 /* Skip whitespace. */
164 while (isspace ((unsigned char) *prog))
178 else if (!lex_get_line ())
199 /* Actually parse the token. */
206 case '0': case '1': case '2': case '3': case '4':
207 case '5': case '6': case '7': case '8': case '9':
211 /* `-' can introduce a negative number, or it can be a
212 token by itself. If it is not followed by a digit or a
213 decimal point, it is definitely not a number.
214 Otherwise, it might be either, but most of the time we
215 want it as a number. When the syntax calls for a `-'
216 token, lex_negative_to_dash() must be used to break
217 negative numbers into two tokens. */
220 ds_putc (&tokstr, *prog++);
221 while (isspace ((unsigned char) *prog))
224 if (!isdigit ((unsigned char) *prog) && *prog != '.')
234 /* Parse the number, copying it into tokstr. */
235 while (isdigit ((unsigned char) *prog))
236 ds_putc (&tokstr, *prog++);
239 ds_putc (&tokstr, *prog++);
240 while (isdigit ((unsigned char) *prog))
241 ds_putc (&tokstr, *prog++);
243 if (*prog == 'e' || *prog == 'E')
245 ds_putc (&tokstr, *prog++);
246 if (*prog == '+' || *prog == '-')
247 ds_putc (&tokstr, *prog++);
248 while (isdigit ((unsigned char) *prog))
249 ds_putc (&tokstr, *prog++);
252 /* Parse as floating point. */
253 tokval = strtod (ds_c_str (&tokstr), &tail);
256 msg (SE, _("%s does not form a valid number."),
261 ds_putc (&tokstr, '0');
268 token = parse_string (0);
271 case '(': case ')': case ',': case '=': case '+': case '/':
291 else if (*prog == '>')
330 case 'a': case 'b': case 'c': case 'd': case 'e':
331 case 'f': case 'g': case 'h': case 'i': case 'j':
332 case 'k': case 'l': case 'm': case 'n': case 'o':
333 case 'p': case 'q': case 'r': case 's': case 't':
334 case 'u': case 'v': case 'w': case 'x': case 'y':
336 case 'A': case 'B': case 'C': case 'D': case 'E':
337 case 'F': case 'G': case 'H': case 'I': case 'J':
338 case 'K': case 'L': case 'M': case 'N': case 'O':
339 case 'P': case 'Q': case 'R': case 'S': case 'T':
340 case 'U': case 'V': case 'W': case 'X': case 'Y':
342 case '#': case '$': case '@':
343 /* Strings can be specified in binary, octal, or hex using
344 this special syntax. */
345 if (prog[1] == '\'' || prog[1] == '"')
347 static const char special[3] = "box";
350 p = strchr (special, tolower ((unsigned char) *prog));
354 token = parse_string (p - special + 1);
359 /* Copy id to tokstr. */
360 ds_putc (&tokstr, *prog++);
361 while (CHAR_IS_IDN (*prog))
362 ds_putc (&tokstr, *prog++);
364 /* Copy tokstr to tokid, possibly truncating it.*/
365 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
367 /* Determine token type. */
368 token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
372 if (isgraph ((unsigned char) *prog))
373 msg (SE, _("Bad character in input: `%c'."), *prog++);
375 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
387 /* Reports an error to the effect that subcommand SBC may only be
390 lex_sbc_only_once (const char *sbc)
392 msg (SE, _("Subcommand %s may only be specified once."), sbc);
395 /* Reports an error to the effect that subcommand SBC is
398 lex_sbc_missing (const char *sbc)
400 lex_error (_("missing required subcommand %s"), sbc);
403 /* Prints a syntax error message containing the current token and
404 given message MESSAGE (if non-null). */
406 lex_error (const char *message, ...)
411 token_rep = lex_token_representation ();
413 strcpy (where, "end of file");
414 else if (token == '.')
415 strcpy (where, "end of command");
417 snprintf (where, sizeof where, "`%s'", token_rep);
425 va_start (args, message);
426 vsnprintf (buf, 1024, message, args);
429 msg (SE, _("Syntax error %s at %s."), buf, where);
432 msg (SE, _("Syntax error at %s."), where);
435 /* Checks that we're at end of command.
436 If so, returns a successful command completion code.
437 If not, flags a syntax error and returns an error command
440 lex_end_of_command (void)
444 lex_error (_("expecting end of command"));
445 return CMD_TRAILING_GARBAGE;
451 /* Token testing functions. */
453 /* Returns true if the current token is a number. */
457 return token == T_POS_NUM || token == T_NEG_NUM;
460 /* Returns the value of the current token, which must be a
461 floating point number. */
465 assert (lex_is_number ());
469 /* Returns true iff the current token is an integer. */
471 lex_is_integer (void)
473 return (lex_is_number ()
474 && tokval != NOT_LONG
475 && tokval >= LONG_MIN
476 && tokval <= LONG_MAX
477 && floor (tokval) == tokval);
480 /* Returns the value of the current token, which must be an
485 assert (lex_is_integer ());
489 /* Token matching functions. */
491 /* If TOK is the current token, skips it and returns nonzero.
492 Otherwise, returns zero. */
505 /* If the current token is the identifier S, skips it and returns
506 nonzero. The identifier may be abbreviated to its first three
508 Otherwise, returns zero. */
510 lex_match_id (const char *s)
512 if (token == T_ID && lex_id_match (s, tokid))
521 /* If the current token is integer N, skips it and returns nonzero.
522 Otherwise, returns zero. */
524 lex_match_int (int x)
526 if (lex_is_integer () && lex_integer () == x)
535 /* Forced matches. */
537 /* If this token is identifier S, fetches the next token and returns
539 Otherwise, reports an error and returns zero. */
541 lex_force_match_id (const char *s)
543 if (token == T_ID && lex_id_match (s, tokid))
550 lex_error (_("expecting `%s'"), s);
555 /* If the current token is T, skips the token. Otherwise, reports an
556 error and returns from the current function with return value 0. */
558 lex_force_match (int t)
567 lex_error (_("expecting `%s'"), lex_token_name (t));
572 /* If this token is a string, does nothing and returns nonzero.
573 Otherwise, reports an error and returns zero. */
575 lex_force_string (void)
577 if (token == T_STRING)
581 lex_error (_("expecting string"));
586 /* If this token is an integer, does nothing and returns nonzero.
587 Otherwise, reports an error and returns zero. */
591 if (lex_is_integer ())
595 lex_error (_("expecting integer"));
600 /* If this token is a number, does nothing and returns nonzero.
601 Otherwise, reports an error and returns zero. */
605 if (lex_is_number ())
609 lex_error (_("expecting number"));
614 /* If this token is an identifier, does nothing and returns nonzero.
615 Otherwise, reports an error and returns zero. */
623 lex_error (_("expecting identifier"));
628 /* Comparing identifiers. */
630 /* Keywords match if one of the following is true: KW and TOK are
631 identical (except for differences in case), or TOK is at least 3
632 characters long and those characters are identical to KW. KW_LEN
633 is the length of KW, TOK_LEN is the length of TOK. */
635 lex_id_match_len (const char *kw, size_t kw_len,
636 const char *tok, size_t tok_len)
643 if (i == kw_len && i == tok_len)
645 else if (i == tok_len)
647 else if (i == kw_len)
649 else if (toupper ((unsigned char) kw[i])
650 != toupper ((unsigned char) tok[i]))
657 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
659 lex_id_match (const char *kw, const char *tok)
661 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
664 /* Returns the proper token type, either T_ID or a reserved keyword
665 enum, for ID[], which must contain LEN characters. */
667 lex_id_to_token (const char *id, size_t len)
671 if (len < 2 || len > 4)
674 for (kwp = keywords; *kwp; kwp++)
675 if (!strcasecmp (*kwp, id))
676 return T_FIRST_KEYWORD + (kwp - keywords);
681 /* Weird token functions. */
683 /* Returns the first character of the next token, except that if the
684 next token is not an identifier, the character returned will not be
685 a character that can begin an identifier. Specifically, the
686 hexstring lead-in X' causes lookahead() to return '. Note that an
687 alphanumeric return value doesn't guarantee an ID token, it could
688 also be a reserved-word token. */
690 lex_look_ahead (void)
702 while (isspace ((unsigned char) *prog))
709 else if (!lex_get_line ())
716 if ((toupper ((unsigned char) *prog) == 'X'
717 || toupper ((unsigned char) *prog) == 'B')
718 && (prog[1] == '\'' || prog[1] == '"'))
725 /* Makes the current token become the next token to be read; the
726 current token is set to T. */
734 /* Makes the current token become the next token to be read; the
735 current token is set to the identifier ID. */
737 lex_put_back_id (const char *id)
739 assert (lex_id_to_token (id, strlen (id)) == T_ID);
742 ds_replace (&tokstr, id);
743 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
746 /* Weird line processing functions. */
748 /* Returns the entire contents of the current line. */
750 lex_entire_line (void)
752 return ds_c_str (&getl_buf);
755 /* As lex_entire_line(), but only returns the part of the current line
756 that hasn't already been tokenized.
757 If END_DOT is non-null, stores nonzero into *END_DOT if the line
758 ends with a terminal dot, or zero if it doesn't. */
760 lex_rest_of_line (int *end_dot)
767 /* Causes the rest of the current input line to be ignored for
768 tokenization purposes. */
770 lex_discard_line (void)
772 prog = ds_end (&getl_buf);
776 /* Sets the current position in the current line to P, which must be
779 lex_set_prog (char *p)
784 /* Weird line reading functions. */
786 /* Read a line for use by the tokenizer. */
790 if (!getl_read_line ())
793 lex_preprocess_line ();
797 /* Preprocesses getl_buf by removing comments, stripping trailing
798 whitespace and the terminal dot, and removing leading indentors. */
800 lex_preprocess_line (void)
802 /* Strips comments. */
804 /* getl_buf iterator. */
807 /* Nonzero inside a comment. */
810 /* Nonzero inside a quoted string. */
813 /* Remove C-style comments begun by slash-star and terminated by
814 star-slash or newline. */
816 for (cp = ds_c_str (&getl_buf); *cp; )
818 /* If we're not commented out, toggle quoting. */
823 else if (*cp == '\'' || *cp == '"')
827 /* If we're not quoting, toggle commenting. */
830 if (cp[0] == '/' && cp[1] == '*')
837 else if (cp[0] == '*' && cp[1] == '/' && comment)
846 /* Check commenting. */
854 /* Strip trailing whitespace and terminal dot. */
856 size_t len = ds_length (&getl_buf);
857 char *s = ds_c_str (&getl_buf);
859 /* Strip trailing whitespace. */
860 while (len > 0 && isspace ((unsigned char) s[len - 1]))
863 /* Check for and remove terminal dot. */
864 if (len > 0 && s[len - 1] == get_endcmd() )
869 else if (len == 0 && get_nullline() )
875 ds_truncate (&getl_buf, len);
878 /* In batch mode, strip leading indentors and insert a terminal dot
880 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
882 char *s = ds_c_str (&getl_buf);
884 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
886 else if (s[0] && !isspace ((unsigned char) s[0]))
890 prog = ds_c_str (&getl_buf);
895 /* Returns the name of a token in a static buffer. */
897 lex_token_name (int token)
899 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
900 return keywords[token - T_FIRST_KEYWORD];
912 /* Returns an ASCII representation of the current token as a
913 malloc()'d string. */
915 lex_token_representation (void)
924 return xstrdup (ds_c_str (&tokstr));
932 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
933 if (!isprint ((unsigned char) *sp))
939 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
947 for (sp = ds_c_str (&tokstr); *sp; )
951 *dp++ = (unsigned char) *sp++;
954 for (sp = ds_c_str (&tokstr); sp < ds_end (&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 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
976 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
979 token_rep = xmalloc (2);
980 token_rep[0] = token;
989 /* Really weird functions. */
991 /* Most of the time, a `-' is a lead-in to a negative number. But
992 sometimes it's actually part of the syntax. If a dash can be part
993 of syntax then this function is called to rip it off of a
996 lex_negative_to_dash (void)
998 if (token == T_NEG_NUM)
1002 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
1008 /* We're not at eof any more. */
1010 lex_reset_eof (void)
1015 /* Skip a COMMENT command. */
1017 lex_skip_comment (void)
1021 if (!lex_get_line ())
1028 if (put_token == '.')
1031 prog = ds_end (&getl_buf);
1037 /* Private functions. */
1039 /* Unexpected end of file. */
1041 unexpected_eof (void)
1043 msg (FE, _("Unexpected end of file."));
1046 /* When invoked, tokstr contains a string of binary, octal, or hex
1047 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1048 is converted to characters having the specified values. */
1050 convert_numeric_string_to_char_string (int type)
1052 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1053 static const int bases[] = {2, 8, 16};
1054 static const int chars_per_byte[] = {8, 3, 2};
1056 const char *const base_name = base_names[type];
1057 const int base = bases[type];
1058 const int cpb = chars_per_byte[type];
1059 const int nb = ds_length (&tokstr) / cpb;
1063 assert (type >= 0 && type <= 2);
1065 if (ds_length (&tokstr) % cpb)
1066 msg (SE, _("String of %s digits has %d characters, which is not a "
1068 gettext (base_name), ds_length (&tokstr), cpb);
1070 p = ds_c_str (&tokstr);
1071 for (i = 0; i < nb; i++)
1077 for (j = 0; j < cpb; j++, p++)
1081 if (*p >= '0' && *p <= '9')
1085 static const char alpha[] = "abcdef";
1086 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1095 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1097 value = value * base + v;
1100 ds_c_str (&tokstr)[i] = (unsigned char) value;
1103 ds_truncate (&tokstr, nb);
1106 /* Parses a string from the input buffer into tokstr. The input
1107 buffer pointer prog must point to the initial single or double
1108 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1109 binary, octal, or hexstring, respectively. Returns token type. */
1111 parse_string (int type)
1113 /* Accumulate the entire string, joining sections indicated by +
1117 /* Single or double quote. */
1120 /* Accumulate section. */
1123 /* Check end of line. */
1126 msg (SE, _("Unterminated string constant."));
1130 /* Double quote characters to embed them in strings. */
1139 ds_putc (&tokstr, *prog++);
1143 /* Skip whitespace after final quote mark. */
1148 while (isspace ((unsigned char) *prog))
1156 if (!lex_get_line ())
1160 /* Skip plus sign. */
1165 /* Skip whitespace after plus sign. */
1170 while (isspace ((unsigned char) *prog))
1178 if (!lex_get_line ())
1182 /* Ensure that a valid string follows. */
1183 if (*prog != '\'' && *prog != '"')
1185 msg (SE, "String expected following `+'.");
1190 /* We come here when we've finished concatenating all the string sections
1191 into one large string. */
1194 convert_numeric_string_to_char_string (type - 1);
1196 if (ds_length (&tokstr) > 255)
1198 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1199 ds_length (&tokstr));
1200 ds_truncate (&tokstr, 255);
1208 for (i = 0; i < ds_length (&tokstr); i++)
1209 if (ds_c_str (&tokstr)[i] == 0)
1213 msg (SE, _("Sorry, literal strings may not contain null "
1214 "characters. Replacing with spaces."));
1217 ds_c_str (&tokstr)[i] = ' ';
1225 /* Reads one token from the lexer and writes a textual representation
1226 on stdout for debugging purposes. */
1234 getl_location (&curfn, &curln);
1236 fprintf (stderr, "%s:%d\t", curfn, curln);
1242 fprintf (stderr, "ID\t%s\n", tokid);
1247 fprintf (stderr, "NUM\t%f\n", tokval);
1251 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1255 fprintf (stderr, "STOP\n");
1259 fprintf (stderr, "MISC\tEXP\"");
1263 fprintf (stderr, "MISC\tEOF\n");
1267 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1268 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1270 fprintf (stderr, "PUNCT\t%c\n", token);
1274 #endif /* DUMP_TOKENS */