1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2007, 2009, 2010 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/dictionary.h>
27 #include <data/format.h>
28 #include <data/file-handle-def.h>
29 #include <data/procedure.h>
30 #include <data/settings.h>
31 #include <language/data-io/data-reader.h>
32 #include <libpspp/message.h>
33 #include <libpspp/str.h>
34 #include <output/tab.h>
39 #define _(msgid) gettext (msgid)
41 /* Data parser for textual data like that read by DATA LIST. */
44 const struct dictionary *dict; /*Dictionary of destination */
45 enum data_parser_type type; /* Type of data to parse. */
46 int skip_records; /* Records to skip before first real data. */
47 casenumber max_cases; /* Max number of cases to read. */
48 int percent_cases; /* Approximate percent of cases to read. */
50 struct field *fields; /* Fields to parse. */
51 size_t field_cnt; /* 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 struct substring quotes; /* Characters that can quote separators. */
58 bool quote_escape; /* Doubled quote acts as escape? */
59 struct substring soft_seps; /* Two soft separators act like just one. */
60 struct substring hard_seps; /* Two hard separators yield empty fields. */
61 struct string any_sep; /* Concatenation of soft_seps and hard_seps. */
63 /* DP_FIXED parsers only. */
64 int records_per_case; /* Number of records in each case. */
67 /* How to parse one variable. */
70 struct fmt_spec format; /* Input format of this field. */
71 int case_idx; /* First value in case. */
72 char *name; /* Var name for error messages and tables. */
75 int record; /* Record number (1-based). */
76 int first_column; /* First column in record (1-based). */
79 static void set_any_sep (struct data_parser *parser);
81 /* Creates and returns a new data parser. */
83 data_parser_create (const struct dictionary *dict)
85 struct data_parser *parser = xmalloc (sizeof *parser);
87 parser->type = DP_FIXED;
88 parser->skip_records = 0;
89 parser->max_cases = -1;
90 parser->percent_cases = 100;
92 parser->fields = NULL;
93 parser->field_cnt = 0;
94 parser->field_allocated = 0;
98 parser->empty_line_has_field = false;
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 for (i = 0; i < parser->field_cnt; i++)
120 free (parser->fields[i].name);
121 free (parser->fields);
122 ss_dealloc (&parser->quotes);
123 ss_dealloc (&parser->soft_seps);
124 ss_dealloc (&parser->hard_seps);
125 ds_destroy (&parser->any_sep);
130 /* Returns the type of PARSER (either DP_DELIMITED or DP_FIXED). */
131 enum data_parser_type
132 data_parser_get_type (const struct data_parser *parser)
137 /* Sets the type of PARSER to TYPE (either DP_DELIMITED or
140 data_parser_set_type (struct data_parser *parser, enum data_parser_type type)
142 assert (parser->field_cnt == 0);
143 assert (type == DP_FIXED || type == DP_DELIMITED);
147 /* Configures PARSER to skip the specified number of
148 INITIAL_RECORDS_TO_SKIP before parsing any data. By default,
149 no records are skipped. */
151 data_parser_set_skip (struct data_parser *parser, int initial_records_to_skip)
153 assert (initial_records_to_skip >= 0);
154 parser->skip_records = initial_records_to_skip;
157 /* Sets the maximum number of cases parsed by PARSER to
158 MAX_CASES. The default is -1, meaning no limit. */
160 data_parser_set_case_limit (struct data_parser *parser, casenumber max_cases)
162 parser->max_cases = max_cases;
165 /* Sets the percentage of cases that PARSER should read from the
166 input file to PERCENT_CASES. By default, all cases are
169 data_parser_set_case_percent (struct data_parser *parser, int percent_cases)
171 assert (percent_cases >= 0 && percent_cases <= 100);
172 parser->percent_cases = percent_cases;
175 /* Returns true if PARSER is configured to allow cases to span
178 data_parser_get_span (const struct data_parser *parser)
183 /* If MAY_CASES_SPAN_RECORDS is true, configures PARSER to allow
184 a single case to span multiple records and multiple cases to
185 occupy a single record. If MAY_CASES_SPAN_RECORDS is false,
186 configures PARSER to require each record to contain exactly
189 This setting affects parsing of DP_DELIMITED files only. */
191 data_parser_set_span (struct data_parser *parser, bool may_cases_span_records)
193 parser->span = may_cases_span_records;
196 /* If EMPTY_LINE_HAS_FIELD is true, configures PARSER to parse an
197 empty line as an empty field and to treat a hard delimiter
198 followed by end-of-line as an empty field. If
199 EMPTY_LINE_HAS_FIELD is false, PARSER will skip empty lines
200 and hard delimiters at the end of lines without emitting empty
203 This setting affects parsing of DP_DELIMITED files only. */
205 data_parser_set_empty_line_has_field (struct data_parser *parser,
206 bool empty_line_has_field)
208 parser->empty_line_has_field = empty_line_has_field;
211 /* Sets the characters that may be used for quoting field
212 contents to QUOTES. If QUOTES is empty, quoting will be
215 The caller retains ownership of QUOTES.
217 This setting affects parsing of DP_DELIMITED files only. */
219 data_parser_set_quotes (struct data_parser *parser, struct substring quotes)
221 ss_dealloc (&parser->quotes);
222 ss_alloc_substring (&parser->quotes, quotes);
225 /* If ESCAPE is false (the default setting), a character used for
226 quoting cannot itself be embedded within a quoted field. If
227 ESCAPE is true, then a quote character can be embedded within
228 a quoted field by doubling it.
230 This setting affects parsing of DP_DELIMITED files only, and
231 only when at least one quote character has been set (with
232 data_parser_set_quotes). */
234 data_parser_set_quote_escape (struct data_parser *parser, bool escape)
236 parser->quote_escape = escape;
239 /* Sets PARSER's soft delimiters to DELIMITERS. Soft delimiters
240 separate fields, but consecutive soft delimiters do not yield
241 empty fields. (Ordinarily, only white space characters are
242 appropriate soft delimiters.)
244 The caller retains ownership of DELIMITERS.
246 This setting affects parsing of DP_DELIMITED files only. */
248 data_parser_set_soft_delimiters (struct data_parser *parser,
249 struct substring delimiters)
251 ss_dealloc (&parser->soft_seps);
252 ss_alloc_substring (&parser->soft_seps, delimiters);
253 set_any_sep (parser);
256 /* Sets PARSER's hard delimiters to DELIMITERS. Hard delimiters
257 separate fields. A consecutive pair of hard delimiters yield
260 The caller retains ownership of DELIMITERS.
262 This setting affects parsing of DP_DELIMITED files only. */
264 data_parser_set_hard_delimiters (struct data_parser *parser,
265 struct substring delimiters)
267 ss_dealloc (&parser->hard_seps);
268 ss_alloc_substring (&parser->hard_seps, delimiters);
269 set_any_sep (parser);
272 /* Returns the number of records per case. */
274 data_parser_get_records (const struct data_parser *parser)
276 return parser->records_per_case;
279 /* Sets the number of records per case to RECORDS_PER_CASE.
281 This setting affects parsing of DP_FIXED files only. */
283 data_parser_set_records (struct data_parser *parser, int records_per_case)
285 assert (records_per_case >= 0);
286 assert (records_per_case >= parser->records_per_case);
287 parser->records_per_case = records_per_case;
291 add_field (struct data_parser *p, const struct fmt_spec *format, int case_idx,
292 const char *name, int record, int first_column)
296 if (p->field_cnt == p->field_allocated)
297 p->fields = x2nrealloc (p->fields, &p->field_allocated, sizeof *p->fields);
298 field = &p->fields[p->field_cnt++];
299 field->format = *format;
300 field->case_idx = case_idx;
301 field->name = xstrdup (name);
302 field->record = record;
303 field->first_column = first_column;
306 /* Adds a delimited field to the field parsed by PARSER, which
307 must be configured as a DP_DELIMITED parser. The field is
308 parsed as input format FORMAT. Its data will be stored into case
309 index CASE_INDEX. Errors in input data will be reported
310 against variable NAME. */
312 data_parser_add_delimited_field (struct data_parser *parser,
313 const struct fmt_spec *format, int case_idx,
316 assert (parser->type == DP_DELIMITED);
317 add_field (parser, format, case_idx, name, 0, 0);
320 /* Adds a fixed field to the field parsed by PARSER, which
321 must be configured as a DP_FIXED parser. The field is
322 parsed as input format FORMAT. Its data will be stored into case
323 index CASE_INDEX. Errors in input data will be reported
324 against variable NAME. The field will be drawn from the
325 FORMAT->w columns in 1-based RECORD starting at 1-based
328 RECORD must be at least as great as that of any field already
329 added; that is, fields must be added in increasing order of
330 record number. If RECORD is greater than the current number
331 of records per case, the number of records per case are
332 increased as needed. */
334 data_parser_add_fixed_field (struct data_parser *parser,
335 const struct fmt_spec *format, int case_idx,
337 int record, int first_column)
339 assert (parser->type == DP_FIXED);
340 assert (parser->field_cnt == 0
341 || record >= parser->fields[parser->field_cnt - 1].record);
342 if (record > parser->records_per_case)
343 parser->records_per_case = record;
344 add_field (parser, format, case_idx, name, record, first_column);
347 /* Returns true if any fields have been added to PARSER, false
350 data_parser_any_fields (const struct data_parser *parser)
352 return parser->field_cnt > 0;
356 set_any_sep (struct data_parser *parser)
358 ds_assign_substring (&parser->any_sep, parser->soft_seps);
359 ds_put_substring (&parser->any_sep, parser->hard_seps);
362 static bool parse_delimited_span (const struct data_parser *,
363 struct dfm_reader *, struct ccase *);
364 static bool parse_delimited_no_span (const struct data_parser *,
365 struct dfm_reader *, struct ccase *);
366 static bool parse_fixed (const struct data_parser *,
367 struct dfm_reader *, struct ccase *);
369 /* Reads a case from DFM into C, parsing it with PARSER. Returns
370 true if successful, false at end of file or on I/O error.
372 Case C must not be shared. */
374 data_parser_parse (struct data_parser *parser, struct dfm_reader *reader,
379 assert (!case_is_shared (c));
380 assert (data_parser_any_fields (parser));
382 /* Skip the requested number of records before reading the
384 for (; parser->skip_records > 0; parser->skip_records--)
386 if (dfm_eof (reader))
388 dfm_forward_record (reader);
392 if (parser->max_cases != -1 && parser->max_cases-- == 0)
394 if (parser->percent_cases < 100
395 && dfm_get_percent_read (reader) >= parser->percent_cases)
399 if (parser->type == DP_DELIMITED)
402 retval = parse_delimited_span (parser, reader, c);
404 retval = parse_delimited_no_span (parser, reader, c);
407 retval = parse_fixed (parser, reader, c);
413 /* Extracts a delimited field from the current position in the
414 current record according to PARSER, reading data from READER.
416 *FIELD is set to the field content. The caller must not or
417 destroy this constant string.
419 After parsing the field, sets the current position in the
420 record to just past the field and any trailing delimiter.
421 Returns 0 on failure or a 1-based column number indicating the
422 beginning of the field on success. */
424 cut_field (const struct data_parser *parser, struct dfm_reader *reader,
425 int *first_column, int *last_column, struct string *tmp,
426 struct substring *field)
428 struct substring line, p;
430 if (dfm_eof (reader))
432 if (ss_is_empty (parser->hard_seps))
433 dfm_expand_tabs (reader);
434 line = p = dfm_get_record (reader);
436 /* Skip leading soft separators. */
437 ss_ltrim (&p, parser->soft_seps);
439 /* Handle empty or completely consumed lines. */
442 if (!parser->empty_line_has_field || dfm_columns_past_end (reader) > 0)
447 *first_column = dfm_column_start (reader);
448 *last_column = *first_column + 1;
449 dfm_forward_columns (reader, 1);
454 *first_column = dfm_column_start (reader);
455 if (ss_find_char (parser->quotes, ss_first (p)) != SIZE_MAX)
458 int quote = ss_get_char (&p);
459 if (!ss_get_until (&p, quote, field))
460 msg (SW, _("Quoted string extends beyond end of line."));
461 if (parser->quote_escape && ss_first (p) == quote)
463 ds_assign_substring (tmp, *field);
464 while (ss_match_char (&p, quote))
467 ds_put_char (tmp, quote);
468 if (!ss_get_until (&p, quote, &ss))
469 msg (SW, _("Quoted string extends beyond end of line."));
470 ds_put_substring (tmp, ss);
472 *field = ds_ss (tmp);
474 *last_column = *first_column + (ss_length (line) - ss_length (p));
476 /* Skip trailing soft separator and a single hard separator
478 ss_ltrim (&p, parser->soft_seps);
480 && ss_find_char (parser->hard_seps, ss_first (p)) != SIZE_MAX)
486 ss_get_chars (&p, ss_cspan (p, ds_ss (&parser->any_sep)), field);
487 *last_column = *first_column + ss_length (*field);
489 if (!ss_ltrim (&p, parser->soft_seps) || ss_is_empty (p)
490 || ss_find_char (parser->hard_seps, p.string[0]) != SIZE_MAX)
492 /* Advance past a trailing hard separator,
493 regardless of whether one actually existed. If
494 we "skip" a delimiter that was not actually
495 there, then we will return end-of-line on our
496 next call, which is what we want. */
497 dfm_forward_columns (reader, 1);
500 dfm_forward_columns (reader, ss_length (line) - ss_length (p));
505 /* Reads a case from READER into C, parsing it according to
506 fixed-format syntax rules in PARSER.
507 Returns true if successful, false at end of file or on I/O error. */
509 parse_fixed (const struct data_parser *parser, struct dfm_reader *reader,
512 const char *input_encoding = dfm_reader_get_legacy_encoding (reader);
513 const char *output_encoding = dict_get_encoding (parser->dict);
517 if (dfm_eof (reader))
521 for (row = 1; row <= parser->records_per_case; row++)
523 struct substring line;
525 if (dfm_eof (reader))
527 msg (SW, _("Partial case of %d of %d records discarded."),
528 row - 1, parser->records_per_case);
531 dfm_expand_tabs (reader);
532 line = dfm_get_record (reader);
534 for (; f < &parser->fields[parser->field_cnt] && f->record == row; f++)
536 struct substring s = ss_substr (line, f->first_column - 1,
538 union value *value = case_data_rw_idx (c, f->case_idx);
540 data_in (s, input_encoding, f->format.type,
541 f->first_column, f->first_column + f->format.w,
542 value, fmt_var_width (&f->format), output_encoding);
544 data_in_imply_decimals (s, input_encoding, f->format.type,
548 dfm_forward_record (reader);
554 /* Reads a case from READER into C, parsing it according to
555 free-format syntax rules in PARSER.
556 Returns true if successful, false at end of file or on I/O error. */
558 parse_delimited_span (const struct data_parser *parser,
559 struct dfm_reader *reader, struct ccase *c)
561 const char *input_encoding = dfm_reader_get_legacy_encoding (reader);
562 const char *output_encoding = dict_get_encoding (parser->dict);
563 struct string tmp = DS_EMPTY_INITIALIZER;
566 for (f = parser->fields; f < &parser->fields[parser->field_cnt]; f++)
569 int first_column, last_column;
571 /* Cut out a field and read in a new record if necessary. */
572 while (!cut_field (parser, reader,
573 &first_column, &last_column, &tmp, &s))
575 if (!dfm_eof (reader))
576 dfm_forward_record (reader);
577 if (dfm_eof (reader))
579 if (f > parser->fields)
580 msg (SW, _("Partial case discarded. The first variable "
581 "missing was %s."), f->name);
587 data_in (s, input_encoding, f->format.type, first_column, last_column,
588 case_data_rw_idx (c, f->case_idx),
589 fmt_var_width (&f->format), output_encoding);
595 /* Reads a case from READER into C, parsing it according to
596 delimited syntax rules with one case per record in PARSER.
597 Returns true if successful, false at end of file or on I/O error. */
599 parse_delimited_no_span (const struct data_parser *parser,
600 struct dfm_reader *reader, struct ccase *c)
602 const char *input_encoding = dfm_reader_get_legacy_encoding (reader);
603 const char *output_encoding = dict_get_encoding (parser->dict);
604 struct string tmp = DS_EMPTY_INITIALIZER;
606 struct field *f, *end;
608 if (dfm_eof (reader))
611 end = &parser->fields[parser->field_cnt];
612 for (f = parser->fields; f < end; f++)
614 int first_column, last_column;
615 if (!cut_field (parser, reader, &first_column, &last_column, &tmp, &s))
617 if (f < end - 1 && settings_get_undefined ())
618 msg (SW, _("Missing value(s) for all variables from %s onward. "
619 "These will be filled with the system-missing value "
620 "or blanks, as appropriate."),
623 value_set_missing (case_data_rw_idx (c, f->case_idx),
624 fmt_var_width (&f->format));
628 data_in (s, input_encoding, f->format.type, first_column, last_column,
629 case_data_rw_idx (c, f->case_idx),
630 fmt_var_width (&f->format), output_encoding);
633 s = dfm_get_record (reader);
634 ss_ltrim (&s, parser->soft_seps);
635 if (!ss_is_empty (s))
636 msg (SW, _("Record ends in data not part of any field."));
639 dfm_forward_record (reader);
644 /* Displays a table giving information on fixed-format variable
645 parsing on DATA LIST. */
647 dump_fixed_table (const struct data_parser *parser,
648 const struct file_handle *fh)
653 t = tab_create (4, parser->field_cnt + 1);
654 tab_headers (t, 0, 0, 1, 0);
655 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
656 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
657 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
658 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
659 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, parser->field_cnt);
660 tab_hline (t, TAL_2, 0, 3, 1);
662 for (i = 0; i < parser->field_cnt; i++)
664 struct field *f = &parser->fields[i];
665 char fmt_string[FMT_STRING_LEN_MAX + 1];
668 tab_text (t, 0, row, TAB_LEFT, f->name);
669 tab_text_format (t, 1, row, 0, "%d", f->record);
670 tab_text_format (t, 2, row, 0, "%3d-%3d",
671 f->first_column, f->first_column + f->format.w - 1);
672 tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
673 fmt_to_string (&f->format, fmt_string));
676 tab_title (t, ngettext ("Reading %d record from %s.",
677 "Reading %d records from %s.",
678 parser->records_per_case),
679 parser->records_per_case, fh_get_name (fh));
683 /* Displays a table giving information on free-format variable parsing
686 dump_delimited_table (const struct data_parser *parser,
687 const struct file_handle *fh)
692 t = tab_create (2, parser->field_cnt + 1);
693 tab_headers (t, 0, 0, 1, 0);
694 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
695 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Format"));
696 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 1, parser->field_cnt);
697 tab_hline (t, TAL_2, 0, 1, 1);
699 for (i = 0; i < parser->field_cnt; i++)
701 struct field *f = &parser->fields[i];
702 char str[FMT_STRING_LEN_MAX + 1];
705 tab_text (t, 0, row, TAB_LEFT, f->name);
706 tab_text (t, 1, row, TAB_LEFT | TAB_FIX,
707 fmt_to_string (&f->format, str));
710 tab_title (t, _("Reading free-form data from %s."), fh_get_name (fh));
715 /* Displays a table giving information on how PARSER will read
718 data_parser_output_description (struct data_parser *parser,
719 const struct file_handle *fh)
721 if (parser->type == DP_FIXED)
722 dump_fixed_table (parser, fh);
724 dump_delimited_table (parser, fh);
727 /* Data parser input program. */
728 struct data_parser_casereader
730 struct data_parser *parser; /* Parser. */
731 struct dfm_reader *reader; /* Data file reader. */
732 struct caseproto *proto; /* Format of cases. */
735 static const struct casereader_class data_parser_casereader_class;
737 /* Replaces DS's active file by an input program that reads data
738 from READER according to the rules in PARSER, using DICT as
739 the underlying dictionary. Ownership of PARSER and READER is
740 transferred to the input program, and ownership of DICT is
741 transferred to the dataset. */
743 data_parser_make_active_file (struct data_parser *parser, struct dataset *ds,
744 struct dfm_reader *reader,
745 struct dictionary *dict)
747 struct data_parser_casereader *r;
748 struct casereader *casereader;
750 r = xmalloc (sizeof *r);
753 r->proto = caseproto_ref (dict_get_proto (dict));
754 casereader = casereader_create_sequential (NULL, r->proto,
756 &data_parser_casereader_class, r);
757 proc_set_active_file (ds, casereader, dict);
760 static struct ccase *
761 data_parser_casereader_read (struct casereader *reader UNUSED, void *r_)
763 struct data_parser_casereader *r = r_;
764 struct ccase *c = case_create (r->proto);
765 if (data_parser_parse (r->parser, r->reader, c))
775 data_parser_casereader_destroy (struct casereader *reader UNUSED, void *r_)
777 struct data_parser_casereader *r = r_;
778 if (dfm_reader_error (r->reader))
779 casereader_force_error (reader);
780 data_parser_destroy (r->parser);
781 dfm_close_reader (r->reader);
782 caseproto_unref (r->proto);
786 static const struct casereader_class data_parser_casereader_class =
788 data_parser_casereader_read,
789 data_parser_casereader_destroy,