Move all command implementations into a single 'commands' directory.
[pspp] / src / language / commands / flip.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011, 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 <ctype.h>
20 #include <errno.h>
21 #include <float.h>
22 #include <limits.h>
23 #include <stdlib.h>
24
25 #include "data/case.h"
26 #include "data/casereader.h"
27 #include "data/casereader-provider.h"
28 #include "data/dataset.h"
29 #include "data/dictionary.h"
30 #include "data/settings.h"
31 #include "data/short-names.h"
32 #include "data/value.h"
33 #include "data/variable.h"
34 #include "language/command.h"
35 #include "language/lexer/lexer.h"
36 #include "language/lexer/variable-parser.h"
37 #include "libpspp/array.h"
38 #include "libpspp/assertion.h"
39 #include "libpspp/message.h"
40 #include "libpspp/misc.h"
41 #include "libpspp/pool.h"
42 #include "libpspp/str.h"
43 #include "data/data-in.h"
44 #include "data/data-out.h"
45
46 #include "gl/intprops.h"
47 #include "gl/minmax.h"
48 #include "gl/xalloc.h"
49
50 #include "gettext.h"
51 #define _(msgid) gettext (msgid)
52
53 /* List of variable names. */
54 struct var_names
55   {
56     const char **names;
57     size_t n_names, allocated_names;
58   };
59
60 static void var_names_init (struct var_names *);
61 static void var_names_add (struct pool *, struct var_names *, const char *);
62
63 /* Represents a FLIP input program. */
64 struct flip_pgm
65   {
66     struct pool *pool;          /* Pool containing FLIP data. */
67     size_t n_vars;              /* Pre-flip number of variables. */
68     int n_cases;                /* Pre-flip number of cases. */
69
70     struct variable *new_names_var; /* Variable with new variable names. */
71     const char *encoding;           /* Variable names' encoding. */
72     struct var_names old_names; /* Variable names before FLIP. */
73     struct var_names new_names; /* Variable names after FLIP. */
74
75     FILE *file;                 /* Temporary file containing data. */
76     size_t cases_read;          /* Number of cases already read. */
77     bool error;                 /* Error reading temporary file? */
78   };
79
80 static const struct casereader_class flip_casereader_class;
81
82 static void destroy_flip_pgm (struct flip_pgm *);
83 static bool flip_file (struct flip_pgm *);
84 static void make_new_var (struct dictionary *, const char *name);
85
86 /* Parses and executes FLIP. */
87 int
88 cmd_flip (struct lexer *lexer, struct dataset *ds)
89 {
90   struct dictionary *old_dict = dataset_dict (ds);
91   struct dictionary *new_dict = NULL;
92   const struct variable **vars;
93   struct flip_pgm *flip;
94   struct casereader *input, *reader;
95   struct ccase *c;
96   size_t i;
97   bool ok;
98
99   if (proc_make_temporary_transformations_permanent (ds))
100     lex_ofs_msg (lexer, SW, 0, lex_ofs (lexer) - 1,
101                  _("%s ignores %s.  "
102                    "Temporary transformations will be made permanent."),
103                  "FLIP", "TEMPORARY");
104
105   flip = pool_create_container (struct flip_pgm, pool);
106   flip->n_vars = 0;
107   flip->n_cases = 0;
108   flip->new_names_var = NULL;
109   var_names_init (&flip->old_names);
110   var_names_init (&flip->new_names);
111   flip->file = NULL;
112   flip->cases_read = 0;
113   flip->error = false;
114
115   lex_match (lexer, T_SLASH);
116   if (lex_match_id (lexer, "VARIABLES"))
117     {
118       lex_match (lexer, T_EQUALS);
119       if (!parse_variables_const (lexer, old_dict, &vars, &flip->n_vars,
120                                   PV_NO_DUPLICATE))
121         goto error;
122       lex_match (lexer, T_SLASH);
123     }
124   else
125     dict_get_vars (old_dict, &vars, &flip->n_vars, DC_SYSTEM);
126   pool_register (flip->pool, free, vars);
127
128   lex_match (lexer, T_SLASH);
129   if (lex_match_id (lexer, "NEWNAMES"))
130     {
131       lex_match (lexer, T_EQUALS);
132       flip->new_names_var = parse_variable (lexer, old_dict);
133       if (!flip->new_names_var)
134         goto error;
135     }
136   else
137     flip->new_names_var = dict_lookup_var (old_dict, "CASE_LBL");
138
139   if (flip->new_names_var)
140     {
141       for (i = 0; i < flip->n_vars; i++)
142         if (vars[i] == flip->new_names_var)
143           {
144             remove_element (vars, flip->n_vars, sizeof *vars, i);
145             flip->n_vars--;
146             break;
147           }
148     }
149   if (flip->n_vars <= 0)
150     goto error;
151
152   flip->file = pool_create_temp_file (flip->pool);
153   if (flip->file == NULL)
154     {
155       msg (SE, _("Could not create temporary file for %s."), "FLIP");
156       goto error;
157     }
158
159   /* Save old variable names for use as values of CASE_LBL
160      variable in flipped file. */
161   for (i = 0; i < flip->n_vars; i++)
162     var_names_add (flip->pool, &flip->old_names,
163                    pool_strdup (flip->pool, var_get_name (vars[i])));
164
165   /* Read the active dataset into a flip_sink. */
166   proc_discard_output (ds);
167
168   /* Save old dictionary. */
169   new_dict = dict_clone (old_dict);
170   flip->encoding = dict_get_encoding (new_dict);
171   dict_clear (new_dict);
172
173   input = proc_open_filtering (ds, false);
174   while ((c = casereader_read (input)) != NULL)
175     {
176       flip->n_cases++;
177       for (i = 0; i < flip->n_vars; i++)
178         {
179           const struct variable *v = vars[i];
180           double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
181           fwrite (&out, sizeof out, 1, flip->file);
182         }
183       if (flip->new_names_var != NULL)
184         {
185           const union value *value = case_data (c, flip->new_names_var);
186           const char *name;
187           if (var_is_numeric (flip->new_names_var))
188             {
189               double f = value->f;
190               name = (f == SYSMIS ? "VSYSMIS"
191                       : f < INT_MIN ? "VNEGINF"
192                       : f > INT_MAX ? "VPOSINF"
193                       : pool_asprintf (flip->pool, "V%d", (int) f));
194             }
195           else
196             {
197               name = data_out_pool (value, dict_get_encoding (old_dict),
198                                     var_get_write_format (flip->new_names_var),
199                                     settings_get_fmt_settings (), flip->pool);
200             }
201           var_names_add (flip->pool, &flip->new_names, name);
202         }
203       case_unref (c);
204     }
205   ok = casereader_destroy (input);
206   ok = proc_commit (ds) && ok;
207
208   /* Flip the data we read. */
209   if (!ok || !flip_file (flip))
210     {
211       dataset_clear (ds);
212       goto error;
213     }
214
215   /* Flip the dictionary. */
216   dict_create_var_assert (new_dict, "CASE_LBL", 8);
217   for (i = 0; i < flip->n_cases; i++)
218     if (flip->new_names.n_names)
219       make_new_var (new_dict, flip->new_names.names[i]);
220     else
221       {
222         char s[3 + INT_STRLEN_BOUND (i) + 1];
223         sprintf (s, "VAR%03zu", i);
224         dict_create_var_assert (new_dict, s, 0);
225       }
226
227   /* Set up flipped data for reading. */
228   reader = casereader_create_sequential (NULL, dict_get_proto (new_dict),
229                                          flip->n_vars,
230                                          &flip_casereader_class, flip);
231   dataset_set_dict (ds, new_dict);
232   dataset_set_source (ds, reader);
233   return CMD_SUCCESS;
234
235  error:
236   dict_unref (new_dict);
237   destroy_flip_pgm (flip);
238   return CMD_CASCADING_FAILURE;
239 }
240
241 /* Destroys FLIP. */
242 static void
243 destroy_flip_pgm (struct flip_pgm *flip)
244 {
245   if (flip != NULL)
246     pool_destroy (flip->pool);
247 }
248
249 /* Make a new variable with base name NAME, which is bowdlerized and
250    mangled until acceptable. */
251 static void
252 make_new_var (struct dictionary *dict, const char *name_)
253 {
254   char *name = xstrdup (name_);
255   char *cp;
256
257   /* Trim trailing spaces. */
258   cp = strchr (name, '\0');
259   while (cp > name && isspace ((unsigned char) cp[-1]))
260     *--cp = '\0';
261
262   /* Fix invalid characters. */
263   for (cp = name; *cp && cp < name + ID_MAX_LEN; cp++)
264     if (cp == name)
265       {
266         if (!lex_is_id1 (*cp) || *cp == '$')
267           *cp = 'V';
268       }
269     else
270       {
271         if (!lex_is_idn (*cp))
272           *cp = '_';
273       }
274   *cp = '\0';
275
276   if (strlen (name) == 0)
277     {
278       free (name);
279       name = xstrdup ("v");
280     }
281
282   /* Use the mangled name, if it is available, or add numeric
283      extensions until we find one that is. */
284   if (!id_is_plausible (name) || !dict_create_var (dict, name, 0))
285     {
286       int len = strlen (name);
287       int i;
288       for (i = 1; ; i++)
289         {
290           char n[ID_MAX_LEN + 1];
291           int ofs = MIN (ID_MAX_LEN - 1 - intlog10 (i), len);
292           strncpy (n, name, ofs);
293           sprintf (&n[ofs], "%d", i);
294
295           if (id_is_plausible (n) && dict_create_var (dict, n, 0))
296             break;
297         }
298     }
299   free (name);
300 }
301
302 /* Transposes the external file into a new file. */
303 static bool
304 flip_file (struct flip_pgm *flip)
305 {
306   size_t case_bytes;
307   size_t case_capacity;
308   size_t case_idx;
309   double *input_buf, *output_buf;
310   FILE *input_file, *output_file;
311
312   /* Allocate memory for many cases. */
313   case_bytes = flip->n_vars * sizeof *input_buf;
314   case_capacity = settings_get_workspace () / case_bytes;
315   if (case_capacity > flip->n_cases * 2)
316     case_capacity = flip->n_cases * 2;
317   if (case_capacity < 2)
318     case_capacity = 2;
319   for (;;)
320     {
321       size_t bytes = case_bytes * case_capacity;
322       if (case_capacity > 2)
323         input_buf = malloc (bytes);
324       else
325         input_buf = xmalloc (bytes);
326       if (input_buf != NULL)
327         break;
328
329       case_capacity /= 2;
330       if (case_capacity < 2)
331         case_capacity = 2;
332     }
333   pool_register (flip->pool, free, input_buf);
334
335   /* Use half the allocated memory for input_buf, half for
336      output_buf. */
337   case_capacity /= 2;
338   output_buf = input_buf + flip->n_vars * case_capacity;
339
340   input_file = flip->file;
341   if (fseeko (input_file, 0, SEEK_SET) != 0)
342     {
343       msg (SE, _("Error rewinding %s file: %s."), "FLIP", strerror (errno));
344       return false;
345     }
346
347   output_file = pool_create_temp_file (flip->pool);
348   if (output_file == NULL)
349     {
350       msg (SE, _("Error creating %s source file."), "FLIP");
351       return false;
352     }
353
354   for (case_idx = 0; case_idx < flip->n_cases;)
355     {
356       unsigned long read_cases = MIN (flip->n_cases - case_idx,
357                                       case_capacity);
358       size_t i;
359
360       if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
361         {
362           if (ferror (input_file))
363             msg (SE, _("Error reading %s file: %s."), "FLIP", strerror (errno));
364           else
365             msg (SE, _("Unexpected end of file reading %s file."), "FLIP");
366           return false;
367         }
368
369       for (i = 0; i < flip->n_vars; i++)
370         {
371           unsigned long j;
372
373           for (j = 0; j < read_cases; j++)
374             output_buf[j] = input_buf[i + j * flip->n_vars];
375
376           if (fseeko (output_file,
377                       sizeof *input_buf * (case_idx
378                                            + (off_t) i * flip->n_cases),
379                       SEEK_SET) != 0)
380             {
381               msg (SE, _("Error seeking %s source file: %s."), "FLIP",
382                    strerror (errno));
383               return false;
384             }
385
386           if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
387               != read_cases)
388             {
389               msg (SE, _("Error writing %s source file: %s."), "FLIP",
390                    strerror (errno));
391               return false;
392             }
393         }
394
395       case_idx += read_cases;
396     }
397
398   pool_fclose_temp_file (flip->pool, input_file);
399   pool_unregister (flip->pool, input_buf);
400   free (input_buf);
401
402   if (fseeko (output_file, 0, SEEK_SET) != 0)
403     {
404       msg (SE, _("Error rewinding %s source file: %s."), "FLIP", strerror (errno));
405       return false;
406     }
407   flip->file = output_file;
408
409   return true;
410 }
411
412 /* Reads and returns one case.
413    Returns a null pointer at end of file or if an I/O error occurred. */
414 static struct ccase *
415 flip_casereader_read (struct casereader *reader, void *flip_)
416 {
417   struct flip_pgm *flip = flip_;
418   struct ccase *c;
419   size_t i;
420
421   if (flip->error || flip->cases_read >= flip->n_vars)
422     return false;
423
424   c = case_create (casereader_get_proto (reader));
425   data_in (ss_cstr (flip->old_names.names[flip->cases_read]), flip->encoding,
426            FMT_A, settings_get_fmt_settings (), case_data_rw_idx (c, 0),
427            8, flip->encoding);
428
429   for (i = 0; i < flip->n_cases; i++)
430     {
431       double in;
432       if (fread (&in, sizeof in, 1, flip->file) != 1)
433         {
434           case_unref (c);
435           if (ferror (flip->file))
436             msg (SE, _("Error reading %s temporary file: %s."), "FLIP",
437                  strerror (errno));
438           else if (feof (flip->file))
439             msg (SE, _("Unexpected end of file reading %s temporary file."), "FLIP");
440           else
441             NOT_REACHED ();
442           flip->error = true;
443           return NULL;
444         }
445       *case_num_rw_idx (c, i + 1) = in;
446     }
447
448   flip->cases_read++;
449
450   return c;
451 }
452
453 /* Destroys the source.
454    Returns true if successful read, false if an I/O occurred
455    during destruction or previously. */
456 static void
457 flip_casereader_destroy (struct casereader *reader, void *flip_)
458 {
459   struct flip_pgm *flip = flip_;
460   if (flip->error)
461     casereader_force_error (reader);
462   destroy_flip_pgm (flip);
463 }
464
465 static const struct casereader_class flip_casereader_class =
466   {
467     flip_casereader_read,
468     flip_casereader_destroy,
469     NULL,
470     NULL,
471   };
472 \f
473 static void
474 var_names_init (struct var_names *vn)
475 {
476   vn->names = NULL;
477   vn->n_names = 0;
478   vn->allocated_names = 0;
479 }
480
481 static void
482 var_names_add (struct pool *pool, struct var_names *vn, const char *name)
483 {
484   if (vn->n_names >= vn->allocated_names)
485     vn->names = pool_2nrealloc (pool, vn->names, &vn->allocated_names,
486                                 sizeof *vn->names);
487   vn->names[vn->n_names++] = name;
488 }
489