bae0e4afb103d7e1838c27616abe7055198f64a7
[pspp-builds.git] / src / language / control / repeat.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010 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 "repeat.h"
20
21 #include <ctype.h>
22 #include <math.h>
23 #include <stdlib.h>
24
25 #include <data/dictionary.h>
26 #include <data/procedure.h>
27 #include <data/settings.h>
28 #include <libpspp/getl.h>
29 #include <language/command.h>
30 #include <language/lexer/lexer.h>
31 #include <language/lexer/variable-parser.h>
32 #include <libpspp/cast.h>
33 #include <libpspp/ll.h>
34 #include <libpspp/message.h>
35 #include <libpspp/misc.h>
36 #include <libpspp/pool.h>
37 #include <libpspp/str.h>
38 #include <data/variable.h>
39
40 #include "intprops.h"
41 #include "xalloc.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* A line repeated by DO REPEAT. */
47 struct repeat_line
48   {
49     struct ll ll;               /* In struct repeat_block line_list. */
50     const char *file_name;      /* File name. */
51     int line_number;            /* Line number. */
52     struct substring text;      /* Contents. */
53   };
54
55 /* The type of substitution made for a DO REPEAT macro. */
56 enum repeat_macro_type
57   {
58     VAR_NAMES,
59     OTHER
60   };
61
62 /* Describes one DO REPEAT macro. */
63 struct repeat_macro
64   {
65     struct ll ll;                       /* In struct repeat_block macros. */
66     enum repeat_macro_type type;        /* Types of replacements. */
67     struct substring name;              /* Macro name. */
68     struct substring *replacements;     /* Macro replacement. */
69   };
70
71 /* A DO REPEAT...END REPEAT block. */
72 struct repeat_block
73   {
74     struct getl_interface parent;
75
76     struct pool *pool;                  /* Pool used for storage. */
77     struct dataset *ds;                 /* The dataset for this block */
78
79     struct ll_list lines;               /* Lines in buffer. */
80     struct ll *cur_line;                /* Last line output. */
81     int loop_cnt;                       /* Number of loops. */
82     int loop_idx;                       /* Number of loops so far. */
83
84     struct ll_list macros;              /* Table of macros. */
85
86     bool print;                         /* Print lines as executed? */
87   };
88
89 static bool parse_specification (struct lexer *, struct repeat_block *);
90 static bool parse_lines (struct lexer *, struct repeat_block *);
91 static void create_vars (struct repeat_block *);
92
93 static struct repeat_macro *find_macro (struct repeat_block *,
94                                         struct substring name);
95
96 static int parse_ids (struct lexer *, const struct dictionary *dict,
97                       struct repeat_macro *, struct pool *);
98
99 static int parse_numbers (struct lexer *, struct repeat_macro *,
100                           struct pool *);
101
102 static int parse_strings (struct lexer *, struct repeat_macro *,
103                           struct pool *);
104
105 static void do_repeat_filter (struct getl_interface *,
106                               struct string *);
107 static bool do_repeat_read (struct getl_interface *,
108                             struct string *);
109 static void do_repeat_close (struct getl_interface *);
110 static bool always_false (const struct getl_interface *);
111 static const char *do_repeat_name (const struct getl_interface *);
112 static int do_repeat_location (const struct getl_interface *);
113
114 int
115 cmd_do_repeat (struct lexer *lexer, struct dataset *ds)
116 {
117   struct repeat_block *block;
118
119   block = pool_create_container (struct repeat_block, pool);
120   block->ds = ds;
121   ll_init (&block->lines);
122   block->cur_line = ll_null (&block->lines);
123   block->loop_idx = 0;
124   ll_init (&block->macros);
125
126   if (!parse_specification (lexer, block) || !parse_lines (lexer, block))
127     goto error;
128
129   create_vars (block);
130
131   block->parent.read = do_repeat_read;
132   block->parent.close = do_repeat_close;
133   block->parent.filter = do_repeat_filter;
134   block->parent.interactive = always_false;
135   block->parent.name = do_repeat_name;
136   block->parent.location = do_repeat_location;
137
138   if (!ll_is_empty (&block->lines))
139     getl_include_source (lex_get_source_stream (lexer),
140                          &block->parent,
141                          lex_current_syntax_mode (lexer),
142                          lex_current_error_mode (lexer)
143                          );
144   else
145     pool_destroy (block->pool);
146
147   return CMD_SUCCESS;
148
149  error:
150   pool_destroy (block->pool);
151   return CMD_CASCADING_FAILURE;
152 }
153
154 /* Parses the whole DO REPEAT command specification.
155    Returns success. */
156 static bool
157 parse_specification (struct lexer *lexer, struct repeat_block *block)
158 {
159   struct substring first_name;
160
161   block->loop_cnt = 0;
162   do
163     {
164       struct repeat_macro *macro;
165       struct dictionary *dict = dataset_dict (block->ds);
166       int count;
167
168       /* Get a stand-in variable name and make sure it's unique. */
169       if (!lex_force_id (lexer))
170         return false;
171       if (dict_lookup_var (dict, lex_tokid (lexer)))
172         msg (SW, _("Dummy variable name `%s' hides dictionary "
173                    "variable `%s'."),
174              lex_tokid (lexer), lex_tokid (lexer));
175       if (find_macro (block, ss_cstr (lex_tokid (lexer))))
176           {
177             msg (SE, _("Dummy variable name `%s' is given twice."),
178                  lex_tokid (lexer));
179             return false;
180           }
181
182       /* Make a new macro. */
183       macro = pool_alloc (block->pool, sizeof *macro);
184       ss_alloc_substring_pool (&macro->name, ss_cstr (lex_tokid (lexer)),
185                                block->pool);
186       ll_push_tail (&block->macros, &macro->ll);
187
188       /* Skip equals sign. */
189       lex_get (lexer);
190       if (!lex_force_match (lexer, '='))
191         return false;
192
193       /* Get the details of the variable's possible values. */
194       if (lex_token (lexer) == T_ID)
195         count = parse_ids (lexer, dict, macro, block->pool);
196       else if (lex_is_number (lexer))
197         count = parse_numbers (lexer, macro, block->pool);
198       else if (lex_is_string (lexer))
199         count = parse_strings (lexer, macro, block->pool);
200       else
201         {
202           lex_error (lexer, NULL);
203           return false;
204         }
205       if (count == 0)
206         return false;
207       if (lex_token (lexer) != '/' && lex_token (lexer) != '.')
208         {
209           lex_error (lexer, NULL);
210           return false;
211         }
212
213       /* If this is the first variable then it defines how many
214          replacements there must be; otherwise enforce this number of
215          replacements. */
216       if (block->loop_cnt == 0)
217         {
218           block->loop_cnt = count;
219           first_name = macro->name;
220         }
221       else if (block->loop_cnt != count)
222         {
223           msg (SE, _("Dummy variable `%.*s' had %d "
224                      "substitutions, so `%.*s' must also, but %d "
225                      "were specified."),
226                (int) ss_length (first_name), ss_data (first_name),
227                block->loop_cnt,
228                (int) ss_length (macro->name), ss_data (macro->name),
229                count);
230           return false;
231         }
232
233       lex_match (lexer, '/');
234     }
235   while (lex_token (lexer) != '.');
236
237   return true;
238 }
239
240 /* Finds and returns a DO REPEAT macro with the given NAME, or
241    NULL if there is none */
242 static struct repeat_macro *
243 find_macro (struct repeat_block *block, struct substring name)
244 {
245   struct repeat_macro *macro;
246
247   ll_for_each (macro, struct repeat_macro, ll, &block->macros)
248     if (ss_equals (macro->name, name))
249       return macro;
250
251   return NULL;
252 }
253
254 /* Advances LINE past white space and an identifier, if present.
255    Returns true if KEYWORD matches the identifer, false
256    otherwise. */
257 static bool
258 recognize_keyword (struct substring *line, const char *keyword)
259 {
260   struct substring id;
261   ss_ltrim (line, ss_cstr (CC_SPACES));
262   ss_get_bytes (line, lex_id_get_length (*line), &id);
263   return lex_id_match (ss_cstr (keyword), id);
264 }
265
266 /* Returns true if LINE contains a DO REPEAT command, false
267    otherwise. */
268 static bool
269 recognize_do_repeat (struct substring line)
270 {
271   return (recognize_keyword (&line, "do")
272           && recognize_keyword (&line, "repeat"));
273 }
274
275 /* Returns true if LINE contains an END REPEAT command, false
276    otherwise.  Sets *PRINT to true for END REPEAT PRINT, false
277    otherwise. */
278 static bool
279 recognize_end_repeat (struct substring line, bool *print)
280 {
281   if (!recognize_keyword (&line, "end")
282       || !recognize_keyword (&line, "repeat"))
283     return false;
284
285   *print = recognize_keyword (&line, "print");
286   return true;
287 }
288
289 /* Read all the lines we are going to substitute, inside the DO
290    REPEAT...END REPEAT block. */
291 static bool
292 parse_lines (struct lexer *lexer, struct repeat_block *block)
293 {
294   char *previous_file_name;
295   int nesting_level;
296
297   previous_file_name = NULL;
298   nesting_level = 0;
299
300   for (;;)
301     {
302       const char *cur_file_name;
303       struct repeat_line *line;
304       struct string text;
305       bool command_ends_before_line, command_ends_after_line;
306
307       /* Retrieve an input line and make a copy of it. */
308       if (!lex_get_line_raw (lexer))
309         {
310           msg (SE, _("DO REPEAT without END REPEAT."));
311           return false;
312         }
313       ds_init_string (&text, lex_entire_line_ds (lexer));
314
315       /* Record file name. */
316       cur_file_name = getl_source_name (lex_get_source_stream (lexer));
317       if (cur_file_name != NULL &&
318           (previous_file_name == NULL
319            || !strcmp (cur_file_name, previous_file_name)))
320         previous_file_name = pool_strdup (block->pool, cur_file_name);
321
322       /* Create a line structure. */
323       line = pool_alloc (block->pool, sizeof *line);
324       line->file_name = previous_file_name;
325       line->line_number = getl_source_location (lex_get_source_stream (lexer));
326       ss_alloc_substring_pool (&line->text, ds_ss (&text), block->pool);
327
328
329       /* Check whether the line contains a DO REPEAT or END
330          REPEAT command. */
331       lex_preprocess_line (&text,
332                            lex_current_syntax_mode (lexer),
333                            &command_ends_before_line,
334                            &command_ends_after_line);
335       if (recognize_do_repeat (ds_ss (&text)))
336         {
337           if (settings_get_syntax () == COMPATIBLE)
338             msg (SE, _("DO REPEAT may not nest in compatibility mode."));
339           else
340             nesting_level++;
341         }
342       else if (recognize_end_repeat (ds_ss (&text), &block->print)
343                && nesting_level-- == 0)
344         {
345           lex_discard_line (lexer);
346           ds_destroy (&text);
347           return true;
348         }
349       ds_destroy (&text);
350
351       /* Add the line to the list. */
352       ll_push_tail (&block->lines, &line->ll);
353     }
354 }
355
356 /* Creates variables for the given DO REPEAT. */
357 static void
358 create_vars (struct repeat_block *block)
359 {
360   struct repeat_macro *macro;
361
362   ll_for_each (macro, struct repeat_macro, ll, &block->macros)
363     if (macro->type == VAR_NAMES)
364       {
365         int i;
366
367         for (i = 0; i < block->loop_cnt; i++)
368           {
369             /* Ignore return value: if the variable already
370                exists there is no harm done. */
371             char *var_name = ss_xstrdup (macro->replacements[i]);
372             dict_create_var (dataset_dict (block->ds), var_name, 0);
373             free (var_name);
374           }
375       }
376 }
377
378 /* Parses a set of ids for DO REPEAT. */
379 static int
380 parse_ids (struct lexer *lexer, const struct dictionary *dict,
381            struct repeat_macro *macro, struct pool *pool)
382 {
383   char **replacements;
384   size_t n, i;
385
386   macro->type = VAR_NAMES;
387   if (!parse_mixed_vars_pool (lexer, dict, pool, &replacements, &n, PV_NONE))
388     return 0;
389
390   macro->replacements = pool_nalloc (pool, n, sizeof *macro->replacements);
391   for (i = 0; i < n; i++)
392     macro->replacements[i] = ss_cstr (replacements[i]);
393   return n;
394 }
395
396 /* Adds REPLACEMENT to MACRO's list of replacements, which has
397    *USED elements and has room for *ALLOCATED.  Allocates memory
398    from POOL. */
399 static void
400 add_replacement (struct substring replacement,
401                  struct repeat_macro *macro, struct pool *pool,
402                  size_t *used, size_t *allocated)
403 {
404   if (*used == *allocated)
405     macro->replacements = pool_2nrealloc (pool, macro->replacements, allocated,
406                                           sizeof *macro->replacements);
407   macro->replacements[(*used)++] = replacement;
408 }
409
410 /* Parses a list or range of numbers for DO REPEAT. */
411 static int
412 parse_numbers (struct lexer *lexer, struct repeat_macro *macro,
413                struct pool *pool)
414 {
415   size_t used = 0;
416   size_t allocated = 0;
417
418   macro->type = OTHER;
419   macro->replacements = NULL;
420
421   do
422     {
423       bool integer_value_seen;
424       double a, b, i;
425
426       /* Parse A TO B into a, b. */
427       if (!lex_force_num (lexer))
428         return 0;
429
430       if ( (integer_value_seen = lex_is_integer (lexer) ) )
431         a = lex_integer (lexer);
432       else
433         a = lex_number (lexer);
434
435       lex_get (lexer);
436       if (lex_token (lexer) == T_TO)
437         {
438           if ( !integer_value_seen )
439             {
440               msg (SE, _("Ranges may only have integer bounds"));
441               return 0;
442             }
443           lex_get (lexer);
444           if (!lex_force_int (lexer))
445             return 0;
446           b = lex_integer (lexer);
447           if (b < a)
448             {
449               msg (SE, _("%g TO %g is an invalid range."), a, b);
450               return 0;
451             }
452           lex_get (lexer);
453         }
454       else
455         b = a;
456
457       for (i = a; i <= b; i++)
458         add_replacement (ss_cstr (pool_asprintf (pool, "%g", i)),
459                          macro, pool, &used, &allocated);
460
461       lex_match (lexer, ',');
462     }
463   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
464
465   return used;
466 }
467
468 /* Parses a list of strings for DO REPEAT. */
469 int
470 parse_strings (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
471 {
472   size_t used = 0;
473   size_t allocated = 0;
474
475   macro->type = OTHER;
476   macro->replacements = NULL;
477
478   do
479     {
480       char *string;
481
482       if (!lex_force_string (lexer))
483         {
484           msg (SE, _("String expected."));
485           return 0;
486         }
487
488       string = lex_token_representation (lexer);
489       pool_register (pool, free, string);
490       add_replacement (ss_cstr (string), macro, pool, &used, &allocated);
491
492       lex_get (lexer);
493       lex_match (lexer, ',');
494     }
495   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
496
497   return used;
498 }
499 \f
500 int
501 cmd_end_repeat (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
502 {
503   msg (SE, _("No matching DO REPEAT."));
504   return CMD_CASCADING_FAILURE;
505 }
506 \f
507 /* Finds a DO REPEAT macro with the given NAME and returns the
508    appropriate substitution if found, or NAME otherwise. */
509 static struct substring
510 find_substitution (struct repeat_block *block, struct substring name)
511 {
512   struct repeat_macro *macro = find_macro (block, name);
513   return macro ? macro->replacements[block->loop_idx] : name;
514 }
515
516 /* Makes appropriate DO REPEAT macro substitutions within the
517    repeated lines. */
518 static void
519 do_repeat_filter (struct getl_interface *interface, struct string *line)
520 {
521   struct repeat_block *block
522     = UP_CAST (interface, struct repeat_block, parent);
523   bool in_apos, in_quote, dot;
524   struct substring input;
525   struct string output;
526   int c;
527
528   ds_init_empty (&output);
529
530   /* Strip trailing whitespace, check for & remove terminal dot. */
531   ds_rtrim (line, ss_cstr (CC_SPACES));
532   dot = ds_chomp (line, settings_get_endcmd ());
533   input = ds_ss (line);
534   in_apos = in_quote = false;
535   while ((c = ss_first (input)) != EOF)
536     {
537       if (c == '\'' && !in_quote)
538         in_apos = !in_apos;
539       else if (c == '"' && !in_apos)
540         in_quote = !in_quote;
541
542       if (in_quote || in_apos || !lex_is_id1 (c))
543         {
544           ds_put_byte (&output, c);
545           ss_advance (&input, 1);
546         }
547       else
548         {
549           struct substring id;
550           ss_get_bytes (&input, lex_id_get_length (input), &id);
551           ds_put_substring (&output, find_substitution (block, id));
552         }
553     }
554   if (dot)
555     ds_put_byte (&output, settings_get_endcmd ());
556
557   ds_swap (line, &output);
558   ds_destroy (&output);
559 }
560
561 static struct repeat_line *
562 current_line (const struct getl_interface *interface)
563 {
564   struct repeat_block *block
565     = UP_CAST (interface, struct repeat_block, parent);
566   return (block->cur_line != ll_null (&block->lines)
567           ? ll_data (block->cur_line, struct repeat_line, ll)
568           : NULL);
569 }
570
571 /* Function called by getl to read a line.  Puts the line in
572    OUTPUT and its syntax mode in *SYNTAX.  Returns true if a line
573    was obtained, false if the source is exhausted. */
574 static bool
575 do_repeat_read  (struct getl_interface *interface,
576                  struct string *output)
577 {
578   struct repeat_block *block
579     = UP_CAST (interface, struct repeat_block, parent);
580   struct repeat_line *line;
581
582   block->cur_line = ll_next (block->cur_line);
583   if (block->cur_line == ll_null (&block->lines))
584     {
585       block->loop_idx++;
586       if (block->loop_idx >= block->loop_cnt)
587         return false;
588
589       block->cur_line = ll_head (&block->lines);
590     }
591
592   line = current_line (interface);
593   ds_assign_substring (output, line->text);
594   return true;
595 }
596
597 /* Frees a DO REPEAT block.
598    Called by getl to close out the DO REPEAT block. */
599 static void
600 do_repeat_close (struct getl_interface *interface)
601 {
602   struct repeat_block *block
603     = UP_CAST (interface, struct repeat_block, parent);
604   pool_destroy (block->pool);
605 }
606
607
608 static bool
609 always_false (const struct getl_interface *i UNUSED)
610 {
611   return false;
612 }
613
614 /* Returns the name of the source file from which the previous
615    line was originally obtained, or a null pointer if none. */
616 static const char *
617 do_repeat_name (const struct getl_interface *interface)
618 {
619   struct repeat_line *line = current_line (interface);
620   return line ? line->file_name : NULL;
621 }
622
623 /* Returns the line number in the source file from which the
624    previous line was originally obtained, or 0 if none. */
625 static int
626 do_repeat_location (const struct getl_interface *interface)
627 {
628   struct repeat_line *line = current_line (interface);
629   return line ? line->line_number : 0;
630 }