005ba8ba2054a7d9580b7ac136c715659002a139
[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         lex_msg (lexer, SW,
121                  _("Dummy variable name `%s' hides dictionary variable `%s'."),
122                  name, name);
123
124       size_t name_len = strlen (name);
125       if (find_dummy_var (dummies, name, name_len))
126         {
127           lex_error (lexer, _("Dummy variable name `%s' is given twice."),
128                      name);
129           goto error;
130         }
131
132       /* Make a new macro. */
133       dv = xmalloc (sizeof *dv);
134       dv->name = xmemdup0 (name, name_len);
135       dv->name_len = name_len;
136       dv->values = NULL;
137       dv->n_values = 0;
138       hmap_insert (dummies, &dv->hmap_node, hash_dummy (name, strlen (name)));
139
140       /* Skip equals sign. */
141       lex_get (lexer);
142       if (!lex_force_match (lexer, T_EQUALS))
143         goto error;
144
145       /* Get the details of the variable's possible values. */
146       if (lex_token (lexer) == T_ID || lex_token (lexer) == T_ALL)
147         ok = parse_ids (lexer, dict, dv);
148       else if (lex_is_number (lexer))
149         ok = parse_numbers (lexer, dv);
150       else if (lex_is_string (lexer))
151         ok = parse_strings (lexer, dv);
152       else
153         {
154           lex_error (lexer, NULL);
155           goto error;
156         }
157       if (!ok)
158         goto error;
159       assert (dv->n_values > 0);
160       if (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD)
161         {
162           lex_error (lexer, NULL);
163           goto error;
164         }
165
166       /* If this is the first variable then it defines how many replacements
167          there must be; otherwise enforce this number of replacements. */
168       if (first_dv == NULL)
169         first_dv = dv;
170       else if (first_dv->n_values != dv->n_values)
171         {
172           msg (SE, _("Dummy variable `%s' had %zu substitutions, so `%s' must "
173                      "also, but %zu were specified."),
174                first_dv->name, first_dv->n_values,
175                dv->name, dv->n_values);
176           goto error;
177         }
178
179       lex_match (lexer, T_SLASH);
180     }
181   while (!lex_match (lexer, T_ENDCMD));
182
183   while (lex_match (lexer, T_ENDCMD))
184     continue;
185
186   return true;
187
188 error:
189   destroy_dummies (dummies);
190   return false;
191 }
192
193 static size_t
194 count_values (struct hmap *dummies)
195 {
196   const struct dummy_var *dv;
197   dv = HMAP_FIRST (struct dummy_var, hmap_node, dummies);
198   return dv->n_values;
199 }
200
201 static void
202 do_parse_commands (struct substring s, enum segmenter_mode mode,
203                    struct hmap *dummies,
204                    struct string *outputs, size_t n_outputs)
205 {
206   struct segmenter segmenter = segmenter_init (mode, false);
207   while (!ss_is_empty (s))
208     {
209       enum segment_type type;
210       int n;
211
212       n = segmenter_push (&segmenter, s.string, s.length, true, &type);
213       assert (n >= 0);
214
215       if (type == SEG_DO_REPEAT_COMMAND)
216         {
217           for (;;)
218             {
219               int k;
220
221               k = segmenter_push (&segmenter, s.string + n, s.length - n,
222                                   true, &type);
223               if (type != SEG_NEWLINE && type != SEG_DO_REPEAT_COMMAND)
224                 break;
225
226               n += k;
227             }
228
229           do_parse_commands (ss_head (s, n), mode, dummies,
230                              outputs, n_outputs);
231         }
232       else if (type != SEG_END)
233         {
234           const struct dummy_var *dv;
235           size_t i;
236
237           dv = (type == SEG_IDENTIFIER
238                 ? find_dummy_var (dummies, s.string, n)
239                 : NULL);
240           for (i = 0; i < n_outputs; i++)
241             if (dv != NULL)
242               ds_put_cstr (&outputs[i], dv->values[i]);
243             else
244               ds_put_substring (&outputs[i], ss_head (s, n));
245         }
246
247       ss_advance (&s, n);
248     }
249 }
250
251 static bool
252 parse_commands (struct lexer *lexer, struct hmap *dummies)
253 {
254   struct string *outputs;
255   struct string input;
256   size_t n_values;
257   char *file_name;
258   bool ok;
259   size_t i;
260
261   if (lex_get_file_name (lexer) != NULL)
262     file_name = xstrdup (lex_get_file_name (lexer));
263   else
264     file_name = NULL;
265   int line_number = lex_ofs_start_point (lexer, lex_ofs (lexer)).line;
266
267   ds_init_empty (&input);
268   while (lex_is_string (lexer))
269     {
270       ds_put_substring (&input, lex_tokss (lexer));
271       ds_put_byte (&input, '\n');
272       lex_get (lexer);
273     }
274
275   n_values = count_values (dummies);
276   outputs = xmalloc (n_values * sizeof *outputs);
277   for (i = 0; i < n_values; i++)
278     ds_init_empty (&outputs[i]);
279
280   do_parse_commands (ds_ss (&input), lex_get_syntax_mode (lexer),
281                      dummies, outputs, n_values);
282
283   ds_destroy (&input);
284
285   while (lex_match (lexer, T_ENDCMD))
286     continue;
287
288   ok = (lex_force_match_id (lexer, "END")
289         && lex_force_match_id (lexer, "REPEAT"));
290   if (ok)
291     lex_match_id (lexer, "PRINT"); /* XXX */
292
293   lex_discard_rest_of_command (lexer);
294
295   for (i = 0; i < n_values; i++)
296     {
297       struct string *output = &outputs[n_values - i - 1];
298       const char *encoding = lex_get_encoding (lexer);
299       struct lex_reader *reader = lex_reader_for_substring_nocopy (ds_ss (output), encoding);
300       lex_reader_set_file_name (reader, file_name);
301       reader->line_number = line_number;
302       lex_include (lexer, reader);
303     }
304   free (file_name);
305   free (outputs);
306
307   return ok;
308 }
309
310 static void
311 destroy_dummies (struct hmap *dummies)
312 {
313   struct dummy_var *dv, *next;
314
315   HMAP_FOR_EACH_SAFE (dv, next, struct dummy_var, hmap_node, dummies)
316     {
317       size_t i;
318
319       hmap_delete (dummies, &dv->hmap_node);
320
321       free (dv->name);
322       for (i = 0; i < dv->n_values; i++)
323         free (dv->values[i]);
324       free (dv->values);
325       free (dv);
326     }
327   hmap_destroy (dummies);
328 }
329
330 /* Parses a set of ids for DO REPEAT. */
331 static bool
332 parse_ids (struct lexer *lexer, const struct dictionary *dict,
333            struct dummy_var *dv)
334 {
335   return parse_mixed_vars (lexer, dict, &dv->values, &dv->n_values, PV_NONE);
336 }
337
338 /* Adds REPLACEMENT to MACRO's list of replacements, which has
339    *USED elements and has room for *ALLOCATED.  Allocates memory
340    from POOL. */
341 static void
342 add_replacement (struct dummy_var *dv, char *value, size_t *allocated)
343 {
344   if (dv->n_values == *allocated)
345     dv->values = x2nrealloc (dv->values, allocated, sizeof *dv->values);
346   dv->values[dv->n_values++] = value;
347 }
348
349 /* Parses a list or range of numbers for DO REPEAT. */
350 static bool
351 parse_numbers (struct lexer *lexer, struct dummy_var *dv)
352 {
353   size_t allocated = 0;
354
355   do
356     {
357       if (!lex_force_num (lexer))
358         return false;
359
360       if (lex_next_token (lexer, 1) == T_TO)
361         {
362           if (!lex_is_integer (lexer))
363             {
364               lex_error (lexer, _("Ranges may only have integer bounds."));
365               return false;
366             }
367
368           long a = lex_integer (lexer);
369           lex_get (lexer);
370           lex_get (lexer);
371
372           if (!lex_force_int_range (lexer, NULL, a, LONG_MAX))
373             return false;
374
375           long b = lex_integer (lexer);
376           if (b < a)
377             {
378               lex_next_error (lexer, -2, 0,
379                               _("%ld TO %ld is an invalid range."), a, b);
380               return false;
381             }
382           lex_get (lexer);
383
384           for (long 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           c_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           return false;
414         }
415
416       add_replacement (dv, token_to_string (lex_next (lexer, 0)), &allocated);
417
418       lex_get (lexer);
419       lex_match (lexer, T_COMMA);
420     }
421   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD);
422
423   return true;
424 }
425 \f
426 int
427 cmd_end_repeat (struct lexer *lexer, struct dataset *ds UNUSED)
428 {
429   lex_ofs_error (lexer, 0, 1, _("No matching %s."), "DO REPEAT");
430   return CMD_CASCADING_FAILURE;
431 }