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