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
26 #include <libpspp/array.h>
27 #include <libpspp/alloc.h>
28 #include <data/case.h>
29 #include <data/dictionary.h>
30 #include <libpspp/message.h>
32 #include <language/lexer/lexer.h>
33 #include <libpspp/misc.h>
34 #include <libpspp/pool.h>
35 #include <data/settings.h>
36 #include <libpspp/str.h>
37 #include <data/variable.h>
41 /* Recursive descent parser in order of increasing precedence. */
42 typedef union any_node *parse_recursively_func (struct expression *);
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;
47 static parse_recursively_func parse_vector_element, parse_function;
49 /* Utility functions. */
50 static struct expression *expr_create (struct dictionary *);
51 atom_type expr_node_returns (const union any_node *);
53 static const char *atom_type_name (atom_type);
54 static struct expression *finish_expression (union any_node *,
56 static bool type_check (struct expression *, union any_node **,
57 enum expr_type expected_type);
58 static union any_node *allocate_unary_variable (struct expression *,
61 /* Public functions. */
63 /* Parses an expression of the given TYPE.
64 If DICT is nonnull then variables and vectors within it may be
65 referenced within the expression; otherwise, the expression
66 must not reference any variables or vectors.
67 Returns the new expression if successful or a null pointer
70 expr_parse (struct dictionary *dict, enum expr_type type)
75 assert (type == EXPR_NUMBER || type == EXPR_STRING || type == EXPR_BOOLEAN);
77 e = expr_create (dict);
79 if (n != NULL && type_check (e, &n, type))
80 return finish_expression (expr_optimize (n, e), e);
88 /* Parses and returns an expression of the given TYPE, as
89 expr_parse(), and sets up so that destroying POOL will free
90 the expression as well. */
92 expr_parse_pool (struct pool *pool,
93 struct dictionary *dict, enum expr_type type)
95 struct expression *e = expr_parse (dict, type);
97 pool_add_subpool (pool, e->expr_pool);
101 /* Free expression E. */
103 expr_free (struct expression *e)
106 pool_destroy (e->expr_pool);
110 expr_parse_any (struct dictionary *dict, bool optimize)
113 struct expression *e;
115 e = expr_create (dict);
124 n = expr_optimize (n, e);
125 return finish_expression (n, e);
128 /* Finishing up expression building. */
130 /* Height of an expression's stacks. */
133 int number_height; /* Height of number stack. */
134 int string_height; /* Height of string stack. */
137 /* Stack heights used by different kinds of arguments. */
138 static const struct stack_heights on_number_stack = {1, 0};
139 static const struct stack_heights on_string_stack = {0, 1};
140 static const struct stack_heights not_on_stack = {0, 0};
142 /* Returns the stack heights used by an atom of the given
144 static const struct stack_heights *
145 atom_type_stack (atom_type type)
147 assert (is_atom (type));
153 return &on_number_stack;
156 return &on_string_stack;
166 return ¬_on_stack;
173 /* Measures the stack height needed for node N, supposing that
174 the stack height is initially *HEIGHT and updating *HEIGHT to
175 the final stack height. Updates *MAX, if necessary, to
176 reflect the maximum intermediate or final height. */
178 measure_stack (const union any_node *n,
179 struct stack_heights *height, struct stack_heights *max)
181 const struct stack_heights *return_height;
183 if (is_composite (n->type))
185 struct stack_heights args;
189 for (i = 0; i < n->composite.arg_cnt; i++)
190 measure_stack (n->composite.args[i], &args, max);
192 return_height = atom_type_stack (operations[n->type].returns);
195 return_height = atom_type_stack (n->type);
197 height->number_height += return_height->number_height;
198 height->string_height += return_height->string_height;
200 if (height->number_height > max->number_height)
201 max->number_height = height->number_height;
202 if (height->string_height > max->string_height)
203 max->string_height = height->string_height;
206 /* Allocates stacks within E sufficient for evaluating node N. */
208 allocate_stacks (union any_node *n, struct expression *e)
210 struct stack_heights initial = {0, 0};
211 struct stack_heights max = {0, 0};
213 measure_stack (n, &initial, &max);
214 e->number_stack = pool_alloc (e->expr_pool,
215 sizeof *e->number_stack * max.number_height);
216 e->string_stack = pool_alloc (e->expr_pool,
217 sizeof *e->string_stack * max.string_height);
220 /* Finalizes expression E for evaluating node N. */
221 static struct expression *
222 finish_expression (union any_node *n, struct expression *e)
224 /* Allocate stacks. */
225 allocate_stacks (n, e);
227 /* Output postfix representation. */
230 /* The eval_pool might have been used for allocating strings
231 during optimization. We need to keep those strings around
232 for all subsequent evaluations, so start a new eval_pool. */
233 e->eval_pool = pool_create_subpool (e->expr_pool);
238 /* Verifies that expression E, whose root node is *N, can be
239 converted to type EXPECTED_TYPE, inserting a conversion at *N
240 if necessary. Returns true if successful, false on failure. */
242 type_check (struct expression *e,
243 union any_node **n, enum expr_type expected_type)
245 atom_type actual_type = expr_node_returns (*n);
247 switch (expected_type)
251 if (actual_type != OP_number && actual_type != OP_boolean)
253 msg (SE, _("Type mismatch: expression has %s type, "
254 "but a numeric value is required here."),
255 atom_type_name (actual_type));
258 if (actual_type == OP_number && expected_type == OP_boolean)
259 *n = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *n);
263 if (actual_type != OP_string)
265 msg (SE, _("Type mismatch: expression has %s type, "
266 "but a string value is required here."),
267 atom_type_name (actual_type));
279 /* Recursive-descent expression parser. */
281 /* Considers whether *NODE may be coerced to type REQUIRED_TYPE.
282 Returns true if possible, false if disallowed.
284 If DO_COERCION is false, then *NODE is not modified and there
287 If DO_COERCION is true, we perform the coercion if possible,
288 modifying *NODE if necessary. If the coercion is not possible
289 then we free *NODE and set *NODE to a null pointer.
291 This function's interface is somewhat awkward. Use one of the
292 wrapper functions type_coercion(), type_coercion_assert(), or
293 is_coercible() instead. */
295 type_coercion_core (struct expression *e,
296 atom_type required_type,
297 union any_node **node,
298 const char *operator_name,
301 atom_type actual_type;
303 assert (!!do_coercion == (e != NULL));
306 /* Propagate error. Whatever caused the original error
307 already emitted an error message. */
311 actual_type = expr_node_returns (*node);
312 if (actual_type == required_type)
318 switch (required_type)
321 if (actual_type == OP_boolean)
323 /* To enforce strict typing rules, insert Boolean to
324 numeric "conversion". This conversion is a no-op,
325 so it will be removed later. */
327 *node = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, *node);
333 /* No coercion to string. */
337 if (actual_type == OP_number)
339 /* Convert numeric to boolean. */
341 *node = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *node);
350 if ((*node)->type == OP_format
351 && check_input_specifier (&(*node)->format.f, false)
352 && check_specifier_type (&(*node)->format.f, NUMERIC, false))
355 (*node)->type = OP_ni_format;
361 if ((*node)->type == OP_format
362 && check_output_specifier (&(*node)->format.f, false)
363 && check_specifier_type (&(*node)->format.f, NUMERIC, false))
366 (*node)->type = OP_no_format;
372 if ((*node)->type == OP_NUM_VAR)
375 *node = (*node)->composite.args[0];
381 if ((*node)->type == OP_STR_VAR)
384 *node = (*node)->composite.args[0];
390 if ((*node)->type == OP_number
391 && floor ((*node)->number.n) == (*node)->number.n
392 && (*node)->number.n > 0 && (*node)->number.n < INT_MAX)
395 *node = expr_allocate_pos_int (e, (*node)->number.n);
406 msg (SE, _("Type mismatch while applying %s operator: "
407 "cannot convert %s to %s."),
409 atom_type_name (actual_type), atom_type_name (required_type));
415 /* Coerces *NODE to type REQUIRED_TYPE, and returns success. If
416 *NODE cannot be coerced to the desired type then we issue an
417 error message about operator OPERATOR_NAME and free *NODE. */
419 type_coercion (struct expression *e,
420 atom_type required_type, union any_node **node,
421 const char *operator_name)
423 return type_coercion_core (e, required_type, node, operator_name, true);
426 /* Coerces *NODE to type REQUIRED_TYPE.
427 Assert-fails if the coercion is disallowed. */
429 type_coercion_assert (struct expression *e,
430 atom_type required_type, union any_node **node)
432 int success = type_coercion_core (e, required_type, node, NULL, true);
436 /* Returns true if *NODE may be coerced to type REQUIRED_TYPE,
439 is_coercible (atom_type required_type, union any_node *const *node)
441 return type_coercion_core (NULL, required_type,
442 (union any_node **) node, NULL, false);
445 /* How to parse an operator. */
448 int token; /* Token representing operator. */
449 operation_type type; /* Operation type representing operation. */
450 const char *name; /* Name of operator. */
453 /* Attempts to match the current token against the tokens for the
454 OP_CNT operators in OPS[]. If successful, returns true
455 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
456 On failure, returns false and, if OPERATOR is non-null, sets
457 *OPERATOR to a null pointer. */
459 match_operator (const struct operator ops[], size_t op_cnt,
460 const struct operator **operator)
462 const struct operator *op;
464 for (op = ops; op < ops + op_cnt; op++)
466 if (op->token == '-')
467 lex_negative_to_dash ();
468 if (lex_match (op->token))
470 if (operator != NULL)
475 if (operator != NULL)
481 check_operator (const struct operator *op, int arg_cnt, atom_type arg_type)
483 const struct operation *o;
487 o = &operations[op->type];
488 assert (o->arg_cnt == arg_cnt);
489 assert ((o->flags & OPF_ARRAY_OPERAND) == 0);
490 for (i = 0; i < arg_cnt; i++)
491 assert (o->args[i] == arg_type);
496 check_binary_operators (const struct operator ops[], size_t op_cnt,
501 for (i = 0; i < op_cnt; i++)
502 check_operator (&ops[i], 2, arg_type);
507 get_operand_type (const struct operator *op)
509 return operations[op->type].args[0];
512 /* Parses a chain of left-associative operator/operand pairs.
513 There are OP_CNT operators, specified in OPS[]. The
514 operators' operands must all be the same type. The next
515 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
516 is non-null, then it will be issued as a warning if more than
517 one operator/operand pair is parsed. */
518 static union any_node *
519 parse_binary_operators (struct expression *e, union any_node *node,
520 const struct operator ops[], size_t op_cnt,
521 parse_recursively_func *parse_next_level,
522 const char *chain_warning)
524 atom_type operand_type = get_operand_type (&ops[0]);
526 const struct operator *operator;
528 assert (check_binary_operators (ops, op_cnt, operand_type));
532 for (op_count = 0; match_operator (ops, op_cnt, &operator); op_count++)
536 /* Convert the left-hand side to type OPERAND_TYPE. */
537 if (!type_coercion (e, operand_type, &node, operator->name))
540 /* Parse the right-hand side and coerce to type
542 rhs = parse_next_level (e);
543 if (!type_coercion (e, operand_type, &rhs, operator->name))
545 node = expr_allocate_binary (e, operator->type, node, rhs);
548 if (op_count > 1 && chain_warning != NULL)
549 msg (SW, chain_warning);
554 static union any_node *
555 parse_inverting_unary_operator (struct expression *e,
556 const struct operator *op,
557 parse_recursively_func *parse_next_level)
559 union any_node *node;
562 check_operator (op, 1, get_operand_type (op));
565 while (match_operator (op, 1, NULL))
568 node = parse_next_level (e);
570 && type_coercion (e, get_operand_type (op), &node, op->name)
571 && op_count % 2 != 0)
572 return expr_allocate_unary (e, op->type, node);
577 /* Parses the OR level. */
578 static union any_node *
579 parse_or (struct expression *e)
581 static const struct operator op =
582 { T_OR, OP_OR, "logical disjunction (\"OR\")" };
584 return parse_binary_operators (e, parse_and (e), &op, 1, parse_and, NULL);
587 /* Parses the AND level. */
588 static union any_node *
589 parse_and (struct expression *e)
591 static const struct operator op =
592 { T_AND, OP_AND, "logical conjunction (\"AND\")" };
594 return parse_binary_operators (e, parse_not (e), &op, 1, parse_not, NULL);
597 /* Parses the NOT level. */
598 static union any_node *
599 parse_not (struct expression *e)
601 static const struct operator op
602 = { T_NOT, OP_NOT, "logical negation (\"NOT\")" };
603 return parse_inverting_unary_operator (e, &op, parse_rel);
606 /* Parse relational operators. */
607 static union any_node *
608 parse_rel (struct expression *e)
610 const char *chain_warning =
611 _("Chaining relational operators (e.g. \"a < b < c\") will "
612 "not produce the mathematically expected result. "
613 "Use the AND logical operator to fix the problem "
614 "(e.g. \"a < b AND b < c\"). "
615 "If chaining is really intended, parentheses will disable "
616 "this warning (e.g. \"(a < b) < c\".)");
618 union any_node *node = parse_add (e);
623 switch (expr_node_returns (node))
628 static const struct operator ops[] =
630 { '=', OP_EQ, "numeric equality (\"=\")" },
631 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
632 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
633 { T_GT, OP_GT, "numeric greater than (\">\")" },
634 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
635 { T_LT, OP_LT, "numeric less than (\"<\")" },
636 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
639 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
640 parse_add, chain_warning);
645 static const struct operator ops[] =
647 { '=', OP_EQ_STRING, "string equality (\"=\")" },
648 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
649 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
650 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
651 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
652 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
653 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
656 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
657 parse_add, chain_warning);
665 /* Parses the addition and subtraction level. */
666 static union any_node *
667 parse_add (struct expression *e)
669 static const struct operator ops[] =
671 { '+', OP_ADD, "addition (\"+\")" },
672 { '-', OP_SUB, "subtraction (\"-\")" },
675 return parse_binary_operators (e, parse_mul (e),
676 ops, sizeof ops / sizeof *ops,
680 /* Parses the multiplication and division level. */
681 static union any_node *
682 parse_mul (struct expression *e)
684 static const struct operator ops[] =
686 { '*', OP_MUL, "multiplication (\"*\")" },
687 { '/', OP_DIV, "division (\"/\")" },
690 return parse_binary_operators (e, parse_neg (e),
691 ops, sizeof ops / sizeof *ops,
695 /* Parses the unary minus level. */
696 static union any_node *
697 parse_neg (struct expression *e)
699 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
700 return parse_inverting_unary_operator (e, &op, parse_exp);
703 static union any_node *
704 parse_exp (struct expression *e)
706 static const struct operator op =
707 { T_EXP, OP_POW, "exponentiation (\"**\")" };
709 const char *chain_warning =
710 _("The exponentiation operator (\"**\") is left-associative, "
711 "even though right-associative semantics are more useful. "
712 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
713 "To disable this warning, insert parentheses.");
715 return parse_binary_operators (e, parse_primary (e), &op, 1,
716 parse_primary, chain_warning);
719 /* Parses system variables. */
720 static union any_node *
721 parse_sysvar (struct expression *e)
723 if (lex_match_id ("$CASENUM"))
724 return expr_allocate_nullary (e, OP_CASENUM);
725 else if (lex_match_id ("$DATE"))
727 static const char *months[12] =
729 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
730 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
733 time_t last_proc_time = time_of_last_procedure ();
737 time = localtime (&last_proc_time);
738 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
739 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
741 return expr_allocate_string_buffer (e, temp_buf, strlen (temp_buf));
743 else if (lex_match_id ("$TRUE"))
744 return expr_allocate_boolean (e, 1.0);
745 else if (lex_match_id ("$FALSE"))
746 return expr_allocate_boolean (e, 0.0);
747 else if (lex_match_id ("$SYSMIS"))
748 return expr_allocate_number (e, SYSMIS);
749 else if (lex_match_id ("$JDATE"))
751 time_t time = time_of_last_procedure ();
752 struct tm *tm = localtime (&time);
753 return expr_allocate_number (e, expr_ymd_to_ofs (tm->tm_year + 1900,
757 else if (lex_match_id ("$TIME"))
759 time_t time = time_of_last_procedure ();
760 struct tm *tm = localtime (&time);
761 return expr_allocate_number (e,
762 expr_ymd_to_date (tm->tm_year + 1900,
765 + tm->tm_hour * 60 * 60.
769 else if (lex_match_id ("$LENGTH"))
770 return expr_allocate_number (e, get_viewlength ());
771 else if (lex_match_id ("$WIDTH"))
772 return expr_allocate_number (e, get_viewwidth ());
775 msg (SE, _("Unknown system variable %s."), tokid);
780 /* Parses numbers, varnames, etc. */
781 static union any_node *
782 parse_primary (struct expression *e)
787 if (lex_look_ahead () == '(')
789 /* An identifier followed by a left parenthesis may be
790 a vector element reference. If not, it's a function
792 if (e->dict != NULL && dict_lookup_vector (e->dict, tokid) != NULL)
793 return parse_vector_element (e);
795 return parse_function (e);
797 else if (tokid[0] == '$')
799 /* $ at the beginning indicates a system variable. */
800 return parse_sysvar (e);
802 else if (e->dict != NULL && dict_lookup_var (e->dict, tokid))
804 /* It looks like a user variable.
805 (It could be a format specifier, but we'll assume
806 it's a variable unless proven otherwise. */
807 return allocate_unary_variable (e, parse_dict_variable (e->dict));
811 /* Try to parse it as a format specifier. */
813 if (parse_format_specifier (&fmt, FMTP_SUPPRESS_ERRORS))
814 return expr_allocate_format (e, &fmt);
816 /* All attempts failed. */
817 msg (SE, _("Unknown identifier %s."), tokid);
825 union any_node *node = expr_allocate_number (e, tokval);
832 union any_node *node = expr_allocate_string_buffer (e, ds_c_str (&tokstr),
833 ds_length (&tokstr));
840 union any_node *node;
843 if (node != NULL && !lex_match (')'))
845 lex_error (_("expecting `)'"));
852 lex_error (_("in expression"));
857 static union any_node *
858 parse_vector_element (struct expression *e)
860 const struct vector *vector;
861 union any_node *element;
863 /* Find vector, skip token.
864 The caller must already have verified that the current token
865 is the name of a vector. */
866 vector = dict_lookup_vector (default_dict, tokid);
867 assert (vector != NULL);
870 /* Skip left parenthesis token.
871 The caller must have verified that the lookahead is a left
873 assert (token == '(');
876 element = parse_or (e);
877 if (!type_coercion (e, OP_number, &element, "vector indexing")
881 return expr_allocate_binary (e, (vector->var[0]->type == NUMERIC
882 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR),
883 element, expr_allocate_vector (e, vector));
886 /* Individual function parsing. */
888 struct operation operations[OP_first + OP_cnt] = {
893 word_matches (const char **test, const char **name)
895 size_t test_len = strcspn (*test, ".");
896 size_t name_len = strcspn (*name, ".");
897 if (test_len == name_len)
899 if (buf_compare_case (*test, *name, test_len))
902 else if (test_len < 3 || test_len > name_len)
906 if (buf_compare_case (*test, *name, test_len))
912 if (**test != **name)
924 compare_names (const char *test, const char *name)
928 if (!word_matches (&test, &name))
930 if (*name == '\0' && *test == '\0')
936 compare_strings (const char *test, const char *name)
938 return strcasecmp (test, name);
942 lookup_function_helper (const char *name,
943 int (*compare) (const char *test, const char *name),
944 const struct operation **first,
945 const struct operation **last)
949 for (f = operations + OP_function_first;
950 f <= operations + OP_function_last; f++)
951 if (!compare (name, f->name))
955 while (f <= operations + OP_function_last && !compare (name, f->name))
966 lookup_function (const char *name,
967 const struct operation **first,
968 const struct operation **last)
970 *first = *last = NULL;
971 return (lookup_function_helper (name, compare_strings, first, last)
972 || lookup_function_helper (name, compare_names, first, last));
976 extract_min_valid (char *s)
978 char *p = strrchr (s, '.');
980 || p[1] < '0' || p[1] > '9'
981 || strspn (p + 1, "0123456789") != strlen (p + 1))
988 function_arg_type (const struct operation *f, size_t arg_idx)
990 assert (arg_idx < f->arg_cnt || (f->flags & OPF_ARRAY_OPERAND));
992 return f->args[arg_idx < f->arg_cnt ? arg_idx : f->arg_cnt - 1];
996 match_function (union any_node **args, int arg_cnt, const struct operation *f)
1000 if (arg_cnt < f->arg_cnt
1001 || (arg_cnt > f->arg_cnt && (f->flags & OPF_ARRAY_OPERAND) == 0)
1002 || arg_cnt - (f->arg_cnt - 1) < f->array_min_elems)
1005 for (i = 0; i < arg_cnt; i++)
1006 if (!is_coercible (function_arg_type (f, i), &args[i]))
1013 coerce_function_args (struct expression *e, const struct operation *f,
1014 union any_node **args, size_t arg_cnt)
1018 for (i = 0; i < arg_cnt; i++)
1019 type_coercion_assert (e, function_arg_type (f, i), &args[i]);
1023 validate_function_args (const struct operation *f, int arg_cnt, int min_valid)
1025 int array_arg_cnt = arg_cnt - (f->arg_cnt - 1);
1026 if (array_arg_cnt < f->array_min_elems)
1028 msg (SE, _("%s must have at least %d arguments in list."),
1029 f->prototype, f->array_min_elems);
1033 if ((f->flags & OPF_ARRAY_OPERAND)
1034 && array_arg_cnt % f->array_granularity != 0)
1036 if (f->array_granularity == 2)
1037 msg (SE, _("%s must have even number of arguments in list."),
1040 msg (SE, _("%s must have multiple of %d arguments in list."),
1041 f->prototype, f->array_granularity);
1045 if (min_valid != -1)
1047 if (f->array_min_elems == 0)
1049 assert ((f->flags & OPF_MIN_VALID) == 0);
1050 msg (SE, _("%s function does not accept a minimum valid "
1051 "argument count."), f->prototype);
1056 assert (f->flags & OPF_MIN_VALID);
1057 if (array_arg_cnt < f->array_min_elems)
1059 msg (SE, _("%s requires at least %d valid arguments in list."),
1060 f->prototype, f->array_min_elems);
1063 else if (min_valid > array_arg_cnt)
1065 msg (SE, _("With %s, "
1066 "using minimum valid argument count of %d "
1067 "does not make sense when passing only %d "
1068 "arguments in list."),
1069 f->prototype, min_valid, array_arg_cnt);
1079 add_arg (union any_node ***args, int *arg_cnt, int *arg_cap,
1080 union any_node *arg)
1082 if (*arg_cnt >= *arg_cap)
1085 *args = xrealloc (*args, sizeof **args * *arg_cap);
1088 (*args)[(*arg_cnt)++] = arg;
1092 put_invocation (struct string *s,
1093 const char *func_name, union any_node **args, size_t arg_cnt)
1097 ds_printf (s, "%s(", func_name);
1098 for (i = 0; i < arg_cnt; i++)
1102 ds_puts (s, operations[expr_node_returns (args[i])].prototype);
1108 no_match (const char *func_name,
1109 union any_node **args, size_t arg_cnt,
1110 const struct operation *first, const struct operation *last)
1113 const struct operation *f;
1117 if (last - first == 1)
1119 ds_printf (&s, _("Type mismatch invoking %s as "), first->prototype);
1120 put_invocation (&s, func_name, args, arg_cnt);
1124 ds_puts (&s, _("Function invocation "));
1125 put_invocation (&s, func_name, args, arg_cnt);
1126 ds_puts (&s, _(" does not match any known function. Candidates are:"));
1128 for (f = first; f < last; f++)
1129 ds_printf (&s, "\n%s", f->prototype);
1133 msg (SE, "%s", ds_c_str (&s));
1138 static union any_node *
1139 parse_function (struct expression *e)
1142 const struct operation *f, *first, *last;
1144 union any_node **args = NULL;
1148 struct fixed_string func_name;
1152 ls_create (&func_name, ds_c_str (&tokstr));
1153 min_valid = extract_min_valid (ds_c_str (&tokstr));
1154 if (!lookup_function (ds_c_str (&tokstr), &first, &last))
1156 msg (SE, _("No function or vector named %s."), ds_c_str (&tokstr));
1157 ls_destroy (&func_name);
1162 if (!lex_force_match ('('))
1164 ls_destroy (&func_name);
1169 arg_cnt = arg_cap = 0;
1173 if (token == T_ID && lex_look_ahead () == 'T')
1175 struct variable **vars;
1179 if (!parse_variables (default_dict, &vars, &var_cnt, PV_SINGLE))
1181 for (i = 0; i < var_cnt; i++)
1182 add_arg (&args, &arg_cnt, &arg_cap,
1183 allocate_unary_variable (e, vars[i]));
1188 union any_node *arg = parse_or (e);
1192 add_arg (&args, &arg_cnt, &arg_cap, arg);
1194 if (lex_match (')'))
1196 else if (!lex_match (','))
1198 lex_error (_("expecting `,' or `)' invoking %s function"),
1204 for (f = first; f < last; f++)
1205 if (match_function (args, arg_cnt, f))
1209 no_match (ls_c_str (&func_name), args, arg_cnt, first, last);
1213 coerce_function_args (e, f, args, arg_cnt);
1214 if (!validate_function_args (f, arg_cnt, min_valid))
1217 if ((f->flags & OPF_EXTENSION) && get_syntax () == COMPATIBLE)
1218 msg (SW, _("%s is a PSPP extension."), f->prototype);
1219 if (f->flags & OPF_UNIMPLEMENTED)
1221 msg (SE, _("%s is not yet implemented."), f->prototype);
1224 if ((f->flags & OPF_PERM_ONLY) && proc_in_temporary_transformations ())
1226 msg (SE, _("%s may not appear after TEMPORARY."), f->prototype);
1230 n = expr_allocate_composite (e, f - operations, args, arg_cnt);
1231 n->composite.min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1233 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1238 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1241 assert (n->composite.arg_cnt == 2);
1242 assert (n->composite.args[1]->type == OP_pos_int);
1243 n_before = n->composite.args[1]->integer.i;
1244 if (n_lag < n_before)
1249 ls_destroy (&func_name);
1254 ls_destroy (&func_name);
1258 /* Utility functions. */
1260 static struct expression *
1261 expr_create (struct dictionary *dict)
1263 struct pool *pool = pool_create ();
1264 struct expression *e = pool_alloc (pool, sizeof *e);
1265 e->expr_pool = pool;
1267 e->eval_pool = pool_create_subpool (e->expr_pool);
1270 e->op_cnt = e->op_cap = 0;
1275 expr_node_returns (const union any_node *n)
1278 assert (is_operation (n->type));
1279 if (is_atom (n->type))
1281 else if (is_composite (n->type))
1282 return operations[n->type].returns;
1288 atom_type_name (atom_type type)
1290 assert (is_atom (type));
1291 return operations[type].name;
1295 expr_allocate_nullary (struct expression *e, operation_type op)
1297 return expr_allocate_composite (e, op, NULL, 0);
1301 expr_allocate_unary (struct expression *e, operation_type op,
1302 union any_node *arg0)
1304 return expr_allocate_composite (e, op, &arg0, 1);
1308 expr_allocate_binary (struct expression *e, operation_type op,
1309 union any_node *arg0, union any_node *arg1)
1311 union any_node *args[2];
1314 return expr_allocate_composite (e, op, args, 2);
1318 is_valid_node (union any_node *n)
1320 struct operation *op;
1324 assert (is_operation (n->type));
1325 op = &operations[n->type];
1327 if (!is_atom (n->type))
1329 struct composite_node *c = &n->composite;
1331 assert (is_composite (n->type));
1332 assert (c->arg_cnt >= op->arg_cnt);
1333 for (i = 0; i < op->arg_cnt; i++)
1334 assert (expr_node_returns (c->args[i]) == op->args[i]);
1335 if (c->arg_cnt > op->arg_cnt && !is_operator (n->type))
1337 assert (op->flags & OPF_ARRAY_OPERAND);
1338 for (i = 0; i < c->arg_cnt; i++)
1339 assert (operations[c->args[i]->type].returns
1340 == op->args[op->arg_cnt - 1]);
1348 expr_allocate_composite (struct expression *e, operation_type op,
1349 union any_node **args, size_t arg_cnt)
1354 n = pool_alloc (e->expr_pool, sizeof n->composite);
1356 n->composite.arg_cnt = arg_cnt;
1357 n->composite.args = pool_alloc (e->expr_pool,
1358 sizeof *n->composite.args * arg_cnt);
1359 for (i = 0; i < arg_cnt; i++)
1361 if (args[i] == NULL)
1363 n->composite.args[i] = args[i];
1365 memcpy (n->composite.args, args, sizeof *n->composite.args * arg_cnt);
1366 n->composite.min_valid = 0;
1367 assert (is_valid_node (n));
1372 expr_allocate_number (struct expression *e, double d)
1374 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1375 n->type = OP_number;
1381 expr_allocate_boolean (struct expression *e, double b)
1383 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1384 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1385 n->type = OP_boolean;
1391 expr_allocate_integer (struct expression *e, int i)
1393 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1394 n->type = OP_integer;
1400 expr_allocate_pos_int (struct expression *e, int i)
1402 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1404 n->type = OP_pos_int;
1410 expr_allocate_vector (struct expression *e, const struct vector *vector)
1412 union any_node *n = pool_alloc (e->expr_pool, sizeof n->vector);
1413 n->type = OP_vector;
1414 n->vector.v = vector;
1419 expr_allocate_string_buffer (struct expression *e,
1420 const char *string, size_t length)
1422 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1423 n->type = OP_string;
1424 if (length > MAX_STRING)
1425 length = MAX_STRING;
1426 n->string.s = copy_string (e, string, length);
1431 expr_allocate_string (struct expression *e, struct fixed_string s)
1433 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1434 n->type = OP_string;
1440 expr_allocate_variable (struct expression *e, struct variable *v)
1442 union any_node *n = pool_alloc (e->expr_pool, sizeof n->variable);
1443 n->type = v->type == NUMERIC ? OP_num_var : OP_str_var;
1449 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1451 union any_node *n = pool_alloc (e->expr_pool, sizeof n->format);
1452 n->type = OP_format;
1453 n->format.f = *format;
1457 /* Allocates a unary composite node that represents the value of
1458 variable V in expression E. */
1459 static union any_node *
1460 allocate_unary_variable (struct expression *e, struct variable *v)
1463 return expr_allocate_unary (e, v->type == NUMERIC ? OP_NUM_VAR : OP_STR_VAR,
1464 expr_allocate_variable (e, v));