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