1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2007, 2009, 2010, 2011, 2012, 2013, 2016 Free Software Foundation, Inc.
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.
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.
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/>. */
19 #include "language/data-io/data-parser.h"
24 #include "data/casereader-provider.h"
25 #include "data/data-in.h"
26 #include "data/dataset.h"
27 #include "data/dictionary.h"
28 #include "data/format.h"
29 #include "data/file-handle-def.h"
30 #include "data/settings.h"
31 #include "language/data-io/data-reader.h"
32 #include "libpspp/intern.h"
33 #include "libpspp/message.h"
34 #include "libpspp/str.h"
35 #include "output/pivot-table.h"
37 #include "gl/xalloc.h"
40 #define N_(msgid) msgid
41 #define _(msgid) gettext (msgid)
43 /* Data parser for textual data like that read by DATA LIST. */
46 struct dictionary *dict; /* Dictionary of destination */
47 enum data_parser_type type; /* Type of data to parse. */
48 int skip_records; /* Records to skip before first real data. */
50 struct field *fields; /* Fields to parse. */
51 size_t n_fields; /* Number of fields. */
52 size_t field_allocated; /* Number of fields spaced allocated for. */
54 /* DP_DELIMITED parsers only. */
55 bool span; /* May cases span multiple records? */
56 bool empty_line_has_field; /* Does an empty line have an (empty) field? */
57 bool warn_missing_fields; /* Should missing fields be considered errors? */
58 struct substring quotes; /* Characters that can quote separators. */
59 bool quote_escape; /* Doubled quote acts as escape? */
60 struct substring soft_seps; /* Two soft separators act like just one. */
61 struct substring hard_seps; /* Two hard separators yield empty fields. */
62 struct string any_sep; /* Concatenation of soft_seps and hard_seps. */
64 /* DP_FIXED parsers only. */
65 int records_per_case; /* Number of records in each case. */
68 /* How to parse one variable. */
71 struct fmt_spec format; /* Input format of this field. */
72 int case_idx; /* First value in case. */
73 char *name; /* Var name for error messages and tables. */
76 int record; /* Record number (1-based). */
77 int first_column; /* First column in record (1-based). */
80 static void set_any_sep (struct data_parser *parser);
82 /* Creates and returns a new data parser. */
84 data_parser_create (struct dictionary *dict)
86 struct data_parser *parser = xmalloc (sizeof *parser);
88 parser->type = DP_FIXED;
89 parser->skip_records = 0;
91 parser->fields = NULL;
93 parser->field_allocated = 0;
94 parser->dict = dict_ref (dict);
97 parser->empty_line_has_field = false;
98 parser->warn_missing_fields = true;
99 ss_alloc_substring (&parser->quotes, ss_cstr ("\"'"));
100 parser->quote_escape = false;
101 ss_alloc_substring (&parser->soft_seps, ss_cstr (CC_SPACES));
102 ss_alloc_substring (&parser->hard_seps, ss_cstr (","));
103 ds_init_empty (&parser->any_sep);
104 set_any_sep (parser);
106 parser->records_per_case = 0;
111 /* Destroys PARSER. */
113 data_parser_destroy (struct data_parser *parser)
119 dict_unref (parser->dict);
120 for (i = 0; i < parser->n_fields; i++)
121 free (parser->fields[i].name);
122 free (parser->fields);
123 ss_dealloc (&parser->quotes);
124 ss_dealloc (&parser->soft_seps);
125 ss_dealloc (&parser->hard_seps);
126 ds_destroy (&parser->any_sep);
131 /* Returns the type of PARSER (either DP_DELIMITED or DP_FIXED). */
132 enum data_parser_type
133 data_parser_get_type (const struct data_parser *parser)
138 /* Sets the type of PARSER to TYPE (either DP_DELIMITED or
141 data_parser_set_type (struct data_parser *parser, enum data_parser_type type)
143 assert (parser->n_fields == 0);
144 assert (type == DP_FIXED || type == DP_DELIMITED);
148 /* Configures PARSER to skip the specified number of
149 INITIAL_RECORDS_TO_SKIP before parsing any data. By default,
150 no records are skipped. */
152 data_parser_set_skip (struct data_parser *parser, int initial_records_to_skip)
154 assert (initial_records_to_skip >= 0);
155 parser->skip_records = initial_records_to_skip;
158 /* Returns true if PARSER is configured to allow cases to span
161 data_parser_get_span (const struct data_parser *parser)
166 /* If MAY_CASES_SPAN_RECORDS is true, configures PARSER to allow
167 a single case to span multiple records and multiple cases to
168 occupy a single record. If MAY_CASES_SPAN_RECORDS is false,
169 configures PARSER to require each record to contain exactly
172 This setting affects parsing of DP_DELIMITED files only. */
174 data_parser_set_span (struct data_parser *parser, bool may_cases_span_records)
176 parser->span = may_cases_span_records;
179 /* If EMPTY_LINE_HAS_FIELD is true, configures PARSER to parse an
180 empty line as an empty field and to treat a hard delimiter
181 followed by end-of-line as an empty field. If
182 EMPTY_LINE_HAS_FIELD is false, PARSER will skip empty lines
183 and hard delimiters at the end of lines without emitting empty
186 This setting affects parsing of DP_DELIMITED files only. */
188 data_parser_set_empty_line_has_field (struct data_parser *parser,
189 bool empty_line_has_field)
191 parser->empty_line_has_field = empty_line_has_field;
195 /* If WARN_MISSING_FIELDS is true, configures PARSER to emit a warning
196 and cause an error condition when a missing field is encountered.
197 If WARN_MISSING_FIELDS is false, PARSER will silently fill such
198 fields with the system missing value.
200 This setting affects parsing of DP_DELIMITED files only. */
202 data_parser_set_warn_missing_fields (struct data_parser *parser,
203 bool warn_missing_fields)
205 parser->warn_missing_fields = warn_missing_fields;
209 /* Sets the characters that may be used for quoting field
210 contents to QUOTES. If QUOTES is empty, quoting will be
213 The caller retains ownership of QUOTES.
215 This setting affects parsing of DP_DELIMITED files only. */
217 data_parser_set_quotes (struct data_parser *parser, struct substring quotes)
219 ss_dealloc (&parser->quotes);
220 ss_alloc_substring (&parser->quotes, quotes);
223 /* If ESCAPE is false (the default setting), a character used for
224 quoting cannot itself be embedded within a quoted field. If
225 ESCAPE is true, then a quote character can be embedded within
226 a quoted field by doubling it.
228 This setting affects parsing of DP_DELIMITED files only, and
229 only when at least one quote character has been set (with
230 data_parser_set_quotes). */
232 data_parser_set_quote_escape (struct data_parser *parser, bool escape)
234 parser->quote_escape = escape;
237 /* Sets PARSER's soft delimiters to DELIMITERS. Soft delimiters
238 separate fields, but consecutive soft delimiters do not yield
239 empty fields. (Ordinarily, only white space characters are
240 appropriate soft delimiters.)
242 The caller retains ownership of DELIMITERS.
244 This setting affects parsing of DP_DELIMITED files only. */
246 data_parser_set_soft_delimiters (struct data_parser *parser,
247 struct substring delimiters)
249 ss_dealloc (&parser->soft_seps);
250 ss_alloc_substring (&parser->soft_seps, delimiters);
251 set_any_sep (parser);
254 /* Sets PARSER's hard delimiters to DELIMITERS. Hard delimiters
255 separate fields. A consecutive pair of hard delimiters yield
258 The caller retains ownership of DELIMITERS.
260 This setting affects parsing of DP_DELIMITED files only. */
262 data_parser_set_hard_delimiters (struct data_parser *parser,
263 struct substring delimiters)
265 ss_dealloc (&parser->hard_seps);
266 ss_alloc_substring (&parser->hard_seps, delimiters);
267 set_any_sep (parser);
270 /* Returns the number of records per case. */
272 data_parser_get_records (const struct data_parser *parser)
274 return parser->records_per_case;
277 /* Sets the number of records per case to RECORDS_PER_CASE.
279 This setting affects parsing of DP_FIXED files only. */
281 data_parser_set_records (struct data_parser *parser, int records_per_case)
283 assert (records_per_case >= 0);
284 assert (records_per_case >= parser->records_per_case);
285 parser->records_per_case = records_per_case;
289 add_field (struct data_parser *p, const struct fmt_spec *format, int case_idx,
290 const char *name, int record, int first_column)
294 if (p->n_fields == p->field_allocated)
295 p->fields = x2nrealloc (p->fields, &p->field_allocated, sizeof *p->fields);
296 field = &p->fields[p->n_fields++];
297 field->format = *format;
298 field->case_idx = case_idx;
299 field->name = xstrdup (name);
300 field->record = record;
301 field->first_column = first_column;
304 /* Adds a delimited field to the field parsed by PARSER, which
305 must be configured as a DP_DELIMITED parser. The field is
306 parsed as input format FORMAT. Its data will be stored into case
307 index CASE_INDEX. Errors in input data will be reported
308 against variable NAME. */
310 data_parser_add_delimited_field (struct data_parser *parser,
311 const struct fmt_spec *format, int case_idx,
314 assert (parser->type == DP_DELIMITED);
315 add_field (parser, format, case_idx, name, 0, 0);
318 /* Adds a fixed field to the field parsed by PARSER, which
319 must be configured as a DP_FIXED parser. The field is
320 parsed as input format FORMAT. Its data will be stored into case
321 index CASE_INDEX. Errors in input data will be reported
322 against variable NAME. The field will be drawn from the
323 FORMAT->w columns in 1-based RECORD starting at 1-based
326 RECORD must be at least as great as that of any field already
327 added; that is, fields must be added in increasing order of
328 record number. If RECORD is greater than the current number
329 of records per case, the number of records per case are
330 increased as needed. */
332 data_parser_add_fixed_field (struct data_parser *parser,
333 const struct fmt_spec *format, int case_idx,
335 int record, int first_column)
337 assert (parser->type == DP_FIXED);
338 assert (parser->n_fields == 0
339 || record >= parser->fields[parser->n_fields - 1].record);
340 if (record > parser->records_per_case)
341 parser->records_per_case = record;
342 add_field (parser, format, case_idx, name, record, first_column);
345 /* Returns true if any fields have been added to PARSER, false
348 data_parser_any_fields (const struct data_parser *parser)
350 return parser->n_fields > 0;
354 set_any_sep (struct data_parser *parser)
356 ds_assign_substring (&parser->any_sep, parser->soft_seps);
357 ds_put_substring (&parser->any_sep, parser->hard_seps);
360 static bool parse_delimited_span (const struct data_parser *,
361 struct dfm_reader *, struct ccase *);
362 static bool parse_delimited_no_span (const struct data_parser *,
363 struct dfm_reader *, struct ccase *);
364 static bool parse_fixed (const struct data_parser *,
365 struct dfm_reader *, struct ccase *);
367 /* Reads a case from DFM into C, parsing it with PARSER. Returns
368 true if successful, false at end of file or on I/O error.
370 Case C must not be shared. */
372 data_parser_parse (struct data_parser *parser, struct dfm_reader *reader,
377 assert (!case_is_shared (c));
378 assert (data_parser_any_fields (parser));
380 /* Skip the requested number of records before reading the
382 for (; parser->skip_records > 0; parser->skip_records--)
384 if (dfm_eof (reader))
386 dfm_forward_record (reader);
390 if (parser->type == DP_DELIMITED)
393 retval = parse_delimited_span (parser, reader, c);
395 retval = parse_delimited_no_span (parser, reader, c);
398 retval = parse_fixed (parser, reader, c);
403 /* Extracts a delimited field from the current position in the
404 current record according to PARSER, reading data from READER.
406 *FIELD is set to the field content. The caller must not or
407 destroy this constant string.
409 Sets *FIRST_COLUMN to the 1-based column number of the start of
410 the extracted field, and *LAST_COLUMN to the end of the extracted
413 Returns true on success, false on failure. */
415 cut_field (const struct data_parser *parser, struct dfm_reader *reader,
416 int *first_column, int *last_column, struct string *tmp,
417 struct substring *field)
419 size_t length_before_separators;
420 struct substring line, p;
423 if (dfm_eof (reader))
425 if (ss_is_empty (parser->hard_seps))
426 dfm_expand_tabs (reader);
427 line = p = dfm_get_record (reader);
429 /* Skip leading soft separators. */
430 ss_ltrim (&p, parser->soft_seps);
432 /* Handle empty or completely consumed lines. */
435 if (!parser->empty_line_has_field || dfm_columns_past_end (reader) > 0)
440 *first_column = dfm_column_start (reader);
441 *last_column = *first_column + 1;
442 dfm_forward_columns (reader, 1);
447 *first_column = dfm_column_start (reader);
448 quoted = ss_find_byte (parser->quotes, ss_first (p)) != SIZE_MAX;
452 int quote = ss_get_byte (&p);
453 if (!ss_get_until (&p, quote, field))
454 msg (DW, _("Quoted string extends beyond end of line."));
455 if (parser->quote_escape && ss_first (p) == quote)
457 ds_assign_substring (tmp, *field);
458 while (ss_match_byte (&p, quote))
461 ds_put_byte (tmp, quote);
462 if (!ss_get_until (&p, quote, &ss))
463 msg (DW, _("Quoted string extends beyond end of line."));
464 ds_put_substring (tmp, ss);
466 *field = ds_ss (tmp);
468 *last_column = *first_column + (ss_length (line) - ss_length (p));
473 ss_get_bytes (&p, ss_cspan (p, ds_ss (&parser->any_sep)), field);
474 *last_column = *first_column + ss_length (*field);
477 /* Skip trailing soft separator and a single hard separator if present. */
478 length_before_separators = ss_length (p);
479 ss_ltrim (&p, parser->soft_seps);
481 && ss_find_byte (parser->hard_seps, ss_first (p)) != SIZE_MAX)
484 ss_ltrim (&p, parser->soft_seps);
487 dfm_forward_columns (reader, 1);
488 else if (quoted && length_before_separators == ss_length (p))
489 msg (DW, _("Missing delimiter following quoted string."));
490 dfm_forward_columns (reader, ss_length (line) - ss_length (p));
496 parse_error (const struct dfm_reader *reader, const struct field *field,
497 int first_column, int last_column, char *error)
499 int line_number = dfm_get_line_number (reader);
500 struct msg_location *location = xmalloc (sizeof *location);
501 *location = (struct msg_location) {
502 .file_name = intern_new (dfm_get_file_name (reader)),
503 .start = { .line = line_number, .column = first_column },
504 .end = { .line = line_number, .column = last_column - 1 },
506 struct msg *m = xmalloc (sizeof *m);
508 .category = MSG_C_DATA,
509 .severity = MSG_S_WARNING,
510 .location = location,
511 .text = xasprintf (_("Data for variable %s is not valid as format %s: %s"),
512 field->name, fmt_name (field->format.type), error),
519 /* Reads a case from READER into C, parsing it according to
520 fixed-format syntax rules in PARSER.
521 Returns true if successful, false at end of file or on I/O error. */
523 parse_fixed (const struct data_parser *parser, struct dfm_reader *reader,
526 const char *input_encoding = dfm_reader_get_encoding (reader);
527 const char *output_encoding = dict_get_encoding (parser->dict);
531 if (dfm_eof (reader))
535 for (row = 1; row <= parser->records_per_case; row++)
537 struct substring line;
539 if (dfm_eof (reader))
541 msg (DW, _("Partial case of %d of %d records discarded."),
542 row - 1, parser->records_per_case);
545 dfm_expand_tabs (reader);
546 line = dfm_get_record (reader);
548 for (; f < &parser->fields[parser->n_fields] && f->record == row; f++)
550 struct substring s = ss_substr (line, f->first_column - 1,
552 union value *value = case_data_rw_idx (c, f->case_idx);
553 char *error = data_in (s, input_encoding, f->format.type,
554 settings_get_fmt_settings (),
555 value, fmt_var_width (&f->format),
559 data_in_imply_decimals (s, input_encoding, f->format.type,
560 f->format.d, settings_get_fmt_settings (),
563 parse_error (reader, f, f->first_column,
564 f->first_column + f->format.w, error);
567 dfm_forward_record (reader);
573 /* Reads a case from READER into C, parsing it according to
574 free-format syntax rules in PARSER.
575 Returns true if successful, false at end of file or on I/O error. */
577 parse_delimited_span (const struct data_parser *parser,
578 struct dfm_reader *reader, struct ccase *c)
580 const char *output_encoding = dict_get_encoding (parser->dict);
581 struct string tmp = DS_EMPTY_INITIALIZER;
584 for (f = parser->fields; f < &parser->fields[parser->n_fields]; f++)
587 int first_column, last_column;
590 /* Cut out a field and read in a new record if necessary. */
591 while (!cut_field (parser, reader,
592 &first_column, &last_column, &tmp, &s))
594 if (!dfm_eof (reader))
595 dfm_forward_record (reader);
596 if (dfm_eof (reader))
598 if (f > parser->fields)
599 msg (DW, _("Partial case discarded. The first variable "
600 "missing was %s."), f->name);
606 const char *input_encoding = dfm_reader_get_encoding (reader);
607 error = data_in (s, input_encoding, f->format.type,
608 settings_get_fmt_settings (),
609 case_data_rw_idx (c, f->case_idx),
610 fmt_var_width (&f->format), output_encoding);
612 parse_error (reader, f, first_column, last_column, error);
618 /* Reads a case from READER into C, parsing it according to
619 delimited syntax rules with one case per record in PARSER.
620 Returns true if successful, false at end of file or on I/O error. */
622 parse_delimited_no_span (const struct data_parser *parser,
623 struct dfm_reader *reader, struct ccase *c)
625 const char *output_encoding = dict_get_encoding (parser->dict);
626 struct string tmp = DS_EMPTY_INITIALIZER;
628 struct field *f, *end;
630 if (dfm_eof (reader))
633 end = &parser->fields[parser->n_fields];
634 for (f = parser->fields; f < end; f++)
636 int first_column, last_column;
639 if (!cut_field (parser, reader, &first_column, &last_column, &tmp, &s))
641 if (f < end - 1 && settings_get_undefined () && parser->warn_missing_fields)
642 msg (DW, _("Missing value(s) for all variables from %s onward. "
643 "These will be filled with the system-missing value "
644 "or blanks, as appropriate."),
647 value_set_missing (case_data_rw_idx (c, f->case_idx),
648 fmt_var_width (&f->format));
652 const char *input_encoding = dfm_reader_get_encoding (reader);
653 error = data_in (s, input_encoding, f->format.type,
654 settings_get_fmt_settings (),
655 case_data_rw_idx (c, f->case_idx),
656 fmt_var_width (&f->format), output_encoding);
658 parse_error (reader, f, first_column, last_column, error);
661 s = dfm_get_record (reader);
662 ss_ltrim (&s, parser->soft_seps);
663 if (!ss_is_empty (s))
664 msg (DW, _("Record ends in data not part of any field."));
667 dfm_forward_record (reader);
672 /* Displays a table giving information on fixed-format variable
673 parsing on DATA LIST. */
675 dump_fixed_table (const struct data_parser *parser,
676 const struct file_handle *fh)
678 /* XXX This should not be preformatted. */
679 char *title = xasprintf (ngettext ("Reading %d record from %s.",
680 "Reading %d records from %s.",
681 parser->records_per_case),
682 parser->records_per_case, fh_get_name (fh));
683 struct pivot_table *table = pivot_table_create__ (
684 pivot_value_new_user_text (title, -1), "Fixed Data Records");
687 pivot_dimension_create (
688 table, PIVOT_AXIS_COLUMN, N_("Attributes"),
689 N_("Record"), N_("Columns"), N_("Format"));
691 struct pivot_dimension *variables = pivot_dimension_create (
692 table, PIVOT_AXIS_ROW, N_("Variable"));
693 variables->root->show_label = true;
694 for (size_t i = 0; i < parser->n_fields; i++)
696 struct field *f = &parser->fields[i];
698 /* XXX It would be better to have the actual variable here. */
699 int variable_idx = pivot_category_create_leaf (
700 variables->root, pivot_value_new_user_text (f->name, -1));
702 pivot_table_put2 (table, 0, variable_idx,
703 pivot_value_new_integer (f->record));
705 int first_column = f->first_column;
706 int last_column = f->first_column + f->format.w - 1;
707 char *columns = xasprintf ("%d-%d", first_column, last_column);
708 pivot_table_put2 (table, 1, variable_idx,
709 pivot_value_new_user_text (columns, -1));
712 char str[FMT_STRING_LEN_MAX + 1];
713 pivot_table_put2 (table, 2, variable_idx,
714 pivot_value_new_user_text (
715 fmt_to_string (&f->format, str), -1));
719 pivot_table_submit (table);
722 /* Displays a table giving information on free-format variable parsing
725 dump_delimited_table (const struct data_parser *parser,
726 const struct file_handle *fh)
728 struct pivot_table *table = pivot_table_create__ (
729 pivot_value_new_text_format (N_("Reading free-form data from %s."),
731 "Free-Form Data Records");
733 pivot_dimension_create (
734 table, PIVOT_AXIS_COLUMN, N_("Attributes"), N_("Format"));
736 struct pivot_dimension *variables = pivot_dimension_create (
737 table, PIVOT_AXIS_ROW, N_("Variable"));
738 variables->root->show_label = true;
739 for (size_t i = 0; i < parser->n_fields; i++)
741 struct field *f = &parser->fields[i];
743 /* XXX It would be better to have the actual variable here. */
744 int variable_idx = pivot_category_create_leaf (
745 variables->root, pivot_value_new_user_text (f->name, -1));
747 char str[FMT_STRING_LEN_MAX + 1];
748 pivot_table_put2 (table, 0, variable_idx,
749 pivot_value_new_user_text (
750 fmt_to_string (&f->format, str), -1));
753 pivot_table_submit (table);
756 /* Displays a table giving information on how PARSER will read
759 data_parser_output_description (struct data_parser *parser,
760 const struct file_handle *fh)
762 if (parser->type == DP_FIXED)
763 dump_fixed_table (parser, fh);
765 dump_delimited_table (parser, fh);
768 /* Data parser input program. */
769 struct data_parser_casereader
771 struct data_parser *parser; /* Parser. */
772 struct dfm_reader *reader; /* Data file reader. */
773 struct caseproto *proto; /* Format of cases. */
776 static const struct casereader_class data_parser_casereader_class;
778 /* Replaces DS's active dataset by an input program that reads data
779 from READER according to the rules in PARSER, using DICT as
780 the underlying dictionary. Ownership of PARSER and READER is
781 transferred to the input program, and ownership of DICT is
782 transferred to the dataset. */
784 data_parser_make_active_file (struct data_parser *parser, struct dataset *ds,
785 struct dfm_reader *reader,
786 struct dictionary *dict,
787 struct casereader* (*func)(struct casereader *,
788 const struct dictionary *,
792 struct data_parser_casereader *r;
793 struct casereader *casereader0;
794 struct casereader *casereader1;
796 r = xmalloc (sizeof *r);
799 r->proto = caseproto_ref (dict_get_proto (dict));
800 casereader0 = casereader_create_sequential (NULL, r->proto,
802 &data_parser_casereader_class, r);
805 casereader1 = func (casereader0, dict, ud);
807 casereader1 = casereader0;
809 dataset_set_dict (ds, dict);
810 dataset_set_source (ds, casereader1);
814 static struct ccase *
815 data_parser_casereader_read (struct casereader *reader UNUSED, void *r_)
817 struct data_parser_casereader *r = r_;
818 struct ccase *c = case_create (r->proto);
819 if (data_parser_parse (r->parser, r->reader, c))
829 data_parser_casereader_destroy (struct casereader *reader, void *r_)
831 struct data_parser_casereader *r = r_;
832 if (dfm_reader_error (r->reader))
833 casereader_force_error (reader);
834 dfm_close_reader (r->reader);
835 caseproto_unref (r->proto);
836 data_parser_destroy (r->parser);
840 static const struct casereader_class data_parser_casereader_class =
842 data_parser_casereader_read,
843 data_parser_casereader_destroy,