1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2010, 2011, 2012, 2014 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/>. */
26 #include "data/case.h"
27 #include "data/dictionary.h"
28 #include "data/settings.h"
29 #include "data/variable.h"
30 #include "language/expressions/helpers.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/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/misc.h"
39 #include "libpspp/pool.h"
40 #include "libpspp/str.h"
42 #include "gl/c-strcase.h"
43 #include "gl/minmax.h"
44 #include "gl/xalloc.h"
48 /* Recursive descent parser in order of increasing precedence. */
49 typedef struct expr_node *parse_recursively_func (struct lexer *, struct expression *);
50 static parse_recursively_func parse_or, parse_and, parse_not;
51 static parse_recursively_func parse_rel, parse_add, parse_mul;
52 static parse_recursively_func parse_neg, parse_exp;
53 static parse_recursively_func parse_primary;
54 static parse_recursively_func parse_vector_element, parse_function;
56 /* Utility functions. */
57 static struct expression *expr_create (struct dataset *ds);
58 atom_type expr_node_returns (const struct expr_node *);
60 static const char *atom_type_name (atom_type);
61 static struct expression *finish_expression (struct expr_node *,
63 static bool type_check (const struct expression *, const struct expr_node *,
64 enum val_type expected_type);
65 static struct expr_node *allocate_unary_variable (struct expression *,
66 const struct variable *);
68 /* Public functions. */
70 /* Parses an expression of the given TYPE. If DS is nonnull then variables and
71 vectors within it may be referenced within the expression; otherwise, the
72 expression must not reference any variables or vectors. Returns the new
73 expression if successful or a null pointer otherwise. */
75 expr_parse (struct lexer *lexer, struct dataset *ds, enum val_type type)
77 assert (val_type_is_valid (type));
79 struct expression *e = expr_create (ds);
80 struct expr_node *n = parse_or (lexer, e);
81 if (!n || !type_check (e, n, type))
87 return finish_expression (expr_optimize (n, e), e);
90 /* Parses a boolean expression, otherwise similar to expr_parse(). */
92 expr_parse_bool (struct lexer *lexer, struct dataset *ds)
94 struct expression *e = expr_create (ds);
95 struct expr_node *n = parse_or (lexer, e);
102 atom_type actual_type = expr_node_returns (n);
103 if (actual_type == OP_number)
104 n = expr_allocate_binary (e, OP_EXPR_TO_BOOLEAN, n,
105 expr_allocate_expr_node (e, n));
106 else if (actual_type != OP_boolean)
108 msg_at (SE, expr_location (e, n),
109 _("Type mismatch: expression has %s type, "
110 "but a boolean value is required here."),
111 atom_type_name (actual_type));
116 return finish_expression (expr_optimize (n, e), e);
119 /* Parses a numeric expression that is intended to be assigned to newly created
120 variable NEW_VAR_NAME. (This allows for a better error message if the
121 expression is not numeric.) Otherwise similar to expr_parse(). */
123 expr_parse_new_variable (struct lexer *lexer, struct dataset *ds,
124 const char *new_var_name)
126 struct expression *e = expr_create (ds);
127 struct expr_node *n = parse_or (lexer, e);
134 atom_type actual_type = expr_node_returns (n);
135 if (actual_type != OP_number && actual_type != OP_boolean)
137 msg (SE, _("This command tries to create a new variable %s by assigning a "
138 "string value to it, but this is not supported. Use "
139 "the STRING command to create the new variable with the "
140 "correct width before assigning to it, e.g. STRING %s(A20)."),
141 new_var_name, new_var_name);
146 return finish_expression (expr_optimize (n, e), e);
149 /* Free expression E. */
151 expr_free (struct expression *e)
154 pool_destroy (e->expr_pool);
158 expr_parse_any (struct lexer *lexer, struct dataset *ds, bool optimize)
161 struct expression *e;
163 e = expr_create (ds);
164 n = parse_or (lexer, e);
172 n = expr_optimize (n, e);
173 return finish_expression (n, e);
176 /* Finishing up expression building. */
178 /* Height of an expression's stacks. */
181 int number_height; /* Height of number stack. */
182 int string_height; /* Height of string stack. */
185 /* Stack heights used by different kinds of arguments. */
186 static const struct stack_heights on_number_stack = {1, 0};
187 static const struct stack_heights on_string_stack = {0, 1};
188 static const struct stack_heights not_on_stack = {0, 0};
190 /* Returns the stack heights used by an atom of the given
192 static const struct stack_heights *
193 atom_type_stack (atom_type type)
195 assert (is_atom (type));
201 return &on_number_stack;
204 return &on_string_stack;
215 return ¬_on_stack;
222 /* Measures the stack height needed for node N, supposing that
223 the stack height is initially *HEIGHT and updating *HEIGHT to
224 the final stack height. Updates *MAX, if necessary, to
225 reflect the maximum intermediate or final height. */
227 measure_stack (const struct expr_node *n,
228 struct stack_heights *height, struct stack_heights *max)
230 const struct stack_heights *return_height;
232 if (is_composite (n->type))
234 struct stack_heights args;
238 for (i = 0; i < n->n_args; i++)
239 measure_stack (n->args[i], &args, max);
241 return_height = atom_type_stack (operations[n->type].returns);
244 return_height = atom_type_stack (n->type);
246 height->number_height += return_height->number_height;
247 height->string_height += return_height->string_height;
249 if (height->number_height > max->number_height)
250 max->number_height = height->number_height;
251 if (height->string_height > max->string_height)
252 max->string_height = height->string_height;
255 /* Allocates stacks within E sufficient for evaluating node N. */
257 allocate_stacks (struct expr_node *n, struct expression *e)
259 struct stack_heights initial = {0, 0};
260 struct stack_heights max = {0, 0};
262 measure_stack (n, &initial, &max);
263 e->number_stack = pool_alloc (e->expr_pool,
264 sizeof *e->number_stack * max.number_height);
265 e->string_stack = pool_alloc (e->expr_pool,
266 sizeof *e->string_stack * max.string_height);
269 /* Finalizes expression E for evaluating node N. */
270 static struct expression *
271 finish_expression (struct expr_node *n, struct expression *e)
273 /* Allocate stacks. */
274 allocate_stacks (n, e);
276 /* Output postfix representation. */
279 /* The eval_pool might have been used for allocating strings
280 during optimization. We need to keep those strings around
281 for all subsequent evaluations, so start a new eval_pool. */
282 e->eval_pool = pool_create_subpool (e->expr_pool);
287 /* Verifies that expression E, whose root node is *N, can be
288 converted to type EXPECTED_TYPE, inserting a conversion at *N
289 if necessary. Returns true if successful, false on failure. */
291 type_check (const struct expression *e, const struct expr_node *n,
292 enum val_type expected_type)
294 atom_type actual_type = expr_node_returns (n);
296 switch (expected_type)
299 if (actual_type != OP_number && actual_type != OP_boolean)
301 msg_at (SE, expr_location (e, n),
302 _("Type mismatch: expression has type '%s', "
303 "but a numeric value is required."),
304 atom_type_name (actual_type));
310 if (actual_type != OP_string)
312 msg_at (SE, expr_location (e, n),
313 _("Type mismatch: expression has type '%s', "
314 "but a string value is required."),
315 atom_type_name (actual_type));
327 /* Recursive-descent expression parser. */
330 free_msg_location (void *loc_)
332 struct msg_location *loc = loc_;
333 msg_location_destroy (loc);
337 expr_location__ (struct expression *e,
338 const struct expr_node *node,
339 const struct msg_location **minp,
340 const struct msg_location **maxp)
342 struct msg_location *loc = node->location;
345 const struct msg_location *min = *minp;
348 || loc->start.line < min->start.line
349 || (loc->start.line == min->start.line
350 && loc->start.column < min->start.column)))
353 const struct msg_location *max = *maxp;
356 || loc->end.line > max->end.line
357 || (loc->end.line == max->end.line
358 && loc->end.column > max->end.column)))
364 if (is_composite (node->type))
365 for (size_t i = 0; i < node->n_args; i++)
366 expr_location__ (e, node->args[i], minp, maxp);
369 /* Returns the source code location corresponding to expression NODE, computing
370 it lazily if needed. */
371 const struct msg_location *
372 expr_location (const struct expression *e_, const struct expr_node *node_)
374 struct expr_node *node = CONST_CAST (struct expr_node *, node_);
380 struct expression *e = CONST_CAST (struct expression *, e_);
381 const struct msg_location *min = NULL;
382 const struct msg_location *max = NULL;
383 expr_location__ (e, node, &min, &max);
386 node->location = msg_location_dup (min);
387 node->location->end = max->end;
388 pool_register (e->expr_pool, free_msg_location, node->location);
391 return node->location;
394 /* Sets e->location to the tokens in S's lexer from offset START_OFS to the
395 token before the current one. Has no effect if E already has a location or
398 expr_add_location (struct lexer *lexer, struct expression *e,
399 int start_ofs, struct expr_node *node)
401 if (node && !node->location)
403 node->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
404 pool_register (e->expr_pool, free_msg_location, node->location);
409 type_coercion__ (struct expression *e, struct expr_node *node, size_t arg_idx,
412 assert (!!do_coercion == (e != NULL));
417 struct expr_node **argp = &node->args[arg_idx];
418 struct expr_node *arg = *argp;
422 const struct operation *op = &operations[node->type];
423 atom_type required_type = op->args[MIN (arg_idx, op->n_args - 1)];
424 atom_type actual_type = expr_node_returns (arg);
425 if (actual_type == required_type)
431 switch (required_type)
434 if (actual_type == OP_boolean)
436 /* To enforce strict typing rules, insert Boolean to
437 numeric "conversion". This conversion is a no-op,
438 so it will be removed later. */
440 *argp = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, arg);
446 /* No coercion to string. */
450 if (actual_type == OP_number)
452 /* Convert numeric to boolean. */
454 *argp = expr_allocate_binary (e, OP_OPERAND_TO_BOOLEAN, arg,
455 expr_allocate_expr_node (e, node));
461 if (actual_type == OP_number)
463 /* Convert number to integer. */
465 *argp = expr_allocate_unary (e, OP_NUM_TO_INTEGER, arg);
475 if (arg->type == OP_format
476 && fmt_check_input (&arg->format)
477 && fmt_check_type_compat (&arg->format, VAL_NUMERIC))
481 arg->type = OP_ni_format;
489 if (arg->type == OP_format
490 && fmt_check_output (&arg->format)
491 && fmt_check_type_compat (&arg->format, VAL_NUMERIC))
495 arg->type = OP_no_format;
502 if (arg->type == OP_NUM_VAR)
505 *argp = arg->args[0];
511 if (arg->type == OP_STR_VAR)
514 *argp = arg->args[0];
520 if (arg->type == OP_NUM_VAR || arg->type == OP_STR_VAR)
523 *argp = arg->args[0];
529 if (arg->type == OP_number
530 && floor (arg->number) == arg->number
531 && arg->number > 0 && arg->number < INT_MAX)
534 *argp = expr_allocate_pos_int (e, arg->number);
546 type_coercion (struct expression *e, struct expr_node *node, size_t arg_idx)
548 return type_coercion__ (e, node, arg_idx, true);
552 is_coercible (const struct expr_node *node_, size_t arg_idx)
554 struct expr_node *node = CONST_CAST (struct expr_node *, node_);
555 return type_coercion__ (NULL, node, arg_idx, false);
558 /* How to parse an operator.
560 Some operators support both numeric and string operators. For those,
561 'num_op' and 'str_op' are both nonzero. Otherwise, only one 'num_op' is
562 nonzero. (PSPP doesn't have any string-only operators.) */
565 enum token_type token; /* Operator token. */
566 operation_type num_op; /* Operation for numeric operands (or 0). */
567 operation_type str_op; /* Operation for string operands (or 0). */
570 static operation_type
571 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops,
572 const struct expr_node *lhs)
574 bool lhs_is_numeric = operations[lhs->type].returns != OP_string;
575 for (const struct operator *op = ops; op < ops + n_ops; op++)
576 if (lex_token (lexer) == op->token)
578 if (op->token != T_NEG_NUM)
581 return op->str_op && !lhs_is_numeric ? op->str_op : op->num_op;
587 operator_name (enum token_type token)
589 return token == T_NEG_NUM ? "-" : token_type_to_string (token);
592 static struct expr_node *
593 parse_binary_operators__ (struct lexer *lexer, struct expression *e,
594 const struct operator ops[], size_t n_ops,
595 parse_recursively_func *parse_next_level,
596 const char *chain_warning, struct expr_node *lhs)
598 for (int op_count = 0; ; op_count++)
600 enum token_type token = lex_token (lexer);
601 operation_type optype = match_operator (lexer, ops, n_ops, lhs);
604 if (op_count > 1 && chain_warning)
605 msg_at (SW, expr_location (e, lhs), "%s", chain_warning);
610 struct expr_node *rhs = parse_next_level (lexer, e);
614 struct expr_node *node = expr_allocate_binary (e, optype, lhs, rhs);
615 if (!is_coercible (node, 0) || !is_coercible (node, 1))
618 for (size_t i = 0; i < n_ops; i++)
619 if (ops[i].token == token)
620 both = ops[i].num_op && ops[i].str_op;
622 const char *name = operator_name (token);
624 msg_at (SE, expr_location (e, node),
625 _("Both operands of %s must have the same type."), name);
626 else if (operations[node->type].args[0] != OP_string)
627 msg_at (SE, expr_location (e, node),
628 _("Both operands of %s must be numeric."), name);
630 msg_at (SE, expr_location (e, node),
631 _("Both operands of %s must be strings."), name);
633 msg_at (SN, expr_location (e, node->args[0]),
634 _("This operand has type '%s'."),
635 atom_type_name (expr_node_returns (node->args[0])));
636 msg_at (SN, expr_location (e, node->args[1]),
637 _("This operand has type '%s'."),
638 atom_type_name (expr_node_returns (node->args[1])));
643 if (!type_coercion (e, node, 0) || !type_coercion (e, node, 1))
650 static struct expr_node *
651 parse_binary_operators (struct lexer *lexer, struct expression *e,
652 const struct operator ops[], size_t n_ops,
653 parse_recursively_func *parse_next_level,
654 const char *chain_warning)
656 struct expr_node *lhs = parse_next_level (lexer, e);
660 return parse_binary_operators__ (lexer, e, ops, n_ops, parse_next_level,
664 static struct expr_node *
665 parse_inverting_unary_operator (struct lexer *lexer, struct expression *e,
666 const struct operator *op,
667 parse_recursively_func *parse_next_level)
669 int start_ofs = lex_ofs (lexer);
670 unsigned int op_count = 0;
671 while (lex_match (lexer, op->token))
674 struct expr_node *inner = parse_next_level (lexer, e);
675 if (!inner || !op_count)
678 struct expr_node *outer = expr_allocate_unary (e, op->num_op, inner);
679 expr_add_location (lexer, e, start_ofs, outer);
681 if (!type_coercion (e, outer, 0))
683 assert (operations[outer->type].args[0] != OP_string);
685 const char *name = operator_name (op->token);
686 msg_at (SE, expr_location (e, outer),
687 _("The unary %s operator requires a numeric operand."), name);
689 msg_at (SN, expr_location (e, outer->args[0]),
690 _("The operand of %s has type '%s'."),
691 name, atom_type_name (expr_node_returns (outer->args[0])));
696 return op_count % 2 ? outer : outer->args[0];
699 /* Parses the OR level. */
700 static struct expr_node *
701 parse_or (struct lexer *lexer, struct expression *e)
703 static const struct operator op = { .token = T_OR, .num_op = OP_OR };
704 return parse_binary_operators (lexer, e, &op, 1, parse_and, NULL);
707 /* Parses the AND level. */
708 static struct expr_node *
709 parse_and (struct lexer *lexer, struct expression *e)
711 static const struct operator op = { .token = T_AND, .num_op = OP_AND };
713 return parse_binary_operators (lexer, e, &op, 1, parse_not, NULL);
716 /* Parses the NOT level. */
717 static struct expr_node *
718 parse_not (struct lexer *lexer, struct expression *e)
720 static const struct operator op = { .token = T_NOT, .num_op = OP_NOT };
721 return parse_inverting_unary_operator (lexer, e, &op, parse_rel);
724 /* Parse relational operators. */
725 static struct expr_node *
726 parse_rel (struct lexer *lexer, struct expression *e)
728 const char *chain_warning =
729 _("Chaining relational operators (e.g. `a < b < c') will "
730 "not produce the mathematically expected result. "
731 "Use the AND logical operator to fix the problem "
732 "(e.g. `a < b AND b < c'). "
733 "To disable this warning, insert parentheses.");
735 static const struct operator ops[] =
737 { .token = T_EQUALS, .num_op = OP_EQ, .str_op = OP_EQ_STRING },
738 { .token = T_EQ, .num_op = OP_EQ, .str_op = OP_EQ_STRING },
739 { .token = T_GE, .num_op = OP_GE, .str_op = OP_GE_STRING },
740 { .token = T_GT, .num_op = OP_GT, .str_op = OP_GT_STRING },
741 { .token = T_LE, .num_op = OP_LE, .str_op = OP_LE_STRING },
742 { .token = T_LT, .num_op = OP_LT, .str_op = OP_LT_STRING },
743 { .token = T_NE, .num_op = OP_NE, .str_op = OP_NE_STRING },
746 return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
747 parse_add, chain_warning);
750 /* Parses the addition and subtraction level. */
751 static struct expr_node *
752 parse_add (struct lexer *lexer, struct expression *e)
754 static const struct operator ops[] =
756 { .token = T_PLUS, .num_op = OP_ADD },
757 { .token = T_DASH, .num_op = OP_SUB },
758 { .token = T_NEG_NUM, .num_op = OP_ADD },
761 return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
765 /* Parses the multiplication and division level. */
766 static struct expr_node *
767 parse_mul (struct lexer *lexer, struct expression *e)
769 static const struct operator ops[] =
771 { .token = T_ASTERISK, .num_op = OP_MUL },
772 { .token = T_SLASH, .num_op = OP_DIV },
775 return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
779 /* Parses the unary minus level. */
780 static struct expr_node *
781 parse_neg (struct lexer *lexer, struct expression *e)
783 static const struct operator op = { .token = T_DASH, .num_op = OP_NEG };
784 return parse_inverting_unary_operator (lexer, e, &op, parse_exp);
787 static struct expr_node *
788 parse_exp (struct lexer *lexer, struct expression *e)
790 static const struct operator op = { .token = T_EXP, .num_op = OP_POW };
792 const char *chain_warning =
793 _("The exponentiation operator (`**') is left-associative: "
794 "`a**b**c' equals `(a**b)**c', not `a**(b**c)'. "
795 "To disable this warning, insert parentheses.");
797 if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
798 return parse_binary_operators (lexer, e, &op, 1,
799 parse_primary, chain_warning);
801 /* Special case for situations like "-5**6", which must be parsed as
804 int start_ofs = lex_ofs (lexer);
805 struct expr_node *lhs = expr_allocate_number (e, -lex_tokval (lexer));
807 expr_add_location (lexer, e, start_ofs, lhs);
809 struct expr_node *node = parse_binary_operators__ (
810 lexer, e, &op, 1, parse_primary, chain_warning, lhs);
814 node = expr_allocate_unary (e, OP_NEG, node);
815 expr_add_location (lexer, e, start_ofs, node);
820 ymd_to_offset (int y, int m, int d)
823 double retval = calendar_gregorian_to_offset (
824 y, m, d, settings_get_fmt_settings (), &error);
827 msg (SE, "%s", error);
833 static struct expr_node *
834 expr_date (struct expression *e, int year_digits)
836 static const char *months[12] =
838 "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
839 "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
842 time_t last_proc_time = time_of_last_procedure (e->ds);
843 struct tm *time = localtime (&last_proc_time);
845 char *tmp = (year_digits == 2
846 ? xasprintf ("%02d-%s-%02d", time->tm_mday, months[time->tm_mon],
848 : xasprintf ("%02d-%s-%04d", time->tm_mday, months[time->tm_mon],
849 time->tm_year + 1900));
852 ss_alloc_substring_pool (&s, ss_cstr (tmp), e->expr_pool);
856 return expr_allocate_string (e, s);
859 /* Parses system variables. */
860 static struct expr_node *
861 parse_sysvar (struct lexer *lexer, struct expression *e)
863 if (lex_match_id (lexer, "$CASENUM"))
864 return expr_allocate_nullary (e, OP_CASENUM);
865 else if (lex_match_id (lexer, "$DATE"))
866 return expr_date (e, 2);
867 else if (lex_match_id (lexer, "$DATE11"))
868 return expr_date (e, 4);
869 else if (lex_match_id (lexer, "$TRUE"))
870 return expr_allocate_boolean (e, 1.0);
871 else if (lex_match_id (lexer, "$FALSE"))
872 return expr_allocate_boolean (e, 0.0);
873 else if (lex_match_id (lexer, "$SYSMIS"))
874 return expr_allocate_number (e, SYSMIS);
875 else if (lex_match_id (lexer, "$JDATE"))
877 time_t time = time_of_last_procedure (e->ds);
878 struct tm *tm = localtime (&time);
879 return expr_allocate_number (e, ymd_to_offset (tm->tm_year + 1900,
883 else if (lex_match_id (lexer, "$TIME"))
885 time_t time = time_of_last_procedure (e->ds);
886 struct tm *tm = localtime (&time);
887 return expr_allocate_number (e, ymd_to_offset (tm->tm_year + 1900,
890 + tm->tm_hour * 60 * 60.
894 else if (lex_match_id (lexer, "$LENGTH"))
895 return expr_allocate_number (e, settings_get_viewlength ());
896 else if (lex_match_id (lexer, "$WIDTH"))
897 return expr_allocate_number (e, settings_get_viewwidth ());
900 msg (SE, _("Unknown system variable %s."), lex_tokcstr (lexer));
905 /* Parses numbers, varnames, etc. */
906 static struct expr_node *
907 parse_primary__ (struct lexer *lexer, struct expression *e)
909 switch (lex_token (lexer))
912 if (lex_next_token (lexer, 1) == T_LPAREN)
914 /* An identifier followed by a left parenthesis may be
915 a vector element reference. If not, it's a function
917 if (e->ds != NULL && dict_lookup_vector (dataset_dict (e->ds), lex_tokcstr (lexer)) != NULL)
918 return parse_vector_element (lexer, e);
920 return parse_function (lexer, e);
922 else if (lex_tokcstr (lexer)[0] == '$')
924 /* $ at the beginning indicates a system variable. */
925 return parse_sysvar (lexer, e);
927 else if (e->ds != NULL && dict_lookup_var (dataset_dict (e->ds), lex_tokcstr (lexer)))
929 /* It looks like a user variable.
930 (It could be a format specifier, but we'll assume
931 it's a variable unless proven otherwise. */
932 return allocate_unary_variable (e, parse_variable (lexer, dataset_dict (e->ds)));
936 /* Try to parse it as a format specifier. */
941 ok = parse_format_specifier (lexer, &fmt);
945 return expr_allocate_format (e, &fmt);
947 /* All attempts failed. */
948 msg (SE, _("Unknown identifier %s."), lex_tokcstr (lexer));
956 struct expr_node *node = expr_allocate_number (e, lex_tokval (lexer));
963 const char *dict_encoding;
964 struct expr_node *node;
967 dict_encoding = (e->ds != NULL
968 ? dict_get_encoding (dataset_dict (e->ds))
970 s = recode_string_pool (dict_encoding, "UTF-8", lex_tokcstr (lexer),
971 ss_length (lex_tokss (lexer)), e->expr_pool);
972 node = expr_allocate_string (e, ss_cstr (s));
981 struct expr_node *node = parse_or (lexer, e);
982 return !node || !lex_force_match (lexer, T_RPAREN) ? NULL : node;
986 lex_error (lexer, NULL);
991 static struct expr_node *
992 parse_primary (struct lexer *lexer, struct expression *e)
994 int start_ofs = lex_ofs (lexer);
995 struct expr_node *node = parse_primary__ (lexer, e);
996 expr_add_location (lexer, e, start_ofs, node);
1000 static struct expr_node *
1001 parse_vector_element (struct lexer *lexer, struct expression *e)
1003 int vector_start_ofs = lex_ofs (lexer);
1005 /* Find vector, skip token.
1006 The caller must already have verified that the current token
1007 is the name of a vector. */
1008 const struct vector *vector = dict_lookup_vector (dataset_dict (e->ds),
1009 lex_tokcstr (lexer));
1010 assert (vector != NULL);
1013 /* Skip left parenthesis token.
1014 The caller must have verified that the lookahead is a left
1016 assert (lex_token (lexer) == T_LPAREN);
1019 int element_start_ofs = lex_ofs (lexer);
1020 struct expr_node *element = parse_or (lexer, e);
1023 expr_add_location (lexer, e, element_start_ofs, element);
1025 if (!lex_match (lexer, T_RPAREN))
1028 operation_type type = (vector_get_type (vector) == VAL_NUMERIC
1029 ? OP_VEC_ELEM_NUM : OP_VEC_ELEM_STR);
1030 struct expr_node *node = expr_allocate_binary (
1031 e, type, element, expr_allocate_vector (e, vector));
1032 expr_add_location (lexer, e, vector_start_ofs, node);
1034 if (!type_coercion (e, node, 0))
1036 msg_at (SE, expr_location (e, node),
1037 _("A vector index must be numeric."));
1039 msg_at (SN, expr_location (e, node->args[0]),
1040 _("This vector index has type '%s'."),
1041 atom_type_name (expr_node_returns (node->args[0])));
1049 /* Individual function parsing. */
1051 const struct operation operations[OP_first + n_OP] = {
1052 #include "parse.inc"
1056 word_matches (const char **test, const char **name)
1058 size_t test_len = strcspn (*test, ".");
1059 size_t name_len = strcspn (*name, ".");
1060 if (test_len == name_len)
1062 if (buf_compare_case (*test, *name, test_len))
1065 else if (test_len < 3 || test_len > name_len)
1069 if (buf_compare_case (*test, *name, test_len))
1075 if (**test != **name)
1086 /* Returns 0 if TOKEN and FUNC do not match,
1087 1 if TOKEN is an acceptable abbreviation for FUNC,
1088 2 if TOKEN equals FUNC. */
1090 compare_function_names (const char *token_, const char *func_)
1092 const char *token = token_;
1093 const char *func = func_;
1094 while (*token || *func)
1095 if (!word_matches (&token, &func))
1097 return !c_strcasecmp (token_, func_) ? 2 : 1;
1101 lookup_function (const char *token,
1102 const struct operation **first,
1103 const struct operation **last)
1105 *first = *last = NULL;
1106 const struct operation *best = NULL;
1108 for (const struct operation *f = operations + OP_function_first;
1109 f <= operations + OP_function_last; f++)
1111 int score = compare_function_names (token, f->name);
1117 else if (score == 1 && !(f->flags & OPF_NO_ABBREV) && !best)
1126 const struct operation *f = best;
1127 while (f <= operations + OP_function_last
1128 && !c_strcasecmp (f->name, best->name))
1136 extract_min_valid (const char *s)
1138 char *p = strrchr (s, '.');
1140 || p[1] < '0' || p[1] > '9'
1141 || strspn (p + 1, "0123456789") != strlen (p + 1))
1144 return atoi (p + 1);
1148 match_function__ (struct expr_node *node, const struct operation *f)
1150 if (node->n_args < f->n_args
1151 || (node->n_args > f->n_args && (f->flags & OPF_ARRAY_OPERAND) == 0)
1152 || node->n_args - (f->n_args - 1) < f->array_min_elems)
1155 node->type = f - operations;
1156 for (size_t i = 0; i < node->n_args; i++)
1157 if (!is_coercible (node, i))
1163 static const struct operation *
1164 match_function (struct expr_node *node,
1165 const struct operation *first, const struct operation *last)
1167 for (const struct operation *f = first; f < last; f++)
1168 if (match_function__ (node, f))
1174 validate_function_args (const struct expression *e, const struct expr_node *n,
1175 const struct operation *f, int n_args, int min_valid)
1177 /* Count the function arguments that go into the trailing array (if any). We
1178 know that there must be at least the minimum number because
1179 match_function() already checked. */
1180 int array_n_args = n_args - (f->n_args - 1);
1181 assert (array_n_args >= f->array_min_elems);
1183 if ((f->flags & OPF_ARRAY_OPERAND)
1184 && array_n_args % f->array_granularity != 0)
1186 /* RANGE is the only case we have so far. It has paired arguments with
1187 one initial argument, and that's the only special case we deal with
1189 assert (f->array_granularity == 2);
1190 assert (n_args % 2 == 0);
1191 msg_at (SE, expr_location (e, n),
1192 _("%s must have an odd number of arguments."), f->prototype);
1196 if (min_valid != -1)
1198 if (f->array_min_elems == 0)
1200 assert ((f->flags & OPF_MIN_VALID) == 0);
1201 msg_at (SE, expr_location (e, n),
1202 _("%s function cannot accept suffix .%d to specify the "
1203 "minimum number of valid arguments."),
1204 f->prototype, min_valid);
1209 assert (f->flags & OPF_MIN_VALID);
1210 if (min_valid > array_n_args)
1212 msg_at (SE, expr_location (e, n),
1213 _("For %s with %d arguments, at most %d (not %d) may be "
1214 "required to be valid."),
1215 f->prototype, n_args, array_n_args, min_valid);
1225 add_arg (struct expr_node ***args, size_t *n_args, size_t *allocated_args,
1226 struct expr_node *arg,
1227 struct expression *e, struct lexer *lexer, int arg_start_ofs)
1229 if (*n_args >= *allocated_args)
1230 *args = x2nrealloc (*args, allocated_args, sizeof **args);
1232 expr_add_location (lexer, e, arg_start_ofs, arg);
1233 (*args)[(*n_args)++] = arg;
1237 put_invocation (struct string *s,
1238 const char *func_name, struct expr_node *node)
1242 ds_put_format (s, "%s(", func_name);
1243 for (i = 0; i < node->n_args; i++)
1246 ds_put_cstr (s, ", ");
1247 ds_put_cstr (s, operations[expr_node_returns (node->args[i])].prototype);
1249 ds_put_byte (s, ')');
1253 no_match (struct expression *e, const char *func_name, struct expr_node *node,
1254 const struct operation *first, const struct operation *last)
1257 const struct operation *f;
1261 if (last - first == 1)
1263 ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1264 put_invocation (&s, func_name, node);
1268 ds_put_cstr (&s, _("Function invocation "));
1269 put_invocation (&s, func_name, node);
1270 ds_put_cstr (&s, _(" does not match any known function. Candidates are:"));
1272 for (f = first; f < last; f++)
1273 ds_put_format (&s, "\n%s", f->prototype);
1275 ds_put_byte (&s, '.');
1277 msg_at (SE, expr_location (e, node), "%s", ds_cstr (&s));
1282 static struct expr_node *
1283 parse_function (struct lexer *lexer, struct expression *e)
1285 struct string func_name;
1286 ds_init_substring (&func_name, lex_tokss (lexer));
1288 int min_valid = extract_min_valid (lex_tokcstr (lexer));
1290 const struct operation *first, *last;
1291 if (!lookup_function (lex_tokcstr (lexer), &first, &last))
1293 msg (SE, _("No function or vector named %s."), lex_tokcstr (lexer));
1294 ds_destroy (&func_name);
1298 int func_start_ofs = lex_ofs (lexer);
1300 if (!lex_force_match (lexer, T_LPAREN))
1302 ds_destroy (&func_name);
1306 struct expr_node **args = NULL;
1308 size_t allocated_args = 0;
1309 if (lex_token (lexer) != T_RPAREN)
1312 int arg_start_ofs = lex_ofs (lexer);
1313 if (lex_token (lexer) == T_ID
1314 && lex_next_token (lexer, 1) == T_TO)
1316 const struct variable **vars;
1319 if (!parse_variables_const (lexer, dataset_dict (e->ds),
1320 &vars, &n_vars, PV_SINGLE))
1322 for (size_t i = 0; i < n_vars; i++)
1323 add_arg (&args, &n_args, &allocated_args,
1324 allocate_unary_variable (e, vars[i]),
1325 e, lexer, arg_start_ofs);
1330 struct expr_node *arg = parse_or (lexer, e);
1334 add_arg (&args, &n_args, &allocated_args, arg,
1335 e, lexer, arg_start_ofs);
1337 if (lex_match (lexer, T_RPAREN))
1339 else if (!lex_match (lexer, T_COMMA))
1341 lex_error_expecting (lexer, "`,'", "`)'");
1346 struct expr_node *n = expr_allocate_composite (e, first - operations,
1348 expr_add_location (lexer, e, func_start_ofs, n);
1349 const struct operation *f = match_function (n, first, last);
1352 no_match (e, ds_cstr (&func_name), n, first, last);
1355 n->type = f - operations;
1356 n->min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1358 for (size_t i = 0; i < n_args; i++)
1359 if (!type_coercion (e, n, i))
1361 /* Unreachable because match_function already checked that the
1362 arguments were coercible. */
1365 if (!validate_function_args (e, n, f, n_args, min_valid))
1368 if ((f->flags & OPF_EXTENSION) && settings_get_syntax () == COMPATIBLE)
1369 msg_at (SW, expr_location (e, n),
1370 _("%s is a PSPP extension."), f->prototype);
1371 if (f->flags & OPF_UNIMPLEMENTED)
1373 msg_at (SE, expr_location (e, n),
1374 _("%s is not available in this version of PSPP."), f->prototype);
1377 if ((f->flags & OPF_PERM_ONLY) &&
1378 proc_in_temporary_transformations (e->ds))
1380 msg_at (SE, expr_location (e, n),
1381 _("%s may not appear after %s."), f->prototype, "TEMPORARY");
1385 if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1386 dataset_need_lag (e->ds, 1);
1387 else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1389 assert (n->n_args == 2);
1390 assert (n->args[1]->type == OP_pos_int);
1391 dataset_need_lag (e->ds, n->args[1]->integer);
1395 ds_destroy (&func_name);
1400 ds_destroy (&func_name);
1404 /* Utility functions. */
1406 static struct expression *
1407 expr_create (struct dataset *ds)
1409 struct pool *pool = pool_create ();
1410 struct expression *e = pool_alloc (pool, sizeof *e);
1411 *e = (struct expression) {
1414 .eval_pool = pool_create_subpool (pool),
1420 expr_node_returns (const struct expr_node *n)
1423 assert (is_operation (n->type));
1424 if (is_atom (n->type))
1426 else if (is_composite (n->type))
1427 return operations[n->type].returns;
1433 atom_type_name (atom_type type)
1435 assert (is_atom (type));
1437 /* The Boolean type is purely an internal concept that the documentation
1438 doesn't mention, so it might confuse users if we talked about them in
1440 return type == OP_boolean ? "number" : operations[type].name;
1444 expr_allocate_nullary (struct expression *e, operation_type op)
1446 return expr_allocate_composite (e, op, NULL, 0);
1450 expr_allocate_unary (struct expression *e, operation_type op,
1451 struct expr_node *arg0)
1453 return expr_allocate_composite (e, op, &arg0, 1);
1457 expr_allocate_binary (struct expression *e, operation_type op,
1458 struct expr_node *arg0, struct expr_node *arg1)
1460 struct expr_node *args[2];
1463 return expr_allocate_composite (e, op, args, 2);
1467 expr_allocate_composite (struct expression *e, operation_type op,
1468 struct expr_node **args, size_t n_args)
1470 for (size_t i = 0; i < n_args; i++)
1474 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1475 *n = (struct expr_node) {
1478 .args = pool_clone (e->expr_pool, args, sizeof *n->args * n_args),
1484 expr_allocate_number (struct expression *e, double d)
1486 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1487 *n = (struct expr_node) { .type = OP_number, .number = d };
1492 expr_allocate_boolean (struct expression *e, double b)
1494 assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1496 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1497 *n = (struct expr_node) { .type = OP_boolean, .number = b };
1502 expr_allocate_integer (struct expression *e, int i)
1504 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1505 *n = (struct expr_node) { .type = OP_integer, .integer = i };
1510 expr_allocate_pos_int (struct expression *e, int i)
1514 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1515 *n = (struct expr_node) { .type = OP_pos_int, .integer = i };
1520 expr_allocate_vector (struct expression *e, const struct vector *vector)
1522 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1523 *n = (struct expr_node) { .type = OP_vector, .vector = vector };
1528 expr_allocate_string (struct expression *e, struct substring s)
1530 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1531 *n = (struct expr_node) { .type = OP_string, .string = s };
1536 expr_allocate_variable (struct expression *e, const struct variable *v)
1538 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1539 *n = (struct expr_node) {
1540 .type = var_is_numeric (v) ? OP_num_var : OP_str_var,
1547 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1549 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1550 *n = (struct expr_node) { .type = OP_format, .format = *format };
1555 expr_allocate_expr_node (struct expression *e,
1556 const struct expr_node *expr_node)
1558 struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1559 *n = (struct expr_node) { .type = OP_expr_node, .expr_node = expr_node };
1563 /* Allocates a unary composite node that represents the value of
1564 variable V in expression E. */
1565 static struct expr_node *
1566 allocate_unary_variable (struct expression *e, const struct variable *v)
1569 return expr_allocate_unary (e, var_is_numeric (v) ? OP_NUM_VAR : OP_STR_VAR,
1570 expr_allocate_variable (e, v));
1573 /* Export function details to other modules. */
1575 /* Returns the operation structure for the function with the
1577 const struct operation *
1578 expr_get_function (size_t idx)
1580 assert (idx < n_OP_function);
1581 return &operations[OP_function_first + idx];
1584 /* Returns the number of expression functions. */
1586 expr_get_n_functions (void)
1588 return n_OP_function;
1591 /* Returns the name of operation OP. */
1593 expr_operation_get_name (const struct operation *op)
1598 /* Returns the human-readable prototype for operation OP. */
1600 expr_operation_get_prototype (const struct operation *op)
1602 return op->prototype;
1605 /* Returns the number of arguments for operation OP. */
1607 expr_operation_get_n_args (const struct operation *op)