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