dd5e6152f3f42a13bc4b7b71a848eb9caadd818b
[pspp] / src / data / variable.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010 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 #include "variable.h"
19
20 #include <stdlib.h>
21
22 #include <data/attributes.h>
23 #include <data/category.h>
24 #include <data/data-out.h>
25 #include <data/format.h>
26 #include <data/dictionary.h>
27 #include <data/identifier.h>
28 #include <data/missing-values.h>
29 #include <data/value-labels.h>
30 #include <data/vardict.h>
31
32 #include <libpspp/misc.h>
33 #include <libpspp/assertion.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/hash.h>
36 #include <libpspp/message.h>
37 #include <libpspp/str.h>
38
39 #include "minmax.h"
40 #include "xalloc.h"
41
42 #include "gettext.h"
43 #define _(msgid) gettext (msgid)
44
45 /* A variable. */
46 struct variable
47   {
48     /* Dictionary information. */
49     char name[VAR_NAME_LEN + 1]; /* Variable name.  Mixed case. */
50     int width;                  /* 0 for numeric, otherwise string width. */
51     struct missing_values miss; /* Missing values. */
52     struct fmt_spec print;      /* Default format for PRINT. */
53     struct fmt_spec write;      /* Default format for WRITE. */
54     struct val_labs *val_labs;  /* Value labels. */
55     char *label;                /* Variable label. */
56
57     /* GUI information. */
58     enum measure measure;       /* Nominal, ordinal, or continuous. */
59     int display_width;          /* Width of data editor column. */
60     enum alignment alignment;   /* Alignment of data in GUI. */
61
62     /* Case information. */
63     bool leave;                 /* Leave value from case to case? */
64
65     /* Data for use by containing dictionary. */
66     struct vardict_info vardict;
67
68     /* Used only for system and portable file input and output.
69        See short-names.h. */
70     char **short_names;
71     size_t short_name_cnt;
72
73     /* Each command may use these fields as needed. */
74     void *aux;
75     void (*aux_dtor) (struct variable *);
76
77     /* Values of a categorical variable.  Procedures need
78        vectors with binary entries, so any variable of type ALPHA will
79        have its values stored here. */
80     struct cat_vals *obs_vals;
81
82     /* Custom attributes. */
83     struct attrset attributes;
84   };
85 \f
86 /* Creates and returns a new variable with the given NAME and
87    WIDTH and other fields initialized to default values.  The
88    variable is not added to a dictionary; for that, use
89    dict_create_var instead. */
90 struct variable *
91 var_create (const char *name, int width)
92 {
93   struct variable *v;
94   enum val_type type;
95
96   assert (width >= 0 && width <= MAX_STRING);
97
98   v = xmalloc (sizeof *v);
99   v->vardict.dict_index = v->vardict.case_index = -1;
100   var_set_name (v, name);
101   v->width = width;
102   mv_init (&v->miss, width);
103   v->leave = var_must_leave (v);
104   type = val_type_from_width (width);
105   v->alignment = var_default_alignment (type);
106   v->measure = var_default_measure (type);
107   v->display_width = var_default_display_width (width);
108   v->print = v->write = var_default_formats (width);
109   v->val_labs = NULL;
110   v->label = NULL;
111   v->short_names = NULL;
112   v->short_name_cnt = 0;
113   v->aux = NULL;
114   v->aux_dtor = NULL;
115   v->obs_vals = NULL;
116   attrset_init (&v->attributes);
117
118   return v;
119 }
120
121 /* Creates and returns a clone of OLD_VAR.  Most properties of
122    the new variable are copied from OLD_VAR, except:
123
124     - The variable's short name is not copied, because there is
125       no reason to give a new variable with potentially a new
126       name the same short name.
127
128     - The new variable is not added to OLD_VAR's dictionary by
129       default.  Use dict_clone_var, instead, to do that.
130
131     - Auxiliary data and obs_vals are not copied. */
132 struct variable *
133 var_clone (const struct variable *old_var)
134 {
135   struct variable *new_var = var_create (var_get_name (old_var),
136                                          var_get_width (old_var));
137
138   var_set_missing_values (new_var, var_get_missing_values (old_var));
139   var_set_print_format (new_var, var_get_print_format (old_var));
140   var_set_write_format (new_var, var_get_write_format (old_var));
141   var_set_value_labels (new_var, var_get_value_labels (old_var));
142   var_set_label (new_var, var_get_label (old_var));
143   var_set_measure (new_var, var_get_measure (old_var));
144   var_set_display_width (new_var, var_get_display_width (old_var));
145   var_set_alignment (new_var, var_get_alignment (old_var));
146   var_set_leave (new_var, var_get_leave (old_var));
147   var_set_attributes (new_var, var_get_attributes (old_var));
148
149   return new_var;
150 }
151
152 /* Destroys variable V.
153    V must not belong to a dictionary.  If it does, use
154    dict_delete_var instead. */
155 void
156 var_destroy (struct variable *v)
157 {
158   if (v != NULL)
159     {
160       assert (!var_has_vardict (v));
161       mv_destroy (&v->miss);
162       cat_stored_values_destroy (v->obs_vals);
163       var_clear_short_names (v);
164       var_clear_aux (v);
165       val_labs_destroy (v->val_labs);
166       var_clear_label (v);
167       free (v);
168     }
169 }
170 \f
171 /* Variable names. */
172
173 /* Return variable V's name. */
174 const char *
175 var_get_name (const struct variable *v)
176 {
177   return v->name;
178 }
179
180 /* Sets V's name to NAME.
181    Do not use this function for a variable in a dictionary.  Use
182    dict_rename_var instead. */
183 void
184 var_set_name (struct variable *v, const char *name)
185 {
186   assert (v->vardict.dict_index == -1);
187   assert (var_is_plausible_name (name, false));
188
189   str_copy_trunc (v->name, sizeof v->name, name);
190   dict_var_changed (v);
191 }
192
193 /* Returns true if NAME is an acceptable name for a variable,
194    false otherwise.  If ISSUE_ERROR is true, issues an
195    explanatory error message on failure. */
196 bool
197 var_is_valid_name (const char *name, bool issue_error)
198 {
199   bool plausible;
200   size_t length, i;
201
202   assert (name != NULL);
203
204   /* Note that strlen returns number of BYTES, not the number of
205      CHARACTERS */
206   length = strlen (name);
207
208   plausible = var_is_plausible_name(name, issue_error);
209
210   if ( ! plausible )
211     return false;
212
213
214   if (!lex_is_id1 (name[0]))
215     {
216       if (issue_error)
217         msg (SE, _("Character `%c' (in %s) may not appear "
218                    "as the first character in a variable name."),
219              name[0], name);
220       return false;
221     }
222
223
224   for (i = 0; i < length; i++)
225     {
226     if (!lex_is_idn (name[i]))
227       {
228         if (issue_error)
229           msg (SE, _("Character `%c' (in %s) may not appear in "
230                      "a variable name."),
231                name[i], name);
232         return false;
233       }
234     }
235
236   return true;
237 }
238
239 /* Returns true if NAME is an plausible name for a variable,
240    false otherwise.  If ISSUE_ERROR is true, issues an
241    explanatory error message on failure.
242    This function makes no use of LC_CTYPE.
243 */
244 bool
245 var_is_plausible_name (const char *name, bool issue_error)
246 {
247   size_t length;
248
249   assert (name != NULL);
250
251   /* Note that strlen returns number of BYTES, not the number of
252      CHARACTERS */
253   length = strlen (name);
254   if (length < 1)
255     {
256       if (issue_error)
257         msg (SE, _("Variable name cannot be empty string."));
258       return false;
259     }
260   else if (length > VAR_NAME_LEN)
261     {
262       if (issue_error)
263         msg (SE, _("Variable name %s exceeds %d-character limit."),
264              name, (int) VAR_NAME_LEN);
265       return false;
266     }
267
268   if (lex_id_to_token (ss_cstr (name)) != T_ID)
269     {
270       if (issue_error)
271         msg (SE, _("`%s' may not be used as a variable name because it "
272                    "is a reserved word."), name);
273       return false;
274     }
275
276   return true;
277 }
278
279 /* Returns VAR's dictionary class. */
280 enum dict_class
281 var_get_dict_class (const struct variable *var)
282 {
283   return dict_class_from_id (var->name);
284 }
285
286 /* A hsh_compare_func that orders variables A and B by their
287    names. */
288 int
289 compare_vars_by_name (const void *a_, const void *b_, const void *aux UNUSED)
290 {
291   const struct variable *a = a_;
292   const struct variable *b = b_;
293
294   return strcasecmp (a->name, b->name);
295 }
296
297 /* A hsh_hash_func that hashes variable V based on its name. */
298 unsigned
299 hash_var_by_name (const void *v_, const void *aux UNUSED)
300 {
301   const struct variable *v = v_;
302
303   return hash_case_string (v->name, 0);
304 }
305
306 /* A hsh_compare_func that orders pointers to variables A and B
307    by their names. */
308 int
309 compare_var_ptrs_by_name (const void *a_, const void *b_,
310                           const void *aux UNUSED)
311 {
312   struct variable *const *a = a_;
313   struct variable *const *b = b_;
314
315   return strcasecmp (var_get_name (*a), var_get_name (*b));
316 }
317
318 /* A hsh_compare_func that orders pointers to variables A and B
319    by their dictionary indexes. */
320 int
321 compare_var_ptrs_by_dict_index (const void *a_, const void *b_,
322                                 const void *aux UNUSED)
323 {
324   struct variable *const *a = a_;
325   struct variable *const *b = b_;
326   size_t a_index = var_get_dict_index (*a);
327   size_t b_index = var_get_dict_index (*b);
328
329   return a_index < b_index ? -1 : a_index > b_index;
330 }
331
332 /* A hsh_hash_func that hashes pointer to variable V based on its
333    name. */
334 unsigned
335 hash_var_ptr_by_name (const void *v_, const void *aux UNUSED)
336 {
337   struct variable *const *v = v_;
338
339   return hash_case_string (var_get_name (*v), 0);
340 }
341 \f
342 /* Returns the type of variable V. */
343 enum val_type
344 var_get_type (const struct variable *v)
345 {
346   return val_type_from_width (v->width);
347 }
348
349 /* Returns the width of variable V. */
350 int
351 var_get_width (const struct variable *v)
352 {
353   return v->width;
354 }
355
356 /* Changes the width of V to NEW_WIDTH.
357    This function should be used cautiously. */
358 void
359 var_set_width (struct variable *v, int new_width)
360 {
361   const int old_width = v->width;
362
363   if (old_width == new_width)
364     return;
365
366   if (mv_is_resizable (&v->miss, new_width))
367     mv_resize (&v->miss, new_width);
368   else
369     {
370       mv_destroy (&v->miss);
371       mv_init (&v->miss, new_width);
372     }
373
374   if (v->val_labs != NULL)
375     {
376       if (val_labs_can_set_width (v->val_labs, new_width))
377         val_labs_set_width (v->val_labs, new_width);
378       else
379         {
380           val_labs_destroy (v->val_labs);
381           v->val_labs = NULL;
382         }
383     }
384
385   fmt_resize (&v->print, new_width);
386   fmt_resize (&v->write, new_width);
387
388   v->width = new_width;
389   dict_var_resized (v, old_width);
390   dict_var_changed (v);
391 }
392
393 /* Returns true if variable V is numeric, false otherwise. */
394 bool
395 var_is_numeric (const struct variable *v)
396 {
397   return var_get_type (v) == VAL_NUMERIC;
398 }
399
400 /* Returns true if variable V is a string variable, false
401    otherwise. */
402 bool
403 var_is_alpha (const struct variable *v)
404 {
405   return var_get_type (v) == VAL_STRING;
406 }
407 \f
408 /* Returns variable V's missing values. */
409 const struct missing_values *
410 var_get_missing_values (const struct variable *v)
411 {
412   return &v->miss;
413 }
414
415 /* Sets variable V's missing values to MISS, which must be of V's
416    width or at least resizable to V's width.
417    If MISS is null, then V's missing values, if any, are
418    cleared. */
419 void
420 var_set_missing_values (struct variable *v, const struct missing_values *miss)
421 {
422   if (miss != NULL)
423     {
424       assert (mv_is_resizable (miss, v->width));
425       mv_destroy (&v->miss);
426       mv_copy (&v->miss, miss);
427       mv_resize (&v->miss, v->width);
428     }
429   else
430     mv_clear (&v->miss);
431
432   dict_var_changed (v);
433 }
434
435 /* Sets variable V to have no user-missing values. */
436 void
437 var_clear_missing_values (struct variable *v)
438 {
439   var_set_missing_values (v, NULL);
440 }
441
442 /* Returns true if V has any user-missing values,
443    false otherwise. */
444 bool
445 var_has_missing_values (const struct variable *v)
446 {
447   return !mv_is_empty (&v->miss);
448 }
449
450 /* Returns true if VALUE is in the given CLASS of missing values
451    in V, false otherwise. */
452 bool
453 var_is_value_missing (const struct variable *v, const union value *value,
454                       enum mv_class class)
455 {
456   return mv_is_value_missing (&v->miss, value, class);
457 }
458
459 /* Returns true if D is in the given CLASS of missing values in
460    V, false otherwise.
461    V must be a numeric variable. */
462 bool
463 var_is_num_missing (const struct variable *v, double d, enum mv_class class)
464 {
465   return mv_is_num_missing (&v->miss, d, class);
466 }
467
468 /* Returns true if S[] is a missing value for V, false otherwise.
469    S[] must contain exactly as many characters as V's width.
470    V must be a string variable. */
471 bool
472 var_is_str_missing (const struct variable *v, const uint8_t s[],
473                     enum mv_class class)
474 {
475   return mv_is_str_missing (&v->miss, s, class);
476 }
477 \f
478 /* Returns variable V's value labels,
479    possibly a null pointer if it has none. */
480 const struct val_labs *
481 var_get_value_labels (const struct variable *v)
482 {
483   return v->val_labs;
484 }
485
486 /* Returns true if variable V has at least one value label. */
487 bool
488 var_has_value_labels (const struct variable *v)
489 {
490   return val_labs_count (v->val_labs) > 0;
491 }
492
493 /* Sets variable V's value labels to a copy of VLS,
494    which must have a width equal to V's width or one that can be
495    changed to V's width.
496    If VLS is null, then V's value labels, if any, are removed. */
497 void
498 var_set_value_labels (struct variable *v, const struct val_labs *vls)
499 {
500   val_labs_destroy (v->val_labs);
501   v->val_labs = NULL;
502
503   if (vls != NULL)
504     {
505       assert (val_labs_can_set_width (vls, v->width));
506       v->val_labs = val_labs_clone (vls);
507       val_labs_set_width (v->val_labs, v->width);
508       dict_var_changed (v);
509     }
510 }
511
512 /* Makes sure that V has a set of value labels,
513    by assigning one to it if necessary. */
514 static void
515 alloc_value_labels (struct variable *v)
516 {
517   if (v->val_labs == NULL)
518     v->val_labs = val_labs_create (v->width);
519 }
520
521 /* Attempts to add a value label with the given VALUE and LABEL
522    to V.  Returns true if successful, false if VALUE has an
523    existing label or if V is a long string variable. */
524 bool
525 var_add_value_label (struct variable *v,
526                      const union value *value, const char *label)
527 {
528   alloc_value_labels (v);
529   return val_labs_add (v->val_labs, value, label);
530 }
531
532 /* Adds or replaces a value label with the given VALUE and LABEL
533    to V.
534    Has no effect if V is a long string variable. */
535 void
536 var_replace_value_label (struct variable *v,
537                          const union value *value, const char *label)
538 {
539   alloc_value_labels (v);
540   val_labs_replace (v->val_labs, value, label);
541 }
542
543 /* Removes V's value labels, if any. */
544 void
545 var_clear_value_labels (struct variable *v)
546 {
547   var_set_value_labels (v, NULL);
548 }
549
550 /* Returns the label associated with VALUE for variable V,
551    or a null pointer if none. */
552 const char *
553 var_lookup_value_label (const struct variable *v, const union value *value)
554 {
555   return val_labs_find (v->val_labs, value);
556 }
557
558 /* Append STR with a string representing VALUE for variable V.
559    That is, if VALUE has a label, append that label,
560    otherwise format VALUE and append the formatted string.
561    STR must be a pointer to an initialised struct string.
562 */
563 void
564 var_append_value_name (const struct variable *v, const union value *value,
565                        struct string *str)
566 {
567   const char *name = var_lookup_value_label (v, value);
568   if (name == NULL)
569     {
570       char *s = data_out (value, var_get_encoding (v), &v->print);
571       ds_put_cstr (str, s);
572       free (s);
573     }
574   else
575     ds_put_cstr (str, name);
576 }
577 \f
578 /* Print and write formats. */
579
580 /* Returns V's print format specification. */
581 const struct fmt_spec *
582 var_get_print_format (const struct variable *v)
583 {
584   return &v->print;
585 }
586
587 /* Sets V's print format specification to PRINT, which must be a
588    valid format specification for a variable of V's width
589    (ordinarily an output format, but input formats are not
590    rejected). */
591 void
592 var_set_print_format (struct variable *v, const struct fmt_spec *print)
593 {
594   assert (fmt_check_width_compat (print, v->width));
595   v->print = *print;
596   dict_var_changed (v);
597 }
598
599 /* Returns V's write format specification. */
600 const struct fmt_spec *
601 var_get_write_format (const struct variable *v)
602 {
603   return &v->write;
604 }
605
606 /* Sets V's write format specification to WRITE, which must be a
607    valid format specification for a variable of V's width
608    (ordinarily an output format, but input formats are not
609    rejected). */
610 void
611 var_set_write_format (struct variable *v, const struct fmt_spec *write)
612 {
613   assert (fmt_check_width_compat (write, v->width));
614   v->write = *write;
615   dict_var_changed (v);
616 }
617
618 /* Sets V's print and write format specifications to FORMAT,
619    which must be a valid format specification for a variable of
620    V's width (ordinarily an output format, but input formats are
621    not rejected). */
622 void
623 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
624 {
625   var_set_print_format (v, format);
626   var_set_write_format (v, format);
627 }
628
629 /* Returns the default print and write format for a variable of
630    the given TYPE, as set by var_create.  The return value can be
631    used to reset a variable's print and write formats to the
632    default. */
633 struct fmt_spec
634 var_default_formats (int width)
635 {
636   return (width == 0
637           ? fmt_for_output (FMT_F, 8, 2)
638           : fmt_for_output (FMT_A, width, 0));
639 }
640 \f
641 /* Return a string representing this variable, in the form most
642    appropriate from a human factors perspective, that is, its
643    variable label if it has one, otherwise its name. */
644 const char *
645 var_to_string (const struct variable *v)
646 {
647   return v->label != NULL ? v->label : v->name;
648 }
649
650 /* Returns V's variable label, or a null pointer if it has none. */
651 const char *
652 var_get_label (const struct variable *v)
653 {
654   return v->label;
655 }
656
657 /* Sets V's variable label to LABEL, stripping off leading and
658    trailing white space and truncating to 255 characters.
659    If LABEL is a null pointer or if LABEL is an empty string
660    (after stripping white space), then V's variable label (if
661    any) is removed. */
662 void
663 var_set_label (struct variable *v, const char *label)
664 {
665   free (v->label);
666   v->label = NULL;
667
668   if (label != NULL)
669     {
670       struct substring s = ss_cstr (label);
671       ss_trim (&s, ss_cstr (CC_SPACES));
672       ss_truncate (&s, 255);
673       if (!ss_is_empty (s))
674         v->label = ss_xstrdup (s);
675     }
676   dict_var_changed (v);
677 }
678
679 /* Removes any variable label from V. */
680 void
681 var_clear_label (struct variable *v)
682 {
683   var_set_label (v, NULL);
684 }
685
686 /* Returns true if V has a variable V,
687    false otherwise. */
688 bool
689 var_has_label (const struct variable *v)
690 {
691   return v->label != NULL;
692 }
693 \f
694 /* Returns true if M is a valid variable measurement level,
695    false otherwise. */
696 bool
697 measure_is_valid (enum measure m)
698 {
699   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
700 }
701
702 /* Returns V's measurement level. */
703 enum measure
704 var_get_measure (const struct variable *v)
705 {
706   return v->measure;
707 }
708
709 /* Sets V's measurement level to MEASURE. */
710 void
711 var_set_measure (struct variable *v, enum measure measure)
712 {
713   assert (measure_is_valid (measure));
714   v->measure = measure;
715   dict_var_changed (v);
716 }
717
718 /* Returns the default measurement level for a variable of the
719    given TYPE, as set by var_create.  The return value can be
720    used to reset a variable's measurement level to the
721    default. */
722 enum measure
723 var_default_measure (enum val_type type)
724 {
725   return type == VAL_NUMERIC ? MEASURE_SCALE : MEASURE_NOMINAL;
726 }
727 \f
728 /* Returns V's display width, which applies only to GUIs. */
729 int
730 var_get_display_width (const struct variable *v)
731 {
732   return v->display_width;
733 }
734
735 /* Sets V's display width to DISPLAY_WIDTH. */
736 void
737 var_set_display_width (struct variable *v, int new_width)
738 {
739   int old_width = v->display_width;
740
741   v->display_width = new_width;
742
743   if ( old_width != new_width)
744     dict_var_display_width_changed (v);
745
746   dict_var_changed (v);
747 }
748
749 /* Returns the default display width for a variable of the given
750    WIDTH, as set by var_create.  The return value can be used to
751    reset a variable's display width to the default. */
752 int
753 var_default_display_width (int width)
754 {
755   return width == 0 ? 8 : MIN (width, 32);
756 }
757 \f
758 /* Returns true if A is a valid alignment,
759    false otherwise. */
760 bool
761 alignment_is_valid (enum alignment a)
762 {
763   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
764 }
765
766 /* Returns V's display alignment, which applies only to GUIs. */
767 enum alignment
768 var_get_alignment (const struct variable *v)
769 {
770   return v->alignment;
771 }
772
773 /* Sets V's display alignment to ALIGNMENT. */
774 void
775 var_set_alignment (struct variable *v, enum alignment alignment)
776 {
777   assert (alignment_is_valid (alignment));
778   v->alignment = alignment;
779   dict_var_changed (v);
780 }
781
782 /* Returns the default display alignment for a variable of the
783    given TYPE, as set by var_create.  The return value can be
784    used to reset a variable's display alignment to the default. */
785 enum alignment
786 var_default_alignment (enum val_type type)
787 {
788   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
789 }
790 \f
791 /* Whether variables' values should be preserved from case to
792    case. */
793
794 /* Returns true if variable V's value should be left from case to
795    case, instead of being reset to system-missing or blanks. */
796 bool
797 var_get_leave (const struct variable *v)
798 {
799   return v->leave;
800 }
801
802 /* Sets V's leave setting to LEAVE. */
803 void
804 var_set_leave (struct variable *v, bool leave)
805 {
806   assert (leave || !var_must_leave (v));
807   v->leave = leave;
808   dict_var_changed (v);
809 }
810
811 /* Returns true if V must be left from case to case,
812    false if it can be set either way. */
813 bool
814 var_must_leave (const struct variable *v)
815 {
816   return var_get_dict_class (v) == DC_SCRATCH;
817 }
818 \f
819 /* Returns the number of short names stored in VAR.
820
821    Short names are used only for system and portable file input
822    and output.  They are upper-case only, not necessarily unique,
823    and limited to SHORT_NAME_LEN characters (plus a null
824    terminator).  Ordinarily a variable has at most one short
825    name, but very long string variables (longer than 255 bytes)
826    may have more.  A variable might not have any short name at
827    all if it hasn't been saved to or read from a system or
828    portable file. */
829 size_t
830 var_get_short_name_cnt (const struct variable *var) 
831 {
832   return var->short_name_cnt;
833 }
834
835 /* Returns VAR's short name with the given IDX, if it has one
836    with that index, or a null pointer otherwise.  Short names may
837    be sparse: even if IDX is less than the number of short names
838    in VAR, this function may return a null pointer. */
839 const char *
840 var_get_short_name (const struct variable *var, size_t idx)
841 {
842   return idx < var->short_name_cnt ? var->short_names[idx] : NULL;
843 }
844
845 /* Sets VAR's short name with the given IDX to SHORT_NAME,
846    truncating it to SHORT_NAME_LEN characters and converting it
847    to uppercase in the process.  Specifying a null pointer for
848    SHORT_NAME clears the specified short name. */
849 void
850 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
851 {
852   assert (var != NULL);
853   assert (short_name == NULL || var_is_plausible_name (short_name, false));
854
855   /* Clear old short name numbered IDX, if any. */
856   if (idx < var->short_name_cnt) 
857     {
858       free (var->short_names[idx]);
859       var->short_names[idx] = NULL; 
860     }
861
862   /* Install new short name for IDX. */
863   if (short_name != NULL) 
864     {
865       if (idx >= var->short_name_cnt)
866         {
867           size_t old_cnt = var->short_name_cnt;
868           size_t i;
869           var->short_name_cnt = MAX (idx * 2, 1);
870           var->short_names = xnrealloc (var->short_names, var->short_name_cnt,
871                                         sizeof *var->short_names);
872           for (i = old_cnt; i < var->short_name_cnt; i++)
873             var->short_names[i] = NULL;
874         }
875       var->short_names[idx] = xstrndup (short_name, MAX_SHORT_STRING);
876       str_uppercase (var->short_names[idx]);
877     }
878
879   dict_var_changed (var);
880 }
881
882 /* Clears V's short names. */
883 void
884 var_clear_short_names (struct variable *v)
885 {
886   size_t i;
887
888   for (i = 0; i < v->short_name_cnt; i++)
889     free (v->short_names[i]);
890   free (v->short_names);
891   v->short_names = NULL;
892   v->short_name_cnt = 0;
893 }
894 \f
895 /* Relationship with dictionary. */
896
897 /* Returns V's index within its dictionary, the value
898    for which "dict_get_var (dict, index)" will return V.
899    V must be in a dictionary. */
900 size_t
901 var_get_dict_index (const struct variable *v)
902 {
903   assert (v->vardict.dict_index != -1);
904   return v->vardict.dict_index;
905 }
906
907 /* Returns V's index within the case represented by its
908    dictionary, that is, the value for which "case_data_idx (case,
909    index)" will return the data for V in that case.
910    V must be in a dictionary. */
911 size_t
912 var_get_case_index (const struct variable *v)
913 {
914   assert (v->vardict.case_index != -1);
915   return v->vardict.case_index;
916 }
917 \f
918 /* Returns V's auxiliary data, or a null pointer if none has been
919    attached. */
920 void *
921 var_get_aux (const struct variable *v)
922 {
923   return v->aux;
924 }
925
926 /* Assign auxiliary data AUX to variable V, which must not
927    already have auxiliary data.  Before V's auxiliary data is
928    cleared, AUX_DTOR(V) will be called.  (var_dtor_free, below,
929    may be appropriate for use as AUX_DTOR.) */
930 void *
931 var_attach_aux (const struct variable *v_,
932                 void *aux, void (*aux_dtor) (struct variable *))
933 {
934   struct variable *v = CONST_CAST (struct variable *, v_);
935   assert (v->aux == NULL);
936   assert (aux != NULL);
937   v->aux = aux;
938   v->aux_dtor = aux_dtor;
939   return aux;
940 }
941
942 /* Remove auxiliary data, if any, from V, and return it, without
943    calling any associated destructor. */
944 void *
945 var_detach_aux (struct variable *v)
946 {
947   void *aux = v->aux;
948   assert (aux != NULL);
949   v->aux = NULL;
950   return aux;
951 }
952
953 /* Clears auxiliary data, if any, from V, and calls any
954    associated destructor. */
955 void
956 var_clear_aux (struct variable *v)
957 {
958   assert (v != NULL);
959   if (v->aux != NULL)
960     {
961       if (v->aux_dtor != NULL)
962         v->aux_dtor (v);
963       v->aux = NULL;
964     }
965 }
966
967 /* This function is appropriate for use an auxiliary data
968    destructor (passed as AUX_DTOR to var_attach_aux()) for the
969    case where the auxiliary data should be passed to free(). */
970 void
971 var_dtor_free (struct variable *v)
972 {
973   free (v->aux);
974 }
975 \f
976 /* Observed categorical values. */
977
978 /* Returns V's observed categorical values,
979    which V must have. */
980 struct cat_vals *
981 var_get_obs_vals (const struct variable *v)
982 {
983   assert (v->obs_vals != NULL);
984   return v->obs_vals;
985 }
986
987 /* Sets V's observed categorical values to CAT_VALS.
988    V becomes the owner of CAT_VALS. */
989 void
990 var_set_obs_vals (const struct variable *v_, struct cat_vals *cat_vals)
991 {
992   struct variable *v = CONST_CAST (struct variable *, v_ );
993   cat_stored_values_destroy (v->obs_vals);
994   v->obs_vals = cat_vals;
995 }
996
997 /* Returns true if V has observed categorical values,
998    false otherwise. */
999 bool
1000 var_has_obs_vals (const struct variable *v)
1001 {
1002   return v->obs_vals != NULL;
1003 }
1004 \f
1005 /* Returns variable V's attribute set.  The caller may examine or
1006    modify the attribute set, but must not destroy it.  Destroying
1007    V, or calling var_set_attributes() on V, will also destroy its
1008    attribute set. */
1009 struct attrset *
1010 var_get_attributes (const struct variable *v) 
1011 {
1012   return CONST_CAST (struct attrset *, &v->attributes);
1013 }
1014
1015 /* Replaces variable V's attributes set by a copy of ATTRS. */
1016 void
1017 var_set_attributes (struct variable *v, const struct attrset *attrs) 
1018 {
1019   attrset_destroy (&v->attributes);
1020   attrset_clone (&v->attributes, attrs);
1021 }
1022
1023 /* Returns true if V has any custom attributes, false if it has none. */
1024 bool
1025 var_has_attributes (const struct variable *v)
1026 {
1027   return attrset_count (&v->attributes) > 0;
1028 }
1029 \f
1030 /* Returns the encoding of values of variable VAR.  (This is actually a
1031    property of the dictionary.)  Returns null if no specific encoding has been
1032    set.  */
1033 const char *
1034 var_get_encoding (const struct variable *var)
1035 {
1036   return var_has_vardict (var) ? dict_get_encoding (var->vardict.dict) : NULL;
1037 }
1038 \f
1039 /* Returns V's vardict structure. */
1040 const struct vardict_info *
1041 var_get_vardict (const struct variable *v)
1042 {
1043   assert (var_has_vardict (v));
1044   return &v->vardict;
1045 }
1046
1047 /* Sets V's vardict data to VARDICT. */
1048 void
1049 var_set_vardict (struct variable *v, const struct vardict_info *vardict)
1050 {
1051   assert (vardict->dict_index >= 0);
1052   assert (vardict->case_index >= 0);
1053   assert (vardict->dict != NULL);
1054   v->vardict = *vardict;
1055 }
1056
1057 /* Returns true if V has vardict data. */
1058 bool
1059 var_has_vardict (const struct variable *v)
1060 {
1061   return v->vardict.dict_index != -1;
1062 }
1063
1064 /* Clears V's vardict data. */
1065 void
1066 var_clear_vardict (struct variable *v)
1067 {
1068   v->vardict.dict_index = v->vardict.case_index = -1;
1069 }