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