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