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