24aaecf7f12c98fe0c632073d38c58d163b76137
[pspp] / src / language / expressions / parse.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2010, 2011, 2012, 2014 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include "private.h"
20
21 #include <ctype.h>
22 #include <float.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
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"
41
42 #include "gl/c-strcase.h"
43 #include "gl/minmax.h"
44 #include "gl/xalloc.h"
45 \f
46 /* Declarations. */
47
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;
55
56 /* Utility functions. */
57 static struct expression *expr_create (struct dataset *ds);
58 atom_type expr_node_returns (const struct expr_node *);
59
60 static const char *atom_type_name (atom_type);
61 static struct expression *finish_expression (struct expr_node *,
62                                              struct expression *);
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 *);
67 \f
68 /* Public functions. */
69
70 static struct expr_node *
71 parse_expr (struct lexer *lexer, struct expression *e)
72 {
73   struct expr_node *n = parse_or (lexer, e);
74   if (n && n->type == OP_VEC_ELEM_NUM_RAW)
75     n->type = OP_VEC_ELEM_NUM;
76   return n;
77 }
78
79 /* Parses an expression of the given TYPE.  If DS is nonnull then variables and
80    vectors within it may be referenced within the expression; otherwise, the
81    expression must not reference any variables or vectors.  Returns the new
82    expression if successful or a null pointer otherwise. */
83 struct expression *
84 expr_parse (struct lexer *lexer, struct dataset *ds, enum val_type type)
85 {
86   assert (val_type_is_valid (type));
87
88   struct expression *e = expr_create (ds);
89   struct expr_node *n = parse_expr (lexer, e);
90   if (!n || !type_check (e, n, type))
91     {
92       expr_free (e);
93       return NULL;
94     }
95
96   return finish_expression (expr_optimize (n, e), e);
97 }
98
99 /* Parses a boolean expression, otherwise similar to expr_parse(). */
100 struct expression *
101 expr_parse_bool (struct lexer *lexer, struct dataset *ds)
102 {
103   struct expression *e = expr_create (ds);
104   struct expr_node *n = parse_expr (lexer, e);
105   if (!n)
106     {
107       expr_free (e);
108       return NULL;
109     }
110
111   atom_type actual_type = expr_node_returns (n);
112   if (actual_type == OP_number)
113     n = expr_allocate_binary (e, OP_EXPR_TO_BOOLEAN, n,
114                               expr_allocate_expr_node (e, n));
115   else if (actual_type != OP_boolean)
116     {
117       msg_at (SE, expr_location (e, n),
118               _("Type mismatch: expression has %s type, "
119                  "but a boolean value is required here."),
120            atom_type_name (actual_type));
121       expr_free (e);
122       return NULL;
123     }
124
125   return finish_expression (expr_optimize (n, e), e);
126 }
127
128 /* Parses a numeric expression that is intended to be assigned to newly created
129    variable NEW_VAR_NAME.  (This allows for a better error message if the
130    expression is not numeric.)  Otherwise similar to expr_parse(). */
131 struct expression *
132 expr_parse_new_variable (struct lexer *lexer, struct dataset *ds,
133                          const char *new_var_name)
134 {
135   struct expression *e = expr_create (ds);
136   struct expr_node *n = parse_expr (lexer, e);
137   if (!n)
138     {
139       expr_free (e);
140       return NULL;
141     }
142
143   atom_type actual_type = expr_node_returns (n);
144   if (actual_type != OP_number && actual_type != OP_boolean)
145     {
146       msg (SE, _("This command tries to create a new variable %s by assigning a "
147                  "string value to it, but this is not supported.  Use "
148                  "the STRING command to create the new variable with the "
149                  "correct width before assigning to it, e.g. STRING %s(A20)."),
150            new_var_name, new_var_name);
151       expr_free (e);
152       return NULL;
153     }
154
155   return finish_expression (expr_optimize (n, e), e);
156 }
157
158 /* Free expression E. */
159 void
160 expr_free (struct expression *e)
161 {
162   if (e != NULL)
163     pool_destroy (e->expr_pool);
164 }
165
166 struct expression *
167 expr_parse_any (struct lexer *lexer, struct dataset *ds, bool optimize)
168 {
169   struct expr_node *n;
170   struct expression *e;
171
172   e = expr_create (ds);
173   n = parse_expr (lexer, e);
174   if (n == NULL)
175     {
176       expr_free (e);
177       return NULL;
178     }
179
180   if (optimize)
181     n = expr_optimize (n, e);
182   return finish_expression (n, e);
183 }
184 \f
185 /* Finishing up expression building. */
186
187 /* Height of an expression's stacks. */
188 struct stack_heights
189   {
190     int number_height;  /* Height of number stack. */
191     int string_height;  /* Height of string stack. */
192   };
193
194 /* Stack heights used by different kinds of arguments. */
195 static const struct stack_heights on_number_stack = {1, 0};
196 static const struct stack_heights on_string_stack = {0, 1};
197 static const struct stack_heights not_on_stack = {0, 0};
198
199 /* Returns the stack heights used by an atom of the given
200    TYPE. */
201 static const struct stack_heights *
202 atom_type_stack (atom_type type)
203 {
204   assert (is_atom (type));
205
206   switch (type)
207     {
208     case OP_number:
209     case OP_boolean:
210     case OP_num_vec_elem:
211       return &on_number_stack;
212
213     case OP_string:
214       return &on_string_stack;
215
216     case OP_format:
217     case OP_ni_format:
218     case OP_no_format:
219     case OP_num_var:
220     case OP_str_var:
221     case OP_integer:
222     case OP_pos_int:
223     case OP_vector:
224     case OP_expr_node:
225       return &not_on_stack;
226
227     default:
228       NOT_REACHED ();
229     }
230 }
231
232 /* Measures the stack height needed for node N, supposing that
233    the stack height is initially *HEIGHT and updating *HEIGHT to
234    the final stack height.  Updates *MAX, if necessary, to
235    reflect the maximum intermediate or final height. */
236 static void
237 measure_stack (const struct expr_node *n,
238                struct stack_heights *height, struct stack_heights *max)
239 {
240   const struct stack_heights *return_height;
241
242   if (is_composite (n->type))
243     {
244       struct stack_heights args;
245       int i;
246
247       args = *height;
248       for (i = 0; i < n->n_args; i++)
249         measure_stack (n->args[i], &args, max);
250
251       return_height = atom_type_stack (operations[n->type].returns);
252     }
253   else
254     return_height = atom_type_stack (n->type);
255
256   height->number_height += return_height->number_height;
257   height->string_height += return_height->string_height;
258
259   if (height->number_height > max->number_height)
260     max->number_height = height->number_height;
261   if (height->string_height > max->string_height)
262     max->string_height = height->string_height;
263 }
264
265 /* Allocates stacks within E sufficient for evaluating node N. */
266 static void
267 allocate_stacks (struct expr_node *n, struct expression *e)
268 {
269   struct stack_heights initial = {0, 0};
270   struct stack_heights max = {0, 0};
271
272   measure_stack (n, &initial, &max);
273   e->number_stack = pool_alloc (e->expr_pool,
274                                 sizeof *e->number_stack * max.number_height);
275   e->string_stack = pool_alloc (e->expr_pool,
276                                 sizeof *e->string_stack * max.string_height);
277 }
278
279 /* Finalizes expression E for evaluating node N. */
280 static struct expression *
281 finish_expression (struct expr_node *n, struct expression *e)
282 {
283   /* Allocate stacks. */
284   allocate_stacks (n, e);
285
286   /* Output postfix representation. */
287   expr_flatten (n, e);
288
289   /* The eval_pool might have been used for allocating strings
290      during optimization.  We need to keep those strings around
291      for all subsequent evaluations, so start a new eval_pool. */
292   e->eval_pool = pool_create_subpool (e->expr_pool);
293
294   return e;
295 }
296
297 /* Verifies that expression E, whose root node is *N, can be
298    converted to type EXPECTED_TYPE, inserting a conversion at *N
299    if necessary.  Returns true if successful, false on failure. */
300 static bool
301 type_check (const struct expression *e, const struct expr_node *n,
302             enum val_type expected_type)
303 {
304   atom_type actual_type = expr_node_returns (n);
305
306   switch (expected_type)
307     {
308     case VAL_NUMERIC:
309       if (actual_type != OP_number && actual_type != OP_boolean)
310         {
311           msg_at (SE, expr_location (e, n),
312                   _("Type mismatch: expression has type '%s', "
313                      "but a numeric value is required."),
314                atom_type_name (actual_type));
315           return false;
316         }
317       break;
318
319     case VAL_STRING:
320       if (actual_type != OP_string)
321         {
322           msg_at (SE, expr_location (e, n),
323                   _("Type mismatch: expression has type '%s', "
324                      "but a string value is required."),
325                atom_type_name (actual_type));
326           return false;
327         }
328       break;
329
330     default:
331       NOT_REACHED ();
332     }
333
334   return true;
335 }
336 \f
337 /* Recursive-descent expression parser. */
338
339 static void
340 free_msg_location (void *loc_)
341 {
342   struct msg_location *loc = loc_;
343   msg_location_destroy (loc);
344 }
345
346 static void
347 expr_location__ (struct expression *e,
348                  const struct expr_node *node,
349                  const struct msg_location **minp,
350                  const struct msg_location **maxp)
351 {
352   struct msg_location *loc = node->location;
353   if (loc)
354     {
355       const struct msg_location *min = *minp;
356       if (loc->start.line
357           && (!min
358               || loc->start.line < min->start.line
359               || (loc->start.line == min->start.line
360                   && loc->start.column < min->start.column)))
361         *minp = loc;
362
363       const struct msg_location *max = *maxp;
364       if (loc->end.line
365           && (!max
366               || loc->end.line > max->end.line
367               || (loc->end.line == max->end.line
368                   && loc->end.column > max->end.column)))
369         *maxp = loc;
370
371       return;
372     }
373
374   if (is_composite (node->type))
375     for (size_t i = 0; i < node->n_args; i++)
376       expr_location__ (e, node->args[i], minp, maxp);
377 }
378
379 /* Returns the source code location corresponding to expression NODE, computing
380    it lazily if needed. */
381 const struct msg_location *
382 expr_location (const struct expression *e_, const struct expr_node *node_)
383 {
384   struct expr_node *node = CONST_CAST (struct expr_node *, node_);
385   if (!node)
386     return NULL;
387
388   if (!node->location)
389     {
390       struct expression *e = CONST_CAST (struct expression *, e_);
391       const struct msg_location *min = NULL;
392       const struct msg_location *max = NULL;
393       expr_location__ (e, node, &min, &max);
394       if (min && max)
395         {
396           node->location = msg_location_dup (min);
397           node->location->end = max->end;
398           pool_register (e->expr_pool, free_msg_location, node->location);
399         }
400     }
401   return node->location;
402 }
403
404 /* Sets e->location to the tokens in S's lexer from offset START_OFS to the
405    token before the current one.  Has no effect if E already has a location or
406    if E is null. */
407 static void
408 expr_add_location (struct lexer *lexer, struct expression *e,
409                    int start_ofs, struct expr_node *node)
410 {
411   if (node && !node->location)
412     {
413       node->location = lex_ofs_location (lexer, start_ofs, lex_ofs (lexer) - 1);
414       pool_register (e->expr_pool, free_msg_location, node->location);
415     }
416 }
417
418 static bool
419 type_coercion__ (struct expression *e, struct expr_node *node, size_t arg_idx,
420                  bool do_coercion)
421 {
422   assert (!!do_coercion == (e != NULL));
423
424   if (!node)
425     return false;
426
427   struct expr_node **argp = &node->args[arg_idx];
428   struct expr_node *arg = *argp;
429   if (!arg)
430     return false;
431
432   const struct operation *op = &operations[node->type];
433   atom_type required_type = op->args[MIN (arg_idx, op->n_args - 1)];
434   atom_type actual_type = expr_node_returns (arg);
435   if (actual_type == required_type)
436     {
437       /* Type match. */
438       return true;
439     }
440
441   switch (required_type)
442     {
443     case OP_number:
444       if (actual_type == OP_boolean)
445         {
446           /* To enforce strict typing rules, insert Boolean to
447              numeric "conversion".  This conversion is a no-op,
448              so it will be removed later. */
449           if (do_coercion)
450             *argp = expr_allocate_unary (e, OP_BOOLEAN_TO_NUM, arg);
451           return true;
452         }
453       else if (actual_type == OP_num_vec_elem)
454         {
455           if (do_coercion)
456             arg->type = OP_VEC_ELEM_NUM;
457           return true;
458         }
459       break;
460
461     case OP_string:
462       /* No coercion to string. */
463       break;
464
465     case OP_boolean:
466       if (actual_type == OP_number)
467         {
468           /* Convert numeric to boolean. */
469           if (do_coercion)
470             *argp = expr_allocate_binary (e, OP_OPERAND_TO_BOOLEAN, arg,
471                                           expr_allocate_expr_node (e, node));
472           return true;
473         }
474       break;
475
476     case OP_integer:
477       if (actual_type == OP_number)
478         {
479           /* Convert number to integer. */
480           if (do_coercion)
481             *argp = expr_allocate_unary (e, OP_NUM_TO_INTEGER, arg);
482           return true;
483         }
484       break;
485
486     case OP_format:
487       /* We never coerce to OP_format, only to OP_ni_format or OP_no_format. */
488       NOT_REACHED ();
489
490     case OP_ni_format:
491       msg_disable ();
492       if (arg->type == OP_format
493           && fmt_check_input (&arg->format)
494           && fmt_check_type_compat (&arg->format, VAL_NUMERIC))
495         {
496           msg_enable ();
497           if (do_coercion)
498             arg->type = OP_ni_format;
499           return true;
500         }
501       msg_enable ();
502       break;
503
504     case OP_no_format:
505       msg_disable ();
506       if (arg->type == OP_format
507           && fmt_check_output (&arg->format)
508           && fmt_check_type_compat (&arg->format, VAL_NUMERIC))
509         {
510           msg_enable ();
511           if (do_coercion)
512             arg->type = OP_no_format;
513           return true;
514         }
515       msg_enable ();
516       break;
517
518     case OP_num_var:
519       if (arg->type == OP_NUM_VAR)
520         {
521           if (do_coercion)
522             *argp = arg->args[0];
523           return true;
524         }
525       break;
526
527     case OP_str_var:
528       if (arg->type == OP_STR_VAR)
529         {
530           if (do_coercion)
531             *argp = arg->args[0];
532           return true;
533         }
534       break;
535
536     case OP_var:
537       if (arg->type == OP_NUM_VAR || arg->type == OP_STR_VAR)
538         {
539           if (do_coercion)
540             *argp = arg->args[0];
541           return true;
542         }
543       break;
544
545     case OP_pos_int:
546       if (arg->type == OP_number
547           && floor (arg->number) == arg->number
548           && arg->number > 0 && arg->number < INT_MAX)
549         {
550           if (do_coercion)
551             *argp = expr_allocate_pos_int (e, arg->number);
552           return true;
553         }
554       break;
555
556     default:
557       NOT_REACHED ();
558     }
559   return false;
560 }
561
562 static bool
563 type_coercion (struct expression *e, struct expr_node *node, size_t arg_idx)
564 {
565   return type_coercion__ (e, node, arg_idx, true);
566 }
567
568 static bool
569 is_coercible (const struct expr_node *node_, size_t arg_idx)
570 {
571   struct expr_node *node = CONST_CAST (struct expr_node *, node_);
572   return type_coercion__ (NULL, node, arg_idx, false);
573 }
574
575 /* How to parse an operator.
576
577    Some operators support both numeric and string operators.  For those,
578    'num_op' and 'str_op' are both nonzero.  Otherwise, only one 'num_op' is
579    nonzero.  (PSPP doesn't have any string-only operators.) */
580 struct operator
581   {
582     enum token_type token;      /* Operator token. */
583     operation_type num_op;      /* Operation for numeric operands (or 0). */
584     operation_type str_op;      /* Operation for string operands (or 0). */
585   };
586
587 static operation_type
588 match_operator (struct lexer *lexer, const struct operator ops[], size_t n_ops,
589                 const struct expr_node *lhs)
590 {
591   bool lhs_is_numeric = operations[lhs->type].returns != OP_string;
592   for (const struct operator *op = ops; op < ops + n_ops; op++)
593     if (lex_token (lexer) == op->token)
594       {
595         if (op->token != T_NEG_NUM)
596           lex_get (lexer);
597
598         return op->str_op && !lhs_is_numeric ? op->str_op : op->num_op;
599       }
600   return 0;
601 }
602
603 static const char *
604 operator_name (enum token_type token)
605 {
606   return token == T_NEG_NUM ? "-" : token_type_to_string (token);
607 }
608
609 static struct expr_node *
610 parse_binary_operators__ (struct lexer *lexer, struct expression *e,
611                           const struct operator ops[], size_t n_ops,
612                           parse_recursively_func *parse_next_level,
613                           const char *chain_warning, struct expr_node *lhs)
614 {
615   for (int op_count = 0; ; op_count++)
616     {
617       enum token_type token = lex_token (lexer);
618       operation_type optype = match_operator (lexer, ops, n_ops, lhs);
619       if (!optype)
620         {
621           if (op_count > 1 && chain_warning)
622             msg_at (SW, expr_location (e, lhs), "%s", chain_warning);
623
624           return lhs;
625         }
626
627       struct expr_node *rhs = parse_next_level (lexer, e);
628       if (!rhs)
629         return NULL;
630
631       struct expr_node *node = expr_allocate_binary (e, optype, lhs, rhs);
632       if (!is_coercible (node, 0) || !is_coercible (node, 1))
633         {
634           bool both = false;
635           for (size_t i = 0; i < n_ops; i++)
636             if (ops[i].token == token)
637               both = ops[i].num_op && ops[i].str_op;
638
639           const char *name = operator_name (token);
640           if (both)
641             msg_at (SE, expr_location (e, node),
642                     _("Both operands of %s must have the same type."), name);
643           else if (operations[node->type].args[0] != OP_string)
644             msg_at (SE, expr_location (e, node),
645                     _("Both operands of %s must be numeric."), name);
646           else
647             msg_at (SE, expr_location (e, node),
648                     _("Both operands of %s must be strings."), name);
649
650           msg_at (SN, expr_location (e, node->args[0]),
651                   _("This operand has type '%s'."),
652                   atom_type_name (expr_node_returns (node->args[0])));
653           msg_at (SN, expr_location (e, node->args[1]),
654                   _("This operand has type '%s'."),
655                   atom_type_name (expr_node_returns (node->args[1])));
656
657           return NULL;
658         }
659
660       if (!type_coercion (e, node, 0) || !type_coercion (e, node, 1))
661         NOT_REACHED ();
662
663       lhs = node;
664     }
665 }
666
667 static struct expr_node *
668 parse_binary_operators (struct lexer *lexer, struct expression *e,
669                         const struct operator ops[], size_t n_ops,
670                         parse_recursively_func *parse_next_level,
671                         const char *chain_warning)
672 {
673   struct expr_node *lhs = parse_next_level (lexer, e);
674   if (!lhs)
675     return NULL;
676
677   return parse_binary_operators__ (lexer, e, ops, n_ops, parse_next_level,
678                                    chain_warning, lhs);
679 }
680
681 static struct expr_node *
682 parse_inverting_unary_operator (struct lexer *lexer, struct expression *e,
683                                 const struct operator *op,
684                                 parse_recursively_func *parse_next_level)
685 {
686   int start_ofs = lex_ofs (lexer);
687   unsigned int op_count = 0;
688   while (lex_match (lexer, op->token))
689     op_count++;
690
691   struct expr_node *inner = parse_next_level (lexer, e);
692   if (!inner || !op_count)
693     return inner;
694
695   struct expr_node *outer = expr_allocate_unary (e, op->num_op, inner);
696   expr_add_location (lexer, e, start_ofs, outer);
697
698   if (!type_coercion (e, outer, 0))
699     {
700       assert (operations[outer->type].args[0] != OP_string);
701
702       const char *name = operator_name (op->token);
703       msg_at (SE, expr_location (e, outer),
704               _("The unary %s operator requires a numeric operand."), name);
705
706       msg_at (SN, expr_location (e, outer->args[0]),
707               _("The operand of %s has type '%s'."),
708               name, atom_type_name (expr_node_returns (outer->args[0])));
709
710       return NULL;
711     }
712
713   return op_count % 2 ? outer : outer->args[0];
714 }
715
716 /* Parses the OR level. */
717 static struct expr_node *
718 parse_or (struct lexer *lexer, struct expression *e)
719 {
720   static const struct operator op = { .token = T_OR, .num_op = OP_OR };
721   return parse_binary_operators (lexer, e, &op, 1, parse_and, NULL);
722 }
723
724 /* Parses the AND level. */
725 static struct expr_node *
726 parse_and (struct lexer *lexer, struct expression *e)
727 {
728   static const struct operator op = { .token = T_AND, .num_op = OP_AND };
729
730   return parse_binary_operators (lexer, e, &op, 1, parse_not, NULL);
731 }
732
733 /* Parses the NOT level. */
734 static struct expr_node *
735 parse_not (struct lexer *lexer, struct expression *e)
736 {
737   static const struct operator op = { .token = T_NOT, .num_op = OP_NOT };
738   return parse_inverting_unary_operator (lexer, e, &op, parse_rel);
739 }
740
741 /* Parse relational operators. */
742 static struct expr_node *
743 parse_rel (struct lexer *lexer, struct expression *e)
744 {
745   const char *chain_warning =
746     _("Chaining relational operators (e.g. `a < b < c') will "
747       "not produce the mathematically expected result.  "
748       "Use the AND logical operator to fix the problem "
749       "(e.g. `a < b AND b < c').  "
750       "To disable this warning, insert parentheses.");
751
752   static const struct operator ops[] =
753     {
754       { .token = T_EQUALS, .num_op = OP_EQ, .str_op = OP_EQ_STRING },
755       { .token = T_EQ, .num_op = OP_EQ, .str_op = OP_EQ_STRING },
756       { .token = T_GE, .num_op = OP_GE, .str_op = OP_GE_STRING },
757       { .token = T_GT, .num_op = OP_GT, .str_op = OP_GT_STRING },
758       { .token = T_LE, .num_op = OP_LE, .str_op = OP_LE_STRING },
759       { .token = T_LT, .num_op = OP_LT, .str_op = OP_LT_STRING },
760       { .token = T_NE, .num_op = OP_NE, .str_op = OP_NE_STRING },
761     };
762
763   return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
764                                  parse_add, chain_warning);
765 }
766
767 /* Parses the addition and subtraction level. */
768 static struct expr_node *
769 parse_add (struct lexer *lexer, struct expression *e)
770 {
771   static const struct operator ops[] =
772     {
773       { .token = T_PLUS, .num_op = OP_ADD },
774       { .token = T_DASH, .num_op = OP_SUB },
775       { .token = T_NEG_NUM, .num_op = OP_ADD },
776     };
777
778   return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
779                                  parse_mul, NULL);
780 }
781
782 /* Parses the multiplication and division level. */
783 static struct expr_node *
784 parse_mul (struct lexer *lexer, struct expression *e)
785 {
786   static const struct operator ops[] =
787     {
788       { .token = T_ASTERISK, .num_op = OP_MUL },
789       { .token = T_SLASH, .num_op = OP_DIV },
790     };
791
792   return parse_binary_operators (lexer, e, ops, sizeof ops / sizeof *ops,
793                                  parse_neg, NULL);
794 }
795
796 /* Parses the unary minus level. */
797 static struct expr_node *
798 parse_neg (struct lexer *lexer, struct expression *e)
799 {
800   static const struct operator op = { .token = T_DASH, .num_op = OP_NEG };
801   return parse_inverting_unary_operator (lexer, e, &op, parse_exp);
802 }
803
804 static struct expr_node *
805 parse_exp (struct lexer *lexer, struct expression *e)
806 {
807   static const struct operator op = { .token = T_EXP, .num_op = OP_POW };
808
809   const char *chain_warning =
810     _("The exponentiation operator (`**') is left-associative: "
811       "`a**b**c' equals `(a**b)**c', not `a**(b**c)'.  "
812       "To disable this warning, insert parentheses.");
813
814   if (lex_token (lexer) != T_NEG_NUM || lex_next_token (lexer, 1) != T_EXP)
815     return parse_binary_operators (lexer, e, &op, 1,
816                                    parse_primary, chain_warning);
817
818   /* Special case for situations like "-5**6", which must be parsed as
819      -(5**6). */
820
821   int start_ofs = lex_ofs (lexer);
822   struct expr_node *lhs = expr_allocate_number (e, -lex_tokval (lexer));
823   lex_get (lexer);
824   expr_add_location (lexer, e, start_ofs, lhs);
825
826   struct expr_node *node = parse_binary_operators__ (
827     lexer, e, &op, 1, parse_primary, chain_warning, lhs);
828   if (!node)
829     return NULL;
830
831   node = expr_allocate_unary (e, OP_NEG, node);
832   expr_add_location (lexer, e, start_ofs, node);
833   return node;
834 }
835
836 static double
837 ymd_to_offset (int y, int m, int d)
838 {
839   char *error;
840   double retval = calendar_gregorian_to_offset (
841     y, m, d, settings_get_fmt_settings (), &error);
842   if (error)
843     {
844       msg (SE, "%s", error);
845       free (error);
846     }
847   return retval;
848 }
849
850 static struct expr_node *
851 expr_date (struct expression *e, int year_digits)
852 {
853   static const char *months[12] =
854     {
855       "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
856       "JUL", "AUG", "SEP", "OCT", "NOV", "DEC",
857     };
858
859   time_t last_proc_time = time_of_last_procedure (e->ds);
860   struct tm *time = localtime (&last_proc_time);
861
862   char *tmp = (year_digits == 2
863                ? xasprintf ("%02d-%s-%02d", time->tm_mday, months[time->tm_mon],
864                             time->tm_year % 100)
865                : xasprintf ("%02d-%s-%04d", time->tm_mday, months[time->tm_mon],
866                             time->tm_year + 1900));
867
868   struct substring s;
869   ss_alloc_substring_pool (&s, ss_cstr (tmp), e->expr_pool);
870
871   free (tmp);
872
873   return expr_allocate_string (e, s);
874 }
875
876 /* Parses system variables. */
877 static struct expr_node *
878 parse_sysvar (struct lexer *lexer, struct expression *e)
879 {
880   if (lex_match_id (lexer, "$CASENUM"))
881     return expr_allocate_nullary (e, OP_CASENUM);
882   else if (lex_match_id (lexer, "$DATE"))
883     return expr_date (e, 2);
884   else if (lex_match_id (lexer, "$DATE11"))
885     return expr_date (e, 4);
886   else if (lex_match_id (lexer, "$TRUE"))
887     return expr_allocate_boolean (e, 1.0);
888   else if (lex_match_id (lexer, "$FALSE"))
889     return expr_allocate_boolean (e, 0.0);
890   else if (lex_match_id (lexer, "$SYSMIS"))
891     return expr_allocate_number (e, SYSMIS);
892   else if (lex_match_id (lexer, "$JDATE"))
893     {
894       time_t time = time_of_last_procedure (e->ds);
895       struct tm *tm = localtime (&time);
896       return expr_allocate_number (e, ymd_to_offset (tm->tm_year + 1900,
897                                                      tm->tm_mon + 1,
898                                                      tm->tm_mday));
899     }
900   else if (lex_match_id (lexer, "$TIME"))
901     {
902       time_t time = time_of_last_procedure (e->ds);
903       struct tm *tm = localtime (&time);
904       return expr_allocate_number (e, ymd_to_offset (tm->tm_year + 1900,
905                                                      tm->tm_mon + 1,
906                                                      tm->tm_mday)
907                                    + tm->tm_hour * 60 * 60.
908                                    + tm->tm_min * 60.
909                                    + tm->tm_sec);
910     }
911   else if (lex_match_id (lexer, "$LENGTH"))
912     return expr_allocate_number (e, settings_get_viewlength ());
913   else if (lex_match_id (lexer, "$WIDTH"))
914     return expr_allocate_number (e, settings_get_viewwidth ());
915   else
916     {
917       msg (SE, _("Unknown system variable %s."), lex_tokcstr (lexer));
918       return NULL;
919     }
920 }
921
922 /* Parses numbers, varnames, etc. */
923 static struct expr_node *
924 parse_primary__ (struct lexer *lexer, struct expression *e)
925 {
926   switch (lex_token (lexer))
927     {
928     case T_ID:
929       if (lex_next_token (lexer, 1) == T_LPAREN)
930         {
931           /* An identifier followed by a left parenthesis may be
932              a vector element reference.  If not, it's a function
933              call. */
934           if (e->ds != NULL && dict_lookup_vector (dataset_dict (e->ds), lex_tokcstr (lexer)) != NULL)
935             return parse_vector_element (lexer, e);
936           else
937             return parse_function (lexer, e);
938         }
939       else if (lex_tokcstr (lexer)[0] == '$')
940         {
941           /* $ at the beginning indicates a system variable. */
942           return parse_sysvar (lexer, e);
943         }
944       else if (e->ds != NULL && dict_lookup_var (dataset_dict (e->ds), lex_tokcstr (lexer)))
945         {
946           /* It looks like a user variable.
947              (It could be a format specifier, but we'll assume
948              it's a variable unless proven otherwise. */
949           return allocate_unary_variable (e, parse_variable (lexer, dataset_dict (e->ds)));
950         }
951       else
952         {
953           /* Try to parse it as a format specifier. */
954           struct fmt_spec fmt;
955           bool ok;
956
957           msg_disable ();
958           ok = parse_format_specifier (lexer, &fmt);
959           msg_enable ();
960
961           if (ok)
962             return expr_allocate_format (e, &fmt);
963
964           /* All attempts failed. */
965           msg (SE, _("Unknown identifier %s."), lex_tokcstr (lexer));
966           return NULL;
967         }
968       break;
969
970     case T_POS_NUM:
971     case T_NEG_NUM:
972       {
973         struct expr_node *node = expr_allocate_number (e, lex_tokval (lexer));
974         lex_get (lexer);
975         return node;
976       }
977
978     case T_STRING:
979       {
980         const char *dict_encoding;
981         struct expr_node *node;
982         char *s;
983
984         dict_encoding = (e->ds != NULL
985                          ? dict_get_encoding (dataset_dict (e->ds))
986                          : "UTF-8");
987         s = recode_string_pool (dict_encoding, "UTF-8", lex_tokcstr (lexer),
988                            ss_length (lex_tokss (lexer)), e->expr_pool);
989         node = expr_allocate_string (e, ss_cstr (s));
990
991         lex_get (lexer);
992         return node;
993       }
994
995     case T_LPAREN:
996       {
997         lex_get (lexer);
998         struct expr_node *node = parse_or (lexer, e);
999         return !node || !lex_force_match (lexer, T_RPAREN) ? NULL : node;
1000       }
1001
1002     default:
1003       lex_error (lexer, NULL);
1004       return NULL;
1005     }
1006 }
1007
1008 static struct expr_node *
1009 parse_primary (struct lexer *lexer, struct expression *e)
1010 {
1011   int start_ofs = lex_ofs (lexer);
1012   struct expr_node *node = parse_primary__ (lexer, e);
1013   expr_add_location (lexer, e, start_ofs, node);
1014   return node;
1015 }
1016
1017 static struct expr_node *
1018 parse_vector_element (struct lexer *lexer, struct expression *e)
1019 {
1020   int vector_start_ofs = lex_ofs (lexer);
1021
1022   /* Find vector, skip token.
1023      The caller must already have verified that the current token
1024      is the name of a vector. */
1025   const struct vector *vector = dict_lookup_vector (dataset_dict (e->ds),
1026                                                     lex_tokcstr (lexer));
1027   assert (vector != NULL);
1028   lex_get (lexer);
1029
1030   /* Skip left parenthesis token.
1031      The caller must have verified that the lookahead is a left
1032      parenthesis. */
1033   assert (lex_token (lexer) == T_LPAREN);
1034   lex_get (lexer);
1035
1036   int element_start_ofs = lex_ofs (lexer);
1037   struct expr_node *element = parse_or (lexer, e);
1038   if (!element)
1039     return NULL;
1040   expr_add_location (lexer, e, element_start_ofs, element);
1041
1042   if (!lex_match (lexer, T_RPAREN))
1043     return NULL;
1044
1045   operation_type type = (vector_get_type (vector) == VAL_NUMERIC
1046                          ? OP_VEC_ELEM_NUM_RAW : OP_VEC_ELEM_STR);
1047   struct expr_node *node = expr_allocate_binary (
1048     e, type, element, expr_allocate_vector (e, vector));
1049   expr_add_location (lexer, e, vector_start_ofs, node);
1050
1051   if (!type_coercion (e, node, 0))
1052     {
1053       msg_at (SE, expr_location (e, node),
1054               _("A vector index must be numeric."));
1055
1056       msg_at (SN, expr_location (e, node->args[0]),
1057               _("This vector index has type '%s'."),
1058               atom_type_name (expr_node_returns (node->args[0])));
1059
1060       return NULL;
1061     }
1062
1063   return node;
1064 }
1065 \f
1066 /* Individual function parsing. */
1067
1068 const struct operation operations[OP_first + n_OP] = {
1069 #include "parse.inc"
1070 };
1071
1072 static bool
1073 word_matches (const char **test, const char **name)
1074 {
1075   size_t test_len = strcspn (*test, ".");
1076   size_t name_len = strcspn (*name, ".");
1077   if (test_len == name_len)
1078     {
1079       if (buf_compare_case (*test, *name, test_len))
1080         return false;
1081     }
1082   else if (test_len < 3 || test_len > name_len)
1083     return false;
1084   else
1085     {
1086       if (buf_compare_case (*test, *name, test_len))
1087         return false;
1088     }
1089
1090   *test += test_len;
1091   *name += name_len;
1092   if (**test != **name)
1093     return false;
1094
1095   if (**test == '.')
1096     {
1097       (*test)++;
1098       (*name)++;
1099     }
1100   return true;
1101 }
1102
1103 /* Returns 0 if TOKEN and FUNC do not match,
1104    1 if TOKEN is an acceptable abbreviation for FUNC,
1105    2 if TOKEN equals FUNC. */
1106 static int
1107 compare_function_names (const char *token_, const char *func_)
1108 {
1109   const char *token = token_;
1110   const char *func = func_;
1111   while (*token || *func)
1112     if (!word_matches (&token, &func))
1113       return 0;
1114   return !c_strcasecmp (token_, func_) ? 2 : 1;
1115 }
1116
1117 static bool
1118 lookup_function (const char *token,
1119                  const struct operation **first,
1120                  const struct operation **last)
1121 {
1122   *first = *last = NULL;
1123   const struct operation *best = NULL;
1124
1125   for (const struct operation *f = operations + OP_function_first;
1126        f <= operations + OP_function_last; f++)
1127     {
1128       int score = compare_function_names (token, f->name);
1129       if (score == 2)
1130         {
1131           best = f;
1132           break;
1133         }
1134       else if (score == 1 && !(f->flags & OPF_NO_ABBREV) && !best)
1135         best = f;
1136     }
1137
1138   if (!best)
1139     return false;
1140
1141   *first = best;
1142
1143   const struct operation *f = best;
1144   while (f <= operations + OP_function_last
1145          && !c_strcasecmp (f->name, best->name))
1146     f++;
1147   *last = f;
1148
1149   return true;
1150 }
1151
1152 static int
1153 extract_min_valid (const char *s)
1154 {
1155   char *p = strrchr (s, '.');
1156   if (p == NULL
1157       || p[1] < '0' || p[1] > '9'
1158       || strspn (p + 1, "0123456789") != strlen (p + 1))
1159     return -1;
1160   *p = '\0';
1161   return atoi (p + 1);
1162 }
1163
1164 static bool
1165 match_function__ (struct expr_node *node, const struct operation *f)
1166 {
1167   if (node->n_args < f->n_args
1168       || (node->n_args > f->n_args && (f->flags & OPF_ARRAY_OPERAND) == 0)
1169       || node->n_args - (f->n_args - 1) < f->array_min_elems)
1170     return false;
1171
1172   node->type = f - operations;
1173   for (size_t i = 0; i < node->n_args; i++)
1174     if (!is_coercible (node, i))
1175       return false;
1176
1177   return true;
1178 }
1179
1180 static const struct operation *
1181 match_function (struct expr_node *node,
1182                 const struct operation *first, const struct operation *last)
1183 {
1184   for (const struct operation *f = first; f < last; f++)
1185     if (match_function__ (node, f))
1186       return f;
1187   return NULL;
1188 }
1189
1190 static bool
1191 validate_function_args (const struct expression *e, const struct expr_node *n,
1192                         const struct operation *f, int n_args, int min_valid)
1193 {
1194   /* Count the function arguments that go into the trailing array (if any).  We
1195      know that there must be at least the minimum number because
1196      match_function() already checked. */
1197   int array_n_args = n_args - (f->n_args - 1);
1198   assert (array_n_args >= f->array_min_elems);
1199
1200   if ((f->flags & OPF_ARRAY_OPERAND)
1201       && array_n_args % f->array_granularity != 0)
1202     {
1203       /* RANGE is the only case we have so far.  It has paired arguments with
1204          one initial argument, and that's the only special case we deal with
1205          here. */
1206       assert (f->array_granularity == 2);
1207       assert (n_args % 2 == 0);
1208       msg_at (SE, expr_location (e, n),
1209               _("%s must have an odd number of arguments."), f->prototype);
1210       return false;
1211     }
1212
1213   if (min_valid != -1)
1214     {
1215       if (f->array_min_elems == 0)
1216         {
1217           assert ((f->flags & OPF_MIN_VALID) == 0);
1218           msg_at (SE, expr_location (e, n),
1219                   _("%s function cannot accept suffix .%d to specify the "
1220                     "minimum number of valid arguments."),
1221                   f->prototype, min_valid);
1222           return false;
1223         }
1224       else
1225         {
1226           assert (f->flags & OPF_MIN_VALID);
1227           if (min_valid > array_n_args)
1228             {
1229               msg_at (SE, expr_location (e, n),
1230                       _("For %s with %d arguments, at most %d (not %d) may be "
1231                         "required to be valid."),
1232                       f->prototype, n_args, array_n_args, min_valid);
1233               return false;
1234             }
1235         }
1236     }
1237
1238   return true;
1239 }
1240
1241 static void
1242 add_arg (struct expr_node ***args, size_t *n_args, size_t *allocated_args,
1243          struct expr_node *arg,
1244          struct expression *e, struct lexer *lexer, int arg_start_ofs)
1245 {
1246   if (*n_args >= *allocated_args)
1247     *args = x2nrealloc (*args, allocated_args, sizeof **args);
1248
1249   expr_add_location (lexer, e, arg_start_ofs, arg);
1250   (*args)[(*n_args)++] = arg;
1251 }
1252
1253 static void
1254 put_invocation (struct string *s,
1255                 const char *func_name, struct expr_node *node)
1256 {
1257   size_t i;
1258
1259   ds_put_format (s, "%s(", func_name);
1260   for (i = 0; i < node->n_args; i++)
1261     {
1262       if (i > 0)
1263         ds_put_cstr (s, ", ");
1264       ds_put_cstr (s, operations[expr_node_returns (node->args[i])].prototype);
1265     }
1266   ds_put_byte (s, ')');
1267 }
1268
1269 static void
1270 no_match (struct expression *e, const char *func_name, struct expr_node *node,
1271           const struct operation *first, const struct operation *last)
1272 {
1273   struct string s;
1274   const struct operation *f;
1275
1276   ds_init_empty (&s);
1277
1278   if (last - first == 1)
1279     {
1280       ds_put_format (&s, _("Type mismatch invoking %s as "), first->prototype);
1281       put_invocation (&s, func_name, node);
1282     }
1283   else
1284     {
1285       ds_put_cstr (&s, _("Function invocation "));
1286       put_invocation (&s, func_name, node);
1287       ds_put_cstr (&s, _(" does not match any known function.  Candidates are:"));
1288
1289       for (f = first; f < last; f++)
1290         ds_put_format (&s, "\n%s", f->prototype);
1291     }
1292   ds_put_byte (&s, '.');
1293
1294   msg_at (SE, expr_location (e, node), "%s", ds_cstr (&s));
1295
1296   ds_destroy (&s);
1297 }
1298
1299 static struct expr_node *
1300 parse_function (struct lexer *lexer, struct expression *e)
1301 {
1302   struct string func_name;
1303   ds_init_substring (&func_name, lex_tokss (lexer));
1304
1305   int min_valid = extract_min_valid (lex_tokcstr (lexer));
1306
1307   const struct operation *first, *last;
1308   if (!lookup_function (lex_tokcstr (lexer), &first, &last))
1309     {
1310       msg (SE, _("No function or vector named %s."), lex_tokcstr (lexer));
1311       ds_destroy (&func_name);
1312       return NULL;
1313     }
1314
1315   int func_start_ofs = lex_ofs (lexer);
1316   lex_get (lexer);
1317   if (!lex_force_match (lexer, T_LPAREN))
1318     {
1319       ds_destroy (&func_name);
1320       return NULL;
1321     }
1322
1323   struct expr_node **args = NULL;
1324   size_t n_args = 0;
1325   size_t allocated_args = 0;
1326   if (lex_token (lexer) != T_RPAREN)
1327     for (;;)
1328       {
1329         int arg_start_ofs = lex_ofs (lexer);
1330         if (lex_token (lexer) == T_ID
1331             && lex_next_token (lexer, 1) == T_TO)
1332           {
1333             const struct variable **vars;
1334             size_t n_vars;
1335
1336             if (!parse_variables_const (lexer, dataset_dict (e->ds),
1337                                         &vars, &n_vars, PV_SINGLE))
1338               goto fail;
1339             for (size_t i = 0; i < n_vars; i++)
1340               add_arg (&args, &n_args, &allocated_args,
1341                        allocate_unary_variable (e, vars[i]),
1342                        e, lexer, arg_start_ofs);
1343             free (vars);
1344           }
1345         else
1346           {
1347             struct expr_node *arg = parse_or (lexer, e);
1348             if (arg == NULL)
1349               goto fail;
1350
1351             add_arg (&args, &n_args, &allocated_args, arg,
1352                      e, lexer, arg_start_ofs);
1353           }
1354         if (lex_match (lexer, T_RPAREN))
1355           break;
1356         else if (!lex_match (lexer, T_COMMA))
1357           {
1358             lex_error_expecting (lexer, "`,'", "`)'");
1359             goto fail;
1360           }
1361       }
1362
1363   struct expr_node *n = expr_allocate_composite (e, first - operations,
1364                                                  args, n_args);
1365   expr_add_location (lexer, e, func_start_ofs, n);
1366   const struct operation *f = match_function (n, first, last);
1367   if (!f)
1368     {
1369       no_match (e, ds_cstr (&func_name), n, first, last);
1370       goto fail;
1371     }
1372   n->type = f - operations;
1373   n->min_valid = min_valid != -1 ? min_valid : f->array_min_elems;
1374
1375   for (size_t i = 0; i < n_args; i++)
1376     if (!type_coercion (e, n, i))
1377       {
1378         /* Unreachable because match_function already checked that the
1379            arguments were coercible. */
1380         NOT_REACHED ();
1381       }
1382   if (!validate_function_args (e, n, f, n_args, min_valid))
1383     goto fail;
1384
1385   if ((f->flags & OPF_EXTENSION) && settings_get_syntax () == COMPATIBLE)
1386     msg_at (SW, expr_location (e, n),
1387             _("%s is a PSPP extension."), f->prototype);
1388   if (f->flags & OPF_UNIMPLEMENTED)
1389     {
1390       msg_at (SE, expr_location (e, n),
1391               _("%s is not available in this version of PSPP."), f->prototype);
1392       goto fail;
1393     }
1394   if ((f->flags & OPF_PERM_ONLY) &&
1395       proc_in_temporary_transformations (e->ds))
1396     {
1397       msg_at (SE, expr_location (e, n),
1398               _("%s may not appear after %s."), f->prototype, "TEMPORARY");
1399       goto fail;
1400     }
1401
1402   if (n->type == OP_LAG_Vn || n->type == OP_LAG_Vs)
1403     dataset_need_lag (e->ds, 1);
1404   else if (n->type == OP_LAG_Vnn || n->type == OP_LAG_Vsn)
1405     {
1406       assert (n->n_args == 2);
1407       assert (n->args[1]->type == OP_pos_int);
1408       dataset_need_lag (e->ds, n->args[1]->integer);
1409     }
1410
1411   free (args);
1412   ds_destroy (&func_name);
1413   return n;
1414
1415 fail:
1416   free (args);
1417   ds_destroy (&func_name);
1418   return NULL;
1419 }
1420 \f
1421 /* Utility functions. */
1422
1423 static struct expression *
1424 expr_create (struct dataset *ds)
1425 {
1426   struct pool *pool = pool_create ();
1427   struct expression *e = pool_alloc (pool, sizeof *e);
1428   *e = (struct expression) {
1429     .expr_pool = pool,
1430     .ds = ds,
1431     .eval_pool = pool_create_subpool (pool),
1432   };
1433   return e;
1434 }
1435
1436 atom_type
1437 expr_node_returns (const struct expr_node *n)
1438 {
1439   assert (n != NULL);
1440   assert (is_operation (n->type));
1441   if (is_atom (n->type))
1442     return n->type;
1443   else if (is_composite (n->type))
1444     return operations[n->type].returns;
1445   else
1446     NOT_REACHED ();
1447 }
1448
1449 static const char *
1450 atom_type_name (atom_type type)
1451 {
1452   assert (is_atom (type));
1453
1454   /* The Boolean type is purely an internal concept that the documentation
1455      doesn't mention, so it might confuse users if we talked about them in
1456      diagnostics. */
1457   return type == OP_boolean ? "number" : operations[type].name;
1458 }
1459
1460 struct expr_node *
1461 expr_allocate_nullary (struct expression *e, operation_type op)
1462 {
1463   return expr_allocate_composite (e, op, NULL, 0);
1464 }
1465
1466 struct expr_node *
1467 expr_allocate_unary (struct expression *e, operation_type op,
1468                      struct expr_node *arg0)
1469 {
1470   return expr_allocate_composite (e, op, &arg0, 1);
1471 }
1472
1473 struct expr_node *
1474 expr_allocate_binary (struct expression *e, operation_type op,
1475                       struct expr_node *arg0, struct expr_node *arg1)
1476 {
1477   struct expr_node *args[2];
1478   args[0] = arg0;
1479   args[1] = arg1;
1480   return expr_allocate_composite (e, op, args, 2);
1481 }
1482
1483 struct expr_node *
1484 expr_allocate_composite (struct expression *e, operation_type op,
1485                          struct expr_node **args, size_t n_args)
1486 {
1487   for (size_t i = 0; i < n_args; i++)
1488     if (!args[i])
1489       return NULL;
1490
1491   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1492   *n = (struct expr_node) {
1493     .type = op,
1494     .n_args = n_args,
1495     .args = pool_clone (e->expr_pool, args, sizeof *n->args * n_args),
1496   };
1497   return n;
1498 }
1499
1500 struct expr_node *
1501 expr_allocate_number (struct expression *e, double d)
1502 {
1503   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1504   *n = (struct expr_node) { .type = OP_number, .number = d };
1505   return n;
1506 }
1507
1508 struct expr_node *
1509 expr_allocate_boolean (struct expression *e, double b)
1510 {
1511   assert (b == 0.0 || b == 1.0 || b == SYSMIS);
1512
1513   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1514   *n = (struct expr_node) { .type = OP_boolean, .number = b };
1515   return n;
1516 }
1517
1518 struct expr_node *
1519 expr_allocate_integer (struct expression *e, int i)
1520 {
1521   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1522   *n = (struct expr_node) { .type = OP_integer, .integer = i };
1523   return n;
1524 }
1525
1526 struct expr_node *
1527 expr_allocate_pos_int (struct expression *e, int i)
1528 {
1529   assert (i > 0);
1530
1531   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1532   *n = (struct expr_node) { .type = OP_pos_int, .integer = i };
1533   return n;
1534 }
1535
1536 struct expr_node *
1537 expr_allocate_vector (struct expression *e, const struct vector *vector)
1538 {
1539   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1540   *n = (struct expr_node) { .type = OP_vector, .vector = vector };
1541   return n;
1542 }
1543
1544 struct expr_node *
1545 expr_allocate_string (struct expression *e, struct substring s)
1546 {
1547   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1548   *n = (struct expr_node) { .type = OP_string, .string = s };
1549   return n;
1550 }
1551
1552 struct expr_node *
1553 expr_allocate_variable (struct expression *e, const struct variable *v)
1554 {
1555   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1556   *n = (struct expr_node) {
1557     .type = var_is_numeric (v) ? OP_num_var : OP_str_var,
1558     .variable = v
1559   };
1560   return n;
1561 }
1562
1563 struct expr_node *
1564 expr_allocate_format (struct expression *e, const struct fmt_spec *format)
1565 {
1566   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1567   *n = (struct expr_node) { .type = OP_format, .format = *format };
1568   return n;
1569 }
1570
1571 struct expr_node *
1572 expr_allocate_expr_node (struct expression *e,
1573                          const struct expr_node *expr_node)
1574 {
1575   struct expr_node *n = pool_alloc (e->expr_pool, sizeof *n);
1576   *n = (struct expr_node) { .type = OP_expr_node, .expr_node = expr_node };
1577   return n;
1578 }
1579
1580 /* Allocates a unary composite node that represents the value of
1581    variable V in expression E. */
1582 static struct expr_node *
1583 allocate_unary_variable (struct expression *e, const struct variable *v)
1584 {
1585   assert (v != NULL);
1586   return expr_allocate_unary (e, var_is_numeric (v) ? OP_NUM_VAR : OP_STR_VAR,
1587                               expr_allocate_variable (e, v));
1588 }
1589 \f
1590 /* Export function details to other modules. */
1591
1592 /* Returns the operation structure for the function with the
1593    given IDX. */
1594 const struct operation *
1595 expr_get_function (size_t idx)
1596 {
1597   assert (idx < n_OP_function);
1598   return &operations[OP_function_first + idx];
1599 }
1600
1601 /* Returns the number of expression functions. */
1602 size_t
1603 expr_get_n_functions (void)
1604 {
1605   return n_OP_function;
1606 }
1607
1608 /* Returns the name of operation OP. */
1609 const char *
1610 expr_operation_get_name (const struct operation *op)
1611 {
1612   return op->name;
1613 }
1614
1615 /* Returns the human-readable prototype for operation OP. */
1616 const char *
1617 expr_operation_get_prototype (const struct operation *op)
1618 {
1619   return op->prototype;
1620 }
1621
1622 /* Returns the number of arguments for operation OP. */
1623 int
1624 expr_operation_get_n_args (const struct operation *op)
1625 {
1626   return op->n_args;
1627 }