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