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