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