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