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