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