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