1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
27 #include <data/case.h>
28 #include <data/dictionary.h>
29 #include <data/settings.h>
30 #include <data/variable.h>
31 #include <language/lexer/format-parser.h>
32 #include <language/lexer/lexer.h>
33 #include <language/lexer/variable-parser.h>
34 #include <libpspp/array.h>
35 #include <libpspp/assertion.h>
36 #include <libpspp/message.h>
37 #include <libpspp/misc.h>
38 #include <libpspp/pool.h>
39 #include <libpspp/str.h>
45 /* Recursive descent parser in order of increasing precedence. */
46 typedef union any_node *parse_recursively_func (struct lexer *, struct expression *);
47 static parse_recursively_func parse_or, parse_and, parse_not;
48 static parse_recursively_func parse_rel, parse_add, parse_mul;
49 static parse_recursively_func parse_neg, parse_exp;
50 static parse_recursively_func parse_primary;
51 static parse_recursively_func parse_vector_element, parse_function;
53 /* Utility functions. */
54 static struct expression *expr_create (struct dataset *ds);
55 atom_type expr_node_returns (const union any_node *);
57 static const char *atom_type_name (atom_type);
58 static struct expression *finish_expression (union any_node *,
60 static bool type_check (struct expression *, union any_node **,
61 enum expr_type expected_type);
62 static union any_node *allocate_unary_variable (struct expression *,
63 const struct variable *);
65 /* Public functions. */
67 /* Parses an expression of the given TYPE.
68 If DICT is nonnull then variables and vectors within it may be
69 referenced within the expression; otherwise, the expression
70 must not reference any variables or vectors.
71 Returns the new expression if successful or a null pointer
74 expr_parse (struct lexer *lexer, struct dataset *ds, enum expr_type type)
79 assert (type == EXPR_NUMBER || type == EXPR_STRING || type == EXPR_BOOLEAN);
82 n = parse_or (lexer, e);
83 if (n != NULL && type_check (e, &n, type))
84 return finish_expression (expr_optimize (n, e), e);
92 /* Parses and returns an expression of the given TYPE, as
93 expr_parse(), and sets up so that destroying POOL will free
94 the expression as well. */
96 expr_parse_pool (struct lexer *lexer,
101 struct expression *e = expr_parse (lexer, ds, type);
103 pool_add_subpool (pool, e->expr_pool);
107 /* Free expression E. */
109 expr_free (struct expression *e)
112 pool_destroy (e->expr_pool);
116 expr_parse_any (struct lexer *lexer, struct dataset *ds, bool optimize)
119 struct expression *e;
121 e = expr_create (ds);
122 n = parse_or (lexer, e);
130 n = expr_optimize (n, e);
131 return finish_expression (n, e);
134 /* Finishing up expression building. */
136 /* Height of an expression's stacks. */
139 int number_height; /* Height of number stack. */
140 int string_height; /* Height of string stack. */
143 /* Stack heights used by different kinds of arguments. */
144 static const struct stack_heights on_number_stack = {1, 0};
145 static const struct stack_heights on_string_stack = {0, 1};
146 static const struct stack_heights not_on_stack = {0, 0};
148 /* Returns the stack heights used by an atom of the given
150 static const struct stack_heights *
151 atom_type_stack (atom_type type)
153 assert (is_atom (type));
159 return &on_number_stack;
162 return &on_string_stack;
172 return ¬_on_stack;
179 /* Measures the stack height needed for node N, supposing that
180 the stack height is initially *HEIGHT and updating *HEIGHT to
181 the final stack height. Updates *MAX, if necessary, to
182 reflect the maximum intermediate or final height. */
184 measure_stack (const union any_node *n,
185 struct stack_heights *height, struct stack_heights *max)
187 const struct stack_heights *return_height;
189 if (is_composite (n->type))
191 struct stack_heights args;
195 for (i = 0; i < n->composite.arg_cnt; i++)
196 measure_stack (n->composite.args[i], &args, max);
198 return_height = atom_type_stack (operations[n->type].returns);
201 return_height = atom_type_stack (n->type);
203 height->number_height += return_height->number_height;
204 height->string_height += return_height->string_height;
206 if (height->number_height > max->number_height)
207 max->number_height = height->number_height;
208 if (height->string_height > max->string_height)
209 max->string_height = height->string_height;
212 /* Allocates stacks within E sufficient for evaluating node N. */
214 allocate_stacks (union any_node *n, struct expression *e)
216 struct stack_heights initial = {0, 0};
217 struct stack_heights max = {0, 0};
219 measure_stack (n, &initial, &max);
220 e->number_stack = pool_alloc (e->expr_pool,
221 sizeof *e->number_stack * max.number_height);
222 e->string_stack = pool_alloc (e->expr_pool,
223 sizeof *e->string_stack * max.string_height);
226 /* Finalizes expression E for evaluating node N. */
227 static struct expression *
228 finish_expression (union any_node *n, struct expression *e)
230 /* Allocate stacks. */
231 allocate_stacks (n, e);
233 /* Output postfix representation. */
236 /* The eval_pool might have been used for allocating strings
237 during optimization. We need to keep those strings around
238 for all subsequent evaluations, so start a new eval_pool. */
239 e->eval_pool = pool_create_subpool (e->expr_pool);
244 /* Verifies that expression E, whose root node is *N, can be
245 converted to type EXPECTED_TYPE, inserting a conversion at *N
246 if necessary. Returns true if successful, false on failure. */
248 type_check (struct expression *e,
249 union any_node **n, enum expr_type expected_type)
251 atom_type actual_type = expr_node_returns (*n);
253 switch (expected_type)
257 if (actual_type != OP_number && actual_type != OP_boolean)
259 msg (SE, _("Type mismatch: expression has %s type, "
260 "but a numeric value is required here."),
261 atom_type_name (actual_type));
264 if (actual_type == OP_number && expected_type == OP_boolean)
265 *n = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *n);
269 if (actual_type != OP_string)
271 msg (SE, _("Type mismatch: expression has %s type, "
272 "but a string value is required here."),
273 atom_type_name (actual_type));
285 /* Recursive-descent expression parser. */
287 /* Considers whether *NODE may be coerced to type REQUIRED_TYPE.
288 Returns true if possible, false if disallowed.
290 If DO_COERCION is false, then *NODE is not modified and there
293 If DO_COERCION is true, we perform the coercion if possible,
294 modifying *NODE if necessary. If the coercion is not possible
295 then we free *NODE and set *NODE to a null pointer.
297 This function's interface is somewhat awkward. Use one of the
298 wrapper functions type_coercion(), type_coercion_assert(), or
299 is_coercible() instead. */
301 type_coercion_core (struct expression *e,
302 atom_type required_type,
303 union any_node **node,
304 const char *operator_name,
307 atom_type actual_type;
309 assert (!!do_coercion == (e != NULL));
312 /* Propagate error. Whatever caused the original error
313 already emitted an error message. */
317 actual_type = expr_node_returns (*node);
318 if (actual_type == required_type)
324 switch (required_type)
327 if (actual_type == OP_boolean)
329 /* To enforce strict typing rules, insert Boolean to
330 numeric "conversion". This conversion is a no-op,
331 so it will be removed later. */
333 *node = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, *node);
339 /* No coercion to string. */
343 if (actual_type == OP_number)
345 /* Convert numeric to boolean. */
347 *node = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *node);
357 if ((*node)->type == OP_format
358 && fmt_check_input (&(*node)->format.f)
359 && fmt_check_type_compat (&(*node)->format.f, VAL_NUMERIC))
363 (*node)->type = OP_ni_format;
371 if ((*node)->type == OP_format
372 && fmt_check_output (&(*node)->format.f)
373 && fmt_check_type_compat (&(*node)->format.f, VAL_NUMERIC))
377 (*node)->type = OP_no_format;
384 if ((*node)->type == OP_NUM_VAR)
387 *node = (*node)->composite.args[0];
393 if ((*node)->type == OP_STR_VAR)
396 *node = (*node)->composite.args[0];
402 if ((*node)->type == OP_NUM_VAR || (*node)->type == OP_STR_VAR)
405 *node = (*node)->composite.args[0];
411 if ((*node)->type == OP_number
412 && floor ((*node)->number.n) == (*node)->number.n
413 && (*node)->number.n > 0 && (*node)->number.n < INT_MAX)
416 *node = expr_allocate_pos_int (e, (*node)->number.n);
427 msg (SE, _("Type mismatch while applying %s operator: "
428 "cannot convert %s to %s."),
430 atom_type_name (actual_type), atom_type_name (required_type));
436 /* Coerces *NODE to type REQUIRED_TYPE, and returns success. If
437 *NODE cannot be coerced to the desired type then we issue an
438 error message about operator OPERATOR_NAME and free *NODE. */
440 type_coercion (struct expression *e,
441 atom_type required_type, union any_node **node,
442 const char *operator_name)
444 return type_coercion_core (e, required_type, node, operator_name, true);
447 /* Coerces *NODE to type REQUIRED_TYPE.
448 Assert-fails if the coercion is disallowed. */
450 type_coercion_assert (struct expression *e,
451 atom_type required_type, union any_node **node)
453 int success = type_coercion_core (e, required_type, node, NULL, true);
457 /* Returns true if *NODE may be coerced to type REQUIRED_TYPE,
460 is_coercible (atom_type required_type, union any_node *const *node)
462 return type_coercion_core (NULL, required_type,
463 (union any_node **) node, NULL, false);
466 /* Returns true if ACTUAL_TYPE is a kind of REQUIRED_TYPE, false
469 is_compatible (atom_type required_type, atom_type actual_type)
471 return (required_type == actual_type
472 || (required_type == OP_var
473 && (actual_type == OP_num_var || actual_type == OP_str_var)));
476 /* How to parse an operator. */
479 int token; /* Token representing operator. */
480 operation_type type; /* Operation type representing operation. */
481 const char *name; /* Name of operator. */
484 /* Attempts to match the current token against the tokens for the
485 OP_CNT operators in OPS[]. If successful, returns true
486 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
487 On failure, returns false and, if OPERATOR is non-null, sets
488 *OPERATOR to a null pointer. */
490 match_operator (struct lexer *lexer, const struct operator ops[], size_t op_cnt,
491 const struct operator **operator)
493 const struct operator *op;
495 for (op = ops; op < ops + op_cnt; op++)
497 if (op->token == '-')
498 lex_negative_to_dash (lexer);
499 if (lex_match (lexer, op->token))
501 if (operator != NULL)
506 if (operator != NULL)
512 check_operator (const struct operator *op, int arg_cnt, atom_type arg_type)
514 const struct operation *o;
518 o = &operations[op->type];
519 assert (o->arg_cnt == arg_cnt);
520 assert ((o->flags & OPF_ARRAY_OPERAND) == 0);
521 for (i = 0; i < arg_cnt; i++)
522 assert (is_compatible (arg_type, o->args[i]));
527 check_binary_operators (const struct operator ops[], size_t op_cnt,
532 for (i = 0; i < op_cnt; i++)
533 check_operator (&ops[i], 2, arg_type);
538 get_operand_type (const struct operator *op)
540 return operations[op->type].args[0];
543 /* Parses a chain of left-associative operator/operand pairs.
544 There are OP_CNT operators, specified in OPS[]. The
545 operators' operands must all be the same type. The next
546 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
547 is non-null, then it will be issued as a warning if more than
548 one operator/operand pair is parsed. */
549 static union any_node *
550 parse_binary_operators (struct lexer *lexer, struct expression *e, union any_node *node,
551 const struct operator ops[], size_t op_cnt,
552 parse_recursively_func *parse_next_level,
553 const char *chain_warning)
555 atom_type operand_type = get_operand_type (&ops[0]);
557 const struct operator *operator;
559 assert (check_binary_operators (ops, op_cnt, operand_type));
563 for (op_count = 0; match_operator (lexer, ops, op_cnt, &operator); op_count++)
567 /* Convert the left-hand side to type OPERAND_TYPE. */
568 if (!type_coercion (e, operand_type, &node, operator->name))
571 /* Parse the right-hand side and coerce to type
573 rhs = parse_next_level (lexer, e);
574 if (!type_coercion (e, operand_type, &rhs, operator->name))
576 node = expr_allocate_binary (e, operator->type, node, rhs);
579 if (op_count > 1 && chain_warning != NULL)
580 msg (SW, chain_warning);
585 static union any_node *
586 parse_inverting_unary_operator (struct lexer *lexer, struct expression *e,
587 const struct operator *op,
588 parse_recursively_func *parse_next_level)
590 union any_node *node;
593 check_operator (op, 1, get_operand_type (op));
596 while (match_operator (lexer, op, 1, NULL))
599 node = parse_next_level (lexer, e);
601 && type_coercion (e, get_operand_type (op), &node, op->name)
602 && op_count % 2 != 0)
603 return expr_allocate_unary (e, op->type, node);
608 /* Parses the OR level. */
609 static union any_node *
610 parse_or (struct lexer *lexer, struct expression *e)
612 static const struct operator op =
613 { T_OR, OP_OR, "logical disjunction (\"OR\")" };
615 return parse_binary_operators (lexer, e, parse_and (lexer, e), &op, 1, parse_and, NULL);
618 /* Parses the AND level. */
619 static union any_node *
620 parse_and (struct lexer *lexer, struct expression *e)
622 static const struct operator op =
623 { T_AND, OP_AND, "logical conjunction (\"AND\")" };
625 return parse_binary_operators (lexer, e, parse_not (lexer, e),
626 &op, 1, parse_not, NULL);
629 /* Parses the NOT level. */
630 static union any_node *
631 parse_not (struct lexer *lexer, struct expression *e)
633 static const struct operator op
634 = { T_NOT, OP_NOT, "logical negation (\"NOT\")" };
635 return parse_inverting_unary_operator (lexer, e, &op, parse_rel);
638 /* Parse relational operators. */
639 static union any_node *
640 parse_rel (struct lexer *lexer, struct expression *e)
642 const char *chain_warning =
643 _("Chaining relational operators (e.g. \"a < b < c\") will "
644 "not produce the mathematically expected result. "
645 "Use the AND logical operator to fix the problem "
646 "(e.g. \"a < b AND b < c\"). "
647 "If chaining is really intended, parentheses will disable "
648 "this warning (e.g. \"(a < b) < c\".)");
650 union any_node *node = parse_add (lexer, e);
655 switch (expr_node_returns (node))
660 static const struct operator ops[] =
662 { '=', OP_EQ, "numeric equality (\"=\")" },
663 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
664 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
665 { T_GT, OP_GT, "numeric greater than (\">\")" },
666 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
667 { T_LT, OP_LT, "numeric less than (\"<\")" },
668 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
671 return parse_binary_operators (lexer, e, node, ops,
672 sizeof ops / sizeof *ops,
673 parse_add, chain_warning);
678 static const struct operator ops[] =
680 { '=', OP_EQ_STRING, "string equality (\"=\")" },
681 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
682 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
683 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
684 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
685 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
686 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
689 return parse_binary_operators (lexer, e, node, ops,
690 sizeof ops / sizeof *ops,
691 parse_add, chain_warning);
699 /* Parses the addition and subtraction level. */
700 static union any_node *
701 parse_add (struct lexer *lexer, struct expression *e)
703 static const struct operator ops[] =
705 { '+', OP_ADD, "addition (\"+\")" },
706 { '-', OP_SUB, "subtraction (\"-\")" },
709 return parse_binary_operators (lexer, e, parse_mul (lexer, e),
710 ops, sizeof ops / sizeof *ops,
714 /* Parses the multiplication and division level. */
715 static union any_node *
716 parse_mul (struct lexer *lexer, struct expression *e)
718 static const struct operator ops[] =
720 { '*', OP_MUL, "multiplication (\"*\")" },
721 { '/', OP_DIV, "division (\"/\")" },
724 return parse_binary_operators (lexer, e, parse_neg (lexer, e),
725 ops, sizeof ops / sizeof *ops,
729 /* Parses the unary minus level. */
730 static union any_node *
731 parse_neg (struct lexer *lexer, struct expression *e)
733 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
734 return parse_inverting_unary_operator (lexer, e, &op, parse_exp);
737 static union any_node *
738 parse_exp (struct lexer *lexer, struct expression *e)
740 static const struct operator op =
741 { T_EXP, OP_POW, "exponentiation (\"**\")" };
743 const char *chain_warning =
744 _("The exponentiation operator (\"**\") is left-associative, "
745 "even though right-associative semantics are more useful. "
746 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
747 "To disable this warning, insert parentheses.");
749 return parse_binary_operators (lexer, e, parse_primary (lexer, e), &op, 1,
750 parse_primary, chain_warning);
753 /* Parses system variables. */
754 static union any_node *
755 parse_sysvar (struct lexer *lexer, struct expression *e)
757 if (lex_match_id (lexer, "$CASENUM"))
758 return expr_allocate_nullary (e, OP_CASENUM);
759 else if (lex_match_id (lexer, "$DATE"))
761 static const char *months[12] =
763 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
764 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
767 time_t last_proc_time = time_of_last_procedure (e->ds);
771 time = localtime (&last_proc_time);
772 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
773 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
775 return expr_allocate_string_buffer (e, temp_buf, strlen (temp_buf));
777 else if (lex_match_id (lexer, "$TRUE"))
778 return expr_allocate_boolean (e, 1.0);
779 else if (lex_match_id (lexer, "$FALSE"))
780 return expr_allocate_boolean (e, 0.0);
781 else if (lex_match_id (lexer, "$SYSMIS"))
782 return expr_allocate_number (e, SYSMIS);
783 else if (lex_match_id (lexer, "$JDATE"))
785 time_t time = time_of_last_procedure (e->ds);
786 struct tm *tm = localtime (&time);
787 return expr_allocate_number (e, expr_ymd_to_ofs (tm->tm_year + 1900,
791 else if (lex_match_id (lexer, "$TIME"))
793 time_t time = time_of_last_procedure (e->ds);
794 struct tm *tm = localtime (&time);
795 return expr_allocate_number (e,
796 expr_ymd_to_date (tm->tm_year + 1900,
799 + tm->tm_hour * 60 * 60.
803 else if (lex_match_id (lexer, "$LENGTH"))
804 return expr_allocate_number (e, settings_get_viewlength ());
805 else if (lex_match_id (lexer, "$WIDTH"))
806 return expr_allocate_number (e, settings_get_viewwidth ());
809 msg (SE, _("Unknown system variable %s."), lex_tokid (lexer));
814 /* Parses numbers, varnames, etc. */
815 static union any_node *
816 parse_primary (struct lexer *lexer, struct expression *e)
818 switch (lex_token (lexer))
821 if (lex_look_ahead (lexer) == '(')
823 /* An identifier followed by a left parenthesis may be
824 a vector element reference. If not, it's a function
826 if (e->ds != NULL && dict_lookup_vector (dataset_dict (e->ds), lex_tokid (lexer)) != NULL)
827 return parse_vector_element (lexer, e);
829 return parse_function (lexer, e);
831 else if (lex_tokid (lexer)[0] == '$')
833 /* $ at the beginning indicates a system variable. */
834 return parse_sysvar (lexer, e);
836 else if (e->ds != NULL && dict_lookup_var (dataset_dict (e->ds), lex_tokid (lexer)))
838 /* It looks like a user variable.
839 (It could be a format specifier, but we'll assume
840 it's a variable unless proven otherwise. */
841 return allocate_unary_variable (e, parse_variable (lexer, dataset_dict (e->ds)));
845 /* Try to parse it as a format specifier. */
850 ok = parse_format_specifier (lexer, &fmt);
854 return expr_allocate_format (e, &fmt);
856 /* All attempts failed. */
857 msg (SE, _("Unknown identifier %s."), lex_tokid (lexer));
865 union any_node *node = expr_allocate_number (e, lex_tokval (lexer) );
872 union any_node *node = expr_allocate_string_buffer (
873 e, ds_cstr (lex_tokstr (lexer) ), ds_length (lex_tokstr (lexer) ));
880 union any_node *node;
882 node = parse_or (lexer, e);
883 if (node != NULL && !lex_match (lexer, ')'))
885 lex_error (lexer, _("expecting `)'"));
892 lex_error (lexer, _("in expression"));
897 static union any_node *
898 parse_vector_element (struct lexer *lexer, struct expression *e)
900 const struct vector *vector;
901 union any_node *element;
903 /* Find vector, skip token.
904 The caller must already have verified that the current token
905 is the name of a vector. */
906 vector = dict_lookup_vector (dataset_dict (e->ds), lex_tokid (lexer));
907 assert (vector != NULL);
910 /* Skip left parenthesis token.
911 The caller must have verified that the lookahead is a left
913 assert (lex_token (lexer) == '(');
916 element = parse_or (lexer, e);
917 if (!type_coercion (e, OP_number, &element, "vector indexing")
918 || !lex_match (lexer, ')'))
921 return expr_allocate_binary (e, (vector_get_type (vector) == VAL_NUMERIC
922 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR),
923 element, expr_allocate_vector (e, vector));
926 /* Individual function parsing. */
928 const struct operation operations[OP_first + OP_cnt] = {
933 word_matches (const char **test, const char **name)
935 size_t test_len = strcspn (*test, ".");
936 size_t name_len = strcspn (*name, ".");
937 if (test_len == name_len)
939 if (buf_compare_case (*test, *name, test_len))
942 else if (test_len < 3 || test_len > name_len)
946 if (buf_compare_case (*test, *name, test_len))
952 if (**test != **name)
964 compare_names (const char *test, const char *name, bool abbrev_ok)
971 if (!word_matches (&test, &name))
973 if (*name == '\0' && *test == '\0')
979 compare_strings (const char *test, const char *name, bool abbrev_ok UNUSED)
981 return strcasecmp (test, name);
985 lookup_function_helper (const char *name,
986 int (*compare) (const char *test, const char *name,
988 const struct operation **first,
989 const struct operation **last)
991 const struct operation *f;
993 for (f = operations + OP_function_first;
994 f <= operations + OP_function_last; f++)
995 if (!compare (name, f->name, !(f->flags & OPF_NO_ABBREV)))
999 while (f <= operations + OP_function_last
1000 && !compare (name, f->name, !(f->flags & OPF_NO_ABBREV)))
1011 lookup_function (const char *name,
1012 const struct operation **first,
1013 const struct operation **last)
1015 *first = *last = NULL;
1016 return (lookup_function_helper (name, compare_strings, first, last)
1017 || lookup_function_helper (name, compare_names, first, last));
1021 extract_min_valid (char *s)
1023 char *p = strrchr (s, '.');
1025 || p[1] < '0' || p[1] > '9'
1026 || strspn (p + 1, "0123456789") != strlen (p + 1))
1029 return atoi (p + 1);
1033 function_arg_type (const struct operation *f, size_t arg_idx)
1035 assert (arg_idx < f->arg_cnt || (f->flags & OPF_ARRAY_OPERAND));
1037 return f->args[arg_idx < f->arg_cnt ? arg_idx : f->arg_cnt - 1];
1041 match_function (union any_node **args, int arg_cnt, const struct operation *f)
1045 if (arg_cnt < f->arg_cnt
1046 || (arg_cnt > f->arg_cnt && (f->flags & OPF_ARRAY_OPERAND) == 0)
1047 || arg_cnt - (f->arg_cnt - 1) < f->array_min_elems)
1050 for (i = 0; i < arg_cnt; i++)
1051 if (!is_coercible (function_arg_type (f, i), &args[i]))
1058 coerce_function_args (struct expression *e, const struct operation *f,
1059 union any_node **args, size_t arg_cnt)
1063 for (i = 0; i < arg_cnt; i++)
1064 type_coercion_assert (e, function_arg_type (f, i), &args[i]);
1068 validate_function_args (const struct operation *f, int arg_cnt, int min_valid)
1070 int array_arg_cnt = arg_cnt - (f->arg_cnt - 1);
1071 if (array_arg_cnt < f->array_min_elems)
1073 msg (SE, _("%s must have at least %d arguments in list."),
1074 f->prototype, f->array_min_elems);
1078 if ((f->flags & OPF_ARRAY_OPERAND)
1079 && array_arg_cnt % f->array_granularity != 0)
1081 if (f->array_granularity == 2)
1082 msg (SE, _("%s must have even number of arguments in list."),
1085 msg (SE, _("%s must have multiple of %d arguments in list."),
1086 f->prototype, f->array_granularity);
1090 if (min_valid != -1)
1092 if (f->array_min_elems == 0)
1094 assert ((f->flags & OPF_MIN_VALID) == 0);
1095 msg (SE, _("%s function does not accept a minimum valid "
1096 "argument count."), f->prototype);
1101 assert (f->flags & OPF_MIN_VALID);
1102 if (array_arg_cnt < f->array_min_elems)
1104 msg (SE, _("%s requires at least %d valid arguments in list."),
1105 f->prototype, f->array_min_elems);
1108 else if (min_valid > array_arg_cnt)
1110 msg (SE, _("With %s, "
1111 "using minimum valid argument count of %d "
1112 "does not make sense when passing only %d "
1113 "arguments in list."),
1114 f->prototype, min_valid, array_arg_cnt);
1124 add_arg (union any_node ***args, int *arg_cnt, int *arg_cap,
1125 union any_node *arg)
1127 if (*arg_cnt >= *arg_cap)
1130 *args = xrealloc (*args, sizeof **args * *arg_cap);
1133 (*args)[(*arg_cnt)++] = arg;
1137 put_invocation (struct string *s,
1138 const char *func_name, union any_node **args, size_t arg_cnt)
1142 ds_put_format (s, "%s(", func_name);
1143 for (i = 0; i < arg_cnt; i++)
1146 ds_put_cstr (s, ", ");
1147 ds_put_cstr (s, operations[expr_node_returns (args[i])].prototype);
1149 ds_put_char (s, ')');
1153 no_match (const char *func_name,
1154 union any_node **args, size_t arg_cnt,
1155 const struct operation *first, const struct operation *last)
1158 const struct operation *f;
1162 if (last - first == 1)
1164 ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1165 put_invocation (&s, func_name, args, arg_cnt);
1169 ds_put_cstr (&s, _("Function invocation "));
1170 put_invocation (&s, func_name, args, arg_cnt);
1171 ds_put_cstr (&s, _(" does not match any known function. Candidates are:"));
1173 for (f = first; f < last; f++)
1174 ds_put_format (&s, "\n%s", f->prototype);
1176 ds_put_char (&s, '.');
1178 msg (SE, "%s", ds_cstr (&s));
1183 static union any_node *
1184 parse_function (struct lexer *lexer, struct expression *e)
1187 const struct operation *f, *first, *last;
1189 union any_node **args = NULL;
1193 struct string func_name;
1197 ds_init_string (&func_name, lex_tokstr (lexer));
1198 min_valid = extract_min_valid (ds_cstr (lex_tokstr (lexer)));
1199 if (!lookup_function (ds_cstr (lex_tokstr (lexer)), &first, &last))
1201 msg (SE, _("No function or vector named %s."), ds_cstr (lex_tokstr (lexer)));
1202 ds_destroy (&func_name);
1207 if (!lex_force_match (lexer, '('))
1209 ds_destroy (&func_name);
1214 arg_cnt = arg_cap = 0;
1215 if (lex_token (lexer) != ')')
1218 if (lex_token (lexer) == T_ID
1219 && toupper (lex_look_ahead (lexer)) == 'T')
1221 const struct variable **vars;
1225 if (!parse_variables_const (lexer, dataset_dict (e->ds), &vars, &var_cnt, PV_SINGLE))
1227 for (i = 0; i < var_cnt; i++)
1228 add_arg (&args, &arg_cnt, &arg_cap,
1229 allocate_unary_variable (e, vars[i]));
1234 union any_node *arg = parse_or (lexer, e);
1238 add_arg (&args, &arg_cnt, &arg_cap, arg);
1240 if (lex_match (lexer, ')'))
1242 else if (!lex_match (lexer, ','))
1244 lex_error (lexer, _("expecting `,' or `)' invoking %s function"),
1250 for (f = first; f < last; f++)
1251 if (match_function (args, arg_cnt, f))
1255 no_match (ds_cstr (&func_name), args, arg_cnt, first, last);
1259 coerce_function_args (e, f, args, arg_cnt);
1260 if (!validate_function_args (f, arg_cnt, min_valid))
1263 if ((f->flags & OPF_EXTENSION) && settings_get_syntax () == COMPATIBLE)
1264 msg (SW, _("%s is a PSPP extension."), f->prototype);
1265 if (f->flags & OPF_UNIMPLEMENTED)
1267 msg (SE, _("%s is not yet implemented."), f->prototype);
1270 if ((f->flags & OPF_PERM_ONLY) &&
1271 proc_in_temporary_transformations (e->ds))
1273 msg (SE, _("%s may not appear after TEMPORARY."), f->prototype);
1277 n = expr_allocate_composite (e, f - operations, args, arg_cnt);
1278 n->composite.min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1280 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1281 dataset_need_lag (e->ds, 1);
1282 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1285 assert (n->composite.arg_cnt == 2);
1286 assert (n->composite.args[1]->type == OP_pos_int);
1287 n_before = n->composite.args[1]->integer.i;
1288 dataset_need_lag (e->ds, n_before);
1292 ds_destroy (&func_name);
1297 ds_destroy (&func_name);
1301 /* Utility functions. */
1303 static struct expression *
1304 expr_create (struct dataset *ds)
1306 struct pool *pool = pool_create ();
1307 struct expression *e = pool_alloc (pool, sizeof *e);
1308 e->expr_pool = pool;
1310 e->eval_pool = pool_create_subpool (e->expr_pool);
1313 e->op_cnt = e->op_cap = 0;
1318 expr_node_returns (const union any_node *n)
1321 assert (is_operation (n->type));
1322 if (is_atom (n->type))
1324 else if (is_composite (n->type))
1325 return operations[n->type].returns;
1331 atom_type_name (atom_type type)
1333 assert (is_atom (type));
1334 return operations[type].name;
1338 expr_allocate_nullary (struct expression *e, operation_type op)
1340 return expr_allocate_composite (e, op, NULL, 0);
1344 expr_allocate_unary (struct expression *e, operation_type op,
1345 union any_node *arg0)
1347 return expr_allocate_composite (e, op, &arg0, 1);
1351 expr_allocate_binary (struct expression *e, operation_type op,
1352 union any_node *arg0, union any_node *arg1)
1354 union any_node *args[2];
1357 return expr_allocate_composite (e, op, args, 2);
1361 is_valid_node (union any_node *n)
1363 const struct operation *op;
1367 assert (is_operation (n->type));
1368 op = &operations[n->type];
1370 if (!is_atom (n->type))
1372 struct composite_node *c = &n->composite;
1374 assert (is_composite (n->type));
1375 assert (c->arg_cnt >= op->arg_cnt);
1376 for (i = 0; i < op->arg_cnt; i++)
1377 assert (is_compatible (op->args[i], expr_node_returns (c->args[i])));
1378 if (c->arg_cnt > op->arg_cnt && !is_operator (n->type))
1380 assert (op->flags & OPF_ARRAY_OPERAND);
1381 for (i = 0; i < c->arg_cnt; i++)
1382 assert (is_compatible (op->args[op->arg_cnt - 1],
1383 expr_node_returns (c->args[i])));
1391 expr_allocate_composite (struct expression *e, operation_type op,
1392 union any_node **args, size_t arg_cnt)
1397 n = pool_alloc (e->expr_pool, sizeof n->composite);
1399 n->composite.arg_cnt = arg_cnt;
1400 n->composite.args = pool_alloc (e->expr_pool,
1401 sizeof *n->composite.args * arg_cnt);
1402 for (i = 0; i < arg_cnt; i++)
1404 if (args[i] == NULL)
1406 n->composite.args[i] = args[i];
1408 memcpy (n->composite.args, args, sizeof *n->composite.args * arg_cnt);
1409 n->composite.min_valid = 0;
1410 assert (is_valid_node (n));
1415 expr_allocate_number (struct expression *e, double d)
1417 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1418 n->type = OP_number;
1424 expr_allocate_boolean (struct expression *e, double b)
1426 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1427 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1428 n->type = OP_boolean;
1434 expr_allocate_integer (struct expression *e, int i)
1436 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1437 n->type = OP_integer;
1443 expr_allocate_pos_int (struct expression *e, int i)
1445 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1447 n->type = OP_pos_int;
1453 expr_allocate_vector (struct expression *e, const struct vector *vector)
1455 union any_node *n = pool_alloc (e->expr_pool, sizeof n->vector);
1456 n->type = OP_vector;
1457 n->vector.v = vector;
1462 expr_allocate_string_buffer (struct expression *e,
1463 const char *string, size_t length)
1465 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1466 n->type = OP_string;
1467 if (length > MAX_STRING)
1468 length = MAX_STRING;
1469 n->string.s = copy_string (e, string, length);
1474 expr_allocate_string (struct expression *e, struct substring s)
1476 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1477 n->type = OP_string;
1483 expr_allocate_variable (struct expression *e, const struct variable *v)
1485 union any_node *n = pool_alloc (e->expr_pool, sizeof n->variable);
1486 n->type = var_is_numeric (v) ? OP_num_var : OP_str_var;
1492 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1494 union any_node *n = pool_alloc (e->expr_pool, sizeof n->format);
1495 n->type = OP_format;
1496 n->format.f = *format;
1500 /* Allocates a unary composite node that represents the value of
1501 variable V in expression E. */
1502 static union any_node *
1503 allocate_unary_variable (struct expression *e, const struct variable *v)
1506 return expr_allocate_unary (e, var_is_numeric (v) ? OP_NUM_VAR : OP_STR_VAR,
1507 expr_allocate_variable (e, v));
1510 /* Export function details to other modules. */
1512 /* Returns the operation structure for the function with the
1514 const struct operation *
1515 expr_get_function (size_t idx)
1517 assert (idx < OP_function_cnt);
1518 return &operations[OP_function_first + idx];
1521 /* Returns the number of expression functions. */
1523 expr_get_function_cnt (void)
1525 return OP_function_cnt;
1528 /* Returns the name of operation OP. */
1530 expr_operation_get_name (const struct operation *op)
1535 /* Returns the human-readable prototype for operation OP. */
1537 expr_operation_get_prototype (const struct operation *op)
1539 return op->prototype;
1542 /* Returns the number of arguments for operation OP. */
1544 expr_operation_get_arg_cnt (const struct operation *op)