work on PRINT encoding
[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     PRT_ADVANCE,                /* Skip forward N positions. */
55     PRT_GOTO,                   /* Go to absolute position N. */
56     PRT_NEWLINE,                /* Output the constructed line. */
57     PRT_EJECT                   /* Eject the output page. */
58   };
59
60 /* Describes how to output one field. */
61 struct prt_out_spec
62   {
63     /* All fields. */
64     struct ll ll;               /* In struct print_trns `specs' list. */
65     enum field_type type;       /* What type of field this is. */
66     int first_column;           /* 0-based first column. */
67
68     /* PRT_VAR only. */
69     const struct variable *var; /* Associated variable. */
70     struct fmt_spec format;     /* Output spec. */
71     bool sysmis_as_spaces;      /* Output SYSMIS as spaces? */
72
73     /* PRT_LITERAL only. */
74     struct string string;       /* String to output. */
75   };
76
77 static inline struct prt_out_spec *
78 ll_to_prt_out_spec (struct ll *ll)
79 {
80   return ll_data (ll, struct prt_out_spec, ll);
81 }
82
83 /* PRINT, PRINT EJECT, WRITE private data structure. */
84 struct print_trns
85   {
86     struct pool *pool;          /* Stores related data. */
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     struct u8_line line;        /* Output buffer. */
91
92     int unit;                   /* Unit width, in bytes. */
93     char one[MAX_UNIT];         /* '1' in encoding, 'unit' bytes long. */
94     char space[MAX_UNIT];       /* \n in encoding, 'unit' bytes long. */
95   };
96
97 enum which_formats
98   {
99     PRINT,
100     WRITE
101   };
102
103 static int internal_cmd_print (struct lexer *, struct dataset *ds,
104                                enum which_formats, bool eject);
105 static trns_proc_func print_trns_proc;
106 static trns_free_func print_trns_free;
107 static bool parse_specs (struct lexer *, struct pool *tmp_pool, struct print_trns *,
108                          struct dictionary *dict, enum which_formats);
109 static void dump_table (struct print_trns *, const struct file_handle *);
110 \f
111 /* Basic parsing. */
112
113 /* Parses PRINT command. */
114 int
115 cmd_print (struct lexer *lexer, struct dataset *ds)
116 {
117   return internal_cmd_print (lexer, ds, PRINT, false);
118 }
119
120 /* Parses PRINT EJECT command. */
121 int
122 cmd_print_eject (struct lexer *lexer, struct dataset *ds)
123 {
124   return internal_cmd_print (lexer, ds, PRINT, true);
125 }
126
127 /* Parses WRITE command. */
128 int
129 cmd_write (struct lexer *lexer, struct dataset *ds)
130 {
131   return internal_cmd_print (lexer, ds, WRITE, false);
132 }
133
134 /* Parses the output commands. */
135 static int
136 internal_cmd_print (struct lexer *lexer, struct dataset *ds,
137                     enum which_formats which_formats, bool eject)
138 {
139   bool print_table = 0;
140   struct print_trns *trns;
141   struct file_handle *fh = NULL;
142   char *encoding = NULL;
143   struct pool *tmp_pool;
144   int record_cnt = 0;
145
146   /* Fill in prt to facilitate error-handling. */
147   trns = pool_create_container (struct print_trns, pool);
148   trns->eject = eject;
149   trns->writer = NULL;
150   ll_init (&trns->specs);
151   u8_line_init (&trns->line);
152   u8_line_register_pool (&trns->line, trns->pool);
153
154   tmp_pool = pool_create_subpool (trns->pool);
155
156   /* Parse the command options. */
157   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
158     {
159       if (lex_match_id (lexer, "OUTFILE"))
160         {
161           lex_match (lexer, T_EQUALS);
162
163           fh = fh_parse (lexer, FH_REF_FILE, NULL);
164           if (fh == NULL)
165             goto error;
166         }
167       else if (lex_match_id (lexer, "ENCODING"))
168         {
169           lex_match (lexer, T_EQUALS);
170           if (!lex_force_string (lexer))
171             goto error;
172
173           free (encoding);
174           encoding = ss_xstrdup (lex_tokss (lexer));
175
176           lex_get (lexer);
177         }
178       else if (lex_match_id (lexer, "RECORDS"))
179         {
180           lex_match (lexer, T_EQUALS);
181           lex_match (lexer, T_LPAREN);
182           if (!lex_force_int (lexer))
183             goto error;
184           record_cnt = lex_integer (lexer);
185           lex_get (lexer);
186           lex_match (lexer, T_RPAREN);
187         }
188       else if (lex_match_id (lexer, "TABLE"))
189         print_table = true;
190       else if (lex_match_id (lexer, "NOTABLE"))
191         print_table = false;
192       else
193         {
194           lex_error (lexer, _("expecting a valid subcommand"));
195           goto error;
196         }
197     }
198
199   /* Parse variables and strings. */
200   if (!parse_specs (lexer, tmp_pool, trns, dataset_dict (ds), which_formats))
201     goto error;
202
203   if (lex_end_of_command (lexer) != CMD_SUCCESS)
204     goto error;
205
206   if (fh != NULL)
207     {
208       trns->writer = dfm_open_writer (fh, encoding);
209       if (trns->writer == NULL)
210         goto error;
211       trns->encoding = dfm_writer_get_encoding (trns->writer);
212     }
213   else
214     trns->encoding = UTF8;
215
216   /* Output the variable table if requested. */
217   if (print_table)
218     dump_table (trns, fh);
219
220   /* Put the transformation in the queue. */
221   add_transformation (ds, print_trns_proc, print_trns_free, trns);
222
223   pool_destroy (tmp_pool);
224   fh_unref (fh);
225
226   return CMD_SUCCESS;
227
228  error:
229   print_trns_free (trns);
230   fh_unref (fh);
231   return CMD_FAILURE;
232 }
233 \f
234 static bool parse_string_argument (struct lexer *, struct print_trns *,
235                                    int record, int *column);
236 static bool parse_variable_argument (struct lexer *, const struct dictionary *,
237                                      struct print_trns *,
238                                      struct pool *tmp_pool,
239                                      int *record, int *column,
240                                      enum which_formats);
241
242 /* Parses all the variable and string specifications on a single
243    PRINT, PRINT EJECT, or WRITE command into the prt structure.
244    Returns success. */
245 static bool
246 parse_specs (struct lexer *lexer, struct pool *tmp_pool, struct print_trns *trns,
247              struct dictionary *dict,
248              enum which_formats which_formats)
249 {
250   int record = 0;
251   int column = 1;
252
253   if (lex_token (lexer) == T_ENDCMD)
254     {
255       trns->record_cnt = 1;
256       return true;
257     }
258
259   while (lex_token (lexer) != T_ENDCMD)
260     {
261       bool ok;
262
263       if (!parse_record_placement (lexer, &record, &column))
264         return false;
265
266       if (lex_is_string (lexer))
267         ok = parse_string_argument (lexer, trns, record, &column);
268       else
269         ok = parse_variable_argument (lexer, dict, trns, tmp_pool, &record, &column,
270                                       which_formats);
271       if (!ok)
272         return 0;
273
274       lex_match (lexer, T_COMMA);
275     }
276
277   if (trns->record_cnt != 0 && trns->record_cnt != record)
278     msg (SW, _("Output calls for %d records but %zu specified on RECORDS "
279                "subcommand."),
280          record, trns->record_cnt);
281   trns->record_cnt = record;
282
283   return true;
284 }
285
286 /* Parses a string argument to the PRINT commands.  Returns success. */
287 static bool
288 parse_string_argument (struct lexer *lexer, struct print_trns *trns, int record, int *column)
289 {
290   struct prt_out_spec *spec = pool_alloc (trns->pool, sizeof *spec);
291   spec->type = PRT_LITERAL;
292   spec->record = record;
293   spec->first_column = *column;
294   ds_init_substring (&spec->string, lex_tokss (lexer));
295   ds_register_pool (&spec->string, trns->pool);
296   lex_get (lexer);
297
298   /* Parse the included column range. */
299   if (lex_is_number (lexer))
300     {
301       int first_column, last_column;
302       bool range_specified;
303
304       if (!parse_column_range (lexer, 1,
305                                &first_column, &last_column, &range_specified))
306         return false;
307
308       spec->first_column = first_column;
309       if (range_specified)
310         ds_set_length (&spec->string, last_column - first_column + 1, ' ');
311     }
312   *column = spec->first_column + ds_length (&spec->string);
313
314   ll_push_tail (&trns->specs, &spec->ll);
315   return true;
316 }
317
318 /* Parses a variable argument to the PRINT commands by passing it off
319    to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
320    Returns success. */
321 static bool
322 parse_variable_argument (struct lexer *lexer, const struct dictionary *dict,
323                          struct print_trns *trns, struct pool *tmp_pool,
324                          int *record, int *column,
325                          enum which_formats which_formats)
326 {
327   const struct variable **vars;
328   size_t var_cnt, var_idx;
329   struct fmt_spec *formats, *f;
330   size_t format_cnt;
331   bool add_space;
332
333   if (!parse_variables_const_pool (lexer, tmp_pool, dict,
334                              &vars, &var_cnt, PV_DUPLICATE))
335     return false;
336
337   if (lex_is_number (lexer) || lex_token (lexer) == T_LPAREN)
338     {
339       if (!parse_var_placements (lexer, tmp_pool, var_cnt, FMT_FOR_OUTPUT,
340                                  &formats, &format_cnt))
341         return false;
342       add_space = false;
343     }
344   else
345     {
346       size_t i;
347
348       lex_match (lexer, T_ASTERISK);
349
350       formats = pool_nmalloc (tmp_pool, var_cnt, sizeof *formats);
351       format_cnt = var_cnt;
352       for (i = 0; i < var_cnt; i++)
353         {
354           const struct variable *v = vars[i];
355           formats[i] = (which_formats == PRINT
356                         ? *var_get_print_format (v)
357                         : *var_get_write_format (v));
358         }
359       add_space = which_formats == PRINT;
360     }
361
362   var_idx = 0;
363   for (f = formats; f < &formats[format_cnt]; f++)
364     if (!execute_placement_format (f, record, column))
365       {
366         const struct variable *var;
367         struct prt_out_spec *spec;
368
369         var = vars[var_idx++];
370         if (!fmt_check_width_compat (f, var_get_width (var)))
371           return false;
372
373         spec = pool_alloc (trns->pool, sizeof *spec);
374         spec->type = PRT_VAR;
375         spec->record = *record;
376         spec->first_column = *column;
377         spec->var = var;
378         spec->format = *f;
379         spec->add_space = add_space;
380
381         /* This is a completely bizarre twist for compatibility:
382            WRITE outputs the system-missing value as a field
383            filled with spaces, instead of using the normal format
384            that usually contains a period. */
385         spec->sysmis_as_spaces = (which_formats == WRITE
386                                   && var_is_numeric (var)
387                                   && (fmt_get_category (spec->format.type)
388                                       != FMT_CAT_BINARY));
389
390         ll_push_tail (&trns->specs, &spec->ll);
391
392         *column += f->w + add_space;
393       }
394   assert (var_idx == var_cnt);
395
396   return true;
397 }
398
399 /* Prints the table produced by the TABLE subcommand to the listing
400    file. */
401 static void
402 dump_table (struct print_trns *trns, const struct file_handle *fh)
403 {
404   struct prt_out_spec *spec;
405   struct tab_table *t;
406   int spec_cnt;
407   int row;
408
409   spec_cnt = ll_count (&trns->specs);
410   t = tab_create (4, spec_cnt + 1);
411   tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, spec_cnt);
412   tab_hline (t, TAL_2, 0, 3, 1);
413   tab_headers (t, 0, 0, 1, 0);
414   tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
415   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
416   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
417   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
418   row = 1;
419   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
420     {
421       char fmt_string[FMT_STRING_LEN_MAX + 1];
422       int width;
423       switch (spec->type)
424         {
425         case PRT_LITERAL:
426           tab_text_format (t, 0, row, TAB_LEFT | TAB_FIX, "`%.*s'",
427                            (int) ds_length (&spec->string),
428                            ds_data (&spec->string));
429           width = ds_length (&spec->string);
430           break;
431         case PRT_VAR:
432           tab_text (t, 0, row, TAB_LEFT, var_get_name (spec->var));
433           tab_text (t, 3, row, TAB_LEFT | TAB_FIX,
434                     fmt_to_string (&spec->format, fmt_string));
435           width = spec->format.w;
436           break;
437         default:
438           NOT_REACHED ();
439         }
440       tab_text_format (t, 1, row, 0, "%d", spec->record);
441       tab_text_format (t, 2, row, 0, "%3d-%3d",
442                        spec->first_column, spec->first_column + width - 1);
443       row++;
444     }
445
446   if (fh != NULL)
447     tab_title (t, ngettext ("Writing %zu record to %s.",
448                             "Writing %zu records to %s.", trns->record_cnt),
449                trns->record_cnt, fh_get_name (fh));
450   else
451     tab_title (t, ngettext ("Writing %zu record.",
452                             "Writing %zu records.", trns->record_cnt),
453                trns->record_cnt);
454   tab_submit (t);
455 }
456 \f
457 /* Transformation. */
458
459 static void
460 print_literal (struct print_trns *trns, const struct prt_out_spec *spec)
461 {
462   const char *s = ds_data (&spec->string);
463   int n = ds_length (&spec->string);
464   int width = u8_width (s, n, UTF8);
465
466   u8_line_put (&trns->line, x0, x0 + width, s, n);
467 }
468
469 static void
470 print_var (struct print_trns *trns, const struct prt_out_spec *spec,
471            const union value *value)
472 {
473   int x0 = spec->first_column;
474
475   if (!spec->sysmis_as_spaces || input->f != SYSMIS)
476     {
477       char *s = data_out (input, var_get_encoding (spec->var), &spec->format);
478       size_t n = strlen (s);
479
480       x1 = ;
481       u8_line_put (&trns->line, x0, x1, s, n);
482       free (s);
483     }
484   else
485     {
486       x1 = x0 + spec->format.w;
487       memset (u8_line_reserve (&trns->line, x0, x1, x1 - x0),
488               ' ', x1 - x0);
489     }
490   
491
492 }
493
494 /* Performs the transformation inside print_trns T on case C. */
495 static int
496 print_trns_proc (void *trns_, struct ccase **c, casenumber case_num UNUSED)
497 {
498   struct print_trns *trns = trns_;
499   struct prt_out_spec *spec;
500
501   u8_line_clear (&trns->line);
502
503   ll_for_each (spec, struct prt_out_spec, ll, &trns->specs)
504     switch (spec->type)
505       {
506       case PRT_LITERAL:
507         print_literal (trns, spec);
508         break;
509
510       case PRT_VAR:
511         print_var (trns, spec, case_data (*c, spec->var));
512         break;
513
514       case PRT_NEWLINE:
515         if (trns->writer == NULL)
516           tab_output_text (TAB_FIX, ds_cstr (&trns->line.s));
517         else
518           dfm_put_record (trns->writer, ds_data (&trns->line.s),
519                           ds_length (&trns->line.s));
520         u8_line_clear (&trns->line);
521         break;
522
523       case PRT_EJECT:
524         text_item_submit (text_item_create (TEXT_ITEM_EJECT_PAGE, ""));
525         break;
526       }
527   
528     {
529       int x0 = spec->first_column;
530
531       if (spec->type == PRT_VAR)
532         {
533           const union value *input = ;
534           int x1;
535
536         }
537       else
538         {
539         }
540     }
541
542   if (trns->writer != NULL && dfm_write_error (trns->writer))
543     return TRNS_ERROR;
544   return TRNS_CONTINUE;
545 }
546
547 /* Advance from *RECORD to TARGET_RECORD, outputting records
548    along the way.  If *EJECT is true, then the first record
549    output is preceded by ejecting the page (and *EJECT is set
550    false). */
551 static void
552 flush_records (struct print_trns *trns, int target_record,
553                bool *eject, int *record)
554 {
555   for (; target_record > *record; (*record)++)
556     {
557       char *line = ds_cstr (&trns->line);
558       size_t length = ds_length (&trns->line);
559       char leader = ' ';
560
561       if (*eject)
562         {
563           *eject = false;
564           if (trns->writer == NULL)
565             text_item_submit (text_item_create (TEXT_ITEM_EJECT_PAGE, ""));
566           else
567             leader = '1';
568         }
569       line[0] = recode_byte (trns->encoding, C_ENCODING, leader);
570
571       if (trns->writer == NULL)
572         tab_output_text (TAB_FIX, &line[1]);
573       else
574         dfm_put_record (trns->writer, line, length);
575
576       ds_truncate (&trns->line, 1);
577     }
578 }
579
580 /* Frees TRNS. */
581 static bool
582 print_trns_free (void *trns_)
583 {
584   struct print_trns *trns = trns_;
585   bool ok = true;
586
587   if (trns->writer != NULL)
588     ok = dfm_close_writer (trns->writer);
589   pool_destroy (trns->pool);
590
591   return ok;
592 }
593