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. */
26 #include <data/case.h>
27 #include <data/procedure.h>
28 #include <data/transformations.h>
29 #include <data/variable.h>
30 #include <language/command.h>
31 #include <language/data-io/data-writer.h>
32 #include <language/data-io/file-handle.h>
33 #include <language/expressions/public.h>
34 #include <language/lexer/lexer.h>
35 #include <libpspp/alloc.h>
36 #include <libpspp/compiler.h>
37 #include <libpspp/message.h>
38 #include <libpspp/message.h>
39 #include <libpspp/misc.h>
40 #include <output/manager.h>
41 #include <output/table.h>
44 #define _(msgid) gettext (msgid)
46 /* Describes what to do when an output field is encountered. */
49 PRT_ERROR, /* Invalid value. */
50 PRT_NEWLINE, /* Newline. */
51 PRT_CONST, /* Constant string. */
52 PRT_VAR, /* Variable. */
53 PRT_SPACE /* A single space. */
56 /* Describes how to output one field. */
59 struct prt_out_spec *next;
60 int type; /* PRT_* constant. */
61 int fc; /* 0-based first column. */
64 char *c; /* PRT_CONST: Associated string. */
67 struct variable *v; /* PRT_VAR: Associated variable. */
68 struct fmt_spec f; /* PRT_VAR: Output spec. */
75 /* Enums for use with print_trns's `options' field. */
78 PRT_CMD_MASK = 1, /* Command type mask. */
79 PRT_PRINT = 0, /* PRINT transformation identifier. */
80 PRT_WRITE = 1, /* WRITE transformation identifier. */
81 PRT_EJECT = 002, /* Can be combined with CMD_PRINT only. */
82 PRT_BINARY = 004 /* File is binary, omit newlines. */
85 /* PRINT, PRINT EJECT, WRITE private data structure. */
88 struct dfm_writer *writer; /* Output file, NULL=listing file. */
89 int options; /* PRT_* bitmapped field. */
90 struct prt_out_spec *spec; /* Output specifications. */
91 int max_width; /* Maximum line width including null. */
92 char *line; /* Buffer for sticking lines in. */
95 /* PRT_PRINT or PRT_WRITE. */
98 /* Holds information on parsing the data file. */
99 static struct print_trns prt;
101 /* Last prt_out_spec in the chain. Used for building the linked-list. */
102 static struct prt_out_spec *next;
104 /* Number of records. */
107 static int internal_cmd_print (int flags);
108 static trns_proc_func print_trns_proc;
109 static trns_free_func print_trns_free;
110 static int parse_specs (void);
111 static void dump_table (const struct file_handle *);
112 static void append_var_spec (struct prt_out_spec *);
113 static void alloc_line (void);
117 /* Parses PRINT command. */
121 return internal_cmd_print (PRT_PRINT);
124 /* Parses PRINT EJECT command. */
126 cmd_print_eject (void)
128 return internal_cmd_print (PRT_PRINT | PRT_EJECT);
131 /* Parses WRITE command. */
135 return internal_cmd_print (PRT_WRITE);
138 /* Parses the output commands. F is PRT_PRINT, PRT_WRITE, or
139 PRT_PRINT|PRT_EJECT. */
141 internal_cmd_print (int f)
143 int table = 0; /* Print table? */
144 struct print_trns *trns = NULL; /* malloc()'d transformation. */
145 struct file_handle *fh = NULL;
147 /* Fill in prt to facilitate error-handling. */
155 which_cmd = f & PRT_CMD_MASK;
157 /* Parse the command options. */
158 while (!lex_match ('/'))
160 if (lex_match_id ("OUTFILE"))
164 fh = fh_parse (FH_REF_FILE);
168 else if (lex_match_id ("RECORDS"))
172 if (!lex_force_int ())
174 nrec = lex_integer ();
178 else if (lex_match_id ("TABLE"))
180 else if (lex_match_id ("NOTABLE"))
184 lex_error (_("expecting a valid subcommand"));
189 /* Parse variables and strings. */
195 prt.writer = dfm_open_writer (fh);
196 if (prt.writer == NULL)
199 if (fh_get_mode (fh) == FH_MODE_BINARY)
200 prt.options |= PRT_BINARY;
203 /* Output the variable table if requested. */
207 /* Count the maximum line width. Allocate linebuffer if
211 /* Put the transformation in the queue. */
212 trns = xmalloc (sizeof *trns);
213 memcpy (trns, &prt, sizeof *trns);
214 add_transformation (print_trns_proc, print_trns_free, trns);
219 print_trns_free (&prt);
223 /* Appends the field output specification SPEC to the list maintained
226 append_var_spec (struct prt_out_spec *spec)
229 prt.spec = next = xmalloc (sizeof *spec);
231 next = next->next = xmalloc (sizeof *spec);
233 memcpy (next, spec, sizeof *spec);
237 /* Field parsing. Mostly stolen from data-list.c. */
239 /* Used for chaining together fortran-like format specifiers. */
242 struct fmt_list *next;
245 struct fmt_list *down;
248 /* Used as "local" variables among the fixed-format parsing funcs. If
249 it were guaranteed that PSPP were going to be compiled by gcc,
250 I'd make all these functions a single set of nested functions. */
253 struct variable **v; /* variable list */
254 size_t nv; /* number of variables in list */
255 size_t cv; /* number of variables from list used up so far
256 by the FORTRAN-like format specifiers */
258 int recno; /* current 1-based record number */
259 int sc; /* 1-based starting column for next variable */
261 struct prt_out_spec spec; /* next format spec to append to list */
262 int fc, lc; /* first, last 1-based column number of current
265 int level; /* recursion level for FORTRAN-like format
270 static int fixed_parse_compatible (void);
271 static struct fmt_list *fixed_parse_fortran (void);
273 static int parse_string_argument (void);
274 static int parse_variable_argument (void);
276 /* Parses all the variable and string specifications on a single
277 PRINT, PRINT EJECT, or WRITE command into the prt structure.
282 /* Return code from called function. */
290 while (lex_match ('/'))
292 int prev_recno = fx.recno;
295 if (lex_is_number ())
297 if (!lex_force_int ())
299 if (lex_integer () < fx.recno)
301 msg (SE, _("The record number specified, %ld, is "
302 "before the previous record, %d. Data "
303 "fields must be listed in order of "
304 "increasing record number."),
305 lex_integer (), fx.recno - 1);
308 fx.recno = lex_integer ();
312 fx.spec.type = PRT_NEWLINE;
313 while (prev_recno++ < fx.recno)
314 append_var_spec (&fx.spec);
319 if (token == T_STRING)
320 code = parse_string_argument ();
322 code = parse_variable_argument ();
326 fx.spec.type = PRT_NEWLINE;
327 append_var_spec (&fx.spec);
331 else if (fx.recno > nrec)
333 msg (SE, _("Variables are specified on records that "
334 "should not exist according to RECORDS subcommand."));
340 lex_error (_("expecting end of command"));
347 /* Parses a string argument to the PRINT commands. Returns success. */
349 parse_string_argument (void)
351 fx.spec.type = PRT_CONST;
352 fx.spec.fc = fx.sc - 1;
353 fx.spec.u.c = ds_xstrdup (&tokstr);
356 /* Parse the included column range. */
357 if (lex_is_number ())
359 /* Width of column range in characters. */
362 /* Width of constant string in characters. */
365 /* 1-based index of last column in range. */
368 if (!lex_is_integer () || lex_integer () <= 0)
370 msg (SE, _("%g is not a valid column location."), tokval);
373 fx.spec.fc = lex_integer () - 1;
376 lex_negative_to_dash ();
379 if (!lex_is_integer ())
381 msg (SE, _("Column location expected following `%d-'."),
385 if (lex_integer () <= 0)
387 msg (SE, _("%g is not a valid column location."), tokval);
390 if (lex_integer () < fx.spec.fc + 1)
392 msg (SE, _("%d-%ld is not a valid column range. The second "
393 "column must be greater than or equal to the first."),
394 fx.spec.fc + 1, lex_integer ());
397 lc = lex_integer () - 1;
402 /* If only a starting location is specified then the field is
403 the width of the provided string. */
404 lc = fx.spec.fc + strlen (fx.spec.u.c) - 1;
406 /* Apply the range. */
407 c_len = lc - fx.spec.fc + 1;
408 s_len = strlen (fx.spec.u.c);
410 fx.spec.u.c[c_len] = 0;
411 else if (s_len < c_len)
413 fx.spec.u.c = xrealloc (fx.spec.u.c, c_len + 1);
414 memset (&fx.spec.u.c[s_len], ' ', c_len - s_len);
415 fx.spec.u.c[c_len] = 0;
421 /* If nothing is provided then the field is the width of the
423 fx.sc += strlen (fx.spec.u.c);
425 append_var_spec (&fx.spec);
433 /* Parses a variable argument to the PRINT commands by passing it off
434 to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
437 parse_variable_argument (void)
439 if (!parse_variables (default_dict, &fx.v, &fx.nv, PV_DUPLICATE))
442 if (lex_is_number ())
444 if (!fixed_parse_compatible ())
447 else if (token == '(')
451 if (!fixed_parse_fortran ())
456 /* User wants dictionary format specifiers. */
460 for (i = 0; i < fx.nv; i++)
463 fx.spec.type = PRT_VAR;
464 fx.spec.fc = fx.sc - 1;
465 fx.spec.u.v.v = fx.v[i];
466 fx.spec.u.v.f = fx.v[i]->print;
467 append_var_spec (&fx.spec);
468 fx.sc += fx.v[i]->print.w;
471 fx.spec.type = PRT_SPACE;
472 fx.spec.fc = fx.sc - 1;
473 append_var_spec (&fx.spec);
486 /* Verifies that FORMAT doesn't need a variable wider than WIDTH.
487 Returns true iff that is the case. */
489 check_string_width (const struct fmt_spec *format, const struct variable *v)
491 if (get_format_var_width (format) > v->width)
493 msg (SE, _("Variable %s has width %d so it cannot be output "
495 v->name, v->width, fmt_to_string (format));
501 /* Parses a column specification for parse_specs(). */
503 fixed_parse_compatible (void)
505 int individual_var_width;
509 type = fx.v[0]->type;
510 for (i = 1; i < fx.nv; i++)
511 if (type != fx.v[i]->type)
513 msg (SE, _("%s is not of the same type as %s. To specify "
514 "variables of different types in the same variable "
515 "list, use a FORTRAN-like format specifier."),
516 fx.v[i]->name, fx.v[0]->name);
520 if (!lex_force_int ())
522 fx.fc = lex_integer () - 1;
525 msg (SE, _("Column positions for fields must be positive."));
530 lex_negative_to_dash ();
533 if (!lex_force_int ())
535 fx.lc = lex_integer () - 1;
538 msg (SE, _("Column positions for fields must be positive."));
541 else if (fx.lc < fx.fc)
543 msg (SE, _("The ending column for a field must not "
544 "be less than the starting column."));
552 fx.spec.u.v.f.w = fx.lc - fx.fc + 1;
555 struct fmt_desc *fdp;
561 fx.spec.u.v.f.type = parse_format_specifier_name (&cp, 0);
562 if (fx.spec.u.v.f.type == -1)
566 msg (SE, _("A format specifier on this line "
567 "has extra characters on the end."));
574 fx.spec.u.v.f.type = FMT_F;
576 if (lex_is_number ())
578 if (!lex_force_int ())
580 if (lex_integer () < 1)
582 msg (SE, _("The value for number of decimal places "
583 "must be at least 1."));
586 fx.spec.u.v.f.d = lex_integer ();
592 fdp = &formats[fx.spec.u.v.f.type];
593 if (fdp->n_args < 2 && fx.spec.u.v.f.d)
595 msg (SE, _("Input format %s doesn't accept decimal places."),
599 if (fx.spec.u.v.f.d > 16)
600 fx.spec.u.v.f.d = 16;
602 if (!lex_force_match (')'))
607 fx.spec.u.v.f.type = FMT_F;
613 if ((fx.lc - fx.fc + 1) % fx.nv)
615 msg (SE, _("The %d columns %d-%d can't be evenly divided into %u "
617 fx.lc - fx.fc + 1, fx.fc + 1, fx.lc + 1, (unsigned) fx.nv);
621 individual_var_width = (fx.lc - fx.fc + 1) / fx.nv;
622 fx.spec.u.v.f.w = individual_var_width;
623 if (!check_output_specifier (&fx.spec.u.v.f, true)
624 || !check_specifier_type (&fx.spec.u.v.f, type, true))
628 for (i = 0; i < fx.nv; i++)
629 if (!check_string_width (&fx.spec.u.v.f, fx.v[i]))
633 fx.spec.type = PRT_VAR;
634 for (i = 0; i < fx.nv; i++)
636 fx.spec.fc = fx.fc + individual_var_width * i;
637 fx.spec.u.v.v = fx.v[i];
638 append_var_spec (&fx.spec);
643 /* Destroy a format list and, optionally, all its sublists. */
645 destroy_fmt_list (struct fmt_list *f, int recurse)
647 struct fmt_list *next;
652 if (recurse && f->f.type == FMT_DESCEND)
653 destroy_fmt_list (f->down, 1);
658 /* Recursively puts the format list F (which represents a set of
659 FORTRAN-like format specifications, like 4(F10,2X)) into the
662 dump_fmt_list (struct fmt_list *f)
666 for (; f; f = f->next)
667 if (f->f.type == FMT_X)
669 else if (f->f.type == FMT_T)
671 else if (f->f.type == FMT_NEWREC)
673 fx.recno += f->count;
675 fx.spec.type = PRT_NEWLINE;
676 for (i = 0; i < f->count; i++)
677 append_var_spec (&fx.spec);
680 for (i = 0; i < f->count; i++)
681 if (f->f.type == FMT_DESCEND)
683 if (!dump_fmt_list (f->down))
692 msg (SE, _("The number of format "
693 "specifications exceeds the number of variable "
699 if (!check_output_specifier (&f->f, true)
700 || !check_specifier_type (&f->f, v->type, true)
701 || !check_string_width (&f->f, v))
704 fx.spec.type = PRT_VAR;
706 fx.spec.u.v.f = f->f;
707 fx.spec.fc = fx.sc - 1;
708 append_var_spec (&fx.spec);
715 /* Recursively parses a list of FORTRAN-like format specifiers. Calls
716 itself to parse nested levels of parentheses. Returns to its
717 original caller NULL, to indicate error, non-NULL, but nothing
718 useful, to indicate success (it returns a free()'d block). */
719 static struct fmt_list *
720 fixed_parse_fortran (void)
722 struct fmt_list *head = NULL;
723 struct fmt_list *fl = NULL;
725 lex_get (); /* skip opening parenthesis */
729 fl = fl->next = xmalloc (sizeof *fl);
731 head = fl = xmalloc (sizeof *fl);
733 if (lex_is_number ())
735 if (!lex_is_integer ())
737 fl->count = lex_integer ();
745 fl->f.type = FMT_DESCEND;
747 fl->down = fixed_parse_fortran ();
752 else if (lex_match ('/'))
753 fl->f.type = FMT_NEWREC;
754 else if (!parse_format_specifier (&fl->f, FMTP_ALLOW_XT)
755 || !check_output_specifier (&fl->f, 1))
767 dump_fmt_list (head);
768 destroy_fmt_list (head, 1);
771 msg (SE, _("There aren't enough format specifications "
772 "to match the number of variable names given."));
779 destroy_fmt_list (head, 0);
784 /* Prints the table produced by the TABLE subcommand to the listing
787 dump_table (const struct file_handle *fh)
789 struct prt_out_spec *spec;
794 for (nspec = 0, spec = prt.spec; spec; spec = spec->next)
795 if (spec->type == PRT_CONST || spec->type == PRT_VAR)
797 t = tab_create (4, nspec + 1, 0);
798 tab_columns (t, TAB_COL_DOWN, 1);
799 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, nspec);
800 tab_hline (t, TAL_2, 0, 3, 1);
801 tab_headers (t, 0, 0, 1, 0);
802 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
803 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
804 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
805 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
806 tab_dim (t, tab_natural_dimensions);
807 for (nspec = recno = 0, spec = prt.spec; spec; spec = spec->next)
815 int len = strlen (spec->u.c);
817 tab_text (t, 0, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
818 "\"%s\"", spec->u.c);
819 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
820 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
821 spec->fc + 1, spec->fc + len);
822 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
829 tab_text (t, 0, nspec, TAB_LEFT, spec->u.v.v->name);
830 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
831 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
832 spec->fc + 1, spec->fc + spec->u.v.f.w);
833 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX,
834 fmt_to_string (&spec->u.v.f));
844 tab_title (t, ngettext ("Writing %d record to %s.",
845 "Writing %d records to %s.", recno),
846 recno, fh_get_name (fh));
848 tab_title (t, ngettext ("Writing %d record.",
849 "Writing %d records.", recno), recno);
853 /* Calculates the maximum possible line width and allocates a buffer
854 big enough to contain it */
858 /* Cumulative maximum line width (excluding null terminator) so far. */
861 /* Width required by current this prt_out_spec. */
862 int pot_w; /* Potential w. */
865 struct prt_out_spec *i;
867 for (i = prt.spec; i; i = i->next)
875 pot_w = i->fc + strlen (i->u.c);
878 pot_w = i->fc + i->u.v.f.w;
891 prt.max_width = w + 2;
892 prt.line = xmalloc (prt.max_width);
895 /* Transformation. */
897 /* Performs the transformation inside print_trns T on case C. */
899 print_trns_proc (void *trns_, struct ccase *c, int case_num UNUSED)
901 /* Transformation. */
902 struct print_trns *t = trns_;
905 struct prt_out_spec *i;
910 /* Length of the line in buf. */
912 memset (buf, ' ', t->max_width);
914 if (t->options & PRT_EJECT)
917 /* Note that a field written to a place where a field has
918 already been written truncates the record. `PRINT /A B
919 (T10,F8,T1,F8).' only outputs B. */
920 for (i = t->spec; i; i = i->next)
924 if (t->writer == NULL)
927 tab_output_text (TAB_FIX | TAT_NOWRAP, buf);
931 if ((t->options & PRT_CMD_MASK) == PRT_PRINT
932 || !(t->options & PRT_BINARY))
935 dfm_put_record (t->writer, buf, len);
938 memset (buf, ' ', t->max_width);
943 /* FIXME: Should be revised to keep track of the string's
944 length outside the loop, probably in i->u.c[0]. */
945 memcpy (&buf[i->fc], i->u.c, strlen (i->u.c));
946 len = i->fc + strlen (i->u.c);
950 data_out (&buf[i->fc], &i->u.v.f, case_data (c, i->u.v.v->fv));
951 len = i->fc + i->u.v.f.w;
955 /* PRT_SPACE always immediately follows PRT_VAR. */
964 if (t->writer != NULL && dfm_write_error (t->writer))
966 return TRNS_CONTINUE;
969 /* Frees all the data inside print_trns PRT. Does not free PRT. */
971 print_trns_free (void *prt_)
973 struct print_trns *prt = prt_;
974 struct prt_out_spec *i, *n;
977 for (i = prt->spec; i; i = n)
996 if (prt->writer != NULL)
997 ok = dfm_close_writer (prt->writer);
1004 /* PRINT SPACE transformation. */
1005 struct print_space_trns
1007 struct dfm_writer *writer; /* Output data file. */
1008 struct expression *e; /* Number of lines; NULL=1. */
1012 static trns_proc_func print_space_trns_proc;
1013 static trns_free_func print_space_trns_free;
1016 cmd_print_space (void)
1018 struct print_space_trns *t;
1019 struct file_handle *fh;
1020 struct expression *e;
1021 struct dfm_writer *writer;
1023 if (lex_match_id ("OUTFILE"))
1027 fh = fh_parse (FH_REF_FILE);
1037 e = expr_parse (default_dict, EXPR_NUMBER);
1041 lex_error (_("expecting end of command"));
1050 writer = dfm_open_writer (fh);
1060 t = xmalloc (sizeof *t);
1064 add_transformation (print_space_trns_proc, print_space_trns_free, t);
1068 /* Executes a PRINT SPACE transformation. */
1070 print_space_trns_proc (void *t_, struct ccase *c,
1071 int case_num UNUSED)
1073 struct print_space_trns *t = t_;
1079 double f = expr_evaluate_num (t->e, c, case_num);
1081 msg (SW, _("The expression on PRINT SPACE evaluated to the "
1082 "system-missing value."));
1083 else if (f < 0 || f > INT_MAX)
1084 msg (SW, _("The expression on PRINT SPACE evaluated to %g."), f);
1090 if (t->writer == NULL)
1093 dfm_put_record (t->writer, "\n", 1);
1095 if (t->writer != NULL && dfm_write_error (t->writer))
1097 return TRNS_CONTINUE;
1100 /* Frees a PRINT SPACE transformation.
1101 Returns true if successful, false if an I/O error occurred. */
1103 print_space_trns_free (void *trns_)
1105 struct print_space_trns *trns = trns_;
1106 bool ok = dfm_close_writer (trns->writer);
1107 expr_free (trns->e);