c0fa8fe0d8dfe165deb6f55968f17ed512d9b46f
[pspp-builds.git] / src / language / control / repeat.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 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 <stdlib.h>
20
21 #include "data/dictionary.h"
22 #include "data/procedure.h"
23 #include "language/command.h"
24 #include "language/lexer/lexer.h"
25 #include "language/lexer/segment.h"
26 #include "language/lexer/token.h"
27 #include "language/lexer/variable-parser.h"
28 #include "libpspp/cast.h"
29 #include "libpspp/hash-functions.h"
30 #include "libpspp/hmap.h"
31 #include "libpspp/message.h"
32 #include "libpspp/str.h"
33
34 #include "gl/ftoastr.h"
35 #include "gl/minmax.h"
36 #include "gl/xalloc.h"
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40
41 struct dummy_var
42   {
43     struct hmap_node hmap_node;
44     char *name;
45     char **values;
46     size_t n_values;
47   };
48
49 static bool parse_specification (struct lexer *, struct dictionary *,
50                                  struct hmap *dummies);
51 static bool parse_commands (struct lexer *, struct hmap *dummies);
52 static void destroy_dummies (struct hmap *dummies);
53
54 static bool parse_ids (struct lexer *, const struct dictionary *,
55                        struct dummy_var *);
56 static bool parse_numbers (struct lexer *, struct dummy_var *);
57 static bool parse_strings (struct lexer *, struct dummy_var *);
58
59 int
60 cmd_do_repeat (struct lexer *lexer, struct dataset *ds)
61 {
62   struct hmap dummies;
63   bool ok;
64
65   if (!parse_specification (lexer, dataset_dict (ds), &dummies))
66     return CMD_CASCADING_FAILURE;
67
68   ok = parse_commands (lexer, &dummies);
69
70   destroy_dummies (&dummies);
71
72   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
73 }
74
75 static unsigned int
76 hash_dummy (const char *name, size_t name_len)
77 {
78   return hash_case_bytes (name, name_len, 0);
79 }
80
81 static const struct dummy_var *
82 find_dummy_var (struct hmap *hmap, const char *name, size_t name_len)
83 {
84   const struct dummy_var *dv;
85
86   HMAP_FOR_EACH_WITH_HASH (dv, struct dummy_var, hmap_node,
87                            hash_dummy (name, name_len), hmap)
88     if (strcasecmp (dv->name, name))
89       return dv;
90
91   return NULL;
92 }
93
94 /* Parses the whole DO REPEAT command specification.
95    Returns success. */
96 static bool
97 parse_specification (struct lexer *lexer, struct dictionary *dict,
98                      struct hmap *dummies)
99 {
100   struct dummy_var *first_dv = NULL;
101
102   hmap_init (dummies);
103   do
104     {
105       struct dummy_var *dv;
106       const char *name;
107       bool ok;
108
109       /* Get a stand-in variable name and make sure it's unique. */
110       if (!lex_force_id (lexer))
111         goto error;
112       name = lex_tokcstr (lexer);
113       if (dict_lookup_var (dict, name))
114         msg (SW, _("Dummy variable name `%s' hides dictionary variable `%s'."),
115              name, name);
116       if (find_dummy_var (dummies, name, strlen (name)))
117         {
118           msg (SE, _("Dummy variable name `%s' is given twice."), name);
119           goto error;
120         }
121
122       /* Make a new macro. */
123       dv = xmalloc (sizeof *dv);
124       dv->name = xstrdup (name);
125       dv->values = NULL;
126       dv->n_values = 0;
127       hmap_insert (dummies, &dv->hmap_node, hash_dummy (name, strlen (name)));
128
129       /* Skip equals sign. */
130       lex_get (lexer);
131       if (!lex_force_match (lexer, T_EQUALS))
132         goto error;
133
134       /* Get the details of the variable's possible values. */
135       if (lex_token (lexer) == T_ID || lex_token (lexer) == T_ALL)
136         ok = parse_ids (lexer, dict, dv);
137       else if (lex_is_number (lexer))
138         ok = parse_numbers (lexer, dv);
139       else if (lex_is_string (lexer))
140         ok = parse_strings (lexer, dv);
141       else
142         {
143           lex_error (lexer, NULL);
144           goto error;
145         }
146       if (!ok)
147         goto error;
148       assert (dv->n_values > 0);
149       if (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
150         {
151           lex_error (lexer, NULL);
152           goto error;
153         }
154
155       /* If this is the first variable then it defines how many replacements
156          there must be; otherwise enforce this number of replacements. */
157       if (first_dv == NULL)
158         first_dv = dv;
159       else if (first_dv->n_values != dv->n_values)
160         {
161           msg (SE, _("Dummy variable `%s' had %d substitutions, so `%s' must "
162                      "also, but %d were specified."),
163                first_dv->name, first_dv->n_values,
164                dv->name, dv->n_values);
165           goto error;
166         }
167
168       lex_match (lexer, T_SLASH);
169     }
170   while (!lex_match (lexer, T_ENDCMD));
171
172   while (lex_match (lexer, T_ENDCMD))
173     continue;
174
175   return true;
176
177 error:
178   destroy_dummies (dummies);
179   return false;
180 }
181
182 static size_t
183 count_values (struct hmap *dummies)
184 {
185   const struct dummy_var *dv;
186   dv = HMAP_FIRST (struct dummy_var, hmap_node, dummies);
187   return dv->n_values;
188 }
189
190 static void
191 do_parse_commands (struct substring s, enum lex_syntax_mode syntax_mode,
192                    struct hmap *dummies,
193                    struct string *outputs, size_t n_outputs)
194 {
195   struct segmenter segmenter;
196
197   segmenter_init (&segmenter, syntax_mode);
198
199   while (!ss_is_empty (s))
200     {
201       enum segment_type type;
202       int n;
203
204       n = segmenter_push (&segmenter, s.string, s.length, &type);
205       assert (n >= 0);
206
207       if (type == SEG_DO_REPEAT_COMMAND)
208         {
209           for (;;)
210             {
211               int k;
212
213               k = segmenter_push (&segmenter, s.string + n, s.length - n,
214                                   &type);
215               if (type != SEG_NEWLINE && type != SEG_DO_REPEAT_COMMAND)
216                 break;
217
218               n += k;
219             }
220
221           do_parse_commands (ss_head (s, n), syntax_mode, dummies,
222                              outputs, n_outputs);
223         }
224       else if (type != SEG_END)
225         {
226           const struct dummy_var *dv;
227           size_t i;
228
229           dv = (type == SEG_IDENTIFIER
230                 ? find_dummy_var (dummies, s.string, n)
231                 : NULL);
232           for (i = 0; i < n_outputs; i++)
233             if (dv != NULL)
234               ds_put_cstr (&outputs[i], dv->values[i]);
235             else
236               ds_put_substring (&outputs[i], ss_head (s, n));
237         }
238
239       ss_advance (&s, n);
240     }
241 }
242
243 static bool
244 parse_commands (struct lexer *lexer, struct hmap *dummies)
245 {
246   struct string *outputs;
247   struct string input;
248   size_t input_len;
249   size_t n_values;
250   char *file_name;
251   int line_number;
252   bool ok;
253   size_t i;
254
255   if (lex_get_file_name (lexer) != NULL)
256     file_name = xstrdup (lex_get_file_name (lexer));
257   else
258     file_name = NULL;
259   line_number = lex_get_first_line_number (lexer, 0);
260
261   ds_init_empty (&input);
262   while (lex_is_string (lexer))
263     {
264       ds_put_substring (&input, lex_tokss (lexer));
265       ds_put_byte (&input, '\n');
266       lex_get (lexer);
267     }
268   if (ds_is_empty (&input))
269     ds_put_byte (&input, '\n');
270   ds_put_byte (&input, '\0');
271   input_len = ds_length (&input);
272
273   n_values = count_values (dummies);
274   outputs = xmalloc (n_values * sizeof *outputs);
275   for (i = 0; i < n_values; i++)
276     ds_init_empty (&outputs[i]);
277
278   do_parse_commands (ds_ss (&input), lex_get_syntax_mode (lexer),
279                      dummies, outputs, n_values);
280
281   ds_destroy (&input);
282
283   while (lex_match (lexer, T_ENDCMD))
284     continue;
285
286   ok = (lex_force_match_id (lexer, "END")
287         && lex_force_match_id (lexer, "REPEAT"));
288   if (ok)
289     lex_match_id (lexer, "PRINT"); /* XXX */
290
291   lex_discard_rest_of_command (lexer);
292
293   for (i = 0; i < n_values; i++)
294     {
295       struct string *output = &outputs[n_values - i - 1];
296       struct lex_reader *reader;
297
298       reader = lex_reader_for_substring_nocopy (ds_ss (output));
299       lex_reader_set_file_name (reader, file_name);
300       reader->line_number = line_number;
301       lex_include (lexer, reader);
302     }
303   free (file_name);
304
305   return ok;
306 }
307
308 static void
309 destroy_dummies (struct hmap *dummies)
310 {
311   struct dummy_var *dv, *next;
312
313   HMAP_FOR_EACH_SAFE (dv, next, struct dummy_var, hmap_node, dummies)
314     {
315       size_t i;
316
317       hmap_delete (dummies, &dv->hmap_node);
318
319       free (dv->name);
320       for (i = 0; i < dv->n_values; i++)
321         free (dv->values[i]);
322       free (dv->values);
323       free (dv);
324     }
325   hmap_destroy (dummies);
326 }
327
328 /* Parses a set of ids for DO REPEAT. */
329 static bool
330 parse_ids (struct lexer *lexer, const struct dictionary *dict,
331            struct dummy_var *dv)
332 {
333   return parse_mixed_vars (lexer, dict, &dv->values, &dv->n_values, PV_NONE);
334 }
335
336 /* Adds REPLACEMENT to MACRO's list of replacements, which has
337    *USED elements and has room for *ALLOCATED.  Allocates memory
338    from POOL. */
339 static void
340 add_replacement (struct dummy_var *dv, char *value, size_t *allocated)
341 {
342   if (dv->n_values == *allocated)
343     dv->values = x2nrealloc (dv->values, allocated, sizeof *dv->values);
344   dv->values[dv->n_values++] = value;
345 }
346
347 /* Parses a list or range of numbers for DO REPEAT. */
348 static bool
349 parse_numbers (struct lexer *lexer, struct dummy_var *dv)
350 {
351   size_t allocated = 0;
352
353   do
354     {
355       if (!lex_force_num (lexer))
356         return false;
357
358       if (lex_next_token (lexer, 1) == T_TO)
359         {
360           long int a, b;
361           long int i;
362
363           if (!lex_is_integer (lexer))
364             {
365               msg (SE, _("Ranges may only have integer bounds."));
366               return false;
367             }
368
369           a = lex_integer (lexer);
370           lex_get (lexer);
371           lex_get (lexer);
372
373           if (!lex_force_int (lexer))
374             return false;
375
376           b = lex_integer (lexer);
377           if (b < a)
378             {
379               msg (SE, _("%ld TO %ld is an invalid range."), a, b);
380               return false;
381             }
382           lex_get (lexer);
383
384           for (i = a; i <= b; i++)
385             add_replacement (dv, xasprintf ("%ld", i), &allocated);
386         }
387       else
388         {
389           char s[DBL_BUFSIZE_BOUND];
390
391           dtoastr (s, sizeof s, 0, 0, lex_number (lexer));
392           add_replacement (dv, xstrdup (s), &allocated);
393           lex_get (lexer);
394         }
395
396       lex_match (lexer, T_COMMA);
397     }
398   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD);
399
400   return true;
401 }
402
403 /* Parses a list of strings for DO REPEAT. */
404 static bool
405 parse_strings (struct lexer *lexer, struct dummy_var *dv)
406 {
407   size_t allocated = 0;
408
409   do
410     {
411       if (!lex_force_string (lexer))
412         {
413           msg (SE, _("String expected."));
414           return false;
415         }
416
417       add_replacement (dv, token_to_string (lex_next (lexer, 0)), &allocated);
418
419       lex_get (lexer);
420       lex_match (lexer, T_COMMA);
421     }
422   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD);
423
424   return true;
425 }
426 \f
427 int
428 cmd_end_repeat (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
429 {
430   msg (SE, _("No matching DO REPEAT."));
431   return CMD_CASCADING_FAILURE;
432 }