Change license from GPLv2+ to GPLv3+.
[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/alloc.h>
34 #include <libpspp/assertion.h>
35 #include <libpspp/compiler.h>
36 #include <libpspp/ll.h>
37 #include <libpspp/message.h>
38 #include <libpspp/misc.h>
39 #include <libpspp/pool.h>
40 #include <output/manager.h>
41 #include <output/table.h>
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* Describes what to do when an output field is encountered. */
47 enum field_type
48   {
49     PRT_LITERAL,                /* Literal string. */
50     PRT_VAR                     /* Variable. */
51   };
52
53 /* Describes how to output one field. */
54 struct prt_out_spec
55   {
56     /* All fields. */
57     struct ll ll;               /* In struct print_trns `specs' list. */
58     enum field_type type;       /* What type of field this is. */
59     int record;                 /* 1-based record number. */
60     int first_column;           /* 0-based first column. */
61
62     /* PRT_VAR only. */
63     const struct variable *var; /* Associated variable. */
64     struct fmt_spec format;     /* Output spec. */
65     bool add_space;             /* Add trailing space? */
66     bool sysmis_as_spaces;      /* Output SYSMIS as spaces? */
67
68     /* PRT_LITERAL only. */
69     struct string string;       /* String to output. */
70   };
71
72 static inline struct prt_out_spec *
73 ll_to_prt_out_spec (struct ll *ll)
74 {
75   return ll_data (ll, struct prt_out_spec, ll);
76 }
77
78 /* PRINT, PRINT EJECT, WRITE private data structure. */
79 struct print_trns
80   {
81     struct pool *pool;          /* Stores related data. */
82     bool eject;                 /* Eject page before printing? */
83     bool include_prefix;        /* Prefix lines with space? */
84     struct dfm_writer *writer;  /* Output file, NULL=listing file. */
85     struct ll_list specs;       /* List of struct prt_out_specs. */
86     size_t record_cnt;          /* Number of records to write. */
87     struct string line;         /* Output buffer. */
88   };
89
90 enum which_formats
91   {
92     PRINT,
93     WRITE
94   };
95
96 static int internal_cmd_print (struct lexer *, struct dataset *ds,
97                                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 lexer *, struct pool *tmp_pool, struct print_trns *,
101                          struct dictionary *dict, 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 (struct lexer *lexer, struct dataset *ds)
109 {
110   return internal_cmd_print (lexer, ds, PRINT, false);
111 }
112
113 /* Parses PRINT EJECT command. */
114 int
115 cmd_print_eject (struct lexer *lexer, struct dataset *ds)
116 {
117   return internal_cmd_print (lexer, ds, PRINT, true);
118 }
119
120 /* Parses WRITE command. */
121 int
122 cmd_write (struct lexer *lexer, struct dataset *ds)
123 {
124   return internal_cmd_print (lexer, ds, WRITE, false);
125 }
126
127 /* Parses the output commands. */
128 static int
129 internal_cmd_print (struct lexer *lexer, struct dataset *ds,
130                     enum which_formats which_formats, bool eject)
131 {
132   bool print_table = 0;
133   struct print_trns *trns;
134   struct file_handle *fh = NULL;
135   struct pool *tmp_pool;
136
137   /* Fill in prt to facilitate error-handling. */
138   trns = pool_create_container (struct print_trns, pool);
139   trns->eject = eject;
140   trns->writer = NULL;
141   trns->record_cnt = 0;
142   ll_init (&trns->specs);
143   ds_init_empty (&trns->line);
144   ds_register_pool (&trns->line, trns->pool);
145
146   tmp_pool = pool_create_subpool (trns->pool);
147
148   /* Parse the command options. */
149   while (lex_token (lexer) != '/' && lex_token (lexer) != '.')
150     {
151       if (lex_match_id (lexer, "OUTFILE"))
152         {
153           lex_match (lexer, '=');
154
155           fh = fh_parse (lexer, FH_REF_FILE);
156           if (fh == NULL)
157             goto error;
158         }
159       else if (lex_match_id (lexer, "RECORDS"))
160         {
161           lex_match (lexer, '=');
162           lex_match (lexer, '(');
163           if (!lex_force_int (lexer))
164             goto error;
165           trns->record_cnt = lex_integer (lexer);
166           lex_get (lexer);
167           lex_match (lexer, ')');
168         }
169       else if (lex_match_id (lexer, "TABLE"))
170         print_table = true;
171       else if (lex_match_id (lexer, "NOTABLE"))
172         print_table = false;
173       else
174         {
175           lex_error (lexer, _("expecting a valid subcommand"));
176           goto error;
177         }
178     }
179
180   /* When PRINT or PRINT EJECT writes to an external file, we
181      prefix each line with a space for compatibility. */
182   trns->include_prefix = which_formats == PRINT && fh != NULL;
183
184   /* Parse variables and strings. */
185   if (!parse_specs (lexer, tmp_pool, trns, dataset_dict (ds), which_formats))
186     goto error;
187
188   if (lex_end_of_command (lexer) != CMD_SUCCESS)
189     goto error;
190
191   if (fh != NULL)
192     {
193       trns->writer = dfm_open_writer (fh);
194       if (trns->writer == NULL)
195         goto error;
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 lexer *, struct print_trns *,
215                                    int record, int *column);
216 static bool parse_variable_argument (struct lexer *, 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 lexer *lexer, 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   if (lex_token (lexer) == '.')
234     {
235       trns->record_cnt = 1;
236       return true;
237     }
238
239   while (lex_token (lexer) != '.')
240     {
241       bool ok;
242
243       if (!parse_record_placement (lexer, &record, &column))
244         return false;
245
246       if (lex_token (lexer) == T_STRING)
247         ok = parse_string_argument (lexer, trns, record, &column);
248       else
249         ok = parse_variable_argument (lexer, dict, trns, tmp_pool, &record, &column,
250                                       which_formats);
251       if (!ok)
252         return 0;
253
254       lex_match (lexer, ',');
255     }
256
257   if (trns->record_cnt != 0 && trns->record_cnt != record)
258     msg (SW, _("Output calls for %d records but %u specified on RECORDS "
259                "subcommand."),
260          record, (unsigned int) trns->record_cnt);
261   trns->record_cnt = record;
262
263   return true;
264 }
265
266 /* Parses a string argument to the PRINT commands.  Returns success. */
267 static bool
268 parse_string_argument (struct lexer *lexer, struct print_trns *trns, int record, int *column)
269 {
270   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
271   spec->type = PRT_LITERAL;
272   spec->record = record;
273   spec->first_column = *column;
274   ds_init_string (&spec->string, lex_tokstr (lexer));
275   ds_register_pool (&spec->string, trns->pool);
276   lex_get (lexer);
277
278   /* Parse the included column range. */
279   if (lex_is_number (lexer))
280     {
281       int first_column, last_column;
282       bool range_specified;
283
284       if (!parse_column_range (lexer, &first_column, &last_column, &range_specified))
285         return false;
286
287       spec->first_column = first_column;
288       if (range_specified)
289         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
290     }
291   *column = spec->first_column + ds_length (&spec->string);
292
293   ll_push_tail (&trns->specs, &spec->ll);
294   return true;
295 }
296
297 /* Parses a variable argument to the PRINT commands by passing it off
298    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
299    Returns success. */
300 static bool
301 parse_variable_argument (struct lexer *lexer, const struct dictionary *dict,
302                          struct print_trns *trns, struct pool *tmp_pool,
303                          int *record, int *column,
304                          enum which_formats which_formats)
305 {
306   const struct variable **vars;
307   size_t var_cnt, var_idx;
308   struct fmt_spec *formats, *f;
309   size_t format_cnt;
310   bool add_space;
311
312   if (!parse_variables_const_pool (lexer, tmp_pool, dict,
313                              &vars, &var_cnt, PV_DUPLICATE))
314     return false;
315
316   if (lex_is_number (lexer) || lex_token (lexer) == '(')
317     {
318       if (!parse_var_placements (lexer, tmp_pool, var_cnt, false,
319                                  &formats, &format_cnt))
320         return false;
321       add_space = false;
322     }
323   else
324     {
325       size_t i;
326
327       lex_match (lexer, '*');
328
329       formats = pool_nmalloc (tmp_pool, var_cnt, sizeof *formats);
330       format_cnt = var_cnt;
331       for (i = 0; i < var_cnt; i++)
332         {
333           const struct variable *v = vars[i];
334           formats[i] = (which_formats == PRINT
335                         ? *var_get_print_format (v)
336                         : *var_get_write_format (v));
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         const struct variable *var;
346         struct prt_out_spec *spec;
347
348         var = vars[var_idx++];
349         if (!fmt_check_width_compat (f, var_get_width (var)))
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_is_numeric (var)
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, var_get_name (spec->var));
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);
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