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