Apply patch #5225, assertions.
[pspp-builds.git] / src / language / stats / flip.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
22 #include <ctype.h>
23 #include <errno.h>
24 #include <float.h>
25 #include <limits.h>
26 #include <stdlib.h>
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
29 #endif
30
31 #include <data/case-sink.h>
32 #include <data/case-source.h>
33 #include <data/case.h>
34 #include <data/dictionary.h>
35 #include <data/procedure.h>
36 #include <data/settings.h>
37 #include <data/value.h>
38 #include <data/variable.h>
39 #include <language/command.h>
40 #include <language/lexer/lexer.h>
41 #include <language/lexer/variable-parser.h>
42 #include <libpspp/alloc.h>
43 #include <libpspp/array.h>
44 #include <libpspp/assertion.h>
45 #include <libpspp/message.h>
46 #include <libpspp/message.h>
47 #include <libpspp/misc.h>
48 #include <libpspp/pool.h>
49 #include <libpspp/str.h>
50
51 #include "intprops.h"
52
53 #include "gettext.h"
54 #define _(msgid) gettext (msgid)
55
56 /* List of variable names. */
57 struct varname
58   {
59     struct varname *next;
60     char name[SHORT_NAME_LEN + 1];
61   };
62
63 /* Represents a FLIP input program. */
64 struct flip_pgm 
65   {
66     struct pool *pool;          /* Pool containing FLIP data. */
67     struct variable **var;      /* Variables to transpose. */
68     int *idx_to_fv;             /* var[]->index to compacted sink case fv. */
69     size_t var_cnt;             /* Number of elements in `var'. */
70     int case_cnt;               /* Pre-flip case count. */
71     size_t case_size;           /* Post-flip bytes per case. */
72
73     union value *output_buf;            /* Case output buffer. */
74
75     struct variable *new_names; /* Variable containing new variable names. */
76     struct varname *new_names_head; /* First new variable. */
77     struct varname *new_names_tail; /* Last new variable. */
78
79     FILE *file;                 /* Temporary file containing data. */
80   };
81
82 static void destroy_flip_pgm (struct flip_pgm *);
83 static struct case_sink *flip_sink_create (struct flip_pgm *);
84 static struct case_source *flip_source_create (struct flip_pgm *);
85 static bool flip_file (struct flip_pgm *);
86 static int build_dictionary (struct flip_pgm *);
87
88 static const struct case_source_class flip_source_class;
89 static const struct case_sink_class flip_sink_class;
90
91 /* Parses and executes FLIP. */
92 int
93 cmd_flip (void)
94 {
95   struct flip_pgm *flip;
96   struct case_sink *sink;
97   bool ok;
98
99   if (proc_make_temporary_transformations_permanent ())
100     msg (SW, _("FLIP ignores TEMPORARY.  "
101                "Temporary transformations will be made permanent."));
102
103   flip = pool_create_container (struct flip_pgm, pool);
104   flip->var = NULL;
105   flip->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
106   pool_register (flip->pool, free, flip->idx_to_fv);
107   flip->var_cnt = 0;
108   flip->case_cnt = 0;
109   flip->new_names = NULL;
110   flip->new_names_head = NULL;
111   flip->new_names_tail = NULL;
112   flip->file = NULL;
113
114   lex_match ('/');
115   if (lex_match_id ("VARIABLES"))
116     {
117       lex_match ('=');
118       if (!parse_variables (default_dict, &flip->var, &flip->var_cnt,
119                             PV_NO_DUPLICATE))
120         goto error;
121       lex_match ('/');
122     }
123   else
124     dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
125   pool_register (flip->pool, free, flip->var);
126
127   lex_match ('/');
128   if (lex_match_id ("NEWNAMES"))
129     {
130       lex_match ('=');
131       flip->new_names = parse_variable ();
132       if (!flip->new_names)
133         goto error;
134     }
135   else
136     flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
137
138   if (flip->new_names)
139     {
140       size_t i;
141       
142       for (i = 0; i < flip->var_cnt; i++)
143         if (flip->var[i] == flip->new_names)
144           {
145             remove_element (flip->var, flip->var_cnt, sizeof *flip->var, i);
146             flip->var_cnt--;
147             break;
148           }
149     }
150
151   /* Read the active file into a flip_sink. */
152   flip->case_cnt = 0;
153   proc_make_temporary_transformations_permanent ();
154   sink = flip_sink_create (flip);
155   if (sink == NULL)
156     goto error;
157   proc_set_sink (sink);
158   flip->new_names_tail = NULL;
159   ok = procedure (NULL, NULL);
160
161   /* Flip the data we read. */
162   if (!flip_file (flip)) 
163     {
164       discard_variables ();
165       goto error;
166     }
167
168   /* Flip the dictionary. */
169   dict_clear (default_dict);
170   if (!build_dictionary (flip))
171     {
172       discard_variables ();
173       goto error;
174     }
175   flip->case_size = dict_get_case_size (default_dict);
176
177   /* Set up flipped data for reading. */
178   proc_set_source (flip_source_create (flip));
179
180   return ok ? lex_end_of_command () : CMD_CASCADING_FAILURE;
181
182  error:
183   destroy_flip_pgm (flip);
184   return CMD_CASCADING_FAILURE;
185 }
186
187 /* Destroys FLIP. */
188 static void
189 destroy_flip_pgm (struct flip_pgm *flip) 
190 {
191   if (flip != NULL)
192     pool_destroy (flip->pool);
193 }
194
195 /* Make a new variable with base name NAME, which is bowdlerized and
196    mangled until acceptable, and returns success. */
197 static int
198 make_new_var (char name[])
199 {
200   char *cp;
201
202   /* Trim trailing spaces. */
203   cp = strchr (name, '\0');
204   while (cp > name && isspace ((unsigned char) cp[-1]))
205     *--cp = '\0';
206
207   /* Fix invalid characters. */
208   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
209     if (cp == name) 
210       {
211         if (!lex_is_id1 (*cp) || *cp == '$')
212           *cp = 'V';
213       }
214     else
215       {
216         if (!lex_is_idn (*cp))
217           *cp = '_'; 
218       }
219   *cp = '\0';
220   str_uppercase (name);
221   
222   if (dict_create_var (default_dict, name, 0))
223     return 1;
224
225   /* Add numeric extensions until acceptable. */
226   {
227     const int len = (int) strlen (name);
228     char n[SHORT_NAME_LEN + 1];
229     int i;
230
231     for (i = 1; i < 10000000; i++)
232       {
233         int ofs = min (7 - intlog10 (i), len);
234         memcpy (n, name, ofs);
235         sprintf (&n[ofs], "%d", i);
236
237         if (dict_create_var (default_dict, n, 0))
238           return 1;
239       }
240   }
241
242   msg (SE, _("Could not create acceptable variant for variable %s."), name);
243   return 0;
244 }
245
246 /* Make a new dictionary for all the new variable names. */
247 static int
248 build_dictionary (struct flip_pgm *flip)
249 {
250   dict_create_var_assert (default_dict, "CASE_LBL", 8);
251
252   if (flip->new_names_head == NULL)
253     {
254       int i;
255       
256       if (flip->case_cnt > 99999)
257         {
258           msg (SE, _("Cannot create more than 99999 variable names."));
259           return 0;
260         }
261       
262       for (i = 0; i < flip->case_cnt; i++)
263         {
264           struct variable *v;
265           char s[SHORT_NAME_LEN + 1];
266
267           sprintf (s, "VAR%03d", i);
268           v = dict_create_var_assert (default_dict, s, 0);
269         }
270     }
271   else
272     {
273       struct varname *v;
274
275       for (v = flip->new_names_head; v; v = v->next)
276         if (!make_new_var (v->name))
277           return 0;
278     }
279   
280   return 1;
281 }
282      
283 /* Creates a flip sink based on FLIP. */
284 static struct case_sink *
285 flip_sink_create (struct flip_pgm *flip) 
286 {
287   size_t i;
288
289   flip->output_buf = pool_nalloc (flip->pool,
290                                   flip->var_cnt, sizeof *flip->output_buf);
291
292   flip->file = pool_tmpfile (flip->pool);
293   if (flip->file == NULL)
294     {
295       msg (SE, _("Could not create temporary file for FLIP."));
296       return NULL;
297     }
298
299   /* Write variable names as first case. */
300   for (i = 0; i < flip->var_cnt; i++) 
301     buf_copy_str_rpad (flip->output_buf[i].s, MAX_SHORT_STRING,
302                        flip->var[i]->name);
303   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
304               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
305     {
306       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
307       return NULL;
308     }
309
310   flip->case_cnt = 1;
311
312   return create_case_sink (&flip_sink_class, default_dict, flip);
313 }
314
315 /* Writes case C to the FLIP sink.
316    Returns true if successful, false if an I/O error occurred. */
317 static bool
318 flip_sink_write (struct case_sink *sink, const struct ccase *c)
319 {
320   struct flip_pgm *flip = sink->aux;
321   size_t i;
322   
323   flip->case_cnt++;
324
325   if (flip->new_names != NULL)
326     {
327       struct varname *v = pool_alloc (flip->pool, sizeof *v);
328       v->next = NULL;
329       if (flip->new_names->type == NUMERIC) 
330         {
331           double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
332
333           if (f == SYSMIS)
334             strcpy (v->name, "VSYSMIS");
335           else if (f < INT_MIN)
336             strcpy (v->name, "VNEGINF");
337           else if (f > INT_MAX)
338             strcpy (v->name, "VPOSINF");
339           else
340             snprintf (v->name, sizeof v->name, "V%d", (int) f);
341         }
342       else
343         {
344           int width = min (flip->new_names->width, MAX_SHORT_STRING);
345           memcpy (v->name, case_str (c, flip->idx_to_fv[flip->new_names->index]),
346                   width);
347           v->name[width] = 0;
348         }
349       
350       if (flip->new_names_head == NULL)
351         flip->new_names_head = v;
352       else
353         flip->new_names_tail->next = v;
354       flip->new_names_tail = v;
355     }
356
357   /* Write to external file. */
358   for (i = 0; i < flip->var_cnt; i++)
359     {
360       double out;
361       
362       if (flip->var[i]->type == NUMERIC)
363         out = case_num (c, flip->idx_to_fv[flip->var[i]->index]);
364       else
365         out = SYSMIS;
366       flip->output_buf[i].f = out;
367     }
368           
369   if (fwrite (flip->output_buf, sizeof *flip->output_buf,
370               flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
371     {
372       msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
373       return false; 
374     }
375   return true;
376 }
377
378 /* Transposes the external file into a new file. */
379 static bool
380 flip_file (struct flip_pgm *flip)
381 {
382   size_t case_bytes;
383   size_t case_capacity;
384   size_t case_idx;
385   union value *input_buf, *output_buf;
386   FILE *input_file, *output_file;
387
388   /* Allocate memory for many cases. */
389   case_bytes = flip->var_cnt * sizeof *input_buf;
390   case_capacity = get_workspace () / case_bytes;
391   if (case_capacity > flip->case_cnt * 2)
392     case_capacity = flip->case_cnt * 2;
393   if (case_capacity < 2)
394     case_capacity = 2;
395   for (;;)
396     {
397       size_t bytes = case_bytes * case_capacity;
398       if (case_capacity > 2)
399         input_buf = malloc (bytes);
400       else
401         input_buf = xmalloc (bytes);
402       if (input_buf != NULL)
403         break;
404
405       case_capacity /= 2;
406       if (case_capacity < 2)
407         case_capacity = 2;
408     }
409   pool_register (flip->pool, free, input_buf);
410
411   /* Use half the allocated memory for input_buf, half for
412      output_buf. */
413   case_capacity /= 2;
414   output_buf = input_buf + flip->var_cnt * case_capacity;
415
416   input_file = flip->file;
417   if (fseek (input_file, 0, SEEK_SET) != 0) 
418     {
419       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
420       return false;
421     }
422       
423   output_file = pool_tmpfile (flip->pool);
424   if (output_file == NULL) 
425     {
426       msg (SE, _("Error creating FLIP source file."));
427       return false;
428     }
429   
430   for (case_idx = 0; case_idx < flip->case_cnt; )
431     {
432       unsigned long read_cases = min (flip->case_cnt - case_idx,
433                                       case_capacity);
434       size_t i;
435
436       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file)) 
437         {
438           msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
439           return false;
440         }
441
442       for (i = 0; i < flip->var_cnt; i++)
443         {
444           unsigned long j;
445           
446           for (j = 0; j < read_cases; j++)
447             output_buf[j] = input_buf[i + j * flip->var_cnt];
448
449 #ifndef HAVE_FSEEKO
450 #define fseeko fseek
451 #endif
452
453 #ifndef HAVE_OFF_T
454 #define off_t long int
455 #endif
456
457           if (fseeko (output_file,
458                       sizeof *input_buf * (case_idx
459                                            + (off_t) i * flip->case_cnt),
460                       SEEK_SET) != 0) 
461             {
462               msg (SE, _("Error seeking FLIP source file: %s."),
463                    strerror (errno));
464               return false;
465             }
466
467           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
468               != read_cases) 
469             {
470               msg (SE, _("Error writing FLIP source file: %s."),
471                    strerror (errno));
472               return false; 
473             }
474         }
475
476       case_idx += read_cases;
477     }
478
479   if (pool_fclose (flip->pool, input_file) == EOF)
480     {
481       msg (SE, _("Error closing FLIP source file: %s."), strerror (errno));
482       return false;
483     }
484   pool_unregister (flip->pool, input_buf);
485   free (input_buf);
486   
487   if (fseek (output_file, 0, SEEK_SET) != 0) 
488     {
489       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
490       return false; 
491     }
492   flip->file = output_file;
493
494   return true;
495 }
496
497 /* FLIP sink class. */
498 static const struct case_sink_class flip_sink_class = 
499   {
500     "FLIP",
501     NULL,
502     flip_sink_write,
503     NULL,
504     NULL,
505   };
506
507 /* Creates and returns a FLIP source based on PGM,
508    which should have already been used as a sink. */
509 static struct case_source *
510 flip_source_create (struct flip_pgm *pgm)
511 {
512   return create_case_source (&flip_source_class, pgm);
513 }
514
515 /* Reads the FLIP stream.  Copies each case into C and calls
516    WRITE_CASE passing WC_DATA.
517    Returns true if successful, false if an I/O error occurred. */
518 static bool
519 flip_source_read (struct case_source *source,
520                   struct ccase *c,
521                   write_case_func *write_case, write_case_data wc_data)
522 {
523   struct flip_pgm *flip = source->aux;
524   union value *input_buf;
525   size_t i;
526   bool ok = true;
527
528   input_buf = xnmalloc (flip->case_cnt, sizeof *input_buf);
529   for (i = 0; ok && i < flip->var_cnt; i++)
530     {
531       size_t j;
532       
533       if (fread (input_buf, sizeof *input_buf, flip->case_cnt,
534                  flip->file) != flip->case_cnt) 
535         {
536           if (ferror (flip->file))
537             msg (SE, _("Error reading FLIP temporary file: %s."),
538                  strerror (errno));
539           else if (feof (flip->file))
540             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
541           else
542             NOT_REACHED ();
543           ok = false;
544           break;
545         }
546
547       for (j = 0; j < flip->case_cnt; j++)
548         case_data_rw (c, j)->f = input_buf[j].f;
549       ok = write_case (wc_data);
550     }
551   free (input_buf);
552
553   return ok;
554 }
555
556 /* Destroy internal data in SOURCE. */
557 static void
558 flip_source_destroy (struct case_source *source)
559 {
560   struct flip_pgm *flip = source->aux;
561
562   destroy_flip_pgm (flip);
563 }
564
565 static const struct case_source_class flip_source_class = 
566   {
567     "FLIP",
568     NULL,
569     flip_source_read,
570     flip_source_destroy
571   };