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