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