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
21 #include "dictionary.h"
28 #include "algorithm.h"
41 /* Recursive descent parser in order of increasing precedence. */
42 typedef enum expr_type parse_recursively_func (union any_node **);
43 static parse_recursively_func parse_or, parse_and, parse_not;
44 static parse_recursively_func parse_rel, parse_add, parse_mul;
45 static parse_recursively_func parse_neg, parse_exp;
46 static parse_recursively_func parse_primary, parse_function;
48 /* Utility functions. */
49 static const char *expr_type_name (enum expr_type type);
50 static const char *var_type_name (int var_type);
51 static void make_bool (union any_node **n);
52 static union any_node *allocate_nonterminal (int op, union any_node *n);
53 static union any_node *allocate_binary_nonterminal (int op, union any_node *,
55 static union any_node *allocate_num_con (double value);
56 static union any_node *allocate_str_con (const char *string, size_t length);
57 static union any_node *allocate_var_node (int type, struct variable *);
58 static int type_check (union any_node **n,
59 enum expr_type actual_type,
60 enum expr_type expected_type);
62 static algo_compare_func compare_functions;
63 static void init_func_tab (void);
65 /* Public functions. */
68 expr_free (struct expression *e)
78 pool_destroy (e->pool);
83 expr_parse (enum expr_type expected_type)
87 enum expr_type actual_type;
88 int optimize = (expected_type & EXPR_NO_OPTIMIZE) == 0;
90 expected_type &= ~EXPR_NO_OPTIMIZE;
92 /* Make sure the table of functions is initialized. */
95 /* Parse the expression. */
96 actual_type = parse_or (&n);
97 if (actual_type == EXPR_ERROR)
100 /* Enforce type rules. */
101 if (!type_check (&n, actual_type, expected_type))
107 /* Optimize the expression as best we can. */
109 optimize_expression (&n);
111 /* Dump the tree-based expression to a postfix representation for
112 best evaluation speed, and destroy the tree. */
113 e = xmalloc (sizeof *e);
114 e->type = actual_type;
115 dump_expression (n, e);
121 /* Returns the type of EXPR. */
123 expr_get_type (const struct expression *expr)
125 assert (expr != NULL);
130 type_check (union any_node **n, enum expr_type actual_type, enum expr_type expected_type)
132 switch (expected_type)
136 if (actual_type == EXPR_STRING)
138 msg (SE, _("Type mismatch: expression has string type, "
139 "but a numeric value is required here."));
142 if (actual_type == EXPR_NUMERIC && expected_type == EXPR_BOOLEAN)
143 *n = allocate_nonterminal (OP_NUM_TO_BOOL, *n);
147 if (actual_type != EXPR_STRING)
149 msg (SE, _("Type mismatch: expression has numeric type, "
150 "but a string value is required here."));
165 /* Recursive-descent expression parser. */
167 /* Coerces *NODE, of type ACTUAL_TYPE, to type REQUIRED_TYPE, and
168 returns success. If ACTUAL_TYPE cannot be coerced to the
169 desired type then we issue an error message about operator
170 OPERATOR_NAME and free *NODE. */
172 type_coercion (enum expr_type actual_type, enum expr_type required_type,
173 union any_node **node,
174 const char *operator_name)
176 assert (required_type == EXPR_NUMERIC
177 || required_type == EXPR_BOOLEAN
178 || required_type == EXPR_STRING);
180 if (actual_type == required_type)
185 else if (actual_type == EXPR_ERROR)
187 /* Error already reported. */
191 else if (actual_type == EXPR_BOOLEAN && required_type == EXPR_NUMERIC)
193 /* Boolean -> numeric: nothing to do. */
196 else if (actual_type == EXPR_NUMERIC && required_type == EXPR_BOOLEAN)
198 /* Numeric -> Boolean: insert conversion. */
204 /* We want a string and got a number/Boolean, or vice versa. */
205 assert ((actual_type == EXPR_STRING) != (required_type == EXPR_STRING));
207 if (required_type == EXPR_STRING)
208 msg (SE, _("Type mismatch: operands of %s operator must be strings."),
211 msg (SE, _("Type mismatch: operands of %s operator must be numeric."),
222 int token; /* Operator token. */
223 int type; /* Operator node type. */
224 const char *name; /* Operator name. */
227 /* Attempts to match the current token against the tokens for the
228 OP_CNT operators in OPS[]. If successful, returns nonzero
229 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
230 On failure, returns zero and, if OPERATOR is non-null, sets
231 *OPERATOR to a null pointer. */
233 match_operator (const struct operator ops[], size_t op_cnt,
234 const struct operator **operator)
236 const struct operator *op;
238 for (op = ops; op < ops + op_cnt; op++)
240 if (op->token == '-')
241 lex_negative_to_dash ();
242 if (lex_match (op->token))
244 if (operator != NULL)
249 if (operator != NULL)
254 /* Parses a chain of left-associative operator/operand pairs.
255 The operators' operands uniformly must be type REQUIRED_TYPE.
256 There are OP_CNT operators, specified in OPS[]. The next
257 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
258 is non-null, then it will be issued as a warning if more than
259 one operator/operand pair is parsed. */
260 static enum expr_type
261 parse_binary_operators (union any_node **node,
262 enum expr_type actual_type,
263 enum expr_type required_type,
264 enum expr_type result_type,
265 const struct operator ops[], size_t op_cnt,
266 parse_recursively_func *parse_next_level,
267 const char *chain_warning)
270 const struct operator *operator;
272 if (actual_type == EXPR_ERROR)
275 for (op_count = 0; match_operator (ops, op_cnt, &operator); op_count++)
279 /* Convert the left-hand side to type REQUIRED_TYPE. */
280 if (!type_coercion (actual_type, required_type, node, operator->name))
283 /* Parse the right-hand side and coerce to type
285 if (!type_coercion (parse_next_level (&rhs), required_type,
286 &rhs, operator->name))
292 *node = allocate_binary_nonterminal (operator->type, *node, rhs);
294 /* The result is of type RESULT_TYPE. */
295 actual_type = result_type;
298 if (op_count > 1 && chain_warning != NULL)
299 msg (SW, chain_warning);
304 static enum expr_type
305 parse_inverting_unary_operator (union any_node **node,
306 enum expr_type required_type,
307 const struct operator *operator,
308 parse_recursively_func *parse_next_level)
313 while (match_operator (operator, 1, NULL))
316 return parse_next_level (node);
318 if (!type_coercion (parse_next_level (node), required_type,
319 node, operator->name))
321 if (op_count % 2 != 0)
322 *node = allocate_nonterminal (operator->type, *node);
323 return required_type;
326 /* Parses the OR level. */
327 static enum expr_type
328 parse_or (union any_node **n)
330 static const struct operator ops[] =
332 { T_OR, OP_OR, "logical disjunction (\"OR\")" },
335 return parse_binary_operators (n, parse_and (n), EXPR_BOOLEAN, EXPR_BOOLEAN,
336 ops, sizeof ops / sizeof *ops,
340 /* Parses the AND level. */
341 static enum expr_type
342 parse_and (union any_node ** n)
344 static const struct operator ops[] =
346 { T_AND, OP_AND, "logical conjunction (\"AND\")" },
349 return parse_binary_operators (n, parse_not (n), EXPR_BOOLEAN, EXPR_BOOLEAN,
350 ops, sizeof ops / sizeof *ops,
354 /* Parses the NOT level. */
355 static enum expr_type
356 parse_not (union any_node ** n)
358 static const struct operator op
359 = { T_NOT, OP_NOT, "logical negation (\"NOT-\")" };
360 return parse_inverting_unary_operator (n, EXPR_BOOLEAN, &op, parse_rel);
363 /* Parse relational operators. */
364 static enum expr_type
365 parse_rel (union any_node **n)
367 static const struct operator numeric_ops[] =
369 { '=', OP_EQ, "numeric equality (\"=\")" },
370 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
371 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
372 { T_GT, OP_GT, "numeric greater than (\">\")" },
373 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
374 { T_LT, OP_LT, "numeric less than (\"<\")" },
375 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
378 static const struct operator string_ops[] =
380 { '=', OP_EQ_STRING, "string equality (\"=\")" },
381 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
382 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
383 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
384 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
385 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
386 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
389 int type = parse_add (n);
391 const char *chain_warning =
392 _("Chaining relational operators (e.g. \"a < b < c\") will "
393 "not produce the mathematically expected result. "
394 "Use the AND logical operator to fix the problem "
395 "(e.g. \"a < b AND b < c\"). "
396 "If chaining is really intended, parentheses will disable "
397 "this warning (e.g. \"(a < b) < c\".)");
406 return parse_binary_operators (n,
407 type, EXPR_NUMERIC, EXPR_BOOLEAN,
409 sizeof numeric_ops / sizeof *numeric_ops,
410 parse_add, chain_warning);
413 return parse_binary_operators (n,
414 type, EXPR_STRING, EXPR_BOOLEAN,
416 sizeof string_ops / sizeof *string_ops,
417 parse_add, chain_warning);
425 /* Parses the addition and subtraction level. */
426 static enum expr_type
427 parse_add (union any_node **n)
429 static const struct operator ops[] =
431 { '+', OP_ADD, "addition (\"+\")" },
432 { '-', OP_SUB, "subtraction (\"-\")-" },
435 return parse_binary_operators (n, parse_mul (n), EXPR_NUMERIC, EXPR_NUMERIC,
436 ops, sizeof ops / sizeof *ops,
440 /* Parses the multiplication and division level. */
441 static enum expr_type
442 parse_mul (union any_node ** n)
444 static const struct operator ops[] =
446 { '*', OP_MUL, "multiplication (\"*\")" },
447 { '/', OP_DIV, "division (\"/\")" },
450 return parse_binary_operators (n, parse_neg (n), EXPR_NUMERIC, EXPR_NUMERIC,
451 ops, sizeof ops / sizeof *ops,
455 /* Parses the unary minus level. */
456 static enum expr_type
457 parse_neg (union any_node **n)
459 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
460 return parse_inverting_unary_operator (n, EXPR_NUMERIC, &op, parse_exp);
463 static enum expr_type
464 parse_exp (union any_node **n)
466 static const struct operator ops[] =
468 { T_EXP, OP_POW, "exponentiation (\"**\")" },
471 const char *chain_warning =
472 _("The exponentiation operator (\"**\") is left-associative, "
473 "even though right-associative semantics are more useful. "
474 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
475 "To disable this warning, insert parentheses.");
477 return parse_binary_operators (n,
478 parse_primary (n), EXPR_NUMERIC, EXPR_NUMERIC,
479 ops, sizeof ops / sizeof *ops,
480 parse_primary, chain_warning);
483 /* Parses system variables. */
484 static enum expr_type
485 parse_sysvar (union any_node **n)
487 if (!strcmp (tokid, "$CASENUM"))
489 *n = xmalloc (sizeof (struct casenum_node));
490 (*n)->casenum.type = OP_CASENUM;
493 else if (!strcmp (tokid, "$DATE"))
495 static const char *months[12] =
497 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
498 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
504 time = localtime (&last_vfm_invocation);
505 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
506 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
508 *n = xmalloc (sizeof (struct str_con_node) + 8);
509 (*n)->str_con.type = OP_STR_CON;
510 (*n)->str_con.len = 9;
511 memcpy ((*n)->str_con.s, temp_buf, 9);
520 if (!strcmp (tokid, "$TRUE"))
525 else if (!strcmp (tokid, "$FALSE"))
530 else if (!strcmp (tokid, "$SYSMIS"))
532 else if (!strcmp (tokid, "$JDATE"))
534 struct tm *time = localtime (&last_vfm_invocation);
535 d = yrmoda (time->tm_year + 1900, time->tm_mon + 1, time->tm_mday);
537 else if (!strcmp (tokid, "$TIME"))
540 time = localtime (&last_vfm_invocation);
541 d = (yrmoda (time->tm_year + 1900, time->tm_mon + 1,
542 time->tm_mday) * 60. * 60. * 24.
543 + time->tm_hour * 60 * 60.
547 else if (!strcmp (tokid, "$LENGTH"))
548 d = get_viewlength ();
549 else if (!strcmp (tokid, "$WIDTH"))
550 d = get_viewwidth ();
553 msg (SE, _("Unknown system variable %s."), tokid);
557 *n = xmalloc (sizeof (struct num_con_node));
558 (*n)->num_con.type = OP_NUM_CON;
559 (*n)->num_con.value = d;
564 /* Parses numbers, varnames, etc. */
565 static enum expr_type
566 parse_primary (union any_node **n)
574 /* An identifier followed by a left parenthesis is a function
576 if (lex_look_ahead () == '(')
577 return parse_function (n);
579 /* $ at the beginning indicates a system variable. */
582 enum expr_type type = parse_sysvar (n);
587 /* Otherwise, it must be a user variable. */
588 v = dict_lookup_var (default_dict, tokid);
592 lex_error (_("expecting variable name"));
596 if (v->type == NUMERIC)
598 *n = allocate_var_node (OP_NUM_VAR, v);
603 *n = allocate_var_node (OP_STR_VAR, v);
609 *n = allocate_num_con (tokval);
615 *n = allocate_str_con (ds_c_str (&tokstr), ds_length (&tokstr));
625 if (!lex_match (')'))
627 lex_error (_("expecting `)'"));
635 lex_error (_("in expression"));
640 /* Individual function parsing. */
646 enum expr_type (*func) (const struct function *, int, union any_node **);
649 static struct function func_tab[];
650 static int func_count;
652 static int get_num_args (const struct function *, int, union any_node **);
654 static enum expr_type
655 unary_func (const struct function *f, int x UNUSED, union any_node ** n)
657 if (!get_num_args (f, 1, n))
662 static enum expr_type
663 binary_func (const struct function *f, int x UNUSED, union any_node ** n)
665 if (!get_num_args (f, 2, n))
670 static enum expr_type
671 ternary_func (const struct function *f, int x UNUSED, union any_node **n)
673 if (!get_num_args (f, 3, n))
678 static enum expr_type
679 MISSING_func (const struct function *f, int x UNUSED, union any_node **n)
681 if (!get_num_args (f, 1, n))
686 static enum expr_type
687 SYSMIS_func (const struct function *f, int x UNUSED, union any_node **n)
689 if (!get_num_args (f, 1, n))
691 if ((*n)->nonterm.arg[0]->type == OP_NUM_VAR)
693 struct variable *v = (*n)->nonterm.arg[0]->var.v;
695 *n = allocate_var_node (OP_NUM_SYS, v);
700 static enum expr_type
701 VALUE_func (const struct function *f UNUSED, int x UNUSED, union any_node **n)
703 struct variable *v = parse_variable ();
707 if (v->type == NUMERIC)
709 *n = allocate_var_node (OP_NUM_VAL, v);
714 *n = allocate_var_node (OP_STR_VAR, v);
719 static enum expr_type
720 LAG_func (const struct function *f UNUSED, int x UNUSED, union any_node **n)
722 struct variable *v = parse_variable ();
729 if (!lex_integer_p () || lex_integer () <= 0 || lex_integer () > 1000)
731 msg (SE, _("Argument 2 to LAG must be a small positive "
732 "integer constant."));
736 nlag = lex_integer ();
739 n_lag = max (nlag, n_lag);
740 *n = xmalloc (sizeof (struct lag_node));
741 (*n)->lag.type = (v->type == NUMERIC ? OP_NUM_LAG : OP_STR_LAG);
743 (*n)->lag.lag = nlag;
744 return (v->type == NUMERIC ? EXPR_NUMERIC : EXPR_STRING);
747 /* This screwball function parses n-ary operators:
749 1. NMISS, NVALID, SUM, MEAN: any number of numeric
752 2. SD, VARIANCE, CFVAR: at least two numeric arguments.
754 3. RANGE: An odd number of arguments, but at least three, and
755 all of the same type.
757 4. ANY: At least two arguments, all of the same type.
759 5. MIN, MAX: Any number of arguments, all of the same type.
761 static enum expr_type
762 nary_num_func (const struct function *f, int min_args, union any_node **n)
764 /* Argument number of current argument (used for error messages). */
767 /* Number of arguments. */
770 /* Number of arguments allocated. */
773 /* Type of arguments. */
774 int type = (f->t == OP_ANY || f->t == OP_RANGE
775 || f->t == OP_MIN || f->t == OP_MAX) ? -1 : NUMERIC;
777 *n = xmalloc (sizeof (struct nonterm_node) + sizeof (union any_node *[15]));
778 (*n)->nonterm.type = f->t;
782 /* Special case: vara TO varb. */
784 /* FIXME: Is this condition failsafe? Can we _ever_ have two
785 juxtaposed identifiers otherwise? */
786 if (token == T_ID && dict_lookup_var (default_dict, tokid) != NULL
787 && toupper (lex_look_ahead ()) == 'T')
792 int opts = PV_SINGLE;
796 else if (type == ALPHA)
798 if (!parse_variables (default_dict, &v, &nv, opts))
800 if (nv + (*n)->nonterm.n >= m)
803 *n = xrealloc (*n, (sizeof (struct nonterm_node)
804 + (m - 1) * sizeof (union any_node *)));
809 for (j = 1; j < nv; j++)
810 if (type != v[j]->type)
812 msg (SE, _("Type mismatch in argument %d of %s, which was "
813 "expected to be of %s type. It was actually "
815 arg_idx, f->s, var_type_name (type), var_type_name (v[j]->type));
820 for (j = 0; j < nv; j++)
822 union any_node **c = &(*n)->nonterm.arg[(*n)->nonterm.n++];
823 *c = allocate_var_node ((type == NUMERIC
824 ? OP_NUM_VAR : OP_STR_VAR),
831 int t = parse_or (&c);
835 if (t == EXPR_BOOLEAN)
838 msg (SE, _("%s cannot take Boolean operands."), f->s);
843 if (t == EXPR_NUMERIC)
845 else if (t == EXPR_STRING)
848 else if ((t == EXPR_NUMERIC) ^ (type == NUMERIC))
851 msg (SE, _("Type mismatch in argument %d of %s, which was "
852 "expected to be of %s type. It was actually "
854 arg_idx, f->s, var_type_name (type), expr_type_name (t));
857 if ((*n)->nonterm.n + 1 >= m)
860 *n = xrealloc (*n, (sizeof (struct nonterm_node)
861 + (m - 1) * sizeof (union any_node *)));
863 (*n)->nonterm.arg[(*n)->nonterm.n++] = c;
868 if (!lex_match (','))
870 lex_error (_("in function call"));
876 *n = xrealloc (*n, (sizeof (struct nonterm_node)
877 + ((*n)->nonterm.n) * sizeof (union any_node *)));
879 nargs = (*n)->nonterm.n;
880 if (f->t == OP_RANGE)
882 if (nargs < 3 || (nargs & 1) == 0)
884 msg (SE, _("RANGE requires an odd number of arguments, but "
889 else if (f->t == OP_SD || f->t == OP_VARIANCE
890 || f->t == OP_CFVAR || f->t == OP_ANY)
894 msg (SE, _("%s requires at least two arguments."), f->s);
899 if (f->t == OP_CFVAR || f->t == OP_SD || f->t == OP_VARIANCE)
900 min_args = max (min_args, 2);
902 min_args = max (min_args, 1);
904 /* Yes, this is admittedly a terrible crock, but it works. */
905 (*n)->nonterm.arg[(*n)->nonterm.n] = (union any_node *) min_args;
907 if (min_args > nargs)
909 msg (SE, _("%s.%d requires at least %d arguments."),
910 f->s, min_args, min_args);
914 if (f->t == OP_MIN || f->t == OP_MAX)
919 (*n)->type = OP_MIN_STRING;
920 else if (f->t == OP_MAX)
921 (*n)->type = OP_MAX_STRING;
929 else if (f->t == OP_ANY || f->t == OP_RANGE)
934 (*n)->type = OP_ANY_STRING;
935 else if (f->t == OP_RANGE)
936 (*n)->type = OP_RANGE_STRING;
950 static enum expr_type
951 CONCAT_func (const struct function *f UNUSED, int x UNUSED, union any_node **n)
957 *n = xmalloc (sizeof (struct nonterm_node) + sizeof (union any_node *[15]));
958 (*n)->nonterm.type = OP_CONCAT;
962 if ((*n)->nonterm.n >= m)
965 *n = xrealloc (*n, (sizeof (struct nonterm_node)
966 + (m - 1) * sizeof (union any_node *)));
968 type = parse_or (&(*n)->nonterm.arg[(*n)->nonterm.n]);
969 if (type == EXPR_ERROR)
972 if (type != EXPR_STRING)
974 msg (SE, _("Argument %d to CONCAT is type %s. All arguments "
975 "to CONCAT must be strings."),
976 (*n)->nonterm.n + 1, expr_type_name (type));
980 if (!lex_match (','))
983 *n = xrealloc (*n, (sizeof (struct nonterm_node)
984 + ((*n)->nonterm.n - 1) * sizeof (union any_node *)));
992 /* Parses a string function according to f->desc. f->desc[0] is the
993 return type of the function. Succeeding characters represent
994 successive args. Optional args are separated from the required
995 args by a slash (`/'). Codes are `n', numeric arg; `s', string
996 arg; and `f', format spec (this must be the last arg). If the
997 optional args are included, the type becomes f->t+1. */
998 static enum expr_type
999 generic_str_func (const struct function *f, int x UNUSED, union any_node **n)
1001 struct string_function
1004 enum expr_type return_type;
1005 const char *arg_types;
1008 static const struct string_function string_func_tab[] =
1010 {OP_INDEX_2, OP_INDEX_3, EXPR_NUMERIC, "ssN"},
1011 {OP_RINDEX_2, OP_RINDEX_3, EXPR_NUMERIC, "ssN"},
1012 {OP_LENGTH, 0, EXPR_NUMERIC, "s"},
1013 {OP_LOWER, 0, EXPR_STRING, "s"},
1014 {OP_UPPER, 0, EXPR_STRING, "s"},
1015 {OP_LPAD, 0, EXPR_STRING, "snS"},
1016 {OP_RPAD, 0, EXPR_STRING, "snS"},
1017 {OP_LTRIM, 0, EXPR_STRING, "sS"},
1018 {OP_RTRIM, 0, EXPR_STRING, "sS"},
1019 {OP_NUMBER, 0, EXPR_NUMERIC, "sf"},
1020 {OP_STRING, 0, EXPR_STRING, "nf"},
1021 {OP_SUBSTR_2, OP_SUBSTR_3, EXPR_STRING, "snN"},
1024 const int string_func_cnt = sizeof string_func_tab / sizeof *string_func_tab;
1026 const struct string_function *sf;
1029 struct nonterm_node *nonterm;
1031 /* Find string_function that corresponds to f. */
1032 for (sf = string_func_tab; sf < string_func_tab + string_func_cnt; sf++)
1035 assert (sf < string_func_tab + string_func_cnt);
1037 /* Count max number of arguments. */
1039 for (cp = sf->arg_types; *cp != '\0'; cp++)
1047 /* Allocate node. */
1048 *n = xmalloc (sizeof (struct nonterm_node)
1049 + (arg_cnt - 1) * sizeof (union any_node *));
1050 nonterm = &(*n)->nonterm;
1051 nonterm->type = sf->t1;
1054 /* Parse arguments. */
1058 if (*cp == 'n' || *cp == 's' || *cp == 'N' || *cp == 'S')
1060 enum expr_type wanted_type
1061 = *cp == 'n' || *cp == 'N' ? EXPR_NUMERIC : EXPR_STRING;
1062 enum expr_type actual_type = parse_or (&nonterm->arg[nonterm->n]);
1064 if (actual_type == EXPR_ERROR)
1066 else if (actual_type == EXPR_BOOLEAN)
1067 actual_type = EXPR_NUMERIC;
1069 if (actual_type != wanted_type)
1071 msg (SE, _("Argument %d to %s was expected to be of %s type. "
1072 "It was actually of type %s."),
1073 nonterm->n + 1, f->s,
1074 expr_type_name (actual_type), expr_type_name (wanted_type));
1078 else if (*cp == 'f')
1080 /* This is always the very last argument. Also, this code
1081 is a crock. However, it works. */
1082 struct fmt_spec fmt;
1084 if (!parse_format_specifier (&fmt, 0))
1086 if (formats[fmt.type].cat & FCAT_STRING)
1088 msg (SE, _("%s is not a numeric format."), fmt_to_string (&fmt));
1091 nonterm->arg[nonterm->n + 0] = (union any_node *) fmt.type;
1092 nonterm->arg[nonterm->n + 1] = (union any_node *) fmt.w;
1093 nonterm->arg[nonterm->n + 2] = (union any_node *) fmt.d;
1099 /* We're done if no args are left. */
1104 /* Optional arguments are named with capital letters. */
1105 if (isupper ((unsigned char) *cp))
1107 if (!lex_match (','))
1112 nonterm->arg[nonterm->n++] = allocate_num_con (SYSMIS);
1113 else if (*cp == 'S')
1114 nonterm->arg[nonterm->n++] = allocate_str_con (" ", 1);
1122 nonterm->type = sf->t2;
1124 else if (!lex_match (','))
1126 msg (SE, _("Too few arguments to function %s."), f->s);
1131 return sf->return_type;
1138 /* General function parsing. */
1141 get_num_args (const struct function *f, int num_args, union any_node **n)
1146 *n = xmalloc (sizeof (struct nonterm_node)
1147 + (num_args - 1) * sizeof (union any_node *));
1148 (*n)->nonterm.type = f->t;
1149 (*n)->nonterm.n = 0;
1152 t = parse_or (&(*n)->nonterm.arg[i]);
1153 if (t == EXPR_ERROR)
1157 if (t == EXPR_STRING)
1159 msg (SE, _("Type mismatch in argument %d of %s. A string "
1160 "expression was supplied where only a numeric expression "
1165 if (++i >= num_args)
1167 if (!lex_match (','))
1169 msg (SE, _("Missing comma following argument %d of %s."), i + 1, f->s);
1179 static enum expr_type
1180 parse_function (union any_node ** n)
1182 const struct function *fp;
1183 char fname[32], *cp;
1186 const struct vector *v;
1188 /* Check for a vector with this name. */
1189 v = dict_lookup_vector (default_dict, tokid);
1193 assert (token == '(');
1196 *n = xmalloc (sizeof (struct nonterm_node)
1197 + sizeof (union any_node *[2]));
1198 (*n)->nonterm.type = (v->var[0]->type == NUMERIC
1199 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR);
1200 (*n)->nonterm.n = 0;
1202 t = parse_or (&(*n)->nonterm.arg[0]);
1203 if (t == EXPR_ERROR)
1205 if (t != EXPR_NUMERIC)
1207 msg (SE, _("The index value after a vector name must be numeric."));
1212 if (!lex_match (')'))
1214 msg (SE, _("`)' expected after a vector index value."));
1217 ((*n)->nonterm.arg[1]) = (union any_node *) v->idx;
1219 return v->var[0]->type == NUMERIC ? EXPR_NUMERIC : EXPR_STRING;
1222 ds_truncate (&tokstr, 31);
1223 strcpy (fname, ds_c_str (&tokstr));
1224 cp = strrchr (fname, '.');
1225 if (cp && isdigit ((unsigned char) cp[1]))
1227 min_args = atoi (&cp[1]);
1234 if (!lex_force_match ('('))
1241 fp = binary_search (func_tab, func_count, sizeof *func_tab, &f,
1242 compare_functions, NULL);
1247 msg (SE, _("There is no function named %s."), fname);
1250 if (min_args && fp->func != nary_num_func)
1252 msg (SE, _("Function %s may not be given a minimum number of "
1253 "arguments."), fname);
1256 t = fp->func (fp, min_args, n);
1257 if (t == EXPR_ERROR)
1259 if (!lex_match (')'))
1261 lex_error (_("expecting `)' after %s function"), fname);
1272 /* Utility functions. */
1275 expr_type_name (enum expr_type type)
1283 return _("Boolean");
1286 return _("numeric");
1298 var_type_name (int type)
1303 return _("numeric");
1313 make_bool (union any_node **n)
1317 c = xmalloc (sizeof (struct nonterm_node));
1318 c->nonterm.type = OP_NUM_TO_BOOL;
1320 c->nonterm.arg[0] = *n;
1325 free_node (union any_node *n)
1329 if (IS_NONTERMINAL (n->type))
1333 for (i = 0; i < n->nonterm.n; i++)
1334 free_node (n->nonterm.arg[i]);
1340 static union any_node *
1341 allocate_num_con (double value)
1345 c = xmalloc (sizeof (struct num_con_node));
1346 c->num_con.type = OP_NUM_CON;
1347 c->num_con.value = value;
1352 static union any_node *
1353 allocate_str_con (const char *string, size_t length)
1357 c = xmalloc (sizeof (struct str_con_node) + length - 1);
1358 c->str_con.type = OP_STR_CON;
1359 c->str_con.len = length;
1360 memcpy (c->str_con.s, string, length);
1365 static union any_node *
1366 allocate_var_node (int type, struct variable *variable)
1370 c = xmalloc (sizeof (struct var_node));
1372 c->var.v = variable;
1378 allocate_nonterminal (int op, union any_node *n)
1382 c = xmalloc (sizeof c->nonterm);
1383 c->nonterm.type = op;
1385 c->nonterm.arg[0] = n;
1390 static union any_node *
1391 allocate_binary_nonterminal (int op, union any_node *lhs, union any_node *rhs)
1393 union any_node *node;
1395 node = xmalloc (sizeof node->nonterm + sizeof *node->nonterm.arg);
1396 node->nonterm.type = op;
1397 node->nonterm.n = 2;
1398 node->nonterm.arg[0] = lhs;
1399 node->nonterm.arg[1] = rhs;
1404 static struct function func_tab[] =
1406 {"ABS", OP_ABS, unary_func},
1407 {"ACOS", OP_ARCOS, unary_func},
1408 {"ARCOS", OP_ARCOS, unary_func},
1409 {"ARSIN", OP_ARSIN, unary_func},
1410 {"ARTAN", OP_ARTAN, unary_func},
1411 {"ASIN", OP_ARSIN, unary_func},
1412 {"ATAN", OP_ARTAN, unary_func},
1413 {"COS", OP_COS, unary_func},
1414 {"EXP", OP_EXP, unary_func},
1415 {"LG10", OP_LG10, unary_func},
1416 {"LN", OP_LN, unary_func},
1417 {"MOD10", OP_MOD10, unary_func},
1418 {"NORMAL", OP_NORMAL, unary_func},
1419 {"RND", OP_RND, unary_func},
1420 {"SIN", OP_SIN, unary_func},
1421 {"SQRT", OP_SQRT, unary_func},
1422 {"TAN", OP_TAN, unary_func},
1423 {"TRUNC", OP_TRUNC, unary_func},
1424 {"UNIFORM", OP_UNIFORM, unary_func},
1426 {"TIME.DAYS", OP_TIME_DAYS, unary_func},
1427 {"TIME.HMS", OP_TIME_HMS, ternary_func},
1429 {"CTIME.DAYS", OP_CTIME_DAYS, unary_func},
1430 {"CTIME.HOURS", OP_CTIME_HOURS, unary_func},
1431 {"CTIME.MINUTES", OP_CTIME_MINUTES, unary_func},
1432 {"CTIME.SECONDS", OP_CTIME_SECONDS, unary_func},
1434 {"DATE.DMY", OP_DATE_DMY, ternary_func},
1435 {"DATE.MDY", OP_DATE_MDY, ternary_func},
1436 {"DATE.MOYR", OP_DATE_MOYR, binary_func},
1437 {"DATE.QYR", OP_DATE_QYR, binary_func},
1438 {"DATE.WKYR", OP_DATE_WKYR, binary_func},
1439 {"DATE.YRDAY", OP_DATE_YRDAY, binary_func},
1441 {"XDATE.DATE", OP_XDATE_DATE, unary_func},
1442 {"XDATE.HOUR", OP_XDATE_HOUR, unary_func},
1443 {"XDATE.JDAY", OP_XDATE_JDAY, unary_func},
1444 {"XDATE.MDAY", OP_XDATE_MDAY, unary_func},
1445 {"XDATE.MINUTE", OP_XDATE_MINUTE, unary_func},
1446 {"XDATE.MONTH", OP_XDATE_MONTH, unary_func},
1447 {"XDATE.QUARTER", OP_XDATE_QUARTER, unary_func},
1448 {"XDATE.SECOND", OP_XDATE_SECOND, unary_func},
1449 {"XDATE.TDAY", OP_XDATE_TDAY, unary_func},
1450 {"XDATE.TIME", OP_XDATE_TIME, unary_func},
1451 {"XDATE.WEEK", OP_XDATE_WEEK, unary_func},
1452 {"XDATE.WKDAY", OP_XDATE_WKDAY, unary_func},
1453 {"XDATE.YEAR", OP_XDATE_YEAR, unary_func},
1455 {"MISSING", OP_SYSMIS, MISSING_func},
1456 {"MOD", OP_MOD, binary_func},
1457 {"SYSMIS", OP_SYSMIS, SYSMIS_func},
1458 {"VALUE", OP_NUM_VAL, VALUE_func},
1459 {"LAG", OP_NUM_LAG, LAG_func},
1460 {"YRMODA", OP_YRMODA, ternary_func},
1462 {"ANY", OP_ANY, nary_num_func},
1463 {"CFVAR", OP_CFVAR, nary_num_func},
1464 {"MAX", OP_MAX, nary_num_func},
1465 {"MEAN", OP_MEAN, nary_num_func},
1466 {"MIN", OP_MIN, nary_num_func},
1467 {"NMISS", OP_NMISS, nary_num_func},
1468 {"NVALID", OP_NVALID, nary_num_func},
1469 {"RANGE", OP_RANGE, nary_num_func},
1470 {"SD", OP_SD, nary_num_func},
1471 {"SUM", OP_SUM, nary_num_func},
1472 {"VAR", OP_VARIANCE, nary_num_func},
1473 {"VARIANCE", OP_VARIANCE, nary_num_func},
1475 {"CONCAT", OP_CONCAT, CONCAT_func},
1477 {"INDEX", OP_INDEX_2, generic_str_func},
1478 {"RINDEX", OP_RINDEX_2, generic_str_func},
1479 {"LENGTH", OP_LENGTH, generic_str_func},
1480 {"LOWER", OP_LOWER, generic_str_func},
1481 {"UPCASE", OP_UPPER, generic_str_func},
1482 {"LPAD", OP_LPAD, generic_str_func},
1483 {"RPAD", OP_RPAD, generic_str_func},
1484 {"LTRIM", OP_LTRIM, generic_str_func},
1485 {"RTRIM", OP_RTRIM, generic_str_func},
1486 {"NUMBER", OP_NUMBER, generic_str_func},
1487 {"STRING", OP_STRING, generic_str_func},
1488 {"SUBSTR", OP_SUBSTR_2, generic_str_func},
1491 /* An algo_compare_func that compares functions A and B based on
1494 compare_functions (const void *a_, const void *b_, void *aux UNUSED)
1496 const struct function *a = a_;
1497 const struct function *b = b_;
1499 return strcmp (a->s, b->s);
1503 init_func_tab (void)
1513 func_count = sizeof func_tab / sizeof *func_tab;
1514 sort (func_tab, func_count, sizeof *func_tab, compare_functions, NULL);
1520 expr_debug_print_postfix (const struct expression *e)
1522 const unsigned char *o;
1523 const double *num = e->num;
1524 const unsigned char *str = e->str;
1525 struct variable *const *v = e->var;
1528 printf ("postfix:");
1529 for (o = e->op; *o != OP_SENTINEL;)
1532 if (IS_NONTERMINAL (t))
1534 printf (" %s", ops[t].name);
1536 if (ops[t].flags & OP_VAR_ARGS)
1538 printf ("(%d)", *o);
1541 if (ops[t].flags & OP_MIN_ARGS)
1546 if (ops[t].flags & OP_FMT_SPEC)
1549 f.type = (int) *o++;
1552 printf ("(%s)", fmt_to_string (&f));
1555 else if (t == OP_NUM_CON)
1560 printf (" %f", *num);
1563 else if (t == OP_STR_CON)
1565 printf (" \"%.*s\"", *str, &str[1]);
1568 else if (t == OP_NUM_VAR || t == OP_STR_VAR)
1570 printf (" %s", (*v)->name);
1573 else if (t == OP_NUM_SYS)
1575 printf (" SYSMIS(#%d)", *o);
1578 else if (t == OP_NUM_VAL)
1580 printf (" VALUE(#%d)", *o);
1583 else if (t == OP_NUM_LAG || t == OP_STR_LAG)
1585 printf (" LAG(%s,%d)", (*v)->name, *o);
1591 printf ("%d unknown\n", t);
1598 #define DEFINE_OPERATOR(NAME, STACK_DELTA, FLAGS, ARGS) \
1599 {#NAME, STACK_DELTA, FLAGS, ARGS},
1600 struct op_desc ops[OP_SENTINEL] =
1605 #include "command.h"
1608 cmd_debug_evaluate (void)
1610 struct expression *expr;
1612 enum expr_type expr_flags;
1613 int dump_postfix = 0;
1615 discard_variables ();
1618 if (lex_match_id ("NOOPTIMIZE"))
1619 expr_flags |= EXPR_NO_OPTIMIZE;
1620 if (lex_match_id ("POSTFIX"))
1624 lex_force_match ('/');
1627 fprintf (stderr, "%s => ", lex_rest_of_line (NULL));
1630 expr = expr_parse (EXPR_ANY | expr_flags);
1631 if (!expr || token != '.')
1635 fprintf (stderr, "error\n");
1640 expr_debug_print_postfix (expr);
1643 expr_evaluate (expr, NULL, 0, &value);
1644 switch (expr_get_type (expr))
1647 if (value.f == SYSMIS)
1648 fprintf (stderr, "sysmis\n");
1650 fprintf (stderr, "%.2f\n", value.f);
1654 if (value.f == SYSMIS)
1655 fprintf (stderr, "sysmis\n");
1656 else if (value.f == 0.0)
1657 fprintf (stderr, "false\n");
1659 fprintf (stderr, "true\n");
1663 fputc ('"', stderr);
1664 fwrite (value.c + 1, value.c[0], 1, stderr);
1665 fputs ("\"\n", stderr);