Patch #5244.
[pspp-builds.git] / src / language / data-io / print.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 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/procedure.h>
26 #include <data/transformations.h>
27 #include <data/variable.h>
28 #include <language/command.h>
29 #include <language/data-io/data-writer.h>
30 #include <language/data-io/file-handle.h>
31 #include <language/data-io/placement-parser.h>
32 #include <language/lexer/format-parser.h>
33 #include <language/lexer/lexer.h>
34 #include <language/lexer/variable-parser.h>
35 #include <libpspp/alloc.h>
36 #include <libpspp/assertion.h>
37 #include <libpspp/compiler.h>
38 #include <libpspp/ll.h>
39 #include <libpspp/message.h>
40 #include <libpspp/misc.h>
41 #include <libpspp/pool.h>
42 #include <output/manager.h>
43 #include <output/table.h>
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* Describes what to do when an output field is encountered. */
49 enum field_type
50   {
51     PRT_LITERAL,                /* Literal string. */
52     PRT_VAR                     /* Variable. */
53   };
54
55 /* Describes how to output one field. */
56 struct prt_out_spec
57   {
58     /* All fields. */
59     struct ll ll;               /* In struct print_trns `specs' list. */
60     enum field_type type;       /* What type of field this is. */
61     int record;                 /* 1-based record number. */
62     int first_column;           /* 0-based first column. */
63
64     /* PRT_VAR only. */
65     struct variable *var;       /* Associated variable. */
66     struct fmt_spec format;     /* Output spec. */
67     bool add_space;             /* Add trailing space? */
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 omit_new_lines;        /* Omit new-line characters? */
85     struct dfm_writer *writer;  /* Output file, NULL=listing file. */
86     struct ll_list specs;       /* List of struct prt_out_specs. */
87     size_t record_cnt;          /* Number of records to write. */
88     struct string line;         /* Output buffer. */
89   };
90
91 enum which_formats
92   {
93     PRINT, 
94     WRITE
95   };
96
97 static int internal_cmd_print (enum which_formats, bool eject);
98 static trns_proc_func print_trns_proc;
99 static trns_free_func print_trns_free;
100 static bool parse_specs (struct pool *tmp_pool, struct print_trns *,
101                          enum which_formats);
102 static void dump_table (struct print_trns *, const struct file_handle *);
103 \f
104 /* Basic parsing. */
105
106 /* Parses PRINT command. */
107 int
108 cmd_print (void)
109 {
110   return internal_cmd_print (PRINT, false);
111 }
112
113 /* Parses PRINT EJECT command. */
114 int
115 cmd_print_eject (void)
116 {
117   return internal_cmd_print (PRINT, true);
118 }
119
120 /* Parses WRITE command. */
121 int
122 cmd_write (void)
123 {
124   return internal_cmd_print (WRITE, false);
125 }
126
127 /* Parses the output commands. */
128 static int
129 internal_cmd_print (enum which_formats which_formats, bool eject)
130 {
131   bool print_table = 0;
132   struct print_trns *trns;
133   struct file_handle *fh = NULL;
134   struct pool *tmp_pool;
135
136   /* Fill in prt to facilitate error-handling. */
137   trns = pool_create_container (struct print_trns, pool);
138   trns->eject = eject;
139   trns->writer = NULL;
140   trns->record_cnt = 0;
141   ll_init (&trns->specs);
142   ds_init_empty (&trns->line);
143   ds_register_pool (&trns->line, trns->pool);
144
145   tmp_pool = pool_create_subpool (trns->pool);
146
147   /* Parse the command options. */
148   while (token != '/')
149     {
150       if (lex_match_id ("OUTFILE"))
151         {
152           lex_match ('=');
153
154           fh = fh_parse (FH_REF_FILE);
155           if (fh == NULL)
156             goto error;
157         }
158       else if (lex_match_id ("RECORDS"))
159         {
160           lex_match ('=');
161           lex_match ('(');
162           if (!lex_force_int ())
163             goto error;
164           trns->record_cnt = lex_integer ();
165           lex_get ();
166           lex_match (')');
167         }
168       else if (lex_match_id ("TABLE"))
169         print_table = true;
170       else if (lex_match_id ("NOTABLE"))
171         print_table = false;
172       else
173         {
174           lex_error (_("expecting a valid subcommand"));
175           goto error;
176         }
177     }
178
179   /* Parse variables and strings. */
180   if (!parse_specs (tmp_pool, trns, which_formats))
181     goto error;
182
183   if (lex_end_of_command () != CMD_SUCCESS)
184     goto error;
185
186   if (fh != NULL)
187     {
188       trns->writer = dfm_open_writer (fh);
189       if (trns->writer == NULL)
190         goto error;
191
192       trns->omit_new_lines = (which_formats == WRITE
193                               && fh_get_mode (fh) == FH_MODE_BINARY);
194     }
195
196   /* Output the variable table if requested. */
197   if (print_table)
198     dump_table (trns, fh);
199
200   /* Put the transformation in the queue. */
201   add_transformation (print_trns_proc, print_trns_free, trns);
202
203   pool_destroy (tmp_pool);
204
205   return CMD_SUCCESS;
206
207  error:
208   print_trns_free (trns);
209   return CMD_FAILURE;
210 }
211 \f
212 static bool parse_string_argument (struct print_trns *,
213                                    int record, int *column);
214 static bool parse_variable_argument (struct print_trns *,
215                                      struct pool *tmp_pool,
216                                      int *record, int *column,
217                                      enum which_formats);
218
219 /* Parses all the variable and string specifications on a single
220    PRINT, PRINT EJECT, or WRITE command into the prt structure.
221    Returns success. */
222 static bool
223 parse_specs (struct pool *tmp_pool, struct print_trns *trns,
224              enum which_formats which_formats)
225 {
226   int record = 0;
227   int column = 1;
228
229   while (token != '.')
230     {
231       bool ok;
232
233       if (!parse_record_placement (&record, &column))
234         return false;
235
236       if (token == T_STRING)
237         ok = parse_string_argument (trns, record, &column);
238       else
239         ok = parse_variable_argument (trns, tmp_pool, &record, &column,
240                                       which_formats);
241       if (!ok)
242         return 0;
243     }
244
245   if (trns->record_cnt != 0 && trns->record_cnt != record)
246     msg (SW, _("Output calls for %d records but %d specified on RECORDS "
247                "subcommand."),
248          record, trns->record_cnt);
249   trns->record_cnt = record;
250
251   return true;
252 }
253
254 /* Parses a string argument to the PRINT commands.  Returns success. */
255 static bool
256 parse_string_argument (struct print_trns *trns, int record, int *column)
257 {
258   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
259   spec->type = PRT_LITERAL;
260   spec->record = record;
261   spec->first_column = *column;
262   ds_init_string (&spec->string, &tokstr);
263   ds_register_pool (&spec->string, trns->pool);
264   lex_get ();
265
266   /* Parse the included column range. */
267   if (lex_is_number ())
268     {
269       int first_column, last_column;
270       bool range_specified;
271
272       if (!parse_column_range (&first_column, &last_column, &range_specified)) 
273         return false; 
274
275       spec->first_column = first_column;
276       if (range_specified)
277         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
278     }
279   *column = spec->first_column + ds_length (&spec->string);
280
281   ll_push_tail (&trns->specs, &spec->ll);
282   return true;
283 }
284
285 /* Parses a variable argument to the PRINT commands by passing it off
286    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
287    Returns success. */
288 static bool
289 parse_variable_argument (struct print_trns *trns, struct pool *tmp_pool,
290                          int *record, int *column,
291                          enum which_formats which_formats)
292 {
293   struct variable **vars;
294   size_t var_cnt, var_idx;
295   struct fmt_spec *formats, *f;
296   size_t format_cnt;
297   bool add_space;
298   
299   if (!parse_variables_pool (tmp_pool,
300                              default_dict, &vars, &var_cnt, PV_DUPLICATE))
301     return false;
302
303   if (lex_is_number () || token == '(')
304     {
305       if (!parse_var_placements (tmp_pool, var_cnt, &formats, &format_cnt))
306         return false;
307       add_space = false;
308     }
309   else
310     {
311       size_t i;
312
313       lex_match ('*');
314       
315       formats = pool_nmalloc (tmp_pool, var_cnt, sizeof *formats);
316       format_cnt = var_cnt;
317       for (i = 0; i < var_cnt; i++) 
318         {
319           struct variable *v = vars[i];
320           formats[i] = which_formats == PRINT ? v->print : v->write; 
321         }
322       add_space = true;
323     }
324
325   var_idx = 0;
326   for (f = formats; f < &formats[format_cnt]; f++)
327     if (!execute_placement_format (f, record, column))
328       {
329         struct variable *var;
330         struct prt_out_spec *spec;
331
332         var = vars[var_idx++];
333         if (!check_specifier_width (f, var->width, true))
334           return false;
335
336         spec = pool_alloc (trns->pool, sizeof *spec);
337         spec->type = PRT_VAR;
338         spec->record = *record;
339         spec->first_column = *column;
340         spec->var = var;
341         spec->format = *f;
342         spec->add_space = add_space;
343         ll_push_tail (&trns->specs, &spec->ll);
344
345         *column += f->w + add_space;
346       }
347   assert (var_idx == var_cnt);
348
349   return true;
350 }
351
352 /* Prints the table produced by the TABLE subcommand to the listing
353    file. */
354 static void
355 dump_table (struct print_trns *trns, const struct file_handle *fh)
356 {
357   struct prt_out_spec *spec;
358   struct tab_table *t;
359   int spec_cnt;
360   int row;
361
362   spec_cnt = ll_count (&trns->specs);
363   t = tab_create (4, spec_cnt + 1, 0);
364   tab_columns (t, TAB_COL_DOWN, 1);
365   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, spec_cnt);
366   tab_hline (t, TAL_2, 0, 3, 1);
367   tab_headers (t, 0, 0, 1, 0);
368   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
369   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
370   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
371   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
372   tab_dim (t, tab_natural_dimensions);
373   row = 1;
374   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs) 
375     {
376       int width;
377       switch (spec->type)
378         {
379         case PRT_LITERAL:
380           tab_text (t, 0, row, TAB_LEFT | TAB_FIX | TAT_PRINTF, "\"%.*s\"",
381                     (int) ds_length (&spec->string), ds_data (&spec->string));
382           width = ds_length (&spec->string);
383           break;
384         case PRT_VAR:
385           tab_text (t, 0, row, TAB_LEFT, spec->var->name);
386           tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
387                     fmt_to_string (&spec->format));
388           width = spec->format.w;
389           break;
390         default:
391           NOT_REACHED ();
392         }
393       tab_text (t, 1, row, TAT_PRINTF, "%d", spec->record);
394       tab_text (t, 2, row, TAT_PRINTF, "%3d-%3d",
395                 spec->first_column, spec->first_column + width - 1);
396       row++;
397     }
398
399   if (fh != NULL)
400     tab_title (t, ngettext ("Writing %d record to %s.",
401                             "Writing %d records to %s.", trns->record_cnt),
402                trns->record_cnt, fh_get_name (fh));
403   else
404     tab_title (t, ngettext ("Writing %d record.",
405                             "Writing %d records.", trns->record_cnt),
406                trns->record_cnt);
407   tab_submit (t);
408 }
409 \f
410 /* Transformation. */
411
412 static void flush_records (struct print_trns *,
413                            int target_record, int *record);
414
415 /* Performs the transformation inside print_trns T on case C. */
416 static int
417 print_trns_proc (void *trns_, struct ccase *c, int case_num UNUSED)
418 {
419   struct print_trns *trns = trns_;
420   struct prt_out_spec *spec;
421   int record;
422
423   if (trns->eject)
424     som_eject_page ();
425
426   record = 1;
427   ds_clear (&trns->line);
428   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs) 
429     {
430       flush_records (trns, spec->record, &record);
431  
432       ds_set_length (&trns->line, spec->first_column - 1, ' ');
433       if (spec->type == PRT_VAR)
434         {
435           data_out (ds_put_uninit (&trns->line, spec->format.w),
436                     &spec->format, case_data (c, spec->var->fv));
437           if (spec->add_space)
438             ds_put_char (&trns->line, ' ');
439         }
440       else 
441         ds_put_substring (&trns->line, ds_ss (&spec->string));
442     }
443   flush_records (trns, trns->record_cnt + 1, &record);
444   
445   if (trns->writer != NULL && dfm_write_error (trns->writer))
446     return TRNS_ERROR;
447   return TRNS_CONTINUE;
448 }
449
450 static void
451 flush_records (struct print_trns *trns, int target_record, int *record)
452 {
453   while (target_record > *record) 
454     {
455       if (trns->writer == NULL)
456         tab_output_text (TAB_FIX | TAT_NOWRAP, ds_cstr (&trns->line));
457       else
458         {
459           if (!trns->omit_new_lines)
460             ds_put_char (&trns->line, '\n');
461
462           dfm_put_record (trns->writer,
463                           ds_data (&trns->line), ds_length (&trns->line));
464         }
465       ds_clear (&trns->line);
466
467       (*record)++;
468     }
469 }
470
471 /* Frees TRNS. */
472 static bool
473 print_trns_free (void *trns_)
474 {
475   struct print_trns *trns = trns_;
476   bool ok = true;
477
478   if (trns->writer != NULL)
479     ok = dfm_close_writer (trns->writer);
480   pool_destroy (trns->pool);
481
482   return ok;
483 }
484