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