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