Docs
[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_UNKNOWN, "unknown", N_("Unknown")},
67     {MEASURE_NOMINAL, "nominal", N_("Nominal")},
68     {MEASURE_ORDINAL, "ordinal", N_("Ordinal")},
69     {MEASURE_SCALE,   "scale", N_("Scale")},
70     {0,0,0}
71   };
72
73 const GEnumValue role[] =
74   {
75     {ROLE_INPUT,  "input",    N_("Input")},
76     {ROLE_TARGET, "output",   N_("Output")},
77     {ROLE_BOTH,   "both",     N_("Both")},
78     {ROLE_NONE,   "none",     N_("None")},
79     {ROLE_PARTITION, "partition", N_("Partition")},
80     {ROLE_SPLIT,  "split",    N_("Split")},
81     {0,0,0}
82   };
83
84 /* A variable. */
85 struct variable
86   {
87     int ref_cnt;
88     /* Dictionary information. */
89     char *name;                 /* Variable name.  Mixed case. */
90     int width;                  /* 0 for numeric, otherwise string width. */
91     struct missing_values miss; /* Missing values. */
92     struct fmt_spec print;      /* Default format for PRINT. */
93     struct fmt_spec write;      /* Default format for WRITE. */
94     struct val_labs *val_labs;  /* Value labels. */
95     char *label;                /* Variable label. */
96     struct string name_and_label; /* The name and label in the same string */
97
98     /* GUI information. */
99     enum measure measure;       /* Nominal, ordinal, or continuous. */
100     enum var_role role;         /* Intended use. */
101     int display_width;          /* Width of data editor column. */
102     enum alignment alignment;   /* Alignment of data in GUI. */
103
104     /* Case information. */
105     bool leave;                 /* Leave value from case to case? */
106
107     /* Data for use by containing dictionary. */
108     struct vardict_info *vardict;
109
110     /* Used only for system and portable file input and output.
111        See short-names.h. */
112     char **short_names;
113     size_t n_short_names;
114
115     /* Custom attributes. */
116     struct attrset attributes;
117   };
118 \f
119
120 static void var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print);
121 static void var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write);
122 static void var_set_label_quiet (struct variable *v, const char *label);
123 static void var_set_name_quiet (struct variable *v, const char *name);
124
125 /* Creates and returns a new variable with the given NAME and
126    WIDTH and other fields initialized to default values.  The
127    variable is not added to a dictionary; for that, use
128    dict_create_var instead. */
129 struct variable *
130 var_create (const char *name, int width)
131 {
132   enum val_type type;
133
134   assert (width >= 0 && width <= MAX_STRING);
135
136   struct variable *v = XZALLOC (struct variable);
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_for_type (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 (mv_is_resizable (&v->miss, new_width))
311     mv_resize (&v->miss, new_width);
312   else
313     {
314       mv_destroy (&v->miss);
315       mv_init (&v->miss, new_width);
316     }
317   if (new_width != var_get_width (v))
318     traits |= VAR_TRAIT_MISSING_VALUES;
319
320   if (v->val_labs != NULL)
321     {
322       if (val_labs_can_set_width (v->val_labs, new_width))
323         val_labs_set_width (v->val_labs, new_width);
324       else
325         {
326           val_labs_destroy (v->val_labs);
327           v->val_labs = NULL;
328         }
329       traits |= VAR_TRAIT_VALUE_LABELS;
330     }
331
332   if (fmt_resize (&v->print, new_width))
333     traits |= VAR_TRAIT_PRINT_FORMAT;
334
335   if (fmt_resize (&v->write, new_width))
336     traits |= VAR_TRAIT_WRITE_FORMAT;
337
338   if (v->width != new_width)
339     {
340       v->width = new_width;
341       traits |= VAR_TRAIT_WIDTH;
342     }
343
344   if (print)
345     {
346       var_set_print_format_quiet (v, print);
347       traits |= VAR_TRAIT_PRINT_FORMAT;
348     }
349
350   if (write)
351     {
352       var_set_write_format_quiet (v, write);
353       traits |= VAR_TRAIT_WRITE_FORMAT;
354     }
355
356   if (traits != 0)
357     dict_var_changed (v, traits, ov);
358 }
359
360 /* Changes the width of V to NEW_WIDTH.
361    This function should be used cautiously. */
362 void
363 var_set_width (struct variable *v, int new_width)
364 {
365   const int old_width = v->width;
366
367   if (old_width == new_width)
368     return;
369
370   var_set_width_and_formats (v, new_width, NULL, NULL);
371 }
372
373
374
375
376 /* Returns true if variable V is numeric, false otherwise. */
377 bool
378 var_is_numeric (const struct variable *v)
379 {
380   return var_get_type (v) == VAL_NUMERIC;
381 }
382
383 /* Returns true if variable V is a string variable, false
384    otherwise. */
385 bool
386 var_is_alpha (const struct variable *v)
387 {
388   return var_get_type (v) == VAL_STRING;
389 }
390 \f
391 /* Returns variable V's missing values. */
392 const struct missing_values *
393 var_get_missing_values (const struct variable *v)
394 {
395   return &v->miss;
396 }
397
398 /* Sets variable V's missing values to MISS, which must be of V's
399    width or at least resizable to V's width.
400    If MISS is null, then V's missing values, if any, are
401    cleared. */
402 static void
403 var_set_missing_values_quiet (struct variable *v, const struct missing_values *miss)
404 {
405   if (miss != NULL)
406     {
407       assert (mv_is_resizable (miss, v->width));
408       mv_destroy (&v->miss);
409       mv_copy (&v->miss, miss);
410       mv_resize (&v->miss, v->width);
411     }
412   else
413     mv_clear (&v->miss);
414 }
415
416 /* Sets variable V's missing values to MISS, which must be of V's
417    width or at least resizable to V's width.
418    If MISS is null, then V's missing values, if any, are
419    cleared. */
420 void
421 var_set_missing_values (struct variable *v, const struct missing_values *miss)
422 {
423   struct variable *ov = var_clone (v);
424   var_set_missing_values_quiet (v, miss);
425   dict_var_changed (v, VAR_TRAIT_MISSING_VALUES, ov);
426 }
427
428 /* Sets variable V to have no user-missing values. */
429 void
430 var_clear_missing_values (struct variable *v)
431 {
432   var_set_missing_values (v, NULL);
433 }
434
435 /* Returns true if V has any user-missing values,
436    false otherwise. */
437 bool
438 var_has_missing_values (const struct variable *v)
439 {
440   return !mv_is_empty (&v->miss);
441 }
442
443 /* Returns MV_SYSTEM if VALUE is system-missing, MV_USER if VALUE is
444    user-missing for V, and otherwise 0. */
445 enum mv_class
446 var_is_value_missing (const struct variable *v, const union value *value)
447 {
448   return mv_is_value_missing (&v->miss, value);
449 }
450
451 /* Returns MV_SYSTEM if VALUE is system-missing, MV_USER if VALUE is
452    user-missing for V, and otherwise 0.  V must be a numeric variable. */
453 enum mv_class
454 var_is_num_missing (const struct variable *v, double d)
455 {
456   return mv_is_num_missing (&v->miss, d);
457 }
458
459 /* Returns MV_USER if VALUE is user-missing for V and otherwise 0.  V must be
460    a string variable. */
461 enum mv_class
462 var_is_str_missing (const struct variable *v, const uint8_t s[])
463 {
464   return mv_is_str_missing (&v->miss, s);
465 }
466 \f
467 /* Returns variable V's value labels,
468    possibly a null pointer if it has none. */
469 const struct val_labs *
470 var_get_value_labels (const struct variable *v)
471 {
472   return v->val_labs;
473 }
474
475 /* Returns true if variable V has at least one value label. */
476 bool
477 var_has_value_labels (const struct variable *v)
478 {
479   return val_labs_count (v->val_labs) > 0;
480 }
481
482 /* Sets variable V's value labels to a copy of VLS,
483    which must have a width equal to V's width or one that can be
484    changed to V's width.
485    If VLS is null, then V's value labels, if any, are removed. */
486 static void
487 var_set_value_labels_quiet (struct variable *v, const struct val_labs *vls)
488 {
489   val_labs_destroy (v->val_labs);
490   v->val_labs = NULL;
491
492   if (vls != NULL)
493     {
494       assert (val_labs_can_set_width (vls, v->width));
495       v->val_labs = val_labs_clone (vls);
496       val_labs_set_width (v->val_labs, v->width);
497     }
498 }
499
500
501 /* Sets variable V's value labels to a copy of VLS,
502    which must have a width equal to V's width or one that can be
503    changed to V's width.
504    If VLS is null, then V's value labels, if any, are removed. */
505 void
506 var_set_value_labels (struct variable *v, const struct val_labs *vls)
507 {
508   struct variable *ov = var_clone (v);
509   var_set_value_labels_quiet (v, vls);
510   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
511 }
512
513
514 /* Makes sure that V has a set of value labels,
515    by assigning one to it if necessary. */
516 static void
517 alloc_value_labels (struct variable *v)
518 {
519   if (v->val_labs == NULL)
520     v->val_labs = val_labs_create (v->width);
521 }
522
523 /* Attempts to add a value label with the given VALUE and UTF-8 encoded LABEL
524    to V.  Returns true if successful, false otherwise (probably due to an
525    existing label).
526
527    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
528 bool
529 var_add_value_label (struct variable *v,
530                      const union value *value, const char *label)
531 {
532   alloc_value_labels (v);
533   return val_labs_add (v->val_labs, value, label);
534 }
535
536 /* Adds or replaces a value label with the given VALUE and UTF-8 encoded LABEL
537    to V.
538
539    In LABEL, the two-byte sequence "\\n" is interpreted as a new-line. */
540 void
541 var_replace_value_label (struct variable *v,
542                          const union value *value, const char *label)
543 {
544   alloc_value_labels (v);
545   val_labs_replace (v->val_labs, value, label);
546 }
547
548 /* Removes V's value labels, if any. */
549 void
550 var_clear_value_labels (struct variable *v)
551 {
552   var_set_value_labels (v, NULL);
553 }
554
555 /* Returns the label associated with VALUE for variable V, as a UTF-8 string in
556    a format suitable for output, or a null pointer if none. */
557 const char *
558 var_lookup_value_label (const struct variable *v, const union value *value)
559 {
560   return val_labs_find (v->val_labs, value);
561 }
562
563 /*
564    Append to STR the string representation of VALUE for variable V.
565    STR must be a pointer to an initialised struct string.
566 */
567 static void
568 append_value (const struct variable *v, const union value *value,
569               struct string *str)
570 {
571   char *s = data_out (value, var_get_encoding (v), &v->print,
572                       settings_get_fmt_settings ());
573   struct substring ss = ss_cstr (s);
574   ss_rtrim (&ss, ss_cstr (" "));
575   ds_put_substring (str, ss);
576   free (s);
577 }
578
579 void
580 var_append_value_name__ (const struct variable *v, const union value *value,
581                          enum settings_value_show show, struct string *str)
582 {
583   const char *label = var_lookup_value_label (v, value);
584
585   switch (show)
586     {
587     case SETTINGS_VALUE_SHOW_VALUE:
588       append_value (v, value, str);
589       break;
590
591     default:
592     case SETTINGS_VALUE_SHOW_LABEL:
593       if (label)
594         ds_put_cstr (str, label);
595       else
596         append_value (v, value, str);
597       break;
598
599     case SETTINGS_VALUE_SHOW_BOTH:
600       append_value (v, value, str);
601       if (label != NULL)
602         ds_put_format (str, " %s", label);
603       break;
604     }
605 }
606
607 /* Append STR with a string representing VALUE for variable V.
608    That is, if VALUE has a label, append that label,
609    otherwise format VALUE and append the formatted string.
610    STR must be a pointer to an initialised struct string.
611 */
612 void
613 var_append_value_name (const struct variable *v, const union value *value,
614                        struct string *str)
615 {
616   var_append_value_name__ (v, value, settings_get_show_values (), str);
617 }
618 \f
619 /* Print and write formats. */
620
621 /* Returns V's print format specification. */
622 const struct fmt_spec *
623 var_get_print_format (const struct variable *v)
624 {
625   return &v->print;
626 }
627
628 /* Sets V's print format specification to PRINT, which must be a
629    valid format specification for a variable of V's width
630    (ordinarily an output format, but input formats are not
631    rejected). */
632 static void
633 var_set_print_format_quiet (struct variable *v, const struct fmt_spec *print)
634 {
635   if (!fmt_equal (&v->print, print))
636     {
637       assert (fmt_check_width_compat (print, v->width));
638       v->print = *print;
639     }
640 }
641
642 /* Sets V's print format specification to PRINT, 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_print_format (struct variable *v, const struct fmt_spec *print)
648 {
649   struct variable *ov = var_clone (v);
650   var_set_print_format_quiet (v, print);
651   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT, ov);
652 }
653
654 /* Returns V's write format specification. */
655 const struct fmt_spec *
656 var_get_write_format (const struct variable *v)
657 {
658   return &v->write;
659 }
660
661 /* Sets V's write format specification to WRITE, which must be a
662    valid format specification for a variable of V's width
663    (ordinarily an output format, but input formats are not
664    rejected). */
665 static void
666 var_set_write_format_quiet (struct variable *v, const struct fmt_spec *write)
667 {
668   if (!fmt_equal (&v->write, write))
669     {
670       assert (fmt_check_width_compat (write, v->width));
671       v->write = *write;
672     }
673 }
674
675 /* Sets V's write format specification to WRITE, which must be a
676    valid format specification for a variable of V's width
677    (ordinarily an output format, but input formats are not
678    rejected). */
679 void
680 var_set_write_format (struct variable *v, const struct fmt_spec *write)
681 {
682   struct variable *ov = var_clone (v);
683   var_set_write_format_quiet (v, write);
684   dict_var_changed (v, VAR_TRAIT_WRITE_FORMAT, ov);
685 }
686
687
688 /* Sets V's print and write format specifications to FORMAT,
689    which must be a valid format specification for a variable of
690    V's width (ordinarily an output format, but input formats are
691    not rejected). */
692 void
693 var_set_both_formats (struct variable *v, const struct fmt_spec *format)
694 {
695   struct variable *ov = var_clone (v);
696   var_set_print_format_quiet (v, format);
697   var_set_write_format_quiet (v, format);
698   dict_var_changed (v, VAR_TRAIT_PRINT_FORMAT | VAR_TRAIT_WRITE_FORMAT, ov);
699 }
700
701 /* Returns the default print and write format for a variable of
702    the given TYPE, as set by var_create.  The return value can be
703    used to reset a variable's print and write formats to the
704    default. */
705 struct fmt_spec
706 var_default_formats (int width)
707 {
708   return (width == 0
709           ? fmt_for_output (FMT_F, 8, 2)
710           : fmt_for_output (FMT_A, width, 0));
711 }
712
713
714 \f
715
716 /* Update the combined name and label string if necessary */
717 static void
718 update_vl_string (const struct variable *v)
719 {
720   /* Cast away const! */
721   struct string *str = (struct string *) &v->name_and_label;
722
723   if (ds_is_empty (str))
724     {
725       if (v->label)
726         ds_put_format (str, _("%s (%s)"), v->label, v->name);
727       else
728         ds_put_cstr (str, v->name);
729     }
730 }
731
732
733 /* Return a string representing this variable, in the form most
734    appropriate from a human factors perspective, that is, its
735    variable label if it has one, otherwise its name. */
736 const char *
737 var_to_string (const struct variable *v)
738 {
739   switch (settings_get_show_variables ())
740     {
741     case SETTINGS_VALUE_SHOW_VALUE:
742       return v->name;
743
744     case SETTINGS_VALUE_SHOW_LABEL:
745     default:
746       return v->label != NULL ? v->label : v->name;
747
748     case SETTINGS_VALUE_SHOW_BOTH:
749       update_vl_string (v);
750       return ds_cstr (&v->name_and_label);
751     }
752 }
753
754 /* Returns V's variable label, or a null pointer if it has none. */
755 const char *
756 var_get_label (const struct variable *v)
757 {
758   return v->label;
759 }
760
761 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
762    and trailing white space.  If LABEL is a null pointer or if LABEL is an
763    empty string (after stripping white space), then V's variable label (if any)
764    is removed. */
765 static void
766 var_set_label_quiet (struct variable *v, const char *label)
767 {
768   free (v->label);
769   v->label = NULL;
770
771   if (label != NULL && label[strspn (label, CC_SPACES)])
772     v->label = xstrdup (label);
773
774   ds_destroy (&v->name_and_label);
775   ds_init_empty (&v->name_and_label);
776 }
777
778
779
780 /* Sets V's variable label to UTF-8 encoded string LABEL, stripping off leading
781    and trailing white space.  If LABEL is a null pointer or if LABEL is an
782    empty string (after stripping white space), then V's variable label (if any)
783    is removed. */
784 void
785 var_set_label (struct variable *v, const char *label)
786 {
787   struct variable *ov = var_clone (v);
788   var_set_label_quiet (v, label);
789   dict_var_changed (v, VAR_TRAIT_LABEL, ov);
790 }
791
792
793 /* Removes any variable label from V. */
794 void
795 var_clear_label (struct variable *v)
796 {
797   var_set_label (v, NULL);
798 }
799
800 /* Returns true if V has a variable V,
801    false otherwise. */
802 bool
803 var_has_label (const struct variable *v)
804 {
805   return v->label != NULL;
806 }
807 \f
808 /* Returns true if M is a valid variable measurement level,
809    false otherwise. */
810 bool
811 measure_is_valid (enum measure m)
812 {
813   return (m == MEASURE_UNKNOWN || m == MEASURE_NOMINAL
814           || m == MEASURE_ORDINAL || m == MEASURE_SCALE);
815 }
816
817 /* Returns a string version of measurement level M, for display to a user.
818    The caller may translate the string by passing it to gettext(). */
819 const char *
820 measure_to_string (enum measure m)
821 {
822   assert (m == measure[m].value);
823   return measure[m].label;
824 }
825
826 /* Returns a string version of measurement level M, for use in PSPP command
827    syntax. */
828 const char *
829 measure_to_syntax (enum measure m)
830 {
831   switch (m)
832     {
833     case MEASURE_NOMINAL:
834       return "NOMINAL";
835
836     case MEASURE_ORDINAL:
837       return "ORDINAL";
838
839     case MEASURE_SCALE:
840       return "SCALE";
841
842     default:
843       return "Invalid";
844     }
845 }
846
847 /* Returns V's measurement level. */
848 enum measure
849 var_get_measure (const struct variable *v)
850 {
851   return v->measure;
852 }
853
854 /* Sets V's measurement level to MEASURE. */
855 static void
856 var_set_measure_quiet (struct variable *v, enum measure measure)
857 {
858   assert (measure_is_valid (measure));
859   v->measure = measure;
860 }
861
862
863 /* Sets V's measurement level to MEASURE. */
864 void
865 var_set_measure (struct variable *v, enum measure measure)
866 {
867   struct variable *ov = var_clone (v);
868   var_set_measure_quiet (v, measure);
869   dict_var_changed (v, VAR_TRAIT_MEASURE, ov);
870 }
871
872
873 /* Returns the default measurement level for a variable of the
874    given TYPE, as set by var_create.  The return value can be
875    used to reset a variable's measurement level to the
876    default. */
877 enum measure
878 var_default_measure_for_type (enum val_type type)
879 {
880   return type == VAL_NUMERIC ? MEASURE_UNKNOWN : MEASURE_NOMINAL;
881 }
882
883 /* Returns the default measurement level for a variable with the given
884    FORMAT, or MEASURE_UNKNOWN if there is no good default. */
885 enum measure
886 var_default_measure_for_format (enum fmt_type format)
887 {
888   if (format == FMT_DOLLAR)
889     return MEASURE_SCALE;
890
891   switch (fmt_get_category (format))
892     {
893     case FMT_CAT_BASIC:
894     case FMT_CAT_LEGACY:
895     case FMT_CAT_BINARY:
896     case FMT_CAT_HEXADECIMAL:
897       return MEASURE_UNKNOWN;
898
899     case FMT_CAT_CUSTOM:
900     case FMT_CAT_DATE:
901     case FMT_CAT_TIME:
902       return MEASURE_SCALE;
903
904     case FMT_CAT_DATE_COMPONENT:
905     case FMT_CAT_STRING:
906       return MEASURE_NOMINAL;
907     }
908
909   NOT_REACHED ();
910 }
911 \f
912 /* Returns true if M is a valid variable role,
913    false otherwise. */
914 bool
915 var_role_is_valid (enum var_role role)
916 {
917   switch (role)
918     {
919     case ROLE_NONE:
920     case ROLE_INPUT:
921     case ROLE_TARGET:
922     case ROLE_BOTH:
923     case ROLE_PARTITION:
924     case ROLE_SPLIT:
925       return true;
926
927     default:
928       return false;
929     }
930 }
931
932 /* Returns a string version of ROLE, for display to a user.
933    The caller may translate the string by passing it to gettext(). */
934 const char *
935 var_role_to_string (enum var_role r)
936 {
937   assert (r == role[r].value);
938   return role[r].label;
939 }
940
941 /* Returns a string version of ROLE, for use in PSPP comamnd syntax. */
942 const char *
943 var_role_to_syntax (enum var_role role)
944 {
945   switch (role)
946     {
947     case ROLE_INPUT:
948       return "INPUT";
949
950     case ROLE_TARGET:
951       return "TARGET";
952
953     case ROLE_BOTH:
954       return "BOTH";
955
956     case ROLE_NONE:
957       return "NONE";
958
959     case ROLE_PARTITION:
960       return "PARTITION";
961
962     case ROLE_SPLIT:
963       return "SPLIT";
964
965     default:
966       return "<invalid>";
967     }
968 }
969
970 /* Returns V's role. */
971 enum var_role
972 var_get_role (const struct variable *v)
973 {
974   return v->role;
975 }
976
977 /* Sets V's role to ROLE. */
978 static void
979 var_set_role_quiet (struct variable *v, enum var_role role)
980 {
981   assert (var_role_is_valid (role));
982   v->role = role;
983 }
984
985
986 /* Sets V's role to ROLE. */
987 void
988 var_set_role (struct variable *v, enum var_role role)
989 {
990   struct variable *ov = var_clone (v);
991   var_set_role_quiet (v, role);
992   dict_var_changed (v, VAR_TRAIT_ROLE, ov);
993 }
994 \f
995 /* Returns V's display width, which applies only to GUIs. */
996 int
997 var_get_display_width (const struct variable *v)
998 {
999   return v->display_width;
1000 }
1001
1002 /* Sets V's display width to DISPLAY_WIDTH. */
1003 static void
1004 var_set_display_width_quiet (struct variable *v, int new_width)
1005 {
1006   if (v->display_width != new_width)
1007     {
1008       v->display_width = new_width;
1009     }
1010 }
1011
1012 void
1013 var_set_display_width (struct variable *v, int new_width)
1014 {
1015   if (v->display_width != new_width)
1016     {
1017       struct variable *ov = var_clone (v);
1018       var_set_display_width_quiet (v, new_width);
1019       dict_var_changed (v, VAR_TRAIT_DISPLAY_WIDTH, ov);
1020     }
1021 }
1022
1023 /* Returns the default display width for a variable of the given
1024    WIDTH, as set by var_create.  The return value can be used to
1025    reset a variable's display width to the default. */
1026 int
1027 var_default_display_width (int width)
1028 {
1029   return width == 0 ? 8 : MIN (width, 32);
1030 }
1031 \f
1032 /* Returns true if A is a valid alignment,
1033    false otherwise. */
1034 bool
1035 alignment_is_valid (enum alignment a)
1036 {
1037   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
1038 }
1039
1040 /* Returns a string version of alignment A, for display to a user.
1041    The caller may translate the string by passing it to gettext(). */
1042 const char *
1043 alignment_to_string (enum alignment a)
1044 {
1045   assert (a == align[a].value);
1046   return align[a].label;
1047 }
1048
1049 /* Returns a string version of alignment A, for use in PSPP command syntax. */
1050 const char *
1051 alignment_to_syntax (enum alignment a)
1052 {
1053   switch (a)
1054     {
1055     case ALIGN_LEFT:
1056       return "LEFT";
1057
1058     case ALIGN_RIGHT:
1059       return "RIGHT";
1060
1061     case ALIGN_CENTRE:
1062       return "CENTER";
1063
1064     default:
1065       return "Invalid";
1066     }
1067 }
1068
1069 /* Returns V's display alignment, which applies only to GUIs. */
1070 enum alignment
1071 var_get_alignment (const struct variable *v)
1072 {
1073   return v->alignment;
1074 }
1075
1076 /* Sets V's display alignment to ALIGNMENT. */
1077 static void
1078 var_set_alignment_quiet (struct variable *v, enum alignment alignment)
1079 {
1080   assert (alignment_is_valid (alignment));
1081   v->alignment = alignment;
1082 }
1083
1084 /* Sets V's display alignment to ALIGNMENT. */
1085 void
1086 var_set_alignment (struct variable *v, enum alignment alignment)
1087 {
1088   struct variable *ov = var_clone (v);
1089   var_set_alignment_quiet (v, alignment);
1090   dict_var_changed (v, VAR_TRAIT_ALIGNMENT, ov);
1091 }
1092
1093
1094 /* Returns the default display alignment for a variable of the
1095    given TYPE, as set by var_create.  The return value can be
1096    used to reset a variable's display alignment to the default. */
1097 enum alignment
1098 var_default_alignment (enum val_type type)
1099 {
1100   return type == VAL_NUMERIC ? ALIGN_RIGHT : ALIGN_LEFT;
1101 }
1102 \f
1103 /* Whether variables' values should be preserved from case to
1104    case. */
1105
1106 /* Returns true if variable V's value should be left from case to
1107    case, instead of being reset to system-missing or blanks. */
1108 bool
1109 var_get_leave (const struct variable *v)
1110 {
1111   return v->leave;
1112 }
1113
1114 /* Sets V's leave setting to LEAVE. */
1115 static void
1116 var_set_leave_quiet (struct variable *v, bool leave)
1117 {
1118   assert (leave || !var_must_leave (v));
1119   v->leave = leave;
1120 }
1121
1122
1123 /* Sets V's leave setting to LEAVE. */
1124 void
1125 var_set_leave (struct variable *v, bool leave)
1126 {
1127   struct variable *ov = var_clone (v);
1128   var_set_leave_quiet (v, leave);
1129   dict_var_changed (v, VAR_TRAIT_LEAVE, ov);
1130 }
1131
1132
1133 /* Returns true if V must be left from case to case,
1134    false if it can be set either way. */
1135 bool
1136 var_must_leave (const struct variable *v)
1137 {
1138   return var_get_dict_class (v) == DC_SCRATCH;
1139 }
1140 \f
1141 /* Returns the number of short names stored in VAR.
1142
1143    Short names are used only for system and portable file input
1144    and output.  They are upper-case only, not necessarily unique,
1145    and limited to SHORT_NAME_LEN characters (plus a null
1146    terminator).  Ordinarily a variable has at most one short
1147    name, but very long string variables (longer than 255 bytes)
1148    may have more.  A variable might not have any short name at
1149    all if it hasn't been saved to or read from a system or
1150    portable file. */
1151 size_t
1152 var_get_n_short_names (const struct variable *var)
1153 {
1154   return var->n_short_names;
1155 }
1156
1157 /* Returns VAR's short name with the given IDX, if it has one
1158    with that index, or a null pointer otherwise.  Short names may
1159    be sparse: even if IDX is less than the number of short names
1160    in VAR, this function may return a null pointer. */
1161 const char *
1162 var_get_short_name (const struct variable *var, size_t idx)
1163 {
1164   return idx < var->n_short_names ? var->short_names[idx] : NULL;
1165 }
1166
1167 /* Sets VAR's short name with the given IDX to the UTF-8 string SHORT_NAME.
1168    The caller must already have checked that, in the dictionary encoding,
1169    SHORT_NAME is no more than SHORT_NAME_LEN bytes long.  The new short name
1170    will be converted to uppercase.
1171
1172    Specifying a null pointer for SHORT_NAME clears the specified short name. */
1173 void
1174 var_set_short_name (struct variable *var, size_t idx, const char *short_name)
1175 {
1176   struct variable *ov = var_clone (var);
1177
1178   /* Clear old short name numbered IDX, if any. */
1179   if (idx < var->n_short_names)
1180     {
1181       free (var->short_names[idx]);
1182       var->short_names[idx] = NULL;
1183     }
1184
1185   /* Install new short name for IDX. */
1186   if (short_name != NULL)
1187     {
1188       if (idx >= var->n_short_names)
1189         {
1190           size_t n_old = var->n_short_names;
1191           size_t i;
1192           var->n_short_names = MAX (idx * 2, 1);
1193           var->short_names = xnrealloc (var->short_names, var->n_short_names,
1194                                         sizeof *var->short_names);
1195           for (i = n_old; i < var->n_short_names; i++)
1196             var->short_names[i] = NULL;
1197         }
1198       var->short_names[idx] = utf8_to_upper (short_name);
1199     }
1200
1201   dict_var_changed (var, VAR_TRAIT_NAME, ov);
1202 }
1203
1204 /* Clears V's short names. */
1205 void
1206 var_clear_short_names (struct variable *v)
1207 {
1208   size_t i;
1209
1210   for (i = 0; i < v->n_short_names; i++)
1211     free (v->short_names[i]);
1212   free (v->short_names);
1213   v->short_names = NULL;
1214   v->n_short_names = 0;
1215 }
1216 \f
1217 /* Relationship with dictionary. */
1218
1219 /* Returns V's index within its dictionary, the value
1220    for which "dict_get_var (dict, index)" will return V.
1221    V must be in a dictionary. */
1222 size_t
1223 var_get_dict_index (const struct variable *v)
1224 {
1225   assert (var_has_vardict (v));
1226   return vardict_get_dict_index (v->vardict);
1227 }
1228
1229 /* Returns V's index within the case represented by its
1230    dictionary, that is, the value for which "case_data_idx (case,
1231    index)" will return the data for V in that case.
1232    V must be in a dictionary. */
1233 size_t
1234 var_get_case_index (const struct variable *v)
1235 {
1236   assert (var_has_vardict (v));
1237   return vardict_get_case_index (v->vardict);
1238 }
1239 \f
1240 /* Returns variable V's attribute set.  The caller may examine or
1241    modify the attribute set, but must not destroy it.  Destroying
1242    V, or calling var_set_attributes() on V, will also destroy its
1243    attribute set. */
1244 struct attrset *
1245 var_get_attributes (const struct variable *v)
1246 {
1247   return CONST_CAST (struct attrset *, &v->attributes);
1248 }
1249
1250 /* Replaces variable V's attributes set by a copy of ATTRS. */
1251 static void
1252 var_set_attributes_quiet (struct variable *v, const struct attrset *attrs)
1253 {
1254   attrset_destroy (&v->attributes);
1255   attrset_clone (&v->attributes, attrs);
1256 }
1257
1258 /* Replaces variable V's attributes set by a copy of ATTRS. */
1259 void
1260 var_set_attributes (struct variable *v, const struct attrset *attrs)
1261 {
1262   struct variable *ov = var_clone (v);
1263   var_set_attributes_quiet (v, attrs);
1264   dict_var_changed (v, VAR_TRAIT_ATTRIBUTES, ov);
1265 }
1266
1267
1268 /* Returns true if V has any custom attributes, false if it has none. */
1269 bool
1270 var_has_attributes (const struct variable *v)
1271 {
1272   return attrset_count (&v->attributes) > 0;
1273 }
1274 \f
1275
1276 /* Creates and returns a clone of OLD_VAR.  Most properties of
1277    the new variable are copied from OLD_VAR, except:
1278
1279     - The variable's short name is not copied, because there is
1280       no reason to give a new variable with potentially a new
1281       name the same short name.
1282
1283     - The new variable is not added to OLD_VAR's dictionary by
1284       default.  Use dict_clone_var, instead, to do that.
1285 */
1286 struct variable *
1287 var_clone (const struct variable *old_var)
1288 {
1289   struct variable *new_var = var_create (var_get_name (old_var),
1290                                          var_get_width (old_var));
1291
1292   var_set_missing_values_quiet (new_var, var_get_missing_values (old_var));
1293   var_set_print_format_quiet (new_var, var_get_print_format (old_var));
1294   var_set_write_format_quiet (new_var, var_get_write_format (old_var));
1295   var_set_value_labels_quiet (new_var, var_get_value_labels (old_var));
1296   var_set_label_quiet (new_var, var_get_label (old_var));
1297   var_set_measure_quiet (new_var, var_get_measure (old_var));
1298   var_set_role_quiet (new_var, var_get_role (old_var));
1299   var_set_display_width_quiet (new_var, var_get_display_width (old_var));
1300   var_set_alignment_quiet (new_var, var_get_alignment (old_var));
1301   var_set_leave_quiet (new_var, var_get_leave (old_var));
1302   var_set_attributes_quiet (new_var, var_get_attributes (old_var));
1303
1304   return new_var;
1305 }
1306
1307
1308
1309 /* Returns the encoding of values of variable VAR.  (This is actually a
1310    property of the dictionary.)  Returns null if no specific encoding has been
1311    set.  */
1312 const char *
1313 var_get_encoding (const struct variable *var)
1314 {
1315   return (var_has_vardict (var)
1316           ? dict_get_encoding (vardict_get_dictionary (var->vardict))
1317           : NULL);
1318 }
1319 \f
1320 /* Returns V's vardict structure. */
1321 struct vardict_info *
1322 var_get_vardict (const struct variable *v)
1323 {
1324   return CONST_CAST (struct vardict_info *, v->vardict);
1325 }
1326
1327 /* Sets V's vardict data to VARDICT. */
1328 void
1329 var_set_vardict (struct variable *v, struct vardict_info *vardict)
1330 {
1331   v->vardict = vardict;
1332 }
1333
1334 /* Returns true if V has vardict data. */
1335 bool
1336 var_has_vardict (const struct variable *v)
1337 {
1338   return v->vardict != NULL;
1339 }
1340
1341 /* Clears V's vardict data. */
1342 void
1343 var_clear_vardict (struct variable *v)
1344 {
1345   v->vardict = NULL;
1346 }
1347
1348 \f
1349 /*
1350   Returns zero, if W is a missing value for WV or if it is less than zero.
1351   Typically used to force a numerical value into a valid weight.
1352
1353   As a side effect, this function will emit a warning if the value
1354   WARN_ON_INVALID points to a bool which is TRUE.  That bool will be then
1355   set to FALSE.
1356  */
1357 double
1358 var_force_valid_weight (const struct variable *wv, double w, bool *warn_on_invalid)
1359 {
1360   if (w <= 0.0 || (wv ? var_is_num_missing (wv, w) : w == SYSMIS))
1361     {
1362       w = 0.0;
1363       if (warn_on_invalid != NULL && *warn_on_invalid)
1364         {
1365           *warn_on_invalid = false;
1366           msg (SW, _("At least one case in the data file had a weight value "
1367                      "that was user-missing, system-missing, zero, or "
1368                      "negative.  These case(s) were ignored."));
1369         }
1370     }
1371
1372   return w;
1373 }