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