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. */
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 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), 8);
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. */
140 /* If a token was pushed ahead, return it. */
155 /* Skip whitespace. */
161 while (isspace ((unsigned char) *prog))
175 else if (!lex_get_line ())
196 /* Actually parse the token. */
203 case '0': case '1': case '2': case '3': case '4':
204 case '5': case '6': case '7': case '8': case '9':
208 /* `-' can introduce a negative number, or it can be a
209 token by itself. If it is not followed by a digit or a
210 decimal point, it is definitely not a number.
211 Otherwise, it might be either, but most of the time we
212 want it as a number. When the syntax calls for a `-'
213 token, lex_negative_to_dash() must be used to break
214 negative numbers into two tokens. */
217 ds_putc (&tokstr, *prog++);
218 while (isspace ((unsigned char) *prog))
221 if (!isdigit ((unsigned char) *prog) && *prog != '.')
231 /* Parse the number, copying it into tokstr. */
232 while (isdigit ((unsigned char) *prog))
233 ds_putc (&tokstr, *prog++);
236 ds_putc (&tokstr, *prog++);
237 while (isdigit ((unsigned char) *prog))
238 ds_putc (&tokstr, *prog++);
240 if (*prog == 'e' || *prog == 'E')
242 ds_putc (&tokstr, *prog++);
243 if (*prog == '+' || *prog == '-')
244 ds_putc (&tokstr, *prog++);
245 while (isdigit ((unsigned char) *prog))
246 ds_putc (&tokstr, *prog++);
249 /* Parse as floating point. */
250 tokval = strtod (ds_c_str (&tokstr), &tail);
253 msg (SE, _("%s does not form a valid number."),
258 ds_putc (&tokstr, '0');
265 token = parse_string (0);
268 case '(': case ')': case ',': case '=': case '+': case '/':
288 else if (*prog == '>')
327 case 'a': case 'b': case 'c': case 'd': case 'e':
328 case 'f': case 'g': case 'h': case 'i': case 'j':
329 case 'k': case 'l': case 'm': case 'n': case 'o':
330 case 'p': case 'q': case 'r': case 's': case 't':
331 case 'u': case 'v': case 'w': case 'x': case 'y':
333 case 'A': case 'B': case 'C': case 'D': case 'E':
334 case 'F': case 'G': case 'H': case 'I': case 'J':
335 case 'K': case 'L': case 'M': case 'N': case 'O':
336 case 'P': case 'Q': case 'R': case 'S': case 'T':
337 case 'U': case 'V': case 'W': case 'X': case 'Y':
339 case '#': case '$': case '@':
340 /* Strings can be specified in binary, octal, or hex using
341 this special syntax. */
342 if (prog[1] == '\'' || prog[1] == '"')
344 static const char special[3] = "box";
347 p = strchr (special, tolower ((unsigned char) *prog));
351 token = parse_string (p - special + 1);
356 /* Copy id to tokstr. */
357 ds_putc (&tokstr, toupper ((unsigned char) *prog++));
358 while (CHAR_IS_IDN (*prog))
359 ds_putc (&tokstr, toupper ((unsigned char) *prog++));
361 /* Copy tokstr to tokid, truncating it to 8 characters. */
362 strncpy (tokid, ds_c_str (&tokstr), 8);
365 token = lex_id_to_token (ds_c_str (&tokstr), ds_length (&tokstr));
369 if (isgraph ((unsigned char) *prog))
370 msg (SE, _("Bad character in input: `%c'."), *prog++);
372 msg (SE, _("Bad character in input: `\\%o'."), *prog++);
384 /* Prints a syntax error message containing the current token and
385 given message MESSAGE (if non-null). */
387 lex_error (const char *message, ...)
391 token_rep = lex_token_representation ();
392 if (token_rep[0] == 0)
393 msg (SE, _("Syntax error at end of file."));
399 va_start (args, message);
400 vsnprintf (buf, 1024, message, args);
403 msg (SE, _("Syntax error %s at `%s'."), buf, token_rep);
406 msg (SE, _("Syntax error at `%s'."), token_rep);
411 /* Checks that we're at end of command.
412 If so, returns a successful command completion code.
413 If not, flags a syntax error and returns an error command
416 lex_end_of_command (void)
420 lex_error (_("expecting end of command"));
421 return CMD_TRAILING_GARBAGE;
427 /* Token testing functions. */
429 /* Returns true if the current token is a number. */
433 return token == T_POS_NUM || token == T_NEG_NUM;
436 /* Returns the value of the current token, which must be a
437 floating point number. */
441 assert (lex_is_number ());
445 /* Returns true iff the current token is an integer. */
447 lex_is_integer (void)
449 return (lex_is_number ()
450 && tokval != NOT_LONG
451 && tokval >= LONG_MIN
452 && tokval <= LONG_MAX
453 && floor (tokval) == tokval);
456 /* Returns the value of the current token, which must be an
461 assert (lex_is_integer ());
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_is_integer () && 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_is_integer ())
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. */
580 if (lex_is_number ())
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 /* Returns the proper token type, either T_ID or a reserved keyword
640 enum, for ID[], which must contain LEN characters. */
642 lex_id_to_token (const char *id, size_t len)
646 if (len < 2 || len > 4)
649 for (kwp = keywords; *kwp; kwp++)
650 if (!strcasecmp (*kwp, id))
651 return T_FIRST_KEYWORD + (kwp - keywords);
656 /* Weird token functions. */
658 /* Returns the first character of the next token, except that if the
659 next token is not an identifier, the character returned will not be
660 a character that can begin an identifier. Specifically, the
661 hexstring lead-in X' causes lookahead() to return '. Note that an
662 alphanumeric return value doesn't guarantee an ID token, it could
663 also be a reserved-word token. */
665 lex_look_ahead (void)
677 while (isspace ((unsigned char) *prog))
684 else if (!lex_get_line ())
691 if ((toupper ((unsigned char) *prog) == 'X'
692 || toupper ((unsigned char) *prog) == 'B')
693 && (prog[1] == '\'' || prog[1] == '"'))
700 /* Makes the current token become the next token to be read; the
701 current token is set to T. */
709 /* Makes the current token become the next token to be read; the
710 current token is set to the identifier ID. */
712 lex_put_back_id (const char *id)
716 ds_replace (&tokstr, id);
717 strncpy (tokid, ds_c_str (&tokstr), 8);
721 /* Weird line processing functions. */
723 /* Returns the entire contents of the current line. */
725 lex_entire_line (void)
727 return ds_c_str (&getl_buf);
730 /* As lex_entire_line(), but only returns the part of the current line
731 that hasn't already been tokenized.
732 If END_DOT is non-null, stores nonzero into *END_DOT if the line
733 ends with a terminal dot, or zero if it doesn't. */
735 lex_rest_of_line (int *end_dot)
742 /* Causes the rest of the current input line to be ignored for
743 tokenization purposes. */
745 lex_discard_line (void)
747 prog = ds_end (&getl_buf);
751 /* Sets the current position in the current line to P, which must be
754 lex_set_prog (char *p)
759 /* Weird line reading functions. */
761 /* Read a line for use by the tokenizer. */
765 if (!getl_read_line ())
768 lex_preprocess_line ();
772 /* Preprocesses getl_buf by removing comments, stripping trailing
773 whitespace and the terminal dot, and removing leading indentors. */
775 lex_preprocess_line (void)
777 /* Strips comments. */
779 /* getl_buf iterator. */
782 /* Nonzero inside a comment. */
785 /* Nonzero inside a quoted string. */
788 /* Remove C-style comments begun by slash-star and terminated by
789 star-slash or newline. */
791 for (cp = ds_c_str (&getl_buf); *cp; )
793 /* If we're not commented out, toggle quoting. */
798 else if (*cp == '\'' || *cp == '"')
802 /* If we're not quoting, toggle commenting. */
805 if (cp[0] == '/' && cp[1] == '*')
812 else if (cp[0] == '*' && cp[1] == '/' && comment)
821 /* Check commenting. */
829 /* Strip trailing whitespace and terminal dot. */
831 size_t len = ds_length (&getl_buf);
832 char *s = ds_c_str (&getl_buf);
834 /* Strip trailing whitespace. */
835 while (len > 0 && isspace ((unsigned char) s[len - 1]))
838 /* Check for and remove terminal dot. */
839 if (len > 0 && s[len - 1] == get_endcmd() )
844 else if (len == 0 && get_nullline() )
850 ds_truncate (&getl_buf, len);
853 /* In batch mode, strip leading indentors and insert a terminal dot
855 if (getl_interactive != 2 && getl_mode == GETL_MODE_BATCH)
857 char *s = ds_c_str (&getl_buf);
859 if (s[0] == '+' || s[0] == '-' || s[0] == '.')
861 else if (s[0] && !isspace ((unsigned char) s[0]))
865 prog = ds_c_str (&getl_buf);
870 /* Returns the name of a token in a static buffer. */
872 lex_token_name (int token)
874 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
875 return keywords[token - T_FIRST_KEYWORD];
887 /* Returns an ASCII representation of the current token as a
888 malloc()'d string. */
890 lex_token_representation (void)
899 return xstrdup (ds_c_str (&tokstr));
907 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
908 if (!isprint ((unsigned char) *sp))
914 token_rep = xmalloc (2 + ds_length (&tokstr) * 2 + 1 + 1);
922 for (sp = ds_c_str (&tokstr); *sp; )
926 *dp++ = (unsigned char) *sp++;
929 for (sp = ds_c_str (&tokstr); sp < ds_end (&tokstr); sp++)
931 *dp++ = (((unsigned char) *sp) >> 4)["0123456789ABCDEF"];
932 *dp++ = (((unsigned char) *sp) & 15)["0123456789ABCDEF"];
942 token_rep = xmalloc (1);
947 return xstrdup ("**");
950 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
951 return xstrdup (keywords [token - T_FIRST_KEYWORD]);
954 token_rep = xmalloc (2);
955 token_rep[0] = token;
964 /* Really weird functions. */
966 /* Most of the time, a `-' is a lead-in to a negative number. But
967 sometimes it's actually part of the syntax. If a dash can be part
968 of syntax then this function is called to rip it off of a
971 lex_negative_to_dash (void)
973 if (token == T_NEG_NUM)
977 ds_replace (&tokstr, ds_c_str (&tokstr) + 1);
983 /* We're not at eof any more. */
990 /* Skip a COMMENT command. */
992 lex_skip_comment (void)
996 if (!lex_get_line ())
1003 if (put_token == '.')
1006 prog = ds_end (&getl_buf);
1012 /* Private functions. */
1014 /* Unexpected end of file. */
1016 unexpected_eof (void)
1018 msg (FE, _("Unexpected end of file."));
1021 /* When invoked, tokstr contains a string of binary, octal, or hex
1022 digits, for values of TYPE of 0, 1, or 2, respectively. The string
1023 is converted to characters having the specified values. */
1025 convert_numeric_string_to_char_string (int type)
1027 static const char *base_names[] = {N_("binary"), N_("octal"), N_("hex")};
1028 static const int bases[] = {2, 8, 16};
1029 static const int chars_per_byte[] = {8, 3, 2};
1031 const char *const base_name = base_names[type];
1032 const int base = bases[type];
1033 const int cpb = chars_per_byte[type];
1034 const int nb = ds_length (&tokstr) / cpb;
1038 assert (type >= 0 && type <= 2);
1040 if (ds_length (&tokstr) % cpb)
1041 msg (SE, _("String of %s digits has %d characters, which is not a "
1043 gettext (base_name), ds_length (&tokstr), cpb);
1045 p = ds_c_str (&tokstr);
1046 for (i = 0; i < nb; i++)
1052 for (j = 0; j < cpb; j++, p++)
1056 if (*p >= '0' && *p <= '9')
1060 static const char alpha[] = "abcdef";
1061 const char *q = strchr (alpha, tolower ((unsigned char) *p));
1070 msg (SE, _("`%c' is not a valid %s digit."), *p, base_name);
1072 value = value * base + v;
1075 ds_c_str (&tokstr)[i] = (unsigned char) value;
1078 ds_truncate (&tokstr, nb);
1081 /* Parses a string from the input buffer into tokstr. The input
1082 buffer pointer prog must point to the initial single or double
1083 quote. TYPE is 0 if it is an ordinary string, or 1, 2, or 3 for a
1084 binary, octal, or hexstring, respectively. Returns token type. */
1086 parse_string (int type)
1088 /* Accumulate the entire string, joining sections indicated by +
1092 /* Single or double quote. */
1095 /* Accumulate section. */
1098 /* Check end of line. */
1101 msg (SE, _("Unterminated string constant."));
1105 /* Double quote characters to embed them in strings. */
1114 ds_putc (&tokstr, *prog++);
1118 /* Skip whitespace after final quote mark. */
1123 while (isspace ((unsigned char) *prog))
1131 if (!lex_get_line ())
1135 /* Skip plus sign. */
1140 /* Skip whitespace after plus sign. */
1145 while (isspace ((unsigned char) *prog))
1153 if (!lex_get_line ())
1157 /* Ensure that a valid string follows. */
1158 if (*prog != '\'' && *prog != '"')
1160 msg (SE, "String expected following `+'.");
1165 /* We come here when we've finished concatenating all the string sections
1166 into one large string. */
1169 convert_numeric_string_to_char_string (type - 1);
1171 if (ds_length (&tokstr) > 255)
1173 msg (SE, _("String exceeds 255 characters in length (%d characters)."),
1174 ds_length (&tokstr));
1175 ds_truncate (&tokstr, 255);
1183 for (i = 0; i < ds_length (&tokstr); i++)
1184 if (ds_c_str (&tokstr)[i] == 0)
1188 msg (SE, _("Sorry, literal strings may not contain null "
1189 "characters. Replacing with spaces."));
1192 ds_c_str (&tokstr)[i] = ' ';
1200 /* Reads one token from the lexer and writes a textual representation
1201 on stdout for debugging purposes. */
1209 getl_location (&curfn, &curln);
1211 fprintf (stderr, "%s:%d\t", curfn, curln);
1217 fprintf (stderr, "ID\t%s\n", tokid);
1222 fprintf (stderr, "NUM\t%f\n", tokval);
1226 fprintf (stderr, "STRING\t\"%s\"\n", ds_c_str (&tokstr));
1230 fprintf (stderr, "STOP\n");
1234 fprintf (stderr, "MISC\tEXP\"");
1238 fprintf (stderr, "MISC\tEOF\n");
1242 if (token >= T_FIRST_KEYWORD && token <= T_LAST_KEYWORD)
1243 fprintf (stderr, "KEYWORD\t%s\n", lex_token_name (token));
1245 fprintf (stderr, "PUNCT\t%c\n", token);
1249 #endif /* DUMP_TOKENS */