9819acbbc192aff766a53bf337616ed0528a6014
[pspp] / src / language / lexer / variable-parser.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "language/lexer/variable-parser.h"
20
21 #include <ctype.h>
22 #include <limits.h>
23 #include <stdbool.h>
24 #include <stdlib.h>
25
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/variable.h"
29 #include "language/lexer/lexer.h"
30 #include "libpspp/assertion.h"
31 #include "libpspp/cast.h"
32 #include "libpspp/hash-functions.h"
33 #include "libpspp/i18n.h"
34 #include "libpspp/hmapx.h"
35 #include "libpspp/message.h"
36 #include "libpspp/misc.h"
37 #include "libpspp/pool.h"
38 #include "libpspp/str.h"
39 #include "libpspp/stringi-set.h"
40
41 #include "math/interaction.h"
42
43 #include "gl/c-ctype.h"
44 #include "gl/xalloc.h"
45
46 #include "gettext.h"
47 #define _(msgid) gettext (msgid)
48
49 static struct variable * var_set_get_var (const struct var_set *, size_t );
50
51 static struct variable *var_set_lookup_var (const struct var_set *,
52                                             const char *);
53
54 static bool var_set_lookup_var_idx (const struct var_set *, const char *,
55                                     size_t *);
56
57
58
59 /* Parses a name as a variable within VS.  Sets *IDX to the
60    variable's index and returns true if successful.  On failure
61    emits an error message and returns false. */
62 static bool
63 parse_vs_variable_idx (struct lexer *lexer, const struct var_set *vs,
64                 size_t *idx)
65 {
66   assert (idx != NULL);
67
68   if (lex_token (lexer) != T_ID)
69     {
70       lex_error (lexer, _("expecting variable name"));
71       return false;
72     }
73   else if (var_set_lookup_var_idx (vs, lex_tokcstr (lexer), idx))
74     {
75       lex_get (lexer);
76       return true;
77     }
78   else
79     {
80       msg (SE, _("%s is not a variable name."), lex_tokcstr (lexer));
81       return false;
82     }
83 }
84
85 /* Parses a name as a variable within VS and returns the variable
86    if successful.  On failure emits an error message and returns
87    a null pointer. */
88 static struct variable *
89 parse_vs_variable (struct lexer *lexer, const struct var_set *vs)
90 {
91   size_t idx;
92   return parse_vs_variable_idx (lexer, vs, &idx) ? var_set_get_var (vs, idx) : NULL;
93 }
94
95 /* Parses a variable name in dictionary D and returns the
96    variable if successful.  On failure emits an error message and
97    returns a null pointer. */
98 struct variable *
99 parse_variable (struct lexer *lexer, const struct dictionary *d)
100 {
101   struct var_set *vs = var_set_create_from_dict (d);
102   struct variable *var = parse_vs_variable (lexer, vs);
103   var_set_destroy (vs);
104   return var;
105 }
106
107 /* Parses a set of variables from dictionary D given options
108    OPTS.  Resulting list of variables stored in *VAR and the
109    number of variables into *CNT.  Returns true only if
110    successful. */
111 bool
112 parse_variables (struct lexer *lexer, const struct dictionary *d,
113                         struct variable ***var,
114                         size_t *cnt, int opts)
115 {
116   struct var_set *vs;
117   int success;
118
119   assert (d != NULL);
120   assert (var != NULL);
121   assert (cnt != NULL);
122
123   vs = var_set_create_from_dict (d);
124   success = parse_var_set_vars (lexer, vs, var, cnt, opts);
125   var_set_destroy (vs);
126   return success;
127 }
128
129 /* Parses a set of variables from dictionary D given options
130    OPTS.  Resulting list of variables stored in *VARS and the
131    number of variables into *VAR_CNT.  Returns true only if
132    successful.  Same behavior as parse_variables, except that all
133    allocations are taken from the given POOL. */
134 bool
135 parse_variables_pool (struct lexer *lexer, struct pool *pool,
136                 const struct dictionary *dict,
137                 struct variable ***vars, size_t *var_cnt, int opts)
138 {
139   int retval;
140
141   /* PV_APPEND is unsafe because parse_variables would free the
142      existing names on failure, but those names are presumably
143      already in the pool, which would attempt to re-free it
144      later. */
145   assert (!(opts & PV_APPEND));
146
147   retval = parse_variables (lexer, dict, vars, var_cnt, opts);
148   if (retval)
149     pool_register (pool, free, *vars);
150   return retval;
151 }
152
153 /* Parses a variable name from VS.  If successful, sets *IDX to
154    the variable's index in VS, *CLASS to the variable's
155    dictionary class, and returns true.  Returns false on
156    failure. */
157 static bool
158 parse_var_idx_class (struct lexer *lexer, const struct var_set *vs,
159                         size_t *idx,
160                         enum dict_class *class)
161 {
162   if (!parse_vs_variable_idx (lexer, vs, idx))
163     return false;
164
165   *class = dict_class_from_id (var_get_name (var_set_get_var (vs, *idx)));
166   return true;
167 }
168
169 /* Add the variable from VS with index IDX to the list of
170    variables V that has *NV elements and room for *MV.
171    Uses and updates INCLUDED to avoid duplicates if indicated by
172    PV_OPTS, which also affects what variables are allowed in
173    appropriate ways. */
174 static void
175 add_variable (struct variable ***v, size_t *nv, size_t *mv,
176               char *included, int pv_opts,
177               const struct var_set *vs, size_t idx)
178 {
179   struct variable *add = var_set_get_var (vs, idx);
180   const char *add_name = var_get_name (add);
181
182   if ((pv_opts & PV_NUMERIC) && !var_is_numeric (add))
183     msg (SW, _("%s is not a numeric variable.  It will not be "
184                "included in the variable list."), add_name);
185   else if ((pv_opts & PV_STRING) && !var_is_alpha (add))
186     msg (SE, _("%s is not a string variable.  It will not be "
187                "included in the variable list."), add_name);
188   else if ((pv_opts & PV_NO_SCRATCH)
189            && dict_class_from_id (add_name) == DC_SCRATCH)
190     msg (SE, _("Scratch variables (such as %s) are not allowed "
191                "here."), add_name);
192   else if ((pv_opts & (PV_SAME_TYPE | PV_SAME_WIDTH)) && *nv
193            && var_get_type (add) != var_get_type ((*v)[0]))
194     msg (SE, _("%s and %s are not the same type.  All variables in "
195                "this variable list must be of the same type.  %s "
196                "will be omitted from the list."),
197          var_get_name ((*v)[0]), add_name, add_name);
198   else if ((pv_opts & PV_SAME_WIDTH) && *nv
199            && var_get_width (add) != var_get_width ((*v)[0]))
200     msg (SE, _("%s and %s are string variables with different widths.  "
201                "All variables in this variable list must have the "
202                "same width.  %s will be omitted from the list."),
203          var_get_name ((*v)[0]), add_name, add_name);
204   else if ((pv_opts & PV_NO_DUPLICATE) && included && included[idx])
205     msg (SE, _("Variable %s appears twice in variable list."), add_name);
206   else if ((pv_opts & PV_DUPLICATE) || !included || !included[idx])
207     {
208       if (*nv >= *mv)
209         {
210           *mv = 2 * (*nv + 1);
211           *v = xnrealloc (*v, *mv, sizeof **v);
212         }
213       (*v)[(*nv)++] = add;
214       if (included != NULL)
215         included[idx] = 1;
216     }
217 }
218
219 /* Adds the variables in VS with indexes FIRST_IDX through
220    LAST_IDX, inclusive, to the list of variables V that has *NV
221    elements and room for *MV.  Uses and updates INCLUDED to avoid
222    duplicates if indicated by PV_OPTS, which also affects what
223    variables are allowed in appropriate ways. */
224 static void
225 add_variables (struct variable ***v, size_t *nv, size_t *mv, char *included,
226                int pv_opts,
227                const struct var_set *vs, int first_idx, int last_idx,
228                enum dict_class class)
229 {
230   size_t i;
231
232   for (i = first_idx; i <= last_idx; i++)
233     if (dict_class_from_id (var_get_name (var_set_get_var (vs, i))) == class)
234       add_variable (v, nv, mv, included, pv_opts, vs, i);
235 }
236
237 /* Note that if parse_variables() returns false, *v is free()'d.
238    Conversely, if parse_variables() returns true, then *nv is
239    nonzero and *v is non-NULL. */
240 bool
241 parse_var_set_vars (struct lexer *lexer, const struct var_set *vs,
242                     struct variable ***v, size_t *nv,
243                     int pv_opts)
244 {
245   size_t mv;
246   char *included;
247
248   assert (vs != NULL);
249   assert (v != NULL);
250   assert (nv != NULL);
251
252   /* At most one of PV_NUMERIC, PV_STRING, PV_SAME_TYPE,
253      PV_SAME_WIDTH may be specified. */
254   assert (((pv_opts & PV_NUMERIC) != 0)
255           + ((pv_opts & PV_STRING) != 0)
256           + ((pv_opts & PV_SAME_TYPE) != 0)
257           + ((pv_opts & PV_SAME_WIDTH) != 0) <= 1);
258
259   /* PV_DUPLICATE and PV_NO_DUPLICATE are incompatible. */
260   assert (!(pv_opts & PV_DUPLICATE) || !(pv_opts & PV_NO_DUPLICATE));
261
262   if (!(pv_opts & PV_APPEND))
263     {
264       *v = NULL;
265       *nv = 0;
266       mv = 0;
267     }
268   else
269     mv = *nv;
270
271   if (!(pv_opts & PV_DUPLICATE))
272     {
273       size_t i;
274
275       included = xcalloc (var_set_get_cnt (vs), sizeof *included);
276       for (i = 0; i < *nv; i++)
277         {
278           size_t index;
279           if (!var_set_lookup_var_idx (vs, var_get_name ((*v)[i]), &index))
280             NOT_REACHED ();
281           included[index] = 1;
282         }
283     }
284   else
285     included = NULL;
286
287   do
288     {
289       if (lex_match (lexer, T_ALL))
290         add_variables (v, nv, &mv, included, pv_opts,
291                        vs, 0, var_set_get_cnt (vs) - 1, DC_ORDINARY);
292       else
293         {
294           enum dict_class class;
295           size_t first_idx;
296
297           if (!parse_var_idx_class (lexer, vs, &first_idx, &class))
298             goto fail;
299
300           if (!lex_match (lexer, T_TO))
301             add_variable (v, nv, &mv, included, pv_opts, vs, first_idx);
302           else
303             {
304               size_t last_idx;
305               enum dict_class last_class;
306               struct variable *first_var, *last_var;
307
308               if (!parse_var_idx_class (lexer, vs, &last_idx, &last_class))
309                 goto fail;
310
311               first_var = var_set_get_var (vs, first_idx);
312               last_var = var_set_get_var (vs, last_idx);
313
314               if (last_idx < first_idx)
315                 {
316                   const char *first_name = var_get_name (first_var);
317                   const char *last_name = var_get_name (last_var);
318                   msg (SE, _("%s TO %s is not valid syntax since %s "
319                              "precedes %s in the dictionary."),
320                        first_name, last_name, first_name, last_name);
321                   goto fail;
322                 }
323
324               if (class != last_class)
325                 {
326                   msg (SE, _("When using the TO keyword to specify several "
327                              "variables, both variables must be from "
328                              "the same variable dictionaries, of either "
329                              "ordinary, scratch, or system variables.  "
330                              "%s is a %s variable, whereas %s is %s."),
331                        var_get_name (first_var), dict_class_to_name (class),
332                        var_get_name (last_var),
333                        dict_class_to_name (last_class));
334                   goto fail;
335                 }
336
337               add_variables (v, nv, &mv, included, pv_opts,
338                              vs, first_idx, last_idx, class);
339             }
340         }
341
342       if (pv_opts & PV_SINGLE)
343         break;
344       lex_match (lexer, T_COMMA);
345     }
346   while (lex_token (lexer) == T_ALL
347          || (lex_token (lexer) == T_ID && var_set_lookup_var (vs, lex_tokcstr (lexer)) != NULL));
348
349   if (*nv == 0)
350     goto fail;
351
352   free (included);
353   return 1;
354
355 fail:
356   free (included);
357   free (*v);
358   *v = NULL;
359   *nv = 0;
360   return 0;
361 }
362
363 /* Attempts to break UTF-8 encoded NAME into a root (whose contents are
364    arbitrary except that it does not end in a digit) followed by an integer
365    numeric suffix.  On success, stores the value of the suffix into *NUMBERP,
366    the number of digits in the suffix into *N_DIGITSP, and returns the number
367    of bytes in the root.  On failure, returns 0. */
368 static int
369 extract_numeric_suffix (const char *name,
370                         unsigned long int *numberp, int *n_digitsp)
371 {
372   size_t root_len, n_digits;
373   size_t i;
374
375   /* Count length of root. */
376   root_len = 1;                 /* Valid identifier never starts with digit. */
377   for (i = 1; name[i] != '\0'; i++)
378     if (!c_isdigit (name[i]))
379       root_len = i + 1;
380   n_digits = i - root_len;
381
382   if (n_digits == 0)
383     {
384       msg (SE, _("`%s' cannot be used with TO because it does not end in "
385                  "a digit."), name);
386       return 0;
387     }
388
389   *numberp = strtoull (name + root_len, NULL, 10);
390   if (*numberp == ULONG_MAX)
391     {
392       msg (SE, _("Numeric suffix on `%s' is larger than supported with TO."),
393            name);
394       return 0;
395     }
396   *n_digitsp = n_digits;
397   return root_len;
398 }
399
400 static bool
401 add_var_name (char *name,
402               char ***names, size_t *n_vars, size_t *allocated_vars,
403               struct stringi_set *set, int pv_opts)
404 {
405   if (pv_opts & PV_NO_DUPLICATE && !stringi_set_insert (set, name))
406     {
407       msg (SE, _("Variable %s appears twice in variable list."),
408            name);
409       return false;
410     }
411
412   if (*n_vars >= *allocated_vars)
413     *names = x2nrealloc (*names, allocated_vars, sizeof **names);
414   (*names)[(*n_vars)++] = name;
415   return true;
416 }
417
418 /* Parses a list of variable names according to the DATA LIST version
419    of the TO convention.  */
420 bool
421 parse_DATA_LIST_vars (struct lexer *lexer, const struct dictionary *dict,
422                       char ***namesp, size_t *n_varsp, int pv_opts)
423 {
424   char **names;
425   size_t n_vars;
426   size_t allocated_vars;
427
428   struct stringi_set set;
429
430   char *name1 = NULL;
431
432   bool ok = false;
433
434   assert ((pv_opts & ~(PV_APPEND | PV_SINGLE
435                        | PV_NO_SCRATCH | PV_NO_DUPLICATE)) == 0);
436   stringi_set_init (&set);
437
438   if (pv_opts & PV_APPEND)
439     {
440       n_vars = allocated_vars = *n_varsp;
441       names = *namesp;
442
443       if (pv_opts & PV_NO_DUPLICATE)
444         {
445           size_t i;
446
447           for (i = 0; i < n_vars; i++)
448             stringi_set_insert (&set, names[i]);
449         }
450     }
451   else
452     {
453       n_vars = allocated_vars = 0;
454       names = NULL;
455     }
456
457   do
458     {
459       if (lex_token (lexer) != T_ID
460           || !dict_id_is_valid (dict, lex_tokcstr (lexer), true))
461         {
462           lex_error (lexer, "expecting variable name");
463           goto exit;
464         }
465       if (dict_class_from_id (lex_tokcstr (lexer)) == DC_SCRATCH
466           && (pv_opts & PV_NO_SCRATCH))
467         {
468           msg (SE, _("Scratch variables not allowed here."));
469           goto exit;
470         }
471       name1 = xstrdup (lex_tokcstr (lexer));
472       lex_get (lexer);
473       if (lex_token (lexer) == T_TO)
474         {
475           char *name2 = NULL;
476           unsigned long int num1, num2;
477           int n_digits1, n_digits2;
478           int root_len1, root_len2;
479           unsigned long int number;
480
481           lex_get (lexer);
482           if (lex_token (lexer) != T_ID
483               || !dict_id_is_valid (dict, lex_tokcstr (lexer), true))
484             {
485               lex_error (lexer, "expecting variable name");
486               goto exit;
487             }
488           name2 = xstrdup (lex_tokcstr (lexer));
489           lex_get (lexer);
490
491           root_len1 = extract_numeric_suffix (name1, &num1, &n_digits1);
492           if (root_len1 == 0)
493             goto exit;
494
495           root_len2 = extract_numeric_suffix (name2, &num2, &n_digits2);
496           if (root_len2 == 0)
497             goto exit;
498
499           if (root_len1 != root_len2 || memcasecmp (name1, name2, root_len1))
500             {
501               msg (SE, _("Prefixes don't match in use of TO convention."));
502               goto exit;
503             }
504           if (num1 > num2)
505             {
506               msg (SE, _("Bad bounds in use of TO convention."));
507               goto exit;
508             }
509
510           for (number = num1; number <= num2; number++)
511             {
512               char *name = xasprintf ("%.*s%0*lu",
513                                       root_len1, name1,
514                                       n_digits1, number);
515               if (!add_var_name (name, &names, &n_vars, &allocated_vars,
516                                  &set, pv_opts))
517                 {
518                   free (name);
519                   goto exit;
520                 }
521             }
522
523           free (name1);
524           name1 = NULL;
525           free (name2);
526         }
527       else
528         {
529           if (!add_var_name (name1, &names, &n_vars, &allocated_vars,
530                              &set, pv_opts))
531             goto exit;
532           name1 = NULL;
533         }
534
535       lex_match (lexer, T_COMMA);
536
537       if (pv_opts & PV_SINGLE)
538         break;
539     }
540   while (lex_token (lexer) == T_ID);
541   ok = true;
542
543 exit:
544   stringi_set_destroy (&set);
545   if (ok)
546     {
547       *namesp = names;
548       *n_varsp = n_vars;
549     }
550   else
551     {
552       int i;
553       for (i = 0; i < n_vars; i++)
554         free (names[i]);
555       free (names);
556       *namesp = NULL;
557       *n_varsp = 0;
558
559       free (name1);
560     }
561   return ok;
562 }
563
564 /* Registers each of the NAMES[0...NNAMES - 1] in POOL, as well
565    as NAMES itself. */
566 static void
567 register_vars_pool (struct pool *pool, char **names, size_t nnames)
568 {
569   size_t i;
570
571   for (i = 0; i < nnames; i++)
572     pool_register (pool, free, names[i]);
573   pool_register (pool, free, names);
574 }
575
576 /* Parses a list of variable names according to the DATA LIST
577    version of the TO convention.  Same args as
578    parse_DATA_LIST_vars(), except that all allocations are taken
579    from the given POOL. */
580 bool
581 parse_DATA_LIST_vars_pool (struct lexer *lexer, const struct dictionary *dict,
582                            struct pool *pool,
583                            char ***names, size_t *nnames, int pv_opts)
584 {
585   int retval;
586
587   /* PV_APPEND is unsafe because parse_DATA_LIST_vars would free
588      the existing names on failure, but those names are
589      presumably already in the pool, which would attempt to
590      re-free it later. */
591   assert (!(pv_opts & PV_APPEND));
592
593   retval = parse_DATA_LIST_vars (lexer, dict, names, nnames, pv_opts);
594   if (retval)
595     register_vars_pool (pool, *names, *nnames);
596   return retval;
597 }
598
599 /* Parses a list of variables where some of the variables may be
600    existing and the rest are to be created.  Same args as
601    parse_DATA_LIST_vars(). */
602 bool
603 parse_mixed_vars (struct lexer *lexer, const struct dictionary *dict,
604                   char ***names, size_t *nnames, int pv_opts)
605 {
606   size_t i;
607
608   assert (names != NULL);
609   assert (nnames != NULL);
610   assert ((pv_opts & ~PV_APPEND) == 0);
611
612   if (!(pv_opts & PV_APPEND))
613     {
614       *names = NULL;
615       *nnames = 0;
616     }
617   while (lex_token (lexer) == T_ID || lex_token (lexer) == T_ALL)
618     {
619       if (lex_token (lexer) == T_ALL || dict_lookup_var (dict, lex_tokcstr (lexer)) != NULL)
620         {
621           struct variable **v;
622           size_t nv;
623
624           if (!parse_variables (lexer, dict, &v, &nv, PV_NONE))
625             goto fail;
626           *names = xnrealloc (*names, *nnames + nv, sizeof **names);
627           for (i = 0; i < nv; i++)
628             (*names)[*nnames + i] = xstrdup (var_get_name (v[i]));
629           free (v);
630           *nnames += nv;
631         }
632       else if (!parse_DATA_LIST_vars (lexer, dict, names, nnames, PV_APPEND))
633         goto fail;
634     }
635   if (*nnames == 0)
636     goto fail;
637
638   return true;
639
640 fail:
641   for (i = 0; i < *nnames; i++)
642     free ((*names)[i]);
643   free (*names);
644   *names = NULL;
645   *nnames = 0;
646   return false;
647 }
648
649 /* Parses a list of variables where some of the variables may be
650    existing and the rest are to be created.  Same args as
651    parse_mixed_vars(), except that all allocations are taken
652    from the given POOL. */
653 bool
654 parse_mixed_vars_pool (struct lexer *lexer, const struct dictionary *dict, struct pool *pool,
655                        char ***names, size_t *nnames, int pv_opts)
656 {
657   int retval;
658
659   /* PV_APPEND is unsafe because parse_mixed_vars_pool would free
660      the existing names on failure, but those names are
661      presumably already in the pool, which would attempt to
662      re-free it later. */
663   assert (!(pv_opts & PV_APPEND));
664
665   retval = parse_mixed_vars (lexer, dict, names, nnames, pv_opts);
666   if (retval)
667     register_vars_pool (pool, *names, *nnames);
668   return retval;
669 }
670 \f
671 /* A set of variables. */
672 struct var_set
673   {
674     size_t (*get_cnt) (const struct var_set *);
675     struct variable *(*get_var) (const struct var_set *, size_t idx);
676     bool (*lookup_var_idx) (const struct var_set *, const char *, size_t *);
677     void (*destroy) (struct var_set *);
678     void *aux;
679   };
680
681 /* Returns the number of variables in VS. */
682 size_t
683 var_set_get_cnt (const struct var_set *vs)
684 {
685   assert (vs != NULL);
686
687   return vs->get_cnt (vs);
688 }
689
690 /* Return variable with index IDX in VS.
691    IDX must be less than the number of variables in VS. */
692 static struct variable *
693 var_set_get_var (const struct var_set *vs, size_t idx)
694 {
695   assert (vs != NULL);
696   assert (idx < var_set_get_cnt (vs));
697
698   return vs->get_var (vs, idx);
699 }
700
701 /* Returns the variable in VS named NAME, or a null pointer if VS
702    contains no variable with that name. */
703 struct variable *
704 var_set_lookup_var (const struct var_set *vs, const char *name)
705 {
706   size_t idx;
707   return (var_set_lookup_var_idx (vs, name, &idx)
708           ? var_set_get_var (vs, idx)
709           : NULL);
710 }
711
712 /* If VS contains a variable named NAME, sets *IDX to its index
713    and returns true.  Otherwise, returns false. */
714 bool
715 var_set_lookup_var_idx (const struct var_set *vs, const char *name,
716                         size_t *idx)
717 {
718   assert (vs != NULL);
719   assert (name != NULL);
720
721   return vs->lookup_var_idx (vs, name, idx);
722 }
723
724 /* Destroys VS. */
725 void
726 var_set_destroy (struct var_set *vs)
727 {
728   if (vs != NULL)
729     vs->destroy (vs);
730 }
731 \f
732 /* Returns the number of variables in VS. */
733 static size_t
734 dict_var_set_get_cnt (const struct var_set *vs)
735 {
736   struct dictionary *d = vs->aux;
737
738   return dict_get_var_cnt (d);
739 }
740
741 /* Return variable with index IDX in VS.
742    IDX must be less than the number of variables in VS. */
743 static struct variable *
744 dict_var_set_get_var (const struct var_set *vs, size_t idx)
745 {
746   struct dictionary *d = vs->aux;
747
748   return dict_get_var (d, idx);
749 }
750
751 /* If VS contains a variable named NAME, sets *IDX to its index
752    and returns true.  Otherwise, returns false. */
753 static bool
754 dict_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
755                              size_t *idx)
756 {
757   struct dictionary *d = vs->aux;
758   struct variable *v = dict_lookup_var (d, name);
759   if (v != NULL)
760     {
761       *idx = var_get_dict_index (v);
762       return true;
763     }
764   else
765     return false;
766 }
767
768 /* Destroys VS. */
769 static void
770 dict_var_set_destroy (struct var_set *vs)
771 {
772   free (vs);
773 }
774
775 /* Returns a variable set based on D. */
776 struct var_set *
777 var_set_create_from_dict (const struct dictionary *d)
778 {
779   struct var_set *vs = xmalloc (sizeof *vs);
780   vs->get_cnt = dict_var_set_get_cnt;
781   vs->get_var = dict_var_set_get_var;
782   vs->lookup_var_idx = dict_var_set_lookup_var_idx;
783   vs->destroy = dict_var_set_destroy;
784   vs->aux = (void *) d;
785   return vs;
786 }
787 \f
788 /* A variable set based on an array. */
789 struct array_var_set
790   {
791     struct variable *const *var;/* Array of variables. */
792     size_t var_cnt;             /* Number of elements in var. */
793     struct hmapx vars_by_name;  /* Variables hashed by name. */
794   };
795
796 /* Returns the number of variables in VS. */
797 static size_t
798 array_var_set_get_cnt (const struct var_set *vs)
799 {
800   struct array_var_set *avs = vs->aux;
801
802   return avs->var_cnt;
803 }
804
805 /* Return variable with index IDX in VS.
806    IDX must be less than the number of variables in VS. */
807 static struct variable *
808 array_var_set_get_var (const struct var_set *vs, size_t idx)
809 {
810   struct array_var_set *avs = vs->aux;
811
812   return CONST_CAST (struct variable *, avs->var[idx]);
813 }
814
815 /* If VS contains a variable named NAME, sets *IDX to its index
816    and returns true.  Otherwise, returns false. */
817 static bool
818 array_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
819                               size_t *idx)
820 {
821   struct array_var_set *avs = vs->aux;
822   struct hmapx_node *node;
823   struct variable **varp;
824
825   HMAPX_FOR_EACH_WITH_HASH (varp, node, utf8_hash_case_string (name, 0),
826                             &avs->vars_by_name)
827     if (!utf8_strcasecmp (name, var_get_name (*varp)))
828       {
829         *idx = varp - avs->var;
830         return true;
831       }
832
833   return false;
834 }
835
836 /* Destroys VS. */
837 static void
838 array_var_set_destroy (struct var_set *vs)
839 {
840   struct array_var_set *avs = vs->aux;
841
842   hmapx_destroy (&avs->vars_by_name);
843   free (avs);
844   free (vs);
845 }
846
847 /* Returns a variable set based on the VAR_CNT variables in VAR. */
848 struct var_set *
849 var_set_create_from_array (struct variable *const *var, size_t var_cnt)
850 {
851   struct var_set *vs;
852   struct array_var_set *avs;
853   size_t i;
854
855   vs = xmalloc (sizeof *vs);
856   vs->get_cnt = array_var_set_get_cnt;
857   vs->get_var = array_var_set_get_var;
858   vs->lookup_var_idx = array_var_set_lookup_var_idx;
859   vs->destroy = array_var_set_destroy;
860   vs->aux = avs = xmalloc (sizeof *avs);
861   avs->var = var;
862   avs->var_cnt = var_cnt;
863   hmapx_init (&avs->vars_by_name);
864   for (i = 0; i < var_cnt; i++)
865     {
866       const char *name = var_get_name (var[i]);
867       size_t idx;
868
869       if (array_var_set_lookup_var_idx (vs, name, &idx))
870         {
871           var_set_destroy (vs);
872           return NULL;
873         }
874       hmapx_insert (&avs->vars_by_name, CONST_CAST (void *, &avs->var[i]),
875                     utf8_hash_case_string (name, 0));
876     }
877
878   return vs;
879 }
880
881
882 /* Match a variable.
883    If the match succeeds, the variable will be placed in VAR.
884    Returns true if successful */
885 bool
886 lex_match_variable (struct lexer *lexer, const struct dictionary *dict, const struct variable **var)
887 {
888   if (lex_token (lexer) !=  T_ID)
889     return false;
890
891   *var = parse_variable_const  (lexer, dict);
892
893   if ( *var == NULL)
894     return false;
895   return true;
896 }
897
898 /* An interaction is a variable followed by {*, BY} followed by an interaction */
899 static bool
900 parse_internal_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact, struct interaction **it)
901 {
902   const struct variable *v = NULL;
903   assert (iact);
904
905   switch  (lex_next_token (lexer, 1))
906     {
907     case T_ENDCMD:
908     case T_SLASH:
909     case T_COMMA:
910     case T_ID:
911     case T_BY:
912     case T_ASTERISK:
913       break;
914     default:
915       return false;
916       break;
917     }
918
919   if (! lex_match_variable (lexer, dict, &v))
920     {
921       if (it)
922         interaction_destroy (*it);
923       *iact = NULL;
924       return false;
925     }
926
927   assert (v);
928
929   if ( *iact == NULL)
930     *iact = interaction_create (v);
931   else
932     interaction_add_variable (*iact, v);
933
934   if ( lex_match (lexer, T_ASTERISK) || lex_match (lexer, T_BY))
935     {
936       return parse_internal_interaction (lexer, dict, iact, iact);
937     }
938
939   return true;
940 }
941
942 bool
943 parse_design_interaction (struct lexer *lexer, const struct dictionary *dict, struct interaction **iact)
944 {
945   return parse_internal_interaction (lexer, dict, iact, NULL);
946 }
947