work on PRINT encoding
[pspp] / perl-module / PSPP.xs
1 /* PSPP - computes sample statistics.
2    Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19
20 #include <config.h>
21
22 /* The Gnulib "strftime" module defines my_strftime in <config.h> for use by
23    gl/strftime.c.  Perl also defines my_strftime in embed.h for some other
24    purpose.  The former definition doesn't matter in this file, so suppress it
25    to avoid a compiler warning. */
26 #undef my_strftime
27
28 #include "EXTERN.h"
29 #include "perl.h"
30 #include "XSUB.h"
31
32 #include "ppport.h"
33
34 #include "minmax.h"
35 #include <libpspp/message.h>
36 #include <libpspp/version.h>
37 #include <libpspp/i18n.h>
38 #include <gl/xalloc.h>
39 #include <data/dictionary.h>
40 #include <data/case.h>
41 #include <data/casereader.h>
42 #include <data/casewriter.h>
43 #include <data/variable.h>
44 #include <data/attributes.h>
45 #include <data/file-handle-def.h>
46 #include <data/identifier.h>
47 #include <data/settings.h>
48 #include <data/sys-file-writer.h>
49 #include <data/sys-file-reader.h>
50 #include <data/value.h>
51 #include <data/vardict.h>
52 #include <data/value-labels.h>
53 #include <data/format.h>
54 #include <data/data-in.h>
55 #include <data/data-out.h>
56 #include <string.h>
57
58 typedef struct fmt_spec input_format ;
59 typedef struct fmt_spec output_format ;
60
61
62 /*  A thin wrapper around sfm_writer */
63 struct sysfile_info
64 {
65   bool opened;
66
67   /* A pointer to the writer. The writer is owned by the struct */
68   struct casewriter *writer;
69
70   /* A pointer to the dictionary. Owned externally */
71   const struct dictionary *dict;
72
73   /* The scalar containing the dictionary */
74   SV *dict_sv;
75 };
76
77
78 /*  A thin wrapper around sfm_reader */
79 struct sysreader_info
80 {
81   struct sfm_read_info opts;
82
83   /* A pointer to the reader. The reader is owned by the struct */
84   struct casereader *reader;
85
86   /* A pointer to the dictionary. */
87   struct dictionary *dict;
88 };
89
90
91
92 /*  A message handler which writes messages to PSPP::errstr */
93 static void
94 message_handler (const struct msg *m, void *aux)
95 {
96  SV *errstr = get_sv("PSPP::errstr", TRUE);
97  sv_setpv (errstr, m->text);
98 }
99
100 static int
101 sysfile_close (struct sysfile_info *sfi)
102 {
103   int retval ;
104   if ( ! sfi->opened )
105     return 0;
106
107   retval = casewriter_destroy (sfi->writer);
108   if (retval > 0 )
109     sfi->opened = false;
110
111   return retval;
112 }
113
114 static void
115 scalar_to_value (union value *val, SV *scalar, const struct variable *var)
116 {
117   if ( var_is_numeric (var))
118     {
119         if ( SvNOK (scalar) || SvIOK (scalar) )
120            val->f = SvNV (scalar);
121         else
122            val->f = SYSMIS;
123     }
124   else
125     {
126         STRLEN len;
127         const char *p = SvPV (scalar, len);
128         int width = var_get_width (var);
129         value_set_missing (val, width);
130         memcpy (value_str_rw (val, width), p, len);
131     }
132 }
133
134
135 static SV *
136 value_to_scalar (const union value *val, const struct variable *var)
137 {
138   if ( var_is_numeric (var))
139     {
140       if ( var_is_value_missing (var, val, MV_SYSTEM))
141         return newSVpvn ("", 0);
142
143       return newSVnv (val->f);
144     }
145   else
146     {
147       int width = var_get_width (var);
148       return newSVpvn (value_str (val, width), width);
149     }
150 }
151
152
153 static void
154 var_set_input_format (struct variable *v, input_format ip_fmt)
155 {
156   struct fmt_spec *if_copy = malloc (sizeof (*if_copy));
157   memcpy (if_copy, &ip_fmt, sizeof (ip_fmt));
158   var_attach_aux (v, if_copy, var_dtor_free);
159 }
160
161 static void
162 make_value_from_scalar (union value *uv, SV *val, const struct variable *var)
163 {
164  value_init (uv, var_get_width (var));
165  scalar_to_value (uv, val, var);
166 }
167
168
169 MODULE = PSPP
170
171 MODULE = PSPP           PACKAGE = PSPP
172
173 PROTOTYPES: ENABLE
174
175 void
176 onBoot (ver)
177  const char *ver
178 CODE:
179  /* Check that the version is correct up to the length of 'ver'.
180     This allows PSPP autobuilders to add a "-build#" suffix to the
181     PSPP version without causing failures here. */
182  assert (0 == strncmp (ver, bare_version, strlen (ver)));
183
184  i18n_init ();
185  msg_set_handler (message_handler, NULL);
186  settings_init ();
187  fh_init ();
188
189 SV *
190 format_value (val, var)
191  SV *val
192  struct variable *var
193 CODE:
194  SV *ret;
195  const struct fmt_spec *fmt = var_get_print_format (var);
196  union value uv;
197  char *s;
198  make_value_from_scalar (&uv, val, var);
199  s = data_out (&uv, var_get_encoding (var), fmt);
200  value_destroy (&uv, var_get_width (var));
201  ret = newSVpv (s, fmt->w);
202  free (s);
203  RETVAL = ret;
204  OUTPUT:
205 RETVAL
206
207
208 int
209 value_is_missing (val, var)
210  SV *val
211  struct variable *var
212 CODE:
213  union value uv;
214  int ret;
215  make_value_from_scalar (&uv, val, var);
216  ret = var_is_value_missing (var, &uv, MV_ANY);
217  value_destroy (&uv, var_get_width (var));
218  RETVAL = ret;
219  OUTPUT:
220 RETVAL
221
222
223
224 MODULE = PSPP           PACKAGE = PSPP::Dict
225
226 struct dictionary *
227 pxs_dict_new()
228 CODE:
229  RETVAL = dict_create ("UTF-8");
230 OUTPUT:
231  RETVAL
232
233
234 void
235 DESTROY (dict)
236  struct dictionary *dict
237 CODE:
238  dict_destroy (dict);
239
240
241 int
242 get_var_cnt (dict)
243  struct dictionary *dict
244 CODE:
245  RETVAL = dict_get_var_cnt (dict);
246 OUTPUT:
247 RETVAL
248
249 void
250 set_label (dict, label)
251  struct dictionary *dict
252  char *label
253 CODE:
254  dict_set_label (dict, label);
255
256 void
257 set_documents (dict, docs)
258  struct dictionary *dict
259  char *docs
260 CODE:
261  dict_set_documents_string (dict, docs);
262
263
264 void
265 add_document (dict, doc)
266  struct dictionary *dict
267  char *doc
268 CODE:
269  dict_add_document_line (dict, doc, false);
270
271
272 void
273 clear_documents (dict)
274  struct dictionary *dict
275 CODE:
276  dict_clear_documents (dict);
277
278
279 void
280 set_weight (dict, var)
281  struct dictionary *dict
282  struct variable *var
283 CODE:
284  dict_set_weight (dict, var);
285
286
287 struct variable *
288 pxs_get_variable (dict, idx)
289  struct dictionary *dict
290  SV *idx
291 INIT:
292  SV *errstr = get_sv("PSPP::errstr", TRUE);
293  sv_setpv (errstr, "");
294  if ( SvIV (idx) >= dict_get_var_cnt (dict))
295   {
296     sv_setpv (errstr, "The dictionary doesn't have that many variables.");
297     XSRETURN_UNDEF;
298   }
299 CODE:
300  RETVAL = dict_get_var (dict, SvIV (idx));
301  OUTPUT:
302 RETVAL
303
304
305 struct variable *
306 pxs_get_var_by_name (dict, name)
307  struct dictionary *dict
308  const char *name
309 INIT:
310  SV *errstr = get_sv("PSPP::errstr", TRUE);
311  sv_setpv (errstr, "");
312 CODE:
313  struct variable *var = dict_lookup_var (dict, name);
314  if ( ! var )
315       sv_setpv (errstr, "No such variable.");
316  RETVAL = var;
317  OUTPUT:
318 RETVAL
319
320
321 MODULE = PSPP           PACKAGE = PSPP::Var
322
323
324 struct variable *
325 pxs_dict_create_var (dict, name, ip_fmt)
326  struct dictionary * dict
327  char *name
328  input_format ip_fmt
329 INIT:
330  SV *errstr = get_sv("PSPP::errstr", TRUE);
331  sv_setpv (errstr, "");
332  if ( ! id_is_plausible (name, false))
333   {
334     sv_setpv (errstr, "The variable name is not valid.");
335     XSRETURN_UNDEF;
336   }
337 CODE:
338  struct fmt_spec op_fmt;
339
340  struct variable *v;
341  op_fmt = fmt_for_output_from_input (&ip_fmt);
342  v = dict_create_var (dict, name,
343         fmt_is_string (op_fmt.type) ? op_fmt.w : 0);
344  if ( NULL == v )
345   {
346     sv_setpv (errstr, "The variable could not be created (probably already exists).");
347     XSRETURN_UNDEF;
348   }
349  var_set_both_formats (v, &op_fmt);
350  var_set_input_format (v, ip_fmt);
351  RETVAL = v;
352 OUTPUT:
353  RETVAL
354
355
356 int
357 set_missing_values (var, v1, ...)
358  struct variable *var;
359  SV *v1;
360 INIT:
361  int i;
362  union value val[3];
363
364  if ( items > 4 )
365   croak ("No more than 3 missing values are permitted");
366
367  for (i = 0; i < items - 1; ++i)
368    scalar_to_value (&val[i], ST(i+1), var);
369 CODE:
370  struct missing_values mv;
371  mv_init (&mv, var_get_width (var));
372  for (i = 0 ; i < items - 1; ++i )
373    mv_add_value (&mv, &val[i]);
374  var_set_missing_values (var, &mv);
375
376
377 void
378 set_label (var, label)
379  struct variable *var;
380  char *label
381 CODE:
382   var_set_label (var, label, false);
383
384
385 void
386 clear_value_labels (var)
387  struct variable *var;
388 CODE:
389  var_clear_value_labels (var);
390
391 SV *
392 get_write_format (var)
393  struct variable *var
394 CODE:
395  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
396  const struct fmt_spec *fmt = var_get_write_format (var);
397
398  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
399  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
400  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
401
402  RETVAL = newRV ((SV *) fmthash);
403  OUTPUT:
404 RETVAL
405
406 SV *
407 get_print_format (var)
408  struct variable *var
409 CODE:
410  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
411  const struct fmt_spec *fmt = var_get_print_format (var);
412
413  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
414  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
415  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
416
417  RETVAL = newRV ((SV *) fmthash);
418  OUTPUT:
419 RETVAL
420
421
422 void
423 pxs_set_write_format (var, fmt)
424  struct variable *var
425  output_format fmt
426 CODE:
427  var_set_write_format (var, &fmt);
428
429
430 void
431 pxs_set_print_format (var, fmt)
432  struct variable *var
433  output_format fmt
434 CODE:
435  var_set_print_format (var, &fmt);
436
437 void
438 pxs_set_output_format (var, fmt)
439  struct variable *var
440  output_format fmt
441 CODE:
442  var_set_both_formats (var, &fmt);
443
444
445 int
446 add_value_label (var, key, label)
447  struct variable *var
448  SV *key
449  char *label
450 INIT:
451  SV *errstr = get_sv("PSPP::errstr", TRUE);
452  sv_setpv (errstr, "");
453 CODE:
454  union value the_value;
455  int width = var_get_width (var);
456  int ok;
457
458  value_init (&the_value, width);
459  if ( var_is_numeric (var))
460  {
461   if ( ! looks_like_number (key))
462     {
463       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
464       value_destroy (&the_value, width);
465       XSRETURN_IV (0);
466     }
467   the_value.f = SvNV (key);
468  }
469  else
470  {
471   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
472  }
473  ok = var_add_value_label (var, &the_value, label);
474  value_destroy (&the_value, width);
475  if (!ok)
476  {
477    sv_setpv (errstr, "Something went wrong");
478    XSRETURN_IV (0);
479  }
480  XSRETURN_IV (1);
481
482
483 SV *
484 get_attributes (var)
485  struct variable *var
486 CODE:
487  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
488
489  struct attrset *as = var_get_attributes (var);
490
491  if ( as )
492    {
493      struct attrset_iterator iter;
494      struct attribute *attr;
495
496      for (attr = attrset_first (as, &iter);
497           attr;
498           attr = attrset_next (as, &iter))
499        {
500          int i;
501          const char *name = attribute_get_name (attr);
502
503          AV *values = newAV ();
504
505          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
506            {
507              const char *value = attribute_get_value (attr, i);
508              av_push (values, newSVpv (value, 0));
509            }
510
511          hv_store (attrhash, name, strlen (name),
512                    newRV_noinc ((SV*) values), 0);
513        }
514    }
515
516  RETVAL = newRV ((SV *) attrhash);
517  OUTPUT:
518 RETVAL
519
520
521 const char *
522 get_name (var)
523  struct variable * var
524 CODE:
525  RETVAL = var_get_name (var);
526  OUTPUT:
527 RETVAL
528
529
530 const char *
531 get_label (var)
532  struct variable * var
533 CODE:
534  RETVAL = var_get_label (var);
535  OUTPUT:
536 RETVAL
537
538
539 SV *
540 get_value_labels (var)
541  struct variable *var
542 CODE:
543  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
544  const struct val_lab *vl;
545  struct val_labs_iterator *viter = NULL;
546  const struct val_labs *labels = var_get_value_labels (var);
547
548  if ( labels )
549    {
550      for (vl = val_labs_first (labels);
551           vl;
552           vl = val_labs_next (labels, vl))
553        {
554          SV *sv = value_to_scalar (&vl->value, var);
555          STRLEN len;
556          const char *s = SvPV (sv, len);
557          hv_store (labelhash, s, len, newSVpv (val_lab_get_label (vl), 0), 0);
558        }
559    }
560
561  RETVAL = newRV ((SV *) labelhash);
562  OUTPUT:
563 RETVAL
564
565
566
567 MODULE = PSPP           PACKAGE = PSPP::Sysfile
568
569
570 struct sysfile_info *
571 pxs_create_sysfile (name, dict_ref, opts_hr)
572  char *name
573  SV *dict_ref
574  SV *opts_hr
575 INIT:
576  SV *dict_sv = SvRV (dict_ref);
577  struct dictionary *dict = (void *) SvIV (dict_sv);
578  struct sfm_write_options opts;
579  if (!SvROK (opts_hr))
580   {
581     opts = sfm_writer_default_options ();
582   }
583  else
584   {
585     HV *opt_h = (HV *) SvRV (opts_hr);
586     SV** readonly = hv_fetch(opt_h, "readonly", 8, 0);
587     SV** compress = hv_fetch(opt_h, "compress", 8, 0);
588     SV** version = hv_fetch(opt_h, "version", 7, 0);
589
590     opts.create_writeable = readonly ? ! SvIV (*readonly) : true;
591     opts.compress = compress ? SvIV (*compress) : false;
592     opts.version = version ? SvIV (*version) : 3 ;
593   }
594 CODE:
595  struct file_handle *fh =
596   fh_create_file (NULL, name, fh_default_properties () );
597  struct sysfile_info *sfi = xmalloc (sizeof (*sfi));
598  sfi->writer = sfm_open_writer (fh, dict, opts);
599  sfi->dict = dict;
600  sfi->opened = true;
601  sfi->dict_sv = dict_sv;
602  SvREFCNT_inc (sfi->dict_sv);
603  
604  RETVAL = sfi;
605  OUTPUT:
606 RETVAL
607
608 int
609 close (sfi)
610  struct sysfile_info *sfi
611 CODE:
612  RETVAL = sysfile_close (sfi);
613 OUTPUT:
614  RETVAL
615
616 void
617 DESTROY (sfi)
618  struct sysfile_info *sfi
619 CODE:
620  sysfile_close (sfi);
621  SvREFCNT_dec (sfi->dict_sv);
622  free (sfi);
623
624 int
625 append_case (sfi, ccase)
626  struct sysfile_info *sfi
627  SV *ccase
628 INIT:
629  SV *errstr = get_sv("PSPP::errstr", TRUE);
630  sv_setpv (errstr, "");
631  if ( (!SvROK(ccase)))
632   {
633     XSRETURN_UNDEF;
634   }
635 CODE:
636  int i = 0;
637  AV *av_case = (AV*) SvRV (ccase);
638
639  const struct variable **vv;
640  size_t nv;
641  struct ccase *c;
642  SV *sv;
643
644  if ( av_len (av_case) >= dict_get_var_cnt (sfi->dict))
645    XSRETURN_UNDEF;
646
647  c =  case_create (dict_get_proto (sfi->dict));
648
649  dict_get_vars (sfi->dict, &vv, &nv, 1u << DC_ORDINARY | 1u << DC_SYSTEM);
650
651  for (sv = av_shift (av_case); SvOK (sv);  sv = av_shift (av_case))
652  {
653     const struct variable *v = vv[i++];
654     const struct fmt_spec *ifmt = var_get_aux (v);
655
656     /* If an input format has been set, then use it.
657        Otherwise just convert the raw value.
658     */
659     if ( ifmt )
660       {
661         struct substring ss = ss_cstr (SvPV_nolen (sv));
662         char *error;
663         bool ok;
664
665         error = data_in (ss, SvUTF8(sv) ? UTF8: "iso-8859-1", ifmt->type,
666                          case_data_rw (c, v), var_get_width (v),
667                          dict_get_encoding (sfi->dict));
668         ok = error == NULL;
669         free (error);
670
671         if ( !ok )
672           {
673             RETVAL = 0;
674             goto finish;
675           }
676       }
677     else
678       {
679         scalar_to_value (case_data_rw (c, v), sv, v);
680       }
681  }
682
683  /* The remaining variables must be sysmis or blank string */
684  while (i < dict_get_var_cnt (sfi->dict))
685  {
686    const struct variable *v = vv[i++];
687    union value *val = case_data_rw (c, v);
688    value_set_missing (val, var_get_width (v));
689  }
690  casewriter_write (sfi->writer, c);
691  RETVAL = 1;
692  finish:
693  free (vv);
694 OUTPUT:
695  RETVAL
696
697
698 \f
699
700 MODULE = PSPP           PACKAGE = PSPP::Reader
701
702 struct sysreader_info *
703 pxs_open_sysfile (name)
704  char * name
705 CODE:
706  struct casereader *reader;
707  struct sysreader_info *sri = NULL;
708  struct file_handle *fh =
709          fh_create_file (NULL, name, fh_default_properties () );
710
711  sri = xmalloc (sizeof (*sri));
712  sri->reader = sfm_open_reader (fh, NULL, &sri->dict, &sri->opts);
713
714  if ( NULL == sri->reader)
715  {
716    free (sri);
717    sri = NULL;
718  }
719
720  RETVAL = sri;
721  OUTPUT:
722 RETVAL
723
724
725 struct dictionary *
726 pxs_get_dict (reader)
727  struct sysreader_info *reader;
728 CODE:
729  RETVAL = reader->dict;
730  OUTPUT:
731 RETVAL
732
733 SV *
734 get_case_cnt (sfr)
735  struct sysreader_info *sfr;
736 CODE:
737  SV *ret;
738  casenumber n = casereader_get_case_cnt (sfr->reader);
739  if (n == CASENUMBER_MAX)
740   ret = &PL_sv_undef;
741  else 
742   ret = newSViv (n);
743  RETVAL = ret;
744  OUTPUT:
745 RETVAL
746
747
748
749 void
750 get_next_case (sfr)
751  struct sysreader_info *sfr;
752 PPCODE:
753  struct ccase *c;
754
755  if ((c = casereader_read (sfr->reader)) != NULL)
756  {
757   int v;
758
759   EXTEND (SP, dict_get_var_cnt (sfr->dict));
760   for (v = 0; v < dict_get_var_cnt (sfr->dict); ++v )
761     {
762       const struct variable *var = dict_get_var (sfr->dict, v);
763       const union value *val = case_data (c, var);
764
765       PUSHs (sv_2mortal (value_to_scalar (val, var)));
766     }
767
768   case_unref (c);
769  }