Clean up how transformations work.
[pspp] / src / language / control / loop.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2009-2011 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 <limits.h>
20
21 #include "data/case.h"
22 #include "data/dataset.h"
23 #include "data/dictionary.h"
24 #include "data/settings.h"
25 #include "data/transformations.h"
26 #include "data/variable.h"
27 #include "language/command.h"
28 #include "language/data-io/inpt-pgm.h"
29 #include "language/expressions/public.h"
30 #include "language/lexer/lexer.h"
31 #include "libpspp/assertion.h"
32 #include "libpspp/compiler.h"
33 #include "libpspp/message.h"
34 #include "libpspp/misc.h"
35 #include "libpspp/pool.h"
36 #include "libpspp/str.h"
37
38 #include "gl/xalloc.h"
39
40 #include "gettext.h"
41 #define _(msgid) gettext (msgid)
42
43 struct loop_trns
44   {
45     /* a=a TO b [BY c]. */
46     struct variable *index_var;    /* Index variable. */
47     struct expression *first_expr; /* Starting index. */
48     struct expression *by_expr;    /* Index increment (or NULL). */
49     struct expression *last_expr;  /* Terminal index. */
50
51     /* IF condition for LOOP or END LOOP. */
52     struct expression *loop_condition;
53     struct expression *end_loop_condition;
54
55     /* Inner transformations. */
56     struct trns_chain xforms;
57
58     /* State. */
59     double cur, by, last;       /* Index data. */
60     int iteration;              /* For MXLOOPS. */
61     size_t resume_idx;          /* For resuming after END CASE. */
62   };
63
64 static struct trns_class loop_trns_class;
65
66 static int in_loop;
67
68 static bool parse_if_clause (struct lexer *, struct dataset *,
69                              struct expression **);
70 static bool parse_index_clause (struct dataset *, struct lexer *,
71                                 struct loop_trns *);
72 \f
73 /* LOOP. */
74
75 /* Parses LOOP. */
76 int
77 cmd_loop (struct lexer *lexer, struct dataset *ds)
78 {
79   struct loop_trns *loop = xmalloc (sizeof *loop);
80   *loop = (struct loop_trns) { .resume_idx = SIZE_MAX };
81
82   bool ok = true;
83   while (lex_token (lexer) != T_ENDCMD && ok)
84     {
85       if (lex_match_id (lexer, "IF"))
86         ok = parse_if_clause (lexer, ds, &loop->loop_condition);
87       else
88         ok = parse_index_clause (ds, lexer, loop);
89     }
90   if (ok)
91     lex_end_of_command (lexer);
92   lex_discard_rest_of_command (lexer);
93
94   proc_push_transformations (ds);
95   in_loop++;
96   for (;;)
97     {
98       if (lex_token (lexer) == T_STOP)
99         {
100           lex_error (lexer, NULL);
101           ok = false;
102           break;
103         }
104       else if (lex_match_phrase (lexer, "END LOOP"))
105         {
106           if (lex_match_id (lexer, "IF"))
107             ok = parse_if_clause (lexer, ds, &loop->end_loop_condition) && ok;
108           break;
109         }
110       else
111         cmd_parse_in_state (lexer, ds,
112                             (in_input_program ()
113                              ? CMD_STATE_NESTED_INPUT_PROGRAM
114                              : CMD_STATE_NESTED_DATA));
115     }
116   in_loop--;
117   proc_pop_transformations (ds, &loop->xforms);
118
119   add_transformation (ds, &loop_trns_class, loop);
120
121   return ok ? CMD_SUCCESS : CMD_FAILURE;
122 }
123
124 int
125 cmd_inside_loop (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
126 {
127   msg (SE, _("This command cannot appear outside LOOP...END LOOP."));
128   return CMD_FAILURE;
129 }
130
131 static enum trns_result
132 break_trns_proc (void *aux UNUSED, struct ccase **c UNUSED,
133                  casenumber case_num UNUSED)
134 {
135   return TRNS_BREAK;
136 }
137
138 /* Parses BREAK. */
139 int
140 cmd_break (struct lexer *lexer, struct dataset *ds)
141 {
142   if (!in_loop)
143     {
144       cmd_inside_loop (lexer, ds);
145       return CMD_FAILURE;
146     }
147
148   static const struct trns_class trns_class = {
149     .name = "BREAK",
150     .execute = break_trns_proc
151   };
152   add_transformation (ds, &trns_class, NULL);
153
154   return CMD_SUCCESS;
155 }
156
157 /* Parses an IF clause for LOOP or END LOOP and stores the
158    resulting expression to *CONDITION.
159    Returns true if successful, false on failure. */
160 static bool
161 parse_if_clause (struct lexer *lexer, struct dataset *ds,
162                  struct expression **condition)
163 {
164   if (*condition != NULL)
165     {
166       lex_sbc_only_once ("IF");
167       return false;
168     }
169
170   *condition = expr_parse_bool (lexer, ds);
171   return *condition != NULL;
172 }
173
174 /* Parses an indexing clause into LOOP.  Returns true if successful, false on
175    failure. */
176 static bool
177 parse_index_clause (struct dataset *ds, struct lexer *lexer,
178                     struct loop_trns *loop)
179 {
180   if (loop->index_var != NULL)
181     {
182       msg (SE, _("Only one index clause may be specified."));
183       return false;
184     }
185
186   if (lex_token (lexer) != T_ID)
187     {
188       lex_error (lexer, NULL);
189       return false;
190     }
191
192   loop->index_var = dict_lookup_var (dataset_dict (ds), lex_tokcstr (lexer));
193   if (!loop->index_var)
194     loop->index_var = dict_create_var_assert (dataset_dict (ds),
195                                               lex_tokcstr (lexer), 0);
196   lex_get (lexer);
197
198   if (!lex_force_match (lexer, T_EQUALS))
199     return false;
200
201   loop->first_expr = expr_parse (lexer, ds, VAL_NUMERIC);
202   if (loop->first_expr == NULL)
203     return false;
204
205   for (;;)
206     {
207       struct expression **e;
208       if (lex_match (lexer, T_TO))
209         e = &loop->last_expr;
210       else if (lex_match (lexer, T_BY))
211         e = &loop->by_expr;
212       else
213         break;
214
215       if (*e != NULL)
216         {
217           lex_sbc_only_once (e == &loop->last_expr ? "TO" : "BY");
218           return false;
219         }
220       *e = expr_parse (lexer, ds, VAL_NUMERIC);
221       if (*e == NULL)
222         return false;
223     }
224   if (loop->last_expr == NULL)
225     {
226       lex_sbc_missing ("TO");
227       return false;
228     }
229
230   return true;
231 }
232
233 /* Sets up LOOP for the first pass. */
234 static enum trns_result
235 loop_trns_proc (void *loop_, struct ccase **c, casenumber case_num)
236 {
237   struct loop_trns *loop = loop_;
238
239   size_t start_idx = loop->resume_idx;
240   loop->resume_idx = SIZE_MAX;
241   if (start_idx != SIZE_MAX)
242     goto resume;
243
244   if (loop->index_var)
245     {
246       /* Evaluate loop index expressions. */
247       loop->cur = expr_evaluate_num (loop->first_expr, *c, case_num);
248       loop->by = (loop->by_expr
249                   ? expr_evaluate_num (loop->by_expr, *c, case_num)
250                   : 1.0);
251       loop->last = expr_evaluate_num (loop->last_expr, *c, case_num);
252
253       /* Even if the loop is never entered, set the index
254          variable to the initial value. */
255       *c = case_unshare (*c);
256       *case_num_rw (*c, loop->index_var) = loop->cur;
257
258       /* Throw out pathological cases. */
259       if (!isfinite (loop->cur)
260           || !isfinite (loop->by)
261           || !isfinite (loop->last)
262           || loop->by == 0.0
263           || (loop->by > 0.0 && loop->cur > loop->last)
264           || (loop->by < 0.0 && loop->cur < loop->last))
265         return TRNS_CONTINUE;
266     }
267
268   for (loop->iteration = 0;
269        loop->index_var || loop->iteration < settings_get_mxloops ();
270        loop->iteration++)
271     {
272       if (loop->loop_condition
273           && expr_evaluate_num (loop->loop_condition, *c, case_num) != 1.0)
274         break;
275
276       start_idx = 0;
277     resume:
278       for (size_t i = start_idx; i < loop->xforms.n; i++)
279         {
280           const struct transformation *trns = &loop->xforms.xforms[i];
281           enum trns_result r = trns->class->execute (trns->aux, c, case_num);
282           switch (r)
283             {
284             case TRNS_CONTINUE:
285               break;
286
287             case TRNS_BREAK:
288               return TRNS_CONTINUE;
289
290             case TRNS_END_CASE:
291               loop->resume_idx = i;
292               return TRNS_END_CASE;
293
294             case TRNS_ERROR:
295             case TRNS_END_FILE:
296               return r;
297
298             case TRNS_DROP_CASE:
299               NOT_REACHED ();
300             }
301         }
302
303       if (loop->end_loop_condition != NULL
304           && expr_evaluate_num (loop->end_loop_condition, *c, case_num) != 0.0)
305         break;
306
307       if (loop->index_var)
308         {
309           loop->cur += loop->by;
310           if (loop->by > 0.0 ? loop->cur > loop->last : loop->cur < loop->last)
311             break;
312
313           *c = case_unshare (*c);
314           *case_num_rw (*c, loop->index_var) = loop->cur;
315         }
316     }
317   return TRNS_CONTINUE;
318 }
319
320 /* Frees LOOP. */
321 static bool
322 loop_trns_free (void *loop_)
323 {
324   struct loop_trns *loop = loop_;
325
326   expr_free (loop->first_expr);
327   expr_free (loop->by_expr);
328   expr_free (loop->last_expr);
329
330   expr_free (loop->loop_condition);
331   expr_free (loop->end_loop_condition);
332
333   trns_chain_uninit (&loop->xforms);
334
335   free (loop);
336   return true;
337 }
338
339 static struct trns_class loop_trns_class = {
340   .name = "LOOP",
341   .execute = loop_trns_proc,
342   .destroy = loop_trns_free,
343 };