Change "union value" to dynamically allocate long strings.
[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 to be used for internal calculations only.
153    The variable is assigned a unique dictionary index and a case
154    index of CASE_IDX. */
155 struct variable *
156 var_create_internal (int case_idx)
157 {
158   struct variable *v = var_create ("$internal", 0);
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       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     mv_init (&v->miss, new_width);
394
395   if (v->val_labs != NULL)
396     {
397       if (val_labs_can_set_width (v->val_labs, new_width))
398         val_labs_set_width (v->val_labs, new_width);
399       else
400         {
401           val_labs_destroy (v->val_labs);
402           v->val_labs = NULL;
403         }
404     }
405
406   fmt_resize (&v->print, new_width);
407   fmt_resize (&v->write, new_width);
408
409   v->width = new_width;
410   dict_var_resized (v, old_width);
411   dict_var_changed (v);
412 }
413
414 /* Returns true if variable V is numeric, false otherwise. */
415 bool
416 var_is_numeric (const struct variable *v)
417 {
418   return var_get_type (v) == VAL_NUMERIC;
419 }
420
421 /* Returns true if variable V is a string variable, false
422    otherwise. */
423 bool
424 var_is_alpha (const struct variable *v)
425 {
426   return var_get_type (v) == VAL_STRING;
427 }
428
429 /* Returns true if variable V is a short string variable, false
430    otherwise. */
431 bool
432 var_is_short_string (const struct variable *v)
433 {
434   return v->width > 0 && v->width <= MAX_SHORT_STRING;
435 }
436
437 /* Returns true if variable V is a long string variable, false
438    otherwise. */
439 bool
440 var_is_long_string (const struct variable *v)
441 {
442   return v->width > MAX_SHORT_STRING;
443 }
444 \f
445 /* Returns variable V's missing values. */
446 const struct missing_values *
447 var_get_missing_values (const struct variable *v)
448 {
449   return &v->miss;
450 }
451
452 /* Sets variable V's missing values to MISS, which must be of V's
453    width or at least resizable to V's width.
454    If MISS is null, then V's missing values, if any, are
455    cleared. */
456 void
457 var_set_missing_values (struct variable *v, const struct missing_values *miss)
458 {
459   if (miss != NULL)
460     {
461       assert (mv_is_resizable (miss, v->width));
462       mv_copy (&v->miss, miss);
463       mv_resize (&v->miss, v->width);
464     }
465   else
466     mv_init (&v->miss, v->width);
467
468   dict_var_changed (v);
469 }
470
471 /* Sets variable V to have no user-missing values. */
472 void
473 var_clear_missing_values (struct variable *v)
474 {
475   var_set_missing_values (v, NULL);
476 }
477
478 /* Returns true if V has any user-missing values,
479    false otherwise. */
480 bool
481 var_has_missing_values (const struct variable *v)
482 {
483   return !mv_is_empty (&v->miss);
484 }
485
486 /* Returns true if VALUE is in the given CLASS of missing values
487    in V, false otherwise. */
488 bool
489 var_is_value_missing (const struct variable *v, const union value *value,
490                       enum mv_class class)
491 {
492   return mv_is_value_missing (&v->miss, value, class);
493 }
494
495 /* Returns true if D is in the given CLASS of missing values in
496    V, false otherwise.
497    V must be a numeric variable. */
498 bool
499 var_is_num_missing (const struct variable *v, double d, enum mv_class class)
500 {
501   return mv_is_num_missing (&v->miss, d, class);
502 }
503
504 /* Returns true if S[] is a missing value for V, false otherwise.
505    S[] must contain exactly as many characters as V's width.
506    V must be a string variable. */
507 bool
508 var_is_str_missing (const struct variable *v, const char s[],
509                     enum mv_class class)
510 {
511   return mv_is_str_missing (&v->miss, s, class);
512 }
513 \f
514 /* Returns variable V's value labels,
515    possibly a null pointer if it has none. */
516 const struct val_labs *
517 var_get_value_labels (const struct variable *v)
518 {
519   return v->val_labs;
520 }
521
522 /* Returns true if variable V has at least one value label. */
523 bool
524 var_has_value_labels (const struct variable *v)
525 {
526   return val_labs_count (v->val_labs) > 0;
527 }
528
529 /* Sets variable V's value labels to a copy of VLS,
530    which must have a width equal to V's width or one that can be
531    changed to V's width.
532    If VLS is null, then V's value labels, if any, are removed. */
533 void
534 var_set_value_labels (struct variable *v, const struct val_labs *vls)
535 {
536   val_labs_destroy (v->val_labs);
537   v->val_labs = NULL;
538
539   if (vls != NULL)
540     {
541       assert (val_labs_can_set_width (vls, v->width));
542       v->val_labs = val_labs_clone (vls);
543       val_labs_set_width (v->val_labs, v->width);
544       dict_var_changed (v);
545     }
546 }
547
548 /* Makes sure that V has a set of value labels,
549    by assigning one to it if necessary. */
550 static void
551 alloc_value_labels (struct variable *v)
552 {
553   assert (!var_is_long_string (v));
554   if (v->val_labs == NULL)
555     v->val_labs = val_labs_create (v->width);
556 }
557
558 /* Attempts to add a value label with the given VALUE and LABEL
559    to V.  Returns true if successful, false if VALUE has an
560    existing label or if V is a long string variable. */
561 bool
562 var_add_value_label (struct variable *v,
563                      const union value *value, const char *label)
564 {
565   alloc_value_labels (v);
566   return val_labs_add (v->val_labs, value, label);
567 }
568
569 /* Adds or replaces a value label with the given VALUE and LABEL
570    to V.
571    Has no effect if V is a long string variable. */
572 void
573 var_replace_value_label (struct variable *v,
574                          const union value *value, const char *label)
575 {
576   alloc_value_labels (v);
577   val_labs_replace (v->val_labs, value, label);
578 }
579
580 /* Removes V's value labels, if any. */
581 void
582 var_clear_value_labels (struct variable *v)
583 {
584   var_set_value_labels (v, NULL);
585 }
586
587 /* Returns the label associated with VALUE for variable V,
588    or a null pointer if none. */
589 const char *
590 var_lookup_value_label (const struct variable *v, const union value *value)
591 {
592   return val_labs_find (v->val_labs, value);
593 }
594
595 /* Append STR with a string representing VALUE for variable V.
596    That is, if VALUE has a label, append that label,
597    otherwise format VALUE and append the formatted string.
598    STR must be a pointer to an initialised struct string.
599 */
600 void
601 var_append_value_name (const struct variable *v, const union value *value,
602                        struct string *str)
603 {
604   const char *name = var_lookup_value_label (v, value);
605   if (name == NULL)
606     {
607       char *s = ds_put_uninit (str, v->print.w);
608       data_out (value, &v->print, s);
609     }
610   else
611     ds_put_cstr (str, name);
612 }
613 \f
614 /* Print and write formats. */
615
616 /* Returns V's print format specification. */
617 const struct fmt_spec *
618 var_get_print_format (const struct variable *v)
619 {
620   return &v->print;
621 }
622
623 /* Sets V's print format specification to PRINT, which must be a
624    valid format specification for a variable of V's width
625    (ordinarily an output format, but input formats are not
626    rejected). */
627 void
628 var_set_print_format (struct variable *v, const struct fmt_spec *print)
629 {
630   assert (fmt_check_width_compat (print, v->width));
631   v->print = *print;
632   dict_var_changed (v);
633 }
634
635 /* Returns V's write format specification. */
636 const struct fmt_spec *
637 var_get_write_format (const struct variable *v)
638 {
639   return &v->write;
640 }
641
642 /* Sets V's write format specification to WRITE, which must be a
643    valid format specification for a variable of V's width
644    (ordinarily an output format, but input formats are not
645    rejected). */
646 void
647 var_set_write_format (struct variable *v, const struct fmt_spec *write)
648 {
649   assert (fmt_check_width_compat (write, v->width));
650   v->write = *write;
651   dict_var_changed (v);
652 }
653
654 /* Sets V's print and write format specifications to FORMAT,
655    which must be a valid format specification for a variable of
656    V's width (ordinarily an output format, but input formats are
657    not rejected). */
658 void
659 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
660 {
661   var_set_print_format (v, format);
662   var_set_write_format (v, format);
663 }
664
665 /* Returns the default print and write format for a variable of
666    the given TYPE, as set by var_create.  The return value can be
667    used to reset a variable's print and write formats to the
668    default. */
669 struct fmt_spec
670 var_default_formats (int width)
671 {
672   return (width == 0
673           ? fmt_for_output (FMT_F, 8, 2)
674           : fmt_for_output (FMT_A, width, 0));
675 }
676 \f
677 /* Return a string representing this variable, in the form most
678    appropriate from a human factors perspective, that is, its
679    variable label if it has one, otherwise its name. */
680 const char *
681 var_to_string (const struct variable *v)
682 {
683   return v->label != NULL ? v->label : v->name;
684 }
685
686 /* Returns V's variable label, or a null pointer if it has none. */
687 const char *
688 var_get_label (const struct variable *v)
689 {
690   return v->label;
691 }
692
693 /* Sets V's variable label to LABEL, stripping off leading and
694    trailing white space and truncating to 255 characters.
695    If LABEL is a null pointer or if LABEL is an empty string
696    (after stripping white space), then V's variable label (if
697    any) is removed. */
698 void
699 var_set_label (struct variable *v, const char *label)
700 {
701   free (v->label);
702   v->label = NULL;
703
704   if (label != NULL)
705     {
706       struct substring s = ss_cstr (label);
707       ss_trim (&s, ss_cstr (CC_SPACES));
708       ss_truncate (&s, 255);
709       if (!ss_is_empty (s))
710         v->label = ss_xstrdup (s);
711     }
712   dict_var_changed (v);
713 }
714
715 /* Removes any variable label from V. */
716 void
717 var_clear_label (struct variable *v)
718 {
719   var_set_label (v, NULL);
720 }
721
722 /* Returns true if V has a variable V,
723    false otherwise. */
724 bool
725 var_has_label (const struct variable *v)
726 {
727   return v->label != NULL;
728 }
729 \f
730 /* Returns true if M is a valid variable measurement level,
731    false otherwise. */
732 bool
733 measure_is_valid (enum measure m)
734 {
735   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
736 }
737
738 /* Returns V's measurement level. */
739 enum measure
740 var_get_measure (const struct variable *v)
741 {
742   return v->measure;
743 }
744
745 /* Sets V's measurement level to MEASURE. */
746 void
747 var_set_measure (struct variable *v, enum measure measure)
748 {
749   assert (measure_is_valid (measure));
750   v->measure = measure;
751   dict_var_changed (v);
752 }
753
754 /* Returns the default measurement level for a variable of the
755    given TYPE, as set by var_create.  The return value can be
756    used to reset a variable's measurement level to the
757    default. */
758 enum measure
759 var_default_measure (enum val_type type)
760 {
761   return type == VAL_NUMERIC ? MEASURE_SCALE : MEASURE_NOMINAL;
762 }
763 \f
764 /* Returns V's display width, which applies only to GUIs. */
765 int
766 var_get_display_width (const struct variable *v)
767 {
768   return v->display_width;
769 }
770
771 /* Sets V's display width to DISPLAY_WIDTH. */
772 void
773 var_set_display_width (struct variable *v, int new_width)
774 {
775   int old_width = v->display_width;
776
777   v->display_width = new_width;
778
779   if ( old_width != new_width)
780     dict_var_display_width_changed (v);
781
782   dict_var_changed (v);
783 }
784
785 /* Returns the default display width for a variable of the given
786    WIDTH, as set by var_create.  The return value can be used to
787    reset a variable's display width to the default. */
788 int
789 var_default_display_width (int width)
790 {
791   return width == 0 ? 8 : MIN (width, 32);
792 }
793 \f
794 /* Returns true if A is a valid alignment,
795    false otherwise. */
796 bool
797 alignment_is_valid (enum alignment a)
798 {
799   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
800 }
801
802 /* Returns V's display alignment, which applies only to GUIs. */
803 enum alignment
804 var_get_alignment (const struct variable *v)
805 {
806   return v->alignment;
807 }
808
809 /* Sets V's display alignment to ALIGNMENT. */
810 void
811 var_set_alignment (struct variable *v, enum alignment alignment)
812 {
813   assert (alignment_is_valid (alignment));
814   v->alignment = alignment;
815   dict_var_changed (v);
816 }
817
818 /* Returns the default display alignment for a variable of the
819    given TYPE, as set by var_create.  The return value can be
820    used to reset a variable's display alignment to the default. */
821 enum alignment
822 var_default_alignment (enum val_type type)
823 {
824   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
825 }
826 \f
827 /* Whether variables' values should be preserved from case to
828    case. */
829
830 /* Returns true if variable V's value should be left from case to
831    case, instead of being reset to system-missing or blanks. */
832 bool
833 var_get_leave (const struct variable *v)
834 {
835   return v->leave;
836 }
837
838 /* Sets V's leave setting to LEAVE. */
839 void
840 var_set_leave (struct variable *v, bool leave)
841 {
842   assert (leave || !var_must_leave (v));
843   v->leave = leave;
844   dict_var_changed (v);
845 }
846
847 /* Returns true if V must be left from case to case,
848    false if it can be set either way. */
849 bool
850 var_must_leave (const struct variable *v)
851 {
852   return var_get_dict_class (v) == DC_SCRATCH;
853 }
854 \f
855 /* Returns the number of short names stored in VAR.
856
857    Short names are used only for system and portable file input
858    and output.  They are upper-case only, not necessarily unique,
859    and limited to SHORT_NAME_LEN characters (plus a null
860    terminator).  Ordinarily a variable has at most one short
861    name, but very long string variables (longer than 255 bytes)
862    may have more.  A variable might not have any short name at
863    all if it hasn't been saved to or read from a system or
864    portable file. */
865 size_t
866 var_get_short_name_cnt (const struct variable *var) 
867 {
868   return var->short_name_cnt;
869 }
870
871 /* Returns VAR's short name with the given IDX, if it has one
872    with that index, or a null pointer otherwise.  Short names may
873    be sparse: even if IDX is less than the number of short names
874    in VAR, this function may return a null pointer. */
875 const char *
876 var_get_short_name (const struct variable *var, size_t idx)
877 {
878   return idx < var->short_name_cnt ? var->short_names[idx] : NULL;
879 }
880
881 /* Sets VAR's short name with the given IDX to SHORT_NAME,
882    truncating it to SHORT_NAME_LEN characters and converting it
883    to uppercase in the process.  Specifying a null pointer for
884    SHORT_NAME clears the specified short name. */
885 void
886 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
887 {
888   assert (var != NULL);
889   assert (short_name == NULL || var_is_plausible_name (short_name, false));
890
891   /* Clear old short name numbered IDX, if any. */
892   if (idx < var->short_name_cnt) 
893     {
894       free (var->short_names[idx]);
895       var->short_names[idx] = NULL; 
896     }
897
898   /* Install new short name for IDX. */
899   if (short_name != NULL) 
900     {
901       if (idx >= var->short_name_cnt)
902         {
903           size_t old_cnt = var->short_name_cnt;
904           size_t i;
905           var->short_name_cnt = MAX (idx * 2, 1);
906           var->short_names = xnrealloc (var->short_names, var->short_name_cnt,
907                                         sizeof *var->short_names);
908           for (i = old_cnt; i < var->short_name_cnt; i++)
909             var->short_names[i] = NULL;
910         }
911       var->short_names[idx] = xstrndup (short_name, MAX_SHORT_STRING);
912       str_uppercase (var->short_names[idx]);
913     }
914
915   dict_var_changed (var);
916 }
917
918 /* Clears V's short names. */
919 void
920 var_clear_short_names (struct variable *v)
921 {
922   size_t i;
923
924   for (i = 0; i < v->short_name_cnt; i++)
925     free (v->short_names[i]);
926   free (v->short_names);
927   v->short_names = NULL;
928   v->short_name_cnt = 0;
929 }
930 \f
931 /* Relationship with dictionary. */
932
933 /* Returns V's index within its dictionary, the value
934    for which "dict_get_var (dict, index)" will return V.
935    V must be in a dictionary. */
936 size_t
937 var_get_dict_index (const struct variable *v)
938 {
939   assert (v->vardict.dict_index != -1);
940   return v->vardict.dict_index;
941 }
942
943 /* Returns V's index within the case represented by its
944    dictionary, that is, the value for which "case_data_idx (case,
945    index)" will return the data for V in that case.
946    V must be in a dictionary. */
947 size_t
948 var_get_case_index (const struct variable *v)
949 {
950   assert (v->vardict.case_index != -1);
951   return v->vardict.case_index;
952 }
953 \f
954 /* Returns V's auxiliary data, or a null pointer if none has been
955    attached. */
956 void *
957 var_get_aux (const struct variable *v)
958 {
959   return v->aux;
960 }
961
962 /* Assign auxiliary data AUX to variable V, which must not
963    already have auxiliary data.  Before V's auxiliary data is
964    cleared, AUX_DTOR(V) will be called.  (var_dtor_free, below,
965    may be appropriate for use as AUX_DTOR.) */
966 void *
967 var_attach_aux (const struct variable *v_,
968                 void *aux, void (*aux_dtor) (struct variable *))
969 {
970   struct variable *v = (struct variable *) v_ ; /* cast away const  */
971   assert (v->aux == NULL);
972   assert (aux != NULL);
973   v->aux = aux;
974   v->aux_dtor = aux_dtor;
975   return aux;
976 }
977
978 /* Remove auxiliary data, if any, from V, and return it, without
979    calling any associated destructor. */
980 void *
981 var_detach_aux (struct variable *v)
982 {
983   void *aux = v->aux;
984   assert (aux != NULL);
985   v->aux = NULL;
986   return aux;
987 }
988
989 /* Clears auxiliary data, if any, from V, and calls any
990    associated destructor. */
991 void
992 var_clear_aux (struct variable *v)
993 {
994   assert (v != NULL);
995   if (v->aux != NULL)
996     {
997       if (v->aux_dtor != NULL)
998         v->aux_dtor (v);
999       v->aux = NULL;
1000     }
1001 }
1002
1003 /* This function is appropriate for use an auxiliary data
1004    destructor (passed as AUX_DTOR to var_attach_aux()) for the
1005    case where the auxiliary data should be passed to free(). */
1006 void
1007 var_dtor_free (struct variable *v)
1008 {
1009   free (v->aux);
1010 }
1011 \f
1012 /* Observed categorical values. */
1013
1014 /* Returns V's observed categorical values,
1015    which V must have. */
1016 struct cat_vals *
1017 var_get_obs_vals (const struct variable *v)
1018 {
1019   assert (v->obs_vals != NULL);
1020   return v->obs_vals;
1021 }
1022
1023 /* Sets V's observed categorical values to CAT_VALS.
1024    V becomes the owner of CAT_VALS. */
1025 void
1026 var_set_obs_vals (const struct variable *v_, struct cat_vals *cat_vals)
1027 {
1028   struct variable *v = (struct variable *) v_ ; /* cast away const */
1029   cat_stored_values_destroy (v->obs_vals);
1030   v->obs_vals = cat_vals;
1031 }
1032
1033 /* Returns true if V has observed categorical values,
1034    false otherwise. */
1035 bool
1036 var_has_obs_vals (const struct variable *v)
1037 {
1038   return v->obs_vals != NULL;
1039 }
1040 \f
1041 /* Returns variable V's attribute set.  The caller may examine or
1042    modify the attribute set, but must not destroy it.  Destroying
1043    V, or calling var_set_attributes() on V, will also destroy its
1044    attribute set. */
1045 struct attrset *
1046 var_get_attributes (const struct variable *v) 
1047 {
1048   return (struct attrset *) &v->attributes;
1049 }
1050
1051 /* Replaces variable V's attributes set by a copy of ATTRS. */
1052 void
1053 var_set_attributes (struct variable *v, const struct attrset *attrs) 
1054 {
1055   attrset_destroy (&v->attributes);
1056   attrset_clone (&v->attributes, attrs);
1057 }
1058
1059 /* Returns true if V has any custom attributes, false if it has none. */
1060 bool
1061 var_has_attributes (const struct variable *v)
1062 {
1063   return attrset_count (&v->attributes) > 0;
1064 }
1065 \f
1066 /* Returns V's vardict structure. */
1067 const struct vardict_info *
1068 var_get_vardict (const struct variable *v)
1069 {
1070   assert (var_has_vardict (v));
1071   return &v->vardict;
1072 }
1073
1074 /* Sets V's vardict data to VARDICT. */
1075 void
1076 var_set_vardict (struct variable *v, const struct vardict_info *vardict)
1077 {
1078   assert (vardict->dict_index >= 0);
1079   assert (vardict->case_index >= 0);
1080   v->vardict = *vardict;
1081 }
1082
1083 /* Returns true if V has vardict data. */
1084 bool
1085 var_has_vardict (const struct variable *v)
1086 {
1087   return v->vardict.dict_index != -1;
1088 }
1089
1090 /* Clears V's vardict data. */
1091 void
1092 var_clear_vardict (struct variable *v)
1093 {
1094   v->vardict.dict_index = v->vardict.case_index = -1;
1095 }