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