Make cases simpler, faster, and easier to understand.
[pspp-builds.git] / src / language / stats / flip.c
index 0e9b56c5c87ecf7962db9cacd7083d9c29c8f2b8..7583374b22874c530f3047d0adafca477f391247 100644 (file)
@@ -1,21 +1,18 @@
-/* PSPP - computes sample statistics.
-   Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
-   Written by Ben Pfaff <blp@gnu.org>.
+/* PSPP - a program for statistical analysis.
+   Copyright (C) 1997-9, 2000, 2009 Free Software Foundation, Inc.
 
-   This program is free software; you can redistribute it and/or
-   modify it under the terms of the GNU General Public License as
-   published by the Free Software Foundation; either version 2 of the
-   License, or (at your option) any later version.
+   This program is free software: you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation, either version 3 of the License, or
+   (at your option) any later version.
 
-   This program is distributed in the hope that it will be useful, but
-   WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-   General Public License for more details.
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-   02110-1301, USA. */
+   along with this program.  If not, see <http://www.gnu.org/licenses/>. */
 
 #include "config.h"
 
 #include <float.h>
 #include <limits.h>
 #include <stdlib.h>
-#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h>
-#endif
 
-#include <data/case-sink.h>
-#include <data/case-source.h>
 #include <data/case.h>
+#include <data/casereader.h>
+#include <data/casereader-provider.h>
 #include <data/dictionary.h>
 #include <data/procedure.h>
 #include <data/settings.h>
+#include <data/short-names.h>
 #include <data/value.h>
 #include <data/variable.h>
 #include <language/command.h>
 #include <language/lexer/lexer.h>
 #include <language/lexer/variable-parser.h>
-#include <libpspp/alloc.h>
 #include <libpspp/array.h>
-#include <libpspp/message.h>
+#include <libpspp/assertion.h>
 #include <libpspp/message.h>
 #include <libpspp/misc.h>
 #include <libpspp/pool.h>
 #include <libpspp/str.h>
 
 #include "intprops.h"
+#include "minmax.h"
+#include "xalloc.h"
 
 #include "gettext.h"
 #define _(msgid) gettext (msgid)
@@ -60,84 +56,84 @@ struct varname
   };
 
 /* Represents a FLIP input program. */
-struct flip_pgm 
+struct flip_pgm
   {
     struct pool *pool;          /* Pool containing FLIP data. */
-    struct variable **var;      /* Variables to transpose. */
-    int *idx_to_fv;             /* var[]->index to compacted sink case fv. */
+    const struct variable **var;      /* Variables to transpose. */
     size_t var_cnt;             /* Number of elements in `var'. */
     int case_cnt;               /* Pre-flip case count. */
-    size_t case_size;           /* Post-flip bytes per case. */
-
-    union value *output_buf;            /* Case output buffer. */
 
     struct variable *new_names; /* Variable containing new variable names. */
     struct varname *new_names_head; /* First new variable. */
     struct varname *new_names_tail; /* Last new variable. */
 
     FILE *file;                 /* Temporary file containing data. */
+    union value *input_buf;     /* Input buffer for temporary file. */
+    size_t cases_read;          /* Number of cases already read. */
+    bool error;                 /* Error reading temporary file? */
   };
 
+static const struct casereader_class flip_casereader_class;
+
 static void destroy_flip_pgm (struct flip_pgm *);
-static struct case_sink *flip_sink_create (struct flip_pgm *);
-static struct case_source *flip_source_create (struct flip_pgm *);
 static bool flip_file (struct flip_pgm *);
-static int build_dictionary (struct flip_pgm *);
-
-static const struct case_source_class flip_source_class;
-static const struct case_sink_class flip_sink_class;
+static bool build_dictionary (struct dictionary *, struct flip_pgm *);
+static bool write_flip_case (struct flip_pgm *, const struct ccase *);
 
 /* Parses and executes FLIP. */
 int
-cmd_flip (void)
+cmd_flip (struct lexer *lexer, struct dataset *ds)
 {
+  struct dictionary *dict = dataset_dict (ds);
   struct flip_pgm *flip;
-  struct case_sink *sink;
+  struct casereader *input, *reader;
+  union value *output_buf;
+  struct ccase *c;
+  size_t i;
   bool ok;
 
-  if (proc_make_temporary_transformations_permanent ())
+  if (proc_make_temporary_transformations_permanent (ds))
     msg (SW, _("FLIP ignores TEMPORARY.  "
                "Temporary transformations will be made permanent."));
 
   flip = pool_create_container (struct flip_pgm, pool);
   flip->var = NULL;
-  flip->idx_to_fv = dict_get_compacted_idx_to_fv (default_dict);
-  pool_register (flip->pool, free, flip->idx_to_fv);
   flip->var_cnt = 0;
   flip->case_cnt = 0;
   flip->new_names = NULL;
   flip->new_names_head = NULL;
   flip->new_names_tail = NULL;
   flip->file = NULL;
+  flip->input_buf = NULL;
+  flip->cases_read = 0;
+  flip->error = false;
 
-  lex_match ('/');
-  if (lex_match_id ("VARIABLES"))
+  lex_match (lexer, '/');
+  if (lex_match_id (lexer, "VARIABLES"))
     {
-      lex_match ('=');
-      if (!parse_variables (default_dict, &flip->var, &flip->var_cnt,
-                            PV_NO_DUPLICATE))
+      lex_match (lexer, '=');
+      if (!parse_variables_const (lexer, dict, &flip->var, &flip->var_cnt,
+                                  PV_NO_DUPLICATE))
        goto error;
-      lex_match ('/');
+      lex_match (lexer, '/');
     }
   else
-    dict_get_vars (default_dict, &flip->var, &flip->var_cnt, 1u << DC_SYSTEM);
+    dict_get_vars (dict, &flip->var, &flip->var_cnt, DC_SYSTEM);
   pool_register (flip->pool, free, flip->var);
 
-  lex_match ('/');
-  if (lex_match_id ("NEWNAMES"))
+  lex_match (lexer, '/');
+  if (lex_match_id (lexer, "NEWNAMES"))
     {
-      lex_match ('=');
-      flip->new_names = parse_variable ();
+      lex_match (lexer, '=');
+      flip->new_names = parse_variable (lexer, dict);
       if (!flip->new_names)
         goto error;
     }
   else
-    flip->new_names = dict_lookup_var (default_dict, "CASE_LBL");
+    flip->new_names = dict_lookup_var (dict, "CASE_LBL");
 
   if (flip->new_names)
     {
-      size_t i;
-      
       for (i = 0; i < flip->var_cnt; i++)
        if (flip->var[i] == flip->new_names)
          {
@@ -147,36 +143,61 @@ cmd_flip (void)
          }
     }
 
+  output_buf = pool_nalloc (flip->pool, flip->var_cnt, sizeof *output_buf);
+
+  flip->file = pool_tmpfile (flip->pool);
+  if (flip->file == NULL)
+    {
+      msg (SE, _("Could not create temporary file for FLIP."));
+      goto error;
+    }
+
+  /* Write variable names as first case. */
+  for (i = 0; i < flip->var_cnt; i++)
+    buf_copy_str_rpad (output_buf[i].s, MAX_SHORT_STRING,
+                       var_get_name (flip->var[i]));
+  if (fwrite (output_buf, sizeof *output_buf,
+              flip->var_cnt, flip->file) != (size_t) flip->var_cnt)
+    {
+      msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
+      goto error;
+    }
+
+  flip->case_cnt = 1;
+
   /* Read the active file into a flip_sink. */
-  flip->case_cnt = 0;
-  proc_make_temporary_transformations_permanent ();
-  sink = flip_sink_create (flip);
-  if (sink == NULL)
-    goto error;
-  proc_set_sink (sink);
-  flip->new_names_tail = NULL;
-  ok = procedure (NULL, NULL);
+  proc_discard_output (ds);
+
+  input = proc_open (ds);
+  while ((c = casereader_read (input)) != NULL)
+    {
+      write_flip_case (flip, c);
+      case_unref (c);
+    }
+  ok = casereader_destroy (input);
+  ok = proc_commit (ds) && ok;
 
   /* Flip the data we read. */
-  if (!flip_file (flip)) 
+  if (!ok || !flip_file (flip))
     {
-      discard_variables ();
+      proc_discard_active_file (ds);
       goto error;
     }
 
   /* Flip the dictionary. */
-  dict_clear (default_dict);
-  if (!build_dictionary (flip))
+  dict_clear (dict);
+  if (!build_dictionary (dict, flip))
     {
-      discard_variables ();
+      proc_discard_active_file (ds);
       goto error;
     }
-  flip->case_size = dict_get_case_size (default_dict);
 
   /* Set up flipped data for reading. */
-  proc_set_source (flip_source_create (flip));
-
-  return ok ? lex_end_of_command () : CMD_CASCADING_FAILURE;
+  reader = casereader_create_sequential (NULL, dict_get_next_value_idx (dict),
+                                         flip->var_cnt,
+                                         &flip_casereader_class, flip);
+  proc_set_active_file_data (ds, reader);
+  return lex_end_of_command (lexer);
 
  error:
   destroy_flip_pgm (flip);
@@ -185,7 +206,7 @@ cmd_flip (void)
 
 /* Destroys FLIP. */
 static void
-destroy_flip_pgm (struct flip_pgm *flip) 
+destroy_flip_pgm (struct flip_pgm *flip)
 {
   if (flip != NULL)
     pool_destroy (flip->pool);
@@ -194,7 +215,7 @@ destroy_flip_pgm (struct flip_pgm *flip)
 /* Make a new variable with base name NAME, which is bowdlerized and
    mangled until acceptable, and returns success. */
 static int
-make_new_var (char name[])
+make_new_var (struct dictionary *dict, char name[])
 {
   char *cp;
 
@@ -205,7 +226,7 @@ make_new_var (char name[])
 
   /* Fix invalid characters. */
   for (cp = name; *cp && cp < name + SHORT_NAME_LEN; cp++)
-    if (cp == name) 
+    if (cp == name)
       {
         if (!lex_is_id1 (*cp) || *cp == '$')
           *cp = 'V';
@@ -213,12 +234,12 @@ make_new_var (char name[])
     else
       {
         if (!lex_is_idn (*cp))
-          *cp = '_'; 
+          *cp = '_';
       }
   *cp = '\0';
   str_uppercase (name);
-  
-  if (dict_create_var (default_dict, name, 0))
+
+  if (dict_create_var (dict, name, 0))
     return 1;
 
   /* Add numeric extensions until acceptable. */
@@ -229,11 +250,11 @@ make_new_var (char name[])
 
     for (i = 1; i < 10000000; i++)
       {
-       int ofs = min (7 - intlog10 (i), len);
+       int ofs = MIN (7 - intlog10 (i), len);
        memcpy (n, name, ofs);
        sprintf (&n[ofs], "%d", i);
 
-       if (dict_create_var (default_dict, n, 0))
+       if (dict_create_var (dict, n, 0))
          return 1;
       }
   }
@@ -243,28 +264,28 @@ make_new_var (char name[])
 }
 
 /* Make a new dictionary for all the new variable names. */
-static int
-build_dictionary (struct flip_pgm *flip)
+static bool
+build_dictionary (struct dictionary *dict, struct flip_pgm *flip)
 {
-  dict_create_var_assert (default_dict, "CASE_LBL", 8);
+  dict_create_var_assert (dict, "CASE_LBL", 8);
 
   if (flip->new_names_head == NULL)
     {
       int i;
-      
+
       if (flip->case_cnt > 99999)
        {
          msg (SE, _("Cannot create more than 99999 variable names."));
-         return 0;
+         return false;
        }
-      
-      for (i = 0; i < flip->case_cnt; i++)
+
+      for (i = 0; i < flip->case_cnt - 1; i++)
        {
           struct variable *v;
          char s[SHORT_NAME_LEN + 1];
 
          sprintf (s, "VAR%03d", i);
-         v = dict_create_var_assert (default_dict, s, 0);
+         v = dict_create_var_assert (dict, s, 0);
        }
     }
   else
@@ -272,62 +293,29 @@ build_dictionary (struct flip_pgm *flip)
       struct varname *v;
 
       for (v = flip->new_names_head; v; v = v->next)
-        if (!make_new_var (v->name))
-          return 0;
-    }
-  
-  return 1;
-}
-     
-/* Creates a flip sink based on FLIP. */
-static struct case_sink *
-flip_sink_create (struct flip_pgm *flip) 
-{
-  size_t i;
-
-  flip->output_buf = pool_nalloc (flip->pool,
-                                  flip->var_cnt, sizeof *flip->output_buf);
-
-  flip->file = pool_tmpfile (flip->pool);
-  if (flip->file == NULL)
-    {
-      msg (SE, _("Could not create temporary file for FLIP."));
-      return NULL;
-    }
-
-  /* Write variable names as first case. */
-  for (i = 0; i < flip->var_cnt; i++) 
-    buf_copy_str_rpad (flip->output_buf[i].s, MAX_SHORT_STRING,
-                       flip->var[i]->name);
-  if (fwrite (flip->output_buf, sizeof *flip->output_buf,
-              flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
-    {
-      msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
-      return NULL;
+        if (!make_new_var (dict, v->name))
+          return false;
     }
 
-  flip->case_cnt = 1;
-
-  return create_case_sink (&flip_sink_class, default_dict, flip);
+  return true;
 }
 
 /* Writes case C to the FLIP sink.
    Returns true if successful, false if an I/O error occurred. */
 static bool
-flip_sink_write (struct case_sink *sink, const struct ccase *c)
+write_flip_case (struct flip_pgm *flip, const struct ccase *c)
 {
-  struct flip_pgm *flip = sink->aux;
   size_t i;
-  
+
   flip->case_cnt++;
 
   if (flip->new_names != NULL)
     {
       struct varname *v = pool_alloc (flip->pool, sizeof *v);
       v->next = NULL;
-      if (flip->new_names->type == NUMERIC) 
+      if (var_is_numeric (flip->new_names))
         {
-          double f = case_num (c, flip->idx_to_fv[flip->new_names->index]);
+          double f = case_num (c, flip->new_names);
 
           if (f == SYSMIS)
             strcpy (v->name, "VSYSMIS");
@@ -340,12 +328,11 @@ flip_sink_write (struct case_sink *sink, const struct ccase *c)
         }
       else
        {
-         int width = min (flip->new_names->width, MAX_SHORT_STRING);
-         memcpy (v->name, case_str (c, flip->idx_to_fv[flip->new_names->index]),
-                  width);
+         int width = MIN (var_get_width (flip->new_names), MAX_SHORT_STRING);
+         memcpy (v->name, case_str (c, flip->new_names), width);
          v->name[width] = 0;
        }
-      
+
       if (flip->new_names_head == NULL)
        flip->new_names_head = v;
       else
@@ -356,20 +343,9 @@ flip_sink_write (struct case_sink *sink, const struct ccase *c)
   /* Write to external file. */
   for (i = 0; i < flip->var_cnt; i++)
     {
-      double out;
-      
-      if (flip->var[i]->type == NUMERIC)
-        out = case_num (c, flip->idx_to_fv[flip->var[i]->index]);
-      else
-        out = SYSMIS;
-      flip->output_buf[i].f = out;
-    }
-         
-  if (fwrite (flip->output_buf, sizeof *flip->output_buf,
-              flip->var_cnt, flip->file) != (size_t) flip->var_cnt) 
-    {
-      msg (SE, _("Error writing FLIP file: %s."), strerror (errno));
-      return false; 
+      const struct variable *v = flip->var[i];
+      double out = var_is_numeric (v) ? case_num (c, v) : SYSMIS;
+      fwrite (&out, sizeof out, 1, flip->file);
     }
   return true;
 }
@@ -386,7 +362,7 @@ flip_file (struct flip_pgm *flip)
 
   /* Allocate memory for many cases. */
   case_bytes = flip->var_cnt * sizeof *input_buf;
-  case_capacity = get_workspace () / case_bytes;
+  case_capacity = settings_get_workspace () / case_bytes;
   if (case_capacity > flip->case_cnt * 2)
     case_capacity = flip->case_cnt * 2;
   if (case_capacity < 2)
@@ -413,50 +389,45 @@ flip_file (struct flip_pgm *flip)
   output_buf = input_buf + flip->var_cnt * case_capacity;
 
   input_file = flip->file;
-  if (fseek (input_file, 0, SEEK_SET) != 0) 
+  if (fseek (input_file, 0, SEEK_SET) != 0)
     {
       msg (SE, _("Error rewinding FLIP file: %s."), strerror (errno));
       return false;
     }
-      
+
   output_file = pool_tmpfile (flip->pool);
-  if (output_file == NULL) 
+  if (output_file == NULL)
     {
       msg (SE, _("Error creating FLIP source file."));
       return false;
     }
-  
+
   for (case_idx = 0; case_idx < flip->case_cnt; )
     {
-      unsigned long read_cases = min (flip->case_cnt - case_idx,
+      unsigned long read_cases = MIN (flip->case_cnt - case_idx,
                                       case_capacity);
       size_t i;
 
-      if (read_cases != fread (input_buf, case_bytes, read_cases, input_file)) 
+      if (read_cases != fread (input_buf, case_bytes, read_cases, input_file))
         {
-          msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
+          if (ferror (input_file))
+            msg (SE, _("Error reading FLIP file: %s."), strerror (errno));
+          else
+            msg (SE, _("Unexpected end of file reading FLIP file."));
           return false;
         }
 
       for (i = 0; i < flip->var_cnt; i++)
        {
          unsigned long j;
-         
+
          for (j = 0; j < read_cases; j++)
            output_buf[j] = input_buf[i + j * flip->var_cnt];
 
-#ifndef HAVE_FSEEKO
-#define fseeko fseek
-#endif
-
-#ifndef HAVE_OFF_T
-#define off_t long int
-#endif
-
          if (fseeko (output_file,
                       sizeof *input_buf * (case_idx
                                            + (off_t) i * flip->case_cnt),
-                      SEEK_SET) != 0) 
+                      SEEK_SET) != 0)
             {
               msg (SE, _("Error seeking FLIP source file: %s."),
                    strerror (errno));
@@ -464,11 +435,11 @@ flip_file (struct flip_pgm *flip)
             }
 
          if (fwrite (output_buf, sizeof *output_buf, read_cases, output_file)
-             != read_cases) 
+             != read_cases)
             {
               msg (SE, _("Error writing FLIP source file: %s."),
                    strerror (errno));
-              return false; 
+              return false;
             }
        }
 
@@ -482,89 +453,70 @@ flip_file (struct flip_pgm *flip)
     }
   pool_unregister (flip->pool, input_buf);
   free (input_buf);
-  
-  if (fseek (output_file, 0, SEEK_SET) != 0) 
+
+  if (fseek (output_file, 0, SEEK_SET) != 0)
     {
       msg (SE, _("Error rewinding FLIP source file: %s."), strerror (errno));
-      return false; 
+      return false;
     }
   flip->file = output_file;
 
   return true;
 }
 
-/* FLIP sink class. */
-static const struct case_sink_class flip_sink_class = 
-  {
-    "FLIP",
-    NULL,
-    flip_sink_write,
-    NULL,
-    NULL,
-  };
-
-/* Creates and returns a FLIP source based on PGM,
-   which should have already been used as a sink. */
-static struct case_source *
-flip_source_create (struct flip_pgm *pgm)
+/* Reads and returns one case.
+   Returns a null pointer at end of file or if an I/O error occurred. */
+static struct ccase *
+flip_casereader_read (struct casereader *reader UNUSED, void *flip_)
 {
-  return create_case_source (&flip_source_class, pgm);
-}
-
-/* Reads the FLIP stream.  Copies each case into C and calls
-   WRITE_CASE passing WC_DATA.
-   Returns true if successful, false if an I/O error occurred. */
-static bool
-flip_source_read (struct case_source *source,
-                  struct ccase *c,
-                  write_case_func *write_case, write_case_data wc_data)
-{
-  struct flip_pgm *flip = source->aux;
-  union value *input_buf;
+  struct flip_pgm *flip = flip_;
+  struct ccase *c;
   size_t i;
-  bool ok = true;
 
-  input_buf = xnmalloc (flip->case_cnt, sizeof *input_buf);
-  for (i = 0; ok && i < flip->var_cnt; i++)
+  if (flip->error || flip->cases_read >= flip->var_cnt)
+    return NULL;
+
+  c = case_create (flip->case_cnt);
+  for (i = 0; i < flip->case_cnt; i++)
     {
-      size_t j;
-      
-      if (fread (input_buf, sizeof *input_buf, flip->case_cnt,
-                 flip->file) != flip->case_cnt) 
+      double in;
+      if (fread (&in, sizeof in, 1, flip->file) != 1)
         {
+          case_unref (c);
           if (ferror (flip->file))
             msg (SE, _("Error reading FLIP temporary file: %s."),
                  strerror (errno));
           else if (feof (flip->file))
             msg (SE, _("Unexpected end of file reading FLIP temporary file."));
           else
-            abort ();
-          ok = false;
-          break;
+            NOT_REACHED ();
+          flip->error = true;
+          return NULL;
         }
-
-      for (j = 0; j < flip->case_cnt; j++)
-        case_data_rw (c, j)->f = input_buf[j].f;
-      ok = write_case (wc_data);
+      case_data_rw_idx (c, i)->f = in;
     }
-  free (input_buf);
 
-  return ok;
+  flip->cases_read++;
+
+  return c;
 }
 
-/* Destroy internal data in SOURCE. */
+/* Destroys the source.
+   Returns true if successful read, false if an I/O occurred
+   during destruction or previously. */
 static void
-flip_source_destroy (struct case_source *source)
+flip_casereader_destroy (struct casereader *reader UNUSED, void *flip_)
 {
-  struct flip_pgm *flip = source->aux;
-
+  struct flip_pgm *flip = flip_;
+  if (flip->error)
+    casereader_force_error (reader);
   destroy_flip_pgm (flip);
 }
 
-static const struct case_source_class flip_source_class = 
+static const struct casereader_class flip_casereader_class =
   {
-    "FLIP",
+    flip_casereader_read,
+    flip_casereader_destroy,
+    NULL,
     NULL,
-    flip_source_read,
-    flip_source_destroy
   };