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 <language/lexer/variable-parser.h>
34 #include <libpspp/assertion.h>
35 #include <libpspp/misc.h>
36 #include <libpspp/pool.h>
37 #include <data/settings.h>
38 #include <libpspp/str.h>
39 #include <data/variable.h>
43 /* Recursive descent parser in order of increasing precedence. */
44 typedef union any_node *parse_recursively_func (struct expression *);
45 static parse_recursively_func parse_or, parse_and, parse_not;
46 static parse_recursively_func parse_rel, parse_add, parse_mul;
47 static parse_recursively_func parse_neg, parse_exp;
48 static parse_recursively_func parse_primary;
49 static parse_recursively_func parse_vector_element, parse_function;
51 /* Utility functions. */
52 static struct expression *expr_create (struct dictionary *);
53 atom_type expr_node_returns (const union any_node *);
55 static const char *atom_type_name (atom_type);
56 static struct expression *finish_expression (union any_node *,
58 static bool type_check (struct expression *, union any_node **,
59 enum expr_type expected_type);
60 static union any_node *allocate_unary_variable (struct expression *,
63 /* Public functions. */
65 /* Parses an expression of the given TYPE.
66 If DICT is nonnull then variables and vectors within it may be
67 referenced within the expression; otherwise, the expression
68 must not reference any variables or vectors.
69 Returns the new expression if successful or a null pointer
72 expr_parse (struct dictionary *dict, enum expr_type type)
77 assert (type == EXPR_NUMBER || type == EXPR_STRING || type == EXPR_BOOLEAN);
79 e = expr_create (dict);
81 if (n != NULL && type_check (e, &n, type))
82 return finish_expression (expr_optimize (n, e), e);
90 /* Parses and returns an expression of the given TYPE, as
91 expr_parse(), and sets up so that destroying POOL will free
92 the expression as well. */
94 expr_parse_pool (struct pool *pool,
95 struct dictionary *dict, enum expr_type type)
97 struct expression *e = expr_parse (dict, type);
99 pool_add_subpool (pool, e->expr_pool);
103 /* Free expression E. */
105 expr_free (struct expression *e)
108 pool_destroy (e->expr_pool);
112 expr_parse_any (struct dictionary *dict, bool optimize)
115 struct expression *e;
117 e = expr_create (dict);
126 n = expr_optimize (n, e);
127 return finish_expression (n, e);
130 /* Finishing up expression building. */
132 /* Height of an expression's stacks. */
135 int number_height; /* Height of number stack. */
136 int string_height; /* Height of string stack. */
139 /* Stack heights used by different kinds of arguments. */
140 static const struct stack_heights on_number_stack = {1, 0};
141 static const struct stack_heights on_string_stack = {0, 1};
142 static const struct stack_heights not_on_stack = {0, 0};
144 /* Returns the stack heights used by an atom of the given
146 static const struct stack_heights *
147 atom_type_stack (atom_type type)
149 assert (is_atom (type));
155 return &on_number_stack;
158 return &on_string_stack;
168 return ¬_on_stack;
175 /* Measures the stack height needed for node N, supposing that
176 the stack height is initially *HEIGHT and updating *HEIGHT to
177 the final stack height. Updates *MAX, if necessary, to
178 reflect the maximum intermediate or final height. */
180 measure_stack (const union any_node *n,
181 struct stack_heights *height, struct stack_heights *max)
183 const struct stack_heights *return_height;
185 if (is_composite (n->type))
187 struct stack_heights args;
191 for (i = 0; i < n->composite.arg_cnt; i++)
192 measure_stack (n->composite.args[i], &args, max);
194 return_height = atom_type_stack (operations[n->type].returns);
197 return_height = atom_type_stack (n->type);
199 height->number_height += return_height->number_height;
200 height->string_height += return_height->string_height;
202 if (height->number_height > max->number_height)
203 max->number_height = height->number_height;
204 if (height->string_height > max->string_height)
205 max->string_height = height->string_height;
208 /* Allocates stacks within E sufficient for evaluating node N. */
210 allocate_stacks (union any_node *n, struct expression *e)
212 struct stack_heights initial = {0, 0};
213 struct stack_heights max = {0, 0};
215 measure_stack (n, &initial, &max);
216 e->number_stack = pool_alloc (e->expr_pool,
217 sizeof *e->number_stack * max.number_height);
218 e->string_stack = pool_alloc (e->expr_pool,
219 sizeof *e->string_stack * max.string_height);
222 /* Finalizes expression E for evaluating node N. */
223 static struct expression *
224 finish_expression (union any_node *n, struct expression *e)
226 /* Allocate stacks. */
227 allocate_stacks (n, e);
229 /* Output postfix representation. */
232 /* The eval_pool might have been used for allocating strings
233 during optimization. We need to keep those strings around
234 for all subsequent evaluations, so start a new eval_pool. */
235 e->eval_pool = pool_create_subpool (e->expr_pool);
240 /* Verifies that expression E, whose root node is *N, can be
241 converted to type EXPECTED_TYPE, inserting a conversion at *N
242 if necessary. Returns true if successful, false on failure. */
244 type_check (struct expression *e,
245 union any_node **n, enum expr_type expected_type)
247 atom_type actual_type = expr_node_returns (*n);
249 switch (expected_type)
253 if (actual_type != OP_number && actual_type != OP_boolean)
255 msg (SE, _("Type mismatch: expression has %s type, "
256 "but a numeric value is required here."),
257 atom_type_name (actual_type));
260 if (actual_type == OP_number && expected_type == OP_boolean)
261 *n = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *n);
265 if (actual_type != OP_string)
267 msg (SE, _("Type mismatch: expression has %s type, "
268 "but a string value is required here."),
269 atom_type_name (actual_type));
281 /* Recursive-descent expression parser. */
283 /* Considers whether *NODE may be coerced to type REQUIRED_TYPE.
284 Returns true if possible, false if disallowed.
286 If DO_COERCION is false, then *NODE is not modified and there
289 If DO_COERCION is true, we perform the coercion if possible,
290 modifying *NODE if necessary. If the coercion is not possible
291 then we free *NODE and set *NODE to a null pointer.
293 This function's interface is somewhat awkward. Use one of the
294 wrapper functions type_coercion(), type_coercion_assert(), or
295 is_coercible() instead. */
297 type_coercion_core (struct expression *e,
298 atom_type required_type,
299 union any_node **node,
300 const char *operator_name,
303 atom_type actual_type;
305 assert (!!do_coercion == (e != NULL));
308 /* Propagate error. Whatever caused the original error
309 already emitted an error message. */
313 actual_type = expr_node_returns (*node);
314 if (actual_type == required_type)
320 switch (required_type)
323 if (actual_type == OP_boolean)
325 /* To enforce strict typing rules, insert Boolean to
326 numeric "conversion". This conversion is a no-op,
327 so it will be removed later. */
329 *node = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, *node);
335 /* No coercion to string. */
339 if (actual_type == OP_number)
341 /* Convert numeric to boolean. */
343 *node = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *node);
352 if ((*node)->type == OP_format
353 && check_input_specifier (&(*node)->format.f, false)
354 && check_specifier_type (&(*node)->format.f, NUMERIC, false))
357 (*node)->type = OP_ni_format;
363 if ((*node)->type == OP_format
364 && check_output_specifier (&(*node)->format.f, false)
365 && check_specifier_type (&(*node)->format.f, NUMERIC, false))
368 (*node)->type = OP_no_format;
374 if ((*node)->type == OP_NUM_VAR)
377 *node = (*node)->composite.args[0];
383 if ((*node)->type == OP_STR_VAR)
386 *node = (*node)->composite.args[0];
392 if ((*node)->type == OP_number
393 && floor ((*node)->number.n) == (*node)->number.n
394 && (*node)->number.n > 0 && (*node)->number.n < INT_MAX)
397 *node = expr_allocate_pos_int (e, (*node)->number.n);
408 msg (SE, _("Type mismatch while applying %s operator: "
409 "cannot convert %s to %s."),
411 atom_type_name (actual_type), atom_type_name (required_type));
417 /* Coerces *NODE to type REQUIRED_TYPE, and returns success. If
418 *NODE cannot be coerced to the desired type then we issue an
419 error message about operator OPERATOR_NAME and free *NODE. */
421 type_coercion (struct expression *e,
422 atom_type required_type, union any_node **node,
423 const char *operator_name)
425 return type_coercion_core (e, required_type, node, operator_name, true);
428 /* Coerces *NODE to type REQUIRED_TYPE.
429 Assert-fails if the coercion is disallowed. */
431 type_coercion_assert (struct expression *e,
432 atom_type required_type, union any_node **node)
434 int success = type_coercion_core (e, required_type, node, NULL, true);
438 /* Returns true if *NODE may be coerced to type REQUIRED_TYPE,
441 is_coercible (atom_type required_type, union any_node *const *node)
443 return type_coercion_core (NULL, required_type,
444 (union any_node **) node, NULL, false);
447 /* How to parse an operator. */
450 int token; /* Token representing operator. */
451 operation_type type; /* Operation type representing operation. */
452 const char *name; /* Name of operator. */
455 /* Attempts to match the current token against the tokens for the
456 OP_CNT operators in OPS[]. If successful, returns true
457 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
458 On failure, returns false and, if OPERATOR is non-null, sets
459 *OPERATOR to a null pointer. */
461 match_operator (const struct operator ops[], size_t op_cnt,
462 const struct operator **operator)
464 const struct operator *op;
466 for (op = ops; op < ops + op_cnt; op++)
468 if (op->token == '-')
469 lex_negative_to_dash ();
470 if (lex_match (op->token))
472 if (operator != NULL)
477 if (operator != NULL)
483 check_operator (const struct operator *op, int arg_cnt, atom_type arg_type)
485 const struct operation *o;
489 o = &operations[op->type];
490 assert (o->arg_cnt == arg_cnt);
491 assert ((o->flags & OPF_ARRAY_OPERAND) == 0);
492 for (i = 0; i < arg_cnt; i++)
493 assert (o->args[i] == arg_type);
498 check_binary_operators (const struct operator ops[], size_t op_cnt,
503 for (i = 0; i < op_cnt; i++)
504 check_operator (&ops[i], 2, arg_type);
509 get_operand_type (const struct operator *op)
511 return operations[op->type].args[0];
514 /* Parses a chain of left-associative operator/operand pairs.
515 There are OP_CNT operators, specified in OPS[]. The
516 operators' operands must all be the same type. The next
517 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
518 is non-null, then it will be issued as a warning if more than
519 one operator/operand pair is parsed. */
520 static union any_node *
521 parse_binary_operators (struct expression *e, union any_node *node,
522 const struct operator ops[], size_t op_cnt,
523 parse_recursively_func *parse_next_level,
524 const char *chain_warning)
526 atom_type operand_type = get_operand_type (&ops[0]);
528 const struct operator *operator;
530 assert (check_binary_operators (ops, op_cnt, operand_type));
534 for (op_count = 0; match_operator (ops, op_cnt, &operator); op_count++)
538 /* Convert the left-hand side to type OPERAND_TYPE. */
539 if (!type_coercion (e, operand_type, &node, operator->name))
542 /* Parse the right-hand side and coerce to type
544 rhs = parse_next_level (e);
545 if (!type_coercion (e, operand_type, &rhs, operator->name))
547 node = expr_allocate_binary (e, operator->type, node, rhs);
550 if (op_count > 1 && chain_warning != NULL)
551 msg (SW, chain_warning);
556 static union any_node *
557 parse_inverting_unary_operator (struct expression *e,
558 const struct operator *op,
559 parse_recursively_func *parse_next_level)
561 union any_node *node;
564 check_operator (op, 1, get_operand_type (op));
567 while (match_operator (op, 1, NULL))
570 node = parse_next_level (e);
572 && type_coercion (e, get_operand_type (op), &node, op->name)
573 && op_count % 2 != 0)
574 return expr_allocate_unary (e, op->type, node);
579 /* Parses the OR level. */
580 static union any_node *
581 parse_or (struct expression *e)
583 static const struct operator op =
584 { T_OR, OP_OR, "logical disjunction (\"OR\")" };
586 return parse_binary_operators (e, parse_and (e), &op, 1, parse_and, NULL);
589 /* Parses the AND level. */
590 static union any_node *
591 parse_and (struct expression *e)
593 static const struct operator op =
594 { T_AND, OP_AND, "logical conjunction (\"AND\")" };
596 return parse_binary_operators (e, parse_not (e), &op, 1, parse_not, NULL);
599 /* Parses the NOT level. */
600 static union any_node *
601 parse_not (struct expression *e)
603 static const struct operator op
604 = { T_NOT, OP_NOT, "logical negation (\"NOT\")" };
605 return parse_inverting_unary_operator (e, &op, parse_rel);
608 /* Parse relational operators. */
609 static union any_node *
610 parse_rel (struct expression *e)
612 const char *chain_warning =
613 _("Chaining relational operators (e.g. \"a < b < c\") will "
614 "not produce the mathematically expected result. "
615 "Use the AND logical operator to fix the problem "
616 "(e.g. \"a < b AND b < c\"). "
617 "If chaining is really intended, parentheses will disable "
618 "this warning (e.g. \"(a < b) < c\".)");
620 union any_node *node = parse_add (e);
625 switch (expr_node_returns (node))
630 static const struct operator ops[] =
632 { '=', OP_EQ, "numeric equality (\"=\")" },
633 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
634 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
635 { T_GT, OP_GT, "numeric greater than (\">\")" },
636 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
637 { T_LT, OP_LT, "numeric less than (\"<\")" },
638 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
641 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
642 parse_add, chain_warning);
647 static const struct operator ops[] =
649 { '=', OP_EQ_STRING, "string equality (\"=\")" },
650 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
651 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
652 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
653 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
654 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
655 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
658 return parse_binary_operators (e, node, ops, sizeof ops / sizeof *ops,
659 parse_add, chain_warning);
667 /* Parses the addition and subtraction level. */
668 static union any_node *
669 parse_add (struct expression *e)
671 static const struct operator ops[] =
673 { '+', OP_ADD, "addition (\"+\")" },
674 { '-', OP_SUB, "subtraction (\"-\")" },
677 return parse_binary_operators (e, parse_mul (e),
678 ops, sizeof ops / sizeof *ops,
682 /* Parses the multiplication and division level. */
683 static union any_node *
684 parse_mul (struct expression *e)
686 static const struct operator ops[] =
688 { '*', OP_MUL, "multiplication (\"*\")" },
689 { '/', OP_DIV, "division (\"/\")" },
692 return parse_binary_operators (e, parse_neg (e),
693 ops, sizeof ops / sizeof *ops,
697 /* Parses the unary minus level. */
698 static union any_node *
699 parse_neg (struct expression *e)
701 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
702 return parse_inverting_unary_operator (e, &op, parse_exp);
705 static union any_node *
706 parse_exp (struct expression *e)
708 static const struct operator op =
709 { T_EXP, OP_POW, "exponentiation (\"**\")" };
711 const char *chain_warning =
712 _("The exponentiation operator (\"**\") is left-associative, "
713 "even though right-associative semantics are more useful. "
714 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
715 "To disable this warning, insert parentheses.");
717 return parse_binary_operators (e, parse_primary (e), &op, 1,
718 parse_primary, chain_warning);
721 /* Parses system variables. */
722 static union any_node *
723 parse_sysvar (struct expression *e)
725 if (lex_match_id ("$CASENUM"))
726 return expr_allocate_nullary (e, OP_CASENUM);
727 else if (lex_match_id ("$DATE"))
729 static const char *months[12] =
731 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
732 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
735 time_t last_proc_time = time_of_last_procedure ();
739 time = localtime (&last_proc_time);
740 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
741 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
743 return expr_allocate_string_buffer (e, temp_buf, strlen (temp_buf));
745 else if (lex_match_id ("$TRUE"))
746 return expr_allocate_boolean (e, 1.0);
747 else if (lex_match_id ("$FALSE"))
748 return expr_allocate_boolean (e, 0.0);
749 else if (lex_match_id ("$SYSMIS"))
750 return expr_allocate_number (e, SYSMIS);
751 else if (lex_match_id ("$JDATE"))
753 time_t time = time_of_last_procedure ();
754 struct tm *tm = localtime (&time);
755 return expr_allocate_number (e, expr_ymd_to_ofs (tm->tm_year + 1900,
759 else if (lex_match_id ("$TIME"))
761 time_t time = time_of_last_procedure ();
762 struct tm *tm = localtime (&time);
763 return expr_allocate_number (e,
764 expr_ymd_to_date (tm->tm_year + 1900,
767 + tm->tm_hour * 60 * 60.
771 else if (lex_match_id ("$LENGTH"))
772 return expr_allocate_number (e, get_viewlength ());
773 else if (lex_match_id ("$WIDTH"))
774 return expr_allocate_number (e, get_viewwidth ());
777 msg (SE, _("Unknown system variable %s."), tokid);
782 /* Parses numbers, varnames, etc. */
783 static union any_node *
784 parse_primary (struct expression *e)
789 if (lex_look_ahead () == '(')
791 /* An identifier followed by a left parenthesis may be
792 a vector element reference. If not, it's a function
794 if (e->dict != NULL && dict_lookup_vector (e->dict, tokid) != NULL)
795 return parse_vector_element (e);
797 return parse_function (e);
799 else if (tokid[0] == '$')
801 /* $ at the beginning indicates a system variable. */
802 return parse_sysvar (e);
804 else if (e->dict != NULL && dict_lookup_var (e->dict, tokid))
806 /* It looks like a user variable.
807 (It could be a format specifier, but we'll assume
808 it's a variable unless proven otherwise. */
809 return allocate_unary_variable (e, parse_dict_variable (e->dict));
813 /* Try to parse it as a format specifier. */
815 if (parse_format_specifier (&fmt, FMTP_SUPPRESS_ERRORS))
816 return expr_allocate_format (e, &fmt);
818 /* All attempts failed. */
819 msg (SE, _("Unknown identifier %s."), tokid);
827 union any_node *node = expr_allocate_number (e, tokval);
834 union any_node *node = expr_allocate_string_buffer (
835 e, ds_cstr (&tokstr), ds_length (&tokstr));
842 union any_node *node;
845 if (node != NULL && !lex_match (')'))
847 lex_error (_("expecting `)'"));
854 lex_error (_("in expression"));
859 static union any_node *
860 parse_vector_element (struct expression *e)
862 const struct vector *vector;
863 union any_node *element;
865 /* Find vector, skip token.
866 The caller must already have verified that the current token
867 is the name of a vector. */
868 vector = dict_lookup_vector (default_dict, tokid);
869 assert (vector != NULL);
872 /* Skip left parenthesis token.
873 The caller must have verified that the lookahead is a left
875 assert (token == '(');
878 element = parse_or (e);
879 if (!type_coercion (e, OP_number, &element, "vector indexing")
883 return expr_allocate_binary (e, (vector->var[0]->type == NUMERIC
884 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR),
885 element, expr_allocate_vector (e, vector));
888 /* Individual function parsing. */
890 struct operation operations[OP_first + OP_cnt] = {
895 word_matches (const char **test, const char **name)
897 size_t test_len = strcspn (*test, ".");
898 size_t name_len = strcspn (*name, ".");
899 if (test_len == name_len)
901 if (buf_compare_case (*test, *name, test_len))
904 else if (test_len < 3 || test_len > name_len)
908 if (buf_compare_case (*test, *name, test_len))
914 if (**test != **name)
926 compare_names (const char *test, const char *name)
930 if (!word_matches (&test, &name))
932 if (*name == '\0' && *test == '\0')
938 compare_strings (const char *test, const char *name)
940 return strcasecmp (test, name);
944 lookup_function_helper (const char *name,
945 int (*compare) (const char *test, const char *name),
946 const struct operation **first,
947 const struct operation **last)
951 for (f = operations + OP_function_first;
952 f <= operations + OP_function_last; f++)
953 if (!compare (name, f->name))
957 while (f <= operations + OP_function_last && !compare (name, f->name))
968 lookup_function (const char *name,
969 const struct operation **first,
970 const struct operation **last)
972 *first = *last = NULL;
973 return (lookup_function_helper (name, compare_strings, first, last)
974 || lookup_function_helper (name, compare_names, first, last));
978 extract_min_valid (char *s)
980 char *p = strrchr (s, '.');
982 || p[1] < '0' || p[1] > '9'
983 || strspn (p + 1, "0123456789") != strlen (p + 1))
990 function_arg_type (const struct operation *f, size_t arg_idx)
992 assert (arg_idx < f->arg_cnt || (f->flags & OPF_ARRAY_OPERAND));
994 return f->args[arg_idx < f->arg_cnt ? arg_idx : f->arg_cnt - 1];
998 match_function (union any_node **args, int arg_cnt, const struct operation *f)
1002 if (arg_cnt < f->arg_cnt
1003 || (arg_cnt > f->arg_cnt && (f->flags & OPF_ARRAY_OPERAND) == 0)
1004 || arg_cnt - (f->arg_cnt - 1) < f->array_min_elems)
1007 for (i = 0; i < arg_cnt; i++)
1008 if (!is_coercible (function_arg_type (f, i), &args[i]))
1015 coerce_function_args (struct expression *e, const struct operation *f,
1016 union any_node **args, size_t arg_cnt)
1020 for (i = 0; i < arg_cnt; i++)
1021 type_coercion_assert (e, function_arg_type (f, i), &args[i]);
1025 validate_function_args (const struct operation *f, int arg_cnt, int min_valid)
1027 int array_arg_cnt = arg_cnt - (f->arg_cnt - 1);
1028 if (array_arg_cnt < f->array_min_elems)
1030 msg (SE, _("%s must have at least %d arguments in list."),
1031 f->prototype, f->array_min_elems);
1035 if ((f->flags & OPF_ARRAY_OPERAND)
1036 && array_arg_cnt % f->array_granularity != 0)
1038 if (f->array_granularity == 2)
1039 msg (SE, _("%s must have even number of arguments in list."),
1042 msg (SE, _("%s must have multiple of %d arguments in list."),
1043 f->prototype, f->array_granularity);
1047 if (min_valid != -1)
1049 if (f->array_min_elems == 0)
1051 assert ((f->flags & OPF_MIN_VALID) == 0);
1052 msg (SE, _("%s function does not accept a minimum valid "
1053 "argument count."), f->prototype);
1058 assert (f->flags & OPF_MIN_VALID);
1059 if (array_arg_cnt < f->array_min_elems)
1061 msg (SE, _("%s requires at least %d valid arguments in list."),
1062 f->prototype, f->array_min_elems);
1065 else if (min_valid > array_arg_cnt)
1067 msg (SE, _("With %s, "
1068 "using minimum valid argument count of %d "
1069 "does not make sense when passing only %d "
1070 "arguments in list."),
1071 f->prototype, min_valid, array_arg_cnt);
1081 add_arg (union any_node ***args, int *arg_cnt, int *arg_cap,
1082 union any_node *arg)
1084 if (*arg_cnt >= *arg_cap)
1087 *args = xrealloc (*args, sizeof **args * *arg_cap);
1090 (*args)[(*arg_cnt)++] = arg;
1094 put_invocation (struct string *s,
1095 const char *func_name, union any_node **args, size_t arg_cnt)
1099 ds_put_format (s, "%s(", func_name);
1100 for (i = 0; i < arg_cnt; i++)
1103 ds_put_cstr (s, ", ");
1104 ds_put_cstr (s, operations[expr_node_returns (args[i])].prototype);
1106 ds_put_char (s, ')');
1110 no_match (const char *func_name,
1111 union any_node **args, size_t arg_cnt,
1112 const struct operation *first, const struct operation *last)
1115 const struct operation *f;
1119 if (last - first == 1)
1121 ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1122 put_invocation (&s, func_name, args, arg_cnt);
1126 ds_put_cstr (&s, _("Function invocation "));
1127 put_invocation (&s, func_name, args, arg_cnt);
1128 ds_put_cstr (&s, _(" does not match any known function. Candidates are:"));
1130 for (f = first; f < last; f++)
1131 ds_put_format (&s, "\n%s", f->prototype);
1133 ds_put_char (&s, '.');
1135 msg (SE, "%s", ds_cstr (&s));
1140 static union any_node *
1141 parse_function (struct expression *e)
1144 const struct operation *f, *first, *last;
1146 union any_node **args = NULL;
1150 struct string func_name;
1154 ds_init_string (&func_name, &tokstr);
1155 min_valid = extract_min_valid (ds_cstr (&tokstr));
1156 if (!lookup_function (ds_cstr (&tokstr), &first, &last))
1158 msg (SE, _("No function or vector named %s."), ds_cstr (&tokstr));
1159 ds_destroy (&func_name);
1164 if (!lex_force_match ('('))
1166 ds_destroy (&func_name);
1171 arg_cnt = arg_cap = 0;
1175 if (token == T_ID && lex_look_ahead () == 'T')
1177 struct variable **vars;
1181 if (!parse_variables (default_dict, &vars, &var_cnt, PV_SINGLE))
1183 for (i = 0; i < var_cnt; i++)
1184 add_arg (&args, &arg_cnt, &arg_cap,
1185 allocate_unary_variable (e, vars[i]));
1190 union any_node *arg = parse_or (e);
1194 add_arg (&args, &arg_cnt, &arg_cap, arg);
1196 if (lex_match (')'))
1198 else if (!lex_match (','))
1200 lex_error (_("expecting `,' or `)' invoking %s function"),
1206 for (f = first; f < last; f++)
1207 if (match_function (args, arg_cnt, f))
1211 no_match (ds_cstr (&func_name), args, arg_cnt, first, last);
1215 coerce_function_args (e, f, args, arg_cnt);
1216 if (!validate_function_args (f, arg_cnt, min_valid))
1219 if ((f->flags & OPF_EXTENSION) && get_syntax () == COMPATIBLE)
1220 msg (SW, _("%s is a PSPP extension."), f->prototype);
1221 if (f->flags & OPF_UNIMPLEMENTED)
1223 msg (SE, _("%s is not yet implemented."), f->prototype);
1226 if ((f->flags & OPF_PERM_ONLY) && proc_in_temporary_transformations ())
1228 msg (SE, _("%s may not appear after TEMPORARY."), f->prototype);
1232 n = expr_allocate_composite (e, f - operations, args, arg_cnt);
1233 n->composite.min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1235 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1240 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1243 assert (n->composite.arg_cnt == 2);
1244 assert (n->composite.args[1]->type == OP_pos_int);
1245 n_before = n->composite.args[1]->integer.i;
1246 if (n_lag < n_before)
1251 ds_destroy (&func_name);
1256 ds_destroy (&func_name);
1260 /* Utility functions. */
1262 static struct expression *
1263 expr_create (struct dictionary *dict)
1265 struct pool *pool = pool_create ();
1266 struct expression *e = pool_alloc (pool, sizeof *e);
1267 e->expr_pool = pool;
1269 e->eval_pool = pool_create_subpool (e->expr_pool);
1272 e->op_cnt = e->op_cap = 0;
1277 expr_node_returns (const union any_node *n)
1280 assert (is_operation (n->type));
1281 if (is_atom (n->type))
1283 else if (is_composite (n->type))
1284 return operations[n->type].returns;
1290 atom_type_name (atom_type type)
1292 assert (is_atom (type));
1293 return operations[type].name;
1297 expr_allocate_nullary (struct expression *e, operation_type op)
1299 return expr_allocate_composite (e, op, NULL, 0);
1303 expr_allocate_unary (struct expression *e, operation_type op,
1304 union any_node *arg0)
1306 return expr_allocate_composite (e, op, &arg0, 1);
1310 expr_allocate_binary (struct expression *e, operation_type op,
1311 union any_node *arg0, union any_node *arg1)
1313 union any_node *args[2];
1316 return expr_allocate_composite (e, op, args, 2);
1320 is_valid_node (union any_node *n)
1322 struct operation *op;
1326 assert (is_operation (n->type));
1327 op = &operations[n->type];
1329 if (!is_atom (n->type))
1331 struct composite_node *c = &n->composite;
1333 assert (is_composite (n->type));
1334 assert (c->arg_cnt >= op->arg_cnt);
1335 for (i = 0; i < op->arg_cnt; i++)
1336 assert (expr_node_returns (c->args[i]) == op->args[i]);
1337 if (c->arg_cnt > op->arg_cnt && !is_operator (n->type))
1339 assert (op->flags & OPF_ARRAY_OPERAND);
1340 for (i = 0; i < c->arg_cnt; i++)
1341 assert (operations[c->args[i]->type].returns
1342 == op->args[op->arg_cnt - 1]);
1350 expr_allocate_composite (struct expression *e, operation_type op,
1351 union any_node **args, size_t arg_cnt)
1356 n = pool_alloc (e->expr_pool, sizeof n->composite);
1358 n->composite.arg_cnt = arg_cnt;
1359 n->composite.args = pool_alloc (e->expr_pool,
1360 sizeof *n->composite.args * arg_cnt);
1361 for (i = 0; i < arg_cnt; i++)
1363 if (args[i] == NULL)
1365 n->composite.args[i] = args[i];
1367 memcpy (n->composite.args, args, sizeof *n->composite.args * arg_cnt);
1368 n->composite.min_valid = 0;
1369 assert (is_valid_node (n));
1374 expr_allocate_number (struct expression *e, double d)
1376 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1377 n->type = OP_number;
1383 expr_allocate_boolean (struct expression *e, double b)
1385 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1386 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1387 n->type = OP_boolean;
1393 expr_allocate_integer (struct expression *e, int i)
1395 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1396 n->type = OP_integer;
1402 expr_allocate_pos_int (struct expression *e, int i)
1404 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1406 n->type = OP_pos_int;
1412 expr_allocate_vector (struct expression *e, const struct vector *vector)
1414 union any_node *n = pool_alloc (e->expr_pool, sizeof n->vector);
1415 n->type = OP_vector;
1416 n->vector.v = vector;
1421 expr_allocate_string_buffer (struct expression *e,
1422 const char *string, size_t length)
1424 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1425 n->type = OP_string;
1426 if (length > MAX_STRING)
1427 length = MAX_STRING;
1428 n->string.s = copy_string (e, string, length);
1433 expr_allocate_string (struct expression *e, struct substring s)
1435 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1436 n->type = OP_string;
1442 expr_allocate_variable (struct expression *e, struct variable *v)
1444 union any_node *n = pool_alloc (e->expr_pool, sizeof n->variable);
1445 n->type = v->type == NUMERIC ? OP_num_var : OP_str_var;
1451 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1453 union any_node *n = pool_alloc (e->expr_pool, sizeof n->format);
1454 n->type = OP_format;
1455 n->format.f = *format;
1459 /* Allocates a unary composite node that represents the value of
1460 variable V in expression E. */
1461 static union any_node *
1462 allocate_unary_variable (struct expression *e, struct variable *v)
1465 return expr_allocate_unary (e, v->type == NUMERIC ? OP_NUM_VAR : OP_STR_VAR,
1466 expr_allocate_variable (e, v));