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., 59 Temple Place - Suite 330, Boston, MA
42 /* Global variables. */
47 /* T_POS_NUM, T_NEG_NUM: the token's value. */
50 /* T_ID: the identifier. */
53 /* T_ID, T_STRING: token string value.
54 For T_ID, this is not truncated to 8 characters as is tokid. */
57 /* Static variables. */
59 /* Table of keywords. */
60 static const char *keywords[T_N_KEYWORDS + 1] =
63 "EQ", "GE", "GT", "LE", "LT", "NE",
64 "ALL", "BY", "TO", "WITH",
68 /* Pointer to next token in getl_buf. */
71 /* Nonzero only if this line ends with a terminal dot. */
74 /* Nonzero only if the last token returned was T_STOP. */
77 /* If nonzero, next token returned by lex_get().
78 Used only in exceptional circumstances. */
80 static struct string put_tokstr;
81 static double put_tokval;
83 static void unexpected_eof (void);
84 static inline int check_id (const char *id, size_t len);
85 static void convert_numeric_string_to_char_string (int type);
86 static int parse_string (int type);
89 static void dump_token (void);
94 /* Initializes the lexer. */
98 ds_init (&put_tokstr, 64);
106 ds_destroy(&put_tokstr);
110 /* Common functions. */
112 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
113 tokval, respectively, and sets tokid appropriately. */
117 assert (put_token != 0);
119 ds_replace (&tokstr, ds_c_str (&put_tokstr));
120 strncpy (tokid, ds_c_str (&put_tokstr), 8);
126 /* Copies token, tokstr, tokval into put_token, put_tokstr,
127 put_tokval respectively. */
132 ds_replace (&put_tokstr, ds_c_str (&tokstr));
136 /* Parses a single token, setting appropriate global variables to
137 indicate the token's attributes. */
141 /* If a token was pushed ahead, return it. */
156 /* Skip whitespace. */
162 while (isspace ((unsigned char) *prog))
176 else if (!lex_get_line ())
197 /* Actually parse the token. */
204 case '0': case '1': case '2': case '3': case '4':
205 case '5': case '6': case '7': case '8': case '9':
209 /* `-' can introduce a negative number, or it can be a
210 token by itself. If it is not followed by a digit or a
211 decimal point, it is definitely not a number.
212 Otherwise, it might be either, but most of the time we
213 want it as a number. When the syntax calls for a `-'
214 token, lex_negative_to_dash() must be used to break
215 negative numbers into two tokens. */
218 ds_putc (&tokstr, *prog++);
219 while (isspace ((unsigned char) *prog))
222 if (!isdigit ((unsigned char) *prog) && *prog != '.')
232 /* Parse the number, copying it into tokstr. */
233 while (isdigit ((unsigned char) *prog))
234 ds_putc (&tokstr, *prog++);
237 ds_putc (&tokstr, *prog++);
238 while (isdigit ((unsigned char) *prog))
239 ds_putc (&tokstr, *prog++);
241 if (*prog == 'e' || *prog == 'E')
243 ds_putc (&tokstr, *prog++);
244 if (*prog == '+' || *prog == '-')
245 ds_putc (&tokstr, *prog++);
246 while (isdigit ((unsigned char) *prog))
247 ds_putc (&tokstr, *prog++);
250 /* Parse as floating point. */
251 tokval = strtod (ds_c_str (&tokstr), &tail);
254 msg (SE, _("%s does not form a valid number."),
259 ds_putc (&tokstr, '0');
266 token = parse_string (0);
269 case '(': case ')': case ',': case '=': case '+': case '/':
289 else if (*prog == '>')
328 case 'a': case 'b': case 'c': case 'd': case 'e':
329 case 'f': case 'g': case 'h': case 'i': case 'j':
330 case 'k': case 'l': case 'm': case 'n': case 'o':
331 case 'p': case 'q': case 'r': case 's': case 't':
332 case 'u': case 'v': case 'w': case 'x': case 'y':
334 case 'A': case 'B': case 'C': case 'D': case 'E':
335 case 'F': case 'G': case 'H': case 'I': case 'J':
336 case 'K': case 'L': case 'M': case 'N': case 'O':
337 case 'P': case 'Q': case 'R': case 'S': case 'T':
338 case 'U': case 'V': case 'W': case 'X': case 'Y':
340 case '#': case '$': case '@':
341 /* Strings can be specified in binary, octal, or hex using
342 this special syntax. */
343 if (prog[1] == '\'' || prog[1] == '"')
345 static const char special[3] = "box";
348 p = strchr (special, tolower ((unsigned char) *prog));
352 token = parse_string (p - special + 1);
357 /* Copy id to tokstr. */
358 ds_putc (&tokstr, toupper ((unsigned char) *prog++));
359 while (CHAR_IS_IDN (*prog))
360 ds_putc (&tokstr, toupper ((unsigned char) *prog++));
362 /* Copy tokstr to tokid, truncating it to 8 characters. */
363 strncpy (tokid, ds_c_str (&tokstr), 8);
366 token = check_id (ds_c_str (&tokstr), ds_length (&tokstr));
370 if (isgraph ((unsigned char) *prog))
371 msg (SE, _("Bad character in input: `%c'."), *prog++);
373 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
385 /* Prints a syntax error message containing the current token and
386 given message MESSAGE (if non-null). */
388 lex_error (const char *message, ...)
392 token_rep = lex_token_representation ();
393 if (token_rep[0] == 0)
394 msg (SE, _("Syntax error at end of file."));
400 va_start (args, message);
401 vsnprintf (buf, 1024, message, args);
404 msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
407 msg (SE, _("Syntax error at `%s'."), token_rep);
412 /* Checks that we're at end of command.
413 If so, returns a successful command completion code.
414 If not, flags a syntax error and returns an error command
417 lex_end_of_command (void)
421 lex_error (_("expecting end of command"));
422 return CMD_TRAILING_GARBAGE;
428 /* Token testing functions. */
430 /* Returns true if the current token is a number. */
434 return token == T_POS_NUM || token == T_NEG_NUM;
437 /* Returns the value of the current token, which must be a
438 floating point number. */
442 assert (lex_is_number ());
446 /* Returns true iff the current token is an integer. */
448 lex_is_integer (void)
450 return (lex_is_number ()
451 && tokval != NOT_LONG
452 && tokval >= LONG_MIN
453 && tokval <= LONG_MAX
454 && floor (tokval) == tokval);
457 /* Returns the value of the current token, which must be an
462 assert (lex_is_integer ());
466 /* Token matching functions. */
468 /* If TOK is the current token, skips it and returns nonzero.
469 Otherwise, returns zero. */
482 /* If the current token is the identifier S, skips it and returns
484 Otherwise, returns zero. */
486 lex_match_id (const char *s)
488 if (token == T_ID && lex_id_match (s, tokid))
497 /* If the current token is integer N, skips it and returns nonzero.
498 Otherwise, returns zero. */
500 lex_match_int (int x)
502 if (lex_is_integer () && lex_integer () == x)
511 /* Forced matches. */
513 /* If this token is identifier S, fetches the next token and returns
515 Otherwise, reports an error and returns zero. */
517 lex_force_match_id (const char *s)
519 if (token == T_ID && lex_id_match (s, tokid))
526 lex_error (_("expecting `%s'"), s);
531 /* If the current token is T, skips the token. Otherwise, reports an
532 error and returns from the current function with return value 0. */
534 lex_force_match (int t)
543 lex_error (_("expecting %s"), lex_token_name (t));
548 /* If this token is a string, does nothing and returns nonzero.
549 Otherwise, reports an error and returns zero. */
551 lex_force_string (void)
553 if (token == T_STRING)
557 lex_error (_("expecting string"));
562 /* If this token is an integer, does nothing and returns nonzero.
563 Otherwise, reports an error and returns zero. */
567 if (lex_is_integer ())
571 lex_error (_("expecting integer"));
576 /* If this token is a number, does nothing and returns nonzero.
577 Otherwise, reports an error and returns zero. */
581 if (lex_is_number ())
585 lex_error (_("expecting number"));
590 /* If this token is an identifier, does nothing and returns nonzero.
591 Otherwise, reports an error and returns zero. */
599 lex_error (_("expecting identifier"));
604 /* Comparing identifiers. */
606 /* Keywords match if one of the following is true: KW and TOK are
607 identical (barring differences in case), or TOK is at least 3
608 characters long and those characters are identical to KW. KW_LEN
609 is the length of KW, TOK_LEN is the length of TOK. */
611 lex_id_match_len (const char *kw, size_t kw_len,
612 const char *tok, size_t tok_len)
619 if (i == kw_len && i == tok_len)
621 else if (i == tok_len)
623 else if (i == kw_len)
625 else if (toupper ((unsigned char) kw[i])
626 != toupper ((unsigned char) tok[i]))
633 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
635 lex_id_match (const char *kw, const char *tok)
637 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
640 /* Weird token functions. */
642 /* Returns the first character of the next token, except that if the
643 next token is not an identifier, the character returned will not be
644 a character that can begin an identifier. Specifically, the
645 hexstring lead-in X' causes lookahead() to return '. Note that an
646 alphanumeric return value doesn't guarantee an ID token, it could
647 also be a reserved-word token. */
649 lex_look_ahead (void)
661 while (isspace ((unsigned char) *prog))
668 else if (!lex_get_line ())
675 if ((toupper ((unsigned char) *prog) == 'X'
676 || toupper ((unsigned char) *prog) == 'B')
677 && (prog[1] == '\'' || prog[1] == '"'))
684 /* Makes the current token become the next token to be read; the
685 current token is set to T. */
693 /* Makes the current token become the next token to be read; the
694 current token is set to the identifier ID. */
696 lex_put_back_id (const char *id)
700 ds_replace (&tokstr, id);
701 strncpy (tokid, ds_c_str (&tokstr), 8);
705 /* Weird line processing functions. */
707 /* Returns the entire contents of the current line. */
709 lex_entire_line (void)
711 return ds_c_str (&getl_buf);
714 /* As lex_entire_line(), but only returns the part of the current line
715 that hasn't already been tokenized.
716 If END_DOT is non-null, stores nonzero into *END_DOT if the line
717 ends with a terminal dot, or zero if it doesn't. */
719 lex_rest_of_line (int *end_dot)
726 /* Causes the rest of the current input line to be ignored for
727 tokenization purposes. */
729 lex_discard_line (void)
731 prog = ds_end (&getl_buf);
735 /* Sets the current position in the current line to P, which must be
738 lex_set_prog (char *p)
743 /* Weird line reading functions. */
745 /* Read a line for use by the tokenizer. */
749 if (!getl_read_line ())
752 lex_preprocess_line ();
756 /* Preprocesses getl_buf by removing comments, stripping trailing
757 whitespace and the terminal dot, and removing leading indentors. */
759 lex_preprocess_line (void)
761 /* Strips comments. */
763 /* getl_buf iterator. */
766 /* Nonzero inside a comment. */
769 /* Nonzero inside a quoted string. */
772 /* Remove C-style comments begun by slash-star and terminated by
773 star-slash or newline. */
775 for (cp = ds_c_str (&getl_buf); *cp; )
777 /* If we're not commented out, toggle quoting. */
782 else if (*cp == '\'' || *cp == '"')
786 /* If we're not quoting, toggle commenting. */
789 if (cp[0] == '/' && cp[1] == '*')
796 else if (cp[0] == '*' && cp[1] == '/' && comment)
805 /* Check commenting. */
813 /* Strip trailing whitespace and terminal dot. */
815 size_t len = ds_length (&getl_buf);
816 char *s = ds_c_str (&getl_buf);
818 /* Strip trailing whitespace. */
819 while (len > 0 && isspace ((unsigned char) s[len - 1]))
822 /* Check for and remove terminal dot. */
823 if (len > 0 && s[len - 1] == get_endcmd() )
828 else if (len == 0 && get_nullline() )
834 ds_truncate (&getl_buf, len);
837 /* In batch mode, strip leading indentors and insert a terminal dot
839 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
841 char *s = ds_c_str (&getl_buf);
843 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
845 else if (s[0] && !isspace ((unsigned char) s[0]))
849 prog = ds_c_str (&getl_buf);
854 /* Returns the name of a token in a static buffer. */
856 lex_token_name (int token)
858 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
859 return keywords[token - T_FIRST_KEYWORD];
871 /* Returns an ASCII representation of the current token as a
872 malloc()'d string. */
874 lex_token_representation (void)
883 return xstrdup (ds_c_str (&tokstr));
891 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
892 if (!isprint ((unsigned char) *sp))
898 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
906 for (sp = ds_c_str (&tokstr); *sp; )
910 *dp++ = (unsigned char) *sp++;
913 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
915 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
916 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
926 token_rep = xmalloc (1);
931 return xstrdup ("**");
934 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
935 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
938 token_rep = xmalloc (2);
939 token_rep[0] = token;
948 /* Really weird functions. */
950 /* Most of the time, a `-' is a lead-in to a negative number. But
951 sometimes it's actually part of the syntax. If a dash can be part
952 of syntax then this function is called to rip it off of a
955 lex_negative_to_dash (void)
957 if (token == T_NEG_NUM)
961 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
967 /* We're not at eof any more. */
974 /* Skip a COMMENT command. */
976 lex_skip_comment (void)
980 if (!lex_get_line ())
987 if (put_token == '.')
990 prog = ds_end (&getl_buf);
996 /* Private functions. */
998 /* Unexpected end of file. */
1000 unexpected_eof (void)
1002 msg (FE, _("Unexpected end of file."));
1005 /* Returns the proper token type, either T_ID or a reserved keyword
1006 enum, for ID[], which must contain LEN characters. */
1008 check_id (const char *id, size_t len)
1012 if (len < 2 || len > 4)
1015 for (kwp = keywords; *kwp; kwp++)
1016 if (!strcmp (*kwp, id))
1017 return T_FIRST_KEYWORD + (kwp - keywords);
1022 /* When invoked, tokstr contains a string of binary, octal, or hex
1023 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1024 is converted to characters having the specified values. */
1026 convert_numeric_string_to_char_string (int type)
1028 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1029 static const int bases[] = {2, 8, 16};
1030 static const int chars_per_byte[] = {8, 3, 2};
1032 const char *const base_name = base_names[type];
1033 const int base = bases[type];
1034 const int cpb = chars_per_byte[type];
1035 const int nb = ds_length (&tokstr) / cpb;
1039 assert (type >= 0 && type <= 2);
1041 if (ds_length (&tokstr) % cpb)
1042 msg (SE, _("String of %s digits has %d characters, which is not a "
1044 gettext (base_name), ds_length (&tokstr), cpb);
1046 p = ds_c_str (&tokstr);
1047 for (i = 0; i < nb; i++)
1053 for (j = 0; j < cpb; j++, p++)
1057 if (*p >= '0' && *p <= '9')
1061 static const char alpha[] = "abcdef";
1062 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1071 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1073 value = value * base + v;
1076 ds_c_str (&tokstr)[i] = (unsigned char) value;
1079 ds_truncate (&tokstr, nb);
1082 /* Parses a string from the input buffer into tokstr. The input
1083 buffer pointer prog must point to the initial single or double
1084 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1085 binary, octal, or hexstring, respectively. Returns token type. */
1087 parse_string (int type)
1089 /* Accumulate the entire string, joining sections indicated by +
1093 /* Single or double quote. */
1096 /* Accumulate section. */
1099 /* Check end of line. */
1102 msg (SE, _("Unterminated string constant."));
1106 /* Double quote characters to embed them in strings. */
1115 ds_putc (&tokstr, *prog++);
1119 /* Skip whitespace after final quote mark. */
1124 while (isspace ((unsigned char) *prog))
1132 if (!lex_get_line ())
1136 /* Skip plus sign. */
1141 /* Skip whitespace after plus sign. */
1146 while (isspace ((unsigned char) *prog))
1154 if (!lex_get_line ())
1158 /* Ensure that a valid string follows. */
1159 if (*prog != '\'' && *prog != '"')
1161 msg (SE, "String expected following `+'.");
1166 /* We come here when we've finished concatenating all the string sections
1167 into one large string. */
1170 convert_numeric_string_to_char_string (type - 1);
1172 if (ds_length (&tokstr) > 255)
1174 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1175 ds_length (&tokstr));
1176 ds_truncate (&tokstr, 255);
1184 for (i = 0; i < ds_length (&tokstr); i++)
1185 if (ds_c_str (&tokstr)[i] == 0)
1189 msg (SE, _("Sorry, literal strings may not contain null "
1190 "characters. Replacing with spaces."));
1193 ds_c_str (&tokstr)[i] = ' ';
1201 /* Reads one token from the lexer and writes a textual representation
1202 on stdout for debugging purposes. */
1210 getl_location (&curfn, &curln);
1212 fprintf (stderr, "%s:%d\t", curfn, curln);
1218 fprintf (stderr, "ID\t%s\n", tokid);
1223 fprintf (stderr, "NUM\t%f\n", tokval);
1227 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1231 fprintf (stderr, "STOP\n");
1235 fprintf (stderr, "MISC\tEXP\"");
1239 fprintf (stderr, "MISC\tEOF\n");
1243 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1244 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1246 fprintf (stderr, "PUNCT\t%c\n", token);
1250 #endif /* DUMP_TOKENS */