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_EOF. */
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 (NULL, &put_tokstr, 64);
103 /* Common functions. */
105 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
106 tokval, respectively, and sets tokid appropriately. */
110 assert (put_token != 0);
112 ds_replace (&tokstr, ds_value (&put_tokstr));
113 strncpy (tokid, ds_value (&put_tokstr), 8);
119 /* Copies token, tokstr, tokval into put_token, put_tokstr,
120 put_tokval respectively. */
125 ds_replace (&put_tokstr, ds_value (&tokstr));
129 /* Parses a single token, setting appropriate global variables to
130 indicate the token's attributes. */
134 /* If a token was pushed ahead, return it. */
149 /* Skip whitespace. */
155 while (isspace ((unsigned char) *prog))
169 else if (!lex_get_line ())
190 /* Actually parse the token. */
197 case '0': case '1': case '2': case '3': case '4':
198 case '5': case '6': case '7': case '8': case '9':
202 /* `-' can introduce a negative number, or it can be a
203 token by itself. If it is not followed by a digit or a
204 decimal point, it is definitely not a number.
205 Otherwise, it might be either, but most of the time we
206 want it as a number. When the syntax calls for a `-'
207 token, lex_negative_to_dash() must be used to break
208 negative numbers into two tokens. */
211 ds_putchar (&tokstr, *prog++);
212 while (isspace ((unsigned char) *prog))
215 if (!isdigit ((unsigned char) *prog) && *prog != '.')
222 /* Parse the number, copying it into tokstr. */
223 while (isdigit ((unsigned char) *prog))
224 ds_putchar (&tokstr, *prog++);
227 ds_putchar (&tokstr, *prog++);
228 while (isdigit ((unsigned char) *prog))
229 ds_putchar (&tokstr, *prog++);
231 if (*prog == 'e' || *prog == 'E')
233 ds_putchar (&tokstr, *prog++);
234 if (*prog == '+' || *prog == '-')
235 ds_putchar (&tokstr, *prog++);
236 while (isdigit ((unsigned char) *prog))
237 ds_putchar (&tokstr, *prog++);
240 /* Parse as floating point. */
241 tokval = strtod (ds_value (&tokstr), &tail);
244 msg (SE, _("%s does not form a valid number."),
249 ds_putchar (&tokstr, '0');
257 token = parse_string (0);
260 case '(': case ')': case ',': case '=': case '+': case '/':
280 else if (*prog == '>')
319 case 'a': case 'b': case 'c': case 'd': case 'e':
320 case 'f': case 'g': case 'h': case 'i': case 'j':
321 case 'k': case 'l': case 'm': case 'n': case 'o':
322 case 'p': case 'q': case 'r': case 's': case 't':
323 case 'u': case 'v': case 'w': case 'x': case 'y':
325 case 'A': case 'B': case 'C': case 'D': case 'E':
326 case 'F': case 'G': case 'H': case 'I': case 'J':
327 case 'K': case 'L': case 'M': case 'N': case 'O':
328 case 'P': case 'Q': case 'R': case 'S': case 'T':
329 case 'U': case 'V': case 'W': case 'X': case 'Y':
331 case '#': case '$': case '@':
332 /* Strings can be specified in binary, octal, or hex using
333 this special syntax. */
334 if (prog[1] == '\'' || prog[1] == '"')
336 static const char special[3] = "box";
339 p = strchr (special, tolower ((unsigned char) *prog));
343 token = parse_string (p - special + 1);
348 /* Copy id to tokstr. */
349 ds_putchar (&tokstr, toupper ((unsigned char) *prog++));
350 while (CHAR_IS_IDN (*prog))
351 ds_putchar (&tokstr, toupper ((unsigned char) *prog++));
353 /* Copy tokstr to tokid, truncating it to 8 characters. */
354 strncpy (tokid, ds_value (&tokstr), 8);
357 token = check_id (ds_value (&tokstr), ds_length (&tokstr));
361 if (isgraph ((unsigned char) *prog))
362 msg (SE, _("Bad character in input: `%c'."), *prog++);
364 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
376 /* Prints a syntax error message containing the current token and
377 given message MESSAGE (if non-null). */
379 lex_error (const char *message, ...)
383 token_rep = lex_token_representation ();
384 if (token_rep[0] == 0)
385 msg (SE, _("Syntax error at end of file."));
391 va_start (args, message);
392 vsnprintf (buf, 1024, message, args);
395 msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
398 msg (SE, _("Syntax error at `%s'."), token_rep);
403 /* Checks that we're at end of command.
404 If so, returns a successful command completion code.
405 If not, flags a syntax error and returns an error command
408 lex_end_of_command (void)
412 lex_error (_("expecting end of command"));
413 return CMD_TRAILING_GARBAGE;
419 /* Token testing functions. */
421 /* Returns nonzero if the current token is an integer. */
425 return (token == T_NUM
426 && tokval != NOT_LONG
427 && tokval >= LONG_MIN
428 && tokval <= LONG_MAX
429 && floor (tokval) == tokval);
432 /* Returns the value of the current token, which must be an
437 assert (lex_integer_p ());
440 /* Returns nonzero if the current token is an floating point. */
444 return ( token == T_NUM
445 && tokval != NOT_DOUBLE );
448 /* Returns the value of the current token, which must be a
449 floating point number. */
453 assert (lex_double_p ());
458 /* Token matching functions. */
460 /* If TOK is the current token, skips it and returns nonzero.
461 Otherwise, returns zero. */
474 /* If the current token is the identifier S, skips it and returns
476 Otherwise, returns zero. */
478 lex_match_id (const char *s)
480 if (token == T_ID && lex_id_match (s, tokid))
489 /* If the current token is integer N, skips it and returns nonzero.
490 Otherwise, returns zero. */
492 lex_match_int (int x)
494 if (lex_integer_p () && lex_integer () == x)
503 /* Forced matches. */
505 /* If this token is identifier S, fetches the next token and returns
507 Otherwise, reports an error and returns zero. */
509 lex_force_match_id (const char *s)
511 if (token == T_ID && lex_id_match (s, tokid))
518 lex_error (_("expecting `%s'"), s);
523 /* If the current token is T, skips the token. Otherwise, reports an
524 error and returns from the current function with return value 0. */
526 lex_force_match (int t)
535 lex_error (_("expecting %s"), lex_token_name (t));
540 /* If this token is a string, does nothing and returns nonzero.
541 Otherwise, reports an error and returns zero. */
543 lex_force_string (void)
545 if (token == T_STRING)
549 lex_error (_("expecting string"));
554 /* If this token is an integer, does nothing and returns nonzero.
555 Otherwise, reports an error and returns zero. */
559 if (lex_integer_p ())
563 lex_error (_("expecting integer"));
568 /* If this token is a number, does nothing and returns nonzero.
569 Otherwise, reports an error and returns zero. */
577 lex_error (_("expecting number"));
582 /* If this token is an identifier, does nothing and returns nonzero.
583 Otherwise, reports an error and returns zero. */
591 lex_error (_("expecting identifier"));
596 /* Comparing identifiers. */
598 /* Keywords match if one of the following is true: KW and TOK are
599 identical (barring differences in case), or TOK is at least 3
600 characters long and those characters are identical to KW. KW_LEN
601 is the length of KW, TOK_LEN is the length of TOK. */
603 lex_id_match_len (const char *kw, size_t kw_len,
604 const char *tok, size_t tok_len)
611 if (i == kw_len && i == tok_len)
613 else if (i == tok_len)
615 else if (i == kw_len)
617 else if (toupper ((unsigned char) kw[i])
618 != toupper ((unsigned char) tok[i]))
625 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
627 lex_id_match (const char *kw, const char *tok)
629 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
632 /* Weird token functions. */
634 /* Returns the first character of the next token, except that if the
635 next token is not an identifier, the character returned will not be
636 a character that can begin an identifier. Specifically, the
637 hexstring lead-in X' causes lookahead() to return '. Note that an
638 alphanumeric return value doesn't guarantee an ID token, it could
639 also be a reserved-word token. */
641 lex_look_ahead (void)
653 while (isspace ((unsigned char) *prog))
660 else if (!lex_get_line ())
667 if ((toupper ((unsigned char) *prog) == 'X'
668 || toupper ((unsigned char) *prog) == 'B')
669 && (prog[1] == '\'' || prog[1] == '"'))
676 /* Makes the current token become the next token to be read; the
677 current token is set to T. */
685 /* Makes the current token become the next token to be read; the
686 current token is set to the identifier ID. */
688 lex_put_back_id (const char *id)
692 ds_replace (&tokstr, id);
693 strncpy (tokid, ds_value (&tokstr), 8);
697 /* Weird line processing functions. */
699 /* Discards the rest of the current input line for tokenization
700 purposes, but returns the entire contents of the line for use by
703 lex_entire_line (void)
705 prog = ds_end (&getl_buf);
707 return ds_value (&getl_buf);
710 /* As lex_entire_line(), but only returns the part of the current line
711 that hasn't already been tokenized.
712 If HAD_DOT is non-null, stores nonzero into *HAD_DOT if the line
713 ends with a terminal dot, or zero if it doesn't. */
715 lex_rest_of_line (int *had_dot)
718 prog = ds_end (&getl_buf);
727 /* Causes the rest of the current input line to be ignored for
728 tokenization purposes. */
730 lex_discard_line (void)
732 msg (SW, _("The rest of this command has been discarded."));
734 ds_clear (&getl_buf);
735 prog = ds_value (&getl_buf);
739 /* Sets the current position in the current line to P, which must be
742 lex_set_prog (char *p)
747 /* Weird line reading functions. */
749 /* Read a line for use by the tokenizer. */
753 if (!getl_read_line ())
756 lex_preprocess_line ();
760 /* Preprocesses getl_buf by removing comments, stripping trailing
761 whitespace and the terminal dot, and removing leading indentors. */
763 lex_preprocess_line (void)
765 /* Strips comments. */
767 /* getl_buf iterator. */
770 /* Nonzero inside a comment. */
773 /* Nonzero inside a quoted string. */
776 /* Remove C-style comments begun by slash-star and terminated by
777 star-slash or newline. */
779 for (cp = ds_value (&getl_buf); *cp; )
781 /* If we're not commented out, toggle quoting. */
786 else if (*cp == '\'' || *cp == '"')
790 /* If we're not quoting, toggle commenting. */
793 if (cp[0] == '/' && cp[1] == '*')
800 else if (cp[0] == '*' && cp[1] == '/' && comment)
809 /* Check commenting. */
817 /* Strip trailing whitespace and terminal dot. */
819 size_t len = ds_length (&getl_buf);
820 char *s = ds_value (&getl_buf);
822 /* Strip trailing whitespace. */
823 while (len > 0 && isspace ((unsigned char) s[len - 1]))
826 /* Check for and remove terminal dot. */
827 if (len > 0 && s[len - 1] == get_endcmd() )
832 else if (len == 0 && get_nullline() )
838 ds_truncate (&getl_buf, len);
841 /* In batch mode, strip leading indentors and insert a terminal dot
843 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
845 char *s = ds_value (&getl_buf);
847 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
849 else if (s[0] && !isspace ((unsigned char) s[0]))
853 prog = ds_value (&getl_buf);
858 /* Returns the name of a token in a static buffer. */
860 lex_token_name (int token)
862 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
863 return keywords[token - T_FIRST_KEYWORD];
875 /* Returns an ASCII representation of the current token as a
876 malloc()'d string. */
878 lex_token_representation (void)
886 return xstrdup (ds_value (&tokstr));
894 for (sp = ds_value (&tokstr); sp < ds_end (&tokstr); sp++)
895 if (!isprint ((unsigned char) *sp))
901 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
909 for (sp = ds_value (&tokstr); *sp; )
913 *dp++ = (unsigned char) *sp++;
916 for (sp = ds_value (&tokstr); sp < ds_end (&tokstr); sp++)
918 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
919 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
929 token_rep = xmalloc (1);
934 return xstrdup ("**");
937 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
938 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
941 token_rep = xmalloc (2);
942 token_rep[0] = token;
951 /* Really weird functions. */
953 /* Most of the time, a `-' is a lead-in to a negative number. But
954 sometimes it's actually part of the syntax. If a dash can be part
955 of syntax then this function is called to rip it off of a
958 lex_negative_to_dash (void)
960 if (token == T_NUM && tokval < 0.0)
964 ds_replace (&tokstr, ds_value (&tokstr) + 1);
970 /* We're not at eof any more. */
977 /* Skip a COMMENT command. */
979 lex_skip_comment (void)
984 if (put_token == '.')
987 prog = ds_end (&getl_buf);
993 /* Private functions. */
995 /* Unexpected end of file. */
997 unexpected_eof (void)
999 msg (FE, _("Unexpected end of file."));
1002 /* Returns the proper token type, either T_ID or a reserved keyword
1003 enum, for ID[], which must contain LEN characters. */
1005 check_id (const char *id, size_t len)
1009 if (len < 2 || len > 4)
1012 for (kwp = keywords; *kwp; kwp++)
1013 if (!strcmp (*kwp, id))
1014 return T_FIRST_KEYWORD + (kwp - keywords);
1019 /* When invoked, tokstr contains a string of binary, octal, or hex
1020 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1021 is converted to characters having the specified values. */
1023 convert_numeric_string_to_char_string (int type)
1025 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1026 static const int bases[] = {2, 8, 16};
1027 static const int chars_per_byte[] = {8, 3, 2};
1029 const char *const base_name = base_names[type];
1030 const int base = bases[type];
1031 const int cpb = chars_per_byte[type];
1032 const int nb = ds_length (&tokstr) / cpb;
1036 assert (type >= 0 && type <= 2);
1038 if (ds_length (&tokstr) % cpb)
1039 msg (SE, _("String of %s digits has %d characters, which is not a "
1041 gettext (base_name), ds_length (&tokstr), cpb);
1043 p = ds_value (&tokstr);
1044 for (i = 0; i < nb; i++)
1050 for (j = 0; j < cpb; j++, p++)
1054 if (*p >= '0' && *p <= '9')
1058 static const char alpha[] = "abcdef";
1059 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1068 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1070 value = value * base + v;
1073 ds_value (&tokstr)[i] = (unsigned char) value;
1076 ds_truncate (&tokstr, nb);
1079 /* Parses a string from the input buffer into tokstr. The input
1080 buffer pointer prog must point to the initial single or double
1081 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1082 binary, octal, or hexstring, respectively. Returns token type. */
1084 parse_string (int type)
1086 /* Accumulate the entire string, joining sections indicated by +
1090 /* Single or double quote. */
1093 /* Accumulate section. */
1096 /* Check end of line. */
1099 msg (SE, _("Unterminated string constant."));
1103 /* Double quote characters to embed them in strings. */
1112 ds_putchar (&tokstr, *prog++);
1116 /* Skip whitespace after final quote mark. */
1121 while (isspace ((unsigned char) *prog))
1129 if (!lex_get_line ())
1133 /* Skip plus sign. */
1138 /* Skip whitespace after plus sign. */
1143 while (isspace ((unsigned char) *prog))
1151 if (!lex_get_line ())
1155 /* Ensure that a valid string follows. */
1156 if (*prog != '\'' && *prog != '"')
1158 msg (SE, "String expected following `+'.");
1163 /* We come here when we've finished concatenating all the string sections
1164 into one large string. */
1167 convert_numeric_string_to_char_string (type - 1);
1169 if (ds_length (&tokstr) > 255)
1171 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1172 ds_length (&tokstr));
1173 ds_truncate (&tokstr, 255);
1181 for (i = 0; i < ds_length (&tokstr); i++)
1182 if (ds_value (&tokstr)[i] == 0)
1186 msg (SE, _("Sorry, literal strings may not contain null "
1187 "characters. Replacing with spaces."));
1190 ds_value (&tokstr)[i] = ' ';
1198 /* Reads one token from the lexer and writes a textual representation
1199 on stdout for debugging purposes. */
1207 getl_location (&curfn, &curln);
1209 fprintf (stderr, "%s:%d\t", curfn, curln);
1215 fprintf (stderr, "ID\t%s\n", tokid);
1219 fprintf (stderr, "NUM\t%f\n", tokval);
1223 fprintf (stderr, "STRING\t\"%s\"\n", ds_value (&tokstr));
1227 fprintf (stderr, "STOP\n");
1231 fprintf (stderr, "MISC\tEXP\"");
1235 fprintf (stderr, "MISC\tEOF\n");
1239 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1240 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1242 fprintf (stderr, "PUNCT\t%c\n", token);
1246 #endif /* DEBUGGING */