Remove erroneously commited diagnostic statement
[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 "EXTERN.h"
21 #include "perl.h"
22 #include "XSUB.h"
23
24 #include <config.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  assert (0 == strcmp (ver, bare_version));
168  i18n_init ();
169  msg_init (NULL, message_handler);
170  settings_init (0, 0);
171  fh_init ();
172
173 SV *
174 format_value (val, var)
175  SV *val
176  struct variable *var
177 CODE:
178  SV *ret;
179  const struct fmt_spec *fmt = var_get_print_format (var);
180  const struct dictionary *dict = var_get_vardict (var)->dict;
181  union value uv;
182  char *s;
183  make_value_from_scalar (&uv, val, var);
184  s = data_out (&uv, dict_get_encoding (dict), fmt);
185  value_destroy (&uv, var_get_width (var));
186  ret = newSVpv (s, fmt->w);
187  free (s);
188  RETVAL = ret;
189  OUTPUT:
190 RETVAL
191
192
193 int
194 value_is_missing (val, var)
195  SV *val
196  struct variable *var
197 CODE:
198  union value uv;
199  int ret;
200  make_value_from_scalar (&uv, val, var);
201  ret = var_is_value_missing (var, &uv, MV_ANY);
202  value_destroy (&uv, var_get_width (var));
203  RETVAL = ret;
204  OUTPUT:
205 RETVAL
206
207
208
209 MODULE = PSPP           PACKAGE = PSPP::Dict
210
211 struct dictionary *
212 pxs_dict_new()
213 CODE:
214  RETVAL = dict_create ();
215 OUTPUT:
216  RETVAL
217
218
219 void
220 DESTROY (dict)
221  struct dictionary *dict
222 CODE:
223  dict_destroy (dict);
224
225
226 int
227 get_var_cnt (dict)
228  struct dictionary *dict
229 CODE:
230  RETVAL = dict_get_var_cnt (dict);
231 OUTPUT:
232 RETVAL
233
234 void
235 set_label (dict, label)
236  struct dictionary *dict
237  char *label
238 CODE:
239  dict_set_label (dict, label);
240
241 void
242 set_documents (dict, docs)
243  struct dictionary *dict
244  char *docs
245 CODE:
246  dict_set_documents (dict, docs);
247
248
249 void
250 add_document (dict, doc)
251  struct dictionary *dict
252  char *doc
253 CODE:
254  dict_add_document_line (dict, doc);
255
256
257 void
258 clear_documents (dict)
259  struct dictionary *dict
260 CODE:
261  dict_clear_documents (dict);
262
263
264 void
265 set_weight (dict, var)
266  struct dictionary *dict
267  struct variable *var
268 CODE:
269  dict_set_weight (dict, var);
270
271
272 struct variable *
273 pxs_get_variable (dict, idx)
274  struct dictionary *dict
275  SV *idx
276 INIT:
277  SV *errstr = get_sv("PSPP::errstr", TRUE);
278  sv_setpv (errstr, "");
279  if ( SvIV (idx) >= dict_get_var_cnt (dict))
280   {
281     sv_setpv (errstr, "The dictionary doesn't have that many variables.");
282     XSRETURN_UNDEF;
283   }
284 CODE:
285  RETVAL = dict_get_var (dict, SvIV (idx));
286  OUTPUT:
287 RETVAL
288
289
290 struct variable *
291 pxs_get_var_by_name (dict, name)
292  struct dictionary *dict
293  const char *name
294 INIT:
295  SV *errstr = get_sv("PSPP::errstr", TRUE);
296  sv_setpv (errstr, "");
297 CODE:
298  struct variable *var = dict_lookup_var (dict, name);
299  if ( ! var )
300       sv_setpv (errstr, "No such variable.");
301  RETVAL = var;
302  OUTPUT:
303 RETVAL
304
305
306 MODULE = PSPP           PACKAGE = PSPP::Var
307
308
309 struct variable *
310 pxs_dict_create_var (dict, name, ip_fmt)
311  struct dictionary * dict
312  char *name
313  input_format ip_fmt
314 INIT:
315  SV *errstr = get_sv("PSPP::errstr", TRUE);
316  sv_setpv (errstr, "");
317  if ( ! var_is_plausible_name (name, false))
318   {
319     sv_setpv (errstr, "The variable name is not valid.");
320     XSRETURN_UNDEF;
321   }
322 CODE:
323  struct fmt_spec op_fmt;
324
325  struct variable *v;
326  op_fmt = fmt_for_output_from_input (&ip_fmt);
327  v = dict_create_var (dict, name,
328         fmt_is_string (op_fmt.type) ? op_fmt.w : 0);
329  if ( NULL == v )
330   {
331     sv_setpv (errstr, "The variable could not be created (probably already exists).");
332     XSRETURN_UNDEF;
333   }
334  var_set_both_formats (v, &op_fmt);
335  var_set_input_format (v, ip_fmt);
336  RETVAL = v;
337 OUTPUT:
338  RETVAL
339
340
341 int
342 set_missing_values (var, v1, ...)
343  struct variable *var;
344  SV *v1;
345 INIT:
346  int i;
347  union value val[3];
348
349  if ( items > 4 )
350   croak ("No more than 3 missing values are permitted");
351
352  for (i = 0; i < items - 1; ++i)
353    scalar_to_value (&val[i], ST(i+1), var);
354 CODE:
355  struct missing_values mv;
356  mv_init (&mv, var_get_width (var));
357  for (i = 0 ; i < items - 1; ++i )
358    mv_add_value (&mv, &val[i]);
359  var_set_missing_values (var, &mv);
360
361
362 void
363 set_label (var, label)
364  struct variable *var;
365  char *label
366 CODE:
367   var_set_label (var, label);
368
369
370 void
371 clear_value_labels (var)
372  struct variable *var;
373 CODE:
374  var_clear_value_labels (var);
375
376 void
377 pxs_set_write_format (var, fmt)
378  struct variable *var
379  output_format fmt
380 CODE:
381  var_set_write_format (var, &fmt);
382
383
384 void
385 pxs_set_print_format (var, fmt)
386  struct variable *var
387  output_format fmt
388 CODE:
389  var_set_print_format (var, &fmt);
390
391 void
392 pxs_set_output_format (var, fmt)
393  struct variable *var
394  output_format fmt
395 CODE:
396  var_set_both_formats (var, &fmt);
397
398
399 int
400 add_value_label (var, key, label)
401  struct variable *var
402  SV *key
403  char *label
404 INIT:
405  SV *errstr = get_sv("PSPP::errstr", TRUE);
406  sv_setpv (errstr, "");
407 CODE:
408  union value the_value;
409  int width = var_get_width (var);
410  int ok;
411
412  value_init (&the_value, width);
413  if ( var_is_numeric (var))
414  {
415   if ( ! looks_like_number (key))
416     {
417       sv_setpv (errstr, "Cannot add label with string key to a numeric variable");
418       value_destroy (&the_value, width);
419       XSRETURN_IV (0);
420     }
421   the_value.f = SvNV (key);
422  }
423  else
424  {
425   value_copy_str_rpad (&the_value, width, SvPV_nolen(key), ' ');
426  }
427  ok = var_add_value_label (var, &the_value, label);
428  value_destroy (&the_value, width);
429  if (!ok)
430  {
431    sv_setpv (errstr, "Something went wrong");
432    XSRETURN_IV (0);
433  }
434  XSRETURN_IV (1);
435
436
437 SV *
438 get_attributes (var)
439  struct variable *var
440 CODE:
441  HV *attrhash = (HV *) sv_2mortal ((SV *) newHV());
442
443  struct attrset *as = var_get_attributes (var);
444
445  if ( as )
446    {
447      struct attrset_iterator iter;
448      struct attribute *attr;
449
450      for (attr = attrset_first (as, &iter);
451           attr;
452           attr = attrset_next (as, &iter))
453        {
454          int i;
455          const char *name = attribute_get_name (attr);
456
457          AV *values = newAV ();
458
459          for (i = 0 ; i < attribute_get_n_values (attr); ++i )
460            {
461              const char *value = attribute_get_value (attr, i);
462              av_push (values, newSVpv (value, 0));
463            }
464
465          hv_store (attrhash, name, strlen (name),
466                    newRV_noinc ((SV*) values), 0);
467        }
468    }
469
470  RETVAL = newRV ((SV *) attrhash);
471  OUTPUT:
472 RETVAL
473
474
475 const char *
476 get_name (var)
477  struct variable * var
478 CODE:
479  RETVAL = var_get_name (var);
480  OUTPUT:
481 RETVAL
482
483
484 const char *
485 get_label (var)
486  struct variable * var
487 CODE:
488  RETVAL = var_get_label (var);
489  OUTPUT:
490 RETVAL
491
492
493 SV *
494 get_value_labels (var)
495  struct variable *var
496 CODE:
497  HV *labelhash = (HV *) sv_2mortal ((SV *) newHV());
498  const struct val_lab *vl;
499  struct val_labs_iterator *viter = NULL;
500  const struct val_labs *labels = var_get_value_labels (var);
501
502  if ( labels )
503    {
504      for (vl = val_labs_first (labels);
505           vl;
506           vl = val_labs_next (labels, vl))
507        {
508          SV *sv = value_to_scalar (&vl->value, var);
509          STRLEN len;
510          const char *s = SvPV (sv, len);
511          hv_store (labelhash, s, len, newSVpv (val_lab_get_label (vl), 0), 0);
512        }
513    }
514
515  RETVAL = newRV ((SV *) labelhash);
516  OUTPUT:
517 RETVAL
518
519
520
521 MODULE = PSPP           PACKAGE = PSPP::Sysfile
522
523
524 struct sysfile_info *
525 pxs_create_sysfile (name, dict_ref, opts_hr)
526  char *name
527  SV *dict_ref
528  SV *opts_hr
529 INIT:
530  SV *dict_sv = SvRV (dict_ref);
531  struct dictionary *dict = (void *) SvIV (dict_sv);
532  struct sfm_write_options opts;
533  if (!SvROK (opts_hr))
534   {
535     opts = sfm_writer_default_options ();
536   }
537  else
538   {
539     HV *opt_h = (HV *) SvRV (opts_hr);
540     SV** readonly = hv_fetch(opt_h, "readonly", 8, 0);
541     SV** compress = hv_fetch(opt_h, "compress", 8, 0);
542     SV** version = hv_fetch(opt_h, "version", 7, 0);
543
544     opts.create_writeable = readonly ? ! SvIV (*readonly) : true;
545     opts.compress = compress ? SvIV (*compress) : false;
546     opts.version = version ? SvIV (*version) : 3 ;
547   }
548 CODE:
549  struct file_handle *fh =
550   fh_create_file (NULL, name, fh_default_properties () );
551  struct sysfile_info *sfi = xmalloc (sizeof (*sfi));
552  sfi->writer = sfm_open_writer (fh, dict, opts);
553  sfi->dict = dict;
554  sfi->opened = true;
555  sfi->dict_sv = dict_sv;
556  SvREFCNT_inc (sfi->dict_sv);
557  
558  RETVAL = sfi;
559  OUTPUT:
560 RETVAL
561
562 int
563 close (sfi)
564  struct sysfile_info *sfi
565 CODE:
566  RETVAL = sysfile_close (sfi);
567 OUTPUT:
568  RETVAL
569
570 void
571 DESTROY (sfi)
572  struct sysfile_info *sfi
573 CODE:
574  sysfile_close (sfi);
575  SvREFCNT_dec (sfi->dict_sv);
576  free (sfi);
577
578 int
579 append_case (sfi, ccase)
580  struct sysfile_info *sfi
581  SV *ccase
582 INIT:
583  SV *errstr = get_sv("PSPP::errstr", TRUE);
584  sv_setpv (errstr, "");
585  if ( (!SvROK(ccase)))
586   {
587     XSRETURN_UNDEF;
588   }
589 CODE:
590  int i = 0;
591  AV *av_case = (AV*) SvRV (ccase);
592
593  const struct variable **vv;
594  size_t nv;
595  struct ccase *c;
596  SV *sv;
597
598  if ( av_len (av_case) >= dict_get_var_cnt (sfi->dict))
599    XSRETURN_UNDEF;
600
601  c =  case_create (dict_get_proto (sfi->dict));
602
603  dict_get_vars (sfi->dict, &vv, &nv, 1u << DC_ORDINARY | 1u << DC_SYSTEM);
604
605  for (sv = av_shift (av_case); SvOK (sv);  sv = av_shift (av_case))
606  {
607     const struct variable *v = vv[i++];
608     const struct fmt_spec *ifmt = var_get_aux (v);
609
610     /* If an input format has been set, then use it.
611        Otherwise just convert the raw value.
612     */
613     if ( ifmt )
614       {
615         struct substring ss = ss_cstr (SvPV_nolen (sv));
616         if ( ! data_in (ss, LEGACY_NATIVE, ifmt->type, 0, 0, 0,
617                         case_data_rw (c, v),
618                         var_get_width (v)) )
619           {
620             RETVAL = 0;
621             goto finish;
622           }
623       }
624     else
625       {
626         scalar_to_value (case_data_rw (c, v), sv, v);
627       }
628  }
629
630  /* The remaining variables must be sysmis or blank string */
631  while (i < dict_get_var_cnt (sfi->dict))
632  {
633    const struct variable *v = vv[i++];
634    union value *val = case_data_rw (c, v);
635    value_set_missing (val, var_get_width (v));
636  }
637  RETVAL = casewriter_write (sfi->writer, c);
638  finish:
639  free (vv);
640 OUTPUT:
641  RETVAL
642
643
644 \f
645
646 MODULE = PSPP           PACKAGE = PSPP::Reader
647
648 struct sysreader_info *
649 pxs_open_sysfile (name)
650  char * name
651 CODE:
652  struct casereader *reader;
653  struct sysreader_info *sri = NULL;
654  struct file_handle *fh =
655          fh_create_file (NULL, name, fh_default_properties () );
656
657  sri = xmalloc (sizeof (*sri));
658  sri->reader = sfm_open_reader (fh, &sri->dict, &sri->opts);
659
660  if ( NULL == sri->reader)
661  {
662    free (sri);
663    sri = NULL;
664  }
665
666  RETVAL = sri;
667  OUTPUT:
668 RETVAL
669
670
671 struct dictionary *
672 pxs_get_dict (reader)
673  struct sysreader_info *reader;
674 CODE:
675  RETVAL = reader->dict;
676  OUTPUT:
677 RETVAL
678
679
680 void
681 get_next_case (sfr)
682  struct sysreader_info *sfr;
683 PPCODE:
684  struct ccase *c;
685
686  if (c = casereader_read (sfr->reader))
687  {
688   int v;
689
690   EXTEND (SP, dict_get_var_cnt (sfr->dict));
691   for (v = 0; v < dict_get_var_cnt (sfr->dict); ++v )
692     {
693       const struct variable *var = dict_get_var (sfr->dict, v);
694       const union value *val = case_data (c, var);
695
696       PUSHs (sv_2mortal (value_to_scalar (val, var)));
697     }
698
699   case_unref (c);
700  }