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