Remove "Written by Ben Pfaff <blp@gnu.org>" lines everywhere.
[pspp-builds.git] / src / language / lexer / variable-parser.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 #include <config.h>
20
21 #include <language/lexer/variable-parser.h>
22
23 #include <ctype.h>
24 #include <stdbool.h>
25 #include <stdlib.h>
26
27 #include "lexer.h"
28 #include <data/dictionary.h>
29 #include <data/procedure.h>
30 #include <data/variable.h>
31 #include <libpspp/alloc.h>
32 #include <libpspp/assertion.h>
33 #include <libpspp/bit-vector.h>
34 #include <libpspp/hash.h>
35 #include <libpspp/message.h>
36 #include <libpspp/misc.h>
37 #include <libpspp/pool.h>
38 #include <libpspp/str.h>
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 /* Parses a name as a variable within VS.  Sets *IDX to the
44    variable's index and returns true if successful.  On failure
45    emits an error message and returns false. */
46 static bool
47 parse_vs_variable_idx (struct lexer *lexer, const struct var_set *vs, 
48                 size_t *idx)
49 {
50   assert (idx != NULL);
51   
52   if (lex_token (lexer) != T_ID)
53     {
54       lex_error (lexer, _("expecting variable name"));
55       return false;
56     }
57   else if (var_set_lookup_var_idx (vs, lex_tokid (lexer), idx)) 
58     {
59       lex_get (lexer);
60       return true;
61     }
62   else 
63     {
64       msg (SE, _("%s is not a variable name."), lex_tokid (lexer));
65       return false;
66     }
67 }
68
69 /* Parses a name as a variable within VS and returns the variable
70    if successful.  On failure emits an error message and returns
71    a null pointer. */
72 static struct variable *
73 parse_vs_variable (struct lexer *lexer, const struct var_set *vs)
74 {
75   size_t idx;
76   return parse_vs_variable_idx (lexer, vs, &idx) ? var_set_get_var (vs, idx) : NULL;
77 }
78
79 /* Parses a variable name in dictionary D and returns the
80    variable if successful.  On failure emits an error message and
81    returns a null pointer. */
82 struct variable *
83 parse_variable (struct lexer *lexer, const struct dictionary *d) 
84 {
85   struct var_set *vs = var_set_create_from_dict (d);
86   struct variable *var = parse_vs_variable (lexer, vs);
87   var_set_destroy (vs);
88   return var;
89 }
90
91 /* Parses a set of variables from dictionary D given options
92    OPTS.  Resulting list of variables stored in *VAR and the
93    number of variables into *CNT.  Returns true only if
94    successful. */
95 bool
96 parse_variables (struct lexer *lexer, const struct dictionary *d, 
97                         struct variable ***var,
98                         size_t *cnt, int opts) 
99 {
100   struct var_set *vs;
101   int success;
102
103   assert (d != NULL);
104   assert (var != NULL);
105   assert (cnt != NULL);
106
107   vs = var_set_create_from_dict (d);
108   success = parse_var_set_vars (lexer, vs, var, cnt, opts);
109   if ( success == 0 )
110      free ( *var ) ;
111   var_set_destroy (vs);
112   return success;
113 }
114
115 /* Parses a set of variables from dictionary D given options
116    OPTS.  Resulting list of variables stored in *VARS and the
117    number of variables into *VAR_CNT.  Returns true only if
118    successful.  Same behavior as parse_variables, except that all
119    allocations are taken from the given POOL. */
120 bool
121 parse_variables_pool (struct lexer *lexer, struct pool *pool, 
122                 const struct dictionary *dict,
123                 struct variable ***vars, size_t *var_cnt, int opts) 
124 {
125   int retval;
126
127   /* PV_APPEND is unsafe because parse_variables would free the
128      existing names on failure, but those names are presumably
129      already in the pool, which would attempt to re-free it
130      later. */
131   assert (!(opts & PV_APPEND));
132   
133   retval = parse_variables (lexer, dict, vars, var_cnt, opts);
134   if (retval)
135     pool_register (pool, free, *vars);
136   return retval;
137 }
138
139 /* Parses a variable name from VS.  If successful, sets *IDX to
140    the variable's index in VS, *CLASS to the variable's
141    dictionary class, and returns true.  Returns false on
142    failure. */
143 static bool
144 parse_var_idx_class (struct lexer *lexer, const struct var_set *vs, 
145                         size_t *idx,
146                         enum dict_class *class)
147 {
148   if (!parse_vs_variable_idx (lexer, vs, idx))
149     return false;
150
151   *class = dict_class_from_id (var_get_name (var_set_get_var (vs, *idx)));
152   return true;
153 }
154
155 /* Add the variable from VS with index IDX to the list of
156    variables V that has *NV elements and room for *MV.
157    Uses and updates INCLUDED to avoid duplicates if indicated by
158    PV_OPTS, which also affects what variables are allowed in
159    appropriate ways. */
160 static void
161 add_variable (struct variable ***v, size_t *nv, size_t *mv,
162               char *included, int pv_opts,
163               const struct var_set *vs, size_t idx)
164 {
165   struct variable *add = var_set_get_var (vs, idx);
166   const char *add_name = var_get_name (add);
167
168   if ((pv_opts & PV_NUMERIC) && !var_is_numeric (add)) 
169     msg (SW, _("%s is not a numeric variable.  It will not be "
170                "included in the variable list."), add_name);
171   else if ((pv_opts & PV_STRING) && !var_is_alpha (add)) 
172     msg (SE, _("%s is not a string variable.  It will not be "
173                "included in the variable list."), add_name);
174   else if ((pv_opts & PV_NO_SCRATCH)
175            && dict_class_from_id (add_name) == DC_SCRATCH)
176     msg (SE, _("Scratch variables (such as %s) are not allowed "
177                "here."), add_name);
178   else if ((pv_opts & (PV_SAME_TYPE | PV_SAME_WIDTH)) && *nv
179            && var_get_type (add) != var_get_type ((*v)[0])) 
180     msg (SE, _("%s and %s are not the same type.  All variables in "
181                "this variable list must be of the same type.  %s "
182                "will be omitted from the list."),
183          var_get_name ((*v)[0]), add_name, add_name);
184   else if ((pv_opts & PV_SAME_WIDTH) && *nv
185            && var_get_width (add) != var_get_width ((*v)[0]))
186     msg (SE, _("%s and %s are string variables with different widths.  "
187                "All variables in this variable list must have the "
188                "same width.  %s will be omttied from the list."),
189          var_get_name ((*v)[0]), add_name, add_name);
190   else if ((pv_opts & PV_NO_DUPLICATE) && included[idx]) 
191     msg (SE, _("Variable %s appears twice in variable list."), add_name);
192   else if ((pv_opts & PV_DUPLICATE) || !included[idx])
193     {
194       if (*nv >= *mv)
195         {
196           *mv = 2 * (*nv + 1);
197           *v = xnrealloc (*v, *mv, sizeof **v);
198         }
199       (*v)[(*nv)++] = add;
200       if (included != NULL)
201         included[idx] = 1;
202     }
203 }
204
205 /* Adds the variables in VS with indexes FIRST_IDX through
206    LAST_IDX, inclusive, to the list of variables V that has *NV
207    elements and room for *MV.  Uses and updates INCLUDED to avoid
208    duplicates if indicated by PV_OPTS, which also affects what
209    variables are allowed in appropriate ways. */
210 static void
211 add_variables (struct variable ***v, size_t *nv, size_t *mv, char *included,
212                int pv_opts,
213                const struct var_set *vs, int first_idx, int last_idx,
214                enum dict_class class) 
215 {
216   size_t i;
217   
218   for (i = first_idx; i <= last_idx; i++)
219     if (dict_class_from_id (var_get_name (var_set_get_var (vs, i))) == class)
220       add_variable (v, nv, mv, included, pv_opts, vs, i);
221 }
222
223 /* Note that if parse_variables() returns false, *v is free()'d.
224    Conversely, if parse_variables() returns true, then *nv is
225    nonzero and *v is non-NULL. */
226 bool
227 parse_var_set_vars (struct lexer *lexer, const struct var_set *vs, 
228                     struct variable ***v, size_t *nv,
229                     int pv_opts)
230 {
231   size_t mv;
232   char *included;
233
234   assert (vs != NULL);
235   assert (v != NULL);
236   assert (nv != NULL);
237
238   /* At most one of PV_NUMERIC, PV_STRING, PV_SAME_TYPE,
239      PV_SAME_WIDTH may be specified. */
240   assert (((pv_opts & PV_NUMERIC) != 0)
241           + ((pv_opts & PV_STRING) != 0)
242           + ((pv_opts & PV_SAME_TYPE) != 0)
243           + ((pv_opts & PV_SAME_WIDTH) != 0) <= 1);
244
245   /* PV_DUPLICATE and PV_NO_DUPLICATE are incompatible. */
246   assert (!(pv_opts & PV_DUPLICATE) || !(pv_opts & PV_NO_DUPLICATE));
247
248   if (!(pv_opts & PV_APPEND))
249     {
250       *v = NULL;
251       *nv = 0;
252       mv = 0;
253     }
254   else
255     mv = *nv;
256
257   if (!(pv_opts & PV_DUPLICATE))
258     {
259       size_t i;
260       
261       included = xcalloc (var_set_get_cnt (vs), sizeof *included);
262       for (i = 0; i < *nv; i++) 
263         {
264           size_t index;
265           if (!var_set_lookup_var_idx (vs, var_get_name ((*v)[i]), &index))
266             NOT_REACHED ();
267           included[index] = 1; 
268         }
269     }
270   else
271     included = NULL;
272
273   do
274     {
275       if (lex_match (lexer, T_ALL))
276         add_variables (v, nv, &mv, included, pv_opts,
277                        vs, 0, var_set_get_cnt (vs) - 1, DC_ORDINARY);
278       else 
279         {
280           enum dict_class class;
281           size_t first_idx;
282
283           if (!parse_var_idx_class (lexer, vs, &first_idx, &class))
284             goto fail;
285
286           if (!lex_match (lexer, T_TO))
287             add_variable (v, nv, &mv, included, pv_opts, vs, first_idx);
288           else 
289             {
290               size_t last_idx;
291               enum dict_class last_class;
292               struct variable *first_var, *last_var;
293
294               if (!parse_var_idx_class (lexer, vs, &last_idx, &last_class))
295                 goto fail;
296
297               first_var = var_set_get_var (vs, first_idx);
298               last_var = var_set_get_var (vs, last_idx);
299
300               if (last_idx < first_idx)
301                 {
302                   const char *first_name = var_get_name (first_var);
303                   const char *last_name = var_get_name (last_var);
304                   msg (SE, _("%s TO %s is not valid syntax since %s "
305                              "precedes %s in the dictionary."),
306                        first_name, last_name, first_name, last_name);
307                   goto fail;
308                 }
309
310               if (class != last_class)
311                 {
312                   msg (SE, _("When using the TO keyword to specify several "
313                              "variables, both variables must be from "
314                              "the same variable dictionaries, of either "
315                              "ordinary, scratch, or system variables.  "
316                              "%s is a %s variable, whereas %s is %s."),
317                        var_get_name (first_var), dict_class_to_name (class),
318                        var_get_name (last_var),
319                        dict_class_to_name (last_class));
320                   goto fail;
321                 }
322
323               add_variables (v, nv, &mv, included, pv_opts,
324                              vs, first_idx, last_idx, class);
325             } 
326         }
327
328       if (pv_opts & PV_SINGLE)
329         break;
330       lex_match (lexer, ',');
331     }
332   while (lex_token (lexer) == T_ALL
333          || (lex_token (lexer) == T_ID && var_set_lookup_var (vs, lex_tokid (lexer)) != NULL));
334   
335   if (*nv == 0)
336     goto fail;
337
338   free (included);
339   return 1;
340
341 fail:
342   free (included);
343   free (*v);
344   *v = NULL;
345   *nv = 0;
346   return 0;
347 }
348
349 /* Extracts a numeric suffix from variable name S, copying it
350    into string R.  Sets *D to the length of R and *N to its
351    value. */
352 static int
353 extract_num (char *s, char *r, int *n, int *d)
354 {
355   char *cp;
356
357   /* Find first digit. */
358   cp = s + strlen (s) - 1;
359   while (isdigit ((unsigned char) *cp) && cp > s)
360     cp--;
361   cp++;
362
363   /* Extract root. */
364   strncpy (r, s, cp - s);
365   r[cp - s] = 0;
366
367   /* Count initial zeros. */
368   *n = *d = 0;
369   while (*cp == '0')
370     {
371       (*d)++;
372       cp++;
373     }
374
375   /* Extract value. */
376   while (isdigit ((unsigned char) *cp))
377     {
378       (*d)++;
379       *n = (*n * 10) + (*cp - '0');
380       cp++;
381     }
382
383   /* Sanity check. */
384   if (*n == 0 && *d == 0)
385     {
386       msg (SE, _("incorrect use of TO convention"));
387       return 0;
388     }
389   return 1;
390 }
391
392 /* Parses a list of variable names according to the DATA LIST version
393    of the TO convention.  */
394 bool
395 parse_DATA_LIST_vars (struct lexer *lexer, char ***names, size_t *nnames, int pv_opts)
396 {
397   int n1, n2;
398   int d1, d2;
399   int n;
400   size_t nvar, mvar;
401   char name1[LONG_NAME_LEN + 1], name2[LONG_NAME_LEN + 1];
402   char root1[LONG_NAME_LEN + 1], root2[LONG_NAME_LEN + 1];
403   int success = 0;
404
405   assert (names != NULL);
406   assert (nnames != NULL);
407   assert ((pv_opts & ~(PV_APPEND | PV_SINGLE
408                        | PV_NO_SCRATCH | PV_NO_DUPLICATE)) == 0);
409   /* FIXME: PV_NO_DUPLICATE is not implemented. */
410
411   if (pv_opts & PV_APPEND)
412     nvar = mvar = *nnames;
413   else
414     {
415       nvar = mvar = 0;
416       *names = NULL;
417     }
418
419   do
420     {
421       if (lex_token (lexer) != T_ID)
422         {
423           lex_error (lexer, "expecting variable name");
424           goto fail;
425         }
426       if (dict_class_from_id (lex_tokid (lexer)) == DC_SCRATCH
427           && (pv_opts & PV_NO_SCRATCH))
428         {
429           msg (SE, _("Scratch variables not allowed here."));
430           goto fail;
431         }
432       strcpy (name1, lex_tokid (lexer));
433       lex_get (lexer);
434       if (lex_token (lexer) == T_TO)
435         {
436           lex_get (lexer);
437           if (lex_token (lexer) != T_ID)
438             {
439               lex_error (lexer, "expecting variable name");
440               goto fail;
441             }
442           strcpy (name2, lex_tokid (lexer));
443           lex_get (lexer);
444
445           if (!extract_num (name1, root1, &n1, &d1)
446               || !extract_num (name2, root2, &n2, &d2))
447             goto fail;
448
449           if (strcasecmp (root1, root2))
450             {
451               msg (SE, _("Prefixes don't match in use of TO convention."));
452               goto fail;
453             }
454           if (n1 > n2)
455             {
456               msg (SE, _("Bad bounds in use of TO convention."));
457               goto fail;
458             }
459           if (d2 > d1)
460             d2 = d1;
461
462           if (mvar < nvar + (n2 - n1 + 1))
463             {
464               mvar += ROUND_UP (n2 - n1 + 1, 16);
465               *names = xnrealloc (*names, mvar, sizeof **names);
466             }
467
468           for (n = n1; n <= n2; n++)
469             {
470               char name[LONG_NAME_LEN + 1];
471               sprintf (name, "%s%0*d", root1, d1, n);
472               (*names)[nvar] = xstrdup (name);
473               nvar++;
474             }
475         }
476       else
477         {
478           if (nvar >= mvar)
479             {
480               mvar += 16;
481               *names = xnrealloc (*names, mvar, sizeof **names);
482             }
483           (*names)[nvar++] = xstrdup (name1);
484         }
485
486       lex_match (lexer, ',');
487
488       if (pv_opts & PV_SINGLE)
489         break;
490     }
491   while (lex_token (lexer) == T_ID);
492   success = 1;
493
494 fail:
495   *nnames = nvar;
496   if (!success)
497     {
498       int i;
499       for (i = 0; i < nvar; i++)
500         free ((*names)[i]);
501       free (*names);
502       *names = NULL;
503       *nnames = 0;
504     }
505   return success;
506 }
507
508 /* Registers each of the NAMES[0...NNAMES - 1] in POOL, as well
509    as NAMES itself. */
510 static void
511 register_vars_pool (struct pool *pool, char **names, size_t nnames)
512 {
513   size_t i;
514
515   for (i = 0; i < nnames; i++)
516     pool_register (pool, free, names[i]);
517   pool_register (pool, free, names);
518 }
519
520 /* Parses a list of variable names according to the DATA LIST
521    version of the TO convention.  Same args as
522    parse_DATA_LIST_vars(), except that all allocations are taken
523    from the given POOL. */
524 bool
525 parse_DATA_LIST_vars_pool (struct lexer *lexer, struct pool *pool,
526                            char ***names, size_t *nnames, int pv_opts)
527 {
528   int retval;
529
530   /* PV_APPEND is unsafe because parse_DATA_LIST_vars would free
531      the existing names on failure, but those names are
532      presumably already in the pool, which would attempt to
533      re-free it later. */
534   assert (!(pv_opts & PV_APPEND));
535   
536   retval = parse_DATA_LIST_vars (lexer, names, nnames, pv_opts);
537   if (retval)
538     register_vars_pool (pool, *names, *nnames);
539   return retval;
540 }
541
542 /* Parses a list of variables where some of the variables may be
543    existing and the rest are to be created.  Same args as
544    parse_DATA_LIST_vars(). */
545 bool
546 parse_mixed_vars (struct lexer *lexer, const struct dictionary *dict, 
547                   char ***names, size_t *nnames, int pv_opts)
548 {
549   size_t i;
550
551   assert (names != NULL);
552   assert (nnames != NULL);
553   assert ((pv_opts & ~PV_APPEND) == 0);
554
555   if (!(pv_opts & PV_APPEND))
556     {
557       *names = NULL;
558       *nnames = 0;
559     }
560   while (lex_token (lexer) == T_ID || lex_token (lexer) == T_ALL)
561     {
562       if (lex_token (lexer) == T_ALL || dict_lookup_var (dict, lex_tokid (lexer)) != NULL)
563         {
564           struct variable **v;
565           size_t nv;
566
567           if (!parse_variables (lexer, dict, &v, &nv, PV_NONE))
568             goto fail;
569           *names = xnrealloc (*names, *nnames + nv, sizeof **names);
570           for (i = 0; i < nv; i++)
571             (*names)[*nnames + i] = xstrdup (var_get_name (v[i]));
572           free (v);
573           *nnames += nv;
574         }
575       else if (!parse_DATA_LIST_vars (lexer, names, nnames, PV_APPEND))
576         goto fail;
577     }
578   return 1;
579
580 fail:
581   for (i = 0; i < *nnames; i++)
582     free ((*names)[i]);
583   free (*names);
584   *names = NULL;
585   *nnames = 0;
586   return 0;
587 }
588
589 /* Parses a list of variables where some of the variables may be
590    existing and the rest are to be created.  Same args as
591    parse_mixed_vars(), except that all allocations are taken
592    from the given POOL. */
593 bool
594 parse_mixed_vars_pool (struct lexer *lexer, const struct dictionary *dict, struct pool *pool,
595                        char ***names, size_t *nnames, int pv_opts)
596 {
597   int retval;
598
599   /* PV_APPEND is unsafe because parse_mixed_vars_pool would free
600      the existing names on failure, but those names are
601      presumably already in the pool, which would attempt to
602      re-free it later. */
603   assert (!(pv_opts & PV_APPEND));
604
605   retval = parse_mixed_vars (lexer, dict, names, nnames, pv_opts);
606   if (retval)
607     register_vars_pool (pool, *names, *nnames);
608   return retval;
609 }
610 \f
611 /* A set of variables. */
612 struct var_set 
613   {
614     size_t (*get_cnt) (const struct var_set *);
615     struct variable *(*get_var) (const struct var_set *, size_t idx);
616     bool (*lookup_var_idx) (const struct var_set *, const char *, size_t *);
617     void (*destroy) (struct var_set *);
618     void *aux;
619   };
620
621 /* Returns the number of variables in VS. */
622 size_t
623 var_set_get_cnt (const struct var_set *vs) 
624 {
625   assert (vs != NULL);
626
627   return vs->get_cnt (vs);
628 }
629
630 /* Return variable with index IDX in VS.
631    IDX must be less than the number of variables in VS. */
632 struct variable *
633 var_set_get_var (const struct var_set *vs, size_t idx) 
634 {
635   assert (vs != NULL);
636   assert (idx < var_set_get_cnt (vs));
637
638   return vs->get_var (vs, idx);
639 }
640
641 /* Returns the variable in VS named NAME, or a null pointer if VS
642    contains no variable with that name. */
643 struct variable *
644 var_set_lookup_var (const struct var_set *vs, const char *name) 
645 {
646   size_t idx;
647   return (var_set_lookup_var_idx (vs, name, &idx)
648           ? var_set_get_var (vs, idx)
649           : NULL);
650 }
651
652 /* If VS contains a variable named NAME, sets *IDX to its index
653    and returns true.  Otherwise, returns false. */
654 bool
655 var_set_lookup_var_idx (const struct var_set *vs, const char *name,
656                         size_t *idx)
657 {
658   assert (vs != NULL);
659   assert (name != NULL);
660   assert (strlen (name) <= LONG_NAME_LEN);
661
662   return vs->lookup_var_idx (vs, name, idx);
663 }
664
665 /* Destroys VS. */
666 void
667 var_set_destroy (struct var_set *vs) 
668 {
669   if (vs != NULL)
670     vs->destroy (vs);
671 }
672 \f
673 /* Returns the number of variables in VS. */
674 static size_t
675 dict_var_set_get_cnt (const struct var_set *vs) 
676 {
677   struct dictionary *d = vs->aux;
678
679   return dict_get_var_cnt (d);
680 }
681
682 /* Return variable with index IDX in VS.
683    IDX must be less than the number of variables in VS. */
684 static struct variable *
685 dict_var_set_get_var (const struct var_set *vs, size_t idx) 
686 {
687   struct dictionary *d = vs->aux;
688
689   return dict_get_var (d, idx);
690 }
691
692 /* If VS contains a variable named NAME, sets *IDX to its index
693    and returns true.  Otherwise, returns false. */
694 static bool
695 dict_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
696                              size_t *idx) 
697 {
698   struct dictionary *d = vs->aux;
699   struct variable *v = dict_lookup_var (d, name);
700   if (v != NULL) 
701     {
702       *idx = var_get_dict_index (v);
703       return true;
704     }
705   else
706     return false;
707 }
708
709 /* Destroys VS. */
710 static void
711 dict_var_set_destroy (struct var_set *vs) 
712 {
713   free (vs);
714 }
715
716 /* Returns a variable set based on D. */
717 struct var_set *
718 var_set_create_from_dict (const struct dictionary *d) 
719 {
720   struct var_set *vs = xmalloc (sizeof *vs);
721   vs->get_cnt = dict_var_set_get_cnt;
722   vs->get_var = dict_var_set_get_var;
723   vs->lookup_var_idx = dict_var_set_lookup_var_idx;
724   vs->destroy = dict_var_set_destroy;
725   vs->aux = (void *) d;
726   return vs;
727 }
728 \f
729 /* A variable set based on an array. */
730 struct array_var_set 
731   {
732     struct variable *const *var;/* Array of variables. */
733     size_t var_cnt;             /* Number of elements in var. */
734     struct hsh_table *name_tab; /* Hash from variable names to variables. */
735   };
736
737 /* Returns the number of variables in VS. */
738 static size_t
739 array_var_set_get_cnt (const struct var_set *vs) 
740 {
741   struct array_var_set *avs = vs->aux;
742
743   return avs->var_cnt;
744 }
745
746 /* Return variable with index IDX in VS.
747    IDX must be less than the number of variables in VS. */
748 static struct variable *
749 array_var_set_get_var (const struct var_set *vs, size_t idx) 
750 {
751   struct array_var_set *avs = vs->aux;
752
753   return (struct variable *) avs->var[idx];
754 }
755
756 /* If VS contains a variable named NAME, sets *IDX to its index
757    and returns true.  Otherwise, returns false. */
758 static bool
759 array_var_set_lookup_var_idx (const struct var_set *vs, const char *name,
760                               size_t *idx) 
761 {
762   struct array_var_set *avs = vs->aux;
763   struct variable *v, *const *vpp;
764
765   v = var_create (name, 0);
766   vpp = hsh_find (avs->name_tab, &v);
767   var_destroy (v);
768   
769   if (vpp != NULL) 
770     {
771       *idx = vpp - avs->var;
772       return true;
773     }
774   else
775     return false;
776 }
777
778 /* Destroys VS. */
779 static void
780 array_var_set_destroy (struct var_set *vs) 
781 {
782   struct array_var_set *avs = vs->aux;
783
784   hsh_destroy (avs->name_tab);
785   free (avs);
786   free (vs);
787 }
788
789 /* Returns a variable set based on the VAR_CNT variables in
790    VAR. */
791 struct var_set *
792 var_set_create_from_array (struct variable *const *var, size_t var_cnt) 
793 {
794   struct var_set *vs;
795   struct array_var_set *avs;
796   size_t i;
797
798   vs = xmalloc (sizeof *vs);
799   vs->get_cnt = array_var_set_get_cnt;
800   vs->get_var = array_var_set_get_var;
801   vs->lookup_var_idx = array_var_set_lookup_var_idx;
802   vs->destroy = array_var_set_destroy;
803   vs->aux = avs = xmalloc (sizeof *avs);
804   avs->var = var;
805   avs->var_cnt = var_cnt;
806   avs->name_tab = hsh_create (2 * var_cnt,
807                               compare_var_ptrs_by_name, hash_var_ptr_by_name,
808                               NULL, NULL);
809   for (i = 0; i < var_cnt; i++)
810     if (hsh_insert (avs->name_tab, (void *) &var[i]) != NULL) 
811       {
812         var_set_destroy (vs);
813         return NULL;
814       }
815   
816   return vs;
817 }