More memory leaks fixed.
[pspp] / src / vars-prs.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 #include <config.h>
21 #include "var.h"
22 #include <ctype.h>
23 #include <stdlib.h>
24 #include "alloc.h"
25 #include "bitvector.h"
26 #include "dictionary.h"
27 #include "error.h"
28 #include "hash.h"
29 #include "lexer.h"
30 #include "misc.h"
31 #include "str.h"
32
33 /* Parses a name as a variable within VS and returns the variable
34    if successful.  On failure emits an error message and returns
35    a null pointer. */
36 static struct variable *
37 parse_vs_variable (const struct var_set *vs)
38 {
39   struct variable *vp;
40
41   if (token != T_ID)
42     {
43       lex_error ("expecting variable name");
44       return NULL;
45     }
46
47   vp = var_set_lookup_var (vs, tokid);
48   if (vp == NULL)
49     msg (SE, _("%s is not a variable name."), tokid);
50   lex_get ();
51
52   return vp;
53 }
54
55 /* Parses a variable name in dictionary D and returns the
56    variable if successful.  On failure emits an error message and
57    returns a null pointer. */
58 struct variable *
59 parse_dict_variable (const struct dictionary *d) 
60 {
61   struct var_set *vs = var_set_create_from_dict (d);
62   struct variable *var = parse_vs_variable (vs);
63   var_set_destroy (vs);
64   return var;
65 }
66
67 /* Parses a variable name in default_dict and returns the
68    variable if successful.  On failure emits an error message and
69    returns a null pointer. */
70 struct variable *
71 parse_variable (void)
72 {
73   return parse_dict_variable (default_dict);
74 }
75
76 /* Returns the dictionary class corresponding to a variable named
77    NAME. */
78 enum dict_class
79 dict_class_from_id (const char *name) 
80 {
81   assert (name != NULL);
82
83   switch (name[0]) 
84     {
85     default:
86       return DC_ORDINARY;
87     case '$':
88       return DC_SYSTEM;
89     case '#':
90       return DC_SCRATCH;
91     }
92 }
93
94 /* Returns the name of dictionary class DICT_CLASS. */
95 const char *
96 dict_class_to_name (enum dict_class dict_class) 
97 {
98   switch (dict_class) 
99     {
100     case DC_ORDINARY:
101       return _("ordinary");
102     case DC_SYSTEM:
103       return _("system");
104     case DC_SCRATCH:
105       return _("scratch");
106     default:
107       assert (0);
108       abort ();
109     }
110 }
111
112 /* Parses a set of variables from dictionary D given options
113    OPTS.  Resulting list of variables stored in *VAR and the
114    number of variables into *CNT.  Returns nonzero only if
115    successful. */
116 int
117 parse_variables (const struct dictionary *d, struct variable ***var,
118                  int *cnt, int opts) 
119 {
120   struct var_set *vs;
121   int success;
122
123   assert (d != NULL);
124   assert (var != NULL);
125   assert (cnt != NULL);
126
127   vs = var_set_create_from_dict (d);
128   success = parse_var_set_vars (vs, var, cnt, opts);
129   if ( success == 0 )
130      free ( *var ) ;
131   var_set_destroy (vs);
132   return success;
133 }
134
135 /* Note that if parse_variables() returns 0, *v is free()'d.
136    Conversely, if parse_variables() returns non-zero, then *nv is
137    nonzero and *v is non-NULL. */
138 int
139 parse_var_set_vars (const struct var_set *vs, 
140                     struct variable ***v, int *nv,
141                     int pv_opts)
142 {
143   size_t vs_var_cnt;
144   int i;
145   char *included = NULL;
146
147   struct variable *v1, *v2;
148   int count, mv;
149   enum dict_class dict_class;
150
151   assert (vs != NULL);
152   assert (v != NULL);
153   assert (nv != NULL);
154
155   /* At most one of PV_NUMERIC, PV_STRING, PV_SAME_TYPE may be
156      specified. */
157   assert ((((pv_opts & PV_NUMERIC) != 0)
158            + ((pv_opts & PV_STRING) != 0)
159            + ((pv_opts & PV_SAME_TYPE) != 0)) <= 1);
160
161   /* PV_DUPLICATE and PV_NO_DUPLICATE are incompatible. */
162   assert (!(pv_opts & PV_DUPLICATE) || !(pv_opts & PV_NO_DUPLICATE));
163
164   vs_var_cnt = var_set_get_cnt (vs);
165
166   if (!(pv_opts & PV_APPEND))
167     {
168       *v = NULL;
169       *nv = 0;
170       mv = 0;
171     }
172   else
173     mv = *nv;
174
175   if (!(pv_opts & PV_DUPLICATE))
176     {
177       included = xmalloc (vs_var_cnt);
178       memset (included, 0, vs_var_cnt);
179       for (i = 0; i < *nv; i++)
180         included[(*v)[i]->index] = 1;
181     }
182
183   do
184     {
185       if (lex_match (T_ALL))
186         {
187           v1 = var_set_get_var (vs, 0);
188           v2 = var_set_get_var (vs, vs_var_cnt - 1);
189           count = vs_var_cnt;
190           dict_class = DC_ORDINARY;
191         }
192       else
193         {
194           v1 = parse_vs_variable (vs);
195           if (!v1)
196             goto fail;
197
198           if (lex_match (T_TO))
199             {
200               enum dict_class dict_class_2;
201
202               v2 = parse_vs_variable (vs);
203               if (!v2)
204                 {
205                   lex_error ("expecting variable name");
206                   goto fail;
207                 }
208
209               count = v2->index - v1->index + 1;
210               if (count < 1)
211                 {
212                   msg (SE, _("%s TO %s is not valid syntax since %s "
213                        "precedes %s in the dictionary."),
214                        v1->name, v2->name, v2->name, v1->name);
215                   goto fail;
216                 }
217
218               dict_class = dict_class_from_id (v1->name);
219               dict_class_2 = dict_class_from_id (v2->name);
220               if (dict_class != dict_class_2)
221                 {
222                   msg (SE, _("When using the TO keyword to specify several "
223                              "variables, both variables must be from "
224                              "the same variable dictionaries, of either "
225                              "ordinary, scratch, or system variables.  "
226                              "%s is a %s variable, whereas %s is %s."),
227                        v1->name, dict_class_to_name (dict_class),
228                        v2->name, dict_class_to_name (dict_class_2));
229                   goto fail;
230                 }
231             }
232           else
233             {
234               v2 = v1;
235               count = 1;
236               dict_class = dict_class_from_id (v1->name);
237             }
238           if (dict_class == DC_SCRATCH && (pv_opts & PV_NO_SCRATCH))
239             {
240               msg (SE, _("Scratch variables (such as %s) are not allowed "
241                          "here."), v1->name);
242               goto fail;
243             }
244         }
245
246       if (*nv + count > mv)
247         {
248           mv += ROUND_UP (count, 16);
249           *v = xrealloc (*v, mv * sizeof **v);
250         }
251
252       /* Add v1...v2 to the list. */
253       for (i = v1->index; i <= v2->index; i++)
254         {
255           struct variable *add = var_set_get_var (vs, i);
256
257           /* Skip over other dictionaries. */
258           if (dict_class != dict_class_from_id (add->name))
259             continue;
260
261           /* Different kinds of errors. */
262           if ((pv_opts & PV_NUMERIC) && add->type != NUMERIC)
263             msg (SW, _("%s is not a numeric variable.  It will not be "
264                        "included in the variable list."), add->name);
265           else if ((pv_opts & PV_STRING) && add->type != ALPHA)
266             msg (SE, _("%s is not a string variable.  It will not be "
267                        "included in the variable list."), add->name);
268           else if ((pv_opts & PV_SAME_TYPE) && *nv
269                    && add->type != (*v)[0]->type)
270             msg (SE, _("%s and %s are not the same type.  All variables in "
271                        "this variable list must be of the same type.  %s "
272                        "will be omitted from list."),
273                  (*v)[0]->name, add->name, add->name);
274           else if ((pv_opts & PV_NO_DUPLICATE) && included[add->index])
275             msg (SE, _("Variable %s appears twice in variable list."),
276                  add->name);
277           else {
278             /* Success--add the variable to the list. */
279             if ((pv_opts & PV_DUPLICATE) || !included[add->index])
280               {
281                 (*v)[(*nv)++] = var_set_get_var (vs, i);
282                 if (!(pv_opts & PV_DUPLICATE))
283                   included[add->index] = 1;
284               }
285
286             /* Next. */
287             continue;
288           }
289
290           /* Arrive here only on failure. */
291           if (pv_opts & PV_SINGLE)
292             goto fail;
293         }
294
295       /* We finished adding v1...v2 to the list. */
296       if (pv_opts & PV_SINGLE)
297         return 1;
298       lex_match (',');
299     }
300   while ((token == T_ID && var_set_lookup_var (vs, tokid) != NULL)
301          || token == T_ALL);
302
303   if (!(pv_opts & PV_DUPLICATE))
304     free (included);
305   if (!*nv)
306     goto fail;
307   return 1;
308
309 fail:
310   free (*v);
311   *v = NULL;
312   *nv = 0;
313   if (!(pv_opts & PV_DUPLICATE))
314     free (included);
315   return 0;
316 }
317
318 /* Extracts a numeric suffix from variable name S, copying it
319    into string R.  Sets *D to the length of R and *N to its
320    value. */
321 static int
322 extract_num (char *s, char *r, int *n, int *d)
323 {
324   char *cp;
325
326   /* Find first digit. */
327   cp = s + strlen (s) - 1;
328   while (isdigit ((unsigned char) *cp) && cp > s)
329     cp--;
330   cp++;
331
332   /* Extract root. */
333   strncpy (r, s, cp - s);
334   r[cp - s] = 0;
335
336   /* Count initial zeros. */
337   *n = *d = 0;
338   while (*cp == '0')
339     {
340       (*d)++;
341       cp++;
342     }
343
344   /* Extract value. */
345   while (isdigit ((unsigned char) *cp))
346     {
347       (*d)++;
348       *n = (*n * 10) + (*cp - '0');
349       cp++;
350     }
351
352   /* Sanity check. */
353   if (*n == 0 && *d == 0)
354     {
355       msg (SE, _("incorrect use of TO convention"));
356       return 0;
357     }
358   return 1;
359 }
360
361 /* Parses a list of variable names according to the DATA LIST version
362    of the TO convention.  */
363 int
364 parse_DATA_LIST_vars (char ***names, int *nnames, int pv_opts)
365 {
366   int n1, n2;
367   int d1, d2;
368   int n;
369   int nvar, mvar;
370   char *name1, *name2;
371   char *root1, *root2;
372   int success = 0;
373
374   assert (names != NULL);
375   assert (nnames != NULL);
376   assert ((pv_opts & ~(PV_APPEND | PV_SINGLE
377                        | PV_NO_SCRATCH | PV_NO_DUPLICATE)) == 0);
378   /* FIXME: PV_NO_DUPLICATE is not implemented. */
379
380   if (pv_opts & PV_APPEND)
381     nvar = mvar = *nnames;
382   else
383     {
384       nvar = mvar = 0;
385       *names = NULL;
386     }
387
388   name1 = xmalloc (36);
389   name2 = &name1[1 * 9];
390   root1 = &name1[2 * 9];
391   root2 = &name1[3 * 9];
392   do
393     {
394       if (token != T_ID)
395         {
396           lex_error ("expecting variable name");
397           goto fail;
398         }
399       if (dict_class_from_id (tokid) == DC_SCRATCH
400           && (pv_opts & PV_NO_SCRATCH))
401         {
402           msg (SE, _("Scratch variables not allowed here."));
403           goto fail;
404         }
405       strcpy (name1, tokid);
406       lex_get ();
407       if (token == T_TO)
408         {
409           lex_get ();
410           if (token != T_ID)
411             {
412               lex_error ("expecting variable name");
413               goto fail;
414             }
415           strcpy (name2, tokid);
416           lex_get ();
417
418           if (!extract_num (name1, root1, &n1, &d1)
419               || !extract_num (name2, root2, &n2, &d2))
420             goto fail;
421
422           if (strcmp (root1, root2))
423             {
424               msg (SE, _("Prefixes don't match in use of TO convention."));
425               goto fail;
426             }
427           if (n1 > n2)
428             {
429               msg (SE, _("Bad bounds in use of TO convention."));
430               goto fail;
431             }
432           if (d2 > d1)
433             d2 = d1;
434
435           if (mvar < nvar + (n2 - n1 + 1))
436             {
437               mvar += ROUND_UP (n2 - n1 + 1, 16);
438               *names = xrealloc (*names, mvar * sizeof **names);
439             }
440
441           for (n = n1; n <= n2; n++)
442             {
443               (*names)[nvar] = xmalloc (9);
444               sprintf ((*names)[nvar], "%s%0*d", root1, d1, n);
445               nvar++;
446             }
447         }
448       else
449         {
450           if (nvar >= mvar)
451             {
452               mvar += 16;
453               *names = xrealloc (*names, mvar * sizeof **names);
454             }
455           (*names)[nvar++] = xstrdup (name1);
456         }
457
458       lex_match (',');
459
460       if (pv_opts & PV_SINGLE)
461         break;
462     }
463   while (token == T_ID);
464   success = 1;
465
466 fail:
467   *nnames = nvar;
468   free (name1);
469   if (!success)
470     {
471       int i;
472       for (i = 0; i < nvar; i++)
473         free ((*names)[i]);
474       free (*names);
475       *names = NULL;
476       *nnames = 0;
477     }
478   return success;
479 }
480
481 /* Parses a list of variables where some of the variables may be
482    existing and the rest are to be created.  Same args as
483    parse_DATA_LIST_vars(). */
484 int
485 parse_mixed_vars (char ***names, int *nnames, int pv_opts)
486 {
487   int i;
488
489   assert (names != NULL);
490   assert (nnames != NULL);
491   assert ((pv_opts & ~PV_APPEND) == 0);
492
493   if (!(pv_opts & PV_APPEND))
494     {
495       *names = NULL;
496       *nnames = 0;
497     }
498   while (token == T_ID || token == T_ALL)
499     {
500       if (token == T_ALL || dict_lookup_var (default_dict, tokid) != NULL)
501         {
502           struct variable **v;
503           int nv;
504
505           if (!parse_variables (default_dict, &v, &nv, PV_NONE))
506             goto fail;
507           *names = xrealloc (*names, (*nnames + nv) * sizeof **names);
508           for (i = 0; i < nv; i++)
509             (*names)[*nnames + i] = xstrdup (v[i]->name);
510           free (v);
511           *nnames += nv;
512         }
513       else if (!parse_DATA_LIST_vars (names, nnames, PV_APPEND))
514         goto fail;
515     }
516   return 1;
517
518 fail:
519   for (i = 0; i < *nnames; i++)
520     free ((*names)[*nnames]);
521   free (names);
522   *names = NULL;
523   *nnames = 0;
524   return 0;
525 }
526 \f
527 /* A set of variables. */
528 struct var_set 
529   {
530     size_t (*get_cnt) (const struct var_set *);
531     struct variable *(*get_var) (const struct var_set *, size_t idx);
532     struct variable *(*lookup_var) (const struct var_set *, const char *);
533     void (*destroy) (struct var_set *);
534     void *aux;
535   };
536
537 /* Returns the number of variables in VS. */
538 size_t
539 var_set_get_cnt (const struct var_set *vs) 
540 {
541   assert (vs != NULL);
542
543   return vs->get_cnt (vs);
544 }
545
546 /* Return variable with index IDX in VS.
547    IDX must be less than the number of variables in VS. */
548 struct variable *
549 var_set_get_var (const struct var_set *vs, size_t idx) 
550 {
551   assert (vs != NULL);
552   assert (idx < var_set_get_cnt (vs));
553
554   return vs->get_var (vs, idx);
555 }
556
557 /* Returns the variable in VS named NAME, or a null pointer if VS
558    contains no variable with that name. */
559 struct variable *
560 var_set_lookup_var (const struct var_set *vs, const char *name) 
561 {
562   assert (vs != NULL);
563   assert (name != NULL);
564   assert (strlen (name) < 9);
565
566   return vs->lookup_var (vs, name);
567 }
568
569 /* Destroys VS. */
570 void
571 var_set_destroy (struct var_set *vs) 
572 {
573   if (vs != NULL)
574     vs->destroy (vs);
575 }
576 \f
577 /* Returns the number of variables in VS. */
578 static size_t
579 dict_var_set_get_cnt (const struct var_set *vs) 
580 {
581   struct dictionary *d = vs->aux;
582
583   return dict_get_var_cnt (d);
584 }
585
586 /* Return variable with index IDX in VS.
587    IDX must be less than the number of variables in VS. */
588 static struct variable *
589 dict_var_set_get_var (const struct var_set *vs, size_t idx) 
590 {
591   struct dictionary *d = vs->aux;
592
593   return dict_get_var (d, idx);
594 }
595
596 /* Returns the variable in VS named NAME, or a null pointer if VS
597    contains no variable with that name. */
598 static struct variable *
599 dict_var_set_lookup_var (const struct var_set *vs, const char *name) 
600 {
601   struct dictionary *d = vs->aux;
602
603   return dict_lookup_var (d, name);
604 }
605
606 /* Destroys VS. */
607 static void
608 dict_var_set_destroy (struct var_set *vs) 
609 {
610   free (vs);
611 }
612
613 /* Returns a variable set based on D. */
614 struct var_set *
615 var_set_create_from_dict (const struct dictionary *d) 
616 {
617   struct var_set *vs = xmalloc (sizeof *vs);
618   vs->get_cnt = dict_var_set_get_cnt;
619   vs->get_var = dict_var_set_get_var;
620   vs->lookup_var = dict_var_set_lookup_var;
621   vs->destroy = dict_var_set_destroy;
622   vs->aux = (void *) d;
623   return vs;
624 }
625 \f
626 /* A variable set based on an array. */
627 struct array_var_set 
628   {
629     struct variable *const *var;/* Array of variables. */
630     size_t var_cnt;             /* Number of elements in var. */
631     struct hsh_table *name_tab; /* Hash from variable names to variables. */
632   };
633
634 /* Returns the number of variables in VS. */
635 static size_t
636 array_var_set_get_cnt (const struct var_set *vs) 
637 {
638   struct array_var_set *avs = vs->aux;
639
640   return avs->var_cnt;
641 }
642
643 /* Return variable with index IDX in VS.
644    IDX must be less than the number of variables in VS. */
645 static struct variable *
646 array_var_set_get_var (const struct var_set *vs, size_t idx) 
647 {
648   struct array_var_set *avs = vs->aux;
649
650   return (struct variable *) avs->var[idx];
651 }
652
653 /* Returns the variable in VS named NAME, or a null pointer if VS
654    contains no variable with that name. */
655 static struct variable *
656 array_var_set_lookup_var (const struct var_set *vs, const char *name) 
657 {
658   struct array_var_set *avs = vs->aux;
659   struct variable v;
660
661   strcpy (v.name, name);
662
663   return hsh_find (avs->name_tab, &v);
664 }
665
666 /* Destroys VS. */
667 static void
668 array_var_set_destroy (struct var_set *vs) 
669 {
670   struct array_var_set *avs = vs->aux;
671
672   hsh_destroy (avs->name_tab);
673   free (avs);
674   free (vs);
675 }
676
677 /* Returns a variable set based on the VAR_CNT variables in
678    VAR. */
679 struct var_set *
680 var_set_create_from_array (struct variable *const *var, size_t var_cnt) 
681 {
682   struct var_set *vs;
683   struct array_var_set *avs;
684   size_t i;
685
686   vs = xmalloc (sizeof *vs);
687   vs->get_cnt = array_var_set_get_cnt;
688   vs->get_var = array_var_set_get_var;
689   vs->lookup_var = array_var_set_lookup_var;
690   vs->destroy = array_var_set_destroy;
691   vs->aux = avs = xmalloc (sizeof *avs);
692   avs->var = var;
693   avs->var_cnt = var_cnt;
694   avs->name_tab = hsh_create (2 * var_cnt,
695                               compare_variables, hash_variable, NULL,
696                               NULL);
697   for (i = 0; i < var_cnt; i++)
698     if (hsh_insert (avs->name_tab, (void *) var[i]) != NULL) 
699       {
700         var_set_destroy (vs);
701         return NULL;
702       }
703   
704   return vs;
705 }