1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2007 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/table.h>
39 #define _(msgid) gettext (msgid)
41 /* Data parser for textual data like that read by DATA LIST. */
44 enum data_parser_type type; /* Type of data to parse. */
45 int skip_records; /* Records to skip before first real data. */
46 casenumber max_cases; /* Max number of cases to read. */
47 int percent_cases; /* Approximate percent of cases to read. */
49 struct field *fields; /* Fields to parse. */
50 size_t field_cnt; /* Number of fields. */
51 size_t field_allocated; /* Number of fields spaced allocated for. */
53 /* DP_DELIMITED parsers only. */
54 bool span; /* May cases span multiple records? */
55 bool empty_line_has_field; /* Does an empty line have an (empty) field? */
56 struct substring quotes; /* Characters that can quote separators. */
57 bool quote_escape; /* Doubled quote acts as escape? */
58 struct substring soft_seps; /* Two soft separators act like just one. */
59 struct substring hard_seps; /* Two hard separators yield empty fields. */
60 struct string any_sep; /* Concatenation of soft_seps and hard_seps. */
62 /* DP_FIXED parsers only. */
63 int records_per_case; /* Number of records in each case. */
66 /* How to parse one variable. */
69 struct fmt_spec format; /* Input format of this field. */
70 int case_idx; /* First value in case. */
71 char *name; /* Var name for error messages and tables. */
74 int record; /* Record number (1-based). */
75 int first_column; /* First column in record (1-based). */
78 static void set_any_sep (struct data_parser *parser);
80 /* Creates and returns a new data parser. */
82 data_parser_create (void)
84 struct data_parser *parser = xmalloc (sizeof *parser);
86 parser->type = DP_FIXED;
87 parser->skip_records = 0;
88 parser->max_cases = -1;
89 parser->percent_cases = 100;
91 parser->fields = NULL;
92 parser->field_cnt = 0;
93 parser->field_allocated = 0;
96 parser->empty_line_has_field = false;
97 ss_alloc_substring (&parser->quotes, ss_cstr ("\"'"));
98 parser->quote_escape = false;
99 ss_alloc_substring (&parser->soft_seps, ss_cstr (CC_SPACES));
100 ss_alloc_substring (&parser->hard_seps, ss_cstr (","));
101 ds_init_empty (&parser->any_sep);
102 set_any_sep (parser);
104 parser->records_per_case = 0;
109 /* Destroys PARSER. */
111 data_parser_destroy (struct data_parser *parser)
117 for (i = 0; i < parser->field_cnt; i++)
118 free (parser->fields[i].name);
119 free (parser->fields);
120 ss_dealloc (&parser->quotes);
121 ss_dealloc (&parser->soft_seps);
122 ss_dealloc (&parser->hard_seps);
123 ds_destroy (&parser->any_sep);
128 /* Returns the type of PARSER (either DP_DELIMITED or DP_FIXED). */
129 enum data_parser_type
130 data_parser_get_type (const struct data_parser *parser)
135 /* Sets the type of PARSER to TYPE (either DP_DELIMITED or
138 data_parser_set_type (struct data_parser *parser, enum data_parser_type type)
140 assert (parser->field_cnt == 0);
141 assert (type == DP_FIXED || type == DP_DELIMITED);
145 /* Configures PARSER to skip the specified number of
146 INITIAL_RECORDS_TO_SKIP before parsing any data. By default,
147 no records are skipped. */
149 data_parser_set_skip (struct data_parser *parser, int initial_records_to_skip)
151 assert (initial_records_to_skip >= 0);
152 parser->skip_records = initial_records_to_skip;
155 /* Sets the maximum number of cases parsed by PARSER to
156 MAX_CASES. The default is -1, meaning no limit. */
158 data_parser_set_case_limit (struct data_parser *parser, casenumber max_cases)
160 parser->max_cases = max_cases;
163 /* Sets the percentage of cases that PARSER should read from the
164 input file to PERCENT_CASES. By default, all cases are
167 data_parser_set_case_percent (struct data_parser *parser, int percent_cases)
169 assert (percent_cases >= 0 && percent_cases <= 100);
170 parser->percent_cases = percent_cases;
173 /* Returns true if PARSER is configured to allow cases to span
176 data_parser_get_span (const struct data_parser *parser)
181 /* If MAY_CASES_SPAN_RECORDS is true, configures PARSER to allow
182 a single case to span multiple records and multiple cases to
183 occupy a single record. If MAY_CASES_SPAN_RECORDS is false,
184 configures PARSER to require each record to contain exactly
187 This setting affects parsing of DP_DELIMITED files only. */
189 data_parser_set_span (struct data_parser *parser, bool may_cases_span_records)
191 parser->span = may_cases_span_records;
194 /* If EMPTY_LINE_HAS_FIELD is true, configures PARSER to parse an
195 empty line as an empty field and to treat a hard delimiter
196 followed by end-of-line as an empty field. If
197 EMPTY_LINE_HAS_FIELD is false, PARSER will skip empty lines
198 and hard delimiters at the end of lines without emitting empty
201 This setting affects parsing of DP_DELIMITED files only. */
203 data_parser_set_empty_line_has_field (struct data_parser *parser,
204 bool empty_line_has_field)
206 parser->empty_line_has_field = empty_line_has_field;
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->field_cnt == p->field_allocated)
295 p->fields = x2nrealloc (p->fields, &p->field_allocated, sizeof *p->fields);
296 field = &p->fields[p->field_cnt++];
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->field_cnt == 0
339 || record >= parser->fields[parser->field_cnt - 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->field_cnt > 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.
368 Returns true if successful, false at end of file or on I/O error. */
370 data_parser_parse (struct data_parser *parser, struct dfm_reader *reader,
375 assert (data_parser_any_fields (parser));
377 /* Skip the requested number of records before reading the
379 for (; parser->skip_records > 0; parser->skip_records--)
381 if (dfm_eof (reader))
383 dfm_forward_record (reader);
387 if (parser->max_cases != -1 && parser->max_cases-- == 0)
389 if (parser->percent_cases < 100
390 && dfm_get_percent_read (reader) >= parser->percent_cases)
394 if (parser->type == DP_DELIMITED)
397 retval = parse_delimited_span (parser, reader, c);
399 retval = parse_delimited_no_span (parser, reader, c);
402 retval = parse_fixed (parser, reader, c);
408 /* Extracts a delimited field from the current position in the
409 current record according to PARSER, reading data from READER.
411 *FIELD is set to the field content. The caller must not or
412 destroy this constant string.
414 After parsing the field, sets the current position in the
415 record to just past the field and any trailing delimiter.
416 Returns 0 on failure or a 1-based column number indicating the
417 beginning of the field on success. */
419 cut_field (const struct data_parser *parser, struct dfm_reader *reader,
420 int *first_column, int *last_column, struct string *tmp,
421 struct substring *field)
423 struct substring line, p;
425 if (dfm_eof (reader))
427 if (ss_is_empty (parser->hard_seps))
428 dfm_expand_tabs (reader);
429 line = p = dfm_get_record (reader);
431 /* Skip leading soft separators. */
432 ss_ltrim (&p, parser->soft_seps);
434 /* Handle empty or completely consumed lines. */
437 if (!parser->empty_line_has_field || dfm_columns_past_end (reader) > 0)
442 *first_column = dfm_column_start (reader);
443 *last_column = *first_column + 1;
444 dfm_forward_columns (reader, 1);
449 *first_column = dfm_column_start (reader);
450 if (ss_find_char (parser->quotes, ss_first (p)) != SIZE_MAX)
453 int quote = ss_get_char (&p);
454 if (!ss_get_until (&p, quote, field))
455 msg (SW, _("Quoted string extends beyond end of line."));
456 if (parser->quote_escape && ss_first (p) == quote)
458 ds_assign_substring (tmp, *field);
459 while (ss_match_char (&p, quote))
462 ds_put_char (tmp, quote);
463 if (!ss_get_until (&p, quote, &ss))
464 msg (SW, _("Quoted string extends beyond end of line."));
465 ds_put_substring (tmp, ss);
467 *field = ds_ss (tmp);
469 *last_column = dfm_column_start (reader);
471 /* Skip trailing soft separator and a single hard separator
473 ss_ltrim (&p, parser->soft_seps);
475 && ss_find_char (parser->hard_seps, ss_first (p)) != SIZE_MAX)
481 ss_get_chars (&p, ss_cspan (p, ds_ss (&parser->any_sep)), field);
482 *last_column = dfm_column_start (reader);
483 if (!ss_ltrim (&p, parser->soft_seps) || ss_is_empty (p)
484 || ss_find_char (parser->hard_seps, p.string[0]) != SIZE_MAX)
486 /* Advance past a trailing hard separator,
487 regardless of whether one actually existed. If
488 we "skip" a delimiter that was not actually
489 there, then we will return end-of-line on our
490 next call, which is what we want. */
491 dfm_forward_columns (reader, 1);
494 dfm_forward_columns (reader, ss_length (line) - ss_length (p));
499 /* Reads a case from READER into C, parsing it according to
500 fixed-format syntax rules in PARSER.
501 Returns true if successful, false at end of file or on I/O error. */
503 parse_fixed (const struct data_parser *parser, struct dfm_reader *reader,
506 enum legacy_encoding encoding = dfm_reader_get_legacy_encoding (reader);
510 if (dfm_eof (reader))
514 for (row = 1; row <= parser->records_per_case; row++)
516 struct substring line;
518 if (dfm_eof (reader))
520 msg (SW, _("Partial case of %d of %d records discarded."),
521 row - 1, parser->records_per_case);
524 dfm_expand_tabs (reader);
525 line = dfm_get_record (reader);
527 for (; f < &parser->fields[parser->field_cnt] && f->record == row; f++)
528 data_in (ss_substr (line, f->first_column - 1,
530 encoding, f->format.type, f->format.d,
531 f->first_column, f->first_column + f->format.w,
532 case_data_rw_idx (c, f->case_idx),
533 fmt_var_width (&f->format));
535 dfm_forward_record (reader);
541 /* Reads a case from READER into C, parsing it according to
542 free-format syntax rules in PARSER.
543 Returns true if successful, false at end of file or on I/O error. */
545 parse_delimited_span (const struct data_parser *parser,
546 struct dfm_reader *reader, struct ccase *c)
548 enum legacy_encoding encoding = dfm_reader_get_legacy_encoding (reader);
549 struct string tmp = DS_EMPTY_INITIALIZER;
552 for (f = parser->fields; f < &parser->fields[parser->field_cnt]; f++)
555 int first_column, last_column;
557 /* Cut out a field and read in a new record if necessary. */
558 while (!cut_field (parser, reader,
559 &first_column, &last_column, &tmp, &s))
561 if (!dfm_eof (reader))
562 dfm_forward_record (reader);
563 if (dfm_eof (reader))
565 if (f > parser->fields)
566 msg (SW, _("Partial case discarded. The first variable "
567 "missing was %s."), f->name);
573 data_in (s, encoding, f->format.type, 0,
574 first_column, last_column,
575 case_data_rw_idx (c, f->case_idx),
576 fmt_var_width (&f->format));
582 /* Reads a case from READER into C, parsing it according to
583 delimited syntax rules with one case per record in PARSER.
584 Returns true if successful, false at end of file or on I/O error. */
586 parse_delimited_no_span (const struct data_parser *parser,
587 struct dfm_reader *reader, struct ccase *c)
589 enum legacy_encoding encoding = dfm_reader_get_legacy_encoding (reader);
590 struct string tmp = DS_EMPTY_INITIALIZER;
594 if (dfm_eof (reader))
597 for (f = parser->fields; f < &parser->fields[parser->field_cnt]; f++)
599 int first_column, last_column;
600 if (!cut_field (parser, reader, &first_column, &last_column, &tmp, &s))
602 if (settings_get_undefined ())
603 msg (SW, _("Missing value(s) for all variables from %s onward. "
604 "These will be filled with the system-missing value "
605 "or blanks, as appropriate."),
607 for (; f < &parser->fields[parser->field_cnt]; f++)
608 value_set_missing (case_data_rw_idx (c, f->case_idx),
609 fmt_var_width (&f->format));
613 data_in (s, encoding, f->format.type, 0,
614 first_column, last_column,
615 case_data_rw_idx (c, f->case_idx),
616 fmt_var_width (&f->format));
619 s = dfm_get_record (reader);
620 ss_ltrim (&s, parser->soft_seps);
621 if (!ss_is_empty (s))
622 msg (SW, _("Record ends in data not part of any field."));
625 dfm_forward_record (reader);
630 /* Displays a table giving information on fixed-format variable
631 parsing on DATA LIST. */
633 dump_fixed_table (const struct data_parser *parser,
634 const struct file_handle *fh)
639 t = tab_create (4, parser->field_cnt + 1, 0);
640 tab_columns (t, TAB_COL_DOWN, 1);
641 tab_headers (t, 0, 0, 1, 0);
642 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
643 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
644 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
645 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
646 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, parser->field_cnt);
647 tab_hline (t, TAL_2, 0, 3, 1);
648 tab_dim (t, tab_natural_dimensions);
650 for (i = 0; i < parser->field_cnt; i++)
652 struct field *f = &parser->fields[i];
653 char fmt_string[FMT_STRING_LEN_MAX + 1];
656 tab_text (t, 0, row, TAB_LEFT, f->name);
657 tab_text (t, 1, row, TAT_PRINTF, "%d", f->record);
658 tab_text (t, 2, row, TAT_PRINTF, "%3d-%3d",
659 f->first_column, f->first_column + f->format.w - 1);
660 tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
661 fmt_to_string (&f->format, fmt_string));
664 tab_title (t, ngettext ("Reading %d record from %s.",
665 "Reading %d records from %s.",
666 parser->records_per_case),
667 parser->records_per_case, fh_get_name (fh));
671 /* Displays a table giving information on free-format variable parsing
674 dump_delimited_table (const struct data_parser *parser,
675 const struct file_handle *fh)
680 t = tab_create (2, parser->field_cnt + 1, 0);
681 tab_columns (t, TAB_COL_DOWN, 1);
682 tab_headers (t, 0, 0, 1, 0);
683 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
684 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Format"));
685 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 1, parser->field_cnt);
686 tab_hline (t, TAL_2, 0, 1, 1);
687 tab_dim (t, tab_natural_dimensions);
689 for (i = 0; i < parser->field_cnt; i++)
691 struct field *f = &parser->fields[i];
692 char str[FMT_STRING_LEN_MAX + 1];
695 tab_text (t, 0, row, TAB_LEFT, f->name);
696 tab_text (t, 1, row, TAB_LEFT | TAB_FIX,
697 fmt_to_string (&f->format, str));
700 tab_title (t, _("Reading free-form data from %s."), fh_get_name (fh));
705 /* Displays a table giving information on how PARSER will read
708 data_parser_output_description (struct data_parser *parser,
709 const struct file_handle *fh)
711 if (parser->type == DP_FIXED)
712 dump_fixed_table (parser, fh);
714 dump_delimited_table (parser, fh);
717 /* Data parser input program. */
718 struct data_parser_casereader
720 struct data_parser *parser; /* Parser. */
721 struct dfm_reader *reader; /* Data file reader. */
722 size_t value_cnt; /* Number of `union value's in case. */
725 static const struct casereader_class data_parser_casereader_class;
727 /* Replaces DS's active file by an input program that reads data
728 from READER according to the rules in PARSER, using DICT as
729 the underlying dictionary. Ownership of PARSER and READER is
730 transferred to the input program, and ownership of DICT is
731 transferred to the dataset. */
733 data_parser_make_active_file (struct data_parser *parser, struct dataset *ds,
734 struct dfm_reader *reader,
735 struct dictionary *dict)
737 struct data_parser_casereader *r;
738 struct casereader *casereader;
740 r = xmalloc (sizeof *r);
743 r->value_cnt = dict_get_next_value_idx (dict);
744 casereader = casereader_create_sequential (NULL, r->value_cnt,
746 &data_parser_casereader_class, r);
747 proc_set_active_file (ds, casereader, dict);
751 data_parser_casereader_read (struct casereader *reader UNUSED, void *r_,
754 struct data_parser_casereader *r = r_;
757 case_create (c, r->value_cnt);
758 ok = data_parser_parse (r->parser, r->reader, c);
765 data_parser_casereader_destroy (struct casereader *reader UNUSED, void *r_)
767 struct data_parser_casereader *r = r_;
768 if (dfm_reader_error (r->reader))
769 casereader_force_error (reader);
770 data_parser_destroy (r->parser);
771 dfm_close_reader (r->reader);
775 static const struct casereader_class data_parser_casereader_class =
777 data_parser_casereader_read,
778 data_parser_casereader_destroy,