Remove "Written by Ben Pfaff <blp@gnu.org>" lines everywhere.
[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
4    This program is free software; you can redistribute it and/or
5    modify it under the terms of the GNU General Public License as
6    published by the Free Software Foundation; either version 2 of the
7    License, or (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful, but
10    WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12    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, write to the Free Software
16    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17    02110-1301, USA. */
18
19 #include <config.h>
20
21 #include <stdlib.h>
22
23 #include <data/case.h>
24 #include <data/data-out.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     bool sysmis_as_spaces;      /* Output SYSMIS as spaces? */
69
70     /* PRT_LITERAL only. */
71     struct string string;       /* String to output. */
72   };
73
74 static inline struct prt_out_spec *
75 ll_to_prt_out_spec (struct ll *ll) 
76 {
77   return ll_data (ll, struct prt_out_spec, ll);
78 }
79
80 /* PRINT, PRINT EJECT, WRITE private data structure. */
81 struct print_trns
82   {
83     struct pool *pool;          /* Stores related data. */
84     bool eject;                 /* Eject page before printing? */
85     bool include_prefix;        /* Prefix lines with space? */
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     }
199
200   /* Output the variable table if requested. */
201   if (print_table)
202     dump_table (trns, fh);
203
204   /* Put the transformation in the queue. */
205   add_transformation (ds, print_trns_proc, print_trns_free, trns);
206
207   pool_destroy (tmp_pool);
208
209   return CMD_SUCCESS;
210
211  error:
212   print_trns_free (trns);
213   return CMD_FAILURE;
214 }
215 \f
216 static bool parse_string_argument (struct lexer *, struct print_trns *,
217                                    int record, int *column);
218 static bool parse_variable_argument (struct lexer *, const struct dictionary *, 
219                                      struct print_trns *,
220                                      struct pool *tmp_pool,
221                                      int *record, int *column,
222                                      enum which_formats);
223
224 /* Parses all the variable and string specifications on a single
225    PRINT, PRINT EJECT, or WRITE command into the prt structure.
226    Returns success. */
227 static bool
228 parse_specs (struct lexer *lexer, struct pool *tmp_pool, struct print_trns *trns,
229              struct dictionary *dict, 
230              enum which_formats which_formats)
231 {
232   int record = 0;
233   int column = 1;
234
235   if (lex_token (lexer) == '.') 
236     {
237       trns->record_cnt = 1;
238       return true;
239     }
240
241   while (lex_token (lexer) != '.')
242     {
243       bool ok;
244
245       if (!parse_record_placement (lexer, &record, &column))
246         return false;
247
248       if (lex_token (lexer) == T_STRING)
249         ok = parse_string_argument (lexer, trns, record, &column);
250       else
251         ok = parse_variable_argument (lexer, dict, trns, tmp_pool, &record, &column,
252                                       which_formats);
253       if (!ok)
254         return 0;
255
256       lex_match (lexer, ',');
257     }
258
259   if (trns->record_cnt != 0 && trns->record_cnt != record)
260     msg (SW, _("Output calls for %d records but %d specified on RECORDS "
261                "subcommand."),
262          record, trns->record_cnt);
263   trns->record_cnt = record;
264
265   return true;
266 }
267
268 /* Parses a string argument to the PRINT commands.  Returns success. */
269 static bool
270 parse_string_argument (struct lexer *lexer, struct print_trns *trns, int record, int *column)
271 {
272   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
273   spec->type = PRT_LITERAL;
274   spec->record = record;
275   spec->first_column = *column;
276   ds_init_string (&spec->string, lex_tokstr (lexer));
277   ds_register_pool (&spec->string, trns->pool);
278   lex_get (lexer);
279
280   /* Parse the included column range. */
281   if (lex_is_number (lexer))
282     {
283       int first_column, last_column;
284       bool range_specified;
285
286       if (!parse_column_range (lexer, &first_column, &last_column, &range_specified)) 
287         return false; 
288
289       spec->first_column = first_column;
290       if (range_specified)
291         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
292     }
293   *column = spec->first_column + ds_length (&spec->string);
294
295   ll_push_tail (&trns->specs, &spec->ll);
296   return true;
297 }
298
299 /* Parses a variable argument to the PRINT commands by passing it off
300    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
301    Returns success. */
302 static bool
303 parse_variable_argument (struct lexer *lexer, const struct dictionary *dict,
304                          struct print_trns *trns, struct pool *tmp_pool,
305                          int *record, int *column,
306                          enum which_formats which_formats)
307 {
308   struct variable **vars;
309   size_t var_cnt, var_idx;
310   struct fmt_spec *formats, *f;
311   size_t format_cnt;
312   bool add_space;
313   
314   if (!parse_variables_pool (lexer, tmp_pool, dict, 
315                              &vars, &var_cnt, PV_DUPLICATE))
316     return false;
317
318   if (lex_is_number (lexer) || lex_token (lexer) == '(')
319     {
320       if (!parse_var_placements (lexer, 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 (lexer, '*');
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
337                         ? *var_get_print_format (v)
338                         : *var_get_write_format (v));
339         }
340       add_space = which_formats == PRINT;
341     }
342
343   var_idx = 0;
344   for (f = formats; f < &formats[format_cnt]; f++)
345     if (!execute_placement_format (f, record, column))
346       {
347         struct variable *var;
348         struct prt_out_spec *spec;
349
350         var = vars[var_idx++];
351         if (!fmt_check_width_compat (f, var_get_width (var)))
352           return false;
353
354         spec = pool_alloc (trns->pool, sizeof *spec);
355         spec->type = PRT_VAR;
356         spec->record = *record;
357         spec->first_column = *column;
358         spec->var = var;
359         spec->format = *f;
360         spec->add_space = add_space;
361
362         /* This is a completely bizarre twist for compatibility:
363            WRITE outputs the system-missing value as a field
364            filled with spaces, instead of using the normal format
365            that usually contains a period. */ 
366         spec->sysmis_as_spaces = (which_formats == WRITE
367                                   && var_is_numeric (var)
368                                   && (fmt_get_category (spec->format.type)
369                                       != FMT_CAT_BINARY));
370
371         ll_push_tail (&trns->specs, &spec->ll);
372
373         *column += f->w + add_space;
374       }
375   assert (var_idx == var_cnt);
376
377   return true;
378 }
379
380 /* Prints the table produced by the TABLE subcommand to the listing
381    file. */
382 static void
383 dump_table (struct print_trns *trns, const struct file_handle *fh)
384 {
385   struct prt_out_spec *spec;
386   struct tab_table *t;
387   int spec_cnt;
388   int row;
389
390   spec_cnt = ll_count (&trns->specs);
391   t = tab_create (4, spec_cnt + 1, 0);
392   tab_columns (t, TAB_COL_DOWN, 1);
393   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, spec_cnt);
394   tab_hline (t, TAL_2, 0, 3, 1);
395   tab_headers (t, 0, 0, 1, 0);
396   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
397   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
398   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
399   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
400   tab_dim (t, tab_natural_dimensions);
401   row = 1;
402   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs) 
403     {
404       char fmt_string[FMT_STRING_LEN_MAX + 1];
405       int width;
406       switch (spec->type)
407         {
408         case PRT_LITERAL:
409           tab_text (t, 0, row, TAB_LEFT | TAB_FIX | TAT_PRINTF, "\"%.*s\"",
410                     (int) ds_length (&spec->string), ds_data (&spec->string));
411           width = ds_length (&spec->string);
412           break;
413         case PRT_VAR:
414           tab_text (t, 0, row, TAB_LEFT, var_get_name (spec->var));
415           tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
416                     fmt_to_string (&spec->format, fmt_string));
417           width = spec->format.w;
418           break;
419         default:
420           NOT_REACHED ();
421         }
422       tab_text (t, 1, row, TAT_PRINTF, "%d", spec->record);
423       tab_text (t, 2, row, TAT_PRINTF, "%3d-%3d",
424                 spec->first_column, spec->first_column + width - 1);
425       row++;
426     }
427
428   if (fh != NULL)
429     tab_title (t, ngettext ("Writing %d record to %s.",
430                             "Writing %d records to %s.", trns->record_cnt),
431                trns->record_cnt, fh_get_name (fh));
432   else
433     tab_title (t, ngettext ("Writing %d record.",
434                             "Writing %d records.", trns->record_cnt),
435                trns->record_cnt);
436   tab_submit (t);
437 }
438 \f
439 /* Transformation. */
440
441 static void flush_records (struct print_trns *, int target_record,
442                            bool *eject, int *record);
443
444 /* Performs the transformation inside print_trns T on case C. */
445 static int
446 print_trns_proc (void *trns_, struct ccase *c, casenumber case_num UNUSED)
447 {
448   struct print_trns *trns = trns_;
449   bool eject = trns->eject;
450   int record = 1;
451   struct prt_out_spec *spec;
452
453   ds_clear (&trns->line);
454   ds_put_char (&trns->line, ' ');
455   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs) 
456     {
457       flush_records (trns, spec->record, &eject, &record);
458  
459       ds_set_length (&trns->line, spec->first_column, ' ');
460       if (spec->type == PRT_VAR)
461         {
462           const union value *input = case_data (c, spec->var);
463           char *output = ds_put_uninit (&trns->line, spec->format.w);
464           if (!spec->sysmis_as_spaces || input->f != SYSMIS)
465             data_out (input, &spec->format, output);
466           else
467             memset (output, ' ', spec->format.w);
468           if (spec->add_space)
469             ds_put_char (&trns->line, ' ');
470         }
471       else 
472         ds_put_substring (&trns->line, ds_ss (&spec->string));
473     }
474   flush_records (trns, trns->record_cnt + 1, &eject, &record);
475   
476   if (trns->writer != NULL && dfm_write_error (trns->writer))
477     return TRNS_ERROR;
478   return TRNS_CONTINUE;
479 }
480
481 /* Advance from *RECORD to TARGET_RECORD, outputting records
482    along the way.  If *EJECT is true, then the first record
483    output is preceded by ejecting the page (and *EJECT is set
484    false). */
485 static void
486 flush_records (struct print_trns *trns, int target_record,
487                bool *eject, int *record)
488 {
489   for (; target_record > *record; (*record)++) 
490     {
491       char *line = ds_cstr (&trns->line);
492       size_t length = ds_length (&trns->line);
493       char leader = ' ';
494       
495       if (*eject) 
496         {
497           *eject = false;
498           if (trns->writer == NULL)
499             som_eject_page ();
500           else
501             leader = '1';
502         }
503       line[0] = leader;
504       
505       if (trns->writer == NULL)
506         tab_output_text (TAB_FIX | TAT_NOWRAP, &line[1]);
507       else
508         {
509           if (!trns->include_prefix) 
510             {
511               line++;
512               length--; 
513             }
514           dfm_put_record (trns->writer, line, length);
515         }
516       
517       ds_truncate (&trns->line, 1);
518     }
519 }
520
521 /* Frees TRNS. */
522 static bool
523 print_trns_free (void *trns_)
524 {
525   struct print_trns *trns = trns_;
526   bool ok = true;
527
528   if (trns->writer != NULL)
529     ok = dfm_close_writer (trns->writer);
530   pool_destroy (trns->pool);
531
532   return ok;
533 }
534