Fix compiler warning whilst building perl module
[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
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/hmap.h>
36 #include <libpspp/hash-functions.h>
37 #include <libpspp/message.h>
38 #include <libpspp/version.h>
39 #include <libpspp/i18n.h>
40 #include <gl/xalloc.h>
41 #include <data/dictionary.h>
42 #include <data/case.h>
43 #include <data/casereader.h>
44 #include <data/casewriter.h>
45 #include <data/variable.h>
46 #include <data/attributes.h>
47 #include <data/file-handle-def.h>
48 #include <data/identifier.h>
49 #include <data/settings.h>
50 #include <data/sys-file-writer.h>
51 #include <data/value.h>
52 #include <data/vardict.h>
53 #include <data/value-labels.h>
54 #include <data/format.h>
55 #include <data/data-in.h>
56 #include <data/data-out.h>
57 #include <string.h>
58
59 typedef struct fmt_spec input_format ;
60 typedef struct fmt_spec output_format ;
61
62
63 /*  A thin wrapper around sfm_writer */
64 struct syswriter_info
65 {
66   bool opened;
67
68   /* A pointer to the writer. The writer is owned by the struct */
69   struct casewriter *writer;
70
71   /* A pointer to the dictionary. Owned externally */
72   const struct pspp_dict *dict;
73
74   /* The scalar containing the dictionary */
75   SV *dict_sv;
76 };
77
78
79 /*  A thin wrapper around sfm_reader */
80 struct sysreader_info
81 {
82   struct any_read_info opts;
83
84   /* A pointer to the reader. The reader is owned by the struct */
85   struct casereader *reader;
86
87   /* A pointer to the dictionary. */
88   struct pspp_dict *dict;
89 };
90
91
92 struct input_format {
93   struct hmap_node hmap_node;   /* In struct pspp_dict's input_formats map. */
94   const struct variable *var;
95   struct fmt_spec input_format;
96 };
97
98 /* A thin wrapper around struct dictionary.*/
99 struct pspp_dict {
100   struct dictionary *dict;
101   struct hmap input_formats;    /* Contains struct input_format. */
102 };
103
104
105 /*  A message handler which writes messages to PSPP::errstr */
106 static void
107 message_handler (const struct msg *m, void *aux)
108 {
109  SV *errstr = get_sv("PSPP::errstr", TRUE);
110  sv_setpv (errstr, m->text);
111 }
112
113 static int
114 sysfile_close (struct syswriter_info *swi)
115 {
116   int retval ;
117   if ( ! swi->opened )
118     return 0;
119
120   retval = casewriter_destroy (swi->writer);
121   if (retval > 0 )
122     swi->opened = false;
123
124   return retval;
125 }
126
127 static void
128 scalar_to_value (union value *val, SV *scalar, const struct variable *var)
129 {
130   if ( var_is_numeric (var))
131     {
132         if ( SvNOK (scalar) || SvIOK (scalar) )
133            val->f = SvNV (scalar);
134         else
135            val->f = SYSMIS;
136     }
137   else
138     {
139         STRLEN len;
140         const char *p = SvPV (scalar, len);
141         int width = var_get_width (var);
142         value_set_missing (val, width);
143         memcpy (value_str_rw (val, width), p, len);
144     }
145 }
146
147
148 static SV *
149 value_to_scalar (const union value *val, const struct variable *var)
150 {
151   if ( var_is_numeric (var))
152     {
153       if ( var_is_value_missing (var, val, MV_SYSTEM))
154         return newSVpvn ("", 0);
155
156       return newSVnv (val->f);
157     }
158   else
159     {
160       int width = var_get_width (var);
161       return newSVpvn (value_str (val, width), width);
162     }
163 }
164
165
166 static void
167 make_value_from_scalar (union value *uv, SV *val, const struct variable *var)
168 {
169  value_init (uv, var_get_width (var));
170  scalar_to_value (uv, val, var);
171 }
172
173 static struct pspp_dict *
174 create_pspp_dict (struct dictionary *dict)
175 {
176   struct pspp_dict *pspp_dict = xmalloc (sizeof *pspp_dict);
177   pspp_dict->dict = dict;
178   hmap_init (&pspp_dict->input_formats);
179   return pspp_dict;
180 }
181
182 static const struct fmt_spec *
183 find_input_format (const struct pspp_dict *dict, const struct variable *var)
184 {
185   struct input_format *input_format;
186
187   HMAP_FOR_EACH_IN_BUCKET (input_format, struct input_format, hmap_node,
188                            hash_pointer (var, 0), &dict->input_formats)
189     if (input_format->var == var)
190       return &input_format->input_format;
191
192   return NULL;
193 }
194
195
196 MODULE = PSPP
197
198 MODULE = PSPP           PACKAGE = PSPP
199
200 PROTOTYPES: ENABLE
201
202 void
203 onBoot (ver)
204  const char *ver
205 CODE:
206  /* Check that the version is correct up to the length of 'ver'.
207     This allows PSPP autobuilders to add a "-build#" suffix to the
208     PSPP version without causing failures here. */
209  assert (0 == strncmp (ver, bare_version, strlen (ver)));
210
211  i18n_init ();
212  msg_set_handler (message_handler, NULL);
213  settings_init ();
214  fh_init ();
215
216 SV *
217 format_value (val, var)
218  SV *val
219  struct variable *var
220 CODE:
221  SV *ret;
222  const struct fmt_spec *fmt = var_get_print_format (var);
223  union value uv;
224  char *s;
225  make_value_from_scalar (&uv, val, var);
226  s = data_out (&uv, var_get_encoding (var), fmt);
227  value_destroy (&uv, var_get_width (var));
228  ret = newSVpv (s, fmt->w);
229  free (s);
230  RETVAL = ret;
231  OUTPUT:
232 RETVAL
233
234
235 int
236 value_is_missing (val, var)
237  SV *val
238  struct variable *var
239 CODE:
240  union value uv;
241  int ret;
242  make_value_from_scalar (&uv, val, var);
243  ret = var_is_value_missing (var, &uv, MV_ANY);
244  value_destroy (&uv, var_get_width (var));
245  RETVAL = ret;
246  OUTPUT:
247 RETVAL
248
249
250
251 MODULE = PSPP           PACKAGE = PSPP::Dict
252
253 struct pspp_dict *
254 pxs_dict_new()
255 CODE:
256  RETVAL = create_pspp_dict (dict_create ("UTF-8"));
257 OUTPUT:
258  RETVAL
259
260
261 void
262 DESTROY (dict)
263  struct pspp_dict *dict
264 CODE:
265  if (dict != NULL)
266    {
267      struct input_format *input_format, *next_input_format;
268
269      HMAP_FOR_EACH_SAFE (input_format, next_input_format,
270                          struct input_format, hmap_node, &dict->input_formats)
271        {
272          hmap_delete (&dict->input_formats, &input_format->hmap_node);
273          free (input_format);
274        }
275      hmap_destroy (&dict->input_formats);
276      dict_destroy (dict->dict);
277      free (dict);
278    }
279
280 int
281 get_var_cnt (dict)
282  struct pspp_dict *dict
283 CODE:
284  RETVAL = dict_get_var_cnt (dict->dict);
285 OUTPUT:
286 RETVAL
287
288 void
289 set_label (dict, label)
290  struct pspp_dict *dict
291  char *label
292 CODE:
293  dict_set_label (dict->dict, label);
294
295 void
296 set_documents (dict, docs)
297  struct pspp_dict *dict
298  char *docs
299 CODE:
300  dict_set_documents_string (dict->dict, docs);
301
302
303 void
304 add_document (dict, doc)
305  struct pspp_dict *dict
306  char *doc
307 CODE:
308  dict_add_document_line (dict->dict, doc, false);
309
310
311 void
312 clear_documents (dict)
313  struct pspp_dict *dict
314 CODE:
315  dict_clear_documents (dict->dict);
316
317
318 void
319 set_weight (dict, var)
320  struct pspp_dict *dict
321  struct variable *var
322 CODE:
323  dict_set_weight (dict->dict, var);
324
325
326 struct variable *
327 pxs_get_variable (dict, idx)
328  struct pspp_dict *dict
329  SV *idx
330 INIT:
331  SV *errstr = get_sv("PSPP::errstr", TRUE);
332  sv_setpv (errstr, "");
333  if ( SvIV (idx) >= dict_get_var_cnt (dict->dict))
334   {
335     sv_setpv (errstr, "The dictionary doesn't have that many variables.");
336     XSRETURN_UNDEF;
337   }
338 CODE:
339  RETVAL = dict_get_var (dict->dict, SvIV (idx));
340  OUTPUT:
341 RETVAL
342
343
344 struct variable *
345 pxs_get_var_by_name (dict, name)
346  struct pspp_dict *dict
347  const char *name
348 INIT:
349  SV *errstr = get_sv("PSPP::errstr", TRUE);
350  sv_setpv (errstr, "");
351 CODE:
352  struct variable *var = dict_lookup_var (dict->dict, name);
353  if ( ! var )
354       sv_setpv (errstr, "No such variable.");
355  RETVAL = var;
356  OUTPUT:
357 RETVAL
358
359
360 MODULE = PSPP           PACKAGE = PSPP::Var
361
362
363 struct variable *
364 pxs_dict_create_var (dict, name, ip_fmt)
365  struct pspp_dict * dict
366  char *name
367  input_format ip_fmt
368 INIT:
369  SV *errstr = get_sv("PSPP::errstr", TRUE);
370  sv_setpv (errstr, "");
371  if ( ! id_is_plausible (name, false))
372   {
373     sv_setpv (errstr, "The variable name is not valid.");
374     XSRETURN_UNDEF;
375   }
376 CODE:
377  struct fmt_spec op_fmt;
378  struct input_format *input_format;
379
380  struct variable *v;
381  op_fmt = fmt_for_output_from_input (&ip_fmt);
382  v = dict_create_var (dict->dict, name,
383         fmt_is_string (op_fmt.type) ? op_fmt.w : 0);
384  if ( NULL == v )
385   {
386     sv_setpv (errstr, "The variable could not be created (probably already exists).");
387     XSRETURN_UNDEF;
388   }
389  var_set_both_formats (v, &op_fmt);
390
391  input_format = xmalloc (sizeof *input_format);
392  input_format->var = v;
393  input_format->input_format = ip_fmt;
394  hmap_insert (&dict->input_formats, &input_format->hmap_node,
395               hash_pointer (v, 0));
396
397  RETVAL = v;
398 OUTPUT:
399  RETVAL
400
401
402 int
403 set_missing_values (var, v1, ...)
404  struct variable *var;
405  SV *v1;
406 INIT:
407  int i;
408  union value val[3];
409
410  if ( items > 4 )
411   croak ("No more than 3 missing values are permitted");
412
413  for (i = 0; i < items - 1; ++i)
414    scalar_to_value (&val[i], ST(i+1), var);
415 CODE:
416  struct missing_values mv;
417  mv_init (&mv, var_get_width (var));
418  for (i = 0 ; i < items - 1; ++i )
419    mv_add_value (&mv, &val[i]);
420  var_set_missing_values (var, &mv);
421
422
423 void
424 set_label (var, label)
425  struct variable *var;
426  char *label
427 CODE:
428   var_set_label (var, label);
429
430
431 void
432 clear_value_labels (var)
433  struct variable *var;
434 CODE:
435  var_clear_value_labels (var);
436
437 SV *
438 get_write_format (var)
439  struct variable *var
440 CODE:
441  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
442  const struct fmt_spec *fmt = var_get_write_format (var);
443
444  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
445  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
446  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
447
448  RETVAL = newRV ((SV *) fmthash);
449  OUTPUT:
450 RETVAL
451
452 SV *
453 get_print_format (var)
454  struct variable *var
455 CODE:
456  HV *fmthash = (HV *) sv_2mortal ((SV *) newHV());
457  const struct fmt_spec *fmt = var_get_print_format (var);
458
459  hv_store (fmthash, "fmt", 3, newSVnv (fmt->type), 0);
460  hv_store (fmthash, "decimals", 8, newSVnv (fmt->d), 0);
461  hv_store (fmthash, "width", 5, newSVnv (fmt->w), 0);
462
463  RETVAL = newRV ((SV *) fmthash);
464  OUTPUT:
465 RETVAL
466
467
468 void
469 pxs_set_write_format (var, fmt)
470  struct variable *var
471  output_format fmt
472 CODE:
473  var_set_write_format (var, &fmt);
474
475
476 void
477 pxs_set_print_format (var, fmt)
478  struct variable *var
479  output_format fmt
480 CODE:
481  var_set_print_format (var, &fmt);
482
483 void
484 pxs_set_output_format (var, fmt)
485  struct variable *var
486  output_format fmt
487 CODE:
488  var_set_both_formats (var, &fmt);
489
490
491 int
492 add_value_label (var, key, label)
493  struct variable *var
494  SV *key
495  char *label
496 INIT:
497  SV *errstr = get_sv("PSPP::errstr", TRUE);
498  sv_setpv (errstr, "");
499 CODE:
500  union value the_value;
501  int width = var_get_width (var);
502  int ok;
503
504  value_init (&the_value, width);
505  if ( var_is_numeric (var))
506  {
507   if ( ! looks_like_number (key))
508     {
509       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
510       value_destroy (&the_value, width);
511       XSRETURN_IV (0);
512     }
513   the_value.f = SvNV (key);
514  }
515  else
516  {
517   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
518  }
519  ok = var_add_value_label (var, &the_value, label);
520  value_destroy (&the_value, width);
521  if (!ok)
522  {
523    sv_setpv (errstr, "Something went wrong");
524    XSRETURN_IV (0);
525  }
526  XSRETURN_IV (1);
527
528
529 SV *
530 get_attributes (var)
531  struct variable *var
532 CODE:
533  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
534
535  struct attrset *as = var_get_attributes (var);
536
537  if ( as )
538    {
539      struct attrset_iterator iter;
540      struct attribute *attr;
541
542      for (attr = attrset_first (as, &iter);
543           attr;
544           attr = attrset_next (as, &iter))
545        {
546          int i;
547          const char *name = attribute_get_name (attr);
548
549          AV *values = newAV ();
550
551          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
552            {
553              const char *value = attribute_get_value (attr, i);
554              av_push (values, newSVpv (value, 0));
555            }
556
557          hv_store (attrhash, name, strlen (name),
558                    newRV_noinc ((SV*) values), 0);
559        }
560    }
561
562  RETVAL = newRV ((SV *) attrhash);
563  OUTPUT:
564 RETVAL
565
566
567 const char *
568 get_name (var)
569  struct variable * var
570 CODE:
571  RETVAL = var_get_name (var);
572  OUTPUT:
573 RETVAL
574
575
576 const char *
577 get_label (var)
578  struct variable * var
579 CODE:
580  RETVAL = var_get_label (var);
581  OUTPUT:
582 RETVAL
583
584
585 SV *
586 get_value_labels (var)
587  struct variable *var
588 CODE:
589  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
590  const struct val_lab *vl;
591  struct val_labs_iterator *viter = NULL;
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 casereader *reader;
755  struct sysreader_info *sri = NULL;
756  struct file_handle *fh =
757    fh_create_file (NULL, name, "UTF-8", fh_default_properties () );
758  struct dictionary *dict;
759
760  sri = xmalloc (sizeof (*sri));
761  sri->reader = any_reader_open_and_decode (fh, NULL, &dict, &sri->opts);
762  if (sri->reader)
763    sri->dict = create_pspp_dict (dict);
764  else
765    {
766      free (sri);
767      sri = NULL;
768    }
769
770  RETVAL = sri;
771  OUTPUT:
772 RETVAL
773
774
775 struct pspp_dict *
776 pxs_get_dict (reader)
777  struct sysreader_info *reader;
778 CODE:
779  RETVAL = reader->dict;
780  OUTPUT:
781 RETVAL
782
783 SV *
784 get_case_cnt (sfr)
785  struct sysreader_info *sfr;
786 CODE:
787  SV *ret;
788  casenumber n = casereader_get_case_cnt (sfr->reader);
789  if (n == CASENUMBER_MAX)
790   ret = &PL_sv_undef;
791  else 
792   ret = newSViv (n);
793  RETVAL = ret;
794  OUTPUT:
795 RETVAL
796
797
798
799 void
800 get_next_case (sfr)
801  struct sysreader_info *sfr;
802 PPCODE:
803  struct ccase *c;
804
805  if ((c = casereader_read (sfr->reader)) != NULL)
806  {
807   int v;
808
809   EXTEND (SP, dict_get_var_cnt (sfr->dict->dict));
810   for (v = 0; v < dict_get_var_cnt (sfr->dict->dict); ++v )
811     {
812       const struct variable *var = dict_get_var (sfr->dict->dict, v);
813       const union value *val = case_data (c, var);
814
815       PUSHs (sv_2mortal (value_to_scalar (val, var)));
816     }
817
818   case_unref (c);
819  }