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