posix-xprintf-functions.patch from patch #6230.
[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/assertion.h>
34 #include <libpspp/compiler.h>
35 #include <libpspp/ll.h>
36 #include <libpspp/message.h>
37 #include <libpspp/misc.h>
38 #include <libpspp/pool.h>
39 #include <output/manager.h>
40 #include <output/table.h>
41
42 #include "xalloc.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* Describes what to do when an output field is encountered. */
48 enum field_type
49   {
50     PRT_LITERAL,                /* Literal string. */
51     PRT_VAR                     /* Variable. */
52   };
53
54 /* Describes how to output one field. */
55 struct prt_out_spec
56   {
57     /* All fields. */
58     struct ll ll;               /* In struct print_trns `specs' list. */
59     enum field_type type;       /* What type of field this is. */
60     int record;                 /* 1-based record number. */
61     int first_column;           /* 0-based first column. */
62
63     /* PRT_VAR only. */
64     const struct variable *var; /* Associated variable. */
65     struct fmt_spec format;     /* Output spec. */
66     bool add_space;             /* Add trailing space? */
67     bool sysmis_as_spaces;      /* Output SYSMIS as spaces? */
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 include_prefix;        /* Prefix lines with space? */
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 lexer *, 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 lexer *, 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 lexer *lexer, struct dataset *ds)
110 {
111   return internal_cmd_print (lexer, ds, PRINT, false);
112 }
113
114 /* Parses PRINT EJECT command. */
115 int
116 cmd_print_eject (struct lexer *lexer, struct dataset *ds)
117 {
118   return internal_cmd_print (lexer, ds, PRINT, true);
119 }
120
121 /* Parses WRITE command. */
122 int
123 cmd_write (struct lexer *lexer, struct dataset *ds)
124 {
125   return internal_cmd_print (lexer, ds, WRITE, false);
126 }
127
128 /* Parses the output commands. */
129 static int
130 internal_cmd_print (struct lexer *lexer, 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 (lex_token (lexer) != '/' && lex_token (lexer) != '.')
151     {
152       if (lex_match_id (lexer, "OUTFILE"))
153         {
154           lex_match (lexer, '=');
155
156           fh = fh_parse (lexer, FH_REF_FILE);
157           if (fh == NULL)
158             goto error;
159         }
160       else if (lex_match_id (lexer, "RECORDS"))
161         {
162           lex_match (lexer, '=');
163           lex_match (lexer, '(');
164           if (!lex_force_int (lexer))
165             goto error;
166           trns->record_cnt = lex_integer (lexer);
167           lex_get (lexer);
168           lex_match (lexer, ')');
169         }
170       else if (lex_match_id (lexer, "TABLE"))
171         print_table = true;
172       else if (lex_match_id (lexer, "NOTABLE"))
173         print_table = false;
174       else
175         {
176           lex_error (lexer, _("expecting a valid subcommand"));
177           goto error;
178         }
179     }
180
181   /* When PRINT or PRINT EJECT writes to an external file, we
182      prefix each line with a space for compatibility. */
183   trns->include_prefix = which_formats == PRINT && fh != NULL;
184
185   /* Parse variables and strings. */
186   if (!parse_specs (lexer, tmp_pool, trns, dataset_dict (ds), which_formats))
187     goto error;
188
189   if (lex_end_of_command (lexer) != CMD_SUCCESS)
190     goto error;
191
192   if (fh != NULL)
193     {
194       trns->writer = dfm_open_writer (fh);
195       if (trns->writer == NULL)
196         goto error;
197     }
198
199   /* Output the variable table if requested. */
200   if (print_table)
201     dump_table (trns, fh);
202
203   /* Put the transformation in the queue. */
204   add_transformation (ds, print_trns_proc, print_trns_free, trns);
205
206   pool_destroy (tmp_pool);
207
208   return CMD_SUCCESS;
209
210  error:
211   print_trns_free (trns);
212   return CMD_FAILURE;
213 }
214 \f
215 static bool parse_string_argument (struct lexer *, struct print_trns *,
216                                    int record, int *column);
217 static bool parse_variable_argument (struct lexer *, const struct dictionary *,
218                                      struct print_trns *,
219                                      struct pool *tmp_pool,
220                                      int *record, int *column,
221                                      enum which_formats);
222
223 /* Parses all the variable and string specifications on a single
224    PRINT, PRINT EJECT, or WRITE command into the prt structure.
225    Returns success. */
226 static bool
227 parse_specs (struct lexer *lexer, struct pool *tmp_pool, struct print_trns *trns,
228              struct dictionary *dict,
229              enum which_formats which_formats)
230 {
231   int record = 0;
232   int column = 1;
233
234   if (lex_token (lexer) == '.')
235     {
236       trns->record_cnt = 1;
237       return true;
238     }
239
240   while (lex_token (lexer) != '.')
241     {
242       bool ok;
243
244       if (!parse_record_placement (lexer, &record, &column))
245         return false;
246
247       if (lex_token (lexer) == T_STRING)
248         ok = parse_string_argument (lexer, trns, record, &column);
249       else
250         ok = parse_variable_argument (lexer, dict, trns, tmp_pool, &record, &column,
251                                       which_formats);
252       if (!ok)
253         return 0;
254
255       lex_match (lexer, ',');
256     }
257
258   if (trns->record_cnt != 0 && trns->record_cnt != record)
259     msg (SW, _("Output calls for %d records but %zu specified on RECORDS "
260                "subcommand."),
261          record, trns->record_cnt);
262   trns->record_cnt = record;
263
264   return true;
265 }
266
267 /* Parses a string argument to the PRINT commands.  Returns success. */
268 static bool
269 parse_string_argument (struct lexer *lexer, struct print_trns *trns, int record, int *column)
270 {
271   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
272   spec->type = PRT_LITERAL;
273   spec->record = record;
274   spec->first_column = *column;
275   ds_init_string (&spec->string, lex_tokstr (lexer));
276   ds_register_pool (&spec->string, trns->pool);
277   lex_get (lexer);
278
279   /* Parse the included column range. */
280   if (lex_is_number (lexer))
281     {
282       int first_column, last_column;
283       bool range_specified;
284
285       if (!parse_column_range (lexer, &first_column, &last_column, &range_specified))
286         return false;
287
288       spec->first_column = first_column;
289       if (range_specified)
290         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
291     }
292   *column = spec->first_column + ds_length (&spec->string);
293
294   ll_push_tail (&trns->specs, &spec->ll);
295   return true;
296 }
297
298 /* Parses a variable argument to the PRINT commands by passing it off
299    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
300    Returns success. */
301 static bool
302 parse_variable_argument (struct lexer *lexer, const struct dictionary *dict,
303                          struct print_trns *trns, struct pool *tmp_pool,
304                          int *record, int *column,
305                          enum which_formats which_formats)
306 {
307   const struct variable **vars;
308   size_t var_cnt, var_idx;
309   struct fmt_spec *formats, *f;
310   size_t format_cnt;
311   bool add_space;
312
313   if (!parse_variables_const_pool (lexer, tmp_pool, dict,
314                              &vars, &var_cnt, PV_DUPLICATE))
315     return false;
316
317   if (lex_is_number (lexer) || lex_token (lexer) == '(')
318     {
319       if (!parse_var_placements (lexer, tmp_pool, var_cnt, false,
320                                  &formats, &format_cnt))
321         return false;
322       add_space = false;
323     }
324   else
325     {
326       size_t i;
327
328       lex_match (lexer, '*');
329
330       formats = pool_nmalloc (tmp_pool, var_cnt, sizeof *formats);
331       format_cnt = var_cnt;
332       for (i = 0; i < var_cnt; i++)
333         {
334           const struct variable *v = vars[i];
335           formats[i] = (which_formats == PRINT
336                         ? *var_get_print_format (v)
337                         : *var_get_write_format (v));
338         }
339       add_space = which_formats == PRINT;
340     }
341
342   var_idx = 0;
343   for (f = formats; f < &formats[format_cnt]; f++)
344     if (!execute_placement_format (f, record, column))
345       {
346         const struct variable *var;
347         struct prt_out_spec *spec;
348
349         var = vars[var_idx++];
350         if (!fmt_check_width_compat (f, var_get_width (var)))
351           return false;
352
353         spec = pool_alloc (trns->pool, sizeof *spec);
354         spec->type = PRT_VAR;
355         spec->record = *record;
356         spec->first_column = *column;
357         spec->var = var;
358         spec->format = *f;
359         spec->add_space = add_space;
360
361         /* This is a completely bizarre twist for compatibility:
362            WRITE outputs the system-missing value as a field
363            filled with spaces, instead of using the normal format
364            that usually contains a period. */
365         spec->sysmis_as_spaces = (which_formats == WRITE
366                                   && var_is_numeric (var)
367                                   && (fmt_get_category (spec->format.type)
368                                       != FMT_CAT_BINARY));
369
370         ll_push_tail (&trns->specs, &spec->ll);
371
372         *column += f->w + add_space;
373       }
374   assert (var_idx == var_cnt);
375
376   return true;
377 }
378
379 /* Prints the table produced by the TABLE subcommand to the listing
380    file. */
381 static void
382 dump_table (struct print_trns *trns, const struct file_handle *fh)
383 {
384   struct prt_out_spec *spec;
385   struct tab_table *t;
386   int spec_cnt;
387   int row;
388
389   spec_cnt = ll_count (&trns->specs);
390   t = tab_create (4, spec_cnt + 1, 0);
391   tab_columns (t, TAB_COL_DOWN, 1);
392   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, spec_cnt);
393   tab_hline (t, TAL_2, 0, 3, 1);
394   tab_headers (t, 0, 0, 1, 0);
395   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
396   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
397   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
398   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
399   tab_dim (t, tab_natural_dimensions);
400   row = 1;
401   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
402     {
403       char fmt_string[FMT_STRING_LEN_MAX + 1];
404       int width;
405       switch (spec->type)
406         {
407         case PRT_LITERAL:
408           tab_text (t, 0, row, TAB_LEFT | TAB_FIX | TAT_PRINTF, "\"%.*s\"",
409                     (int) ds_length (&spec->string), ds_data (&spec->string));
410           width = ds_length (&spec->string);
411           break;
412         case PRT_VAR:
413           tab_text (t, 0, row, TAB_LEFT, var_get_name (spec->var));
414           tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
415                     fmt_to_string (&spec->format, fmt_string));
416           width = spec->format.w;
417           break;
418         default:
419           NOT_REACHED ();
420         }
421       tab_text (t, 1, row, TAT_PRINTF, "%d", spec->record);
422       tab_text (t, 2, row, TAT_PRINTF, "%3d-%3d",
423                 spec->first_column, spec->first_column + width - 1);
424       row++;
425     }
426
427   if (fh != NULL)
428     tab_title (t, ngettext ("Writing %d record to %s.",
429                             "Writing %d records to %s.", trns->record_cnt),
430                trns->record_cnt, fh_get_name (fh));
431   else
432     tab_title (t, ngettext ("Writing %d record.",
433                             "Writing %d records.", trns->record_cnt),
434                trns->record_cnt);
435   tab_submit (t);
436 }
437 \f
438 /* Transformation. */
439
440 static void flush_records (struct print_trns *, int target_record,
441                            bool *eject, int *record);
442
443 /* Performs the transformation inside print_trns T on case C. */
444 static int
445 print_trns_proc (void *trns_, struct ccase *c, casenumber case_num UNUSED)
446 {
447   struct print_trns *trns = trns_;
448   bool eject = trns->eject;
449   int record = 1;
450   struct prt_out_spec *spec;
451
452   ds_clear (&trns->line);
453   ds_put_char (&trns->line, ' ');
454   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
455     {
456       flush_records (trns, spec->record, &eject, &record);
457
458       ds_set_length (&trns->line, spec->first_column, ' ');
459       if (spec->type == PRT_VAR)
460         {
461           const union value *input = case_data (c, spec->var);
462           char *output = ds_put_uninit (&trns->line, spec->format.w);
463           if (!spec->sysmis_as_spaces || input->f != SYSMIS)
464             data_out (input, &spec->format, output);
465           else
466             memset (output, ' ', spec->format.w);
467           if (spec->add_space)
468             ds_put_char (&trns->line, ' ');
469         }
470       else
471         ds_put_substring (&trns->line, ds_ss (&spec->string));
472     }
473   flush_records (trns, trns->record_cnt + 1, &eject, &record);
474
475   if (trns->writer != NULL && dfm_write_error (trns->writer))
476     return TRNS_ERROR;
477   return TRNS_CONTINUE;
478 }
479
480 /* Advance from *RECORD to TARGET_RECORD, outputting records
481    along the way.  If *EJECT is true, then the first record
482    output is preceded by ejecting the page (and *EJECT is set
483    false). */
484 static void
485 flush_records (struct print_trns *trns, int target_record,
486                bool *eject, int *record)
487 {
488   for (; target_record > *record; (*record)++)
489     {
490       char *line = ds_cstr (&trns->line);
491       size_t length = ds_length (&trns->line);
492       char leader = ' ';
493
494       if (*eject)
495         {
496           *eject = false;
497           if (trns->writer == NULL)
498             som_eject_page ();
499           else
500             leader = '1';
501         }
502       line[0] = leader;
503
504       if (trns->writer == NULL)
505         tab_output_text (TAB_FIX | TAT_NOWRAP, &line[1]);
506       else
507         {
508           if (!trns->include_prefix)
509             {
510               line++;
511               length--;
512             }
513           dfm_put_record (trns->writer, line, length);
514         }
515
516       ds_truncate (&trns->line, 1);
517     }
518 }
519
520 /* Frees TRNS. */
521 static bool
522 print_trns_free (void *trns_)
523 {
524   struct print_trns *trns = trns_;
525   bool ok = true;
526
527   if (trns->writer != NULL)
528     ok = dfm_close_writer (trns->writer);
529   pool_destroy (trns->pool);
530
531   return ok;
532 }
533