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