treewide: Replace <name>_cnt by n_<name>s and <name>_cap by allocated_<name>.
[pspp] / src / language / data-io / data-list.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2007, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU 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, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <ctype.h>
20 #include <float.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "data/case.h"
26 #include "data/casereader.h"
27 #include "data/data-in.h"
28 #include "data/dataset.h"
29 #include "data/dictionary.h"
30 #include "data/format.h"
31 #include "data/settings.h"
32 #include "data/transformations.h"
33 #include "data/variable.h"
34 #include "language/command.h"
35 #include "language/data-io/data-parser.h"
36 #include "language/data-io/data-reader.h"
37 #include "language/data-io/file-handle.h"
38 #include "language/data-io/inpt-pgm.h"
39 #include "language/data-io/placement-parser.h"
40 #include "language/lexer/format-parser.h"
41 #include "language/lexer/lexer.h"
42 #include "language/lexer/variable-parser.h"
43 #include "libpspp/assertion.h"
44 #include "libpspp/compiler.h"
45 #include "libpspp/i18n.h"
46 #include "libpspp/message.h"
47 #include "libpspp/misc.h"
48 #include "libpspp/pool.h"
49 #include "libpspp/str.h"
50
51 #include "gl/xsize.h"
52 #include "gl/xalloc.h"
53
54 #include "gettext.h"
55 #define _(msgid) gettext (msgid)
56 \f
57 /* DATA LIST transformation data. */
58 struct data_list_trns
59   {
60     struct data_parser *parser; /* Parser. */
61     struct dfm_reader *reader;  /* Data file reader. */
62     struct variable *end;       /* Variable specified on END subcommand. */
63   };
64
65 static bool parse_fixed (struct lexer *, struct dictionary *,
66                          struct pool *, struct data_parser *);
67 static bool parse_free (struct lexer *, struct dictionary *,
68                         struct pool *, struct data_parser *);
69
70 static trns_free_func data_list_trns_free;
71 static trns_proc_func data_list_trns_proc;
72
73 int
74 cmd_data_list (struct lexer *lexer, struct dataset *ds)
75 {
76   struct dictionary *dict;
77   struct data_parser *parser;
78   struct dfm_reader *reader;
79   struct variable *end = NULL;
80   struct file_handle *fh = NULL;
81   char *encoding = NULL;
82
83   int table;
84   enum data_parser_type type;
85   bool has_type;
86   struct pool *tmp_pool;
87   bool ok;
88
89   dict = (in_input_program ()
90           ? dataset_dict (ds)
91           : dict_create (get_default_encoding ()));
92   parser = data_parser_create (dict);
93   reader = NULL;
94
95   table = -1;                /* Print table if nonzero, -1=undecided. */
96   has_type = false;
97
98   while (lex_token (lexer) != T_SLASH)
99     {
100       if (lex_match_id (lexer, "FILE"))
101         {
102           lex_match (lexer, T_EQUALS);
103           fh_unref (fh);
104           fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
105           if (fh == NULL)
106             goto error;
107         }
108       else if (lex_match_id (lexer, "ENCODING"))
109         {
110           lex_match (lexer, T_EQUALS);
111           if (!lex_force_string (lexer))
112             goto error;
113
114           free (encoding);
115           encoding = ss_xstrdup (lex_tokss (lexer));
116
117           lex_get (lexer);
118         }
119       else if (lex_match_id (lexer, "RECORDS"))
120         {
121           if (data_parser_get_records (parser) > 0)
122             {
123               lex_sbc_only_once ("RECORDS");
124               goto error;
125             }
126           lex_match (lexer, T_EQUALS);
127           lex_match (lexer, T_LPAREN);
128           if (!lex_force_int_range (lexer, "RECORDS", 0, INT_MAX))
129             goto error;
130           data_parser_set_records (parser, lex_integer (lexer));
131           lex_get (lexer);
132           lex_match (lexer, T_RPAREN);
133         }
134       else if (lex_match_id (lexer, "SKIP"))
135         {
136           lex_match (lexer, T_EQUALS);
137           if (!lex_force_int_range (lexer, "SKIP", 0, INT_MAX))
138             goto error;
139           data_parser_set_skip (parser, lex_integer (lexer));
140           lex_get (lexer);
141         }
142       else if (lex_match_id (lexer, "END"))
143         {
144           if (!in_input_program ())
145             {
146               msg (SE, _("The %s subcommand may only be used within %s."), "END", "INPUT PROGRAM");
147               goto error;
148             }
149           if (end)
150             {
151               lex_sbc_only_once ("END");
152               goto error;
153             }
154
155           lex_match (lexer, T_EQUALS);
156           if (!lex_force_id (lexer))
157             goto error;
158           end = dict_lookup_var (dict, lex_tokcstr (lexer));
159           if (!end)
160             end = dict_create_var_assert (dict, lex_tokcstr (lexer), 0);
161           lex_get (lexer);
162         }
163       else if (lex_match_id (lexer, "NOTABLE"))
164         table = 0;
165       else if (lex_match_id (lexer, "TABLE"))
166         table = 1;
167       else if (lex_token (lexer) == T_ID)
168         {
169           if (lex_match_id (lexer, "FIXED"))
170             data_parser_set_type (parser, DP_FIXED);
171           else if (lex_match_id (lexer, "FREE"))
172             {
173               data_parser_set_type (parser, DP_DELIMITED);
174               data_parser_set_span (parser, true);
175             }
176           else if (lex_match_id (lexer, "LIST"))
177             {
178               data_parser_set_type (parser, DP_DELIMITED);
179               data_parser_set_span (parser, false);
180             }
181           else
182             {
183               lex_error (lexer, NULL);
184               goto error;
185             }
186
187           if (has_type)
188             {
189               msg (SE, _("Only one of FIXED, FREE, or LIST may "
190                          "be specified."));
191               goto error;
192             }
193           has_type = true;
194
195           if (data_parser_get_type (parser) == DP_DELIMITED)
196             {
197               if (lex_match (lexer, T_LPAREN))
198                 {
199                   struct string delims = DS_EMPTY_INITIALIZER;
200
201                   while (!lex_match (lexer, T_RPAREN))
202                     {
203                       int delim;
204
205                       if (lex_match_id (lexer, "TAB"))
206                         delim = '\t';
207                       else if (lex_is_string (lexer)
208                                && ss_length (lex_tokss (lexer)) == 1)
209                         {
210                           delim = ss_first (lex_tokss (lexer));
211                           lex_get (lexer);
212                         }
213                       else
214                         {
215                           /* XXX should support multibyte UTF-8 characters */
216                           lex_error (lexer, NULL);
217                           ds_destroy (&delims);
218                           goto error;
219                         }
220                       ds_put_byte (&delims, delim);
221
222                       lex_match (lexer, T_COMMA);
223                     }
224
225                   data_parser_set_empty_line_has_field (parser, true);
226                   data_parser_set_quotes (parser, ss_empty ());
227                   data_parser_set_soft_delimiters (parser, ss_empty ());
228                   data_parser_set_hard_delimiters (parser, ds_ss (&delims));
229                   ds_destroy (&delims);
230                 }
231               else
232                 {
233                   data_parser_set_empty_line_has_field (parser, false);
234                   data_parser_set_quotes (parser, ss_cstr ("'\""));
235                   data_parser_set_soft_delimiters (parser,
236                                                    ss_cstr (CC_SPACES));
237                   const char decimal = settings_get_fmt_settings ()->decimal;
238                   data_parser_set_hard_delimiters (parser,
239                                                    ss_buffer (",", (decimal == '.') ? 1 : 0));
240                 }
241             }
242         }
243       else
244         {
245           lex_error (lexer, NULL);
246           goto error;
247         }
248     }
249   type = data_parser_get_type (parser);
250
251   if (encoding && NULL == fh)
252     msg (MW, _("Encoding should not be specified for inline data. It will be "
253                "ignored."));
254
255   if (fh == NULL)
256     fh = fh_inline_file ();
257   fh_set_default_handle (fh);
258
259   if (type != DP_FIXED && end != NULL)
260     {
261       msg (SE, _("The %s subcommand may be used only with %s."), "END", "DATA LIST FIXED");
262       goto error;
263     }
264
265   tmp_pool = pool_create ();
266   if (type == DP_FIXED)
267     ok = parse_fixed (lexer, dict, tmp_pool, parser);
268   else
269     ok = parse_free (lexer, dict, tmp_pool, parser);
270   pool_destroy (tmp_pool);
271   if (!ok)
272     goto error;
273
274   if (!data_parser_any_fields (parser))
275     {
276       msg (SE, _("At least one variable must be specified."));
277       goto error;
278     }
279
280   if (lex_end_of_command (lexer) != CMD_SUCCESS)
281     goto error;
282
283   if (table == -1)
284     table = type == DP_FIXED || !data_parser_get_span (parser);
285   if (table)
286     data_parser_output_description (parser, fh);
287
288   reader = dfm_open_reader (fh, lexer, encoding);
289   if (reader == NULL)
290     goto error;
291
292   if (in_input_program ())
293     {
294       struct data_list_trns *trns = xmalloc (sizeof *trns);
295       trns->parser = parser;
296       trns->reader = reader;
297       trns->end = end;
298       add_transformation (ds, data_list_trns_proc, data_list_trns_free, trns);
299     }
300   else
301     data_parser_make_active_file (parser, ds, reader, dict, NULL, NULL);
302
303   fh_unref (fh);
304   free (encoding);
305
306   return CMD_DATA_LIST;
307
308  error:
309   data_parser_destroy (parser);
310   if (!in_input_program ())
311     dict_unref (dict);
312   fh_unref (fh);
313   free (encoding);
314   return CMD_CASCADING_FAILURE;
315 }
316 \f
317 /* Fixed-format parsing. */
318
319 /* Parses all the variable specifications for DATA LIST FIXED,
320    storing them into DLS.  Uses TMP_POOL for temporary storage;
321    the caller may destroy it.  Returns true only if
322    successful. */
323 static bool
324 parse_fixed (struct lexer *lexer, struct dictionary *dict,
325              struct pool *tmp_pool, struct data_parser *parser)
326 {
327   int max_records = data_parser_get_records (parser);
328   int record = 0;
329   int column = 1;
330
331   while (lex_token (lexer) != T_ENDCMD)
332     {
333       char **names;
334       size_t n_names, name_idx;
335       struct fmt_spec *formats, *f;
336       size_t n_formats;
337
338       /* Parse everything. */
339       if (!parse_record_placement (lexer, &record, &column)
340           || !parse_DATA_LIST_vars_pool (lexer, dict, tmp_pool,
341                                          &names, &n_names, PV_NONE)
342           || !parse_var_placements (lexer, tmp_pool, n_names, FMT_FOR_INPUT,
343                                     &formats, &n_formats))
344         return false;
345
346       /* Create variables and var specs. */
347       name_idx = 0;
348       for (f = formats; f < &formats[n_formats]; f++)
349         if (!execute_placement_format (f, &record, &column))
350           {
351             char *name;
352             int width;
353             struct variable *v;
354
355             name = names[name_idx++];
356
357             /* Create variable. */
358             width = fmt_var_width (f);
359             v = dict_create_var (dict, name, width);
360             if (v != NULL)
361               {
362                 /* Success. */
363                 struct fmt_spec output = fmt_for_output_from_input (
364                   f, settings_get_fmt_settings ());
365                 var_set_both_formats (v, &output);
366               }
367             else
368               {
369                 /* Failure.
370                    This can be acceptable if we're in INPUT
371                    PROGRAM, but only if the existing variable has
372                    the same width as the one we would have
373                    created. */
374                 if (!in_input_program ())
375                   {
376                     msg (SE, _("%s is a duplicate variable name."), name);
377                     return false;
378                   }
379
380                 v = dict_lookup_var_assert (dict, name);
381                 if ((width != 0) != (var_get_width (v) != 0))
382                   {
383                     msg (SE, _("There is already a variable %s of a "
384                                "different type."),
385                          name);
386                     return false;
387                   }
388                 if (width != 0 && width != var_get_width (v))
389                   {
390                     msg (SE, _("There is already a string variable %s of a "
391                                "different width."), name);
392                     return false;
393                   }
394               }
395
396             if (max_records && record > max_records)
397               {
398                 msg (SE, _("Cannot place variable %s on record %d when "
399                            "RECORDS=%d is specified."),
400                      var_get_name (v), record,
401                      data_parser_get_records (parser));
402               }
403
404             data_parser_add_fixed_field (parser, f,
405                                          var_get_case_index (v),
406                                          var_get_name (v), record, column);
407
408             column += f->w;
409           }
410       assert (name_idx == n_names);
411     }
412
413   return true;
414 }
415 \f
416 /* Free-format parsing. */
417
418 /* Parses variable specifications for DATA LIST FREE and adds
419    them to DLS.  Uses TMP_POOL for temporary storage; the caller
420    may destroy it.  Returns true only if successful. */
421 static bool
422 parse_free (struct lexer *lexer, struct dictionary *dict,
423             struct pool *tmp_pool, struct data_parser *parser)
424 {
425   lex_get (lexer);
426   while (lex_token (lexer) != T_ENDCMD)
427     {
428       struct fmt_spec input, output;
429       char **name;
430       size_t n_names;
431       size_t i;
432
433       if (!parse_DATA_LIST_vars_pool (lexer, dict, tmp_pool,
434                                       &name, &n_names, PV_NONE))
435         return false;
436
437       if (lex_match (lexer, T_LPAREN))
438         {
439           char type[FMT_TYPE_LEN_MAX + 1];
440
441           if (!parse_abstract_format_specifier (lexer, type, &input.w,
442                                                 &input.d))
443             return NULL;
444           if (!fmt_from_name (type, &input.type))
445             {
446               msg (SE, _("Unknown format type `%s'."), type);
447               return NULL;
448             }
449
450           /* If no width was included, use the minimum width for the type.
451              This isn't quite right, because DATETIME by itself seems to become
452              DATETIME20 (see bug #30690), whereas this will become
453              DATETIME17.  The correct behavior is not documented. */
454           if (input.w == 0)
455             {
456               input.w = fmt_min_input_width (input.type);
457               input.d = 0;
458             }
459
460           if (!fmt_check_input (&input) || !lex_force_match (lexer, T_RPAREN))
461             return NULL;
462
463           /* As a special case, N format is treated as F format
464              for free-field input. */
465           if (input.type == FMT_N)
466             input.type = FMT_F;
467
468           output = fmt_for_output_from_input (&input,
469                                               settings_get_fmt_settings ());
470         }
471       else
472         {
473           lex_match (lexer, T_ASTERISK);
474           input = fmt_for_input (FMT_F, 8, 0);
475           output = *settings_get_format ();
476         }
477
478       for (i = 0; i < n_names; i++)
479         {
480           struct variable *v;
481
482           v = dict_create_var (dict, name[i], fmt_var_width (&input));
483           if (v == NULL)
484             {
485               msg (SE, _("%s is a duplicate variable name."), name[i]);
486               return false;
487             }
488           var_set_both_formats (v, &output);
489
490           data_parser_add_delimited_field (parser,
491                                            &input, var_get_case_index (v),
492                                            var_get_name (v));
493         }
494     }
495
496   return true;
497 }
498 \f
499 /* Input procedure. */
500
501 /* Destroys DATA LIST transformation TRNS.
502    Returns true if successful, false if an I/O error occurred. */
503 static bool
504 data_list_trns_free (void *trns_)
505 {
506   struct data_list_trns *trns = trns_;
507   data_parser_destroy (trns->parser);
508   dfm_close_reader (trns->reader);
509   free (trns);
510   return true;
511 }
512
513 /* Handle DATA LIST transformation TRNS, parsing data into *C. */
514 static int
515 data_list_trns_proc (void *trns_, struct ccase **c, casenumber case_num UNUSED)
516 {
517   struct data_list_trns *trns = trns_;
518   int retval;
519
520   *c = case_unshare (*c);
521   if (data_parser_parse (trns->parser, trns->reader, *c))
522     retval = TRNS_CONTINUE;
523   else if (dfm_reader_error (trns->reader) || dfm_eof (trns->reader) > 1)
524     {
525       /* An I/O error, or encountering end of file for a second
526          time, should be escalated into a more serious error. */
527       retval = TRNS_ERROR;
528     }
529   else
530     retval = TRNS_END_FILE;
531
532   /* If there was an END subcommand handle it. */
533   if (trns->end != NULL)
534     {
535       double *end = case_num_rw (*c, trns->end);
536       if (retval == TRNS_END_FILE)
537         {
538           *end = 1.0;
539           retval = TRNS_CONTINUE;
540         }
541       else
542         *end = 0.0;
543     }
544
545   return retval;
546 }
547 \f