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