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