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