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