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
42 /* Global variables. */
47 /* T_POS_NUM, T_NEG_NUM: the token's value. */
50 /* T_ID: the identifier. */
51 char tokid[LONG_NAME_LEN + 1];
53 /* T_ID, T_STRING: token string value.
54 For T_ID, this is not truncated 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 void convert_numeric_string_to_char_string (int type);
85 static int parse_string (int type);
88 static void dump_token (void);
93 /* Initializes the lexer. */
97 ds_init (&put_tokstr, 64);
105 ds_destroy(&put_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 /* Prints a syntax error message containing the current token and
384 given message MESSAGE (if non-null). */
386 lex_error (const char *message, ...)
391 token_rep = lex_token_representation ();
393 strcpy (where, "end of file");
394 else if (token == '.')
395 strcpy (where, "end of command");
397 snprintf (where, sizeof where, "`%s'", token_rep);
405 va_start (args, message);
406 vsnprintf (buf, 1024, message, args);
409 msg (SE, _("Syntax error %s at %s."), buf, where);
412 msg (SE, _("Syntax error at %s."), where);
415 /* Checks that we're at end of command.
416 If so, returns a successful command completion code.
417 If not, flags a syntax error and returns an error command
420 lex_end_of_command (void)
424 lex_error (_("expecting end of command"));
425 return CMD_TRAILING_GARBAGE;
431 /* Token testing functions. */
433 /* Returns true if the current token is a number. */
437 return token == T_POS_NUM || token == T_NEG_NUM;
440 /* Returns the value of the current token, which must be a
441 floating point number. */
445 assert (lex_is_number ());
449 /* Returns true iff the current token is an integer. */
451 lex_is_integer (void)
453 return (lex_is_number ()
454 && tokval != NOT_LONG
455 && tokval >= LONG_MIN
456 && tokval <= LONG_MAX
457 && floor (tokval) == tokval);
460 /* Returns the value of the current token, which must be an
465 assert (lex_is_integer ());
469 /* Token matching functions. */
471 /* If TOK is the current token, skips it and returns nonzero.
472 Otherwise, returns zero. */
485 /* If the current token is the identifier S, skips it and returns
486 nonzero. The identifier may be abbreviated to its first three
488 Otherwise, returns zero. */
490 lex_match_id (const char *s)
492 if (token == T_ID && lex_id_match (s, tokid))
501 /* If the current token is integer N, skips it and returns nonzero.
502 Otherwise, returns zero. */
504 lex_match_int (int x)
506 if (lex_is_integer () && lex_integer () == x)
515 /* Forced matches. */
517 /* If this token is identifier S, fetches the next token and returns
519 Otherwise, reports an error and returns zero. */
521 lex_force_match_id (const char *s)
523 if (token == T_ID && lex_id_match (s, tokid))
530 lex_error (_("expecting `%s'"), s);
535 /* If the current token is T, skips the token. Otherwise, reports an
536 error and returns from the current function with return value 0. */
538 lex_force_match (int t)
547 lex_error (_("expecting `%s'"), lex_token_name (t));
552 /* If this token is a string, does nothing and returns nonzero.
553 Otherwise, reports an error and returns zero. */
555 lex_force_string (void)
557 if (token == T_STRING)
561 lex_error (_("expecting string"));
566 /* If this token is an integer, does nothing and returns nonzero.
567 Otherwise, reports an error and returns zero. */
571 if (lex_is_integer ())
575 lex_error (_("expecting integer"));
580 /* If this token is a number, does nothing and returns nonzero.
581 Otherwise, reports an error and returns zero. */
585 if (lex_is_number ())
589 lex_error (_("expecting number"));
594 /* If this token is an identifier, does nothing and returns nonzero.
595 Otherwise, reports an error and returns zero. */
603 lex_error (_("expecting identifier"));
608 /* Comparing identifiers. */
610 /* Keywords match if one of the following is true: KW and TOK are
611 identical (except for differences in case), or TOK is at least 3
612 characters long and those characters are identical to KW. KW_LEN
613 is the length of KW, TOK_LEN is the length of TOK. */
615 lex_id_match_len (const char *kw, size_t kw_len,
616 const char *tok, size_t tok_len)
623 if (i == kw_len && i == tok_len)
625 else if (i == tok_len)
627 else if (i == kw_len)
629 else if (toupper ((unsigned char) kw[i])
630 != toupper ((unsigned char) tok[i]))
637 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
639 lex_id_match (const char *kw, const char *tok)
641 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
644 /* Returns the proper token type, either T_ID or a reserved keyword
645 enum, for ID[], which must contain LEN characters. */
647 lex_id_to_token (const char *id, size_t len)
651 if (len < 2 || len > 4)
654 for (kwp = keywords; *kwp; kwp++)
655 if (!strcasecmp (*kwp, id))
656 return T_FIRST_KEYWORD + (kwp - keywords);
661 /* Weird token functions. */
663 /* Returns the first character of the next token, except that if the
664 next token is not an identifier, the character returned will not be
665 a character that can begin an identifier. Specifically, the
666 hexstring lead-in X' causes lookahead() to return '. Note that an
667 alphanumeric return value doesn't guarantee an ID token, it could
668 also be a reserved-word token. */
670 lex_look_ahead (void)
682 while (isspace ((unsigned char) *prog))
689 else if (!lex_get_line ())
696 if ((toupper ((unsigned char) *prog) == 'X'
697 || toupper ((unsigned char) *prog) == 'B')
698 && (prog[1] == '\'' || prog[1] == '"'))
705 /* Makes the current token become the next token to be read; the
706 current token is set to T. */
714 /* Makes the current token become the next token to be read; the
715 current token is set to the identifier ID. */
717 lex_put_back_id (const char *id)
719 assert (lex_id_to_token (id, strlen (id)) == T_ID);
722 ds_replace (&tokstr, id);
723 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
726 /* Weird line processing functions. */
728 /* Returns the entire contents of the current line. */
730 lex_entire_line (void)
732 return ds_c_str (&getl_buf);
735 /* As lex_entire_line(), but only returns the part of the current line
736 that hasn't already been tokenized.
737 If END_DOT is non-null, stores nonzero into *END_DOT if the line
738 ends with a terminal dot, or zero if it doesn't. */
740 lex_rest_of_line (int *end_dot)
747 /* Causes the rest of the current input line to be ignored for
748 tokenization purposes. */
750 lex_discard_line (void)
752 prog = ds_end (&getl_buf);
756 /* Sets the current position in the current line to P, which must be
759 lex_set_prog (char *p)
764 /* Weird line reading functions. */
766 /* Read a line for use by the tokenizer. */
770 if (!getl_read_line ())
773 lex_preprocess_line ();
777 /* Preprocesses getl_buf by removing comments, stripping trailing
778 whitespace and the terminal dot, and removing leading indentors. */
780 lex_preprocess_line (void)
782 /* Strips comments. */
784 /* getl_buf iterator. */
787 /* Nonzero inside a comment. */
790 /* Nonzero inside a quoted string. */
793 /* Remove C-style comments begun by slash-star and terminated by
794 star-slash or newline. */
796 for (cp = ds_c_str (&getl_buf); *cp; )
798 /* If we're not commented out, toggle quoting. */
803 else if (*cp == '\'' || *cp == '"')
807 /* If we're not quoting, toggle commenting. */
810 if (cp[0] == '/' && cp[1] == '*')
817 else if (cp[0] == '*' && cp[1] == '/' && comment)
826 /* Check commenting. */
834 /* Strip trailing whitespace and terminal dot. */
836 size_t len = ds_length (&getl_buf);
837 char *s = ds_c_str (&getl_buf);
839 /* Strip trailing whitespace. */
840 while (len > 0 && isspace ((unsigned char) s[len - 1]))
843 /* Check for and remove terminal dot. */
844 if (len > 0 && s[len - 1] == get_endcmd() )
849 else if (len == 0 && get_nullline() )
855 ds_truncate (&getl_buf, len);
858 /* In batch mode, strip leading indentors and insert a terminal dot
860 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
862 char *s = ds_c_str (&getl_buf);
864 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
866 else if (s[0] && !isspace ((unsigned char) s[0]))
870 prog = ds_c_str (&getl_buf);
875 /* Returns the name of a token in a static buffer. */
877 lex_token_name (int token)
879 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
880 return keywords[token - T_FIRST_KEYWORD];
892 /* Returns an ASCII representation of the current token as a
893 malloc()'d string. */
895 lex_token_representation (void)
904 return xstrdup (ds_c_str (&tokstr));
912 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
913 if (!isprint ((unsigned char) *sp))
919 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
927 for (sp = ds_c_str (&tokstr); *sp; )
931 *dp++ = (unsigned char) *sp++;
934 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
936 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
937 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
947 token_rep = xmalloc (1);
952 return xstrdup ("**");
955 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
956 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
959 token_rep = xmalloc (2);
960 token_rep[0] = token;
969 /* Really weird functions. */
971 /* Most of the time, a `-' is a lead-in to a negative number. But
972 sometimes it's actually part of the syntax. If a dash can be part
973 of syntax then this function is called to rip it off of a
976 lex_negative_to_dash (void)
978 if (token == T_NEG_NUM)
982 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
988 /* We're not at eof any more. */
995 /* Skip a COMMENT command. */
997 lex_skip_comment (void)
1001 if (!lex_get_line ())
1008 if (put_token == '.')
1011 prog = ds_end (&getl_buf);
1017 /* Private functions. */
1019 /* Unexpected end of file. */
1021 unexpected_eof (void)
1023 msg (FE, _("Unexpected end of file."));
1026 /* When invoked, tokstr contains a string of binary, octal, or hex
1027 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1028 is converted to characters having the specified values. */
1030 convert_numeric_string_to_char_string (int type)
1032 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1033 static const int bases[] = {2, 8, 16};
1034 static const int chars_per_byte[] = {8, 3, 2};
1036 const char *const base_name = base_names[type];
1037 const int base = bases[type];
1038 const int cpb = chars_per_byte[type];
1039 const int nb = ds_length (&tokstr) / cpb;
1043 assert (type >= 0 && type <= 2);
1045 if (ds_length (&tokstr) % cpb)
1046 msg (SE, _("String of %s digits has %d characters, which is not a "
1048 gettext (base_name), ds_length (&tokstr), cpb);
1050 p = ds_c_str (&tokstr);
1051 for (i = 0; i < nb; i++)
1057 for (j = 0; j < cpb; j++, p++)
1061 if (*p >= '0' && *p <= '9')
1065 static const char alpha[] = "abcdef";
1066 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1075 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1077 value = value * base + v;
1080 ds_c_str (&tokstr)[i] = (unsigned char) value;
1083 ds_truncate (&tokstr, nb);
1086 /* Parses a string from the input buffer into tokstr. The input
1087 buffer pointer prog must point to the initial single or double
1088 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1089 binary, octal, or hexstring, respectively. Returns token type. */
1091 parse_string (int type)
1093 /* Accumulate the entire string, joining sections indicated by +
1097 /* Single or double quote. */
1100 /* Accumulate section. */
1103 /* Check end of line. */
1106 msg (SE, _("Unterminated string constant."));
1110 /* Double quote characters to embed them in strings. */
1119 ds_putc (&tokstr, *prog++);
1123 /* Skip whitespace after final quote mark. */
1128 while (isspace ((unsigned char) *prog))
1136 if (!lex_get_line ())
1140 /* Skip plus sign. */
1145 /* Skip whitespace after plus sign. */
1150 while (isspace ((unsigned char) *prog))
1158 if (!lex_get_line ())
1162 /* Ensure that a valid string follows. */
1163 if (*prog != '\'' && *prog != '"')
1165 msg (SE, "String expected following `+'.");
1170 /* We come here when we've finished concatenating all the string sections
1171 into one large string. */
1174 convert_numeric_string_to_char_string (type - 1);
1176 if (ds_length (&tokstr) > 255)
1178 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1179 ds_length (&tokstr));
1180 ds_truncate (&tokstr, 255);
1188 for (i = 0; i < ds_length (&tokstr); i++)
1189 if (ds_c_str (&tokstr)[i] == 0)
1193 msg (SE, _("Sorry, literal strings may not contain null "
1194 "characters. Replacing with spaces."));
1197 ds_c_str (&tokstr)[i] = ' ';
1205 /* Reads one token from the lexer and writes a textual representation
1206 on stdout for debugging purposes. */
1214 getl_location (&curfn, &curln);
1216 fprintf (stderr, "%s:%d\t", curfn, curln);
1222 fprintf (stderr, "ID\t%s\n", tokid);
1227 fprintf (stderr, "NUM\t%f\n", tokval);
1231 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1235 fprintf (stderr, "STOP\n");
1239 fprintf (stderr, "MISC\tEXP\"");
1243 fprintf (stderr, "MISC\tEOF\n");
1247 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1248 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1250 fprintf (stderr, "PUNCT\t%c\n", token);
1254 #endif /* DUMP_TOKENS */