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_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 != '.')
229 /* Parse the number, copying it into tokstr. */
230 while (isdigit ((unsigned char) *prog))
231 ds_putc (&tokstr, *prog++);
234 ds_putc (&tokstr, *prog++);
235 while (isdigit ((unsigned char) *prog))
236 ds_putc (&tokstr, *prog++);
238 if (*prog == 'e' || *prog == 'E')
240 ds_putc (&tokstr, *prog++);
241 if (*prog == '+' || *prog == '-')
242 ds_putc (&tokstr, *prog++);
243 while (isdigit ((unsigned char) *prog))
244 ds_putc (&tokstr, *prog++);
247 /* Parse as floating point. */
248 tokval = strtod (ds_c_str (&tokstr), &tail);
251 msg (SE, _("%s does not form a valid number."),
256 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, toupper ((unsigned char) *prog++));
357 while (CHAR_IS_IDN (*prog))
358 ds_putc (&tokstr, toupper ((unsigned char) *prog++));
360 /* Copy tokstr to tokid, truncating it to 8 characters. */
361 strncpy (tokid, ds_c_str (&tokstr), 8);
364 token = check_id (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 /* Prints a syntax error message containing the current token and
384 given message MESSAGE (if non-null). */
386 lex_error (const char *message, ...)
390 token_rep = lex_token_representation ();
391 if (token_rep[0] == 0)
392 msg (SE, _("Syntax error at end of file."));
398 va_start (args, message);
399 vsnprintf (buf, 1024, message, args);
402 msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
405 msg (SE, _("Syntax error at `%s'."), token_rep);
410 /* Checks that we're at end of command.
411 If so, returns a successful command completion code.
412 If not, flags a syntax error and returns an error command
415 lex_end_of_command (void)
419 lex_error (_("expecting end of command"));
420 return CMD_TRAILING_GARBAGE;
426 /* Token testing functions. */
428 /* Returns nonzero if the current token is an integer. */
432 return (token == T_NUM
433 && tokval != NOT_LONG
434 && tokval >= LONG_MIN
435 && tokval <= LONG_MAX
436 && floor (tokval) == tokval);
439 /* Returns the value of the current token, which must be an
444 assert (lex_integer_p ());
447 /* Returns nonzero if the current token is an floating point. */
451 return ( token == T_NUM
452 && tokval != NOT_DOUBLE );
455 /* Returns the value of the current token, which must be a
456 floating point number. */
460 assert (lex_double_p ());
465 /* Token matching functions. */
467 /* If TOK is the current token, skips it and returns nonzero.
468 Otherwise, returns zero. */
481 /* If the current token is the identifier S, skips it and returns
483 Otherwise, returns zero. */
485 lex_match_id (const char *s)
487 if (token == T_ID && lex_id_match (s, tokid))
496 /* If the current token is integer N, skips it and returns nonzero.
497 Otherwise, returns zero. */
499 lex_match_int (int x)
501 if (lex_integer_p () && lex_integer () == x)
510 /* Forced matches. */
512 /* If this token is identifier S, fetches the next token and returns
514 Otherwise, reports an error and returns zero. */
516 lex_force_match_id (const char *s)
518 if (token == T_ID && lex_id_match (s, tokid))
525 lex_error (_("expecting `%s'"), s);
530 /* If the current token is T, skips the token. Otherwise, reports an
531 error and returns from the current function with return value 0. */
533 lex_force_match (int t)
542 lex_error (_("expecting %s"), lex_token_name (t));
547 /* If this token is a string, does nothing and returns nonzero.
548 Otherwise, reports an error and returns zero. */
550 lex_force_string (void)
552 if (token == T_STRING)
556 lex_error (_("expecting string"));
561 /* If this token is an integer, does nothing and returns nonzero.
562 Otherwise, reports an error and returns zero. */
566 if (lex_integer_p ())
570 lex_error (_("expecting integer"));
575 /* If this token is a number, does nothing and returns nonzero.
576 Otherwise, reports an error and returns zero. */
584 lex_error (_("expecting number"));
589 /* If this token is an identifier, does nothing and returns nonzero.
590 Otherwise, reports an error and returns zero. */
598 lex_error (_("expecting identifier"));
603 /* Comparing identifiers. */
605 /* Keywords match if one of the following is true: KW and TOK are
606 identical (barring differences in case), or TOK is at least 3
607 characters long and those characters are identical to KW. KW_LEN
608 is the length of KW, TOK_LEN is the length of TOK. */
610 lex_id_match_len (const char *kw, size_t kw_len,
611 const char *tok, size_t tok_len)
618 if (i == kw_len && i == tok_len)
620 else if (i == tok_len)
622 else if (i == kw_len)
624 else if (toupper ((unsigned char) kw[i])
625 != toupper ((unsigned char) tok[i]))
632 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
634 lex_id_match (const char *kw, const char *tok)
636 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
639 /* Weird token functions. */
641 /* Returns the first character of the next token, except that if the
642 next token is not an identifier, the character returned will not be
643 a character that can begin an identifier. Specifically, the
644 hexstring lead-in X' causes lookahead() to return '. Note that an
645 alphanumeric return value doesn't guarantee an ID token, it could
646 also be a reserved-word token. */
648 lex_look_ahead (void)
660 while (isspace ((unsigned char) *prog))
667 else if (!lex_get_line ())
674 if ((toupper ((unsigned char) *prog) == 'X'
675 || toupper ((unsigned char) *prog) == 'B')
676 && (prog[1] == '\'' || prog[1] == '"'))
683 /* Makes the current token become the next token to be read; the
684 current token is set to T. */
692 /* Makes the current token become the next token to be read; the
693 current token is set to the identifier ID. */
695 lex_put_back_id (const char *id)
699 ds_replace (&tokstr, id);
700 strncpy (tokid, ds_c_str (&tokstr), 8);
704 /* Weird line processing functions. */
706 /* Returns the entire contents of the current line. */
708 lex_entire_line (void)
710 return ds_c_str (&getl_buf);
713 /* As lex_entire_line(), but only returns the part of the current line
714 that hasn't already been tokenized.
715 If END_DOT is non-null, stores nonzero into *END_DOT if the line
716 ends with a terminal dot, or zero if it doesn't. */
718 lex_rest_of_line (int *end_dot)
725 /* Causes the rest of the current input line to be ignored for
726 tokenization purposes. */
728 lex_discard_line (void)
730 prog = ds_end (&getl_buf);
734 /* Sets the current position in the current line to P, which must be
737 lex_set_prog (char *p)
742 /* Weird line reading functions. */
744 /* Read a line for use by the tokenizer. */
748 if (!getl_read_line ())
751 lex_preprocess_line ();
755 /* Preprocesses getl_buf by removing comments, stripping trailing
756 whitespace and the terminal dot, and removing leading indentors. */
758 lex_preprocess_line (void)
760 /* Strips comments. */
762 /* getl_buf iterator. */
765 /* Nonzero inside a comment. */
768 /* Nonzero inside a quoted string. */
771 /* Remove C-style comments begun by slash-star and terminated by
772 star-slash or newline. */
774 for (cp = ds_c_str (&getl_buf); *cp; )
776 /* If we're not commented out, toggle quoting. */
781 else if (*cp == '\'' || *cp == '"')
785 /* If we're not quoting, toggle commenting. */
788 if (cp[0] == '/' && cp[1] == '*')
795 else if (cp[0] == '*' && cp[1] == '/' && comment)
804 /* Check commenting. */
812 /* Strip trailing whitespace and terminal dot. */
814 size_t len = ds_length (&getl_buf);
815 char *s = ds_c_str (&getl_buf);
817 /* Strip trailing whitespace. */
818 while (len > 0 && isspace ((unsigned char) s[len - 1]))
821 /* Check for and remove terminal dot. */
822 if (len > 0 && s[len - 1] == get_endcmd() )
827 else if (len == 0 && get_nullline() )
833 ds_truncate (&getl_buf, len);
836 /* In batch mode, strip leading indentors and insert a terminal dot
838 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
840 char *s = ds_c_str (&getl_buf);
842 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
844 else if (s[0] && !isspace ((unsigned char) s[0]))
848 prog = ds_c_str (&getl_buf);
853 /* Returns the name of a token in a static buffer. */
855 lex_token_name (int token)
857 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
858 return keywords[token - T_FIRST_KEYWORD];
870 /* Returns an ASCII representation of the current token as a
871 malloc()'d string. */
873 lex_token_representation (void)
881 return xstrdup (ds_c_str (&tokstr));
889 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
890 if (!isprint ((unsigned char) *sp))
896 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
904 for (sp = ds_c_str (&tokstr); *sp; )
908 *dp++ = (unsigned char) *sp++;
911 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
913 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
914 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
924 token_rep = xmalloc (1);
929 return xstrdup ("**");
932 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
933 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
936 token_rep = xmalloc (2);
937 token_rep[0] = token;
946 /* Really weird functions. */
948 /* Most of the time, a `-' is a lead-in to a negative number. But
949 sometimes it's actually part of the syntax. If a dash can be part
950 of syntax then this function is called to rip it off of a
953 lex_negative_to_dash (void)
955 if (token == T_NUM && tokval < 0.0)
959 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
965 /* We're not at eof any more. */
972 /* Skip a COMMENT command. */
974 lex_skip_comment (void)
978 if (!lex_get_line ())
985 if (put_token == '.')
988 prog = ds_end (&getl_buf);
994 /* Private functions. */
996 /* Unexpected end of file. */
998 unexpected_eof (void)
1000 msg (FE, _("Unexpected end of file."));
1003 /* Returns the proper token type, either T_ID or a reserved keyword
1004 enum, for ID[], which must contain LEN characters. */
1006 check_id (const char *id, size_t len)
1010 if (len < 2 || len > 4)
1013 for (kwp = keywords; *kwp; kwp++)
1014 if (!strcmp (*kwp, id))
1015 return T_FIRST_KEYWORD + (kwp - keywords);
1020 /* When invoked, tokstr contains a string of binary, octal, or hex
1021 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1022 is converted to characters having the specified values. */
1024 convert_numeric_string_to_char_string (int type)
1026 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1027 static const int bases[] = {2, 8, 16};
1028 static const int chars_per_byte[] = {8, 3, 2};
1030 const char *const base_name = base_names[type];
1031 const int base = bases[type];
1032 const int cpb = chars_per_byte[type];
1033 const int nb = ds_length (&tokstr) / cpb;
1037 assert (type >= 0 && type <= 2);
1039 if (ds_length (&tokstr) % cpb)
1040 msg (SE, _("String of %s digits has %d characters, which is not a "
1042 gettext (base_name), ds_length (&tokstr), cpb);
1044 p = ds_c_str (&tokstr);
1045 for (i = 0; i < nb; i++)
1051 for (j = 0; j < cpb; j++, p++)
1055 if (*p >= '0' && *p <= '9')
1059 static const char alpha[] = "abcdef";
1060 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1069 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1071 value = value * base + v;
1074 ds_c_str (&tokstr)[i] = (unsigned char) value;
1077 ds_truncate (&tokstr, nb);
1080 /* Parses a string from the input buffer into tokstr. The input
1081 buffer pointer prog must point to the initial single or double
1082 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1083 binary, octal, or hexstring, respectively. Returns token type. */
1085 parse_string (int type)
1087 /* Accumulate the entire string, joining sections indicated by +
1091 /* Single or double quote. */
1094 /* Accumulate section. */
1097 /* Check end of line. */
1100 msg (SE, _("Unterminated string constant."));
1104 /* Double quote characters to embed them in strings. */
1113 ds_putc (&tokstr, *prog++);
1117 /* Skip whitespace after final quote mark. */
1122 while (isspace ((unsigned char) *prog))
1130 if (!lex_get_line ())
1134 /* Skip plus sign. */
1139 /* Skip whitespace after plus sign. */
1144 while (isspace ((unsigned char) *prog))
1152 if (!lex_get_line ())
1156 /* Ensure that a valid string follows. */
1157 if (*prog != '\'' && *prog != '"')
1159 msg (SE, "String expected following `+'.");
1164 /* We come here when we've finished concatenating all the string sections
1165 into one large string. */
1168 convert_numeric_string_to_char_string (type - 1);
1170 if (ds_length (&tokstr) > 255)
1172 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1173 ds_length (&tokstr));
1174 ds_truncate (&tokstr, 255);
1182 for (i = 0; i < ds_length (&tokstr); i++)
1183 if (ds_c_str (&tokstr)[i] == 0)
1187 msg (SE, _("Sorry, literal strings may not contain null "
1188 "characters. Replacing with spaces."));
1191 ds_c_str (&tokstr)[i] = ' ';
1199 /* Reads one token from the lexer and writes a textual representation
1200 on stdout for debugging purposes. */
1208 getl_location (&curfn, &curln);
1210 fprintf (stderr, "%s:%d\t", curfn, curln);
1216 fprintf (stderr, "ID\t%s\n", tokid);
1220 fprintf (stderr, "NUM\t%f\n", tokval);
1224 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1228 fprintf (stderr, "STOP\n");
1232 fprintf (stderr, "MISC\tEXP\"");
1236 fprintf (stderr, "MISC\tEOF\n");
1240 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1241 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1243 fprintf (stderr, "PUNCT\t%c\n", token);
1247 #endif /* DUMP_TOKENS */