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