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