1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
5 This program is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 This program is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 /* FIXME: seems like a lot of code duplication with data-list.c. */
23 #include <libpspp/message.h>
25 #include <libpspp/alloc.h>
26 #include <data/case.h>
27 #include <language/command.h>
28 #include <libpspp/compiler.h>
29 #include <language/data-io/data-writer.h>
30 #include <libpspp/message.h>
31 #include <language/expressions/public.h>
32 #include <language/data-io/file-handle.h>
33 #include <language/lexer/lexer.h>
34 #include <libpspp/misc.h>
35 #include <output/manager.h>
36 #include <output/table.h>
37 #include <data/variable.h>
40 #define _(msgid) gettext (msgid)
42 /* Describes what to do when an output field is encountered. */
45 PRT_ERROR, /* Invalid value. */
46 PRT_NEWLINE, /* Newline. */
47 PRT_CONST, /* Constant string. */
48 PRT_VAR, /* Variable. */
49 PRT_SPACE /* A single space. */
52 /* Describes how to output one field. */
55 struct prt_out_spec *next;
56 int type; /* PRT_* constant. */
57 int fc; /* 0-based first column. */
60 char *c; /* PRT_CONST: Associated string. */
63 struct variable *v; /* PRT_VAR: Associated variable. */
64 struct fmt_spec f; /* PRT_VAR: Output spec. */
71 /* Enums for use with print_trns's `options' field. */
74 PRT_CMD_MASK = 1, /* Command type mask. */
75 PRT_PRINT = 0, /* PRINT transformation identifier. */
76 PRT_WRITE = 1, /* WRITE transformation identifier. */
77 PRT_EJECT = 002, /* Can be combined with CMD_PRINT only. */
78 PRT_BINARY = 004 /* File is binary, omit newlines. */
81 /* PRINT, PRINT EJECT, WRITE private data structure. */
84 struct dfm_writer *writer; /* Output file, NULL=listing file. */
85 int options; /* PRT_* bitmapped field. */
86 struct prt_out_spec *spec; /* Output specifications. */
87 int max_width; /* Maximum line width including null. */
88 char *line; /* Buffer for sticking lines in. */
91 /* PRT_PRINT or PRT_WRITE. */
94 /* Holds information on parsing the data file. */
95 static struct print_trns prt;
97 /* Last prt_out_spec in the chain. Used for building the linked-list. */
98 static struct prt_out_spec *next;
100 /* Number of records. */
103 static int internal_cmd_print (int flags);
104 static trns_proc_func print_trns_proc;
105 static trns_free_func print_trns_free;
106 static int parse_specs (void);
107 static void dump_table (const struct file_handle *);
108 static void append_var_spec (struct prt_out_spec *);
109 static void alloc_line (void);
113 /* Parses PRINT command. */
117 return internal_cmd_print (PRT_PRINT);
120 /* Parses PRINT EJECT command. */
122 cmd_print_eject (void)
124 return internal_cmd_print (PRT_PRINT | PRT_EJECT);
127 /* Parses WRITE command. */
131 return internal_cmd_print (PRT_WRITE);
134 /* Parses the output commands. F is PRT_PRINT, PRT_WRITE, or
135 PRT_PRINT|PRT_EJECT. */
137 internal_cmd_print (int f)
139 int table = 0; /* Print table? */
140 struct print_trns *trns; /* malloc()'d transformation. */
141 struct file_handle *fh = NULL;
143 /* Fill in prt to facilitate error-handling. */
151 which_cmd = f & PRT_CMD_MASK;
153 /* Parse the command options. */
154 while (!lex_match ('/'))
156 if (lex_match_id ("OUTFILE"))
160 fh = fh_parse (FH_REF_FILE);
164 else if (lex_match_id ("RECORDS"))
168 if (!lex_force_int ())
170 nrec = lex_integer ();
174 else if (lex_match_id ("TABLE"))
176 else if (lex_match_id ("NOTABLE"))
180 lex_error (_("expecting a valid subcommand"));
185 /* Parse variables and strings. */
191 prt.writer = dfm_open_writer (fh);
192 if (prt.writer == NULL)
195 if (fh_get_mode (fh) == FH_MODE_BINARY)
196 prt.options |= PRT_BINARY;
199 /* Output the variable table if requested. */
203 /* Count the maximum line width. Allocate linebuffer if
207 /* Put the transformation in the queue. */
208 trns = xmalloc (sizeof *trns);
209 memcpy (trns, &prt, sizeof *trns);
210 add_transformation (print_trns_proc, print_trns_free, trns);
215 print_trns_free (&prt);
219 /* Appends the field output specification SPEC to the list maintained
222 append_var_spec (struct prt_out_spec *spec)
225 prt.spec = next = xmalloc (sizeof *spec);
227 next = next->next = xmalloc (sizeof *spec);
229 memcpy (next, spec, sizeof *spec);
233 /* Field parsing. Mostly stolen from data-list.c. */
235 /* Used for chaining together fortran-like format specifiers. */
238 struct fmt_list *next;
241 struct fmt_list *down;
244 /* Used as "local" variables among the fixed-format parsing funcs. If
245 it were guaranteed that PSPP were going to be compiled by gcc,
246 I'd make all these functions a single set of nested functions. */
249 struct variable **v; /* variable list */
250 size_t nv; /* number of variables in list */
251 size_t cv; /* number of variables from list used up so far
252 by the FORTRAN-like format specifiers */
254 int recno; /* current 1-based record number */
255 int sc; /* 1-based starting column for next variable */
257 struct prt_out_spec spec; /* next format spec to append to list */
258 int fc, lc; /* first, last 1-based column number of current
261 int level; /* recursion level for FORTRAN-like format
266 static int fixed_parse_compatible (void);
267 static struct fmt_list *fixed_parse_fortran (void);
269 static int parse_string_argument (void);
270 static int parse_variable_argument (void);
272 /* Parses all the variable and string specifications on a single
273 PRINT, PRINT EJECT, or WRITE command into the prt structure.
278 /* Return code from called function. */
286 while (lex_match ('/'))
288 int prev_recno = fx.recno;
291 if (lex_is_number ())
293 if (!lex_force_int ())
295 if (lex_integer () < fx.recno)
297 msg (SE, _("The record number specified, %ld, is "
298 "before the previous record, %d. Data "
299 "fields must be listed in order of "
300 "increasing record number."),
301 lex_integer (), fx.recno - 1);
304 fx.recno = lex_integer ();
308 fx.spec.type = PRT_NEWLINE;
309 while (prev_recno++ < fx.recno)
310 append_var_spec (&fx.spec);
315 if (token == T_STRING)
316 code = parse_string_argument ();
318 code = parse_variable_argument ();
322 fx.spec.type = PRT_NEWLINE;
323 append_var_spec (&fx.spec);
327 else if (fx.recno > nrec)
329 msg (SE, _("Variables are specified on records that "
330 "should not exist according to RECORDS subcommand."));
336 lex_error (_("expecting end of command"));
343 /* Parses a string argument to the PRINT commands. Returns success. */
345 parse_string_argument (void)
347 fx.spec.type = PRT_CONST;
348 fx.spec.fc = fx.sc - 1;
349 fx.spec.u.c = xstrdup (ds_c_str (&tokstr));
352 /* Parse the included column range. */
353 if (lex_is_number ())
355 /* Width of column range in characters. */
358 /* Width of constant string in characters. */
361 /* 1-based index of last column in range. */
364 if (!lex_is_integer () || lex_integer () <= 0)
366 msg (SE, _("%g is not a valid column location."), tokval);
369 fx.spec.fc = lex_integer () - 1;
372 lex_negative_to_dash ();
375 if (!lex_is_integer ())
377 msg (SE, _("Column location expected following `%d-'."),
381 if (lex_integer () <= 0)
383 msg (SE, _("%g is not a valid column location."), tokval);
386 if (lex_integer () < fx.spec.fc + 1)
388 msg (SE, _("%d-%ld is not a valid column range. The second "
389 "column must be greater than or equal to the first."),
390 fx.spec.fc + 1, lex_integer ());
393 lc = lex_integer () - 1;
398 /* If only a starting location is specified then the field is
399 the width of the provided string. */
400 lc = fx.spec.fc + strlen (fx.spec.u.c) - 1;
402 /* Apply the range. */
403 c_len = lc - fx.spec.fc + 1;
404 s_len = strlen (fx.spec.u.c);
406 fx.spec.u.c[c_len] = 0;
407 else if (s_len < c_len)
409 fx.spec.u.c = xrealloc (fx.spec.u.c, c_len + 1);
410 memset (&fx.spec.u.c[s_len], ' ', c_len - s_len);
411 fx.spec.u.c[c_len] = 0;
417 /* If nothing is provided then the field is the width of the
419 fx.sc += strlen (fx.spec.u.c);
421 append_var_spec (&fx.spec);
429 /* Parses a variable argument to the PRINT commands by passing it off
430 to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
433 parse_variable_argument (void)
435 if (!parse_variables (default_dict, &fx.v, &fx.nv, PV_DUPLICATE))
438 if (lex_is_number ())
440 if (!fixed_parse_compatible ())
443 else if (token == '(')
447 if (!fixed_parse_fortran ())
452 /* User wants dictionary format specifiers. */
456 for (i = 0; i < fx.nv; i++)
459 fx.spec.type = PRT_VAR;
460 fx.spec.fc = fx.sc - 1;
461 fx.spec.u.v.v = fx.v[i];
462 fx.spec.u.v.f = fx.v[i]->print;
463 append_var_spec (&fx.spec);
464 fx.sc += fx.v[i]->print.w;
467 fx.spec.type = PRT_SPACE;
468 fx.spec.fc = fx.sc - 1;
469 append_var_spec (&fx.spec);
482 /* Verifies that FORMAT doesn't need a variable wider than WIDTH.
483 Returns true iff that is the case. */
485 check_string_width (const struct fmt_spec *format, const struct variable *v)
487 if (get_format_var_width (format) > v->width)
489 msg (SE, _("Variable %s has width %d so it cannot be output "
491 v->name, v->width, fmt_to_string (format));
497 /* Parses a column specification for parse_specs(). */
499 fixed_parse_compatible (void)
501 int individual_var_width;
505 type = fx.v[0]->type;
506 for (i = 1; i < fx.nv; i++)
507 if (type != fx.v[i]->type)
509 msg (SE, _("%s is not of the same type as %s. To specify "
510 "variables of different types in the same variable "
511 "list, use a FORTRAN-like format specifier."),
512 fx.v[i]->name, fx.v[0]->name);
516 if (!lex_force_int ())
518 fx.fc = lex_integer () - 1;
521 msg (SE, _("Column positions for fields must be positive."));
526 lex_negative_to_dash ();
529 if (!lex_force_int ())
531 fx.lc = lex_integer () - 1;
534 msg (SE, _("Column positions for fields must be positive."));
537 else if (fx.lc < fx.fc)
539 msg (SE, _("The ending column for a field must not "
540 "be less than the starting column."));
548 fx.spec.u.v.f.w = fx.lc - fx.fc + 1;
551 struct fmt_desc *fdp;
557 fx.spec.u.v.f.type = parse_format_specifier_name (&cp, 0);
558 if (fx.spec.u.v.f.type == -1)
562 msg (SE, _("A format specifier on this line "
563 "has extra characters on the end."));
570 fx.spec.u.v.f.type = FMT_F;
572 if (lex_is_number ())
574 if (!lex_force_int ())
576 if (lex_integer () < 1)
578 msg (SE, _("The value for number of decimal places "
579 "must be at least 1."));
582 fx.spec.u.v.f.d = lex_integer ();
588 fdp = &formats[fx.spec.u.v.f.type];
589 if (fdp->n_args < 2 && fx.spec.u.v.f.d)
591 msg (SE, _("Input format %s doesn't accept decimal places."),
595 if (fx.spec.u.v.f.d > 16)
596 fx.spec.u.v.f.d = 16;
598 if (!lex_force_match (')'))
603 fx.spec.u.v.f.type = FMT_F;
609 if ((fx.lc - fx.fc + 1) % fx.nv)
611 msg (SE, _("The %d columns %d-%d can't be evenly divided into %u "
613 fx.lc - fx.fc + 1, fx.fc + 1, fx.lc + 1, (unsigned) fx.nv);
617 individual_var_width = (fx.lc - fx.fc + 1) / fx.nv;
618 fx.spec.u.v.f.w = individual_var_width;
619 if (!check_output_specifier (&fx.spec.u.v.f, true)
620 || !check_specifier_type (&fx.spec.u.v.f, type, true))
624 for (i = 0; i < fx.nv; i++)
625 if (!check_string_width (&fx.spec.u.v.f, fx.v[i]))
629 fx.spec.type = PRT_VAR;
630 for (i = 0; i < fx.nv; i++)
632 fx.spec.fc = fx.fc + individual_var_width * i;
633 fx.spec.u.v.v = fx.v[i];
634 append_var_spec (&fx.spec);
639 /* Destroy a format list and, optionally, all its sublists. */
641 destroy_fmt_list (struct fmt_list *f, int recurse)
643 struct fmt_list *next;
648 if (recurse && f->f.type == FMT_DESCEND)
649 destroy_fmt_list (f->down, 1);
654 /* Recursively puts the format list F (which represents a set of
655 FORTRAN-like format specifications, like 4(F10,2X)) into the
658 dump_fmt_list (struct fmt_list *f)
662 for (; f; f = f->next)
663 if (f->f.type == FMT_X)
665 else if (f->f.type == FMT_T)
667 else if (f->f.type == FMT_NEWREC)
669 fx.recno += f->count;
671 fx.spec.type = PRT_NEWLINE;
672 for (i = 0; i < f->count; i++)
673 append_var_spec (&fx.spec);
676 for (i = 0; i < f->count; i++)
677 if (f->f.type == FMT_DESCEND)
679 if (!dump_fmt_list (f->down))
688 msg (SE, _("The number of format "
689 "specifications exceeds the number of variable "
695 if (!check_output_specifier (&f->f, true)
696 || !check_specifier_type (&f->f, v->type, true)
697 || !check_string_width (&f->f, v))
700 fx.spec.type = PRT_VAR;
702 fx.spec.u.v.f = f->f;
703 fx.spec.fc = fx.sc - 1;
704 append_var_spec (&fx.spec);
711 /* Recursively parses a list of FORTRAN-like format specifiers. Calls
712 itself to parse nested levels of parentheses. Returns to its
713 original caller NULL, to indicate error, non-NULL, but nothing
714 useful, to indicate success (it returns a free()'d block). */
715 static struct fmt_list *
716 fixed_parse_fortran (void)
718 struct fmt_list *head = NULL;
719 struct fmt_list *fl = NULL;
721 lex_get (); /* skip opening parenthesis */
725 fl = fl->next = xmalloc (sizeof *fl);
727 head = fl = xmalloc (sizeof *fl);
729 if (lex_is_number ())
731 if (!lex_is_integer ())
733 fl->count = lex_integer ();
741 fl->f.type = FMT_DESCEND;
743 fl->down = fixed_parse_fortran ();
748 else if (lex_match ('/'))
749 fl->f.type = FMT_NEWREC;
750 else if (!parse_format_specifier (&fl->f, FMTP_ALLOW_XT)
751 || !check_output_specifier (&fl->f, 1))
763 dump_fmt_list (head);
764 destroy_fmt_list (head, 1);
767 msg (SE, _("There aren't enough format specifications "
768 "to match the number of variable names given."));
775 destroy_fmt_list (head, 0);
780 /* Prints the table produced by the TABLE subcommand to the listing
783 dump_table (const struct file_handle *fh)
785 struct prt_out_spec *spec;
790 for (nspec = 0, spec = prt.spec; spec; spec = spec->next)
791 if (spec->type == PRT_CONST || spec->type == PRT_VAR)
793 t = tab_create (4, nspec + 1, 0);
794 tab_columns (t, TAB_COL_DOWN, 1);
795 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, nspec);
796 tab_hline (t, TAL_2, 0, 3, 1);
797 tab_headers (t, 0, 0, 1, 0);
798 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
799 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
800 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
801 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
802 tab_dim (t, tab_natural_dimensions);
803 for (nspec = recno = 0, spec = prt.spec; spec; spec = spec->next)
811 int len = strlen (spec->u.c);
813 tab_text (t, 0, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
814 "\"%s\"", spec->u.c);
815 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
816 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
817 spec->fc + 1, spec->fc + len);
818 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
825 tab_text (t, 0, nspec, TAB_LEFT, spec->u.v.v->name);
826 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
827 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
828 spec->fc + 1, spec->fc + spec->u.v.f.w);
829 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX,
830 fmt_to_string (&spec->u.v.f));
840 tab_title (t, ngettext ("Writing %d record to %s.",
841 "Writing %d records to %s.", recno),
842 recno, fh_get_name (fh));
844 tab_title (t, ngettext ("Writing %d record.",
845 "Writing %d records.", recno), recno);
849 /* Calculates the maximum possible line width and allocates a buffer
850 big enough to contain it */
854 /* Cumulative maximum line width (excluding null terminator) so far. */
857 /* Width required by current this prt_out_spec. */
858 int pot_w; /* Potential w. */
861 struct prt_out_spec *i;
863 for (i = prt.spec; i; i = i->next)
871 pot_w = i->fc + strlen (i->u.c);
874 pot_w = i->fc + i->u.v.f.w;
887 prt.max_width = w + 2;
888 prt.line = xmalloc (prt.max_width);
891 /* Transformation. */
893 /* Performs the transformation inside print_trns T on case C. */
895 print_trns_proc (void *trns_, struct ccase *c, int case_num UNUSED)
897 /* Transformation. */
898 struct print_trns *t = trns_;
901 struct prt_out_spec *i;
906 /* Length of the line in buf. */
908 memset (buf, ' ', t->max_width);
910 if (t->options & PRT_EJECT)
913 /* Note that a field written to a place where a field has
914 already been written truncates the record. `PRINT /A B
915 (T10,F8,T1,F8).' only outputs B. */
916 for (i = t->spec; i; i = i->next)
920 if (t->writer == NULL)
923 tab_output_text (TAB_FIX | TAT_NOWRAP, buf);
927 if ((t->options & PRT_CMD_MASK) == PRT_PRINT
928 || !(t->options & PRT_BINARY))
931 dfm_put_record (t->writer, buf, len);
934 memset (buf, ' ', t->max_width);
939 /* FIXME: Should be revised to keep track of the string's
940 length outside the loop, probably in i->u.c[0]. */
941 memcpy (&buf[i->fc], i->u.c, strlen (i->u.c));
942 len = i->fc + strlen (i->u.c);
946 data_out (&buf[i->fc], &i->u.v.f, case_data (c, i->u.v.v->fv));
947 len = i->fc + i->u.v.f.w;
951 /* PRT_SPACE always immediately follows PRT_VAR. */
960 if (t->writer != NULL && dfm_write_error (t->writer))
962 return TRNS_CONTINUE;
965 /* Frees all the data inside print_trns T. Does not free T. */
967 print_trns_free (void *prt_)
969 struct print_trns *prt = prt_;
970 struct prt_out_spec *i, *n;
973 for (i = prt->spec; i; i = n)
992 if (prt->writer != NULL)
993 ok = dfm_close_writer (prt->writer);
1001 /* PRINT SPACE transformation. */
1002 struct print_space_trns
1004 struct dfm_writer *writer; /* Output data file. */
1005 struct expression *e; /* Number of lines; NULL=1. */
1009 static trns_proc_func print_space_trns_proc;
1010 static trns_free_func print_space_trns_free;
1013 cmd_print_space (void)
1015 struct print_space_trns *t;
1016 struct file_handle *fh;
1017 struct expression *e;
1018 struct dfm_writer *writer;
1020 if (lex_match_id ("OUTFILE"))
1024 fh = fh_parse (FH_REF_FILE);
1034 e = expr_parse (default_dict, EXPR_NUMBER);
1038 lex_error (_("expecting end of command"));
1047 writer = dfm_open_writer (fh);
1057 t = xmalloc (sizeof *t);
1061 add_transformation (print_space_trns_proc, print_space_trns_free, t);
1065 /* Executes a PRINT SPACE transformation. */
1067 print_space_trns_proc (void *t_, struct ccase *c,
1068 int case_num UNUSED)
1070 struct print_space_trns *t = t_;
1076 double f = expr_evaluate_num (t->e, c, case_num);
1078 msg (SW, _("The expression on PRINT SPACE evaluated to the "
1079 "system-missing value."));
1080 else if (f < 0 || f > INT_MAX)
1081 msg (SW, _("The expression on PRINT SPACE evaluated to %g."), f);
1087 if (t->writer == NULL)
1090 dfm_put_record (t->writer, "\n", 1);
1092 if (t->writer != NULL && dfm_write_error (t->writer))
1094 return TRNS_CONTINUE;
1097 /* Frees a PRINT SPACE transformation.
1098 Returns true if successful, false if an I/O error occurred. */
1100 print_space_trns_free (void *trns_)
1102 struct print_space_trns *trns = trns_;
1103 bool ok = dfm_close_writer (trns->writer);
1104 expr_free (trns->e);