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