1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000, 2006 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
30 #include <data/case.h>
31 #include <data/dictionary.h>
32 #include <data/settings.h>
33 #include <data/variable.h>
34 #include <language/lexer/format-parser.h>
35 #include <language/lexer/lexer.h>
36 #include <language/lexer/variable-parser.h>
37 #include <libpspp/alloc.h>
38 #include <libpspp/array.h>
39 #include <libpspp/assertion.h>
40 #include <libpspp/message.h>
41 #include <libpspp/misc.h>
42 #include <libpspp/pool.h>
43 #include <libpspp/str.h>
47 /* Recursive descent parser in order of increasing precedence. */
48 typedef union any_node *parse_recursively_func (struct lexer *, struct expression *);
49 static parse_recursively_func parse_or, parse_and, parse_not;
50 static parse_recursively_func parse_rel, parse_add, parse_mul;
51 static parse_recursively_func parse_neg, parse_exp;
52 static parse_recursively_func parse_primary;
53 static parse_recursively_func parse_vector_element, parse_function;
55 /* Utility functions. */
56 static struct expression *expr_create (struct dataset *ds);
57 atom_type expr_node_returns (const union any_node *);
59 static const char *atom_type_name (atom_type);
60 static struct expression *finish_expression (union any_node *,
62 static bool type_check (struct expression *, union any_node **,
63 enum expr_type expected_type);
64 static union any_node *allocate_unary_variable (struct expression *,
67 /* Public functions. */
69 /* Parses an expression of the given TYPE.
70 If DICT is nonnull then variables and vectors within it may be
71 referenced within the expression; otherwise, the expression
72 must not reference any variables or vectors.
73 Returns the new expression if successful or a null pointer
76 expr_parse (struct lexer *lexer, struct dataset *ds, enum expr_type type)
81 assert (type == EXPR_NUMBER || type == EXPR_STRING || type == EXPR_BOOLEAN);
84 n = parse_or (lexer, e);
85 if (n != NULL && type_check (e, &n, type))
86 return finish_expression (expr_optimize (n, e), e);
94 /* Parses and returns an expression of the given TYPE, as
95 expr_parse(), and sets up so that destroying POOL will free
96 the expression as well. */
98 expr_parse_pool (struct lexer *lexer,
103 struct expression *e = expr_parse (lexer, ds, type);
105 pool_add_subpool (pool, e->expr_pool);
109 /* Free expression E. */
111 expr_free (struct expression *e)
114 pool_destroy (e->expr_pool);
118 expr_parse_any (struct lexer *lexer, struct dataset *ds, bool optimize)
121 struct expression *e;
123 e = expr_create (ds);
124 n = parse_or (lexer, e);
132 n = expr_optimize (n, e);
133 return finish_expression (n, e);
136 /* Finishing up expression building. */
138 /* Height of an expression's stacks. */
141 int number_height; /* Height of number stack. */
142 int string_height; /* Height of string stack. */
145 /* Stack heights used by different kinds of arguments. */
146 static const struct stack_heights on_number_stack = {1, 0};
147 static const struct stack_heights on_string_stack = {0, 1};
148 static const struct stack_heights not_on_stack = {0, 0};
150 /* Returns the stack heights used by an atom of the given
152 static const struct stack_heights *
153 atom_type_stack (atom_type type)
155 assert (is_atom (type));
161 return &on_number_stack;
164 return &on_string_stack;
174 return ¬_on_stack;
181 /* Measures the stack height needed for node N, supposing that
182 the stack height is initially *HEIGHT and updating *HEIGHT to
183 the final stack height. Updates *MAX, if necessary, to
184 reflect the maximum intermediate or final height. */
186 measure_stack (const union any_node *n,
187 struct stack_heights *height, struct stack_heights *max)
189 const struct stack_heights *return_height;
191 if (is_composite (n->type))
193 struct stack_heights args;
197 for (i = 0; i < n->composite.arg_cnt; i++)
198 measure_stack (n->composite.args[i], &args, max);
200 return_height = atom_type_stack (operations[n->type].returns);
203 return_height = atom_type_stack (n->type);
205 height->number_height += return_height->number_height;
206 height->string_height += return_height->string_height;
208 if (height->number_height > max->number_height)
209 max->number_height = height->number_height;
210 if (height->string_height > max->string_height)
211 max->string_height = height->string_height;
214 /* Allocates stacks within E sufficient for evaluating node N. */
216 allocate_stacks (union any_node *n, struct expression *e)
218 struct stack_heights initial = {0, 0};
219 struct stack_heights max = {0, 0};
221 measure_stack (n, &initial, &max);
222 e->number_stack = pool_alloc (e->expr_pool,
223 sizeof *e->number_stack * max.number_height);
224 e->string_stack = pool_alloc (e->expr_pool,
225 sizeof *e->string_stack * max.string_height);
228 /* Finalizes expression E for evaluating node N. */
229 static struct expression *
230 finish_expression (union any_node *n, struct expression *e)
232 /* Allocate stacks. */
233 allocate_stacks (n, e);
235 /* Output postfix representation. */
238 /* The eval_pool might have been used for allocating strings
239 during optimization. We need to keep those strings around
240 for all subsequent evaluations, so start a new eval_pool. */
241 e->eval_pool = pool_create_subpool (e->expr_pool);
246 /* Verifies that expression E, whose root node is *N, can be
247 converted to type EXPECTED_TYPE, inserting a conversion at *N
248 if necessary. Returns true if successful, false on failure. */
250 type_check (struct expression *e,
251 union any_node **n, enum expr_type expected_type)
253 atom_type actual_type = expr_node_returns (*n);
255 switch (expected_type)
259 if (actual_type != OP_number && actual_type != OP_boolean)
261 msg (SE, _("Type mismatch: expression has %s type, "
262 "but a numeric value is required here."),
263 atom_type_name (actual_type));
266 if (actual_type == OP_number && expected_type == OP_boolean)
267 *n = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *n);
271 if (actual_type != OP_string)
273 msg (SE, _("Type mismatch: expression has %s type, "
274 "but a string value is required here."),
275 atom_type_name (actual_type));
287 /* Recursive-descent expression parser. */
289 /* Considers whether *NODE may be coerced to type REQUIRED_TYPE.
290 Returns true if possible, false if disallowed.
292 If DO_COERCION is false, then *NODE is not modified and there
295 If DO_COERCION is true, we perform the coercion if possible,
296 modifying *NODE if necessary. If the coercion is not possible
297 then we free *NODE and set *NODE to a null pointer.
299 This function's interface is somewhat awkward. Use one of the
300 wrapper functions type_coercion(), type_coercion_assert(), or
301 is_coercible() instead. */
303 type_coercion_core (struct expression *e,
304 atom_type required_type,
305 union any_node **node,
306 const char *operator_name,
309 atom_type actual_type;
311 assert (!!do_coercion == (e != NULL));
314 /* Propagate error. Whatever caused the original error
315 already emitted an error message. */
319 actual_type = expr_node_returns (*node);
320 if (actual_type == required_type)
326 switch (required_type)
329 if (actual_type == OP_boolean)
331 /* To enforce strict typing rules, insert Boolean to
332 numeric "conversion". This conversion is a no-op,
333 so it will be removed later. */
335 *node = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, *node);
341 /* No coercion to string. */
345 if (actual_type == OP_number)
347 /* Convert numeric to boolean. */
349 *node = expr_allocate_unary (e, OP_NUM_TO_BOOLEAN, *node);
359 if ((*node)->type == OP_format
360 && fmt_check_input (&(*node)->format.f)
361 && fmt_check_type_compat (&(*node)->format.f, VAR_NUMERIC))
365 (*node)->type = OP_ni_format;
373 if ((*node)->type == OP_format
374 && fmt_check_output (&(*node)->format.f)
375 && fmt_check_type_compat (&(*node)->format.f, VAR_NUMERIC))
379 (*node)->type = OP_no_format;
386 if ((*node)->type == OP_NUM_VAR)
389 *node = (*node)->composite.args[0];
395 if ((*node)->type == OP_STR_VAR)
398 *node = (*node)->composite.args[0];
404 if ((*node)->type == OP_NUM_VAR || (*node)->type == OP_STR_VAR)
407 *node = (*node)->composite.args[0];
413 if ((*node)->type == OP_number
414 && floor ((*node)->number.n) == (*node)->number.n
415 && (*node)->number.n > 0 && (*node)->number.n < INT_MAX)
418 *node = expr_allocate_pos_int (e, (*node)->number.n);
429 msg (SE, _("Type mismatch while applying %s operator: "
430 "cannot convert %s to %s."),
432 atom_type_name (actual_type), atom_type_name (required_type));
438 /* Coerces *NODE to type REQUIRED_TYPE, and returns success. If
439 *NODE cannot be coerced to the desired type then we issue an
440 error message about operator OPERATOR_NAME and free *NODE. */
442 type_coercion (struct expression *e,
443 atom_type required_type, union any_node **node,
444 const char *operator_name)
446 return type_coercion_core (e, required_type, node, operator_name, true);
449 /* Coerces *NODE to type REQUIRED_TYPE.
450 Assert-fails if the coercion is disallowed. */
452 type_coercion_assert (struct expression *e,
453 atom_type required_type, union any_node **node)
455 int success = type_coercion_core (e, required_type, node, NULL, true);
459 /* Returns true if *NODE may be coerced to type REQUIRED_TYPE,
462 is_coercible (atom_type required_type, union any_node *const *node)
464 return type_coercion_core (NULL, required_type,
465 (union any_node **) node, NULL, false);
468 /* Returns true if ACTUAL_TYPE is a kind of REQUIRED_TYPE, false
471 is_compatible (atom_type required_type, atom_type actual_type)
473 return (required_type == actual_type
474 || (required_type == OP_var
475 && (actual_type == OP_num_var || actual_type == OP_str_var)));
478 /* How to parse an operator. */
481 int token; /* Token representing operator. */
482 operation_type type; /* Operation type representing operation. */
483 const char *name; /* Name of operator. */
486 /* Attempts to match the current token against the tokens for the
487 OP_CNT operators in OPS[]. If successful, returns true
488 and, if OPERATOR is non-null, sets *OPERATOR to the operator.
489 On failure, returns false and, if OPERATOR is non-null, sets
490 *OPERATOR to a null pointer. */
492 match_operator (struct lexer *lexer, const struct operator ops[], size_t op_cnt,
493 const struct operator **operator)
495 const struct operator *op;
497 for (op = ops; op < ops + op_cnt; op++)
499 if (op->token == '-')
500 lex_negative_to_dash (lexer);
501 if (lex_match (lexer, op->token))
503 if (operator != NULL)
508 if (operator != NULL)
514 check_operator (const struct operator *op, int arg_cnt, atom_type arg_type)
516 const struct operation *o;
520 o = &operations[op->type];
521 assert (o->arg_cnt == arg_cnt);
522 assert ((o->flags & OPF_ARRAY_OPERAND) == 0);
523 for (i = 0; i < arg_cnt; i++)
524 assert (is_compatible (arg_type, o->args[i]));
529 check_binary_operators (const struct operator ops[], size_t op_cnt,
534 for (i = 0; i < op_cnt; i++)
535 check_operator (&ops[i], 2, arg_type);
540 get_operand_type (const struct operator *op)
542 return operations[op->type].args[0];
545 /* Parses a chain of left-associative operator/operand pairs.
546 There are OP_CNT operators, specified in OPS[]. The
547 operators' operands must all be the same type. The next
548 higher level is parsed by PARSE_NEXT_LEVEL. If CHAIN_WARNING
549 is non-null, then it will be issued as a warning if more than
550 one operator/operand pair is parsed. */
551 static union any_node *
552 parse_binary_operators (struct lexer *lexer, struct expression *e, union any_node *node,
553 const struct operator ops[], size_t op_cnt,
554 parse_recursively_func *parse_next_level,
555 const char *chain_warning)
557 atom_type operand_type = get_operand_type (&ops[0]);
559 const struct operator *operator;
561 assert (check_binary_operators (ops, op_cnt, operand_type));
565 for (op_count = 0; match_operator (lexer, ops, op_cnt, &operator); op_count++)
569 /* Convert the left-hand side to type OPERAND_TYPE. */
570 if (!type_coercion (e, operand_type, &node, operator->name))
573 /* Parse the right-hand side and coerce to type
575 rhs = parse_next_level (lexer, e);
576 if (!type_coercion (e, operand_type, &rhs, operator->name))
578 node = expr_allocate_binary (e, operator->type, node, rhs);
581 if (op_count > 1 && chain_warning != NULL)
582 msg (SW, chain_warning);
587 static union any_node *
588 parse_inverting_unary_operator (struct lexer *lexer, struct expression *e,
589 const struct operator *op,
590 parse_recursively_func *parse_next_level)
592 union any_node *node;
595 check_operator (op, 1, get_operand_type (op));
598 while (match_operator (lexer, op, 1, NULL))
601 node = parse_next_level (lexer, e);
603 && type_coercion (e, get_operand_type (op), &node, op->name)
604 && op_count % 2 != 0)
605 return expr_allocate_unary (e, op->type, node);
610 /* Parses the OR level. */
611 static union any_node *
612 parse_or (struct lexer *lexer, struct expression *e)
614 static const struct operator op =
615 { T_OR, OP_OR, "logical disjunction (\"OR\")" };
617 return parse_binary_operators (lexer, e, parse_and (lexer, e), &op, 1, parse_and, NULL);
620 /* Parses the AND level. */
621 static union any_node *
622 parse_and (struct lexer *lexer, struct expression *e)
624 static const struct operator op =
625 { T_AND, OP_AND, "logical conjunction (\"AND\")" };
627 return parse_binary_operators (lexer, e, parse_not (lexer, e),
628 &op, 1, parse_not, NULL);
631 /* Parses the NOT level. */
632 static union any_node *
633 parse_not (struct lexer *lexer, struct expression *e)
635 static const struct operator op
636 = { T_NOT, OP_NOT, "logical negation (\"NOT\")" };
637 return parse_inverting_unary_operator (lexer, e, &op, parse_rel);
640 /* Parse relational operators. */
641 static union any_node *
642 parse_rel (struct lexer *lexer, struct expression *e)
644 const char *chain_warning =
645 _("Chaining relational operators (e.g. \"a < b < c\") will "
646 "not produce the mathematically expected result. "
647 "Use the AND logical operator to fix the problem "
648 "(e.g. \"a < b AND b < c\"). "
649 "If chaining is really intended, parentheses will disable "
650 "this warning (e.g. \"(a < b) < c\".)");
652 union any_node *node = parse_add (lexer, e);
657 switch (expr_node_returns (node))
662 static const struct operator ops[] =
664 { '=', OP_EQ, "numeric equality (\"=\")" },
665 { T_EQ, OP_EQ, "numeric equality (\"EQ\")" },
666 { T_GE, OP_GE, "numeric greater-than-or-equal-to (\">=\")" },
667 { T_GT, OP_GT, "numeric greater than (\">\")" },
668 { T_LE, OP_LE, "numeric less-than-or-equal-to (\"<=\")" },
669 { T_LT, OP_LT, "numeric less than (\"<\")" },
670 { T_NE, OP_NE, "numeric inequality (\"<>\")" },
673 return parse_binary_operators (lexer, e, node, ops,
674 sizeof ops / sizeof *ops,
675 parse_add, chain_warning);
680 static const struct operator ops[] =
682 { '=', OP_EQ_STRING, "string equality (\"=\")" },
683 { T_EQ, OP_EQ_STRING, "string equality (\"EQ\")" },
684 { T_GE, OP_GE_STRING, "string greater-than-or-equal-to (\">=\")" },
685 { T_GT, OP_GT_STRING, "string greater than (\">\")" },
686 { T_LE, OP_LE_STRING, "string less-than-or-equal-to (\"<=\")" },
687 { T_LT, OP_LT_STRING, "string less than (\"<\")" },
688 { T_NE, OP_NE_STRING, "string inequality (\"<>\")" },
691 return parse_binary_operators (lexer, e, node, ops,
692 sizeof ops / sizeof *ops,
693 parse_add, chain_warning);
701 /* Parses the addition and subtraction level. */
702 static union any_node *
703 parse_add (struct lexer *lexer, struct expression *e)
705 static const struct operator ops[] =
707 { '+', OP_ADD, "addition (\"+\")" },
708 { '-', OP_SUB, "subtraction (\"-\")" },
711 return parse_binary_operators (lexer, e, parse_mul (lexer, e),
712 ops, sizeof ops / sizeof *ops,
716 /* Parses the multiplication and division level. */
717 static union any_node *
718 parse_mul (struct lexer *lexer, struct expression *e)
720 static const struct operator ops[] =
722 { '*', OP_MUL, "multiplication (\"*\")" },
723 { '/', OP_DIV, "division (\"/\")" },
726 return parse_binary_operators (lexer, e, parse_neg (lexer, e),
727 ops, sizeof ops / sizeof *ops,
731 /* Parses the unary minus level. */
732 static union any_node *
733 parse_neg (struct lexer *lexer, struct expression *e)
735 static const struct operator op = { '-', OP_NEG, "negation (\"-\")" };
736 return parse_inverting_unary_operator (lexer, e, &op, parse_exp);
739 static union any_node *
740 parse_exp (struct lexer *lexer, struct expression *e)
742 static const struct operator op =
743 { T_EXP, OP_POW, "exponentiation (\"**\")" };
745 const char *chain_warning =
746 _("The exponentiation operator (\"**\") is left-associative, "
747 "even though right-associative semantics are more useful. "
748 "That is, \"a**b**c\" equals \"(a**b)**c\", not as \"a**(b**c)\". "
749 "To disable this warning, insert parentheses.");
751 return parse_binary_operators (lexer, e, parse_primary (lexer, e), &op, 1,
752 parse_primary, chain_warning);
755 /* Parses system variables. */
756 static union any_node *
757 parse_sysvar (struct lexer *lexer, struct expression *e)
759 if (lex_match_id (lexer, "$CASENUM"))
760 return expr_allocate_nullary (e, OP_CASENUM);
761 else if (lex_match_id (lexer, "$DATE"))
763 static const char *months[12] =
765 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
766 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
769 time_t last_proc_time = time_of_last_procedure (e->ds);
773 time = localtime (&last_proc_time);
774 sprintf (temp_buf, "%02d %s %02d", abs (time->tm_mday) % 100,
775 months[abs (time->tm_mon) % 12], abs (time->tm_year) % 100);
777 return expr_allocate_string_buffer (e, temp_buf, strlen (temp_buf));
779 else if (lex_match_id (lexer, "$TRUE"))
780 return expr_allocate_boolean (e, 1.0);
781 else if (lex_match_id (lexer, "$FALSE"))
782 return expr_allocate_boolean (e, 0.0);
783 else if (lex_match_id (lexer, "$SYSMIS"))
784 return expr_allocate_number (e, SYSMIS);
785 else if (lex_match_id (lexer, "$JDATE"))
787 time_t time = time_of_last_procedure (e->ds);
788 struct tm *tm = localtime (&time);
789 return expr_allocate_number (e, expr_ymd_to_ofs (tm->tm_year + 1900,
793 else if (lex_match_id (lexer, "$TIME"))
795 time_t time = time_of_last_procedure (e->ds);
796 struct tm *tm = localtime (&time);
797 return expr_allocate_number (e,
798 expr_ymd_to_date (tm->tm_year + 1900,
801 + tm->tm_hour * 60 * 60.
805 else if (lex_match_id (lexer, "$LENGTH"))
806 return expr_allocate_number (e, get_viewlength ());
807 else if (lex_match_id (lexer, "$WIDTH"))
808 return expr_allocate_number (e, get_viewwidth ());
811 msg (SE, _("Unknown system variable %s."), lex_tokid (lexer));
816 /* Parses numbers, varnames, etc. */
817 static union any_node *
818 parse_primary (struct lexer *lexer, struct expression *e)
820 switch (lex_token (lexer))
823 if (lex_look_ahead (lexer) == '(')
825 /* An identifier followed by a left parenthesis may be
826 a vector element reference. If not, it's a function
828 if (e->ds != NULL && dict_lookup_vector (dataset_dict (e->ds), lex_tokid (lexer)) != NULL)
829 return parse_vector_element (lexer, e);
831 return parse_function (lexer, e);
833 else if (lex_tokid (lexer)[0] == '$')
835 /* $ at the beginning indicates a system variable. */
836 return parse_sysvar (lexer, e);
838 else if (e->ds != NULL && dict_lookup_var (dataset_dict (e->ds), lex_tokid (lexer)))
840 /* It looks like a user variable.
841 (It could be a format specifier, but we'll assume
842 it's a variable unless proven otherwise. */
843 return allocate_unary_variable (e, parse_variable (lexer, dataset_dict (e->ds)));
847 /* Try to parse it as a format specifier. */
852 ok = parse_format_specifier (lexer, &fmt);
856 return expr_allocate_format (e, &fmt);
858 /* All attempts failed. */
859 msg (SE, _("Unknown identifier %s."), lex_tokid (lexer));
867 union any_node *node = expr_allocate_number (e, lex_tokval (lexer) );
874 union any_node *node = expr_allocate_string_buffer (
875 e, ds_cstr (lex_tokstr (lexer) ), ds_length (lex_tokstr (lexer) ));
882 union any_node *node;
884 node = parse_or (lexer, e);
885 if (node != NULL && !lex_match (lexer, ')'))
887 lex_error (lexer, _("expecting `)'"));
894 lex_error (lexer, _("in expression"));
899 static union any_node *
900 parse_vector_element (struct lexer *lexer, struct expression *e)
902 const struct vector *vector;
903 union any_node *element;
905 /* Find vector, skip token.
906 The caller must already have verified that the current token
907 is the name of a vector. */
908 vector = dict_lookup_vector (dataset_dict (e->ds), lex_tokid (lexer));
909 assert (vector != NULL);
912 /* Skip left parenthesis token.
913 The caller must have verified that the lookahead is a left
915 assert (lex_token (lexer) == '(');
918 element = parse_or (lexer, e);
919 if (!type_coercion (e, OP_number, &element, "vector indexing")
920 || !lex_match (lexer, ')'))
923 return expr_allocate_binary (e, (vector_get_type (vector) == VAR_NUMERIC
924 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR),
925 element, expr_allocate_vector (e, vector));
928 /* Individual function parsing. */
930 const struct operation operations[OP_first + OP_cnt] = {
935 word_matches (const char **test, const char **name)
937 size_t test_len = strcspn (*test, ".");
938 size_t name_len = strcspn (*name, ".");
939 if (test_len == name_len)
941 if (buf_compare_case (*test, *name, test_len))
944 else if (test_len < 3 || test_len > name_len)
948 if (buf_compare_case (*test, *name, test_len))
954 if (**test != **name)
966 compare_names (const char *test, const char *name, bool abbrev_ok)
973 if (!word_matches (&test, &name))
975 if (*name == '\0' && *test == '\0')
981 compare_strings (const char *test, const char *name, bool abbrev_ok UNUSED)
983 return strcasecmp (test, name);
987 lookup_function_helper (const char *name,
988 int (*compare) (const char *test, const char *name,
990 const struct operation **first,
991 const struct operation **last)
993 const struct operation *f;
995 for (f = operations + OP_function_first;
996 f <= operations + OP_function_last; f++)
997 if (!compare (name, f->name, !(f->flags & OPF_NO_ABBREV)))
1001 while (f <= operations + OP_function_last
1002 && !compare (name, f->name, !(f->flags & OPF_NO_ABBREV)))
1013 lookup_function (const char *name,
1014 const struct operation **first,
1015 const struct operation **last)
1017 *first = *last = NULL;
1018 return (lookup_function_helper (name, compare_strings, first, last)
1019 || lookup_function_helper (name, compare_names, first, last));
1023 extract_min_valid (char *s)
1025 char *p = strrchr (s, '.');
1027 || p[1] < '0' || p[1] > '9'
1028 || strspn (p + 1, "0123456789") != strlen (p + 1))
1031 return atoi (p + 1);
1035 function_arg_type (const struct operation *f, size_t arg_idx)
1037 assert (arg_idx < f->arg_cnt || (f->flags & OPF_ARRAY_OPERAND));
1039 return f->args[arg_idx < f->arg_cnt ? arg_idx : f->arg_cnt - 1];
1043 match_function (union any_node **args, int arg_cnt, const struct operation *f)
1047 if (arg_cnt < f->arg_cnt
1048 || (arg_cnt > f->arg_cnt && (f->flags & OPF_ARRAY_OPERAND) == 0)
1049 || arg_cnt - (f->arg_cnt - 1) < f->array_min_elems)
1052 for (i = 0; i < arg_cnt; i++)
1053 if (!is_coercible (function_arg_type (f, i), &args[i]))
1060 coerce_function_args (struct expression *e, const struct operation *f,
1061 union any_node **args, size_t arg_cnt)
1065 for (i = 0; i < arg_cnt; i++)
1066 type_coercion_assert (e, function_arg_type (f, i), &args[i]);
1070 validate_function_args (const struct operation *f, int arg_cnt, int min_valid)
1072 int array_arg_cnt = arg_cnt - (f->arg_cnt - 1);
1073 if (array_arg_cnt < f->array_min_elems)
1075 msg (SE, _("%s must have at least %d arguments in list."),
1076 f->prototype, f->array_min_elems);
1080 if ((f->flags & OPF_ARRAY_OPERAND)
1081 && array_arg_cnt % f->array_granularity != 0)
1083 if (f->array_granularity == 2)
1084 msg (SE, _("%s must have even number of arguments in list."),
1087 msg (SE, _("%s must have multiple of %d arguments in list."),
1088 f->prototype, f->array_granularity);
1092 if (min_valid != -1)
1094 if (f->array_min_elems == 0)
1096 assert ((f->flags & OPF_MIN_VALID) == 0);
1097 msg (SE, _("%s function does not accept a minimum valid "
1098 "argument count."), f->prototype);
1103 assert (f->flags & OPF_MIN_VALID);
1104 if (array_arg_cnt < f->array_min_elems)
1106 msg (SE, _("%s requires at least %d valid arguments in list."),
1107 f->prototype, f->array_min_elems);
1110 else if (min_valid > array_arg_cnt)
1112 msg (SE, _("With %s, "
1113 "using minimum valid argument count of %d "
1114 "does not make sense when passing only %d "
1115 "arguments in list."),
1116 f->prototype, min_valid, array_arg_cnt);
1126 add_arg (union any_node ***args, int *arg_cnt, int *arg_cap,
1127 union any_node *arg)
1129 if (*arg_cnt >= *arg_cap)
1132 *args = xrealloc (*args, sizeof **args * *arg_cap);
1135 (*args)[(*arg_cnt)++] = arg;
1139 put_invocation (struct string *s,
1140 const char *func_name, union any_node **args, size_t arg_cnt)
1144 ds_put_format (s, "%s(", func_name);
1145 for (i = 0; i < arg_cnt; i++)
1148 ds_put_cstr (s, ", ");
1149 ds_put_cstr (s, operations[expr_node_returns (args[i])].prototype);
1151 ds_put_char (s, ')');
1155 no_match (const char *func_name,
1156 union any_node **args, size_t arg_cnt,
1157 const struct operation *first, const struct operation *last)
1160 const struct operation *f;
1164 if (last - first == 1)
1166 ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1167 put_invocation (&s, func_name, args, arg_cnt);
1171 ds_put_cstr (&s, _("Function invocation "));
1172 put_invocation (&s, func_name, args, arg_cnt);
1173 ds_put_cstr (&s, _(" does not match any known function. Candidates are:"));
1175 for (f = first; f < last; f++)
1176 ds_put_format (&s, "\n%s", f->prototype);
1178 ds_put_char (&s, '.');
1180 msg (SE, "%s", ds_cstr (&s));
1185 static union any_node *
1186 parse_function (struct lexer *lexer, struct expression *e)
1189 const struct operation *f, *first, *last;
1191 union any_node **args = NULL;
1195 struct string func_name;
1199 ds_init_string (&func_name, lex_tokstr (lexer));
1200 min_valid = extract_min_valid (ds_cstr (lex_tokstr (lexer)));
1201 if (!lookup_function (ds_cstr (lex_tokstr (lexer)), &first, &last))
1203 msg (SE, _("No function or vector named %s."), ds_cstr (lex_tokstr (lexer)));
1204 ds_destroy (&func_name);
1209 if (!lex_force_match (lexer, '('))
1211 ds_destroy (&func_name);
1216 arg_cnt = arg_cap = 0;
1217 if (lex_token (lexer) != ')')
1220 if (lex_token (lexer) == T_ID && lex_look_ahead (lexer) == 'T')
1222 struct variable **vars;
1226 if (!parse_variables (lexer, dataset_dict (e->ds), &vars, &var_cnt, PV_SINGLE))
1228 for (i = 0; i < var_cnt; i++)
1229 add_arg (&args, &arg_cnt, &arg_cap,
1230 allocate_unary_variable (e, vars[i]));
1235 union any_node *arg = parse_or (lexer, e);
1239 add_arg (&args, &arg_cnt, &arg_cap, arg);
1241 if (lex_match (lexer, ')'))
1243 else if (!lex_match (lexer, ','))
1245 lex_error (lexer, _("expecting `,' or `)' invoking %s function"),
1251 for (f = first; f < last; f++)
1252 if (match_function (args, arg_cnt, f))
1256 no_match (ds_cstr (&func_name), args, arg_cnt, first, last);
1260 coerce_function_args (e, f, args, arg_cnt);
1261 if (!validate_function_args (f, arg_cnt, min_valid))
1264 if ((f->flags & OPF_EXTENSION) && get_syntax () == COMPATIBLE)
1265 msg (SW, _("%s is a PSPP extension."), f->prototype);
1266 if (f->flags & OPF_UNIMPLEMENTED)
1268 msg (SE, _("%s is not yet implemented."), f->prototype);
1271 if ((f->flags & OPF_PERM_ONLY) &&
1272 proc_in_temporary_transformations (e->ds))
1274 msg (SE, _("%s may not appear after TEMPORARY."), f->prototype);
1278 n = expr_allocate_composite (e, f - operations, args, arg_cnt);
1279 n->composite.min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1281 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1283 if (dataset_n_lag (e->ds) < 1)
1284 dataset_set_n_lag (e->ds, 1);
1286 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1289 assert (n->composite.arg_cnt == 2);
1290 assert (n->composite.args[1]->type == OP_pos_int);
1291 n_before = n->composite.args[1]->integer.i;
1292 if ( dataset_n_lag (e->ds) < n_before)
1293 dataset_set_n_lag (e->ds, n_before);
1297 ds_destroy (&func_name);
1302 ds_destroy (&func_name);
1306 /* Utility functions. */
1308 static struct expression *
1309 expr_create (struct dataset *ds)
1311 struct pool *pool = pool_create ();
1312 struct expression *e = pool_alloc (pool, sizeof *e);
1313 e->expr_pool = pool;
1315 e->eval_pool = pool_create_subpool (e->expr_pool);
1318 e->op_cnt = e->op_cap = 0;
1323 expr_node_returns (const union any_node *n)
1326 assert (is_operation (n->type));
1327 if (is_atom (n->type))
1329 else if (is_composite (n->type))
1330 return operations[n->type].returns;
1336 atom_type_name (atom_type type)
1338 assert (is_atom (type));
1339 return operations[type].name;
1343 expr_allocate_nullary (struct expression *e, operation_type op)
1345 return expr_allocate_composite (e, op, NULL, 0);
1349 expr_allocate_unary (struct expression *e, operation_type op,
1350 union any_node *arg0)
1352 return expr_allocate_composite (e, op, &arg0, 1);
1356 expr_allocate_binary (struct expression *e, operation_type op,
1357 union any_node *arg0, union any_node *arg1)
1359 union any_node *args[2];
1362 return expr_allocate_composite (e, op, args, 2);
1366 is_valid_node (union any_node *n)
1368 const struct operation *op;
1372 assert (is_operation (n->type));
1373 op = &operations[n->type];
1375 if (!is_atom (n->type))
1377 struct composite_node *c = &n->composite;
1379 assert (is_composite (n->type));
1380 assert (c->arg_cnt >= op->arg_cnt);
1381 for (i = 0; i < op->arg_cnt; i++)
1382 assert (is_compatible (op->args[i], expr_node_returns (c->args[i])));
1383 if (c->arg_cnt > op->arg_cnt && !is_operator (n->type))
1385 assert (op->flags & OPF_ARRAY_OPERAND);
1386 for (i = 0; i < c->arg_cnt; i++)
1387 assert (is_compatible (op->args[op->arg_cnt - 1],
1388 expr_node_returns (c->args[i])));
1396 expr_allocate_composite (struct expression *e, operation_type op,
1397 union any_node **args, size_t arg_cnt)
1402 n = pool_alloc (e->expr_pool, sizeof n->composite);
1404 n->composite.arg_cnt = arg_cnt;
1405 n->composite.args = pool_alloc (e->expr_pool,
1406 sizeof *n->composite.args * arg_cnt);
1407 for (i = 0; i < arg_cnt; i++)
1409 if (args[i] == NULL)
1411 n->composite.args[i] = args[i];
1413 memcpy (n->composite.args, args, sizeof *n->composite.args * arg_cnt);
1414 n->composite.min_valid = 0;
1415 assert (is_valid_node (n));
1420 expr_allocate_number (struct expression *e, double d)
1422 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1423 n->type = OP_number;
1429 expr_allocate_boolean (struct expression *e, double b)
1431 union any_node *n = pool_alloc (e->expr_pool, sizeof n->number);
1432 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1433 n->type = OP_boolean;
1439 expr_allocate_integer (struct expression *e, int i)
1441 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1442 n->type = OP_integer;
1448 expr_allocate_pos_int (struct expression *e, int i)
1450 union any_node *n = pool_alloc (e->expr_pool, sizeof n->integer);
1452 n->type = OP_pos_int;
1458 expr_allocate_vector (struct expression *e, const struct vector *vector)
1460 union any_node *n = pool_alloc (e->expr_pool, sizeof n->vector);
1461 n->type = OP_vector;
1462 n->vector.v = vector;
1467 expr_allocate_string_buffer (struct expression *e,
1468 const char *string, size_t length)
1470 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1471 n->type = OP_string;
1472 if (length > MAX_STRING)
1473 length = MAX_STRING;
1474 n->string.s = copy_string (e, string, length);
1479 expr_allocate_string (struct expression *e, struct substring s)
1481 union any_node *n = pool_alloc (e->expr_pool, sizeof n->string);
1482 n->type = OP_string;
1488 expr_allocate_variable (struct expression *e, struct variable *v)
1490 union any_node *n = pool_alloc (e->expr_pool, sizeof n->variable);
1491 n->type = var_is_numeric (v) ? OP_num_var : OP_str_var;
1497 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1499 union any_node *n = pool_alloc (e->expr_pool, sizeof n->format);
1500 n->type = OP_format;
1501 n->format.f = *format;
1505 /* Allocates a unary composite node that represents the value of
1506 variable V in expression E. */
1507 static union any_node *
1508 allocate_unary_variable (struct expression *e, struct variable *v)
1511 return expr_allocate_unary (e, var_is_numeric (v) ? OP_NUM_VAR : OP_STR_VAR,
1512 expr_allocate_variable (e, v));