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