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