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