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