Clean up how transformations work.
[pspp] / src / language / data-io / inpt-pgm.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009, 2010, 2011, 2012, 2013 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 <float.h>
20 #include <stdlib.h>
21
22 #include "data/case.h"
23 #include "data/caseinit.h"
24 #include "data/casereader-provider.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/session.h"
28 #include "data/transformations.h"
29 #include "data/variable.h"
30 #include "language/command.h"
31 #include "language/data-io/data-reader.h"
32 #include "language/data-io/file-handle.h"
33 #include "language/data-io/inpt-pgm.h"
34 #include "language/expressions/public.h"
35 #include "language/lexer/lexer.h"
36 #include "libpspp/assertion.h"
37 #include "libpspp/compiler.h"
38 #include "libpspp/message.h"
39 #include "libpspp/misc.h"
40 #include "libpspp/str.h"
41
42 #include "gl/xalloc.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46
47 /* Indicates how a `union value' should be initialized. */
48 struct input_program_pgm
49   {
50     struct session *session;
51     struct dataset *ds;
52
53     struct trns_chain xforms;
54     size_t idx;
55     bool eof;
56
57     casenumber case_nr;             /* Incremented by END CASE transformation. */
58
59     struct caseinit *init;
60     struct caseproto *proto;
61   };
62
63 static void destroy_input_program (struct input_program_pgm *);
64 static const struct trns_class end_case_trns_class;
65 static const struct trns_class reread_trns_class;
66 static const struct trns_class end_file_trns_class;
67
68 static const struct casereader_class input_program_casereader_class;
69
70 static bool inside_input_program;
71 static bool saw_END_CASE;
72 static bool saw_END_FILE;
73 static bool saw_DATA_LIST;
74
75 /* Returns true if we're parsing the inside of a INPUT
76    PROGRAM...END INPUT PROGRAM construct, false otherwise. */
77 bool
78 in_input_program (void)
79 {
80   return inside_input_program;
81 }
82
83 void
84 data_list_seen (void)
85 {
86   saw_DATA_LIST = true;
87 }
88
89 /* Emits an END CASE transformation for INP. */
90 static void
91 emit_END_CASE (struct dataset *ds)
92 {
93   add_transformation (ds, &end_case_trns_class, xzalloc (sizeof (bool)));
94 }
95
96 int
97 cmd_input_program (struct lexer *lexer, struct dataset *ds)
98 {
99   if (!lex_match (lexer, T_ENDCMD))
100     return lex_end_of_command (lexer);
101
102   struct session *session = session_create (dataset_session (ds));
103   struct dataset *inp_ds = dataset_create (session, "INPUT PROGRAM");
104
105   struct input_program_pgm *inp = xmalloc (sizeof *inp);
106   *inp = (struct input_program_pgm) { .session = session, .ds = inp_ds };
107
108   proc_push_transformations (inp->ds);
109   inside_input_program = true;
110   saw_END_CASE = saw_END_FILE = saw_DATA_LIST = false;
111   while (!lex_match_phrase (lexer, "END INPUT PROGRAM"))
112     {
113       enum cmd_result result;
114
115       result = cmd_parse_in_state (lexer, inp->ds, CMD_STATE_INPUT_PROGRAM);
116       if (result == CMD_EOF
117           || result == CMD_FINISH
118           || result == CMD_CASCADING_FAILURE)
119         {
120           proc_pop_transformations (inp->ds, &inp->xforms);
121
122           if (result == CMD_EOF)
123             msg (SE, _("Unexpected end-of-file within %s."), "INPUT PROGRAM");
124           inside_input_program = false;
125           destroy_input_program (inp);
126           return result;
127         }
128     }
129   if (!saw_END_CASE)
130     emit_END_CASE (inp->ds);
131   inside_input_program = false;
132   proc_pop_transformations (inp->ds, &inp->xforms);
133
134   if (!saw_DATA_LIST && !saw_END_FILE)
135     {
136       msg (SE, _("Input program must contain %s or %s."), "DATA LIST", "END FILE");
137       destroy_input_program (inp);
138       return CMD_FAILURE;
139     }
140   if (dict_get_next_value_idx (dataset_dict (inp->ds)) == 0)
141     {
142       msg (SE, _("Input program did not create any variables."));
143       destroy_input_program (inp);
144       return CMD_FAILURE;
145     }
146
147   /* Figure out how to initialize each input case. */
148   inp->init = caseinit_create ();
149   caseinit_mark_for_init (inp->init, dataset_dict (inp->ds));
150   inp->proto = caseproto_ref (dict_get_proto (dataset_dict (inp->ds)));
151
152   dataset_set_dict (ds, dict_clone (dataset_dict (inp->ds)));
153   dataset_set_source (
154     ds, casereader_create_sequential (NULL, inp->proto, CASENUMBER_MAX,
155                                       &input_program_casereader_class, inp));
156
157   return CMD_SUCCESS;
158 }
159
160 /* Reads and returns one case.
161    Returns the case if successful, null at end of file or if an
162    I/O error occurred. */
163 static struct ccase *
164 input_program_casereader_read (struct casereader *reader UNUSED, void *inp_)
165 {
166   struct input_program_pgm *inp = inp_;
167
168   if (inp->eof || !inp->xforms.n)
169     return NULL;
170
171   struct ccase *c = case_create (inp->proto);
172   caseinit_init_vars (inp->init, c);
173
174   for (size_t i = inp->idx < inp->xforms.n ? inp->idx : 0; ; i++)
175     {
176       if (i >= inp->xforms.n)
177         {
178           i = 0;
179           c = case_unshare (c);
180           caseinit_update_left_vars (inp->init, c);
181           caseinit_init_vars (inp->init, c);
182         }
183
184       const struct transformation *trns = &inp->xforms.xforms[i];
185       switch (trns->class->execute (trns->aux, &c, inp->case_nr))
186         {
187         case TRNS_END_CASE:
188           inp->case_nr++;
189           inp->idx = i;
190           return c;
191
192         case TRNS_ERROR:
193           casereader_force_error (reader);
194           /* Fall through. */
195         case TRNS_END_FILE:
196           inp->eof = true;
197           case_unref (c);
198           return NULL;
199
200         case TRNS_CONTINUE:
201           break;
202
203         default:
204           NOT_REACHED ();
205         }
206     }
207 }
208
209 static void
210 destroy_input_program (struct input_program_pgm *pgm)
211 {
212   if (pgm != NULL)
213     {
214       session_destroy (pgm->session);
215       trns_chain_uninit (&pgm->xforms);
216       caseinit_destroy (pgm->init);
217       caseproto_unref (pgm->proto);
218       free (pgm);
219     }
220 }
221
222 /* Destroys the casereader. */
223 static void
224 input_program_casereader_destroy (struct casereader *reader UNUSED, void *inp_)
225 {
226   struct input_program_pgm *inp = inp_;
227   destroy_input_program (inp);
228 }
229
230 static const struct casereader_class input_program_casereader_class =
231   {
232     input_program_casereader_read,
233     input_program_casereader_destroy,
234     NULL,
235     NULL,
236   };
237 \f
238 int
239 cmd_end_case (struct lexer *lexer UNUSED, struct dataset *ds)
240 {
241   assert (in_input_program ());
242   emit_END_CASE (ds);
243   saw_END_CASE = true;
244   return CMD_SUCCESS;
245 }
246
247 /* Outputs the current case */
248 static enum trns_result
249 end_case_trns_proc (void *resume_, struct ccase **c UNUSED,
250                     casenumber case_nr UNUSED)
251 {
252   bool *resume = resume_;
253   enum trns_result retval = *resume ? TRNS_CONTINUE : TRNS_END_CASE;
254   *resume = !*resume;
255   return retval;
256 }
257
258 static bool
259 end_case_trns_free (void *resume)
260 {
261   free (resume);
262   return true;
263 }
264
265 static const struct trns_class end_case_trns_class = {
266   .name = "END CASE",
267   .execute = end_case_trns_proc,
268   .destroy = end_case_trns_free,
269 };
270
271 /* REREAD transformation. */
272 struct reread_trns
273   {
274     struct dfm_reader *reader;  /* File to move file pointer back on. */
275     struct expression *column;  /* Column to reset file pointer to. */
276   };
277
278 /* Parses REREAD command. */
279 int
280 cmd_reread (struct lexer *lexer, struct dataset *ds)
281 {
282   struct file_handle *fh;       /* File to be re-read. */
283   struct expression *e;         /* Expression for column to set. */
284   struct reread_trns *t;        /* Created transformation. */
285   char *encoding = NULL;
286
287   fh = fh_get_default_handle ();
288   e = NULL;
289   while (lex_token (lexer) != T_ENDCMD)
290     {
291       if (lex_match_id (lexer, "COLUMN"))
292         {
293           lex_match (lexer, T_EQUALS);
294
295           if (e)
296             {
297               lex_sbc_only_once ("COLUMN");
298               goto error;
299             }
300
301           e = expr_parse (lexer, ds, VAL_NUMERIC);
302           if (!e)
303             goto error;
304         }
305       else if (lex_match_id (lexer, "FILE"))
306         {
307           lex_match (lexer, T_EQUALS);
308           fh_unref (fh);
309           fh = fh_parse (lexer, FH_REF_FILE | FH_REF_INLINE, NULL);
310           if (fh == NULL)
311             goto error;
312         }
313       else if (lex_match_id (lexer, "ENCODING"))
314         {
315           lex_match (lexer, T_EQUALS);
316           if (!lex_force_string (lexer))
317             goto error;
318
319           free (encoding);
320           encoding = ss_xstrdup (lex_tokss (lexer));
321
322           lex_get (lexer);
323         }
324       else
325         {
326           lex_error (lexer, NULL);
327           goto error;
328         }
329     }
330
331   t = xmalloc (sizeof *t);
332   t->reader = dfm_open_reader (fh, lexer, encoding);
333   t->column = e;
334   add_transformation (ds, &reread_trns_class, t);
335
336   fh_unref (fh);
337   free (encoding);
338   return CMD_SUCCESS;
339
340 error:
341   expr_free (e);
342   free (encoding);
343   return CMD_CASCADING_FAILURE;
344 }
345
346 /* Executes a REREAD transformation. */
347 static enum trns_result
348 reread_trns_proc (void *t_, struct ccase **c, casenumber case_num)
349 {
350   struct reread_trns *t = t_;
351
352   if (t->column == NULL)
353     dfm_reread_record (t->reader, 1);
354   else
355     {
356       double column = expr_evaluate_num (t->column, *c, case_num);
357       if (!isfinite (column) || column < 1)
358         {
359           msg (SE, _("REREAD: Column numbers must be positive finite "
360                "numbers.  Column set to 1."));
361           dfm_reread_record (t->reader, 1);
362         }
363       else
364         dfm_reread_record (t->reader, column);
365     }
366   return TRNS_CONTINUE;
367 }
368
369 /* Frees a REREAD transformation.
370    Returns true if successful, false if an I/O error occurred. */
371 static bool
372 reread_trns_free (void *t_)
373 {
374   struct reread_trns *t = t_;
375   expr_free (t->column);
376   dfm_close_reader (t->reader);
377   return true;
378 }
379
380 static const struct trns_class reread_trns_class = {
381   .name = "REREAD",
382   .execute = reread_trns_proc,
383   .destroy = reread_trns_free,
384 };
385
386 /* Parses END FILE command. */
387 int
388 cmd_end_file (struct lexer *lexer UNUSED, struct dataset *ds)
389 {
390   assert (in_input_program ());
391
392   add_transformation (ds, &end_file_trns_class, NULL);
393   saw_END_FILE = true;
394
395   return CMD_SUCCESS;
396 }
397
398 /* Executes an END FILE transformation. */
399 static enum trns_result
400 end_file_trns_proc (void *trns_ UNUSED, struct ccase **c UNUSED,
401                     casenumber case_num UNUSED)
402 {
403   return TRNS_END_FILE;
404 }
405
406 static const struct trns_class end_file_trns_class = {
407   .name = "END FILE",
408   .execute = end_file_trns_proc,
409 };