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