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. */
51 char tokid[LONG_NAME_LEN + 1];
53 /* T_ID, T_STRING: token string value.
54 For T_ID, this is not truncated to SHORT_NAME_LEN 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 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 strncpy (tokid, ds_c_str (&put_tokstr), SHORT_NAME_LEN);
120 tokid[SHORT_NAME_LEN] = 0;
125 /* Copies token, tokstr, tokval into put_token, put_tokstr,
126 put_tokval respectively. */
131 ds_replace (&put_tokstr, ds_c_str (&tokstr));
135 /* Parses a single token, setting appropriate global variables to
136 indicate the token's attributes. */
142 /* If a token was pushed ahead, return it. */
157 /* Skip whitespace. */
163 while (isspace ((unsigned char) *prog))
177 else if (!lex_get_line ())
198 /* Actually parse the token. */
205 case '0': case '1': case '2': case '3': case '4':
206 case '5': case '6': case '7': case '8': case '9':
210 /* `-' can introduce a negative number, or it can be a
211 token by itself. If it is not followed by a digit or a
212 decimal point, it is definitely not a number.
213 Otherwise, it might be either, but most of the time we
214 want it as a number. When the syntax calls for a `-'
215 token, lex_negative_to_dash() must be used to break
216 negative numbers into two tokens. */
219 ds_putc (&tokstr, *prog++);
220 while (isspace ((unsigned char) *prog))
223 if (!isdigit ((unsigned char) *prog) && *prog != '.')
233 /* Parse the number, copying it into tokstr. */
234 while (isdigit ((unsigned char) *prog))
235 ds_putc (&tokstr, *prog++);
238 ds_putc (&tokstr, *prog++);
239 while (isdigit ((unsigned char) *prog))
240 ds_putc (&tokstr, *prog++);
242 if (*prog == 'e' || *prog == 'E')
244 ds_putc (&tokstr, *prog++);
245 if (*prog == '+' || *prog == '-')
246 ds_putc (&tokstr, *prog++);
247 while (isdigit ((unsigned char) *prog))
248 ds_putc (&tokstr, *prog++);
251 /* Parse as floating point. */
252 tokval = strtod (ds_c_str (&tokstr), &tail);
255 msg (SE, _("%s does not form a valid number."),
260 ds_putc (&tokstr, '0');
267 token = parse_string (0);
270 case '(': case ')': case ',': case '=': case '+': case '/':
290 else if (*prog == '>')
329 case 'a': case 'b': case 'c': case 'd': case 'e':
330 case 'f': case 'g': case 'h': case 'i': case 'j':
331 case 'k': case 'l': case 'm': case 'n': case 'o':
332 case 'p': case 'q': case 'r': case 's': case 't':
333 case 'u': case 'v': case 'w': case 'x': case 'y':
335 case 'A': case 'B': case 'C': case 'D': case 'E':
336 case 'F': case 'G': case 'H': case 'I': case 'J':
337 case 'K': case 'L': case 'M': case 'N': case 'O':
338 case 'P': case 'Q': case 'R': case 'S': case 'T':
339 case 'U': case 'V': case 'W': case 'X': case 'Y':
341 case '#': case '$': case '@':
342 /* Strings can be specified in binary, octal, or hex using
343 this special syntax. */
344 if (prog[1] == '\'' || prog[1] == '"')
346 static const char special[3] = "box";
349 p = strchr (special, tolower ((unsigned char) *prog));
353 token = parse_string (p - special + 1);
358 /* Copy id to tokstr. */
359 ds_putc (&tokstr, *prog++);
360 while (CHAR_IS_IDN (*prog))
361 ds_putc (&tokstr, *prog++);
363 /* Copy tokstr to tokid, truncating it to LONG_NAME_LEN characters.*/
364 strncpy (tokid, ds_c_str (&tokstr), LONG_NAME_LEN);
365 tokid[LONG_NAME_LEN] = 0;
367 /* Convert to upper case */
368 for ( i = 0 ; i < ds_length(&tokstr) ; ++i )
369 tokstr.string[i] = toupper(tokstr.string[i]);
371 token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
375 if (isgraph ((unsigned char) *prog))
376 msg (SE, _("Bad character in input: `%c'."), *prog++);
378 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
390 /* Prints a syntax error message containing the current token and
391 given message MESSAGE (if non-null). */
393 lex_error (const char *message, ...)
397 token_rep = lex_token_representation ();
398 if (token_rep[0] == 0)
399 msg (SE, _("Syntax error at end of file."));
405 va_start (args, message);
406 vsnprintf (buf, 1024, message, args);
409 msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
412 msg (SE, _("Syntax error at `%s'."), token_rep);
417 /* Checks that we're at end of command.
418 If so, returns a successful command completion code.
419 If not, flags a syntax error and returns an error command
422 lex_end_of_command (void)
426 lex_error (_("expecting end of command"));
427 return CMD_TRAILING_GARBAGE;
433 /* Token testing functions. */
435 /* Returns true if the current token is a number. */
439 return token == T_POS_NUM || token == T_NEG_NUM;
442 /* Returns the value of the current token, which must be a
443 floating point number. */
447 assert (lex_is_number ());
451 /* Returns true iff the current token is an integer. */
453 lex_is_integer (void)
455 return (lex_is_number ()
456 && tokval != NOT_LONG
457 && tokval >= LONG_MIN
458 && tokval <= LONG_MAX
459 && floor (tokval) == tokval);
462 /* Returns the value of the current token, which must be an
467 assert (lex_is_integer ());
471 /* Token matching functions. */
473 /* If TOK is the current token, skips it and returns nonzero.
474 Otherwise, returns zero. */
487 /* If the current token is the identifier S, skips it and returns
489 Otherwise, returns zero. */
491 lex_match_id (const char *s)
493 if (token == T_ID && lex_id_match (s, tokid))
502 /* If the current token is integer N, skips it and returns nonzero.
503 Otherwise, returns zero. */
505 lex_match_int (int x)
507 if (lex_is_integer () && lex_integer () == x)
516 /* Forced matches. */
518 /* If this token is identifier S, fetches the next token and returns
520 Otherwise, reports an error and returns zero. */
522 lex_force_match_id (const char *s)
524 if (token == T_ID && lex_id_match (s, tokid))
531 lex_error (_("expecting `%s'"), s);
536 /* If the current token is T, skips the token. Otherwise, reports an
537 error and returns from the current function with return value 0. */
539 lex_force_match (int t)
548 lex_error (_("expecting %s"), lex_token_name (t));
553 /* If this token is a string, does nothing and returns nonzero.
554 Otherwise, reports an error and returns zero. */
556 lex_force_string (void)
558 if (token == T_STRING)
562 lex_error (_("expecting string"));
567 /* If this token is an integer, does nothing and returns nonzero.
568 Otherwise, reports an error and returns zero. */
572 if (lex_is_integer ())
576 lex_error (_("expecting integer"));
581 /* If this token is a number, does nothing and returns nonzero.
582 Otherwise, reports an error and returns zero. */
586 if (lex_is_number ())
590 lex_error (_("expecting number"));
595 /* If this token is an identifier, does nothing and returns nonzero.
596 Otherwise, reports an error and returns zero. */
604 lex_error (_("expecting identifier"));
609 /* Comparing identifiers. */
611 /* Keywords match if one of the following is true: KW and TOK are
612 identical (barring differences in case), or TOK is at least 3
613 characters long and those characters are identical to KW. KW_LEN
614 is the length of KW, TOK_LEN is the length of TOK. */
616 lex_id_match_len (const char *kw, size_t kw_len,
617 const char *tok, size_t tok_len)
624 if (i == kw_len && i == tok_len)
626 else if (i == tok_len)
628 else if (i == kw_len)
630 else if (toupper ((unsigned char) kw[i])
631 != toupper ((unsigned char) tok[i]))
638 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
640 lex_id_match (const char *kw, const char *tok)
642 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
645 /* Returns the proper token type, either T_ID or a reserved keyword
646 enum, for ID[], which must contain LEN characters. */
648 lex_id_to_token (const char *id, size_t len)
652 if (len < 2 || len > 4)
655 for (kwp = keywords; *kwp; kwp++)
656 if (!strcasecmp (*kwp, id))
657 return T_FIRST_KEYWORD + (kwp - keywords);
662 /* Weird token functions. */
664 /* Returns the first character of the next token, except that if the
665 next token is not an identifier, the character returned will not be
666 a character that can begin an identifier. Specifically, the
667 hexstring lead-in X' causes lookahead() to return '. Note that an
668 alphanumeric return value doesn't guarantee an ID token, it could
669 also be a reserved-word token. */
671 lex_look_ahead (void)
683 while (isspace ((unsigned char) *prog))
690 else if (!lex_get_line ())
697 if ((toupper ((unsigned char) *prog) == 'X'
698 || toupper ((unsigned char) *prog) == 'B')
699 && (prog[1] == '\'' || prog[1] == '"'))
706 /* Makes the current token become the next token to be read; the
707 current token is set to T. */
715 /* Makes the current token become the next token to be read; the
716 current token is set to the identifier ID. */
718 lex_put_back_id (const char *id)
722 ds_replace (&tokstr, id);
723 strncpy (tokid, ds_c_str (&tokstr), SHORT_NAME_LEN);
724 tokid[SHORT_NAME_LEN] = 0;
727 /* Weird line processing functions. */
729 /* Returns the entire contents of the current line. */
731 lex_entire_line (void)
733 return ds_c_str (&getl_buf);
736 /* As lex_entire_line(), but only returns the part of the current line
737 that hasn't already been tokenized.
738 If END_DOT is non-null, stores nonzero into *END_DOT if the line
739 ends with a terminal dot, or zero if it doesn't. */
741 lex_rest_of_line (int *end_dot)
748 /* Causes the rest of the current input line to be ignored for
749 tokenization purposes. */
751 lex_discard_line (void)
753 prog = ds_end (&getl_buf);
757 /* Sets the current position in the current line to P, which must be
760 lex_set_prog (char *p)
765 /* Weird line reading functions. */
767 /* Read a line for use by the tokenizer. */
771 if (!getl_read_line ())
774 lex_preprocess_line ();
778 /* Preprocesses getl_buf by removing comments, stripping trailing
779 whitespace and the terminal dot, and removing leading indentors. */
781 lex_preprocess_line (void)
783 /* Strips comments. */
785 /* getl_buf iterator. */
788 /* Nonzero inside a comment. */
791 /* Nonzero inside a quoted string. */
794 /* Remove C-style comments begun by slash-star and terminated by
795 star-slash or newline. */
797 for (cp = ds_c_str (&getl_buf); *cp; )
799 /* If we're not commented out, toggle quoting. */
804 else if (*cp == '\'' || *cp == '"')
808 /* If we're not quoting, toggle commenting. */
811 if (cp[0] == '/' && cp[1] == '*')
818 else if (cp[0] == '*' && cp[1] == '/' && comment)
827 /* Check commenting. */
835 /* Strip trailing whitespace and terminal dot. */
837 size_t len = ds_length (&getl_buf);
838 char *s = ds_c_str (&getl_buf);
840 /* Strip trailing whitespace. */
841 while (len > 0 && isspace ((unsigned char) s[len - 1]))
844 /* Check for and remove terminal dot. */
845 if (len > 0 && s[len - 1] == get_endcmd() )
850 else if (len == 0 && get_nullline() )
856 ds_truncate (&getl_buf, len);
859 /* In batch mode, strip leading indentors and insert a terminal dot
861 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
863 char *s = ds_c_str (&getl_buf);
865 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
867 else if (s[0] && !isspace ((unsigned char) s[0]))
871 prog = ds_c_str (&getl_buf);
876 /* Returns the name of a token in a static buffer. */
878 lex_token_name (int token)
880 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
881 return keywords[token - T_FIRST_KEYWORD];
893 /* Returns an ASCII representation of the current token as a
894 malloc()'d string. */
896 lex_token_representation (void)
905 return xstrdup (ds_c_str (&tokstr));
913 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
914 if (!isprint ((unsigned char) *sp))
920 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
928 for (sp = ds_c_str (&tokstr); *sp; )
932 *dp++ = (unsigned char) *sp++;
935 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
937 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
938 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
948 token_rep = xmalloc (1);
953 return xstrdup ("**");
956 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
957 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
960 token_rep = xmalloc (2);
961 token_rep[0] = token;
970 /* Really weird functions. */
972 /* Most of the time, a `-' is a lead-in to a negative number. But
973 sometimes it's actually part of the syntax. If a dash can be part
974 of syntax then this function is called to rip it off of a
977 lex_negative_to_dash (void)
979 if (token == T_NEG_NUM)
983 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
989 /* We're not at eof any more. */
996 /* Skip a COMMENT command. */
998 lex_skip_comment (void)
1002 if (!lex_get_line ())
1009 if (put_token == '.')
1012 prog = ds_end (&getl_buf);
1018 /* Private functions. */
1020 /* Unexpected end of file. */
1022 unexpected_eof (void)
1024 msg (FE, _("Unexpected end of file."));
1027 /* When invoked, tokstr contains a string of binary, octal, or hex
1028 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1029 is converted to characters having the specified values. */
1031 convert_numeric_string_to_char_string (int type)
1033 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1034 static const int bases[] = {2, 8, 16};
1035 static const int chars_per_byte[] = {8, 3, 2};
1037 const char *const base_name = base_names[type];
1038 const int base = bases[type];
1039 const int cpb = chars_per_byte[type];
1040 const int nb = ds_length (&tokstr) / cpb;
1044 assert (type >= 0 && type <= 2);
1046 if (ds_length (&tokstr) % cpb)
1047 msg (SE, _("String of %s digits has %d characters, which is not a "
1049 gettext (base_name), ds_length (&tokstr), cpb);
1051 p = ds_c_str (&tokstr);
1052 for (i = 0; i < nb; i++)
1058 for (j = 0; j < cpb; j++, p++)
1062 if (*p >= '0' && *p <= '9')
1066 static const char alpha[] = "abcdef";
1067 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1076 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1078 value = value * base + v;
1081 ds_c_str (&tokstr)[i] = (unsigned char) value;
1084 ds_truncate (&tokstr, nb);
1087 /* Parses a string from the input buffer into tokstr. The input
1088 buffer pointer prog must point to the initial single or double
1089 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1090 binary, octal, or hexstring, respectively. Returns token type. */
1092 parse_string (int type)
1094 /* Accumulate the entire string, joining sections indicated by +
1098 /* Single or double quote. */
1101 /* Accumulate section. */
1104 /* Check end of line. */
1107 msg (SE, _("Unterminated string constant."));
1111 /* Double quote characters to embed them in strings. */
1120 ds_putc (&tokstr, *prog++);
1124 /* Skip whitespace after final quote mark. */
1129 while (isspace ((unsigned char) *prog))
1137 if (!lex_get_line ())
1141 /* Skip plus sign. */
1146 /* Skip whitespace after plus sign. */
1151 while (isspace ((unsigned char) *prog))
1159 if (!lex_get_line ())
1163 /* Ensure that a valid string follows. */
1164 if (*prog != '\'' && *prog != '"')
1166 msg (SE, "String expected following `+'.");
1171 /* We come here when we've finished concatenating all the string sections
1172 into one large string. */
1175 convert_numeric_string_to_char_string (type - 1);
1177 if (ds_length (&tokstr) > 255)
1179 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1180 ds_length (&tokstr));
1181 ds_truncate (&tokstr, 255);
1189 for (i = 0; i < ds_length (&tokstr); i++)
1190 if (ds_c_str (&tokstr)[i] == 0)
1194 msg (SE, _("Sorry, literal strings may not contain null "
1195 "characters. Replacing with spaces."));
1198 ds_c_str (&tokstr)[i] = ' ';
1206 /* Reads one token from the lexer and writes a textual representation
1207 on stdout for debugging purposes. */
1215 getl_location (&curfn, &curln);
1217 fprintf (stderr, "%s:%d\t", curfn, curln);
1223 fprintf (stderr, "ID\t%s\n", tokid);
1228 fprintf (stderr, "NUM\t%f\n", tokval);
1232 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1236 fprintf (stderr, "STOP\n");
1240 fprintf (stderr, "MISC\tEXP\"");
1244 fprintf (stderr, "MISC\tEOF\n");
1248 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1249 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1251 fprintf (stderr, "PUNCT\t%c\n", token);
1255 #endif /* DUMP_TOKENS */