1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000, 2006 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
30 #include <data/case.h>
31 #include <data/dictionary.h>
32 #include <data/settings.h>
33 #include <data/variable.h>
34 #include <language/lexer/format-parser.h>
35 #include <language/lexer/lexer.h>
36 #include <language/lexer/variable-parser.h>
37 #include <libpspp/alloc.h>
38 #include <libpspp/array.h>
39 #include <libpspp/assertion.h>
40 #include <libpspp/message.h>
41 #include <libpspp/misc.h>
42 #include <libpspp/pool.h>
43 #include <libpspp/str.h>
47 /* Recursive descent parser in order of increasing precedence. */
48 typedef union any_node *parse_recursively_func (struct expression *);
49 static parse_recursively_func parse_or, parse_and, parse_not;
50 static parse_recursively_func parse_rel, parse_add, parse_mul;
51 static parse_recursively_func parse_neg, parse_exp;
52 static parse_recursively_func parse_primary;
53 static parse_recursively_func parse_vector_element, parse_function;
55 /* Utility functions. */
56 static struct expression *expr_create (struct dataset *ds);
57 atom_type expr_node_returns (const union any_node *);
59 static const char *atom_type_name (atom_type);
60 static struct expression *finish_expression (union any_node *,
62 static bool type_check (struct expression *, union any_node **,
63 enum expr_type expected_type);
64 static union any_node *allocate_unary_variable (struct expression *,
67 /* Public functions. */
69 /* Parses an expression of the given TYPE.
70 If DICT is nonnull then variables and vectors within it may be
71 referenced within the expression; otherwise, the expression
72 must not reference any variables or vectors.
73 Returns the new expression if successful or a null pointer
76 expr_parse (struct dataset *ds, enum expr_type type)
81 assert (type == EXPR_NUMBER || type == EXPR_STRING || type == EXPR_BOOLEAN);
85 if (n != NULL && type_check (e, &n, type))
86 return finish_expression (expr_optimize (n, e), e);
94 /* Parses and returns an expression of the given TYPE, as
95 expr_parse(), and sets up so that destroying POOL will free
96 the expression as well. */
98 expr_parse_pool (struct pool *pool,
102 struct expression *e = expr_parse (ds, type);
104 pool_add_subpool (pool, e->expr_pool);
108 /* Free expression E. */
110 expr_free (struct expression *e)
113 pool_destroy (e->expr_pool);
117 expr_parse_any (struct dataset *ds, bool optimize)
120 struct expression *e;
122 e = expr_create (ds);
131 n = expr_optimize (n, e);
132 return finish_expression (n, e);
135 /* Finishing up expression building. */
137 /* Height of an expression's stacks. */
140 int number_height; /* Height of number stack. */
141 int string_height; /* Height of string stack. */
144 /* Stack heights used by different kinds of arguments. */
145 static const struct stack_heights on_number_stack = {1, 0};
146 static const struct stack_heights on_string_stack = {0, 1};
147 static const struct stack_heights not_on_stack = {0, 0};
149 /* Returns the stack heights used by an atom of the given
151 static const struct stack_heights *
152 atom_type_stack (atom_type type)
154 assert (is_atom (type));
160 return &on_number_stack;
163 return &on_string_stack;
173 return ¬_on_stack;
180 /* Measures the stack height needed for node N, supposing that
181 the stack height is initially *HEIGHT and updating *HEIGHT to
182 the final stack height. Updates *MAX, if necessary, to
183 reflect the maximum intermediate or final height. */
185 measure_stack (const union any_node *n,
186 struct stack_heights *height, struct stack_heights *max)
188 const struct stack_heights *return_height;
190 if (is_composite (n->type))
192 struct stack_heights args;
196 for (i = 0; i < n->composite.arg_cnt; i++)
197 measure_stack (n->composite.args[i], &args, max);
199 return_height = atom_type_stack (operations[n->type].returns);
202 return_height = atom_type_stack (n->type);
204 height->number_height += return_height->number_height;
205 height->string_height += return_height->string_height;
207 if (height->number_height > max->number_height)
208 max->number_height = height->number_height;
209 if (height->string_height > max->string_height)
210 max->string_height = height->string_height;
213 /* Allocates stacks within E sufficient for evaluating node N. */
215 allocate_stacks (union any_node *n, struct expression *e)
217 struct stack_heights initial = {0, 0};
218 struct stack_heights max = {0, 0};
220 measure_stack (n, &initial, &max);
221 e->number_stack = pool_alloc (e->expr_pool,
222 sizeof *e->number_stack * max.number_height);
223 e->string_stack = pool_alloc (e->expr_pool,
224 sizeof *e->string_stack * max.string_height);
227 /* Finalizes expression E for evaluating node N. */
228 static struct expression *
229 finish_expression (union any_node *n, struct expression *e)
231 /* Allocate stacks. */
232 allocate_stacks (n, e);
234 /* Output postfix representation. */
237 /* The eval_pool might have been used for allocating strings
238 during optimization. We need to keep those strings around
239 for all subsequent evaluations, so start a new eval_pool. */
240 e->eval_pool = pool_create_subpool (e->expr_pool);
245 /* Verifies that expression E, whose root node is *N, can be
246 converted to type EXPECTED_TYPE, inserting a conversion at *N
247 if necessary. Returns true if successful, false on failure. */
249 type_check (struct expression *e,
250 union any_node **n, enum expr_type expected_type)
252 atom_type actual_type = expr_node_returns (*n);
254 switch (expected_type)
258 if (actual_type != OP_number && actual_type != OP_boolean)
260 msg (SE, _("Type mismatch: expression has %s type, "
261 "but a numeric value is required here."),
262 atom_type_name (actual_type));
265 if (actual_type == OP_number && expected_type == OP_boolean)
266 *n = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *n);
270 if (actual_type != OP_string)
272 msg (SE, _("Type mismatch: expression has %s type, "
273 "but a string value is required here."),
274 atom_type_name (actual_type));
286 /* Recursive-descent expression parser. */
288 /* Considers whether *NODE may be coerced to type REQUIRED_TYPE.
289 Returns true if possible, false if disallowed.
291 If DO_COERCION is false, then *NODE is not modified and there
294 If DO_COERCION is true, we perform the coercion if possible,
295 modifying *NODE if necessary. If the coercion is not possible
296 then we free *NODE and set *NODE to a null pointer.
298 This function's interface is somewhat awkward. Use one of the
299 wrapper functions type_coercion(), type_coercion_assert(), or
300 is_coercible() instead. */
302 type_coercion_core (struct expression *e,
303 atom_type required_type,
304 union any_node **node,
305 const char *operator_name,
308 atom_type actual_type;
310 assert (!!do_coercion == (e != NULL));
313 /* Propagate error. Whatever caused the original error
314 already emitted an error message. */
318 actual_type = expr_node_returns (*node);
319 if (actual_type == required_type)
325 switch (required_type)
328 if (actual_type == OP_boolean)
330 /* To enforce strict typing rules, insert Boolean to
331 numeric "conversion". This conversion is a no-op,
332 so it will be removed later. */
334 *node = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, *node);
340 /* No coercion to string. */
344 if (actual_type == OP_number)
346 /* Convert numeric to boolean. */
348 *node = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *node);
358 if ((*node)->type == OP_format
359 && fmt_check_input (&(*node)->format.f)
360 && fmt_check_type_compat (&(*node)->format.f, NUMERIC))
364 (*node)->type = OP_ni_format;
372 if ((*node)->type == OP_format
373 && fmt_check_output (&(*node)->format.f)
374 && fmt_check_type_compat (&(*node)->format.f, NUMERIC))
378 (*node)->type = OP_no_format;
385 if ((*node)->type == OP_NUM_VAR)
388 *node = (*node)->composite.args[0];
394 if ((*node)->type == OP_STR_VAR)
397 *node = (*node)->composite.args[0];
403 if ((*node)->type == OP_number
404 && floor ((*node)->number.n) == (*node)->number.n
405 && (*node)->number.n > 0 && (*node)->number.n < INT_MAX)
408 *node = expr_allocate_pos_int (e, (*node)->number.n);
419 msg (SE, _("Type mismatch while applying %s operator: "
420 "cannot convert %s to %s."),
422 atom_type_name (actual_type), atom_type_name (required_type));
428 /* Coerces *NODE to type REQUIRED_TYPE, and returns success. If
429 *NODE cannot be coerced to the desired type then we issue an
430 error message about operator OPERATOR_NAME and free *NODE. */
432 type_coercion (struct expression *e,
433 atom_type required_type, union any_node **node,
434 const char *operator_name)
436 return type_coercion_core (e, required_type, node, operator_name, true);
439 /* Coerces *NODE to type REQUIRED_TYPE.
440 Assert-fails if the coercion is disallowed. */
442 type_coercion_assert (struct expression *e,
443 atom_type required_type, union any_node **node)
445 int success = type_coercion_core (e, required_type, node, NULL, true);
449 /* Returns true if *NODE may be coerced to type REQUIRED_TYPE,
452 is_coercible (atom_type required_type, union any_node *const *node)
454 return type_coercion_core (NULL, required_type,
455 (union any_node **) node, NULL, false);
458 /* How to parse an operator. */
461 int token; /* Token representing operator. */
462 operation_type type; /* Operation type representing operation. */
463 const char *name; /* Name of operator. */
466 /* Attempts to match the current token against the tokens for the
467 OP_CNT operators in OPS[]. If successful, returns true
468 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
469 On failure, returns false and, if OPERATOR is non-null, sets
470 *OPERATOR to a null pointer. */
472 match_operator (const struct operator ops[], size_t op_cnt,
473 const struct operator **operator)
475 const struct operator *op;
477 for (op = ops; op < ops + op_cnt; op++)
479 if (op->token == '-')
480 lex_negative_to_dash ();
481 if (lex_match (op->token))
483 if (operator != NULL)
488 if (operator != NULL)
494 check_operator (const struct operator *op, int arg_cnt, atom_type arg_type)
496 const struct operation *o;
500 o = &operations[op->type];
501 assert (o->arg_cnt == arg_cnt);
502 assert ((o->flags & OPF_ARRAY_OPERAND) == 0);
503 for (i = 0; i < arg_cnt; i++)
504 assert (o->args[i] == arg_type);
509 check_binary_operators (const struct operator ops[], size_t op_cnt,
514 for (i = 0; i < op_cnt; i++)
515 check_operator (&ops[i], 2, arg_type);
520 get_operand_type (const struct operator *op)
522 return operations[op->type].args[0];
525 /* Parses a chain of left-associative operator/operand pairs.
526 There are OP_CNT operators, specified in OPS[]. The
527 operators' operands must all be the same type. The next
528 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
529 is non-null, then it will be issued as a warning if more than
530 one operator/operand pair is parsed. */
531 static union any_node *
532 parse_binary_operators (struct expression *e, union any_node *node,
533 const struct operator ops[], size_t op_cnt,
534 parse_recursively_func *parse_next_level,
535 const char *chain_warning)
537 atom_type operand_type = get_operand_type (&ops[0]);
539 const struct operator *operator;
541 assert (check_binary_operators (ops, op_cnt, operand_type));
545 for (op_count = 0; match_operator (ops, op_cnt, &operator); op_count++)
549 /* Convert the left-hand side to type OPERAND_TYPE. */
550 if (!type_coercion (e, operand_type, &node, operator->name))
553 /* Parse the right-hand side and coerce to type
555 rhs = parse_next_level (e);
556 if (!type_coercion (e, operand_type, &rhs, operator->name))
558 node = expr_allocate_binary (e, operator->type, node, rhs);
561 if (op_count > 1 && chain_warning != NULL)
562 msg (SW, chain_warning);
567 static union any_node *
568 parse_inverting_unary_operator (struct expression *e,
569 const struct operator *op,
570 parse_recursively_func *parse_next_level)
572 union any_node *node;
575 check_operator (op, 1, get_operand_type (op));
578 while (match_operator (op, 1, NULL))
581 node = parse_next_level (e);
583 && type_coercion (e, get_operand_type (op), &node, op->name)
584 && op_count % 2 != 0)
585 return expr_allocate_unary (e, op->type, node);
590 /* Parses the OR level. */
591 static union any_node *
592 parse_or (struct expression *e)
594 static const struct operator op =
595 { T_OR, OP_OR, "logical disjunction (\"OR\")" };
597 return parse_binary_operators (e, parse_and (e), &op, 1, parse_and, NULL);
600 /* Parses the AND level. */
601 static union any_node *
602 parse_and (struct expression *e)
604 static const struct operator op =
605 { T_AND, OP_AND, "logical conjunction (\"AND\")" };
607 return parse_binary_operators (e, parse_not (e), &op, 1, parse_not, NULL);
610 /* Parses the NOT level. */
611 static union any_node *
612 parse_not (struct expression *e)
614 static const struct operator op
615 = { T_NOT, OP_NOT, "logical negation (\"NOT\")" };
616 return parse_inverting_unary_operator (e, &op, parse_rel);
619 /* Parse relational operators. */
620 static union any_node *
621 parse_rel (struct expression *e)
623 const char *chain_warning =
624 _("Chaining relational operators (e.g. \"a < b < c\") will "
625 "not produce the mathematically expected result. "
626 "Use the AND logical operator to fix the problem "
627 "(e.g. \"a < b AND b < c\"). "
628 "If chaining is really intended, parentheses will disable "
629 "this warning (e.g. \"(a < b) < c\".)");
631 union any_node *node = parse_add (e);
636 switch (expr_node_returns (node))
641 static const struct operator ops[] =
643 { '=', OP_EQ, "numeric equality (\"=\")" },
644 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
645 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
646 { T_GT, OP_GT, "numeric greater than (\">\")" },
647 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
648 { T_LT, OP_LT, "numeric less than (\"<\")" },
649 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
652 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
653 parse_add, chain_warning);
658 static const struct operator ops[] =
660 { '=', OP_EQ_STRING, "string equality (\"=\")" },
661 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
662 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
663 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
664 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
665 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
666 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
669 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
670 parse_add, chain_warning);
678 /* Parses the addition and subtraction level. */
679 static union any_node *
680 parse_add (struct expression *e)
682 static const struct operator ops[] =
684 { '+', OP_ADD, "addition (\"+\")" },
685 { '-', OP_SUB, "subtraction (\"-\")" },
688 return parse_binary_operators (e, parse_mul (e),
689 ops, sizeof ops / sizeof *ops,
693 /* Parses the multiplication and division level. */
694 static union any_node *
695 parse_mul (struct expression *e)
697 static const struct operator ops[] =
699 { '*', OP_MUL, "multiplication (\"*\")" },
700 { '/', OP_DIV, "division (\"/\")" },
703 return parse_binary_operators (e, parse_neg (e),
704 ops, sizeof ops / sizeof *ops,
708 /* Parses the unary minus level. */
709 static union any_node *
710 parse_neg (struct expression *e)
712 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
713 return parse_inverting_unary_operator (e, &op, parse_exp);
716 static union any_node *
717 parse_exp (struct expression *e)
719 static const struct operator op =
720 { T_EXP, OP_POW, "exponentiation (\"**\")" };
722 const char *chain_warning =
723 _("The exponentiation operator (\"**\") is left-associative, "
724 "even though right-associative semantics are more useful. "
725 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
726 "To disable this warning, insert parentheses.");
728 return parse_binary_operators (e, parse_primary (e), &op, 1,
729 parse_primary, chain_warning);
732 /* Parses system variables. */
733 static union any_node *
734 parse_sysvar (struct expression *e)
736 if (lex_match_id ("$CASENUM"))
737 return expr_allocate_nullary (e, OP_CASENUM);
738 else if (lex_match_id ("$DATE"))
740 static const char *months[12] =
742 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
743 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
746 time_t last_proc_time = time_of_last_procedure (e->ds);
750 time = localtime (&last_proc_time);
751 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
752 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
754 return expr_allocate_string_buffer (e, temp_buf, strlen (temp_buf));
756 else if (lex_match_id ("$TRUE"))
757 return expr_allocate_boolean (e, 1.0);
758 else if (lex_match_id ("$FALSE"))
759 return expr_allocate_boolean (e, 0.0);
760 else if (lex_match_id ("$SYSMIS"))
761 return expr_allocate_number (e, SYSMIS);
762 else if (lex_match_id ("$JDATE"))
764 time_t time = time_of_last_procedure (e->ds);
765 struct tm *tm = localtime (&time);
766 return expr_allocate_number (e, expr_ymd_to_ofs (tm->tm_year + 1900,
770 else if (lex_match_id ("$TIME"))
772 time_t time = time_of_last_procedure (e->ds);
773 struct tm *tm = localtime (&time);
774 return expr_allocate_number (e,
775 expr_ymd_to_date (tm->tm_year + 1900,
778 + tm->tm_hour * 60 * 60.
782 else if (lex_match_id ("$LENGTH"))
783 return expr_allocate_number (e, get_viewlength ());
784 else if (lex_match_id ("$WIDTH"))
785 return expr_allocate_number (e, get_viewwidth ());
788 msg (SE, _("Unknown system variable %s."), tokid);
793 /* Parses numbers, varnames, etc. */
794 static union any_node *
795 parse_primary (struct expression *e)
800 if (lex_look_ahead () == '(')
802 /* An identifier followed by a left parenthesis may be
803 a vector element reference. If not, it's a function
805 if (e->ds != NULL && dict_lookup_vector (dataset_dict (e->ds), tokid) != NULL)
806 return parse_vector_element (e);
808 return parse_function (e);
810 else if (tokid[0] == '$')
812 /* $ at the beginning indicates a system variable. */
813 return parse_sysvar (e);
815 else if (e->ds != NULL && dict_lookup_var (dataset_dict (e->ds), tokid))
817 /* It looks like a user variable.
818 (It could be a format specifier, but we'll assume
819 it's a variable unless proven otherwise. */
820 return allocate_unary_variable (e, parse_variable (dataset_dict (e->ds)));
824 /* Try to parse it as a format specifier. */
829 ok = parse_format_specifier (&fmt);
833 return expr_allocate_format (e, &fmt);
835 /* All attempts failed. */
836 msg (SE, _("Unknown identifier %s."), tokid);
844 union any_node *node = expr_allocate_number (e, tokval);
851 union any_node *node = expr_allocate_string_buffer (
852 e, ds_cstr (&tokstr), ds_length (&tokstr));
859 union any_node *node;
862 if (node != NULL && !lex_match (')'))
864 lex_error (_("expecting `)'"));
871 lex_error (_("in expression"));
876 static union any_node *
877 parse_vector_element (struct expression *e)
879 const struct vector *vector;
880 union any_node *element;
882 /* Find vector, skip token.
883 The caller must already have verified that the current token
884 is the name of a vector. */
885 vector = dict_lookup_vector (dataset_dict (e->ds), tokid);
886 assert (vector != NULL);
889 /* Skip left parenthesis token.
890 The caller must have verified that the lookahead is a left
892 assert (token == '(');
895 element = parse_or (e);
896 if (!type_coercion (e, OP_number, &element, "vector indexing")
900 return expr_allocate_binary (e, (vector->var[0]->type == NUMERIC
901 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR),
902 element, expr_allocate_vector (e, vector));
905 /* Individual function parsing. */
907 const struct operation operations[OP_first + OP_cnt] = {
912 word_matches (const char **test, const char **name)
914 size_t test_len = strcspn (*test, ".");
915 size_t name_len = strcspn (*name, ".");
916 if (test_len == name_len)
918 if (buf_compare_case (*test, *name, test_len))
921 else if (test_len < 3 || test_len > name_len)
925 if (buf_compare_case (*test, *name, test_len))
931 if (**test != **name)
943 compare_names (const char *test, const char *name)
947 if (!word_matches (&test, &name))
949 if (*name == '\0' && *test == '\0')
955 compare_strings (const char *test, const char *name)
957 return strcasecmp (test, name);
961 lookup_function_helper (const char *name,
962 int (*compare) (const char *test, const char *name),
963 const struct operation **first,
964 const struct operation **last)
966 const struct operation *f;
968 for (f = operations + OP_function_first;
969 f <= operations + OP_function_last; f++)
970 if (!compare (name, f->name))
974 while (f <= operations + OP_function_last && !compare (name, f->name))
985 lookup_function (const char *name,
986 const struct operation **first,
987 const struct operation **last)
989 *first = *last = NULL;
990 return (lookup_function_helper (name, compare_strings, first, last)
991 || lookup_function_helper (name, compare_names, first, last));
995 extract_min_valid (char *s)
997 char *p = strrchr (s, '.');
999 || p[1] < '0' || p[1] > '9'
1000 || strspn (p + 1, "0123456789") != strlen (p + 1))
1003 return atoi (p + 1);
1007 function_arg_type (const struct operation *f, size_t arg_idx)
1009 assert (arg_idx < f->arg_cnt || (f->flags & OPF_ARRAY_OPERAND));
1011 return f->args[arg_idx < f->arg_cnt ? arg_idx : f->arg_cnt - 1];
1015 match_function (union any_node **args, int arg_cnt, const struct operation *f)
1019 if (arg_cnt < f->arg_cnt
1020 || (arg_cnt > f->arg_cnt && (f->flags & OPF_ARRAY_OPERAND) == 0)
1021 || arg_cnt - (f->arg_cnt - 1) < f->array_min_elems)
1024 for (i = 0; i < arg_cnt; i++)
1025 if (!is_coercible (function_arg_type (f, i), &args[i]))
1032 coerce_function_args (struct expression *e, const struct operation *f,
1033 union any_node **args, size_t arg_cnt)
1037 for (i = 0; i < arg_cnt; i++)
1038 type_coercion_assert (e, function_arg_type (f, i), &args[i]);
1042 validate_function_args (const struct operation *f, int arg_cnt, int min_valid)
1044 int array_arg_cnt = arg_cnt - (f->arg_cnt - 1);
1045 if (array_arg_cnt < f->array_min_elems)
1047 msg (SE, _("%s must have at least %d arguments in list."),
1048 f->prototype, f->array_min_elems);
1052 if ((f->flags & OPF_ARRAY_OPERAND)
1053 && array_arg_cnt % f->array_granularity != 0)
1055 if (f->array_granularity == 2)
1056 msg (SE, _("%s must have even number of arguments in list."),
1059 msg (SE, _("%s must have multiple of %d arguments in list."),
1060 f->prototype, f->array_granularity);
1064 if (min_valid != -1)
1066 if (f->array_min_elems == 0)
1068 assert ((f->flags & OPF_MIN_VALID) == 0);
1069 msg (SE, _("%s function does not accept a minimum valid "
1070 "argument count."), f->prototype);
1075 assert (f->flags & OPF_MIN_VALID);
1076 if (array_arg_cnt < f->array_min_elems)
1078 msg (SE, _("%s requires at least %d valid arguments in list."),
1079 f->prototype, f->array_min_elems);
1082 else if (min_valid > array_arg_cnt)
1084 msg (SE, _("With %s, "
1085 "using minimum valid argument count of %d "
1086 "does not make sense when passing only %d "
1087 "arguments in list."),
1088 f->prototype, min_valid, array_arg_cnt);
1098 add_arg (union any_node ***args, int *arg_cnt, int *arg_cap,
1099 union any_node *arg)
1101 if (*arg_cnt >= *arg_cap)
1104 *args = xrealloc (*args, sizeof **args * *arg_cap);
1107 (*args)[(*arg_cnt)++] = arg;
1111 put_invocation (struct string *s,
1112 const char *func_name, union any_node **args, size_t arg_cnt)
1116 ds_put_format (s, "%s(", func_name);
1117 for (i = 0; i < arg_cnt; i++)
1120 ds_put_cstr (s, ", ");
1121 ds_put_cstr (s, operations[expr_node_returns (args[i])].prototype);
1123 ds_put_char (s, ')');
1127 no_match (const char *func_name,
1128 union any_node **args, size_t arg_cnt,
1129 const struct operation *first, const struct operation *last)
1132 const struct operation *f;
1136 if (last - first == 1)
1138 ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1139 put_invocation (&s, func_name, args, arg_cnt);
1143 ds_put_cstr (&s, _("Function invocation "));
1144 put_invocation (&s, func_name, args, arg_cnt);
1145 ds_put_cstr (&s, _(" does not match any known function. Candidates are:"));
1147 for (f = first; f < last; f++)
1148 ds_put_format (&s, "\n%s", f->prototype);
1150 ds_put_char (&s, '.');
1152 msg (SE, "%s", ds_cstr (&s));
1157 static union any_node *
1158 parse_function (struct expression *e)
1161 const struct operation *f, *first, *last;
1163 union any_node **args = NULL;
1167 struct string func_name;
1171 ds_init_string (&func_name, &tokstr);
1172 min_valid = extract_min_valid (ds_cstr (&tokstr));
1173 if (!lookup_function (ds_cstr (&tokstr), &first, &last))
1175 msg (SE, _("No function or vector named %s."), ds_cstr (&tokstr));
1176 ds_destroy (&func_name);
1181 if (!lex_force_match ('('))
1183 ds_destroy (&func_name);
1188 arg_cnt = arg_cap = 0;
1192 if (token == T_ID && lex_look_ahead () == 'T')
1194 struct variable **vars;
1198 if (!parse_variables (dataset_dict (e->ds), &vars, &var_cnt, PV_SINGLE))
1200 for (i = 0; i < var_cnt; i++)
1201 add_arg (&args, &arg_cnt, &arg_cap,
1202 allocate_unary_variable (e, vars[i]));
1207 union any_node *arg = parse_or (e);
1211 add_arg (&args, &arg_cnt, &arg_cap, arg);
1213 if (lex_match (')'))
1215 else if (!lex_match (','))
1217 lex_error (_("expecting `,' or `)' invoking %s function"),
1223 for (f = first; f < last; f++)
1224 if (match_function (args, arg_cnt, f))
1228 no_match (ds_cstr (&func_name), args, arg_cnt, first, last);
1232 coerce_function_args (e, f, args, arg_cnt);
1233 if (!validate_function_args (f, arg_cnt, min_valid))
1236 if ((f->flags & OPF_EXTENSION) && get_syntax () == COMPATIBLE)
1237 msg (SW, _("%s is a PSPP extension."), f->prototype);
1238 if (f->flags & OPF_UNIMPLEMENTED)
1240 msg (SE, _("%s is not yet implemented."), f->prototype);
1243 if ((f->flags & OPF_PERM_ONLY) &&
1244 proc_in_temporary_transformations (e->ds))
1246 msg (SE, _("%s may not appear after TEMPORARY."), f->prototype);
1250 n = expr_allocate_composite (e, f - operations, args, arg_cnt);
1251 n->composite.min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1253 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1255 if (dataset_n_lag (e->ds) < 1)
1256 dataset_set_n_lag (e->ds, 1);
1258 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1261 assert (n->composite.arg_cnt == 2);
1262 assert (n->composite.args[1]->type == OP_pos_int);
1263 n_before = n->composite.args[1]->integer.i;
1264 if ( dataset_n_lag (e->ds) < n_before)
1265 dataset_set_n_lag (e->ds, n_before);
1269 ds_destroy (&func_name);
1274 ds_destroy (&func_name);
1278 /* Utility functions. */
1280 static struct expression *
1281 expr_create (struct dataset *ds)
1283 struct pool *pool = pool_create ();
1284 struct expression *e = pool_alloc (pool, sizeof *e);
1285 e->expr_pool = pool;
1287 e->eval_pool = pool_create_subpool (e->expr_pool);
1290 e->op_cnt = e->op_cap = 0;
1295 expr_node_returns (const union any_node *n)
1298 assert (is_operation (n->type));
1299 if (is_atom (n->type))
1301 else if (is_composite (n->type))
1302 return operations[n->type].returns;
1308 atom_type_name (atom_type type)
1310 assert (is_atom (type));
1311 return operations[type].name;
1315 expr_allocate_nullary (struct expression *e, operation_type op)
1317 return expr_allocate_composite (e, op, NULL, 0);
1321 expr_allocate_unary (struct expression *e, operation_type op,
1322 union any_node *arg0)
1324 return expr_allocate_composite (e, op, &arg0, 1);
1328 expr_allocate_binary (struct expression *e, operation_type op,
1329 union any_node *arg0, union any_node *arg1)
1331 union any_node *args[2];
1334 return expr_allocate_composite (e, op, args, 2);
1338 is_valid_node (union any_node *n)
1340 const struct operation *op;
1344 assert (is_operation (n->type));
1345 op = &operations[n->type];
1347 if (!is_atom (n->type))
1349 struct composite_node *c = &n->composite;
1351 assert (is_composite (n->type));
1352 assert (c->arg_cnt >= op->arg_cnt);
1353 for (i = 0; i < op->arg_cnt; i++)
1354 assert (expr_node_returns (c->args[i]) == op->args[i]);
1355 if (c->arg_cnt > op->arg_cnt && !is_operator (n->type))
1357 assert (op->flags & OPF_ARRAY_OPERAND);
1358 for (i = 0; i < c->arg_cnt; i++)
1359 assert (operations[c->args[i]->type].returns
1360 == op->args[op->arg_cnt - 1]);
1368 expr_allocate_composite (struct expression *e, operation_type op,
1369 union any_node **args, size_t arg_cnt)
1374 n = pool_alloc (e->expr_pool, sizeof n->composite);
1376 n->composite.arg_cnt = arg_cnt;
1377 n->composite.args = pool_alloc (e->expr_pool,
1378 sizeof *n->composite.args * arg_cnt);
1379 for (i = 0; i < arg_cnt; i++)
1381 if (args[i] == NULL)
1383 n->composite.args[i] = args[i];
1385 memcpy (n->composite.args, args, sizeof *n->composite.args * arg_cnt);
1386 n->composite.min_valid = 0;
1387 assert (is_valid_node (n));
1392 expr_allocate_number (struct expression *e, double d)
1394 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1395 n->type = OP_number;
1401 expr_allocate_boolean (struct expression *e, double b)
1403 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1404 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1405 n->type = OP_boolean;
1411 expr_allocate_integer (struct expression *e, int i)
1413 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1414 n->type = OP_integer;
1420 expr_allocate_pos_int (struct expression *e, int i)
1422 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1424 n->type = OP_pos_int;
1430 expr_allocate_vector (struct expression *e, const struct vector *vector)
1432 union any_node *n = pool_alloc (e->expr_pool, sizeof n->vector);
1433 n->type = OP_vector;
1434 n->vector.v = vector;
1439 expr_allocate_string_buffer (struct expression *e,
1440 const char *string, size_t length)
1442 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1443 n->type = OP_string;
1444 if (length > MAX_STRING)
1445 length = MAX_STRING;
1446 n->string.s = copy_string (e, string, length);
1451 expr_allocate_string (struct expression *e, struct substring s)
1453 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1454 n->type = OP_string;
1460 expr_allocate_variable (struct expression *e, struct variable *v)
1462 union any_node *n = pool_alloc (e->expr_pool, sizeof n->variable);
1463 n->type = v->type == NUMERIC ? OP_num_var : OP_str_var;
1469 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1471 union any_node *n = pool_alloc (e->expr_pool, sizeof n->format);
1472 n->type = OP_format;
1473 n->format.f = *format;
1477 /* Allocates a unary composite node that represents the value of
1478 variable V in expression E. */
1479 static union any_node *
1480 allocate_unary_variable (struct expression *e, struct variable *v)
1483 return expr_allocate_unary (e, v->type == NUMERIC ? OP_NUM_VAR : OP_STR_VAR,
1484 expr_allocate_variable (e, v));