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