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