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