Fixed bug reporting the significance of paired value t-test.
[pspp-builds.git] / src / data / dictionary.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007 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 "dictionary.h"
20
21 #include <stdlib.h>
22 #include <ctype.h>
23
24 #include "case.h"
25 #include "category.h"
26 #include "identifier.h"
27 #include "settings.h"
28 #include "value-labels.h"
29 #include "vardict.h"
30 #include "variable.h"
31 #include "vector.h"
32 #include <libpspp/array.h>
33 #include <libpspp/assertion.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/hash.h>
36 #include <libpspp/message.h>
37 #include <libpspp/misc.h>
38 #include <libpspp/pool.h>
39 #include <libpspp/str.h>
40
41 #include "intprops.h"
42 #include "minmax.h"
43 #include "xalloc.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* A dictionary. */
49 struct dictionary
50   {
51     struct variable **var;      /* Variables. */
52     size_t var_cnt, var_cap;    /* Number of variables, capacity. */
53     struct hsh_table *name_tab; /* Variable index by name. */
54     int next_value_idx;         /* Index of next `union value' to allocate. */
55     const struct variable **split;    /* SPLIT FILE vars. */
56     size_t split_cnt;           /* SPLIT FILE count. */
57     struct variable *weight;    /* WEIGHT variable. */
58     struct variable *filter;    /* FILTER variable. */
59     casenumber case_limit;      /* Current case limit (N command). */
60     char *label;                /* File label. */
61     struct string documents;    /* Documents, as a string. */
62     struct vector **vector;     /* Vectors of variables. */
63     size_t vector_cnt;          /* Number of vectors. */
64     const struct dict_callbacks *callbacks; /* Callbacks on dictionary
65                                                modification */
66     void *cb_data ;                  /* Data passed to callbacks */
67   };
68
69 /* Print a representation of dictionary D to stdout, for
70    debugging purposes. */
71 void
72 dict_dump (const struct dictionary *d)
73 {
74   int i;
75   for (i = 0 ; i < d->var_cnt ; ++i )
76     {
77       const struct variable *v =
78         d->var[i];
79       printf ("Name: %s;\tdict_idx: %d; case_idx: %d\n",
80               var_get_name (v),
81               var_get_dict_index (v),
82               var_get_case_index (v));
83
84     }
85 }
86
87 /* Associate CALLBACKS with DICT.  Callbacks will be invoked whenever
88    the dictionary or any of the variables it contains are modified.
89    Each callback will get passed CALLBACK_DATA.
90    Any callback may be NULL, in which case it'll be ignored.
91 */
92 void
93 dict_set_callbacks (struct dictionary *dict,
94                     const struct dict_callbacks *callbacks,
95                     void *callback_data)
96 {
97   dict->callbacks = callbacks;
98   dict->cb_data = callback_data;
99 }
100
101 /* Shallow copy the callbacks from SRC to DEST */
102 void
103 dict_copy_callbacks (struct dictionary *dest,
104                      const struct dictionary *src)
105 {
106   dest->callbacks = src->callbacks;
107   dest->cb_data = src->cb_data;
108 }
109
110 /* Creates and returns a new dictionary. */
111 struct dictionary *
112 dict_create (void)
113 {
114   struct dictionary *d = xzalloc (sizeof *d);
115
116   d->name_tab = hsh_create (8, compare_vars_by_name, hash_var_by_name,
117                             NULL, NULL);
118   return d;
119 }
120
121 /* Creates and returns a (deep) copy of an existing
122    dictionary.
123
124    The new dictionary's case indexes are copied from the old
125    dictionary.  If the new dictionary won't be used to access
126    cases produced with the old dictionary, then the new
127    dictionary's case indexes should be compacted with
128    dict_compact_values to save space. */
129 struct dictionary *
130 dict_clone (const struct dictionary *s)
131 {
132   struct dictionary *d;
133   size_t i;
134
135   assert (s != NULL);
136
137   d = dict_create ();
138
139   for (i = 0; i < s->var_cnt; i++)
140     {
141       const struct vardict_info *svdi;
142       struct vardict_info dvdi;
143       struct variable *sv = s->var[i];
144       struct variable *dv = dict_clone_var_assert (d, sv, var_get_name (sv));
145       size_t i;
146
147       for (i = 0; i < var_get_short_name_cnt (sv); i++)
148         var_set_short_name (dv, i, var_get_short_name (sv, i));
149
150       svdi = var_get_vardict (sv);
151       dvdi = *svdi;
152       dvdi.dict = d;
153       var_set_vardict (dv, &dvdi);
154     }
155
156   d->next_value_idx = s->next_value_idx;
157
158   d->split_cnt = s->split_cnt;
159   if (d->split_cnt > 0)
160     {
161       d->split = xnmalloc (d->split_cnt, sizeof *d->split);
162       for (i = 0; i < d->split_cnt; i++)
163         d->split[i] = dict_lookup_var_assert (d, var_get_name (s->split[i]));
164     }
165
166   if (s->weight != NULL)
167     dict_set_weight (d, dict_lookup_var_assert (d, var_get_name (s->weight)));
168
169   if (s->filter != NULL)
170     dict_set_filter (d, dict_lookup_var_assert (d, var_get_name (s->filter)));
171
172   d->case_limit = s->case_limit;
173   dict_set_label (d, dict_get_label (s));
174   dict_set_documents (d, dict_get_documents (s));
175
176   d->vector_cnt = s->vector_cnt;
177   d->vector = xnmalloc (d->vector_cnt, sizeof *d->vector);
178   for (i = 0; i < s->vector_cnt; i++)
179     d->vector[i] = vector_clone (s->vector[i], s, d);
180
181   return d;
182 }
183
184 /* Clears the contents from a dictionary without destroying the
185    dictionary itself. */
186 void
187 dict_clear (struct dictionary *d)
188 {
189   /* FIXME?  Should we really clear case_limit, label, documents?
190      Others are necessarily cleared by deleting all the variables.*/
191   assert (d != NULL);
192
193   while (d->var_cnt > 0 )
194     {
195       dict_delete_var (d, d->var[d->var_cnt - 1]);
196     }
197
198   free (d->var);
199   d->var = NULL;
200   d->var_cnt = d->var_cap = 0;
201   hsh_clear (d->name_tab);
202   d->next_value_idx = 0;
203   dict_set_split_vars (d, NULL, 0);
204   dict_set_weight (d, NULL);
205   dict_set_filter (d, NULL);
206   d->case_limit = 0;
207   free (d->label);
208   d->label = NULL;
209   ds_destroy (&d->documents);
210   dict_clear_vectors (d);
211 }
212
213 /* Destroys the aux data for every variable in D, by calling
214    var_clear_aux() for each variable. */
215 void
216 dict_clear_aux (struct dictionary *d)
217 {
218   int i;
219
220   assert (d != NULL);
221
222   for (i = 0; i < d->var_cnt; i++)
223     var_clear_aux (d->var[i]);
224 }
225
226 /* Clears a dictionary and destroys it. */
227 void
228 dict_destroy (struct dictionary *d)
229 {
230   if (d != NULL)
231     {
232       /* In general, we don't want callbacks occuring, if the dictionary
233          is being destroyed */
234       d->callbacks  = NULL ;
235
236       dict_clear (d);
237       hsh_destroy (d->name_tab);
238       free (d);
239     }
240 }
241
242 /* Returns the number of variables in D. */
243 size_t
244 dict_get_var_cnt (const struct dictionary *d)
245 {
246   assert (d != NULL);
247
248   return d->var_cnt;
249 }
250
251 /* Returns the variable in D with dictionary index IDX, which
252    must be between 0 and the count returned by
253    dict_get_var_cnt(), exclusive. */
254 struct variable *
255 dict_get_var (const struct dictionary *d, size_t idx)
256 {
257   assert (d != NULL);
258   assert (idx < d->var_cnt);
259
260   return d->var[idx];
261 }
262
263 /* Sets *VARS to an array of pointers to variables in D and *CNT
264    to the number of variables in *D.  All variables are returned
265    except for those, if any, in the classes indicated by EXCLUDE.
266    (There is no point in putting DC_SYSTEM in EXCLUDE as
267    dictionaries never include system variables.) */
268 void
269 dict_get_vars (const struct dictionary *d, const struct variable ***vars,
270                size_t *cnt, enum dict_class exclude)
271 {
272   dict_get_vars_mutable (d, (struct variable ***) vars, cnt, exclude);
273 }
274
275 /* Sets *VARS to an array of pointers to variables in D and *CNT
276    to the number of variables in *D.  All variables are returned
277    except for those, if any, in the classes indicated by EXCLUDE.
278    (There is no point in putting DC_SYSTEM in EXCLUDE as
279    dictionaries never include system variables.) */
280 void
281 dict_get_vars_mutable (const struct dictionary *d, struct variable ***vars,
282                        size_t *cnt, enum dict_class exclude)
283 {
284   size_t count;
285   size_t i;
286
287   assert (d != NULL);
288   assert (vars != NULL);
289   assert (cnt != NULL);
290   assert (exclude == (exclude & DC_ALL));
291
292   count = 0;
293   for (i = 0; i < d->var_cnt; i++)
294     {
295       enum dict_class class = var_get_dict_class (d->var[i]);
296       if (!(class & exclude))
297         count++;
298     }
299
300   *vars = xnmalloc (count, sizeof **vars);
301   *cnt = 0;
302   for (i = 0; i < d->var_cnt; i++)
303     {
304       enum dict_class class = var_get_dict_class (d->var[i]);
305       if (!(class & exclude))
306         (*vars)[(*cnt)++] = d->var[i];
307     }
308   assert (*cnt == count);
309 }
310
311 static struct variable *
312 add_var (struct dictionary *d, struct variable *v)
313 {
314   /* Add dictionary info to variable. */
315   struct vardict_info vdi;
316   vdi.case_index = d->next_value_idx;
317   vdi.dict_index = d->var_cnt;
318   vdi.dict = d;
319   var_set_vardict (v, &vdi);
320
321   /* Update dictionary. */
322   if (d->var_cnt >= d->var_cap)
323     {
324       d->var_cap = 8 + 2 * d->var_cap;
325       d->var = xnrealloc (d->var, d->var_cap, sizeof *d->var);
326     }
327   d->var[d->var_cnt++] = v;
328   hsh_force_insert (d->name_tab, v);
329
330   if ( d->callbacks &&  d->callbacks->var_added )
331     d->callbacks->var_added (d, var_get_dict_index (v), d->cb_data);
332
333   d->next_value_idx += var_get_value_cnt (v);
334
335   return v;
336 }
337
338 /* Creates and returns a new variable in D with the given NAME
339    and WIDTH.  Returns a null pointer if the given NAME would
340    duplicate that of an existing variable in the dictionary. */
341 struct variable *
342 dict_create_var (struct dictionary *d, const char *name, int width)
343 {
344   return (dict_lookup_var (d, name) == NULL
345           ? dict_create_var_assert (d, name, width)
346           : NULL);
347 }
348
349 /* Creates and returns a new variable in D with the given NAME
350    and WIDTH.  Assert-fails if the given NAME would duplicate
351    that of an existing variable in the dictionary. */
352 struct variable *
353 dict_create_var_assert (struct dictionary *d, const char *name, int width)
354 {
355   assert (dict_lookup_var (d, name) == NULL);
356   return add_var (d, var_create (name, width));
357 }
358
359 /* Creates and returns a new variable in D with name NAME, as a
360    copy of existing variable OLD_VAR, which need not be in D or
361    in any dictionary.  Returns a null pointer if the given NAME
362    would duplicate that of an existing variable in the
363    dictionary. */
364 struct variable *
365 dict_clone_var (struct dictionary *d, const struct variable *old_var,
366                 const char *name)
367 {
368   return (dict_lookup_var (d, name) == NULL
369           ? dict_clone_var_assert (d, old_var, name)
370           : NULL);
371 }
372
373 /* Creates and returns a new variable in D with name NAME, as a
374    copy of existing variable OLD_VAR, which need not be in D or
375    in any dictionary.  Assert-fails if the given NAME would
376    duplicate that of an existing variable in the dictionary. */
377 struct variable *
378 dict_clone_var_assert (struct dictionary *d, const struct variable *old_var,
379                        const char *name)
380 {
381   struct variable *new_var = var_clone (old_var);
382   assert (dict_lookup_var (d, name) == NULL);
383   var_set_name (new_var, name);
384   return add_var (d, new_var);
385 }
386
387 /* Returns the variable named NAME in D, or a null pointer if no
388    variable has that name. */
389 struct variable *
390 dict_lookup_var (const struct dictionary *d, const char *name)
391 {
392   struct variable *target ;
393   struct variable *result ;
394
395   if ( ! var_is_plausible_name (name, false))
396     return NULL;
397
398   target = var_create (name, 0);
399   result = hsh_find (d->name_tab, target);
400   var_destroy (target);
401
402   if ( result && var_has_vardict (result)) 
403   {
404       const struct vardict_info *vdi = var_get_vardict (result);
405       assert (vdi->dict == d);
406   }
407
408   return result;
409 }
410
411 /* Returns the variable named NAME in D.  Assert-fails if no
412    variable has that name. */
413 struct variable *
414 dict_lookup_var_assert (const struct dictionary *d, const char *name)
415 {
416   struct variable *v = dict_lookup_var (d, name);
417   assert (v != NULL);
418   return v;
419 }
420
421 /* Returns true if variable V is in dictionary D,
422    false otherwise. */
423 bool
424 dict_contains_var (const struct dictionary *d, const struct variable *v)
425 {
426   if (var_has_vardict (v))
427     {
428       const struct vardict_info *vdi = var_get_vardict (v);
429       return (vdi->dict_index >= 0
430               && vdi->dict_index < d->var_cnt
431               && d->var[vdi->dict_index] == v);
432     }
433   else
434     return false;
435 }
436
437 /* Compares two double pointers to variables, which should point
438    to elements of a struct dictionary's `var' member array. */
439 static int
440 compare_var_ptrs (const void *a_, const void *b_, const void *aux UNUSED)
441 {
442   struct variable *const *a = a_;
443   struct variable *const *b = b_;
444
445   return *a < *b ? -1 : *a > *b;
446 }
447
448 /* Sets the dict_index in V's vardict to DICT_INDEX. */
449 static void
450 set_var_dict_index (struct variable *v, int dict_index)
451 {
452   struct vardict_info vdi = *var_get_vardict (v);
453   struct dictionary *d = vdi.dict;
454   vdi.dict_index = dict_index;
455   var_set_vardict (v, &vdi);
456
457   if ( d->callbacks &&  d->callbacks->var_changed )
458     d->callbacks->var_changed (d, dict_index, d->cb_data);
459 }
460
461 /* Sets the case_index in V's vardict to CASE_INDEX. */
462 static void
463 set_var_case_index (struct variable *v, int case_index)
464 {
465   struct vardict_info vdi = *var_get_vardict (v);
466   vdi.case_index = case_index;
467   var_set_vardict (v, &vdi);
468 }
469
470 /* Re-sets the dict_index in the dictionary variables with
471    indexes from FROM to TO (exclusive). */
472 static void
473 reindex_vars (struct dictionary *d, size_t from, size_t to)
474 {
475   size_t i;
476
477   for (i = from; i < to; i++)
478     set_var_dict_index (d->var[i], i);
479 }
480
481 /* Deletes variable V from dictionary D and frees V.
482
483    This is a very bad idea if there might be any pointers to V
484    from outside D.  In general, no variable in the active file's
485    dictionary should be deleted when any transformations are
486    active on the dictionary's dataset, because those
487    transformations might reference the deleted variable.  The
488    safest time to delete a variable is just after a procedure has
489    been executed, as done by DELETE VARIABLES.
490
491    Pointers to V within D are not a problem, because
492    dict_delete_var() knows to remove V from split variables,
493    weights, filters, etc. */
494 void
495 dict_delete_var (struct dictionary *d, struct variable *v)
496 {
497   int dict_index = var_get_dict_index (v);
498   const int case_index = var_get_case_index (v);
499   const int val_cnt = var_get_value_cnt (v);
500
501   assert (dict_contains_var (d, v));
502
503   /* Delete aux data. */
504   var_clear_aux (v);
505
506   dict_unset_split_var (d, v);
507
508   if (d->weight == v)
509     dict_set_weight (d, NULL);
510
511   if (d->filter == v)
512     dict_set_filter (d, NULL);
513
514   dict_clear_vectors (d);
515
516   /* Remove V from var array. */
517   remove_element (d->var, d->var_cnt, sizeof *d->var, dict_index);
518   d->var_cnt--;
519
520   /* Update dict_index for each affected variable. */
521   reindex_vars (d, dict_index, d->var_cnt);
522
523   /* Update name hash. */
524   hsh_force_delete (d->name_tab, v);
525
526
527   /* Free memory. */
528   var_clear_vardict (v);
529   var_destroy (v);
530
531
532   if (d->callbacks &&  d->callbacks->var_deleted )
533     d->callbacks->var_deleted (d, dict_index, case_index, val_cnt, d->cb_data);
534 }
535
536 /* Deletes the COUNT variables listed in VARS from D.  This is
537    unsafe; see the comment on dict_delete_var() for details. */
538 void
539 dict_delete_vars (struct dictionary *d,
540                   struct variable *const *vars, size_t count)
541 {
542   /* FIXME: this can be done in O(count) time, but this algorithm
543      is O(count**2). */
544   assert (d != NULL);
545   assert (count == 0 || vars != NULL);
546
547   while (count-- > 0)
548     dict_delete_var (d, *vars++);
549 }
550
551 /* Deletes the COUNT variables in D starting at index IDX.  This
552    is unsafe; see the comment on dict_delete_var() for
553    details. */
554 void
555 dict_delete_consecutive_vars (struct dictionary *d, size_t idx, size_t count)
556 {
557   /* FIXME: this can be done in O(count) time, but this algorithm
558      is O(count**2). */
559   assert (idx + count <= d->var_cnt);
560
561   while (count-- > 0)
562     dict_delete_var (d, d->var[idx]);
563 }
564
565 /* Deletes scratch variables from dictionary D. */
566 void
567 dict_delete_scratch_vars (struct dictionary *d)
568 {
569   int i;
570
571   /* FIXME: this can be done in O(count) time, but this algorithm
572      is O(count**2). */
573   assert (d != NULL);
574
575   for (i = 0; i < d->var_cnt; )
576     if (var_get_dict_class (d->var[i]) == DC_SCRATCH)
577       dict_delete_var (d, d->var[i]);
578     else
579       i++;
580 }
581
582 /* Moves V to 0-based position IDX in D.  Other variables in D,
583    if any, retain their relative positions.  Runs in time linear
584    in the distance moved. */
585 void
586 dict_reorder_var (struct dictionary *d, struct variable *v, size_t new_index)
587 {
588   size_t old_index = var_get_dict_index (v);
589
590   assert (new_index < d->var_cnt);
591   move_element (d->var, d->var_cnt, sizeof *d->var, old_index, new_index);
592   reindex_vars (d, MIN (old_index, new_index), MAX (old_index, new_index) + 1);
593 }
594
595 /* Reorders the variables in D, placing the COUNT variables
596    listed in ORDER in that order at the beginning of D.  The
597    other variables in D, if any, retain their relative
598    positions. */
599 void
600 dict_reorder_vars (struct dictionary *d,
601                    struct variable *const *order, size_t count)
602 {
603   struct variable **new_var;
604   size_t i;
605
606   assert (d != NULL);
607   assert (count == 0 || order != NULL);
608   assert (count <= d->var_cnt);
609
610   new_var = xnmalloc (d->var_cnt, sizeof *new_var);
611   memcpy (new_var, order, count * sizeof *new_var);
612   for (i = 0; i < count; i++)
613     {
614       size_t index = var_get_dict_index (order[i]);
615       assert (d->var[index] == order[i]);
616       d->var[index] = NULL;
617       set_var_dict_index (order[i], i);
618     }
619   for (i = 0; i < d->var_cnt; i++)
620     if (d->var[i] != NULL)
621       {
622         assert (count < d->var_cnt);
623         new_var[count] = d->var[i];
624         set_var_dict_index (new_var[count], count);
625         count++;
626       }
627   free (d->var);
628   d->var = new_var;
629 }
630
631 /* Changes the name of variable V in dictionary D to NEW_NAME. */
632 static void
633 rename_var (struct dictionary *d, struct variable *v, const char *new_name)
634 {
635   struct vardict_info vdi;
636
637   assert (dict_contains_var (d, v));
638
639   vdi = *var_get_vardict (v);
640   var_clear_vardict (v);
641   var_set_name (v, new_name);
642   var_set_vardict (v, &vdi);
643 }
644
645 /* Changes the name of V in D to name NEW_NAME.  Assert-fails if
646    a variable named NEW_NAME is already in D, except that
647    NEW_NAME may be the same as V's existing name. */
648 void
649 dict_rename_var (struct dictionary *d, struct variable *v,
650                  const char *new_name)
651 {
652   assert (!strcasecmp (var_get_name (v), new_name)
653           || dict_lookup_var (d, new_name) == NULL);
654
655   hsh_force_delete (d->name_tab, v);
656   rename_var (d, v, new_name);
657   hsh_force_insert (d->name_tab, v);
658
659   if (settings_get_algorithm () == ENHANCED)
660     var_clear_short_names (v);
661
662   if ( d->callbacks &&  d->callbacks->var_changed )
663     d->callbacks->var_changed (d, var_get_dict_index (v), d->cb_data);
664 }
665
666 /* Renames COUNT variables specified in VARS to the names given
667    in NEW_NAMES within dictionary D.  If the renaming would
668    result in a duplicate variable name, returns false and stores a
669    name that would be duplicated into *ERR_NAME (if ERR_NAME is
670    non-null).  Otherwise, the renaming is successful, and true
671    is returned. */
672 bool
673 dict_rename_vars (struct dictionary *d,
674                   struct variable **vars, char **new_names, size_t count,
675                   char **err_name)
676 {
677   struct pool *pool;
678   char **old_names;
679   size_t i;
680
681   assert (count == 0 || vars != NULL);
682   assert (count == 0 || new_names != NULL);
683
684   /* Save the names of the variables to be renamed. */
685   pool = pool_create ();
686   old_names = pool_nalloc (pool, count, sizeof *old_names);
687   for (i = 0; i < count; i++)
688     old_names[i] = pool_strdup (pool, var_get_name (vars[i]));
689
690   /* Remove the variables to be renamed from the name hash,
691      and rename them. */
692   for (i = 0; i < count; i++)
693     {
694       hsh_force_delete (d->name_tab, vars[i]);
695       rename_var (d, vars[i], new_names[i]);
696     }
697
698   /* Add the renamed variables back into the name hash,
699      checking for conflicts. */
700   for (i = 0; i < count; i++)
701     if (hsh_insert (d->name_tab, vars[i]) != NULL)
702       {
703         /* There is a name conflict.
704            Back out all the name changes that have already
705            taken place, and indicate failure. */
706         size_t fail_idx = i;
707         if (err_name != NULL)
708           *err_name = new_names[i];
709
710         for (i = 0; i < fail_idx; i++)
711           hsh_force_delete (d->name_tab, vars[i]);
712
713         for (i = 0; i < count; i++)
714           {
715             rename_var (d, vars[i], old_names[i]);
716             hsh_force_insert (d->name_tab, vars[i]);
717           }
718
719         pool_destroy (pool);
720         return false;
721       }
722
723   /* Clear short names. */
724   if (settings_get_algorithm () == ENHANCED)
725     for (i = 0; i < count; i++)
726       var_clear_short_names (vars[i]);
727
728   pool_destroy (pool);
729   return true;
730 }
731
732 /* Returns true if a variable named NAME may be inserted in DICT;
733    that is, if there is not already a variable with that name in
734    DICT and if NAME is not a reserved word.  (The caller's checks
735    have already verified that NAME is otherwise acceptable as a
736    variable name.) */
737 static bool
738 var_name_is_insertable (const struct dictionary *dict, const char *name)
739 {
740   return (dict_lookup_var (dict, name) == NULL
741           && lex_id_to_token (ss_cstr (name)) == T_ID);
742 }
743
744 static bool
745 make_hinted_name (const struct dictionary *dict, const char *hint,
746                   char name[VAR_NAME_LEN + 1])
747 {
748   bool dropped = false;
749   char *cp;
750
751   for (cp = name; *hint && cp < name + VAR_NAME_LEN; hint++)
752     {
753       if (cp == name
754           ? lex_is_id1 (*hint) && *hint != '$'
755           : lex_is_idn (*hint))
756         {
757           if (dropped)
758             {
759               *cp++ = '_';
760               dropped = false;
761             }
762           if (cp < name + VAR_NAME_LEN)
763             *cp++ = *hint;
764         }
765       else if (cp > name)
766         dropped = true;
767     }
768   *cp = '\0';
769
770   if (name[0] != '\0')
771     {
772       size_t len = strlen (name);
773       unsigned long int i;
774
775       if (var_name_is_insertable (dict, name))
776         return true;
777
778       for (i = 0; i < ULONG_MAX; i++)
779         {
780           char suffix[INT_BUFSIZE_BOUND (i) + 1];
781           int ofs;
782
783           suffix[0] = '_';
784           if (!str_format_26adic (i + 1, &suffix[1], sizeof suffix - 1))
785             NOT_REACHED ();
786
787           ofs = MIN (VAR_NAME_LEN - strlen (suffix), len);
788           strcpy (&name[ofs], suffix);
789
790           if (var_name_is_insertable (dict, name))
791             return true;
792         }
793     }
794
795   return false;
796 }
797
798 static bool
799 make_numeric_name (const struct dictionary *dict, unsigned long int *num_start,
800                    char name[VAR_NAME_LEN + 1])
801 {
802   unsigned long int number;
803
804   for (number = num_start != NULL ? MAX (*num_start, 1) : 1;
805        number < ULONG_MAX;
806        number++)
807     {
808       sprintf (name, "VAR%03lu", number);
809       if (dict_lookup_var (dict, name) == NULL)
810         {
811           if (num_start != NULL)
812             *num_start = number + 1;
813           return true;
814         }
815     }
816
817   if (num_start != NULL)
818     *num_start = ULONG_MAX;
819   return false;
820 }
821
822
823 /* Attempts to devise a variable name unique within DICT.
824    Returns true if successful, in which case the new variable
825    name is stored into NAME.  Returns false if all names that can
826    be generated have already been taken.  (Returning false is
827    quite unlikely: at least ULONG_MAX unique names can be
828    generated.)
829
830    HINT, if it is non-null, is used as a suggestion that will be
831    modified for suitability as a variable name and for
832    uniqueness.
833
834    If HINT is null or entirely unsuitable, a name in the form
835    "VAR%03d" will be generated, where the smallest unused integer
836    value is used.  If NUM_START is non-null, then its value is
837    used as the minimum numeric value to check, and it is updated
838    to the next value to be checked.
839    */
840 bool
841 dict_make_unique_var_name (const struct dictionary *dict, const char *hint,
842                            unsigned long int *num_start,
843                            char name[VAR_NAME_LEN + 1])
844 {
845   return ((hint != NULL && make_hinted_name (dict, hint, name))
846           || make_numeric_name (dict, num_start, name));
847 }
848
849 /* Returns the weighting variable in dictionary D, or a null
850    pointer if the dictionary is unweighted. */
851 struct variable *
852 dict_get_weight (const struct dictionary *d)
853 {
854   assert (d != NULL);
855   assert (d->weight == NULL || dict_contains_var (d, d->weight));
856
857   return d->weight;
858 }
859
860 /* Returns the value of D's weighting variable in case C, except
861    that a negative weight is returned as 0.  Returns 1 if the
862    dictionary is unweighted.  Will warn about missing, negative,
863    or zero values if *WARN_ON_INVALID is true.  The function will
864    set *WARN_ON_INVALID to false if an invalid weight is
865    found. */
866 double
867 dict_get_case_weight (const struct dictionary *d, const struct ccase *c,
868                       bool *warn_on_invalid)
869 {
870   assert (d != NULL);
871   assert (c != NULL);
872
873   if (d->weight == NULL)
874     return 1.0;
875   else
876     {
877       double w = case_num (c, d->weight);
878       if (w < 0.0 || var_is_num_missing (d->weight, w, MV_ANY))
879         w = 0.0;
880       if ( w == 0.0 && warn_on_invalid != NULL && *warn_on_invalid ) {
881           *warn_on_invalid = false;
882           msg (SW, _("At least one case in the data file had a weight value "
883                      "that was user-missing, system-missing, zero, or "
884                      "negative.  These case(s) were ignored."));
885       }
886       return w;
887     }
888 }
889
890 /* Sets the weighting variable of D to V, or turning off
891    weighting if V is a null pointer. */
892 void
893 dict_set_weight (struct dictionary *d, struct variable *v)
894 {
895   assert (d != NULL);
896   assert (v == NULL || dict_contains_var (d, v));
897   assert (v == NULL || var_is_numeric (v));
898
899   d->weight = v;
900
901   if ( d->callbacks &&  d->callbacks->weight_changed )
902     d->callbacks->weight_changed (d,
903                                   v ? var_get_dict_index (v) : -1,
904                                   d->cb_data);
905 }
906
907 /* Returns the filter variable in dictionary D (see cmd_filter())
908    or a null pointer if the dictionary is unfiltered. */
909 struct variable *
910 dict_get_filter (const struct dictionary *d)
911 {
912   assert (d != NULL);
913   assert (d->filter == NULL || dict_contains_var (d, d->filter));
914
915   return d->filter;
916 }
917
918 /* Sets V as the filter variable for dictionary D.  Passing a
919    null pointer for V turn off filtering. */
920 void
921 dict_set_filter (struct dictionary *d, struct variable *v)
922 {
923   assert (d != NULL);
924   assert (v == NULL || dict_contains_var (d, v));
925   assert (v == NULL || var_is_numeric (v));
926
927   d->filter = v;
928
929   if ( d->callbacks && d->callbacks->filter_changed )
930     d->callbacks->filter_changed (d,
931                                   v ? var_get_dict_index (v) : -1,
932                                   d->cb_data);
933 }
934
935 /* Returns the case limit for dictionary D, or zero if the number
936    of cases is unlimited. */
937 casenumber
938 dict_get_case_limit (const struct dictionary *d)
939 {
940   assert (d != NULL);
941
942   return d->case_limit;
943 }
944
945 /* Sets CASE_LIMIT as the case limit for dictionary D.  Use
946    0 for CASE_LIMIT to indicate no limit. */
947 void
948 dict_set_case_limit (struct dictionary *d, casenumber case_limit)
949 {
950   assert (d != NULL);
951
952   d->case_limit = case_limit;
953 }
954
955 /* Returns the case index of the next value to be added to D.
956    This value is the number of `union value's that need to be
957    allocated to store a case for dictionary D. */
958 int
959 dict_get_next_value_idx (const struct dictionary *d)
960 {
961   assert (d != NULL);
962
963   return d->next_value_idx;
964 }
965
966 /* Returns the number of bytes needed to store a case for
967    dictionary D. */
968 size_t
969 dict_get_case_size (const struct dictionary *d)
970 {
971   assert (d != NULL);
972
973   return sizeof (union value) * dict_get_next_value_idx (d);
974 }
975
976 /* Reassigns values in dictionary D so that fragmentation is
977    eliminated. */
978 void
979 dict_compact_values (struct dictionary *d)
980 {
981   size_t i;
982
983   d->next_value_idx = 0;
984   for (i = 0; i < d->var_cnt; i++)
985     {
986       struct variable *v = d->var[i];
987       set_var_case_index (v, d->next_value_idx);
988       d->next_value_idx += var_get_value_cnt (v);
989     }
990 }
991
992 /*
993    Reassigns case indices for D, increasing each index above START by
994    the value PADDING.
995 */
996 static void
997 dict_pad_values (struct dictionary *d, int start, int padding)
998 {
999   size_t i;
1000
1001   if ( padding <= 0 ) 
1002         return;
1003
1004   for (i = 0; i < d->var_cnt; ++i)
1005     {
1006       struct variable *v = d->var[i];
1007
1008       int index = var_get_case_index (v);
1009
1010       if ( index >= start)
1011         set_var_case_index (v, index + padding);
1012     }
1013
1014   d->next_value_idx += padding;
1015 }
1016
1017
1018 /* Returns the number of values occupied by the variables in
1019    dictionary D.  All variables are considered if EXCLUDE_CLASSES
1020    is 0, or it may contain one or more of (1u << DC_ORDINARY),
1021    (1u << DC_SYSTEM), or (1u << DC_SCRATCH) to exclude the
1022    corresponding type of variable.
1023
1024    The return value may be less than the number of values in one
1025    of dictionary D's cases (as returned by
1026    dict_get_next_value_idx) even if E is 0, because there may be
1027    gaps in D's cases due to deleted variables. */
1028 size_t
1029 dict_count_values (const struct dictionary *d, unsigned int exclude_classes)
1030 {
1031   size_t i;
1032   size_t cnt;
1033
1034   assert ((exclude_classes & ~((1u << DC_ORDINARY)
1035                                | (1u << DC_SYSTEM)
1036                                | (1u << DC_SCRATCH))) == 0);
1037
1038   cnt = 0;
1039   for (i = 0; i < d->var_cnt; i++)
1040     {
1041       enum dict_class class = var_get_dict_class (d->var[i]);
1042       if (!(exclude_classes & (1u << class)))
1043         cnt += var_get_value_cnt (d->var[i]);
1044     }
1045   return cnt;
1046 }
1047 \f
1048 /* Returns the SPLIT FILE vars (see cmd_split_file()).  Call
1049    dict_get_split_cnt() to determine how many SPLIT FILE vars
1050    there are.  Returns a null pointer if and only if there are no
1051    SPLIT FILE vars. */
1052 const struct variable *const *
1053 dict_get_split_vars (const struct dictionary *d)
1054 {
1055   assert (d != NULL);
1056
1057   return d->split;
1058 }
1059
1060 /* Returns the number of SPLIT FILE vars. */
1061 size_t
1062 dict_get_split_cnt (const struct dictionary *d)
1063 {
1064   assert (d != NULL);
1065
1066   return d->split_cnt;
1067 }
1068
1069 /* Removes variable V, which must be in D, from D's set of split
1070    variables. */
1071 void
1072 dict_unset_split_var (struct dictionary *d, struct variable *v)
1073 {
1074   int orig_count;
1075
1076   assert (dict_contains_var (d, v));
1077
1078   orig_count = d->split_cnt;
1079   d->split_cnt = remove_equal (d->split, d->split_cnt, sizeof *d->split,
1080                                &v, compare_var_ptrs, NULL);
1081   if (orig_count != d->split_cnt)
1082     {
1083       /* We changed the set of split variables so invoke the
1084          callback. */
1085       if (d->callbacks &&  d->callbacks->split_changed)
1086         d->callbacks->split_changed (d, d->cb_data);
1087     }
1088 }
1089
1090 /* Sets CNT split vars SPLIT in dictionary D. */
1091 void
1092 dict_set_split_vars (struct dictionary *d,
1093                      struct variable *const *split, size_t cnt)
1094 {
1095   assert (d != NULL);
1096   assert (cnt == 0 || split != NULL);
1097
1098   d->split_cnt = cnt;
1099   if ( cnt > 0 )
1100    {
1101     d->split = xnrealloc (d->split, cnt, sizeof *d->split) ;
1102     memcpy (d->split, split, cnt * sizeof *d->split);
1103    }
1104   else
1105    {
1106     free (d->split);
1107     d->split = NULL;
1108    }
1109
1110   if ( d->callbacks &&  d->callbacks->split_changed )
1111     d->callbacks->split_changed (d, d->cb_data);
1112 }
1113
1114 /* Returns the file label for D, or a null pointer if D is
1115    unlabeled (see cmd_file_label()). */
1116 const char *
1117 dict_get_label (const struct dictionary *d)
1118 {
1119   assert (d != NULL);
1120
1121   return d->label;
1122 }
1123
1124 /* Sets D's file label to LABEL, truncating it to a maximum of 60
1125    characters. */
1126 void
1127 dict_set_label (struct dictionary *d, const char *label)
1128 {
1129   assert (d != NULL);
1130
1131   free (d->label);
1132   d->label = label != NULL ? xstrndup (label, 60) : NULL;
1133 }
1134
1135 /* Returns the documents for D, or a null pointer if D has no
1136    documents.  If the return value is nonnull, then the string
1137    will be an exact multiple of DOC_LINE_LENGTH bytes in length,
1138    with each segment corresponding to one line. */
1139 const char *
1140 dict_get_documents (const struct dictionary *d)
1141 {
1142   return ds_is_empty (&d->documents) ? NULL : ds_cstr (&d->documents);
1143 }
1144
1145 /* Sets the documents for D to DOCUMENTS, or removes D's
1146    documents if DOCUMENT is a null pointer.  If DOCUMENTS is
1147    nonnull, then it should be an exact multiple of
1148    DOC_LINE_LENGTH bytes in length, with each segment
1149    corresponding to one line. */
1150 void
1151 dict_set_documents (struct dictionary *d, const char *documents)
1152 {
1153   size_t remainder;
1154
1155   ds_assign_cstr (&d->documents, documents != NULL ? documents : "");
1156
1157   /* In case the caller didn't get it quite right, pad out the
1158      final line with spaces. */
1159   remainder = ds_length (&d->documents) % DOC_LINE_LENGTH;
1160   if (remainder != 0)
1161     ds_put_char_multiple (&d->documents, ' ', DOC_LINE_LENGTH - remainder);
1162 }
1163
1164 /* Drops the documents from dictionary D. */
1165 void
1166 dict_clear_documents (struct dictionary *d)
1167 {
1168   ds_clear (&d->documents);
1169 }
1170
1171 /* Appends LINE to the documents in D.  LINE will be truncated or
1172    padded on the right with spaces to make it exactly
1173    DOC_LINE_LENGTH bytes long. */
1174 void
1175 dict_add_document_line (struct dictionary *d, const char *line)
1176 {
1177   if (strlen (line) > DOC_LINE_LENGTH)
1178     {
1179       /* Note to translators: "bytes" is correct, not characters */
1180       msg (SW, _("Truncating document line to %d bytes."), DOC_LINE_LENGTH);
1181     }
1182   buf_copy_str_rpad (ds_put_uninit (&d->documents, DOC_LINE_LENGTH),
1183                      DOC_LINE_LENGTH, line);
1184 }
1185
1186 /* Returns the number of document lines in dictionary D. */
1187 size_t
1188 dict_get_document_line_cnt (const struct dictionary *d)
1189 {
1190   return ds_length (&d->documents) / DOC_LINE_LENGTH;
1191 }
1192
1193 /* Copies document line number IDX from dictionary D into
1194    LINE, trimming off any trailing white space. */
1195 void
1196 dict_get_document_line (const struct dictionary *d,
1197                         size_t idx, struct string *line)
1198 {
1199   assert (idx < dict_get_document_line_cnt (d));
1200   ds_assign_substring (line, ds_substr (&d->documents, idx * DOC_LINE_LENGTH,
1201                                         DOC_LINE_LENGTH));
1202   ds_rtrim (line, ss_cstr (CC_SPACES));
1203 }
1204
1205 /* Creates in D a vector named NAME that contains the CNT
1206    variables in VAR.  Returns true if successful, or false if a
1207    vector named NAME already exists in D. */
1208 bool
1209 dict_create_vector (struct dictionary *d,
1210                     const char *name,
1211                     struct variable **var, size_t cnt)
1212 {
1213   size_t i;
1214
1215   assert (var != NULL);
1216   assert (cnt > 0);
1217   for (i = 0; i < cnt; i++)
1218     assert (dict_contains_var (d, var[i]));
1219
1220   if (dict_lookup_vector (d, name) == NULL)
1221     {
1222       d->vector = xnrealloc (d->vector, d->vector_cnt + 1, sizeof *d->vector);
1223       d->vector[d->vector_cnt++] = vector_create (name, var, cnt);
1224       return true;
1225     }
1226   else
1227     return false;
1228 }
1229
1230 /* Creates in D a vector named NAME that contains the CNT
1231    variables in VAR.  A vector named NAME must not already exist
1232    in D. */
1233 void
1234 dict_create_vector_assert (struct dictionary *d,
1235                            const char *name,
1236                            struct variable **var, size_t cnt)
1237 {
1238   assert (dict_lookup_vector (d, name) == NULL);
1239   dict_create_vector (d, name, var, cnt);
1240 }
1241
1242 /* Returns the vector in D with index IDX, which must be less
1243    than dict_get_vector_cnt (D). */
1244 const struct vector *
1245 dict_get_vector (const struct dictionary *d, size_t idx)
1246 {
1247   assert (d != NULL);
1248   assert (idx < d->vector_cnt);
1249
1250   return d->vector[idx];
1251 }
1252
1253 /* Returns the number of vectors in D. */
1254 size_t
1255 dict_get_vector_cnt (const struct dictionary *d)
1256 {
1257   assert (d != NULL);
1258
1259   return d->vector_cnt;
1260 }
1261
1262 /* Looks up and returns the vector within D with the given
1263    NAME. */
1264 const struct vector *
1265 dict_lookup_vector (const struct dictionary *d, const char *name)
1266 {
1267   size_t i;
1268   for (i = 0; i < d->vector_cnt; i++)
1269     if (!strcasecmp (vector_get_name (d->vector[i]), name))
1270       return d->vector[i];
1271   return NULL;
1272 }
1273
1274 /* Deletes all vectors from D. */
1275 void
1276 dict_clear_vectors (struct dictionary *d)
1277 {
1278   size_t i;
1279
1280   for (i = 0; i < d->vector_cnt; i++)
1281     vector_destroy (d->vector[i]);
1282   free (d->vector);
1283
1284   d->vector = NULL;
1285   d->vector_cnt = 0;
1286 }
1287
1288 /* Called from variable.c to notify the dictionary that some property of
1289    the variable has changed */
1290 void
1291 dict_var_changed (const struct variable *v)
1292 {
1293   if ( var_has_vardict (v))
1294     {
1295       const struct vardict_info *vdi = var_get_vardict (v);
1296       struct dictionary *d = vdi->dict;
1297
1298       if ( d->callbacks && d->callbacks->var_changed )
1299         d->callbacks->var_changed (d, var_get_dict_index (v), d->cb_data);
1300     }
1301 }
1302
1303
1304 /* Called from variable.c to notify the dictionary that the variable's width
1305    has changed */
1306 void
1307 dict_var_resized (const struct variable *v, int delta)
1308 {
1309   if ( var_has_vardict (v))
1310     {
1311       const struct vardict_info *vdi = var_get_vardict (v);
1312       struct dictionary *d;
1313
1314       d = vdi->dict;
1315
1316       dict_pad_values (d, var_get_case_index(v) + 1, delta);
1317
1318       if ( d->callbacks && d->callbacks->var_resized )
1319         d->callbacks->var_resized (d, var_get_dict_index (v), delta, d->cb_data);
1320     }
1321 }