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