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