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