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 <language/lexer/variable-parser.h>
36 #include <libpspp/alloc.h>
37 #include <libpspp/compiler.h>
38 #include <libpspp/message.h>
39 #include <libpspp/message.h>
40 #include <libpspp/misc.h>
41 #include <output/manager.h>
42 #include <output/table.h>
45 #define _(msgid) gettext (msgid)
47 /* Describes what to do when an output field is encountered. */
50 PRT_ERROR, /* Invalid value. */
51 PRT_NEWLINE, /* Newline. */
52 PRT_CONST, /* Constant string. */
53 PRT_VAR, /* Variable. */
54 PRT_SPACE /* A single space. */
57 /* Describes how to output one field. */
60 struct prt_out_spec *next;
61 int type; /* PRT_* constant. */
62 int fc; /* 0-based first column. */
65 char *c; /* PRT_CONST: Associated string. */
68 struct variable *v; /* PRT_VAR: Associated variable. */
69 struct fmt_spec f; /* PRT_VAR: Output spec. */
76 /* Enums for use with print_trns's `options' field. */
79 PRT_CMD_MASK = 1, /* Command type mask. */
80 PRT_PRINT = 0, /* PRINT transformation identifier. */
81 PRT_WRITE = 1, /* WRITE transformation identifier. */
82 PRT_EJECT = 002, /* Can be combined with CMD_PRINT only. */
83 PRT_BINARY = 004 /* File is binary, omit newlines. */
86 /* PRINT, PRINT EJECT, WRITE private data structure. */
89 struct dfm_writer *writer; /* Output file, NULL=listing file. */
90 int options; /* PRT_* bitmapped field. */
91 struct prt_out_spec *spec; /* Output specifications. */
92 int max_width; /* Maximum line width including null. */
93 char *line; /* Buffer for sticking lines in. */
96 /* PRT_PRINT or PRT_WRITE. */
99 /* Holds information on parsing the data file. */
100 static struct print_trns prt;
102 /* Last prt_out_spec in the chain. Used for building the linked-list. */
103 static struct prt_out_spec *next;
105 /* Number of records. */
108 static int internal_cmd_print (int flags);
109 static trns_proc_func print_trns_proc;
110 static trns_free_func print_trns_free;
111 static int parse_specs (void);
112 static void dump_table (const struct file_handle *);
113 static void append_var_spec (struct prt_out_spec *);
114 static void alloc_line (void);
118 /* Parses PRINT command. */
122 return internal_cmd_print (PRT_PRINT);
125 /* Parses PRINT EJECT command. */
127 cmd_print_eject (void)
129 return internal_cmd_print (PRT_PRINT | PRT_EJECT);
132 /* Parses WRITE command. */
136 return internal_cmd_print (PRT_WRITE);
139 /* Parses the output commands. F is PRT_PRINT, PRT_WRITE, or
140 PRT_PRINT|PRT_EJECT. */
142 internal_cmd_print (int f)
144 int table = 0; /* Print table? */
145 struct print_trns *trns = NULL; /* malloc()'d transformation. */
146 struct file_handle *fh = NULL;
148 /* Fill in prt to facilitate error-handling. */
156 which_cmd = f & PRT_CMD_MASK;
158 /* Parse the command options. */
159 while (!lex_match ('/'))
161 if (lex_match_id ("OUTFILE"))
165 fh = fh_parse (FH_REF_FILE);
169 else if (lex_match_id ("RECORDS"))
173 if (!lex_force_int ())
175 nrec = lex_integer ();
179 else if (lex_match_id ("TABLE"))
181 else if (lex_match_id ("NOTABLE"))
185 lex_error (_("expecting a valid subcommand"));
190 /* Parse variables and strings. */
196 prt.writer = dfm_open_writer (fh);
197 if (prt.writer == NULL)
200 if (fh_get_mode (fh) == FH_MODE_BINARY)
201 prt.options |= PRT_BINARY;
204 /* Output the variable table if requested. */
208 /* Count the maximum line width. Allocate linebuffer if
212 /* Put the transformation in the queue. */
213 trns = xmalloc (sizeof *trns);
214 memcpy (trns, &prt, sizeof *trns);
215 add_transformation (print_trns_proc, print_trns_free, trns);
220 print_trns_free (&prt);
224 /* Appends the field output specification SPEC to the list maintained
227 append_var_spec (struct prt_out_spec *spec)
230 prt.spec = next = xmalloc (sizeof *spec);
232 next = next->next = xmalloc (sizeof *spec);
234 memcpy (next, spec, sizeof *spec);
238 /* Field parsing. Mostly stolen from data-list.c. */
240 /* Used for chaining together fortran-like format specifiers. */
243 struct fmt_list *next;
246 struct fmt_list *down;
249 /* Used as "local" variables among the fixed-format parsing funcs. If
250 it were guaranteed that PSPP were going to be compiled by gcc,
251 I'd make all these functions a single set of nested functions. */
254 struct variable **v; /* variable list */
255 size_t nv; /* number of variables in list */
256 size_t cv; /* number of variables from list used up so far
257 by the FORTRAN-like format specifiers */
259 int recno; /* current 1-based record number */
260 int sc; /* 1-based starting column for next variable */
262 struct prt_out_spec spec; /* next format spec to append to list */
263 int fc, lc; /* first, last 1-based column number of current
266 int level; /* recursion level for FORTRAN-like format
271 static int fixed_parse_compatible (void);
272 static struct fmt_list *fixed_parse_fortran (void);
274 static int parse_string_argument (void);
275 static int parse_variable_argument (void);
277 /* Parses all the variable and string specifications on a single
278 PRINT, PRINT EJECT, or WRITE command into the prt structure.
283 /* Return code from called function. */
291 while (lex_match ('/'))
293 int prev_recno = fx.recno;
296 if (lex_is_number ())
298 if (!lex_force_int ())
300 if (lex_integer () < fx.recno)
302 msg (SE, _("The record number specified, %ld, is "
303 "before the previous record, %d. Data "
304 "fields must be listed in order of "
305 "increasing record number."),
306 lex_integer (), fx.recno - 1);
309 fx.recno = lex_integer ();
313 fx.spec.type = PRT_NEWLINE;
314 while (prev_recno++ < fx.recno)
315 append_var_spec (&fx.spec);
320 if (token == T_STRING)
321 code = parse_string_argument ();
323 code = parse_variable_argument ();
327 fx.spec.type = PRT_NEWLINE;
328 append_var_spec (&fx.spec);
332 else if (fx.recno > nrec)
334 msg (SE, _("Variables are specified on records that "
335 "should not exist according to RECORDS subcommand."));
341 lex_error (_("expecting end of command"));
348 /* Parses a string argument to the PRINT commands. Returns success. */
350 parse_string_argument (void)
352 fx.spec.type = PRT_CONST;
353 fx.spec.fc = fx.sc - 1;
354 fx.spec.u.c = ds_xstrdup (&tokstr);
357 /* Parse the included column range. */
358 if (lex_is_number ())
360 /* Width of column range in characters. */
363 /* Width of constant string in characters. */
366 /* 1-based index of last column in range. */
369 if (!lex_is_integer () || lex_integer () <= 0)
371 msg (SE, _("%g is not a valid column location."), tokval);
374 fx.spec.fc = lex_integer () - 1;
377 lex_negative_to_dash ();
380 if (!lex_is_integer ())
382 msg (SE, _("Column location expected following `%d-'."),
386 if (lex_integer () <= 0)
388 msg (SE, _("%g is not a valid column location."), tokval);
391 if (lex_integer () < fx.spec.fc + 1)
393 msg (SE, _("%d-%ld is not a valid column range. The second "
394 "column must be greater than or equal to the first."),
395 fx.spec.fc + 1, lex_integer ());
398 lc = lex_integer () - 1;
403 /* If only a starting location is specified then the field is
404 the width of the provided string. */
405 lc = fx.spec.fc + strlen (fx.spec.u.c) - 1;
407 /* Apply the range. */
408 c_len = lc - fx.spec.fc + 1;
409 s_len = strlen (fx.spec.u.c);
411 fx.spec.u.c[c_len] = 0;
412 else if (s_len < c_len)
414 fx.spec.u.c = xrealloc (fx.spec.u.c, c_len + 1);
415 memset (&fx.spec.u.c[s_len], ' ', c_len - s_len);
416 fx.spec.u.c[c_len] = 0;
422 /* If nothing is provided then the field is the width of the
424 fx.sc += strlen (fx.spec.u.c);
426 append_var_spec (&fx.spec);
434 /* Parses a variable argument to the PRINT commands by passing it off
435 to fixed_parse_compatible() or fixed_parse_fortran() as appropriate.
438 parse_variable_argument (void)
440 if (!parse_variables (default_dict, &fx.v, &fx.nv, PV_DUPLICATE))
443 if (lex_is_number ())
445 if (!fixed_parse_compatible ())
448 else if (token == '(')
452 if (!fixed_parse_fortran ())
457 /* User wants dictionary format specifiers. */
461 for (i = 0; i < fx.nv; i++)
464 fx.spec.type = PRT_VAR;
465 fx.spec.fc = fx.sc - 1;
466 fx.spec.u.v.v = fx.v[i];
467 fx.spec.u.v.f = fx.v[i]->print;
468 append_var_spec (&fx.spec);
469 fx.sc += fx.v[i]->print.w;
472 fx.spec.type = PRT_SPACE;
473 fx.spec.fc = fx.sc - 1;
474 append_var_spec (&fx.spec);
487 /* Verifies that FORMAT doesn't need a variable wider than WIDTH.
488 Returns true iff that is the case. */
490 check_string_width (const struct fmt_spec *format, const struct variable *v)
492 if (get_format_var_width (format) > v->width)
494 msg (SE, _("Variable %s has width %d so it cannot be output "
496 v->name, v->width, fmt_to_string (format));
502 /* Parses a column specification for parse_specs(). */
504 fixed_parse_compatible (void)
506 int individual_var_width;
510 type = fx.v[0]->type;
511 for (i = 1; i < fx.nv; i++)
512 if (type != fx.v[i]->type)
514 msg (SE, _("%s is not of the same type as %s. To specify "
515 "variables of different types in the same variable "
516 "list, use a FORTRAN-like format specifier."),
517 fx.v[i]->name, fx.v[0]->name);
521 if (!lex_force_int ())
523 fx.fc = lex_integer () - 1;
526 msg (SE, _("Column positions for fields must be positive."));
531 lex_negative_to_dash ();
534 if (!lex_force_int ())
536 fx.lc = lex_integer () - 1;
539 msg (SE, _("Column positions for fields must be positive."));
542 else if (fx.lc < fx.fc)
544 msg (SE, _("The ending column for a field must not "
545 "be less than the starting column."));
553 fx.spec.u.v.f.w = fx.lc - fx.fc + 1;
556 struct fmt_desc *fdp;
562 fx.spec.u.v.f.type = parse_format_specifier_name (&cp, 0);
563 if (fx.spec.u.v.f.type == -1)
567 msg (SE, _("A format specifier on this line "
568 "has extra characters on the end."));
575 fx.spec.u.v.f.type = FMT_F;
577 if (lex_is_number ())
579 if (!lex_force_int ())
581 if (lex_integer () < 1)
583 msg (SE, _("The value for number of decimal places "
584 "must be at least 1."));
587 fx.spec.u.v.f.d = lex_integer ();
593 fdp = &formats[fx.spec.u.v.f.type];
594 if (fdp->n_args < 2 && fx.spec.u.v.f.d)
596 msg (SE, _("Input format %s doesn't accept decimal places."),
600 if (fx.spec.u.v.f.d > 16)
601 fx.spec.u.v.f.d = 16;
603 if (!lex_force_match (')'))
608 fx.spec.u.v.f.type = FMT_F;
614 if ((fx.lc - fx.fc + 1) % fx.nv)
616 msg (SE, _("The %d columns %d-%d can't be evenly divided into %u "
618 fx.lc - fx.fc + 1, fx.fc + 1, fx.lc + 1, (unsigned) fx.nv);
622 individual_var_width = (fx.lc - fx.fc + 1) / fx.nv;
623 fx.spec.u.v.f.w = individual_var_width;
624 if (!check_output_specifier (&fx.spec.u.v.f, true)
625 || !check_specifier_type (&fx.spec.u.v.f, type, true))
629 for (i = 0; i < fx.nv; i++)
630 if (!check_string_width (&fx.spec.u.v.f, fx.v[i]))
634 fx.spec.type = PRT_VAR;
635 for (i = 0; i < fx.nv; i++)
637 fx.spec.fc = fx.fc + individual_var_width * i;
638 fx.spec.u.v.v = fx.v[i];
639 append_var_spec (&fx.spec);
644 /* Destroy a format list and, optionally, all its sublists. */
646 destroy_fmt_list (struct fmt_list *f, int recurse)
648 struct fmt_list *next;
653 if (recurse && f->f.type == FMT_DESCEND)
654 destroy_fmt_list (f->down, 1);
659 /* Recursively puts the format list F (which represents a set of
660 FORTRAN-like format specifications, like 4(F10,2X)) into the
663 dump_fmt_list (struct fmt_list *f)
667 for (; f; f = f->next)
668 if (f->f.type == FMT_X)
670 else if (f->f.type == FMT_T)
672 else if (f->f.type == FMT_NEWREC)
674 fx.recno += f->count;
676 fx.spec.type = PRT_NEWLINE;
677 for (i = 0; i < f->count; i++)
678 append_var_spec (&fx.spec);
681 for (i = 0; i < f->count; i++)
682 if (f->f.type == FMT_DESCEND)
684 if (!dump_fmt_list (f->down))
693 msg (SE, _("The number of format "
694 "specifications exceeds the number of variable "
700 if (!check_output_specifier (&f->f, true)
701 || !check_specifier_type (&f->f, v->type, true)
702 || !check_string_width (&f->f, v))
705 fx.spec.type = PRT_VAR;
707 fx.spec.u.v.f = f->f;
708 fx.spec.fc = fx.sc - 1;
709 append_var_spec (&fx.spec);
716 /* Recursively parses a list of FORTRAN-like format specifiers. Calls
717 itself to parse nested levels of parentheses. Returns to its
718 original caller NULL, to indicate error, non-NULL, but nothing
719 useful, to indicate success (it returns a free()'d block). */
720 static struct fmt_list *
721 fixed_parse_fortran (void)
723 struct fmt_list *head = NULL;
724 struct fmt_list *fl = NULL;
726 lex_get (); /* skip opening parenthesis */
730 fl = fl->next = xmalloc (sizeof *fl);
732 head = fl = xmalloc (sizeof *fl);
734 if (lex_is_number ())
736 if (!lex_is_integer ())
738 fl->count = lex_integer ();
746 fl->f.type = FMT_DESCEND;
748 fl->down = fixed_parse_fortran ();
753 else if (lex_match ('/'))
754 fl->f.type = FMT_NEWREC;
755 else if (!parse_format_specifier (&fl->f, FMTP_ALLOW_XT)
756 || !check_output_specifier (&fl->f, 1))
768 dump_fmt_list (head);
769 destroy_fmt_list (head, 1);
772 msg (SE, _("There aren't enough format specifications "
773 "to match the number of variable names given."));
780 destroy_fmt_list (head, 0);
785 /* Prints the table produced by the TABLE subcommand to the listing
788 dump_table (const struct file_handle *fh)
790 struct prt_out_spec *spec;
795 for (nspec = 0, spec = prt.spec; spec; spec = spec->next)
796 if (spec->type == PRT_CONST || spec->type == PRT_VAR)
798 t = tab_create (4, nspec + 1, 0);
799 tab_columns (t, TAB_COL_DOWN, 1);
800 tab_box (t, TAL_1, TAL_1, TAL_0, TAL_1, 0, 0, 3, nspec);
801 tab_hline (t, TAL_2, 0, 3, 1);
802 tab_headers (t, 0, 0, 1, 0);
803 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Variable"));
804 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Record"));
805 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Columns"));
806 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Format"));
807 tab_dim (t, tab_natural_dimensions);
808 for (nspec = recno = 0, spec = prt.spec; spec; spec = spec->next)
816 int len = strlen (spec->u.c);
818 tab_text (t, 0, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
819 "\"%s\"", spec->u.c);
820 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
821 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
822 spec->fc + 1, spec->fc + len);
823 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX | TAT_PRINTF,
830 tab_text (t, 0, nspec, TAB_LEFT, spec->u.v.v->name);
831 tab_text (t, 1, nspec, TAT_PRINTF, "%d", recno + 1);
832 tab_text (t, 2, nspec, TAT_PRINTF, "%3d-%3d",
833 spec->fc + 1, spec->fc + spec->u.v.f.w);
834 tab_text (t, 3, nspec, TAB_LEFT | TAB_FIX,
835 fmt_to_string (&spec->u.v.f));
845 tab_title (t, ngettext ("Writing %d record to %s.",
846 "Writing %d records to %s.", recno),
847 recno, fh_get_name (fh));
849 tab_title (t, ngettext ("Writing %d record.",
850 "Writing %d records.", recno), recno);
854 /* Calculates the maximum possible line width and allocates a buffer
855 big enough to contain it */
859 /* Cumulative maximum line width (excluding null terminator) so far. */
862 /* Width required by current this prt_out_spec. */
863 int pot_w; /* Potential w. */
866 struct prt_out_spec *i;
868 for (i = prt.spec; i; i = i->next)
876 pot_w = i->fc + strlen (i->u.c);
879 pot_w = i->fc + i->u.v.f.w;
892 prt.max_width = w + 2;
893 prt.line = xmalloc (prt.max_width);
896 /* Transformation. */
898 /* Performs the transformation inside print_trns T on case C. */
900 print_trns_proc (void *trns_, struct ccase *c, int case_num UNUSED)
902 /* Transformation. */
903 struct print_trns *t = trns_;
906 struct prt_out_spec *i;
911 /* Length of the line in buf. */
913 memset (buf, ' ', t->max_width);
915 if (t->options & PRT_EJECT)
918 /* Note that a field written to a place where a field has
919 already been written truncates the record. `PRINT /A B
920 (T10,F8,T1,F8).' only outputs B. */
921 for (i = t->spec; i; i = i->next)
925 if (t->writer == NULL)
928 tab_output_text (TAB_FIX | TAT_NOWRAP, buf);
932 if ((t->options & PRT_CMD_MASK) == PRT_PRINT
933 || !(t->options & PRT_BINARY))
936 dfm_put_record (t->writer, buf, len);
939 memset (buf, ' ', t->max_width);
944 /* FIXME: Should be revised to keep track of the string's
945 length outside the loop, probably in i->u.c[0]. */
946 memcpy (&buf[i->fc], i->u.c, strlen (i->u.c));
947 len = i->fc + strlen (i->u.c);
951 data_out (&buf[i->fc], &i->u.v.f, case_data (c, i->u.v.v->fv));
952 len = i->fc + i->u.v.f.w;
956 /* PRT_SPACE always immediately follows PRT_VAR. */
965 if (t->writer != NULL && dfm_write_error (t->writer))
967 return TRNS_CONTINUE;
970 /* Frees all the data inside print_trns PRT. Does not free PRT. */
972 print_trns_free (void *prt_)
974 struct print_trns *prt = prt_;
975 struct prt_out_spec *i, *n;
978 for (i = prt->spec; i; i = n)
997 if (prt->writer != NULL)
998 ok = dfm_close_writer (prt->writer);
1005 /* PRINT SPACE transformation. */
1006 struct print_space_trns
1008 struct dfm_writer *writer; /* Output data file. */
1009 struct expression *e; /* Number of lines; NULL=1. */
1013 static trns_proc_func print_space_trns_proc;
1014 static trns_free_func print_space_trns_free;
1017 cmd_print_space (void)
1019 struct print_space_trns *t;
1020 struct file_handle *fh;
1021 struct expression *e;
1022 struct dfm_writer *writer;
1024 if (lex_match_id ("OUTFILE"))
1028 fh = fh_parse (FH_REF_FILE);
1038 e = expr_parse (default_dict, EXPR_NUMBER);
1042 lex_error (_("expecting end of command"));
1051 writer = dfm_open_writer (fh);
1061 t = xmalloc (sizeof *t);
1065 add_transformation (print_space_trns_proc, print_space_trns_free, t);
1069 /* Executes a PRINT SPACE transformation. */
1071 print_space_trns_proc (void *t_, struct ccase *c,
1072 int case_num UNUSED)
1074 struct print_space_trns *t = t_;
1080 double f = expr_evaluate_num (t->e, c, case_num);
1082 msg (SW, _("The expression on PRINT SPACE evaluated to the "
1083 "system-missing value."));
1084 else if (f < 0 || f > INT_MAX)
1085 msg (SW, _("The expression on PRINT SPACE evaluated to %g."), f);
1091 if (t->writer == NULL)
1094 dfm_put_record (t->writer, "\n", 1);
1096 if (t->writer != NULL && dfm_write_error (t->writer))
1098 return TRNS_CONTINUE;
1101 /* Frees a PRINT SPACE transformation.
1102 Returns true if successful, false if an I/O error occurred. */
1104 print_space_trns_free (void *trns_)
1106 struct print_space_trns *trns = trns_;
1107 bool ok = dfm_close_writer (trns->writer);
1108 expr_free (trns->e);