bba14c6c7bdb3c1bd6febb6a50a99498a0f9d152
[pspp-builds.git] / src / language / control / repeat.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include "repeat.h"
22 #include "message.h"
23 #include <ctype.h>
24 #include <math.h>
25 #include <stdlib.h>
26 #include "alloc.h"
27 #include "command.h"
28 #include "dictionary.h"
29 #include "message.h"
30 #include "line-buffer.h"
31 #include "lexer.h"
32 #include "misc.h"
33 #include "pool.h"
34 #include "settings.h"
35 #include "str.h"
36 #include "variable.h"
37
38 #include "gettext.h"
39 #define _(msgid) gettext (msgid)
40
41 #include "debug-print.h"
42
43 /* Defines a list of lines used by DO REPEAT. */
44 struct line_list
45   {
46     struct line_list *next;     /* Next line. */
47     char *file_name;            /* File name. */
48     int line_number;            /* Line number. */
49     char *line;                 /* Contents. */
50   };
51
52 /* The type of substitution made for a DO REPEAT macro. */
53 enum repeat_entry_type 
54   {
55     VAR_NAMES,
56     OTHER
57   };
58
59 /* Describes one DO REPEAT macro. */
60 struct repeat_entry
61   {
62     struct repeat_entry *next;          /* Next entry. */
63     enum repeat_entry_type type;        /* Types of replacements. */
64     char id[LONG_NAME_LEN + 1];         /* Macro identifier. */
65     char **replacement;                 /* Macro replacement. */
66   };
67
68 /* A DO REPEAT...END REPEAT block. */
69 struct repeat_block 
70   {
71     struct pool *pool;                  /* Pool used for storage. */
72     struct line_list *first_line;       /* First line in line buffer. */
73     struct line_list *cur_line;         /* Current line in line buffer. */
74     int loop_cnt;                       /* Number of loops. */
75     int loop_idx;                       /* Number of loops so far. */
76     struct repeat_entry *macros;        /* Pointer to macro table. */
77     bool print;                         /* Print lines as executed? */
78   };
79
80 static bool parse_specification (struct repeat_block *);
81 static bool parse_lines (struct repeat_block *);
82 static void create_vars (struct repeat_block *);
83
84 static int parse_ids (struct repeat_entry *);
85 static int parse_numbers (struct repeat_entry *);
86 static int parse_strings (struct repeat_entry *);
87
88 static void do_repeat_filter (struct string *line, void *block);
89 static bool do_repeat_read (struct string *line, char **file_name,
90                             int *line_number, void *block);
91 static void do_repeat_close (void *block);
92
93 int
94 cmd_do_repeat (void)
95 {
96   struct repeat_block *block;
97
98   block = pool_create_container (struct repeat_block, pool);
99
100   if (!parse_specification (block) || !parse_lines (block))
101     goto error;
102   
103   create_vars (block);
104   
105   block->cur_line = NULL;
106   block->loop_idx = -1;
107   getl_include_filter (do_repeat_filter, do_repeat_close, block);
108   getl_include_function (do_repeat_read, NULL, block);
109
110   return CMD_SUCCESS;
111
112  error:
113   pool_destroy (block->pool);
114   return CMD_CASCADING_FAILURE;
115 }
116
117 /* Parses the whole DO REPEAT command specification.
118    Returns success. */
119 static bool
120 parse_specification (struct repeat_block *block) 
121 {
122   char first_name[LONG_NAME_LEN + 1];
123
124   block->loop_cnt = 0;
125   block->macros = NULL;
126   do
127     {
128       struct repeat_entry *e;
129       struct repeat_entry *iter;
130       int count;
131
132       /* Get a stand-in variable name and make sure it's unique. */
133       if (!lex_force_id ())
134         return false;
135       if (dict_lookup_var (default_dict, tokid))
136         msg (SW, _("Dummy variable name \"%s\" hides dictionary "
137                    "variable \"%s\"."),
138              tokid, tokid);
139       for (iter = block->macros; iter != NULL; iter = iter->next)
140         if (!strcasecmp (iter->id, tokid))
141           {
142             msg (SE, _("Dummy variable name \"%s\" is given twice."), tokid);
143             return false;
144           }
145
146       /* Make a new stand-in variable entry and link it into the
147          list. */
148       e = pool_alloc (block->pool, sizeof *e);
149       e->next = block->macros;
150       strcpy (e->id, tokid);
151       block->macros = e;
152
153       /* Skip equals sign. */
154       lex_get ();
155       if (!lex_force_match ('='))
156         return false;
157
158       /* Get the details of the variable's possible values. */
159       if (token == T_ID)
160         count = parse_ids (e);
161       else if (lex_is_number ())
162         count = parse_numbers (e);
163       else if (token == T_STRING)
164         count = parse_strings (e);
165       else
166         {
167           lex_error (NULL);
168           return false;
169         }
170       if (count == 0)
171         return false;
172
173       /* If this is the first variable then it defines how many
174          replacements there must be; otherwise enforce this number of
175          replacements. */
176       if (block->loop_cnt == 0)
177         {
178           block->loop_cnt = count;
179           strcpy (first_name, e->id);
180         }
181       else if (block->loop_cnt != count)
182         {
183           msg (SE, _("Dummy variable \"%s\" had %d "
184                      "substitutions, so \"%s\" must also, but %d "
185                      "were specified."),
186                first_name, block->loop_cnt, e->id, count);
187           return false;
188         }
189
190       lex_match ('/');
191     }
192   while (token != '.');
193
194   return true;
195 }
196
197 /* If KEYWORD appears beginning at CP, possibly preceded by white
198    space, returns a pointer to the character just after the
199    keyword.  Otherwise, returns a null pointer. */
200 static const char *
201 recognize_keyword (const char *cp, const char *keyword)
202 {
203   const char *end;
204
205   while (isspace ((unsigned char) *cp))
206     cp++;
207
208   end = lex_skip_identifier (cp);
209   if (end != cp
210       && lex_id_match_len (keyword, strlen (keyword), cp, end - cp))
211     return end;
212   else
213     return NULL;
214 }
215
216 /* Returns CP, advanced past a '+' or '-' if present. */
217 static const char *
218 skip_indentor (const char *cp) 
219 {
220   if (*cp == '+' || *cp == '-')
221     cp++;
222   return cp;
223 }
224
225 /* Returns true if LINE contains a DO REPEAT command, false
226    otherwise. */
227 static bool
228 recognize_do_repeat (const char *line) 
229 {
230   const char *cp = recognize_keyword (skip_indentor (line), "do");
231   return cp != NULL && recognize_keyword (cp, "repeat") != NULL;
232 }
233
234 /* Returns true if LINE contains an END REPEAT command, false
235    otherwise.  Sets *PRINT to true for END REPEAT PRINT, false
236    otherwise. */
237 static bool
238 recognize_end_repeat (const char *line, bool *print)
239 {
240   const char *cp = recognize_keyword (skip_indentor (line), "end");
241   if (cp == NULL)
242     return false;
243
244   cp = recognize_keyword (cp, "repeat");
245   if (cp == NULL) 
246     return false; 
247
248   *print = recognize_keyword (cp, "print");
249   return true; 
250 }
251
252 /* Read all the lines we are going to substitute, inside the DO
253    REPEAT...END REPEAT block. */
254 static bool
255 parse_lines (struct repeat_block *block) 
256 {
257   char *previous_file_name;
258   struct line_list **last_line;
259   int nesting_level;
260
261   previous_file_name = NULL;
262   block->first_line = NULL;
263   last_line = &block->first_line;
264   nesting_level = 0;
265
266   for (;;)
267     {
268       const char *cur_file_name;
269       int cur_line_number;
270       struct line_list *line;
271       bool dot;
272
273       if (!getl_read_line (NULL))
274         return false;
275
276       /* If the current file has changed then record the fact. */
277       getl_location (&cur_file_name, &cur_line_number);
278       if (previous_file_name == NULL 
279           || !strcmp (cur_file_name, previous_file_name))
280         previous_file_name = pool_strdup (block->pool, cur_file_name);
281
282       ds_rtrim_spaces (&getl_buf);
283       dot = ds_chomp (&getl_buf, get_endcmd ());
284       if (recognize_do_repeat (ds_c_str (&getl_buf))) 
285         nesting_level++; 
286       else if (recognize_end_repeat (ds_c_str (&getl_buf), &block->print)) 
287         {
288         if (nesting_level-- == 0)
289           {
290             lex_discard_line ();
291             return true;
292           } 
293         }
294       if (dot)
295         ds_putc (&getl_buf, get_endcmd ());
296       
297       line = *last_line = pool_alloc (block->pool, sizeof *line);
298       line->next = NULL;
299       line->file_name = previous_file_name;
300       line->line_number = cur_line_number;
301       line->line = pool_strdup (block->pool, ds_c_str (&getl_buf));
302       last_line = &line->next;
303     }
304
305   lex_discard_line ();
306   return true;
307 }
308
309 /* Creates variables for the given DO REPEAT. */
310 static void
311 create_vars (struct repeat_block *block)
312 {
313   struct repeat_entry *iter;
314  
315   for (iter = block->macros; iter; iter = iter->next)
316     if (iter->type == VAR_NAMES)
317       {
318         int i;
319
320         for (i = 0; i < block->loop_cnt; i++)
321           {
322             /* Ignore return value: if the variable already
323                exists there is no harm done. */
324             dict_create_var (default_dict, iter->replacement[i], 0);
325           }
326       }
327 }
328
329 /* Parses a set of ids for DO REPEAT. */
330 static int
331 parse_ids (struct repeat_entry *e)
332 {
333   size_t i;
334   size_t n = 0;
335
336   e->type = VAR_NAMES;
337   e->replacement = NULL;
338
339   do
340     {
341       char **names;
342       size_t nnames;
343
344       if (!parse_mixed_vars (&names, &nnames, PV_NONE))
345         return 0;
346
347       e->replacement = xnrealloc (e->replacement,
348                                   nnames + n, sizeof *e->replacement);
349       for (i = 0; i < nnames; i++)
350         {
351           e->replacement[n + i] = xstrdup (names[i]);
352           free (names[i]);
353         }
354       free (names);
355       n += nnames;
356     }
357   while (token != '/' && token != '.');
358
359   return n;
360 }
361
362 /* Stores VALUE into *REPL. */
363 static inline void
364 store_numeric (char **repl, long value)
365 {
366   *repl = xmalloc (INT_DIGITS + 1);
367   sprintf (*repl, "%ld", value);
368 }
369
370 /* Parses a list of numbers for DO REPEAT. */
371 static int
372 parse_numbers (struct repeat_entry *e)
373 {
374   /* First and last numbers for TO, plus the step factor. */
375   long a, b;
376
377   /* Alias to e->replacement. */
378   char **array;
379
380   /* Number of entries in array; maximum number for this allocation
381      size. */
382   int n, m;
383
384   n = m = 0;
385   e->type = OTHER;
386   e->replacement = array = NULL;
387
388   do
389     {
390       /* Parse A TO B into a, b. */
391       if (!lex_force_int ())
392         return 0;
393       a = lex_integer ();
394
395       lex_get ();
396       if (token == T_TO)
397         {
398           lex_get ();
399           if (!lex_force_int ())
400             return 0;
401           b = lex_integer ();
402
403           lex_get ();
404         }
405       else b = a;
406
407       if (n + (abs (b - a) + 1) > m)
408         {
409           m = n + (abs (b - a) + 1) + 16;
410           e->replacement = array = xnrealloc (array,
411                                               m, sizeof *e->replacement);
412         }
413
414       if (a == b)
415         store_numeric (&array[n++], a);
416       else
417         {
418           long iter;
419
420           if (a < b)
421             for (iter = a; iter <= b; iter++)
422               store_numeric (&array[n++], iter);
423           else
424             for (iter = a; iter >= b; iter--)
425               store_numeric (&array[n++], iter);
426         }
427
428       lex_match (',');
429     }
430   while (token != '/' && token != '.');
431   e->replacement = xrealloc (array, n * sizeof *e->replacement);
432
433   return n;
434 }
435
436 /* Parses a list of strings for DO REPEAT. */
437 int
438 parse_strings (struct repeat_entry *e)
439 {
440   char **string;
441   int n, m;
442
443   e->type = OTHER;
444   string = e->replacement = NULL;
445   n = m = 0;
446
447   do
448     {
449       if (token != T_STRING)
450         {
451           int i;
452           msg (SE, _("String expected."));
453           for (i = 0; i < n; i++)
454             free (string[i]);
455           free (string);
456           return 0;
457         }
458
459       if (n + 1 > m)
460         {
461           m += 16;
462           e->replacement = string = xnrealloc (string,
463                                                m, sizeof *e->replacement);
464         }
465       string[n++] = lex_token_representation ();
466       lex_get ();
467
468       lex_match (',');
469     }
470   while (token != '/' && token != '.');
471   e->replacement = xnrealloc (string, n, sizeof *e->replacement);
472
473   return n;
474 }
475 \f
476 int
477 cmd_end_repeat (void)
478 {
479   msg (SE, _("No matching DO REPEAT."));
480   return CMD_CASCADING_FAILURE;
481 }
482 \f
483 /* Finds a DO REPEAT macro with name MACRO_NAME and returns the
484    appropriate subsitution if found, or NULL if not. */
485 static char *
486 find_substitution (struct repeat_block *block, const char *name, size_t length)
487 {
488   struct repeat_entry *e;
489
490   for (e = block->macros; e; e = e->next)
491     if (!memcasecmp (e->id, name, length) && strlen (e->id) == length)
492       return e->replacement[block->loop_idx];
493   
494   return NULL;
495 }
496
497 /* Makes appropriate DO REPEAT macro substitutions within getl_buf. */
498 static void
499 do_repeat_filter (struct string *line, void *block_)
500 {
501   struct repeat_block *block = block_;
502   bool in_apos, in_quote;
503   char *cp;
504   struct string output;
505   bool dot;
506
507   ds_init (&output, ds_capacity (line));
508
509   /* Strip trailing whitespace, check for & remove terminal dot. */
510   while (isspace (ds_last (line)))
511     ds_truncate (line, ds_length (line) - 1);
512   dot = ds_chomp (line, get_endcmd ());
513
514   in_apos = in_quote = false;
515   for (cp = ds_c_str (line); cp < ds_end (line); )
516     {
517       if (*cp == '\'' && !in_quote)
518         in_apos = !in_apos;
519       else if (*cp == '"' && !in_apos)
520         in_quote = !in_quote;
521       
522       if (in_quote || in_apos || !lex_is_id1 (*cp))
523         ds_putc (&output, *cp++);
524       else 
525         {
526           const char *start = cp;
527           char *end = lex_skip_identifier (start);
528           const char *substitution = find_substitution (block,
529                                                         start, end - start);
530           if (substitution != NULL) 
531             ds_puts (&output, substitution);
532           else
533             ds_concat (&output, start, end - start);
534           cp = end;
535         }
536     }
537   if (dot)
538     ds_putc (&output, get_endcmd ());
539
540   ds_swap (line, &output);
541   ds_destroy (&output);
542 }
543
544 /* Function called by getl to read a line.
545    Puts the line in OUTPUT, sets the file name in *FILE_NAME and
546    line number in *LINE_NUMBER.  Returns true if a line was
547    obtained, false if the source is exhausted. */
548 static bool
549 do_repeat_read (struct string *output, char **file_name, int *line_number,
550                 void *block_) 
551 {
552   struct repeat_block *block = block_;
553   struct line_list *line;
554
555   if (block->cur_line == NULL) 
556     {
557       block->loop_idx++;
558       if (block->loop_idx >= block->loop_cnt)
559         return false;
560       block->cur_line = block->first_line;
561     }
562   line = block->cur_line;
563
564   ds_replace (output, line->line);
565   *file_name = line->file_name;
566   *line_number = -line->line_number;
567   block->cur_line = line->next;
568   return true;
569 }
570
571 /* Frees a DO REPEAT block.
572    Called by getl to close out the DO REPEAT block. */
573 static void
574 do_repeat_close (void *block_)
575 {
576   struct repeat_block *block = block_;
577   pool_destroy (block->pool);
578 }