Allow parsing 0-based column ranges.
[pspp-builds.git] / src / language / data-io / print.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006 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 <stdlib.h>
20
21 #include <data/case.h>
22 #include <data/data-out.h>
23 #include <data/procedure.h>
24 #include <data/transformations.h>
25 #include <data/variable.h>
26 #include <language/command.h>
27 #include <language/data-io/data-writer.h>
28 #include <language/data-io/file-handle.h>
29 #include <language/data-io/placement-parser.h>
30 #include <language/lexer/format-parser.h>
31 #include <language/lexer/lexer.h>
32 #include <language/lexer/variable-parser.h>
33 #include <libpspp/assertion.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/ll.h>
36 #include <libpspp/message.h>
37 #include <libpspp/misc.h>
38 #include <libpspp/pool.h>
39 #include <output/manager.h>
40 #include <output/table.h>
41
42 #include "xalloc.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* Describes what to do when an output field is encountered. */
48 enum field_type
49   {
50     PRT_LITERAL,                /* Literal string. */
51     PRT_VAR                     /* Variable. */
52   };
53
54 /* Describes how to output one field. */
55 struct prt_out_spec
56   {
57     /* All fields. */
58     struct ll ll;               /* In struct print_trns `specs' list. */
59     enum field_type type;       /* What type of field this is. */
60     int record;                 /* 1-based record number. */
61     int first_column;           /* 0-based first column. */
62
63     /* PRT_VAR only. */
64     const struct variable *var; /* Associated variable. */
65     struct fmt_spec format;     /* Output spec. */
66     bool add_space;             /* Add trailing space? */
67     bool sysmis_as_spaces;      /* Output SYSMIS as spaces? */
68
69     /* PRT_LITERAL only. */
70     struct string string;       /* String to output. */
71   };
72
73 static inline struct prt_out_spec *
74 ll_to_prt_out_spec (struct ll *ll)
75 {
76   return ll_data (ll, struct prt_out_spec, ll);
77 }
78
79 /* PRINT, PRINT EJECT, WRITE private data structure. */
80 struct print_trns
81   {
82     struct pool *pool;          /* Stores related data. */
83     bool eject;                 /* Eject page before printing? */
84     bool include_prefix;        /* Prefix lines with space? */
85     enum legacy_encoding encoding; /* Encoding to use for output. */
86     struct dfm_writer *writer;  /* Output file, NULL=listing file. */
87     struct ll_list specs;       /* List of struct prt_out_specs. */
88     size_t record_cnt;          /* Number of records to write. */
89     struct string line;         /* Output buffer. */
90   };
91
92 enum which_formats
93   {
94     PRINT,
95     WRITE
96   };
97
98 static int internal_cmd_print (struct lexer *, struct dataset *ds,
99                                enum which_formats, bool eject);
100 static trns_proc_func print_trns_proc;
101 static trns_free_func print_trns_free;
102 static bool parse_specs (struct lexer *, struct pool *tmp_pool, struct print_trns *,
103                          struct dictionary *dict, enum which_formats);
104 static void dump_table (struct print_trns *, const struct file_handle *);
105 \f
106 /* Basic parsing. */
107
108 /* Parses PRINT command. */
109 int
110 cmd_print (struct lexer *lexer, struct dataset *ds)
111 {
112   return internal_cmd_print (lexer, ds, PRINT, false);
113 }
114
115 /* Parses PRINT EJECT command. */
116 int
117 cmd_print_eject (struct lexer *lexer, struct dataset *ds)
118 {
119   return internal_cmd_print (lexer, ds, PRINT, true);
120 }
121
122 /* Parses WRITE command. */
123 int
124 cmd_write (struct lexer *lexer, struct dataset *ds)
125 {
126   return internal_cmd_print (lexer, ds, WRITE, false);
127 }
128
129 /* Parses the output commands. */
130 static int
131 internal_cmd_print (struct lexer *lexer, struct dataset *ds,
132                     enum which_formats which_formats, bool eject)
133 {
134   bool print_table = 0;
135   struct print_trns *trns;
136   struct file_handle *fh = NULL;
137   struct pool *tmp_pool;
138
139   /* Fill in prt to facilitate error-handling. */
140   trns = pool_create_container (struct print_trns, pool);
141   trns->eject = eject;
142   trns->writer = NULL;
143   trns->record_cnt = 0;
144   ll_init (&trns->specs);
145   ds_init_empty (&trns->line);
146   ds_register_pool (&trns->line, trns->pool);
147
148   tmp_pool = pool_create_subpool (trns->pool);
149
150   /* Parse the command options. */
151   while (lex_token (lexer) != '/' && lex_token (lexer) != '.')
152     {
153       if (lex_match_id (lexer, "OUTFILE"))
154         {
155           lex_match (lexer, '=');
156
157           fh = fh_parse (lexer, FH_REF_FILE);
158           if (fh == NULL)
159             goto error;
160         }
161       else if (lex_match_id (lexer, "RECORDS"))
162         {
163           lex_match (lexer, '=');
164           lex_match (lexer, '(');
165           if (!lex_force_int (lexer))
166             goto error;
167           trns->record_cnt = lex_integer (lexer);
168           lex_get (lexer);
169           lex_match (lexer, ')');
170         }
171       else if (lex_match_id (lexer, "TABLE"))
172         print_table = true;
173       else if (lex_match_id (lexer, "NOTABLE"))
174         print_table = false;
175       else
176         {
177           lex_error (lexer, _("expecting a valid subcommand"));
178           goto error;
179         }
180     }
181
182   /* When PRINT or PRINT EJECT writes to an external file, we
183      prefix each line with a space for compatibility. */
184   trns->include_prefix = which_formats == PRINT && fh != NULL;
185
186   /* Parse variables and strings. */
187   if (!parse_specs (lexer, tmp_pool, trns, dataset_dict (ds), which_formats))
188     goto error;
189
190   if (lex_end_of_command (lexer) != CMD_SUCCESS)
191     goto error;
192
193   if (fh != NULL)
194     {
195       trns->writer = dfm_open_writer (fh);
196       if (trns->writer == NULL)
197         goto error;
198       trns->encoding = dfm_writer_get_legacy_encoding (trns->writer);
199     }
200   else
201     trns->encoding = LEGACY_NATIVE;
202
203   /* Output the variable table if requested. */
204   if (print_table)
205     dump_table (trns, fh);
206
207   /* Put the transformation in the queue. */
208   add_transformation (ds, print_trns_proc, print_trns_free, trns);
209
210   pool_destroy (tmp_pool);
211   fh_unref (fh);
212
213   return CMD_SUCCESS;
214
215  error:
216   print_trns_free (trns);
217   fh_unref (fh);
218   return CMD_FAILURE;
219 }
220 \f
221 static bool parse_string_argument (struct lexer *, struct print_trns *,
222                                    int record, int *column);
223 static bool parse_variable_argument (struct lexer *, const struct dictionary *,
224                                      struct print_trns *,
225                                      struct pool *tmp_pool,
226                                      int *record, int *column,
227                                      enum which_formats);
228
229 /* Parses all the variable and string specifications on a single
230    PRINT, PRINT EJECT, or WRITE command into the prt structure.
231    Returns success. */
232 static bool
233 parse_specs (struct lexer *lexer, struct pool *tmp_pool, struct print_trns *trns,
234              struct dictionary *dict,
235              enum which_formats which_formats)
236 {
237   int record = 0;
238   int column = 1;
239
240   if (lex_token (lexer) == '.')
241     {
242       trns->record_cnt = 1;
243       return true;
244     }
245
246   while (lex_token (lexer) != '.')
247     {
248       bool ok;
249
250       if (!parse_record_placement (lexer, &record, &column))
251         return false;
252
253       if (lex_token (lexer) == T_STRING)
254         ok = parse_string_argument (lexer, trns, record, &column);
255       else
256         ok = parse_variable_argument (lexer, dict, trns, tmp_pool, &record, &column,
257                                       which_formats);
258       if (!ok)
259         return 0;
260
261       lex_match (lexer, ',');
262     }
263
264   if (trns->record_cnt != 0 && trns->record_cnt != record)
265     msg (SW, _("Output calls for %d records but %zu specified on RECORDS "
266                "subcommand."),
267          record, trns->record_cnt);
268   trns->record_cnt = record;
269
270   return true;
271 }
272
273 /* Parses a string argument to the PRINT commands.  Returns success. */
274 static bool
275 parse_string_argument (struct lexer *lexer, struct print_trns *trns, int record, int *column)
276 {
277   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
278   spec->type = PRT_LITERAL;
279   spec->record = record;
280   spec->first_column = *column;
281   ds_init_string (&spec->string, lex_tokstr (lexer));
282   ds_register_pool (&spec->string, trns->pool);
283   lex_get (lexer);
284
285   /* Parse the included column range. */
286   if (lex_is_number (lexer))
287     {
288       int first_column, last_column;
289       bool range_specified;
290
291       if (!parse_column_range (lexer, 1,
292                                &first_column, &last_column, &range_specified))
293         return false;
294
295       spec->first_column = first_column;
296       if (range_specified)
297         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
298     }
299   *column = spec->first_column + ds_length (&spec->string);
300
301   ll_push_tail (&trns->specs, &spec->ll);
302   return true;
303 }
304
305 /* Parses a variable argument to the PRINT commands by passing it off
306    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
307    Returns success. */
308 static bool
309 parse_variable_argument (struct lexer *lexer, const struct dictionary *dict,
310                          struct print_trns *trns, struct pool *tmp_pool,
311                          int *record, int *column,
312                          enum which_formats which_formats)
313 {
314   const struct variable **vars;
315   size_t var_cnt, var_idx;
316   struct fmt_spec *formats, *f;
317   size_t format_cnt;
318   bool add_space;
319
320   if (!parse_variables_const_pool (lexer, tmp_pool, dict,
321                              &vars, &var_cnt, PV_DUPLICATE))
322     return false;
323
324   if (lex_is_number (lexer) || lex_token (lexer) == '(')
325     {
326       if (!parse_var_placements (lexer, tmp_pool, var_cnt, false,
327                                  &formats, &format_cnt))
328         return false;
329       add_space = false;
330     }
331   else
332     {
333       size_t i;
334
335       lex_match (lexer, '*');
336
337       formats = pool_nmalloc (tmp_pool, var_cnt, sizeof *formats);
338       format_cnt = var_cnt;
339       for (i = 0; i < var_cnt; i++)
340         {
341           const struct variable *v = vars[i];
342           formats[i] = (which_formats == PRINT
343                         ? *var_get_print_format (v)
344                         : *var_get_write_format (v));
345         }
346       add_space = which_formats == PRINT;
347     }
348
349   var_idx = 0;
350   for (f = formats; f < &formats[format_cnt]; f++)
351     if (!execute_placement_format (f, record, column))
352       {
353         const struct variable *var;
354         struct prt_out_spec *spec;
355
356         var = vars[var_idx++];
357         if (!fmt_check_width_compat (f, var_get_width (var)))
358           return false;
359
360         spec = pool_alloc (trns->pool, sizeof *spec);
361         spec->type = PRT_VAR;
362         spec->record = *record;
363         spec->first_column = *column;
364         spec->var = var;
365         spec->format = *f;
366         spec->add_space = add_space;
367
368         /* This is a completely bizarre twist for compatibility:
369            WRITE outputs the system-missing value as a field
370            filled with spaces, instead of using the normal format
371            that usually contains a period. */
372         spec->sysmis_as_spaces = (which_formats == WRITE
373                                   && var_is_numeric (var)
374                                   && (fmt_get_category (spec->format.type)
375                                       != FMT_CAT_BINARY));
376
377         ll_push_tail (&trns->specs, &spec->ll);
378
379         *column += f->w + add_space;
380       }
381   assert (var_idx == var_cnt);
382
383   return true;
384 }
385
386 /* Prints the table produced by the TABLE subcommand to the listing
387    file. */
388 static void
389 dump_table (struct print_trns *trns, const struct file_handle *fh)
390 {
391   struct prt_out_spec *spec;
392   struct tab_table *t;
393   int spec_cnt;
394   int row;
395
396   spec_cnt = ll_count (&trns->specs);
397   t = tab_create (4, spec_cnt + 1, 0);
398   tab_columns (t, TAB_COL_DOWN, 1);
399   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, spec_cnt);
400   tab_hline (t, TAL_2, 0, 3, 1);
401   tab_headers (t, 0, 0, 1, 0);
402   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
403   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
404   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
405   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
406   tab_dim (t, tab_natural_dimensions);
407   row = 1;
408   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
409     {
410       char fmt_string[FMT_STRING_LEN_MAX + 1];
411       int width;
412       switch (spec->type)
413         {
414         case PRT_LITERAL:
415           tab_text (t, 0, row, TAB_LEFT | TAB_FIX | TAT_PRINTF, "\"%.*s\"",
416                     (int) ds_length (&spec->string), ds_data (&spec->string));
417           width = ds_length (&spec->string);
418           break;
419         case PRT_VAR:
420           tab_text (t, 0, row, TAB_LEFT, var_get_name (spec->var));
421           tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
422                     fmt_to_string (&spec->format, fmt_string));
423           width = spec->format.w;
424           break;
425         default:
426           NOT_REACHED ();
427         }
428       tab_text (t, 1, row, TAT_PRINTF, "%d", spec->record);
429       tab_text (t, 2, row, TAT_PRINTF, "%3d-%3d",
430                 spec->first_column, spec->first_column + width - 1);
431       row++;
432     }
433
434   if (fh != NULL)
435     tab_title (t, ngettext ("Writing %d record to %s.",
436                             "Writing %d records to %s.", trns->record_cnt),
437                trns->record_cnt, fh_get_name (fh));
438   else
439     tab_title (t, ngettext ("Writing %d record.",
440                             "Writing %d records.", trns->record_cnt),
441                trns->record_cnt);
442   tab_submit (t);
443 }
444 \f
445 /* Transformation. */
446
447 static void flush_records (struct print_trns *, int target_record,
448                            bool *eject, int *record);
449
450 /* Performs the transformation inside print_trns T on case C. */
451 static int
452 print_trns_proc (void *trns_, struct ccase *c, casenumber case_num UNUSED)
453 {
454   struct print_trns *trns = trns_;
455   bool eject = trns->eject;
456   char encoded_space = legacy_from_native (trns->encoding, ' ');
457   int record = 1;
458   struct prt_out_spec *spec;
459
460   ds_clear (&trns->line);
461   ds_put_char (&trns->line, ' ');
462   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
463     {
464       flush_records (trns, spec->record, &eject, &record);
465
466       ds_set_length (&trns->line, spec->first_column, encoded_space);
467       if (spec->type == PRT_VAR)
468         {
469           const union value *input = case_data (c, spec->var);
470           char *output = ds_put_uninit (&trns->line, spec->format.w);
471           if (!spec->sysmis_as_spaces || input->f != SYSMIS)
472             data_out_legacy (input, trns->encoding, &spec->format, output);
473           else
474             memset (output, encoded_space, spec->format.w);
475           if (spec->add_space)
476             ds_put_char (&trns->line, encoded_space);
477         }
478       else
479         {
480           ds_put_substring (&trns->line, ds_ss (&spec->string));
481           if (trns->encoding != LEGACY_NATIVE)
482             {
483               size_t length = ds_length (&spec->string);
484               char *data = ss_data (ds_tail (&trns->line, length));
485               legacy_recode (LEGACY_NATIVE, data,
486                              trns->encoding, data, length);
487             }
488         }
489     }
490   flush_records (trns, trns->record_cnt + 1, &eject, &record);
491
492   if (trns->writer != NULL && dfm_write_error (trns->writer))
493     return TRNS_ERROR;
494   return TRNS_CONTINUE;
495 }
496
497 /* Advance from *RECORD to TARGET_RECORD, outputting records
498    along the way.  If *EJECT is true, then the first record
499    output is preceded by ejecting the page (and *EJECT is set
500    false). */
501 static void
502 flush_records (struct print_trns *trns, int target_record,
503                bool *eject, int *record)
504 {
505   for (; target_record > *record; (*record)++)
506     {
507       char *line = ds_cstr (&trns->line);
508       size_t length = ds_length (&trns->line);
509       char leader = ' ';
510
511       if (*eject)
512         {
513           *eject = false;
514           if (trns->writer == NULL)
515             som_eject_page ();
516           else
517             leader = '1';
518         }
519       line[0] = legacy_from_native (trns->encoding, leader);
520
521       if (trns->writer == NULL)
522         tab_output_text (TAB_FIX | TAT_NOWRAP, &line[1]);
523       else
524         {
525           if (!trns->include_prefix)
526             {
527               line++;
528               length--;
529             }
530           dfm_put_record (trns->writer, line, length);
531         }
532
533       ds_truncate (&trns->line, 1);
534     }
535 }
536
537 /* Frees TRNS. */
538 static bool
539 print_trns_free (void *trns_)
540 {
541   struct print_trns *trns = trns_;
542   bool ok = true;
543
544   if (trns->writer != NULL)
545     ok = dfm_close_writer (trns->writer);
546   pool_destroy (trns->pool);
547
548   return ok;
549 }
550