Introduce reference counting for variables.
[pspp] / src / data / variable.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012, 2013,
3    2014, 2016, 2020 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 #include "data/variable.h"
21
22 #include <stdlib.h>
23
24 #include "data/attributes.h"
25 #include "data/data-out.h"
26 #include "data/dictionary.h"
27 #include "data/format.h"
28 #include "data/identifier.h"
29 #include "data/missing-values.h"
30 #include "data/settings.h"
31 #include "data/value-labels.h"
32 #include "data/vardict.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/compiler.h"
35 #include "libpspp/hash-functions.h"
36 #include "libpspp/i18n.h"
37 #include "libpspp/message.h"
38 #include "libpspp/misc.h"
39 #include "libpspp/str.h"
40
41 #include "gl/minmax.h"
42 #include "gl/xalloc.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46 #define N_(msgid) (msgid)
47
48 /* This should follow the definition in Gtk */
49 typedef struct
50 {
51   int value;
52   const char *name;
53   const char *label;
54 } GEnumValue;
55
56 const GEnumValue align[] =
57   {
58     {ALIGN_LEFT,   "left", N_("Left")},
59     {ALIGN_RIGHT,  "right", N_("Right")},
60     {ALIGN_CENTRE, "center", N_("Center")},
61     {0,0,0}
62   };
63
64 const GEnumValue measure[] =
65   {
66     {MEASURE_NOMINAL, "nominal", N_("Nominal")},
67     {MEASURE_ORDINAL, "ordinal", N_("Ordinal")},
68     {MEASURE_SCALE,   "scale", N_("Scale")},
69     {0,0,0}
70   };
71
72 const GEnumValue role[] =
73   {
74     {ROLE_INPUT,  "input",    N_("Input")},
75     {ROLE_TARGET, "output",   N_("Output")},
76     {ROLE_BOTH,   "both",     N_("Both")},
77     {ROLE_NONE,   "none",     N_("None")},
78     {ROLE_PARTITION, "partition", N_("Partition")},
79     {ROLE_SPLIT,  "split",    N_("Split")},
80     {0,0,0}
81   };
82
83 /* A variable. */
84 struct variable
85   {
86     int ref_cnt;
87     /* Dictionary information. */
88     char *name;                 /* Variable name.  Mixed case. */
89     int width;                  /* 0 for numeric, otherwise string width. */
90     struct missing_values miss; /* Missing values. */
91     struct fmt_spec print;      /* Default format for PRINT. */
92     struct fmt_spec write;      /* Default format for WRITE. */
93     struct val_labs *val_labs;  /* Value labels. */
94     char *label;                /* Variable label. */
95     struct string name_and_label; /* The name and label in the same string */
96
97     /* GUI information. */
98     enum measure measure;       /* Nominal, ordinal, or continuous. */
99     enum var_role role;         /* Intended use. */
100     int display_width;          /* Width of data editor column. */
101     enum alignment alignment;   /* Alignment of data in GUI. */
102
103     /* Case information. */
104     bool leave;                 /* Leave value from case to case? */
105
106     /* Data for use by containing dictionary. */
107     struct vardict_info *vardict;
108
109     /* Used only for system and portable file input and output.
110        See short-names.h. */
111     char **short_names;
112     size_t short_name_cnt;
113
114     /* Custom attributes. */
115     struct attrset attributes;
116   };
117 \f
118
119 static void var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print);
120 static void var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write);
121 static void var_set_label_quiet (struct variable *v, const char *label);
122 static void var_set_name_quiet (struct variable *v, const char *name);
123
124 /* Creates and returns a new variable with the given NAME and
125    WIDTH and other fields initialized to default values.  The
126    variable is not added to a dictionary; for that, use
127    dict_create_var instead. */
128 struct variable *
129 var_create (const char *name, int width)
130 {
131   struct variable *v;
132   enum val_type type;
133
134   assert (width >= 0 && width <= MAX_STRING);
135
136   v = xzalloc (sizeof *v);
137   var_set_name_quiet (v, name);
138   v->width = width;
139   mv_init (&v->miss, width);
140   v->leave = var_must_leave (v);
141   type = val_type_from_width (width);
142   v->alignment = var_default_alignment (type);
143   v->measure = var_default_measure (type);
144   v->role = ROLE_INPUT;
145   v->display_width = var_default_display_width (width);
146   v->print = v->write = var_default_formats (width);
147   attrset_init (&v->attributes);
148   ds_init_empty (&v->name_and_label);
149
150   v->ref_cnt = 1;
151
152   return v;
153 }
154
155 /* Destroys variable V.
156    V must not belong to a dictionary.  If it does, use
157    dict_delete_var instead. */
158 static void
159 var_destroy__ (struct variable *v)
160 {
161   assert (!var_has_vardict (v));
162   mv_destroy (&v->miss);
163   var_clear_short_names (v);
164   val_labs_destroy (v->val_labs);
165   var_set_label_quiet (v, NULL);
166   attrset_destroy (var_get_attributes (v));
167   free (v->name);
168   ds_destroy (&v->name_and_label);
169   free (v);
170 }
171
172 struct variable *
173 var_ref (struct variable *v)
174 {
175   v->ref_cnt++;
176   return v;
177 }
178
179 void
180 var_unref (struct variable *v)
181 {
182   if (--v->ref_cnt == 0)
183     var_destroy__ (v);
184 }
185
186
187 \f
188 /* Variable names. */
189
190 /* Return variable V's name, as a UTF-8 encoded string. */
191 const char *
192 var_get_name (const struct variable *v)
193 {
194   return v->name;
195 }
196
197
198
199 /* Sets V's name to NAME, a UTF-8 encoded string.
200    Do not use this function for a variable in a dictionary.  Use
201    dict_rename_var instead. */
202 static void
203 var_set_name_quiet (struct variable *v, const char *name)
204 {
205   assert (!var_has_vardict (v));
206
207   free (v->name);
208   v->name = xstrdup (name);
209   ds_destroy (&v->name_and_label);
210   ds_init_empty (&v->name_and_label);
211 }
212
213 /* Sets V's name to NAME, a UTF-8 encoded string.
214    Do not use this function for a variable in a dictionary.  Use
215    dict_rename_var instead. */
216 void
217 var_set_name (struct variable *v, const char *name)
218 {
219   struct variable *ov = var_clone (v);
220   var_set_name_quiet (v, name);
221   dict_var_changed (v, VAR_TRAIT_NAME, ov);
222 }
223
224 /* Returns VAR's dictionary class. */
225 enum dict_class
226 var_get_dict_class (const struct variable *var)
227 {
228   return dict_class_from_id (var->name);
229 }
230
231 /* A hsh_compare_func that orders variables A and B by their
232    names. */
233 int
234 compare_vars_by_name (const void *a_, const void *b_, const void *aux UNUSED)
235 {
236   const struct variable *a = a_;
237   const struct variable *b = b_;
238
239   return utf8_strcasecmp (a->name, b->name);
240 }
241
242 /* A hsh_hash_func that hashes variable V based on its name. */
243 unsigned
244 hash_var_by_name (const void *v_, const void *aux UNUSED)
245 {
246   const struct variable *v = v_;
247
248   return utf8_hash_case_string (v->name, 0);
249 }
250
251 /* A hsh_compare_func that orders pointers to variables A and B
252    by their names. */
253 int
254 compare_var_ptrs_by_name (const void *a_, const void *b_,
255                           const void *aux UNUSED)
256 {
257   struct variable *const *a = a_;
258   struct variable *const *b = b_;
259
260   return utf8_strcasecmp (var_get_name (*a), var_get_name (*b));
261 }
262
263 /* A hsh_compare_func that orders pointers to variables A and B
264    by their dictionary indexes. */
265 int
266 compare_var_ptrs_by_dict_index (const void *a_, const void *b_,
267                                 const void *aux UNUSED)
268 {
269   struct variable *const *a = a_;
270   struct variable *const *b = b_;
271   size_t a_index = var_get_dict_index (*a);
272   size_t b_index = var_get_dict_index (*b);
273
274   return a_index < b_index ? -1 : a_index > b_index;
275 }
276
277 /* A hsh_hash_func that hashes pointer to variable V based on its
278    name. */
279 unsigned
280 hash_var_ptr_by_name (const void *v_, const void *aux UNUSED)
281 {
282   struct variable *const *v = v_;
283
284   return utf8_hash_case_string (var_get_name (*v), 0);
285 }
286 \f
287 /* Returns the type of variable V. */
288 enum val_type
289 var_get_type (const struct variable *v)
290 {
291   return val_type_from_width (v->width);
292 }
293
294 /* Returns the width of variable V. */
295 int
296 var_get_width (const struct variable *v)
297 {
298   return v->width;
299 }
300
301 void
302 var_set_width_and_formats (struct variable *v, int new_width,
303                            const struct fmt_spec *print, const struct fmt_spec *write)
304 {
305   struct variable *ov;
306   unsigned int traits = 0;
307
308   ov = var_clone (v);
309
310   if (var_has_missing_values (v))
311     {
312       if (mv_is_resizable (&v->miss, new_width))
313         mv_resize (&v->miss, new_width);
314       else
315         {
316           mv_destroy (&v->miss);
317           mv_init (&v->miss, new_width);
318         }
319       traits |= VAR_TRAIT_MISSING_VALUES;
320     }
321
322   if (v->val_labs != NULL)
323     {
324       if (val_labs_can_set_width (v->val_labs, new_width))
325         val_labs_set_width (v->val_labs, new_width);
326       else
327         {
328           val_labs_destroy (v->val_labs);
329           v->val_labs = NULL;
330         }
331       traits |= VAR_TRAIT_VALUE_LABELS;
332     }
333
334   if (fmt_resize (&v->print, new_width))
335     traits |= VAR_TRAIT_PRINT_FORMAT;
336
337   if (fmt_resize (&v->write, new_width))
338     traits |= VAR_TRAIT_WRITE_FORMAT;
339
340   if (v->width != new_width)
341     {
342       v->width = new_width;
343       traits |= VAR_TRAIT_WIDTH;
344     }
345
346   if (print)
347     {
348       var_set_print_format_quiet (v, print);
349       traits |= VAR_TRAIT_PRINT_FORMAT;
350     }
351
352   if (write)
353     {
354       var_set_write_format_quiet (v, write);
355       traits |= VAR_TRAIT_WRITE_FORMAT;
356     }
357
358   if (traits != 0)
359     dict_var_changed (v, traits, ov);
360 }
361
362 /* Changes the width of V to NEW_WIDTH.
363    This function should be used cautiously. */
364 void
365 var_set_width (struct variable *v, int new_width)
366 {
367   const int old_width = v->width;
368
369   if (old_width == new_width)
370     return;
371
372   var_set_width_and_formats (v, new_width, NULL, NULL);
373 }
374
375
376
377
378 /* Returns true if variable V is numeric, false otherwise. */
379 bool
380 var_is_numeric (const struct variable *v)
381 {
382   return var_get_type (v) == VAL_NUMERIC;
383 }
384
385 /* Returns true if variable V is a string variable, false
386    otherwise. */
387 bool
388 var_is_alpha (const struct variable *v)
389 {
390   return var_get_type (v) == VAL_STRING;
391 }
392 \f
393 /* Returns variable V's missing values. */
394 const struct missing_values *
395 var_get_missing_values (const struct variable *v)
396 {
397   return &v->miss;
398 }
399
400 /* Sets variable V's missing values to MISS, which must be of V's
401    width or at least resizable to V's width.
402    If MISS is null, then V's missing values, if any, are
403    cleared. */
404 static void
405 var_set_missing_values_quiet (struct variable *v, const struct missing_values *miss)
406 {
407   if (miss != NULL)
408     {
409       assert (mv_is_resizable (miss, v->width));
410       mv_destroy (&v->miss);
411       mv_copy (&v->miss, miss);
412       mv_resize (&v->miss, v->width);
413     }
414   else
415     mv_clear (&v->miss);
416 }
417
418 /* Sets variable V's missing values to MISS, which must be of V's
419    width or at least resizable to V's width.
420    If MISS is null, then V's missing values, if any, are
421    cleared. */
422 void
423 var_set_missing_values (struct variable *v, const struct missing_values *miss)
424 {
425   struct variable *ov = var_clone (v);
426   var_set_missing_values_quiet (v, miss);
427   dict_var_changed (v, VAR_TRAIT_MISSING_VALUES, ov);
428 }
429
430 /* Sets variable V to have no user-missing values. */
431 void
432 var_clear_missing_values (struct variable *v)
433 {
434   var_set_missing_values (v, NULL);
435 }
436
437 /* Returns true if V has any user-missing values,
438    false otherwise. */
439 bool
440 var_has_missing_values (const struct variable *v)
441 {
442   return !mv_is_empty (&v->miss);
443 }
444
445 /* Returns true if VALUE is in the given CLASS of missing values
446    in V, false otherwise. */
447 bool
448 var_is_value_missing (const struct variable *v, const union value *value,
449                       enum mv_class class)
450 {
451   return mv_is_value_missing (&v->miss, value, class);
452 }
453
454 /* Returns true if D is in the given CLASS of missing values in
455    V, false otherwise.
456    V must be a numeric variable. */
457 bool
458 var_is_num_missing (const struct variable *v, double d, enum mv_class class)
459 {
460   return mv_is_num_missing (&v->miss, d, class);
461 }
462
463 /* Returns true if S[] is a missing value for V, false otherwise.
464    S[] must contain exactly as many characters as V's width.
465    V must be a string variable. */
466 bool
467 var_is_str_missing (const struct variable *v, const uint8_t s[],
468                     enum mv_class class)
469 {
470   return mv_is_str_missing (&v->miss, s, class);
471 }
472 \f
473 /* Returns variable V's value labels,
474    possibly a null pointer if it has none. */
475 const struct val_labs *
476 var_get_value_labels (const struct variable *v)
477 {
478   return v->val_labs;
479 }
480
481 /* Returns true if variable V has at least one value label. */
482 bool
483 var_has_value_labels (const struct variable *v)
484 {
485   return val_labs_count (v->val_labs) > 0;
486 }
487
488 /* Sets variable V's value labels to a copy of VLS,
489    which must have a width equal to V's width or one that can be
490    changed to V's width.
491    If VLS is null, then V's value labels, if any, are removed. */
492 static void
493 var_set_value_labels_quiet (struct variable *v, const struct val_labs *vls)
494 {
495   val_labs_destroy (v->val_labs);
496   v->val_labs = NULL;
497
498   if (vls != NULL)
499     {
500       assert (val_labs_can_set_width (vls, v->width));
501       v->val_labs = val_labs_clone (vls);
502       val_labs_set_width (v->val_labs, v->width);
503     }
504 }
505
506
507 /* Sets variable V's value labels to a copy of VLS,
508    which must have a width equal to V's width or one that can be
509    changed to V's width.
510    If VLS is null, then V's value labels, if any, are removed. */
511 void
512 var_set_value_labels (struct variable *v, const struct val_labs *vls)
513 {
514   struct variable *ov = var_clone (v);
515   var_set_value_labels_quiet (v, vls);
516   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
517 }
518
519
520 /* Makes sure that V has a set of value labels,
521    by assigning one to it if necessary. */
522 static void
523 alloc_value_labels (struct variable *v)
524 {
525   if (v->val_labs == NULL)
526     v->val_labs = val_labs_create (v->width);
527 }
528
529 /* Attempts to add a value label with the given VALUE and UTF-8 encoded LABEL
530    to V.  Returns true if successful, false otherwise (probably due to an
531    existing label).
532
533    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
534 bool
535 var_add_value_label (struct variable *v,
536                      const union value *value, const char *label)
537 {
538   alloc_value_labels (v);
539   return val_labs_add (v->val_labs, value, label);
540 }
541
542 /* Adds or replaces a value label with the given VALUE and UTF-8 encoded LABEL
543    to V.
544
545    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
546 void
547 var_replace_value_label (struct variable *v,
548                          const union value *value, const char *label)
549 {
550   alloc_value_labels (v);
551   val_labs_replace (v->val_labs, value, label);
552 }
553
554 /* Removes V's value labels, if any. */
555 void
556 var_clear_value_labels (struct variable *v)
557 {
558   var_set_value_labels (v, NULL);
559 }
560
561 /* Returns the label associated with VALUE for variable V, as a UTF-8 string in
562    a format suitable for output, or a null pointer if none. */
563 const char *
564 var_lookup_value_label (const struct variable *v, const union value *value)
565 {
566   return val_labs_find (v->val_labs, value);
567 }
568
569 /*
570    Append to STR the string representation of VALUE for variable V.
571    STR must be a pointer to an initialised struct string.
572 */
573 static void
574 append_value (const struct variable *v, const union value *value,
575               struct string *str)
576 {
577   char *s = data_out (value, var_get_encoding (v), &v->print);
578   struct substring ss = ss_cstr (s);
579   ss_rtrim (&ss, ss_cstr (" "));
580   ds_put_substring (str, ss);
581   free (s);
582 }
583
584 void
585 var_append_value_name__ (const struct variable *v, const union value *value,
586                          enum settings_value_show show, struct string *str)
587 {
588   const char *label = var_lookup_value_label (v, value);
589
590   switch (show)
591     {
592     case SETTINGS_VALUE_SHOW_VALUE:
593       append_value (v, value, str);
594       break;
595
596     default:
597     case SETTINGS_VALUE_SHOW_LABEL:
598       if (label)
599         ds_put_cstr (str, label);
600       else
601         append_value (v, value, str);
602       break;
603
604     case SETTINGS_VALUE_SHOW_BOTH:
605       append_value (v, value, str);
606       if (label != NULL)
607         ds_put_format (str, " %s", label);
608       break;
609     }
610 }
611
612 /* Append STR with a string representing VALUE for variable V.
613    That is, if VALUE has a label, append that label,
614    otherwise format VALUE and append the formatted string.
615    STR must be a pointer to an initialised struct string.
616 */
617 void
618 var_append_value_name (const struct variable *v, const union value *value,
619                        struct string *str)
620 {
621   var_append_value_name__ (v, value, settings_get_show_values (), str);
622 }
623 \f
624 /* Print and write formats. */
625
626 /* Returns V's print format specification. */
627 const struct fmt_spec *
628 var_get_print_format (const struct variable *v)
629 {
630   return &v->print;
631 }
632
633 /* Sets V's print format specification to PRINT, which must be a
634    valid format specification for a variable of V's width
635    (ordinarily an output format, but input formats are not
636    rejected). */
637 static void
638 var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print)
639 {
640   if (!fmt_equal (&v->print, print))
641     {
642       assert (fmt_check_width_compat (print, v->width));
643       v->print = *print;
644     }
645 }
646
647 /* Sets V's print format specification to PRINT, which must be a
648    valid format specification for a variable of V's width
649    (ordinarily an output format, but input formats are not
650    rejected). */
651 void
652 var_set_print_format (struct variable *v, const struct fmt_spec *print)
653 {
654   struct variable *ov = var_clone (v);
655   var_set_print_format_quiet (v, print);
656   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT, ov);
657 }
658
659 /* Returns V's write format specification. */
660 const struct fmt_spec *
661 var_get_write_format (const struct variable *v)
662 {
663   return &v->write;
664 }
665
666 /* Sets V's write format specification to WRITE, which must be a
667    valid format specification for a variable of V's width
668    (ordinarily an output format, but input formats are not
669    rejected). */
670 static void
671 var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write)
672 {
673   if (!fmt_equal (&v->write, write))
674     {
675       assert (fmt_check_width_compat (write, v->width));
676       v->write = *write;
677     }
678 }
679
680 /* Sets V's write format specification to WRITE, which must be a
681    valid format specification for a variable of V's width
682    (ordinarily an output format, but input formats are not
683    rejected). */
684 void
685 var_set_write_format (struct variable *v, const struct fmt_spec *write)
686 {
687   struct variable *ov = var_clone (v);
688   var_set_write_format_quiet (v, write);
689   dict_var_changed (v, VAR_TRAIT_WRITE_FORMAT, ov);
690 }
691
692
693 /* Sets V's print and write format specifications to FORMAT,
694    which must be a valid format specification for a variable of
695    V's width (ordinarily an output format, but input formats are
696    not rejected). */
697 void
698 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
699 {
700   struct variable *ov = var_clone (v);
701   var_set_print_format_quiet (v, format);
702   var_set_write_format_quiet (v, format);
703   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT | VAR_TRAIT_WRITE_FORMAT, ov);
704 }
705
706 /* Returns the default print and write format for a variable of
707    the given TYPE, as set by var_create.  The return value can be
708    used to reset a variable's print and write formats to the
709    default. */
710 struct fmt_spec
711 var_default_formats (int width)
712 {
713   return (width == 0
714           ? fmt_for_output (FMT_F, 8, 2)
715           : fmt_for_output (FMT_A, width, 0));
716 }
717
718
719 \f
720
721 /* Update the combined name and label string if necessary */
722 static void
723 update_vl_string (const struct variable *v)
724 {
725   /* Cast away const! */
726   struct string *str = (struct string *) &v->name_and_label;
727
728   if (ds_is_empty (str))
729     {
730       if (v->label)
731         ds_put_format (str, _("%s (%s)"), v->label, v->name);
732       else
733         ds_put_cstr (str, v->name);
734     }
735 }
736
737
738 /* Return a string representing this variable, in the form most
739    appropriate from a human factors perspective, that is, its
740    variable label if it has one, otherwise its name. */
741 const char *
742 var_to_string (const struct variable *v)
743 {
744   switch (settings_get_show_variables ())
745     {
746     case SETTINGS_VALUE_SHOW_VALUE:
747       return v->name;
748
749     case SETTINGS_VALUE_SHOW_LABEL:
750     default:
751       return v->label != NULL ? v->label : v->name;
752
753     case SETTINGS_VALUE_SHOW_BOTH:
754       update_vl_string (v);
755       return ds_cstr (&v->name_and_label);
756     }
757 }
758
759 /* Returns V's variable label, or a null pointer if it has none. */
760 const char *
761 var_get_label (const struct variable *v)
762 {
763   return v->label;
764 }
765
766 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
767    and trailing white space.  If LABEL is a null pointer or if LABEL is an
768    empty string (after stripping white space), then V's variable label (if any)
769    is removed. */
770 static void
771 var_set_label_quiet (struct variable *v, const char *label)
772 {
773   free (v->label);
774   v->label = NULL;
775
776   if (label != NULL && label[strspn (label, CC_SPACES)])
777     v->label = xstrdup (label);
778
779   ds_destroy (&v->name_and_label);
780   ds_init_empty (&v->name_and_label);
781 }
782
783
784
785 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
786    and trailing white space.  If LABEL is a null pointer or if LABEL is an
787    empty string (after stripping white space), then V's variable label (if any)
788    is removed. */
789 void
790 var_set_label (struct variable *v, const char *label)
791 {
792   struct variable *ov = var_clone (v);
793   var_set_label_quiet (v, label);
794   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
795 }
796
797
798 /* Removes any variable label from V. */
799 void
800 var_clear_label (struct variable *v)
801 {
802   var_set_label (v, NULL);
803 }
804
805 /* Returns true if V has a variable V,
806    false otherwise. */
807 bool
808 var_has_label (const struct variable *v)
809 {
810   return v->label != NULL;
811 }
812 \f
813 /* Returns true if M is a valid variable measurement level,
814    false otherwise. */
815 bool
816 measure_is_valid (enum measure m)
817 {
818   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
819 }
820
821 /* Returns a string version of measurement level M, for display to a user.
822    The caller may translate the string by passing it to gettext(). */
823 const char *
824 measure_to_string (enum measure m)
825 {
826   assert (m == measure[m].value);
827   return measure[m].label;
828 }
829
830 /* Returns a string version of measurement level M, for use in PSPP command
831    syntax. */
832 const char *
833 measure_to_syntax (enum measure m)
834 {
835   switch (m)
836     {
837     case MEASURE_NOMINAL:
838       return "NOMINAL";
839
840     case MEASURE_ORDINAL:
841       return "ORDINAL";
842
843     case MEASURE_SCALE:
844       return "SCALE";
845
846     default:
847       return "Invalid";
848     }
849 }
850
851 /* Returns V's measurement level. */
852 enum measure
853 var_get_measure (const struct variable *v)
854 {
855   return v->measure;
856 }
857
858 /* Sets V's measurement level to MEASURE. */
859 static void
860 var_set_measure_quiet (struct variable *v, enum measure measure)
861 {
862   assert (measure_is_valid (measure));
863   v->measure = measure;
864 }
865
866
867 /* Sets V's measurement level to MEASURE. */
868 void
869 var_set_measure (struct variable *v, enum measure measure)
870 {
871   struct variable *ov = var_clone (v);
872   var_set_measure_quiet (v, measure);
873   dict_var_changed (v, VAR_TRAIT_MEASURE, ov);
874 }
875
876
877 /* Returns the default measurement level for a variable of the
878    given TYPE, as set by var_create.  The return value can be
879    used to reset a variable's measurement level to the
880    default. */
881 enum measure
882 var_default_measure (enum val_type type)
883 {
884   return type == VAL_NUMERIC ? MEASURE_SCALE : MEASURE_NOMINAL;
885 }
886 \f
887 /* Returns true if M is a valid variable role,
888    false otherwise. */
889 bool
890 var_role_is_valid (enum var_role role)
891 {
892   switch (role)
893     {
894     case ROLE_NONE:
895     case ROLE_INPUT:
896     case ROLE_TARGET:
897     case ROLE_BOTH:
898     case ROLE_PARTITION:
899     case ROLE_SPLIT:
900       return true;
901
902     default:
903       return false;
904     }
905 }
906
907 /* Returns a string version of ROLE, for display to a user.
908    The caller may translate the string by passing it to gettext(). */
909 const char *
910 var_role_to_string (enum var_role r)
911 {
912   assert (r == role[r].value);
913   return role[r].label;
914 }
915
916 /* Returns a string version of ROLE, for use in PSPP comamnd syntax. */
917 const char *
918 var_role_to_syntax (enum var_role role)
919 {
920   switch (role)
921     {
922     case ROLE_INPUT:
923       return "INPUT";
924
925     case ROLE_TARGET:
926       return "TARGET";
927
928     case ROLE_BOTH:
929       return "BOTH";
930
931     case ROLE_NONE:
932       return "NONE";
933
934     case ROLE_PARTITION:
935       return "PARTITION";
936
937     case ROLE_SPLIT:
938       return "SPLIT";
939
940     default:
941       return "<invalid>";
942     }
943 }
944
945 /* Returns V's role. */
946 enum var_role
947 var_get_role (const struct variable *v)
948 {
949   return v->role;
950 }
951
952 /* Sets V's role to ROLE. */
953 static void
954 var_set_role_quiet (struct variable *v, enum var_role role)
955 {
956   assert (var_role_is_valid (role));
957   v->role = role;
958 }
959
960
961 /* Sets V's role to ROLE. */
962 void
963 var_set_role (struct variable *v, enum var_role role)
964 {
965   struct variable *ov = var_clone (v);
966   var_set_role_quiet (v, role);
967   dict_var_changed (v, VAR_TRAIT_ROLE, ov);
968 }
969 \f
970 /* Returns V's display width, which applies only to GUIs. */
971 int
972 var_get_display_width (const struct variable *v)
973 {
974   return v->display_width;
975 }
976
977 /* Sets V's display width to DISPLAY_WIDTH. */
978 static void
979 var_set_display_width_quiet (struct variable *v, int new_width)
980 {
981   if (v->display_width != new_width)
982     {
983       v->display_width = new_width;
984     }
985 }
986
987 void
988 var_set_display_width (struct variable *v, int new_width)
989 {
990   if (v->display_width != new_width)
991     {
992       struct variable *ov = var_clone (v);
993       var_set_display_width_quiet (v, new_width);
994       dict_var_changed (v, VAR_TRAIT_DISPLAY_WIDTH, ov);
995     }
996 }
997
998 /* Returns the default display width for a variable of the given
999    WIDTH, as set by var_create.  The return value can be used to
1000    reset a variable's display width to the default. */
1001 int
1002 var_default_display_width (int width)
1003 {
1004   return width == 0 ? 8 : MIN (width, 32);
1005 }
1006 \f
1007 /* Returns true if A is a valid alignment,
1008    false otherwise. */
1009 bool
1010 alignment_is_valid (enum alignment a)
1011 {
1012   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
1013 }
1014
1015 /* Returns a string version of alignment A, for display to a user.
1016    The caller may translate the string by passing it to gettext(). */
1017 const char *
1018 alignment_to_string (enum alignment a)
1019 {
1020   assert (a == align[a].value);
1021   return align[a].label;
1022 }
1023
1024 /* Returns a string version of alignment A, for use in PSPP command syntax. */
1025 const char *
1026 alignment_to_syntax (enum alignment a)
1027 {
1028   switch (a)
1029     {
1030     case ALIGN_LEFT:
1031       return "LEFT";
1032
1033     case ALIGN_RIGHT:
1034       return "RIGHT";
1035
1036     case ALIGN_CENTRE:
1037       return "CENTER";
1038
1039     default:
1040       return "Invalid";
1041     }
1042 }
1043
1044 /* Returns V's display alignment, which applies only to GUIs. */
1045 enum alignment
1046 var_get_alignment (const struct variable *v)
1047 {
1048   return v->alignment;
1049 }
1050
1051 /* Sets V's display alignment to ALIGNMENT. */
1052 static void
1053 var_set_alignment_quiet (struct variable *v, enum alignment alignment)
1054 {
1055   assert (alignment_is_valid (alignment));
1056   v->alignment = alignment;
1057 }
1058
1059 /* Sets V's display alignment to ALIGNMENT. */
1060 void
1061 var_set_alignment (struct variable *v, enum alignment alignment)
1062 {
1063   struct variable *ov = var_clone (v);
1064   var_set_alignment_quiet (v, alignment);
1065   dict_var_changed (v, VAR_TRAIT_ALIGNMENT, ov);
1066 }
1067
1068
1069 /* Returns the default display alignment for a variable of the
1070    given TYPE, as set by var_create.  The return value can be
1071    used to reset a variable's display alignment to the default. */
1072 enum alignment
1073 var_default_alignment (enum val_type type)
1074 {
1075   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
1076 }
1077 \f
1078 /* Whether variables' values should be preserved from case to
1079    case. */
1080
1081 /* Returns true if variable V's value should be left from case to
1082    case, instead of being reset to system-missing or blanks. */
1083 bool
1084 var_get_leave (const struct variable *v)
1085 {
1086   return v->leave;
1087 }
1088
1089 /* Sets V's leave setting to LEAVE. */
1090 static void
1091 var_set_leave_quiet (struct variable *v, bool leave)
1092 {
1093   assert (leave || !var_must_leave (v));
1094   v->leave = leave;
1095 }
1096
1097
1098 /* Sets V's leave setting to LEAVE. */
1099 void
1100 var_set_leave (struct variable *v, bool leave)
1101 {
1102   struct variable *ov = var_clone (v);
1103   var_set_leave_quiet (v, leave);
1104   dict_var_changed (v, VAR_TRAIT_LEAVE, ov);
1105 }
1106
1107
1108 /* Returns true if V must be left from case to case,
1109    false if it can be set either way. */
1110 bool
1111 var_must_leave (const struct variable *v)
1112 {
1113   return var_get_dict_class (v) == DC_SCRATCH;
1114 }
1115 \f
1116 /* Returns the number of short names stored in VAR.
1117
1118    Short names are used only for system and portable file input
1119    and output.  They are upper-case only, not necessarily unique,
1120    and limited to SHORT_NAME_LEN characters (plus a null
1121    terminator).  Ordinarily a variable has at most one short
1122    name, but very long string variables (longer than 255 bytes)
1123    may have more.  A variable might not have any short name at
1124    all if it hasn't been saved to or read from a system or
1125    portable file. */
1126 size_t
1127 var_get_short_name_cnt (const struct variable *var)
1128 {
1129   return var->short_name_cnt;
1130 }
1131
1132 /* Returns VAR's short name with the given IDX, if it has one
1133    with that index, or a null pointer otherwise.  Short names may
1134    be sparse: even if IDX is less than the number of short names
1135    in VAR, this function may return a null pointer. */
1136 const char *
1137 var_get_short_name (const struct variable *var, size_t idx)
1138 {
1139   return idx < var->short_name_cnt ? var->short_names[idx] : NULL;
1140 }
1141
1142 /* Sets VAR's short name with the given IDX to the UTF-8 string SHORT_NAME.
1143    The caller must already have checked that, in the dictionary encoding,
1144    SHORT_NAME is no more than SHORT_NAME_LEN bytes long.  The new short name
1145    will be converted to uppercase.
1146
1147    Specifying a null pointer for SHORT_NAME clears the specified short name. */
1148 void
1149 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
1150 {
1151   struct variable *ov = var_clone (var);
1152
1153   /* Clear old short name numbered IDX, if any. */
1154   if (idx < var->short_name_cnt)
1155     {
1156       free (var->short_names[idx]);
1157       var->short_names[idx] = NULL;
1158     }
1159
1160   /* Install new short name for IDX. */
1161   if (short_name != NULL)
1162     {
1163       if (idx >= var->short_name_cnt)
1164         {
1165           size_t old_cnt = var->short_name_cnt;
1166           size_t i;
1167           var->short_name_cnt = MAX (idx * 2, 1);
1168           var->short_names = xnrealloc (var->short_names, var->short_name_cnt,
1169                                         sizeof *var->short_names);
1170           for (i = old_cnt; i < var->short_name_cnt; i++)
1171             var->short_names[i] = NULL;
1172         }
1173       var->short_names[idx] = utf8_to_upper (short_name);
1174     }
1175
1176   dict_var_changed (var, VAR_TRAIT_NAME, ov);
1177 }
1178
1179 /* Clears V's short names. */
1180 void
1181 var_clear_short_names (struct variable *v)
1182 {
1183   size_t i;
1184
1185   for (i = 0; i < v->short_name_cnt; i++)
1186     free (v->short_names[i]);
1187   free (v->short_names);
1188   v->short_names = NULL;
1189   v->short_name_cnt = 0;
1190 }
1191 \f
1192 /* Relationship with dictionary. */
1193
1194 /* Returns V's index within its dictionary, the value
1195    for which "dict_get_var (dict, index)" will return V.
1196    V must be in a dictionary. */
1197 size_t
1198 var_get_dict_index (const struct variable *v)
1199 {
1200   assert (var_has_vardict (v));
1201   return vardict_get_dict_index (v->vardict);
1202 }
1203
1204 /* Returns V's index within the case represented by its
1205    dictionary, that is, the value for which "case_data_idx (case,
1206    index)" will return the data for V in that case.
1207    V must be in a dictionary. */
1208 size_t
1209 var_get_case_index (const struct variable *v)
1210 {
1211   assert (var_has_vardict (v));
1212   return vardict_get_case_index (v->vardict);
1213 }
1214 \f
1215 /* Returns variable V's attribute set.  The caller may examine or
1216    modify the attribute set, but must not destroy it.  Destroying
1217    V, or calling var_set_attributes() on V, will also destroy its
1218    attribute set. */
1219 struct attrset *
1220 var_get_attributes (const struct variable *v)
1221 {
1222   return CONST_CAST (struct attrset *, &v->attributes);
1223 }
1224
1225 /* Replaces variable V's attributes set by a copy of ATTRS. */
1226 static void
1227 var_set_attributes_quiet (struct variable *v, const struct attrset *attrs)
1228 {
1229   attrset_destroy (&v->attributes);
1230   attrset_clone (&v->attributes, attrs);
1231 }
1232
1233 /* Replaces variable V's attributes set by a copy of ATTRS. */
1234 void
1235 var_set_attributes (struct variable *v, const struct attrset *attrs)
1236 {
1237   struct variable *ov = var_clone (v);
1238   var_set_attributes_quiet (v, attrs);
1239   dict_var_changed (v, VAR_TRAIT_ATTRIBUTES, ov);
1240 }
1241
1242
1243 /* Returns true if V has any custom attributes, false if it has none. */
1244 bool
1245 var_has_attributes (const struct variable *v)
1246 {
1247   return attrset_count (&v->attributes) > 0;
1248 }
1249 \f
1250
1251 /* Creates and returns a clone of OLD_VAR.  Most properties of
1252    the new variable are copied from OLD_VAR, except:
1253
1254     - The variable's short name is not copied, because there is
1255       no reason to give a new variable with potentially a new
1256       name the same short name.
1257
1258     - The new variable is not added to OLD_VAR's dictionary by
1259       default.  Use dict_clone_var, instead, to do that.
1260 */
1261 struct variable *
1262 var_clone (const struct variable *old_var)
1263 {
1264   struct variable *new_var = var_create (var_get_name (old_var),
1265                                          var_get_width (old_var));
1266
1267   var_set_missing_values_quiet (new_var, var_get_missing_values (old_var));
1268   var_set_print_format_quiet (new_var, var_get_print_format (old_var));
1269   var_set_write_format_quiet (new_var, var_get_write_format (old_var));
1270   var_set_value_labels_quiet (new_var, var_get_value_labels (old_var));
1271   var_set_label_quiet (new_var, var_get_label (old_var));
1272   var_set_measure_quiet (new_var, var_get_measure (old_var));
1273   var_set_role_quiet (new_var, var_get_role (old_var));
1274   var_set_display_width_quiet (new_var, var_get_display_width (old_var));
1275   var_set_alignment_quiet (new_var, var_get_alignment (old_var));
1276   var_set_leave_quiet (new_var, var_get_leave (old_var));
1277   var_set_attributes_quiet (new_var, var_get_attributes (old_var));
1278
1279   return new_var;
1280 }
1281
1282
1283
1284 /* Returns the encoding of values of variable VAR.  (This is actually a
1285    property of the dictionary.)  Returns null if no specific encoding has been
1286    set.  */
1287 const char *
1288 var_get_encoding (const struct variable *var)
1289 {
1290   return (var_has_vardict (var)
1291           ? dict_get_encoding (vardict_get_dictionary (var->vardict))
1292           : NULL);
1293 }
1294 \f
1295 /* Returns V's vardict structure. */
1296 struct vardict_info *
1297 var_get_vardict (const struct variable *v)
1298 {
1299   return CONST_CAST (struct vardict_info *, v->vardict);
1300 }
1301
1302 /* Sets V's vardict data to VARDICT. */
1303 void
1304 var_set_vardict (struct variable *v, struct vardict_info *vardict)
1305 {
1306   v->vardict = vardict;
1307 }
1308
1309 /* Returns true if V has vardict data. */
1310 bool
1311 var_has_vardict (const struct variable *v)
1312 {
1313   return v->vardict != NULL;
1314 }
1315
1316 /* Clears V's vardict data. */
1317 void
1318 var_clear_vardict (struct variable *v)
1319 {
1320   v->vardict = NULL;
1321 }
1322
1323 \f
1324 /*
1325   Returns zero, if W is a missing value for WV or if it is less than zero.
1326   Typically used to force a numerical value into a valid weight.
1327
1328   As a side effect, this function will emit a warning if the value
1329   WARN_ON_INVALID points to a bool which is TRUE.  That bool will be then
1330   set to FALSE.
1331  */
1332 double
1333 var_force_valid_weight (const struct variable *wv, double w, bool *warn_on_invalid)
1334 {
1335   if (w < 0.0 || (wv && var_is_num_missing (wv, w, MV_ANY)))
1336     w = 0.0;
1337
1338   if (w == 0.0 && warn_on_invalid != NULL && *warn_on_invalid)
1339     {
1340       *warn_on_invalid = false;
1341       msg (SW, _("At least one case in the data file had a weight value "
1342                  "that was user-missing, system-missing, zero, or "
1343                  "negative.  These case(s) were ignored."));
1344     }
1345
1346   return w;
1347 }