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
38 #define _(msgid) gettext (msgid)
39 #define N_(msgid) msgid
46 /* Global variables. */
51 /* T_POS_NUM, T_NEG_NUM: the token's value. */
54 /* T_ID: the identifier. */
55 char tokid[LONG_NAME_LEN + 1];
57 /* T_ID, T_STRING: token string value.
58 For T_ID, this is not truncated as is tokid. */
61 /* Static variables. */
63 /* Table of keywords. */
64 static const char *keywords[T_N_KEYWORDS + 1] =
67 "EQ", "GE", "GT", "LE", "LT", "NE",
68 "ALL", "BY", "TO", "WITH",
72 /* Pointer to next token in getl_buf. */
75 /* Nonzero only if this line ends with a terminal dot. */
78 /* Nonzero only if the last token returned was T_STOP. */
81 /* If nonzero, next token returned by lex_get().
82 Used only in exceptional circumstances. */
84 static struct string put_tokstr;
85 static double put_tokval;
87 static void unexpected_eof (void);
88 static void convert_numeric_string_to_char_string (int type);
89 static int parse_string (int type);
92 static void dump_token (void);
97 /* Initializes the lexer. */
101 ds_init (&put_tokstr, 64);
102 if (!lex_get_line ())
109 ds_destroy(&put_tokstr);
113 /* Common functions. */
115 /* Copies put_token, put_tokstr, put_tokval into token, tokstr,
116 tokval, respectively, and sets tokid appropriately. */
120 assert (put_token != 0);
122 ds_replace (&tokstr, ds_c_str (&put_tokstr));
123 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
128 /* Copies token, tokstr, tokval into put_token, put_tokstr,
129 put_tokval respectively. */
134 ds_replace (&put_tokstr, ds_c_str (&tokstr));
138 /* Parses a single token, setting appropriate global variables to
139 indicate the token's attributes. */
143 /* If a token was pushed ahead, return it. */
158 /* Skip whitespace. */
164 while (isspace ((unsigned char) *prog))
178 else if (!lex_get_line ())
199 /* Actually parse the token. */
206 case '0': case '1': case '2': case '3': case '4':
207 case '5': case '6': case '7': case '8': case '9':
211 /* `-' can introduce a negative number, or it can be a
212 token by itself. If it is not followed by a digit or a
213 decimal point, it is definitely not a number.
214 Otherwise, it might be either, but most of the time we
215 want it as a number. When the syntax calls for a `-'
216 token, lex_negative_to_dash() must be used to break
217 negative numbers into two tokens. */
220 ds_putc (&tokstr, *prog++);
221 while (isspace ((unsigned char) *prog))
224 if (!isdigit ((unsigned char) *prog) && *prog != '.')
234 /* Parse the number, copying it into tokstr. */
235 while (isdigit ((unsigned char) *prog))
236 ds_putc (&tokstr, *prog++);
239 ds_putc (&tokstr, *prog++);
240 while (isdigit ((unsigned char) *prog))
241 ds_putc (&tokstr, *prog++);
243 if (*prog == 'e' || *prog == 'E')
245 ds_putc (&tokstr, *prog++);
246 if (*prog == '+' || *prog == '-')
247 ds_putc (&tokstr, *prog++);
248 while (isdigit ((unsigned char) *prog))
249 ds_putc (&tokstr, *prog++);
252 /* Parse as floating point. */
253 tokval = strtod (ds_c_str (&tokstr), &tail);
256 msg (SE, _("%s does not form a valid number."),
261 ds_putc (&tokstr, '0');
268 token = parse_string (0);
271 case '(': case ')': case ',': case '=': case '+': case '/':
291 else if (*prog == '>')
330 case 'a': case 'b': case 'c': case 'd': case 'e':
331 case 'f': case 'g': case 'h': case 'i': case 'j':
332 case 'k': case 'l': case 'm': case 'n': case 'o':
333 case 'p': case 'q': case 'r': case 's': case 't':
334 case 'u': case 'v': case 'w': case 'x': case 'y':
336 case 'A': case 'B': case 'C': case 'D': case 'E':
337 case 'F': case 'G': case 'H': case 'I': case 'J':
338 case 'K': case 'L': case 'M': case 'N': case 'O':
339 case 'P': case 'Q': case 'R': case 'S': case 'T':
340 case 'U': case 'V': case 'W': case 'X': case 'Y':
342 case '#': case '$': case '@':
343 /* Strings can be specified in binary, octal, or hex using
344 this special syntax. */
345 if (prog[1] == '\'' || prog[1] == '"')
347 static const char special[3] = "box";
350 p = strchr (special, tolower ((unsigned char) *prog));
354 token = parse_string (p - special + 1);
359 /* Copy id to tokstr. */
360 ds_putc (&tokstr, *prog++);
361 while (CHAR_IS_IDN (*prog))
362 ds_putc (&tokstr, *prog++);
364 /* Copy tokstr to tokid, possibly truncating it.*/
365 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
367 /* Determine token type. */
368 token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
372 if (isgraph ((unsigned char) *prog))
373 msg (SE, _("Bad character in input: `%c'."), *prog++);
375 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
387 /* Prints a syntax error message containing the current token and
388 given message MESSAGE (if non-null). */
390 lex_error (const char *message, ...)
395 token_rep = lex_token_representation ();
397 strcpy (where, "end of file");
398 else if (token == '.')
399 strcpy (where, "end of command");
401 snprintf (where, sizeof where, "`%s'", token_rep);
409 va_start (args, message);
410 vsnprintf (buf, 1024, message, args);
413 msg (SE, _("Syntax error %s at %s."), buf, where);
416 msg (SE, _("Syntax error at %s."), where);
419 /* Checks that we're at end of command.
420 If so, returns a successful command completion code.
421 If not, flags a syntax error and returns an error command
424 lex_end_of_command (void)
428 lex_error (_("expecting end of command"));
429 return CMD_TRAILING_GARBAGE;
435 /* Token testing functions. */
437 /* Returns true if the current token is a number. */
441 return token == T_POS_NUM || token == T_NEG_NUM;
444 /* Returns the value of the current token, which must be a
445 floating point number. */
449 assert (lex_is_number ());
453 /* Returns true iff the current token is an integer. */
455 lex_is_integer (void)
457 return (lex_is_number ()
458 && tokval != NOT_LONG
459 && tokval >= LONG_MIN
460 && tokval <= LONG_MAX
461 && floor (tokval) == tokval);
464 /* Returns the value of the current token, which must be an
469 assert (lex_is_integer ());
473 /* Token matching functions. */
475 /* If TOK is the current token, skips it and returns nonzero.
476 Otherwise, returns zero. */
489 /* If the current token is the identifier S, skips it and returns
490 nonzero. The identifier may be abbreviated to its first three
492 Otherwise, returns zero. */
494 lex_match_id (const char *s)
496 if (token == T_ID && lex_id_match (s, tokid))
505 /* If the current token is integer N, skips it and returns nonzero.
506 Otherwise, returns zero. */
508 lex_match_int (int x)
510 if (lex_is_integer () && lex_integer () == x)
519 /* Forced matches. */
521 /* If this token is identifier S, fetches the next token and returns
523 Otherwise, reports an error and returns zero. */
525 lex_force_match_id (const char *s)
527 if (token == T_ID && lex_id_match (s, tokid))
534 lex_error (_("expecting `%s'"), s);
539 /* If the current token is T, skips the token. Otherwise, reports an
540 error and returns from the current function with return value 0. */
542 lex_force_match (int t)
551 lex_error (_("expecting `%s'"), lex_token_name (t));
556 /* If this token is a string, does nothing and returns nonzero.
557 Otherwise, reports an error and returns zero. */
559 lex_force_string (void)
561 if (token == T_STRING)
565 lex_error (_("expecting string"));
570 /* If this token is an integer, does nothing and returns nonzero.
571 Otherwise, reports an error and returns zero. */
575 if (lex_is_integer ())
579 lex_error (_("expecting integer"));
584 /* If this token is a number, does nothing and returns nonzero.
585 Otherwise, reports an error and returns zero. */
589 if (lex_is_number ())
593 lex_error (_("expecting number"));
598 /* If this token is an identifier, does nothing and returns nonzero.
599 Otherwise, reports an error and returns zero. */
607 lex_error (_("expecting identifier"));
612 /* Comparing identifiers. */
614 /* Keywords match if one of the following is true: KW and TOK are
615 identical (except for differences in case), or TOK is at least 3
616 characters long and those characters are identical to KW. KW_LEN
617 is the length of KW, TOK_LEN is the length of TOK. */
619 lex_id_match_len (const char *kw, size_t kw_len,
620 const char *tok, size_t tok_len)
627 if (i == kw_len && i == tok_len)
629 else if (i == tok_len)
631 else if (i == kw_len)
633 else if (toupper ((unsigned char) kw[i])
634 != toupper ((unsigned char) tok[i]))
641 /* Same as lex_id_match_len() minus the need to pass in the lengths. */
643 lex_id_match (const char *kw, const char *tok)
645 return lex_id_match_len (kw, strlen (kw), tok, strlen (tok));
648 /* Returns the proper token type, either T_ID or a reserved keyword
649 enum, for ID[], which must contain LEN characters. */
651 lex_id_to_token (const char *id, size_t len)
655 if (len < 2 || len > 4)
658 for (kwp = keywords; *kwp; kwp++)
659 if (!strcasecmp (*kwp, id))
660 return T_FIRST_KEYWORD + (kwp - keywords);
665 /* Weird token functions. */
667 /* Returns the first character of the next token, except that if the
668 next token is not an identifier, the character returned will not be
669 a character that can begin an identifier. Specifically, the
670 hexstring lead-in X' causes lookahead() to return '. Note that an
671 alphanumeric return value doesn't guarantee an ID token, it could
672 also be a reserved-word token. */
674 lex_look_ahead (void)
686 while (isspace ((unsigned char) *prog))
693 else if (!lex_get_line ())
700 if ((toupper ((unsigned char) *prog) == 'X'
701 || toupper ((unsigned char) *prog) == 'B')
702 && (prog[1] == '\'' || prog[1] == '"'))
709 /* Makes the current token become the next token to be read; the
710 current token is set to T. */
718 /* Makes the current token become the next token to be read; the
719 current token is set to the identifier ID. */
721 lex_put_back_id (const char *id)
723 assert (lex_id_to_token (id, strlen (id)) == T_ID);
726 ds_replace (&tokstr, id);
727 str_copy_trunc (tokid, sizeof tokid, ds_c_str (&tokstr));
730 /* Weird line processing functions. */
732 /* Returns the entire contents of the current line. */
734 lex_entire_line (void)
736 return ds_c_str (&getl_buf);
739 /* As lex_entire_line(), but only returns the part of the current line
740 that hasn't already been tokenized.
741 If END_DOT is non-null, stores nonzero into *END_DOT if the line
742 ends with a terminal dot, or zero if it doesn't. */
744 lex_rest_of_line (int *end_dot)
751 /* Causes the rest of the current input line to be ignored for
752 tokenization purposes. */
754 lex_discard_line (void)
756 prog = ds_end (&getl_buf);
760 /* Sets the current position in the current line to P, which must be
763 lex_set_prog (char *p)
768 /* Weird line reading functions. */
770 /* Read a line for use by the tokenizer. */
774 if (!getl_read_line ())
777 lex_preprocess_line ();
781 /* Preprocesses getl_buf by removing comments, stripping trailing
782 whitespace and the terminal dot, and removing leading indentors. */
784 lex_preprocess_line (void)
786 /* Strips comments. */
788 /* getl_buf iterator. */
791 /* Nonzero inside a comment. */
794 /* Nonzero inside a quoted string. */
797 /* Remove C-style comments begun by slash-star and terminated by
798 star-slash or newline. */
800 for (cp = ds_c_str (&getl_buf); *cp; )
802 /* If we're not commented out, toggle quoting. */
807 else if (*cp == '\'' || *cp == '"')
811 /* If we're not quoting, toggle commenting. */
814 if (cp[0] == '/' && cp[1] == '*')
821 else if (cp[0] == '*' && cp[1] == '/' && comment)
830 /* Check commenting. */
838 /* Strip trailing whitespace and terminal dot. */
840 size_t len = ds_length (&getl_buf);
841 char *s = ds_c_str (&getl_buf);
843 /* Strip trailing whitespace. */
844 while (len > 0 && isspace ((unsigned char) s[len - 1]))
847 /* Check for and remove terminal dot. */
848 if (len > 0 && s[len - 1] == get_endcmd() )
853 else if (len == 0 && get_nullline() )
859 ds_truncate (&getl_buf, len);
862 /* In batch mode, strip leading indentors and insert a terminal dot
864 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
866 char *s = ds_c_str (&getl_buf);
868 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
870 else if (s[0] && !isspace ((unsigned char) s[0]))
874 prog = ds_c_str (&getl_buf);
879 /* Returns the name of a token in a static buffer. */
881 lex_token_name (int token)
883 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
884 return keywords[token - T_FIRST_KEYWORD];
896 /* Returns an ASCII representation of the current token as a
897 malloc()'d string. */
899 lex_token_representation (void)
908 return xstrdup (ds_c_str (&tokstr));
916 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
917 if (!isprint ((unsigned char) *sp))
923 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
931 for (sp = ds_c_str (&tokstr); *sp; )
935 *dp++ = (unsigned char) *sp++;
938 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
940 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
941 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
951 token_rep = xmalloc (1);
956 return xstrdup ("**");
959 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
960 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
963 token_rep = xmalloc (2);
964 token_rep[0] = token;
973 /* Really weird functions. */
975 /* Most of the time, a `-' is a lead-in to a negative number. But
976 sometimes it's actually part of the syntax. If a dash can be part
977 of syntax then this function is called to rip it off of a
980 lex_negative_to_dash (void)
982 if (token == T_NEG_NUM)
986 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
992 /* We're not at eof any more. */
999 /* Skip a COMMENT command. */
1001 lex_skip_comment (void)
1005 if (!lex_get_line ())
1012 if (put_token == '.')
1015 prog = ds_end (&getl_buf);
1021 /* Private functions. */
1023 /* Unexpected end of file. */
1025 unexpected_eof (void)
1027 msg (FE, _("Unexpected end of file."));
1030 /* When invoked, tokstr contains a string of binary, octal, or hex
1031 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1032 is converted to characters having the specified values. */
1034 convert_numeric_string_to_char_string (int type)
1036 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1037 static const int bases[] = {2, 8, 16};
1038 static const int chars_per_byte[] = {8, 3, 2};
1040 const char *const base_name = base_names[type];
1041 const int base = bases[type];
1042 const int cpb = chars_per_byte[type];
1043 const int nb = ds_length (&tokstr) / cpb;
1047 assert (type >= 0 && type <= 2);
1049 if (ds_length (&tokstr) % cpb)
1050 msg (SE, _("String of %s digits has %d characters, which is not a "
1052 gettext (base_name), ds_length (&tokstr), cpb);
1054 p = ds_c_str (&tokstr);
1055 for (i = 0; i < nb; i++)
1061 for (j = 0; j < cpb; j++, p++)
1065 if (*p >= '0' && *p <= '9')
1069 static const char alpha[] = "abcdef";
1070 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1079 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1081 value = value * base + v;
1084 ds_c_str (&tokstr)[i] = (unsigned char) value;
1087 ds_truncate (&tokstr, nb);
1090 /* Parses a string from the input buffer into tokstr. The input
1091 buffer pointer prog must point to the initial single or double
1092 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1093 binary, octal, or hexstring, respectively. Returns token type. */
1095 parse_string (int type)
1097 /* Accumulate the entire string, joining sections indicated by +
1101 /* Single or double quote. */
1104 /* Accumulate section. */
1107 /* Check end of line. */
1110 msg (SE, _("Unterminated string constant."));
1114 /* Double quote characters to embed them in strings. */
1123 ds_putc (&tokstr, *prog++);
1127 /* Skip whitespace after final quote mark. */
1132 while (isspace ((unsigned char) *prog))
1140 if (!lex_get_line ())
1144 /* Skip plus sign. */
1149 /* Skip whitespace after plus sign. */
1154 while (isspace ((unsigned char) *prog))
1162 if (!lex_get_line ())
1166 /* Ensure that a valid string follows. */
1167 if (*prog != '\'' && *prog != '"')
1169 msg (SE, "String expected following `+'.");
1174 /* We come here when we've finished concatenating all the string sections
1175 into one large string. */
1178 convert_numeric_string_to_char_string (type - 1);
1180 if (ds_length (&tokstr) > 255)
1182 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1183 ds_length (&tokstr));
1184 ds_truncate (&tokstr, 255);
1192 for (i = 0; i < ds_length (&tokstr); i++)
1193 if (ds_c_str (&tokstr)[i] == 0)
1197 msg (SE, _("Sorry, literal strings may not contain null "
1198 "characters. Replacing with spaces."));
1201 ds_c_str (&tokstr)[i] = ' ';
1209 /* Reads one token from the lexer and writes a textual representation
1210 on stdout for debugging purposes. */
1218 getl_location (&curfn, &curln);
1220 fprintf (stderr, "%s:%d\t", curfn, curln);
1226 fprintf (stderr, "ID\t%s\n", tokid);
1231 fprintf (stderr, "NUM\t%f\n", tokval);
1235 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1239 fprintf (stderr, "STOP\n");
1243 fprintf (stderr, "MISC\tEXP\"");
1247 fprintf (stderr, "MISC\tEOF\n");
1251 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1252 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1254 fprintf (stderr, "PUNCT\t%c\n", token);
1258 #endif /* DUMP_TOKENS */