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