dictionary: Fix misuse of DC_* treewide.
[pspp] / src / language / lexer / variable-parser.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011, 2012, 2020 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 static struct variable *var_set_lookup_var (const struct var_set *,
51                                             const char *);
52 static bool var_set_lookup_var_idx (const struct var_set *, const char *,
53                                     size_t *);
54 static bool var_set_get_names_must_be_ids (const struct var_set *);
55
56 static bool
57 is_name_token (const struct lexer *lexer, bool names_must_be_ids)
58 {
59   return (lex_token (lexer) == T_ID
60           || (!names_must_be_ids && lex_token (lexer) == T_STRING));
61 }
62
63 static bool
64 is_vs_name_token (const struct lexer *lexer, const struct var_set *vs)
65 {
66   return is_name_token (lexer, var_set_get_names_must_be_ids (vs));
67 }
68
69 static bool
70 is_dict_name_token (const struct lexer *lexer, const struct dictionary *d)
71 {
72   return is_name_token (lexer, dict_get_names_must_be_ids (d));
73 }
74
75 /* Parses a name as a variable within VS.  Sets *IDX to the
76    variable's index and returns true if successful.  On failure
77    emits an error message and returns false. */
78 static bool
79 parse_vs_variable_idx (struct lexer *lexer, const struct var_set *vs,
80                        size_t *idx)
81 {
82   assert (idx != NULL);
83
84   if (!is_vs_name_token (lexer, vs))
85     {
86       lex_error (lexer, _("Syntax error expecting variable name."));
87       return false;
88     }
89   else if (var_set_lookup_var_idx (vs, lex_tokcstr (lexer), idx))
90     {
91       lex_get (lexer);
92       return true;
93     }
94   else
95     {
96       lex_error (lexer, _("%s is not a variable name."), lex_tokcstr (lexer));
97       return false;
98     }
99 }
100
101 /* Parses a name as a variable within VS and returns the variable
102    if successful.  On failure emits an error message and returns
103    a null pointer. */
104 static struct variable *
105 parse_vs_variable (struct lexer *lexer, const struct var_set *vs)
106 {
107   size_t idx;
108   return parse_vs_variable_idx (lexer, vs, &idx) ? var_set_get_var (vs, idx) : NULL;
109 }
110
111 /* Parses a variable name in dictionary D and returns the
112    variable if successful.  On failure emits an error message and
113    returns a null pointer. */
114 struct variable *
115 parse_variable (struct lexer *lexer, const struct dictionary *d)
116 {
117   struct var_set *vs = var_set_create_from_dict (d);
118   struct variable *var = parse_vs_variable (lexer, vs);
119   var_set_destroy (vs);
120   return var;
121 }
122
123 /* Parses a set of variables from dictionary D given options
124    OPTS.  Resulting list of variables stored in *VAR and the
125    number of variables into *N.  Returns true only if
126    successful.  The dictionary D must contain at least one
127    variable.  */
128 bool
129 parse_variables (struct lexer *lexer, const struct dictionary *d,
130                  struct variable ***var,
131                  size_t *n, int opts)
132 {
133   struct var_set *vs;
134   int success;
135
136   assert (d != NULL);
137   assert (var != NULL);
138   assert (n != NULL);
139
140   vs = var_set_create_from_dict (d);
141   if (var_set_get_n (vs) == 0)
142     {
143       *n = 0;
144       var_set_destroy (vs);
145       return false;
146     }
147   success = parse_var_set_vars (lexer, vs, var, n, opts);
148   var_set_destroy (vs);
149   return success;
150 }
151
152 /* Parses a set of variables from dictionary D given options
153    OPTS.  Resulting list of variables stored in *VARS and the
154    number of variables into *N_VARS.  Returns true only if
155    successful.  Same behavior as parse_variables, except that all
156    allocations are taken from the given POOL. */
157 bool
158 parse_variables_pool (struct lexer *lexer, struct pool *pool,
159                 const struct dictionary *dict,
160                 struct variable ***vars, size_t *n_vars, int opts)
161 {
162   int retval;
163
164   /* PV_APPEND is unsafe because parse_variables would free the
165      existing names on failure, but those names are presumably
166      already in the pool, which would attempt to re-free it
167      later. */
168   assert (!(opts & PV_APPEND));
169
170   retval = parse_variables (lexer, dict, vars, n_vars, opts);
171   if (retval)
172     pool_register (pool, free, *vars);
173   return retval;
174 }
175
176 /* Parses a variable name from VS.  If successful, sets *IDX to
177    the variable's index in VS, *CLASS to the variable's
178    dictionary class, and returns true.  Returns false on
179    failure. */
180 static bool
181 parse_var_idx_class (struct lexer *lexer, const struct var_set *vs,
182                      size_t *idx, enum dict_class *class)
183 {
184   if (!parse_vs_variable_idx (lexer, vs, idx))
185     return false;
186
187   *class = dict_class_from_id (var_get_name (var_set_get_var (vs, *idx)));
188   return true;
189 }
190
191 /* Add the variable from VS with index IDX to the list of
192    variables V that has *NV elements and room for *MV.
193    Uses and updates INCLUDED to avoid duplicates if indicated by
194    PV_OPTS, which also affects what variables are allowed in
195    appropriate ways. */
196 static void
197 add_variable (struct lexer *lexer,
198               struct variable ***v, size_t *nv, size_t *mv,
199               char *included, int pv_opts,
200               const struct var_set *vs, size_t idx,
201               int start_ofs, int end_ofs)
202 {
203   struct variable *add = var_set_get_var (vs, idx);
204   const char *add_name = var_get_name (add);
205
206   if ((pv_opts & PV_NUMERIC) && !var_is_numeric (add))
207     lex_ofs_msg (lexer, SW, start_ofs, end_ofs,
208                  _("%s is not a numeric variable.  It will not be "
209                    "included in the variable list."), add_name);
210   else if ((pv_opts & PV_STRING) && !var_is_alpha (add))
211     lex_ofs_error (lexer, start_ofs, end_ofs,
212                    _("%s is not a string variable.  It will not be "
213                      "included in the variable list."), add_name);
214   else if ((pv_opts & PV_NO_SCRATCH)
215            && dict_class_from_id (add_name) == DC_SCRATCH)
216     lex_ofs_error (lexer, start_ofs, end_ofs,
217                    _("Scratch variables (such as %s) are not allowed "
218                      "here."), add_name);
219   else if ((pv_opts & (PV_SAME_TYPE | PV_SAME_WIDTH)) && *nv
220            && var_get_type (add) != var_get_type ((*v)[0]))
221     lex_ofs_error (lexer, start_ofs, end_ofs,
222                  _("%s and %s are not the same type.  All variables in "
223                    "this variable list must be of the same type.  %s "
224                    "will be omitted from the list."),
225                  var_get_name ((*v)[0]), add_name, add_name);
226   else if ((pv_opts & PV_SAME_WIDTH) && *nv
227            && var_get_width (add) != var_get_width ((*v)[0]))
228     lex_ofs_error (lexer, start_ofs, end_ofs,
229                  _("%s and %s are string variables with different widths.  "
230                    "All variables in this variable list must have the "
231                    "same width.  %s will be omitted from the list."),
232                  var_get_name ((*v)[0]), add_name, add_name);
233   else if ((pv_opts & PV_NO_DUPLICATE) && included && included[idx])
234     lex_ofs_error (lexer, start_ofs, end_ofs,
235                    _("Variable %s appears twice in variable list."), add_name);
236   else if ((pv_opts & PV_DUPLICATE) || !included || !included[idx])
237     {
238       if (*nv >= *mv)
239         {
240           *mv = 2 * (*nv + 1);
241           *v = xnrealloc (*v, *mv, sizeof **v);
242         }
243       (*v)[(*nv)++] = add;
244       if (included != NULL)
245         included[idx] = 1;
246     }
247 }
248
249 /* Adds the variables in VS with indexes FIRST_IDX through
250    LAST_IDX, inclusive, to the list of variables V that has *NV
251    elements and room for *MV.  Uses and updates INCLUDED to avoid
252    duplicates if indicated by PV_OPTS, which also affects what
253    variables are allowed in appropriate ways. */
254 static void
255 add_variables (struct lexer *lexer,
256                struct variable ***v, size_t *nv, size_t *mv, char *included,
257                int pv_opts,
258                const struct var_set *vs, int first_idx, int last_idx,
259                enum dict_class class,
260                int start_ofs, int end_ofs)
261 {
262   size_t i;
263
264   for (i = first_idx; i <= last_idx; i++)
265     if (dict_class_from_id (var_get_name (var_set_get_var (vs, i))) == class)
266       add_variable (lexer, v, nv, mv, included, pv_opts, vs, i,
267                     start_ofs, end_ofs);
268 }
269
270 /* Note that if parse_variables() returns false, *v is free()'d.
271    Conversely, if parse_variables() returns true, then *nv is
272    nonzero and *v is non-NULL. */
273 bool
274 parse_var_set_vars (struct lexer *lexer, const struct var_set *vs,
275                     struct variable ***v, size_t *nv,
276                     int pv_opts)
277 {
278   size_t mv;
279   char *included;
280
281   assert (vs != NULL);
282   assert (v != NULL);
283   assert (nv != NULL);
284
285   /* At most one of PV_NUMERIC, PV_STRING, PV_SAME_TYPE,
286      PV_SAME_WIDTH may be specified. */
287   assert (((pv_opts & PV_NUMERIC) != 0)
288           + ((pv_opts & PV_STRING) != 0)
289           + ((pv_opts & PV_SAME_TYPE) != 0)
290           + ((pv_opts & PV_SAME_WIDTH) != 0) <= 1);
291
292   /* PV_DUPLICATE and PV_NO_DUPLICATE are incompatible. */
293   assert (!(pv_opts & PV_DUPLICATE) || !(pv_opts & PV_NO_DUPLICATE));
294
295   if (!(pv_opts & PV_APPEND))
296     {
297       *v = NULL;
298       *nv = 0;
299       mv = 0;
300     }
301   else
302     mv = *nv;
303
304   if (!(pv_opts & PV_DUPLICATE))
305     {
306       size_t i;
307
308       included = xcalloc (var_set_get_n (vs), sizeof *included);
309       for (i = 0; i < *nv; i++)
310         {
311           size_t index;
312           if (!var_set_lookup_var_idx (vs, var_get_name ((*v)[i]), &index))
313             NOT_REACHED ();
314           included[index] = 1;
315         }
316     }
317   else
318     included = NULL;
319
320   do
321     {
322       int start_ofs = lex_ofs (lexer);
323       if (lex_match (lexer, T_ALL))
324         add_variables (lexer, v, nv, &mv, included, pv_opts,
325                        vs, 0, var_set_get_n (vs) - 1, DC_ORDINARY,
326                        start_ofs, start_ofs);
327       else
328         {
329           enum dict_class class;
330           size_t first_idx;
331
332           if (!parse_var_idx_class (lexer, vs, &first_idx, &class))
333             goto fail;
334
335           if (!lex_match (lexer, T_TO))
336             add_variable (lexer, v, nv, &mv, included, pv_opts, vs, first_idx,
337                           start_ofs, start_ofs);
338           else
339             {
340               size_t last_idx;
341               enum dict_class last_class;
342               struct variable *first_var, *last_var;
343
344               if (!parse_var_idx_class (lexer, vs, &last_idx, &last_class))
345                 goto fail;
346
347               int end_ofs = lex_ofs (lexer) - 1;
348
349               first_var = var_set_get_var (vs, first_idx);
350               last_var = var_set_get_var (vs, last_idx);
351
352               if (last_idx < first_idx)
353                 {
354                   const char *first_name = var_get_name (first_var);
355                   const char *last_name = var_get_name (last_var);
356                   lex_ofs_error (lexer, start_ofs, end_ofs,
357                                  _("%s TO %s is not valid syntax since %s "
358                                    "precedes %s in the dictionary."),
359                                  first_name, last_name, first_name, last_name);
360                   goto fail;
361                 }
362
363               if (class != last_class)
364                 {
365                   lex_ofs_error (lexer, start_ofs, end_ofs,
366                                  _("With the syntax <a> TO <b>, variables <a> "
367                                    "and <b> must be both regular variables "
368                                    "or both scratch variables."));
369                   struct pair
370                     {
371                       const char *name;
372                       enum dict_class class;
373                       int ofs;
374                     }
375                   pairs[2] = {
376                     { var_get_name (first_var), class, start_ofs },
377                     { var_get_name (last_var), last_class, end_ofs },
378                   };
379                   for (size_t i = 0; i < 2; i++)
380                     switch (pairs[i].class)
381                       {
382                       case DC_ORDINARY:
383                         lex_ofs_msg (lexer, SN, pairs[i].ofs, pairs[i].ofs,
384                                      _("%s is a regular variable."),
385                                      pairs[i].name);
386                         break;
387
388                       case DC_SCRATCH:
389                         lex_ofs_msg (lexer, SN, pairs[i].ofs, pairs[i].ofs,
390                                      _("%s is a scratch variable."),
391                                      pairs[i].name);
392                         break;
393
394                       case DC_SYSTEM:
395                         lex_ofs_msg (lexer, SN, pairs[i].ofs, pairs[i].ofs,
396                                      _("%s is a system variable."),
397                                      pairs[i].name);
398                         break;
399                       }
400                   goto fail;
401                 }
402
403               add_variables (lexer, v, nv, &mv, included, pv_opts,
404                              vs, first_idx, last_idx, class,
405                              start_ofs, lex_ofs (lexer) - 1);
406             }
407         }
408
409       if (pv_opts & PV_SINGLE)
410         break;
411       lex_match (lexer, T_COMMA);
412     }
413   while (lex_token (lexer) == T_ALL
414          || (is_vs_name_token (lexer, vs)
415              && var_set_lookup_var (vs, lex_tokcstr (lexer)) != NULL));
416
417   if (*nv == 0)
418     goto fail;
419
420   free (included);
421   return 1;
422
423 fail:
424   free (included);
425   free (*v);
426   *v = NULL;
427   *nv = 0;
428   return 0;
429 }
430
431 char *
432 parse_DATA_LIST_var (struct lexer *lexer, const struct dictionary *d)
433 {
434   if (!is_dict_name_token (lexer, d))
435     {
436       lex_error (lexer, ("Syntax error expecting variable name."));
437       return NULL;
438     }
439   char *error = dict_id_is_valid__ (d, lex_tokcstr (lexer));
440   if (error)
441     {
442       lex_error (lexer, "%s", error);
443       free (error);
444       return NULL;
445     }
446
447   char *name = xstrdup (lex_tokcstr (lexer));
448   lex_get (lexer);
449   return name;
450 }
451
452 /* Attempts to break UTF-8 encoded NAME into a root (whose contents are
453    arbitrary except that it does not end in a digit) followed by an integer
454    numeric suffix.  On success, stores the value of the suffix into *NUMBERP,
455    the number of digits in the suffix into *N_DIGITSP, and returns the number
456    of bytes in the root.  On failure, returns 0. */
457 static int
458 extract_numeric_suffix (struct lexer *lexer, int ofs, const char *name,
459                         unsigned long int *numberp, int *n_digitsp)
460 {
461   size_t root_len, n_digits;
462   size_t i;
463
464   /* Count length of root. */
465   root_len = 1;                 /* Valid identifier never starts with digit. */
466   for (i = 1; name[i] != '\0'; i++)
467     if (!c_isdigit (name[i]))
468       root_len = i + 1;
469   n_digits = i - root_len;
470
471   if (n_digits == 0)
472     {
473       lex_ofs_error (lexer, ofs, ofs,
474                      _("`%s' cannot be used with TO because it does not end in "
475                        "a digit."), name);
476       return 0;
477     }
478
479   *numberp = strtoull (name + root_len, NULL, 10);
480   if (*numberp == ULONG_MAX)
481     {
482       lex_ofs_error (lexer, ofs, ofs,
483                      _("Numeric suffix on `%s' is larger than supported with TO."),
484                      name);
485       return 0;
486     }
487   *n_digitsp = n_digits;
488   return root_len;
489 }
490
491 static bool
492 add_var_name (struct lexer *lexer, int start_ofs, int end_ofs, char *name,
493               char ***names, size_t *n_vars, size_t *allocated_vars,
494               struct stringi_set *set, int pv_opts)
495 {
496   if (pv_opts & PV_NO_DUPLICATE && !stringi_set_insert (set, name))
497     {
498       lex_ofs_error (lexer, start_ofs, end_ofs,
499                      _("Variable %s appears twice in variable list."),
500                      name);
501       return false;
502     }
503
504   if (*n_vars >= *allocated_vars)
505     *names = x2nrealloc (*names, allocated_vars, sizeof **names);
506   (*names)[(*n_vars)++] = name;
507   return true;
508 }
509
510 /* Parses a list of variable names according to the DATA LIST version
511    of the TO convention.  */
512 bool
513 parse_DATA_LIST_vars (struct lexer *lexer, const struct dictionary *dict,
514                       char ***namesp, size_t *n_varsp, int pv_opts)
515 {
516   char **names;
517   size_t n_vars;
518   size_t allocated_vars;
519
520   struct stringi_set set;
521
522   char *name1 = NULL;
523   char *name2 = NULL;
524
525   bool ok = false;
526
527   assert ((pv_opts & ~(PV_APPEND | PV_SINGLE
528                        | PV_NO_SCRATCH | PV_NO_DUPLICATE)) == 0);
529   stringi_set_init (&set);
530
531   if (pv_opts & PV_APPEND)
532     {
533       n_vars = allocated_vars = *n_varsp;
534       names = *namesp;
535
536       if (pv_opts & PV_NO_DUPLICATE)
537         {
538           size_t i;
539
540           for (i = 0; i < n_vars; i++)
541             stringi_set_insert (&set, names[i]);
542         }
543     }
544   else
545     {
546       n_vars = allocated_vars = 0;
547       names = NULL;
548     }
549
550   do
551     {
552       int start_ofs = lex_ofs (lexer);
553       name1 = parse_DATA_LIST_var (lexer, dict);
554       if (!name1)
555         goto exit;
556       if (dict_class_from_id (name1) == DC_SCRATCH && pv_opts & PV_NO_SCRATCH)
557         {
558           lex_ofs_error (lexer, start_ofs, start_ofs,
559                          _("Scratch variables not allowed here."));
560           goto exit;
561         }
562       if (lex_match (lexer, T_TO))
563         {
564           unsigned long int num1, num2;
565           int n_digits1, n_digits2;
566           int root_len1, root_len2;
567           unsigned long int number;
568
569           name2 = parse_DATA_LIST_var (lexer, dict);
570           if (!name2)
571             goto exit;
572           int end_ofs = lex_ofs (lexer) - 1;
573
574           root_len1 = extract_numeric_suffix (lexer, start_ofs,
575                                               name1, &num1, &n_digits1);
576           if (root_len1 == 0)
577             goto exit;
578
579           root_len2 = extract_numeric_suffix (lexer, end_ofs,
580                                               name2, &num2, &n_digits2);
581           if (root_len2 == 0)
582             goto exit;
583
584           if (root_len1 != root_len2 || memcasecmp (name1, name2, root_len1))
585             {
586               lex_ofs_error (lexer, start_ofs, end_ofs,
587                              _("Prefixes don't match in use of TO convention."));
588               goto exit;
589             }
590           if (num1 > num2)
591             {
592               lex_ofs_error (lexer, start_ofs, end_ofs,
593                              _("Bad bounds in use of TO convention."));
594               goto exit;
595             }
596
597           for (number = num1; number <= num2; number++)
598             {
599               char *name = xasprintf ("%.*s%0*lu",
600                                       root_len1, name1,
601                                       n_digits1, number);
602               if (!add_var_name (lexer, start_ofs, end_ofs,
603                                  name, &names, &n_vars, &allocated_vars,
604                                  &set, pv_opts))
605                 {
606                   free (name);
607                   goto exit;
608                 }
609             }
610
611           free (name1);
612           name1 = NULL;
613           free (name2);
614           name2 = NULL;
615         }
616       else
617         {
618           if (!add_var_name (lexer, start_ofs, start_ofs,
619                              name1, &names, &n_vars, &allocated_vars,
620                              &set, pv_opts))
621             goto exit;
622           name1 = NULL;
623         }
624
625       lex_match (lexer, T_COMMA);
626
627       if (pv_opts & PV_SINGLE)
628         break;
629     }
630   while (lex_token (lexer) == T_ID);
631   ok = true;
632
633 exit:
634   stringi_set_destroy (&set);
635   if (ok)
636     {
637       *namesp = names;
638       *n_varsp = n_vars;
639     }
640   else
641     {
642       int i;
643       for (i = 0; i < n_vars; i++)
644         free (names[i]);
645       free (names);
646       *namesp = NULL;
647       *n_varsp = 0;
648
649       free (name1);
650       free (name2);
651     }
652   return ok;
653 }
654
655 /* Registers each of the NAMES[0...NNAMES - 1] in POOL, as well
656    as NAMES itself. */
657 static void
658 register_vars_pool (struct pool *pool, char **names, size_t nnames)
659 {
660   size_t i;
661
662   for (i = 0; i < nnames; i++)
663     pool_register (pool, free, names[i]);
664   pool_register (pool, free, names);
665 }
666
667 /* Parses a list of variable names according to the DATA LIST
668    version of the TO convention.  Same args as
669    parse_DATA_LIST_vars(), except that all allocations are taken
670    from the given POOL. */
671 bool
672 parse_DATA_LIST_vars_pool (struct lexer *lexer, const struct dictionary *dict,
673                            struct pool *pool,
674                            char ***names, size_t *nnames, int pv_opts)
675 {
676   int retval;
677
678   /* PV_APPEND is unsafe because parse_DATA_LIST_vars would free
679      the existing names on failure, but those names are
680      presumably already in the pool, which would attempt to
681      re-free it later. */
682   assert (!(pv_opts & PV_APPEND));
683
684   retval = parse_DATA_LIST_vars (lexer, dict, names, nnames, pv_opts);
685   if (retval)
686     register_vars_pool (pool, *names, *nnames);
687   return retval;
688 }
689
690 /* Parses a list of variables where some of the variables may be
691    existing and the rest are to be created.  Same args as
692    parse_DATA_LIST_vars(). */
693 bool
694 parse_mixed_vars (struct lexer *lexer, const struct dictionary *dict,
695                   char ***names, size_t *nnames, int pv_opts)
696 {
697   size_t i;
698
699   assert (names != NULL);
700   assert (nnames != NULL);
701
702   if (!(pv_opts & PV_APPEND))
703     {
704       *names = NULL;
705       *nnames = 0;
706     }
707   while (is_dict_name_token (lexer, dict) || lex_token (lexer) == T_ALL)
708     {
709       if (lex_token (lexer) == T_ALL || dict_lookup_var (dict, lex_tokcstr (lexer)) != NULL)
710         {
711           struct variable **v;
712           size_t nv;
713
714           if (!parse_variables (lexer, dict, &v, &nv, pv_opts))
715             goto fail;
716           *names = xnrealloc (*names, *nnames + nv, sizeof **names);
717           for (i = 0; i < nv; i++)
718             (*names)[*nnames + i] = xstrdup (var_get_name (v[i]));
719           free (v);
720           *nnames += nv;
721         }
722       else if (!parse_DATA_LIST_vars (lexer, dict, names, nnames, PV_APPEND | pv_opts))
723         goto fail;
724     }
725   if (*nnames == 0)
726     goto fail;
727
728   return true;
729
730 fail:
731   for (i = 0; i < *nnames; i++)
732     free ((*names)[i]);
733   free (*names);
734   *names = NULL;
735   *nnames = 0;
736   return false;
737 }
738
739 /* Parses a list of variables where some of the variables may be
740    existing and the rest are to be created.  Same args as
741    parse_mixed_vars(), except that all allocations are taken
742    from the given POOL. */
743 bool
744 parse_mixed_vars_pool (struct lexer *lexer, const struct dictionary *dict, struct pool *pool,
745                        char ***names, size_t *nnames, int pv_opts)
746 {
747   int retval;
748
749   /* PV_APPEND is unsafe because parse_mixed_vars_pool would free
750      the existing names on failure, but those names are
751      presumably already in the pool, which would attempt to
752      re-free it later. */
753   assert (!(pv_opts & PV_APPEND));
754
755   retval = parse_mixed_vars (lexer, dict, names, nnames, pv_opts);
756   if (retval)
757     register_vars_pool (pool, *names, *nnames);
758   return retval;
759 }
760 \f
761 /* Frees the N var_syntax structures in VS, as well as VS itself. */
762 void
763 var_syntax_destroy (struct var_syntax *vs, size_t n)
764 {
765   for (size_t i = 0; i < n; i++)
766     {
767       free (vs[i].first);
768       free (vs[i].last);
769     }
770   free (vs);
771 }
772
773 /* Parses syntax for variables and variable ranges from LEXER.  If successful,
774    initializes *VS to the beginning of an array of var_syntax structs and *N_VS
775    to the number of elements in the array and returns true.  On error, sets *VS
776    to NULL and *N_VS to 0 and returns false. */
777 bool
778 var_syntax_parse (struct lexer *lexer, struct var_syntax **vs, size_t *n_vs)
779 {
780   *vs = NULL;
781   *n_vs = 0;
782
783   if (lex_token (lexer) != T_ID)
784     {
785       lex_error (lexer, _("Syntax error expecting variable name."));
786       goto error;
787     }
788
789   size_t allocated_vs = 0;
790   do
791     {
792       if (allocated_vs >= *n_vs)
793         *vs = x2nrealloc (*vs, &allocated_vs, sizeof **vs);
794       struct var_syntax *new = &(*vs)[(*n_vs)++];
795       *new = (struct var_syntax) {
796         .first = ss_xstrdup (lex_tokss (lexer)),
797         .first_ofs = lex_ofs (lexer)
798       };
799       lex_get (lexer);
800
801       if (lex_match (lexer, T_TO))
802         {
803           if (lex_token (lexer) != T_ID)
804             {
805               lex_error (lexer, _("Syntax error expecting variable name."));
806               goto error;
807             }
808
809           new->last = ss_xstrdup (lex_tokss (lexer));
810           lex_get (lexer);
811         }
812       new->last_ofs = lex_ofs (lexer) - 1;
813     }
814   while (lex_token (lexer) == T_ID);
815   return true;
816
817 error:
818   var_syntax_destroy (*vs, *n_vs);
819   *vs = NULL;
820   *n_vs = 0;
821   return false;
822 }
823
824 /* Looks up the N_VS var syntax structs in VS in DICT, translating them to an
825    array of variables.  If successful, initializes *VARS to the beginning of an
826    array of pointers to variables and *N_VARS to the length of the array and
827    returns true.  On error, sets *VARS to NULL and *N_VARS to 0.
828
829    The LEXER is just used for error messages.
830
831    For the moment, only honors PV_NUMERIC in OPTS. */
832 bool
833 var_syntax_evaluate (struct lexer *lexer,
834                      const struct var_syntax *vs, size_t n_vs,
835                      const struct dictionary *dict,
836                      struct variable ***vars, size_t *n_vars, int opts)
837 {
838   assert (!(opts & ~PV_NUMERIC));
839
840   *vars = NULL;
841   *n_vars = 0;
842
843   size_t allocated_vars = 0;
844   for (size_t i = 0; i < n_vs; i++)
845     {
846       int first_ofs = vs[i].first_ofs;
847       struct variable *first = dict_lookup_var (dict, vs[i].first);
848       if (!first)
849         {
850           lex_ofs_error (lexer, first_ofs, first_ofs,
851                          _("%s is not a variable name."), vs[i].first);
852           goto error;
853         }
854
855       int last_ofs = vs[i].last_ofs;
856       struct variable *last = (vs[i].last
857                                ? dict_lookup_var (dict, vs[i].last)
858                                : first);
859       if (!last)
860         {
861           lex_ofs_error (lexer, last_ofs, last_ofs,
862                          _("%s is not a variable name."), vs[i].last);
863           goto error;
864         }
865
866       size_t first_idx = var_get_dict_index (first);
867       size_t last_idx = var_get_dict_index (last);
868       if (last_idx < first_idx)
869         {
870           lex_ofs_error (lexer, first_ofs, last_ofs,
871                          _("%s TO %s is not valid syntax since %s "
872                            "precedes %s in the dictionary."),
873                          vs[i].first, vs[i].last,
874                          vs[i].first, vs[i].last);
875           goto error;
876         }
877
878       for (size_t j = first_idx; j <= last_idx; j++)
879         {
880           struct variable *v = dict_get_var (dict, j);
881           if (opts & PV_NUMERIC && !var_is_numeric (v))
882             {
883               lex_ofs_error (lexer, first_ofs, last_ofs,
884                              _("%s is not a numeric variable."),
885                              var_get_name (v));
886               goto error;
887             }
888
889           if (*n_vars >= allocated_vars)
890             *vars = x2nrealloc (*vars, &allocated_vars, sizeof **vars);
891           (*vars)[(*n_vars)++] = v;
892         }
893     }
894
895   return true;
896
897 error:
898   free (*vars);
899   *vars = NULL;
900   *n_vars = 0;
901   return false;
902 }
903 \f
904 /* A set of variables. */
905 struct var_set
906   {
907     bool names_must_be_ids;
908     size_t (*get_n) (const struct var_set *);
909     struct variable *(*get_var) (const struct var_set *, size_t idx);
910     bool (*lookup_var_idx) (const struct var_set *, const char *, size_t *);
911     void (*destroy) (struct var_set *);
912     void *aux;
913   };
914
915 /* Returns the number of variables in VS. */
916 size_t
917 var_set_get_n (const struct var_set *vs)
918 {
919   assert (vs != NULL);
920
921   return vs->get_n (vs);
922 }
923
924 /* Return variable with index IDX in VS.
925    IDX must be less than the number of variables in VS. */
926 static struct variable *
927 var_set_get_var (const struct var_set *vs, size_t idx)
928 {
929   assert (vs != NULL);
930   assert (idx < var_set_get_n (vs));
931
932   return vs->get_var (vs, idx);
933 }
934
935 /* Returns the variable in VS named NAME, or a null pointer if VS
936    contains no variable with that name. */
937 struct variable *
938 var_set_lookup_var (const struct var_set *vs, const char *name)
939 {
940   size_t idx;
941   return (var_set_lookup_var_idx (vs, name, &idx)
942           ? var_set_get_var (vs, idx)
943           : NULL);
944 }
945
946 /* If VS contains a variable named NAME, sets *IDX to its index
947    and returns true.  Otherwise, returns false. */
948 bool
949 var_set_lookup_var_idx (const struct var_set *vs, const char *name,
950                         size_t *idx)
951 {
952   assert (vs != NULL);
953   assert (name != NULL);
954
955   return vs->lookup_var_idx (vs, name, idx);
956 }
957
958 /* Destroys VS. */
959 void
960 var_set_destroy (struct var_set *vs)
961 {
962   if (vs != NULL)
963     vs->destroy (vs);
964 }
965
966 static bool
967 var_set_get_names_must_be_ids (const struct var_set *vs)
968 {
969   return vs->names_must_be_ids;
970 }
971 \f
972 /* Returns the number of variables in VS. */
973 static size_t
974 dict_var_set_get_n (const struct var_set *vs)
975 {
976   struct dictionary *d = vs->aux;
977
978   return dict_get_n_vars (d);
979 }
980
981 /* Return variable with index IDX in VS.
982    IDX must be less than the number of variables in VS. */
983 static struct variable *
984 dict_var_set_get_var (const struct var_set *vs, size_t idx)
985 {
986   struct dictionary *d = vs->aux;
987
988   return dict_get_var (d, idx);
989 }
990
991 /* If VS contains a variable named NAME, sets *IDX to its index
992    and returns true.  Otherwise, returns false. */
993 static bool
994 dict_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
995                              size_t *idx)
996 {
997   struct dictionary *d = vs->aux;
998   struct variable *v = dict_lookup_var (d, name);
999   if (v != NULL)
1000     {
1001       *idx = var_get_dict_index (v);
1002       return true;
1003     }
1004   else
1005     return false;
1006 }
1007
1008 /* Destroys VS. */
1009 static void
1010 dict_var_set_destroy (struct var_set *vs)
1011 {
1012   free (vs);
1013 }
1014
1015 /* Returns a variable set based on D. */
1016 struct var_set *
1017 var_set_create_from_dict (const struct dictionary *d)
1018 {
1019   struct var_set *vs = xmalloc (sizeof *vs);
1020   vs->names_must_be_ids = dict_get_names_must_be_ids (d);
1021   vs->get_n = dict_var_set_get_n;
1022   vs->get_var = dict_var_set_get_var;
1023   vs->lookup_var_idx = dict_var_set_lookup_var_idx;
1024   vs->destroy = dict_var_set_destroy;
1025   vs->aux = (void *) d;
1026   return vs;
1027 }
1028 \f
1029 /* A variable set based on an array. */
1030 struct array_var_set
1031   {
1032     struct variable *const *var;/* Array of variables. */
1033     size_t n_vars;              /* Number of elements in var. */
1034     struct hmapx vars_by_name;  /* Variables hashed by name. */
1035   };
1036
1037 /* Returns the number of variables in VS. */
1038 static size_t
1039 array_var_set_get_n (const struct var_set *vs)
1040 {
1041   struct array_var_set *avs = vs->aux;
1042
1043   return avs->n_vars;
1044 }
1045
1046 /* Return variable with index IDX in VS.
1047    IDX must be less than the number of variables in VS. */
1048 static struct variable *
1049 array_var_set_get_var (const struct var_set *vs, size_t idx)
1050 {
1051   struct array_var_set *avs = vs->aux;
1052
1053   return CONST_CAST (struct variable *, avs->var[idx]);
1054 }
1055
1056 /* If VS contains a variable named NAME, sets *IDX to its index
1057    and returns true.  Otherwise, returns false. */
1058 static bool
1059 array_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
1060                               size_t *idx)
1061 {
1062   struct array_var_set *avs = vs->aux;
1063   struct hmapx_node *node;
1064   struct variable **varp;
1065
1066   HMAPX_FOR_EACH_WITH_HASH (varp, node, utf8_hash_case_string (name, 0),
1067                             &avs->vars_by_name)
1068     if (!utf8_strcasecmp (name, var_get_name (*varp)))
1069       {
1070         *idx = varp - avs->var;
1071         return true;
1072       }
1073
1074   return false;
1075 }
1076
1077 /* Destroys VS. */
1078 static void
1079 array_var_set_destroy (struct var_set *vs)
1080 {
1081   struct array_var_set *avs = vs->aux;
1082
1083   hmapx_destroy (&avs->vars_by_name);
1084   free (avs);
1085   free (vs);
1086 }
1087
1088 /* Returns a variable set based on the N_VARS variables in VAR. */
1089 struct var_set *
1090 var_set_create_from_array (struct variable *const *var, size_t n_vars)
1091 {
1092   struct var_set *vs;
1093   struct array_var_set *avs;
1094   size_t i;
1095
1096   vs = xmalloc (sizeof *vs);
1097   vs->names_must_be_ids = true;
1098   vs->get_n = array_var_set_get_n;
1099   vs->get_var = array_var_set_get_var;
1100   vs->lookup_var_idx = array_var_set_lookup_var_idx;
1101   vs->destroy = array_var_set_destroy;
1102   vs->aux = avs = xmalloc (sizeof *avs);
1103   avs->var = var;
1104   avs->n_vars = n_vars;
1105   hmapx_init (&avs->vars_by_name);
1106   for (i = 0; i < n_vars; i++)
1107     {
1108       const char *name = var_get_name (var[i]);
1109       size_t idx;
1110
1111       if (array_var_set_lookup_var_idx (vs, name, &idx))
1112         {
1113           var_set_destroy (vs);
1114           return NULL;
1115         }
1116       hmapx_insert (&avs->vars_by_name, CONST_CAST (void *, &avs->var[i]),
1117                     utf8_hash_case_string (name, 0));
1118     }
1119
1120   return vs;
1121 }
1122
1123
1124 /* Match a variable.
1125    If the match succeeds, the variable will be placed in VAR.
1126    Returns true if successful */
1127 bool
1128 lex_match_variable (struct lexer *lexer, const struct dictionary *dict, const struct variable **var)
1129 {
1130   if (lex_token (lexer) != T_ID)
1131     return false;
1132
1133   *var = parse_variable_const (lexer, dict);
1134   return *var != NULL;
1135 }