Changed factors' independent variables to be copies on the heap.
[pspp-builds.git] / src / data / variable.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include "variable.h"
22 #include <libpspp/assertion.h>
23 #include <libpspp/message.h>
24 #include <stdlib.h>
25 #include <libpspp/alloc.h>
26 #include <libpspp/compiler.h>
27 #include "dictionary.h"
28 #include <libpspp/hash.h>
29 #include "identifier.h"
30 #include <libpspp/misc.h>
31 #include <libpspp/str.h>
32 #include "value-labels.h"
33
34 #include "minmax.h"
35
36 #include "gettext.h"
37 #define _(msgid) gettext (msgid)
38
39 /* Returns true if VAR_TYPE is a valid variable type. */
40 bool
41 var_type_is_valid (enum var_type var_type) 
42 {
43   return var_type == NUMERIC || var_type == ALPHA;
44 }
45
46 /* Returns an adjective describing the given variable TYPE,
47    suitable for use in phrases like "numeric variable". */
48 const char *
49 var_type_adj (enum var_type type) 
50 {
51   return type == NUMERIC ? _("numeric") : _("string");
52 }
53
54 /* Returns a noun describing a value of the given variable TYPE,
55    suitable for use in phrases like "a number". */
56 const char *
57 var_type_noun (enum var_type type) 
58 {
59   return type == NUMERIC ? _("number") : _("string");
60 }
61 \f
62 /* Returns true if M is a valid variable measurement level,
63    false otherwise. */
64 bool
65 measure_is_valid (enum measure m)
66 {
67   return m == MEASURE_NOMINAL || m == MEASURE_ORDINAL || m == MEASURE_SCALE;
68 }
69
70 /* Returns true if A is a valid alignment,
71    false otherwise. */
72 bool
73 alignment_is_valid (enum alignment a)
74 {
75   return a == ALIGN_LEFT || a == ALIGN_RIGHT || a == ALIGN_CENTRE;
76 }
77 \f
78 /* Assign auxiliary data AUX to variable V, which must not
79    already have auxiliary data.  Before V's auxiliary data is
80    cleared, AUX_DTOR(V) will be called. */
81 void *
82 var_attach_aux (struct variable *v,
83                 void *aux, void (*aux_dtor) (struct variable *)) 
84 {
85   assert (v->aux == NULL);
86   assert (aux != NULL);
87   v->aux = aux;
88   v->aux_dtor = aux_dtor;
89   return aux;
90 }
91
92 /* Remove auxiliary data, if any, from V, and returns it, without
93    calling any associated destructor. */
94 void *
95 var_detach_aux (struct variable *v) 
96 {
97   void *aux = v->aux;
98   assert (aux != NULL);
99   v->aux = NULL;
100   return aux;
101 }
102
103 /* Clears auxiliary data, if any, from V, and calls any
104    associated destructor. */
105 void
106 var_clear_aux (struct variable *v) 
107 {
108   assert (v != NULL);
109   if (v->aux != NULL) 
110     {
111       if (v->aux_dtor != NULL)
112         v->aux_dtor (v);
113       v->aux = NULL;
114     }
115 }
116
117 /* This function is appropriate for use an auxiliary data
118    destructor (passed as AUX_DTOR to var_attach_aux()) for the
119    case where the auxiliary data should be passed to free(). */
120 void
121 var_dtor_free (struct variable *v) 
122 {
123   free (v->aux);
124 }
125
126 /* Duplicate a value.
127    The caller is responsible for freeing the returned value
128 */
129 union value *
130 value_dup (const union value *val, int width)
131 {
132   size_t bytes = MAX(width, sizeof *val);
133
134   union value *v = xmalloc (bytes);
135   memcpy (v, val, bytes);
136   return v;
137 }
138
139
140
141 /* Compares A and B, which both have the given WIDTH, and returns
142    a strcmp()-type result. */
143 int
144 compare_values (const union value *a, const union value *b, int width) 
145 {
146   if (width == 0) 
147     return a->f < b->f ? -1 : a->f > b->f;
148   else
149     return memcmp (a->s, b->s, MIN(MAX_SHORT_STRING, width));
150 }
151
152 /* Create a hash of v */
153 unsigned 
154 hash_value(const union value  *v, int width)
155 {
156   unsigned id_hash;
157
158   if ( 0 == width ) 
159     id_hash = hsh_hash_double (v->f);
160   else
161     id_hash = hsh_hash_bytes (v->s, MIN(MAX_SHORT_STRING, width));
162
163   return id_hash;
164 }
165 \f
166 /* Return variable V's name. */
167 const char *
168 var_get_name (const struct variable *v) 
169 {
170   return v->name;
171 }
172
173 /* Sets V's name to NAME. */
174 void
175 var_set_name (struct variable *v, const char *name) 
176 {
177   assert (name[0] != '\0');
178   assert (lex_id_to_token (ss_cstr (name)) == T_ID);
179
180   str_copy_trunc (v->name, sizeof v->name, name);
181 }
182
183 /* Returns true if NAME is an acceptable name for a variable,
184    false otherwise.  If ISSUE_ERROR is true, issues an
185    explanatory error message on failure. */
186 bool
187 var_is_valid_name (const char *name, bool issue_error) 
188 {
189   bool plausible;
190   size_t length, i;
191   
192   assert (name != NULL);
193
194   /* Note that strlen returns number of BYTES, not the number of 
195      CHARACTERS */
196   length = strlen (name);
197
198   plausible = var_is_plausible_name(name, issue_error);
199
200   if ( ! plausible ) 
201     return false;
202
203
204   if (!lex_is_id1 (name[0]))
205     {
206       if (issue_error)
207         msg (SE, _("Character `%c' (in %s), may not appear "
208                    "as the first character in a variable name."),
209              name[0], name);
210       return false;
211     }
212
213
214   for (i = 0; i < length; i++)
215     {
216     if (!lex_is_idn (name[i])) 
217       {
218         if (issue_error)
219           msg (SE, _("Character `%c' (in %s) may not appear in "
220                      "a variable name."),
221                name[i], name);
222         return false;
223       }
224     }
225
226   return true;
227 }
228
229 /* 
230    Returns true if NAME is an plausible name for a variable,
231    false otherwise.  If ISSUE_ERROR is true, issues an
232    explanatory error message on failure. 
233    This function makes no use of LC_CTYPE.
234 */
235 bool
236 var_is_plausible_name (const char *name, bool issue_error) 
237 {
238   size_t length;
239   
240   assert (name != NULL);
241
242   /* Note that strlen returns number of BYTES, not the number of 
243      CHARACTERS */
244   length = strlen (name);
245   if (length < 1) 
246     {
247       if (issue_error)
248         msg (SE, _("Variable name cannot be empty string."));
249       return false;
250     }
251   else if (length > LONG_NAME_LEN) 
252     {
253       if (issue_error)
254         msg (SE, _("Variable name %s exceeds %d-character limit."),
255              name, (int) LONG_NAME_LEN);
256       return false;
257     }
258
259   if (lex_id_to_token (ss_cstr (name)) != T_ID) 
260     {
261       if (issue_error)
262         msg (SE, _("`%s' may not be used as a variable name because it "
263                    "is a reserved word."), name);
264       return false;
265     }
266
267   return true;
268 }
269
270 /* A hsh_compare_func that orders variables A and B by their
271    names. */
272 int
273 compare_var_names (const void *a_, const void *b_, const void *aux UNUSED) 
274 {
275   const struct variable *a = a_;
276   const struct variable *b = b_;
277
278   return strcasecmp (var_get_name (a), var_get_name (b));
279 }
280
281 /* A hsh_hash_func that hashes variable V based on its name. */
282 unsigned
283 hash_var_name (const void *v_, const void *aux UNUSED) 
284 {
285   const struct variable *v = v_;
286
287   return hsh_hash_case_string (var_get_name (v));
288 }
289
290 /* A hsh_compare_func that orders pointers to variables A and B
291    by their names. */
292 int
293 compare_var_ptr_names (const void *a_, const void *b_, const void *aux UNUSED) 
294 {
295   struct variable *const *a = a_;
296   struct variable *const *b = b_;
297
298   return strcasecmp (var_get_name (*a), var_get_name (*b));
299 }
300
301 /* A hsh_hash_func that hashes pointer to variable V based on its
302    name. */
303 unsigned
304 hash_var_ptr_name (const void *v_, const void *aux UNUSED) 
305 {
306   struct variable *const *v = v_;
307
308   return hsh_hash_case_string (var_get_name (*v));
309 }
310 \f
311 /* Returns the type of a variable with the given WIDTH. */
312 static enum var_type
313 width_to_type (int width) 
314 {
315   return width == 0 ? NUMERIC : ALPHA;
316 }
317
318 /* Returns the type of variable V. */
319 enum var_type
320 var_get_type (const struct variable *v) 
321 {
322   return width_to_type (v->width);
323 }
324
325 /* Returns the width of variable V. */
326 int
327 var_get_width (const struct variable *v) 
328 {
329   return v->width;
330 }
331
332 /* Sets the width of V to WIDTH. */
333 void
334 var_set_width (struct variable *v, int new_width) 
335 {
336   enum var_type new_type = width_to_type (new_width);
337   
338   if (mv_is_resizable (&v->miss, new_width))
339     mv_resize (&v->miss, new_width);
340   else
341     mv_init (&v->miss, new_width);
342
343   if (v->val_labs != NULL) 
344     {
345       if (val_labs_can_set_width (v->val_labs, new_width))
346         val_labs_set_width (v->val_labs, new_width);
347       else 
348         {
349           val_labs_destroy (v->val_labs);
350           v->val_labs = NULL;
351         }
352     }
353   
354   if (var_get_type (v) != new_type) 
355     {
356       v->print = (new_type == NUMERIC
357                   ? fmt_for_output (FMT_F, 8, 2)
358                   : fmt_for_output (FMT_A, new_width, 0));
359       v->write = v->print;
360     }
361   else if (new_type == ALPHA) 
362     {
363       v->print.w = v->print.type == FMT_AHEX ? new_width * 2 : new_width;
364       v->write.w = v->write.type == FMT_AHEX ? new_width * 2 : new_width;
365     }
366
367   v->width = new_width;
368 }
369
370 /* Returns true if variable V is numeric, false otherwise. */
371 bool
372 var_is_numeric (const struct variable *v) 
373 {
374   return var_get_type (v) == NUMERIC;
375 }
376
377 /* Returns true if variable V is a string variable, false
378    otherwise. */
379 bool
380 var_is_alpha (const struct variable *v) 
381 {
382   return var_get_type (v) == ALPHA;
383 }
384
385 /* Returns true if variable V is a short string variable, false
386    otherwise. */
387 bool
388 var_is_short_string (const struct variable *v) 
389 {
390   return v->width > 0 && v->width <= MAX_SHORT_STRING;
391 }
392
393 /* Returns true if variable V is a long string variable, false
394    otherwise. */
395 bool
396 var_is_long_string (const struct variable *v) 
397 {
398   return v->width > MAX_SHORT_STRING;
399 }
400
401 /* Returns true if variable V is a very long string variable,
402    false otherwise. */
403 bool
404 var_is_very_long_string (const struct variable *v) 
405 {
406   return v->width > MAX_LONG_STRING;
407 }
408
409 /* Returns variable V's missing values. */
410 const struct missing_values *
411 var_get_missing_values (const struct variable *v) 
412 {
413   return &v->miss;
414 }
415
416 /* Sets variable V's missing values to MISS, which must be of the
417    correct width. */
418 void
419 var_set_missing_values (struct variable *v, const struct missing_values *miss)
420 {
421   if (miss != NULL) 
422     {
423       assert (v->width == mv_get_width (miss));
424       mv_copy (&v->miss, miss);
425     }
426   else
427     mv_init (&v->miss, v->width);
428 }
429
430 /* Sets variable V to have no user-missing values. */
431 void
432 var_clear_missing_values (struct variable *v) 
433 {
434   var_set_missing_values (v, NULL);
435 }
436
437 /* Returns true if V has any user-missing values,
438    false otherwise. */
439 bool
440 var_has_missing_values (const struct variable *v) 
441 {
442   return !mv_is_empty (&v->miss);
443 }
444
445 /* Returns true if VALUE is system missing or user-missing value
446    for V, false otherwise. */
447 bool
448 var_is_value_missing (const struct variable *v, const union value *value) 
449 {
450   return mv_is_value_missing (&v->miss, value);
451 }
452
453 /* Returns true if D is system missing or a missing value in V,
454    false otherwise.
455    V must be a numeric variable. */
456 bool
457 var_is_num_missing (const struct variable *v, double d) 
458 {
459   return mv_is_num_missing (&v->miss, d);
460 }
461
462 /* Returns true if S[] is a missing value for V, false otherwise.
463    S[] must contain exactly as many characters as V's width.
464    V must be a string variable. */
465 bool
466 var_is_str_missing (const struct variable *v, const char s[]) 
467 {
468   return mv_is_str_missing (&v->miss, s);
469 }
470
471 /* Returns true if VALUE is a missing value for V, false
472    otherwise. */
473 bool
474 var_is_value_user_missing (const struct variable *v, const union value *value) 
475 {
476   return mv_is_value_user_missing (&v->miss, value);
477 }
478
479 /* Returns true if D is a user-missing value for V, false
480    otherwise.  V must be a numeric variable. */
481 bool
482 var_is_num_user_missing (const struct variable *v, double d) 
483 {
484   return mv_is_num_user_missing (&v->miss, d);
485 }
486
487 /* Returns true if S[] is a missing value for V, false otherwise.
488    V must be a string variable. 
489    S[] must contain exactly as many characters as V's width. */
490 bool
491 var_is_str_user_missing (const struct variable *v, const char s[]) 
492 {
493   return mv_is_str_user_missing (&v->miss, s);
494 }
495
496 /* Returns true if V is a numeric variable and VALUE is the
497    system missing value. */
498 bool
499 var_is_value_system_missing (const struct variable *v,
500                              const union value *value) 
501 {
502   return mv_is_value_system_missing (&v->miss, value);
503 }
504 \f
505 /* Print and write formats. */
506
507 /* Returns V's print format specification. */
508 const struct fmt_spec *
509 var_get_print_format (const struct variable *v) 
510 {
511   return &v->print;
512 }
513
514 /* Sets V's print format specification to PRINT, which must be a
515    valid format specification for outputting a variable of V's
516    width. */
517 void
518 var_set_print_format (struct variable *v, const struct fmt_spec *print) 
519 {
520   assert (fmt_check_width_compat (print, v->width));
521   v->print = *print;
522 }
523
524 /* Returns V's write format specification. */
525 const struct fmt_spec *
526 var_get_write_format (const struct variable *v) 
527 {
528   return &v->write;
529 }
530
531 /* Sets V's write format specification to WRITE, which must be a
532    valid format specification for outputting a variable of V's
533    width. */
534 void
535 var_set_write_format (struct variable *v, const struct fmt_spec *write) 
536 {
537   assert (fmt_check_width_compat (write, v->width));
538   v->write = *write;
539 }
540
541 /* Sets V's print and write format specifications to FORMAT,
542    which must be a valid format specification for outputting a
543    variable of V's width. */
544 void
545 var_set_both_formats (struct variable *v, const struct fmt_spec *format) 
546 {
547   var_set_print_format (v, format);
548   var_set_write_format (v, format);
549 }
550 \f
551 /* Returns V's variable label, or a null pointer if it has none. */
552 const char *
553 var_get_label (const struct variable *v) 
554 {
555   return v->label;
556 }
557
558 /* Sets V's variable label to LABEL, stripping off leading and
559    trailing white space and truncating to 255 characters.
560    If LABEL is a null pointer or if LABEL is an empty string
561    (after stripping white space), then V's variable label (if
562    any) is removed. */
563 void
564 var_set_label (struct variable *v, const char *label) 
565 {
566   free (v->label);
567   v->label = NULL;
568
569   if (label != NULL) 
570     {
571       struct substring s = ss_cstr (label);
572       ss_trim (&s, ss_cstr (CC_SPACES));
573       ss_truncate (&s, 255);
574       if (!ss_is_empty (s)) 
575         v->label = ss_xstrdup (s);
576     }
577 }
578
579 /* Removes any variable label from V. */
580 void
581 var_clear_label (struct variable *v) 
582 {
583   var_set_label (v, NULL);
584 }
585
586 /* Returns true if V has a variable V,
587    false otherwise. */
588 bool
589 var_has_label (const struct variable *v) 
590 {
591   return v->label != NULL;
592 }
593 \f
594 /* Returns V's measurement level. */
595 enum measure
596 var_get_measure (const struct variable *v) 
597 {
598   return v->measure;
599 }
600
601 /* Sets V's measurement level to MEASURE. */
602 void
603 var_set_measure (struct variable *v, enum measure measure) 
604 {
605   assert (measure_is_valid (measure));
606   v->measure = measure;
607 }
608
609 /* Returns V's display width, which applies only to GUIs. */
610 int
611 var_get_display_width (const struct variable *v) 
612 {
613   return v->display_width;
614 }
615
616 /* Sets V's display width to DISPLAY_WIDTH. */
617 void
618 var_set_display_width (struct variable *v, int display_width) 
619 {
620   v->display_width = display_width;
621 }
622
623 /* Returns V's display alignment, which applies only to GUIs. */
624 enum alignment
625 var_get_alignment (const struct variable *v) 
626 {
627   return v->alignment;
628 }
629
630 /* Sets V's display alignment to ALIGNMENT. */
631 void
632 var_set_alignment (struct variable *v, enum alignment alignment) 
633 {
634   assert (alignment_is_valid (alignment));
635   v->alignment = alignment;
636 }
637 \f
638 /* Returns the number of "union value"s need to store a value of
639    variable V. */
640 size_t
641 var_get_value_cnt (const struct variable *v) 
642 {
643   return v->width == 0 ? 1 : DIV_RND_UP (v->width, MAX_SHORT_STRING);
644 }
645
646 /* Return whether variable V's values should be preserved from
647    case to case. */
648 bool
649 var_get_leave (const struct variable *v) 
650 {
651   return v->leave;
652 }
653 \f
654 /* Returns V's short name, if it has one, or a null pointer
655    otherwise.
656
657    Short names are used only for system and portable file input
658    and output.  They are upper-case only, not necessarily unique,
659    and limited to SHORT_NAME_LEN characters (plus a null
660    terminator).  Any variable may have no short name, indicated
661    by returning a null pointer. */
662 const char *
663 var_get_short_name (const struct variable *v) 
664 {
665   return v->short_name[0] != '\0' ? v->short_name : NULL;
666 }
667
668 /* Sets V's short_name to SHORT_NAME, truncating it to
669    SHORT_NAME_LEN characters and converting it to uppercase in
670    the process.  Specifying a null pointer for SHORT_NAME clears
671    the variable's short name. */
672 void
673 var_set_short_name (struct variable *v, const char *short_name) 
674 {
675   assert (v != NULL);
676   assert (short_name == NULL || var_is_plausible_name (short_name, false));
677
678   if (short_name != NULL) 
679     {
680       str_copy_trunc (v->short_name, sizeof v->short_name, short_name);
681       str_uppercase (v->short_name); 
682     }
683   else
684     v->short_name[0] = '\0';
685 }
686
687 /* Clears V's short name. */
688 void
689 var_clear_short_name (struct variable *v) 
690 {
691   assert (v != NULL);
692
693   v->short_name[0] = '\0';
694 }
695
696 /* Sets V's short name to BASE, followed by a suffix of the form
697    _A, _B, _C, ..., _AA, _AB, etc. according to the value of
698    SUFFIX_NUMBER.  Truncates BASE as necessary to fit. */
699 void
700 var_set_short_name_suffix (struct variable *v, const char *base,
701                            int suffix_number)
702 {
703   char suffix[SHORT_NAME_LEN + 1];
704   char short_name[SHORT_NAME_LEN + 1];
705   char *start, *end;
706   int len, ofs;
707
708   assert (v != NULL);
709   assert (suffix_number >= 0);
710
711   /* Set base name. */
712   var_set_short_name (v, base);
713
714   /* Compose suffix. */
715   start = end = suffix + sizeof suffix - 1;
716   *end = '\0';
717   do 
718     {
719       *--start = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[suffix_number % 26];
720       if (start <= suffix + 1)
721         msg (SE, _("Variable suffix too large."));
722       suffix_number /= 26;
723     }
724   while (suffix_number > 0);
725   *--start = '_';
726
727   /* Append suffix to V's short name. */
728   str_copy_trunc (short_name, sizeof short_name, base);
729   len = end - start;
730   if (len + strlen (short_name) > SHORT_NAME_LEN)
731     ofs = SHORT_NAME_LEN - len;
732   else
733     ofs = strlen (short_name);
734   strcpy (short_name + ofs, start);
735
736   /* Set name. */
737   var_set_short_name (v, short_name);
738 }
739
740
741 /* Returns the dictionary class corresponding to a variable named
742    NAME. */
743 enum dict_class
744 dict_class_from_id (const char *name) 
745 {
746   assert (name != NULL);
747
748   switch (name[0]) 
749     {
750     default:
751       return DC_ORDINARY;
752     case '$':
753       return DC_SYSTEM;
754     case '#':
755       return DC_SCRATCH;
756     }
757 }
758
759 /* Returns the name of dictionary class DICT_CLASS. */
760 const char *
761 dict_class_to_name (enum dict_class dict_class) 
762 {
763   switch (dict_class) 
764     {
765     case DC_ORDINARY:
766       return _("ordinary");
767     case DC_SYSTEM:
768       return _("system");
769     case DC_SCRATCH:
770       return _("scratch");
771     default:
772       NOT_REACHED ();
773     }
774 }
775
776 /* Return the number of bytes used when writing case_data for a variable 
777    of WIDTH */
778 int
779 width_to_bytes(int width)
780 {
781   assert (width >= 0);
782
783   if ( width == 0 ) 
784     return MAX_SHORT_STRING ;
785   else if (width <= MAX_LONG_STRING) 
786     return ROUND_UP (width, MAX_SHORT_STRING);
787   else 
788     {
789       int chunks = width / EFFECTIVE_LONG_STRING_LENGTH ;
790       int remainder = width % EFFECTIVE_LONG_STRING_LENGTH ;
791       int bytes = remainder + (chunks * (MAX_LONG_STRING + 1) );
792       return ROUND_UP (bytes, MAX_SHORT_STRING); 
793     }
794 }
795
796