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