Fix lack of ->name and ->location in DO REPEAT's getl_interface.
[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 <libpspp/getl.h>
32 #include <language/command.h>
33 #include <language/lexer/lexer.h>
34 #include <language/lexer/variable-parser.h>
35 #include <libpspp/alloc.h>
36 #include <libpspp/ll.h>
37 #include <libpspp/message.h>
38 #include <libpspp/misc.h>
39 #include <libpspp/pool.h>
40 #include <libpspp/str.h>
41 #include <data/variable.h>
42
43 #include "intprops.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47
48 /* A line repeated by DO REPEAT. */
49 struct repeat_line
50   {
51     struct ll ll;               /* In struct repeat_block line_list. */
52     const char *file_name;      /* File name. */
53     int line_number;            /* Line number. */
54     struct substring text;      /* Contents. */
55     enum getl_syntax syntax;    /* Syntax mode. */
56   };
57
58 /* The type of substitution made for a DO REPEAT macro. */
59 enum repeat_macro_type 
60   {
61     VAR_NAMES,
62     OTHER
63   };
64
65 /* Describes one DO REPEAT macro. */
66 struct repeat_macro
67   {
68     struct ll ll;                       /* In struct repeat_block macros. */
69     enum repeat_macro_type type;        /* Types of replacements. */
70     struct substring name;              /* Macro name. */
71     struct substring *replacements;     /* Macro replacement. */
72   };
73
74 /* A DO REPEAT...END REPEAT block. */
75 struct repeat_block 
76   {
77     struct getl_interface parent;
78
79     struct pool *pool;                  /* Pool used for storage. */
80     struct dataset *ds;                 /* The dataset for this block */
81
82     struct ll_list lines;               /* Lines in buffer. */
83     struct ll *cur_line;                /* Last line output. */
84     int loop_cnt;                       /* Number of loops. */
85     int loop_idx;                       /* Number of loops so far. */
86
87     struct ll_list macros;              /* Table of macros. */
88
89     bool print;                         /* Print lines as executed? */
90   };
91
92 static bool parse_specification (struct lexer *, struct repeat_block *);
93 static bool parse_lines (struct lexer *, struct repeat_block *);
94 static void create_vars (struct repeat_block *);
95
96 static struct repeat_macro *find_macro (struct repeat_block *,
97                                         struct substring name);
98
99 static int parse_ids (struct lexer *, const struct dictionary *dict, 
100                       struct repeat_macro *, struct pool *);
101
102 static int parse_numbers (struct lexer *, struct repeat_macro *, 
103                           struct pool *);
104
105 static int parse_strings (struct lexer *, struct repeat_macro *, 
106                           struct pool *);
107
108 static void do_repeat_filter (struct getl_interface *,
109                               struct string *, enum getl_syntax);
110 static bool do_repeat_read (struct getl_interface *,
111                             struct string *, enum getl_syntax *);
112 static void do_repeat_close (struct getl_interface *);
113 static bool always_false (const struct getl_interface *);
114 static const char *do_repeat_name (const struct getl_interface *);
115 static int do_repeat_location (const struct getl_interface *);
116
117 int
118 cmd_do_repeat (struct lexer *lexer, struct dataset *ds)
119 {
120   struct repeat_block *block;
121
122   block = pool_create_container (struct repeat_block, pool);
123   block->ds = ds;
124   ll_init (&block->lines);
125   block->cur_line = ll_null (&block->lines);
126   block->loop_idx = 0;
127   ll_init (&block->macros);
128
129   if (!parse_specification (lexer, block) || !parse_lines (lexer, block))
130     goto error;
131   
132   create_vars (block);
133
134   block->parent.read = do_repeat_read;
135   block->parent.close = do_repeat_close;
136   block->parent.filter = do_repeat_filter;
137   block->parent.interactive = always_false;
138   block->parent.name = do_repeat_name;
139   block->parent.location = do_repeat_location;
140
141   if (!ll_is_empty (&block->lines))
142     getl_include_source (&block->parent);
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       enum getl_syntax syntax;
305       bool command_ends_before_line, command_ends_after_line;
306
307       /* Retrieve an input line and make a copy of it. */
308       if (!lex_get_line_raw (lexer, &syntax))
309         return false;
310       ds_init_string (&text, lex_entire_line_ds (lexer));
311
312       /* Record file name. */
313       cur_file_name = getl_source_name ();
314       if (cur_file_name != NULL && 
315           (previous_file_name == NULL
316            || !strcmp (cur_file_name, previous_file_name)))
317         previous_file_name = pool_strdup (block->pool, cur_file_name);
318
319       /* Create a line structure. */
320       line = pool_alloc (block->pool, sizeof *line);
321       line->file_name = previous_file_name;
322       line->line_number = getl_source_location ();
323       ss_alloc_substring_pool (&line->text, ds_ss (&text), block->pool);
324       line->syntax = syntax;
325
326       /* Check whether the line contains a DO REPEAT or END
327          REPEAT command. */
328       lex_preprocess_line (&text, syntax,
329                            &command_ends_before_line,
330                            &command_ends_after_line);
331       if (recognize_do_repeat (ds_ss (&text)))
332         nesting_level++; 
333       else if (recognize_end_repeat (ds_ss (&text), &block->print)
334                && nesting_level-- == 0) 
335         {
336           lex_discard_line (lexer);
337           return true;
338         }
339       ds_destroy (&text);
340
341       /* Add the line to the list. */
342       ll_push_tail (&block->lines, &line->ll);
343     }
344 }
345
346 /* Creates variables for the given DO REPEAT. */
347 static void
348 create_vars (struct repeat_block *block)
349 {
350   struct repeat_macro *macro;
351   
352   ll_for_each (macro, struct repeat_macro, ll, &block->macros)
353     if (macro->type == VAR_NAMES)
354       {
355         int i;
356
357         for (i = 0; i < block->loop_cnt; i++)
358           {
359             /* Ignore return value: if the variable already
360                exists there is no harm done. */
361             char *var_name = ss_xstrdup (macro->replacements[i]);
362             dict_create_var (dataset_dict (block->ds), var_name, 0);
363             free (var_name);
364           }
365       }
366 }
367
368 /* Parses a set of ids for DO REPEAT. */
369 static int
370 parse_ids (struct lexer *lexer, const struct dictionary *dict, 
371            struct repeat_macro *macro, struct pool *pool)
372 {
373   char **replacements;
374   size_t n, i;
375   
376   macro->type = VAR_NAMES;
377   if (!parse_mixed_vars_pool (lexer, dict, pool, &replacements, &n, PV_NONE))
378     return 0;
379
380   macro->replacements = pool_nalloc (pool, n, sizeof *macro->replacements);
381   for (i = 0; i < n; i++)
382     macro->replacements[i] = ss_cstr (replacements[i]);
383   return n;
384 }
385
386 /* Adds REPLACEMENT to MACRO's list of replacements, which has
387    *USED elements and has room for *ALLOCATED.  Allocates memory
388    from POOL. */
389 static void
390 add_replacement (struct substring replacement,
391                  struct repeat_macro *macro, struct pool *pool,
392                  size_t *used, size_t *allocated) 
393 {
394   if (*used == *allocated)
395     macro->replacements = pool_2nrealloc (pool, macro->replacements, allocated,
396                                           sizeof *macro->replacements);
397   macro->replacements[(*used)++] = replacement;
398 }
399
400 /* Parses a list of numbers for DO REPEAT. */
401 static int
402 parse_numbers (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
403 {
404   size_t used = 0;
405   size_t allocated = 0;
406   
407   macro->type = OTHER;
408   macro->replacements = NULL;
409
410   do
411     {
412       long a, b, i;
413
414       /* Parse A TO B into a, b. */
415       if (!lex_force_int (lexer))
416         return 0;
417       a = lex_integer (lexer);
418
419       lex_get (lexer);
420       if (lex_token (lexer) == T_TO)
421         {
422           lex_get (lexer);
423           if (!lex_force_int (lexer))
424             return 0;
425           b = lex_integer (lexer);
426           if (b < a) 
427             {
428               msg (SE, _("%ld TO %ld is an invalid range."), a, b);
429               return 0;
430             }
431           lex_get (lexer);
432         }
433       else
434         b = a;
435
436       for (i = a; i <= b; i++)
437         add_replacement (ss_cstr (pool_asprintf (pool, "%ld", i)),
438                          macro, pool, &used, &allocated);
439
440       lex_match (lexer, ',');
441     }
442   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
443
444   return used;
445 }
446
447 /* Parses a list of strings for DO REPEAT. */
448 int
449 parse_strings (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
450 {
451   size_t used = 0;
452   size_t allocated = 0;
453   
454   macro->type = OTHER;
455   macro->replacements = NULL;
456
457   do
458     {
459       char *string;
460       
461       if (lex_token (lexer) != T_STRING)
462         {
463           msg (SE, _("String expected."));
464           return 0;
465         }
466
467       string = lex_token_representation (lexer);
468       pool_register (pool, free, string);
469       add_replacement (ss_cstr (string), macro, pool, &used, &allocated);
470
471       lex_get (lexer);
472       lex_match (lexer, ',');
473     }
474   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
475
476   return used;
477 }
478 \f
479 int
480 cmd_end_repeat (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
481 {
482   msg (SE, _("No matching DO REPEAT."));
483   return CMD_CASCADING_FAILURE;
484 }
485 \f
486 /* Finds a DO REPEAT macro with the given NAME and returns the
487    appropriate substitution if found, or NAME otherwise. */
488 static struct substring
489 find_substitution (struct repeat_block *block, struct substring name)
490 {
491   struct repeat_macro *macro = find_macro (block, name);
492   return macro ? macro->replacements[block->loop_idx] : name;
493 }
494
495 /* Makes appropriate DO REPEAT macro substitutions within the 
496    repeated lines. */
497 static void
498 do_repeat_filter (struct getl_interface *block_,
499                   struct string *line, enum getl_syntax syntax UNUSED)
500 {
501   struct repeat_block *block = (struct repeat_block *) block_;
502   bool in_apos, in_quote, dot;
503   struct substring input;
504   struct string output;
505   int c;
506
507   ds_init_empty (&output);
508
509   /* Strip trailing whitespace, check for & remove terminal dot. */
510   ds_rtrim (line, ss_cstr (CC_SPACES));
511   dot = ds_chomp (line, get_endcmd ());
512
513   input = ds_ss (line);
514   in_apos = in_quote = false;
515   while ((c = ss_first (input)) != EOF)
516     {
517       if (c == '\'' && !in_quote)
518         in_apos = !in_apos;
519       else if (c == '"' && !in_apos)
520         in_quote = !in_quote;
521       
522       if (in_quote || in_apos || !lex_is_id1 (c)) 
523         {
524           ds_put_char (&output, c);
525           ss_advance (&input, 1); 
526         }
527       else 
528         {
529           struct substring id;
530           ss_get_chars (&input, lex_id_get_length (input), &id);
531           ds_put_substring (&output, find_substitution (block, id));
532         }
533     }
534   if (dot)
535     ds_put_char (&output, get_endcmd ());
536
537   ds_swap (line, &output);
538   ds_destroy (&output);
539 }
540
541 static struct repeat_line *
542 current_line (const struct getl_interface *interface) 
543 {
544   struct repeat_block *block = (struct repeat_block *) interface;
545   return (block->cur_line != ll_null (&block->lines)
546           ? ll_data (block->cur_line, struct repeat_line, ll)
547           : NULL);
548 }
549
550 /* Function called by getl to read a line.  Puts the line in
551    OUTPUT and its syntax mode in *SYNTAX.  Returns true if a line
552    was obtained, false if the source is exhausted. */
553 static bool  
554 do_repeat_read  (struct getl_interface *interface,
555                  struct string *output, enum getl_syntax *syntax)
556 {
557   struct repeat_block *block = (struct repeat_block *) interface;
558   struct repeat_line *line;
559
560   block->cur_line = ll_next (block->cur_line);
561   if (block->cur_line == ll_null (&block->lines)) 
562     {
563       block->loop_idx++;
564       if (block->loop_idx >= block->loop_cnt)
565         return false;
566
567       block->cur_line = ll_head (&block->lines);
568     }
569
570   line = current_line (interface);
571   ds_assign_substring (output, line->text);
572   *syntax = line->syntax;
573   return true;
574 }
575
576 /* Frees a DO REPEAT block.
577    Called by getl to close out the DO REPEAT block. */
578 static void
579 do_repeat_close (struct getl_interface *block_)
580 {
581   struct repeat_block *block = (struct repeat_block *) block_;
582   pool_destroy (block->pool);
583 }
584
585
586 static bool 
587 always_false (const struct getl_interface *i UNUSED)
588 {
589   return false;
590 }
591
592 /* Returns the name of the source file from which the previous
593    line was originally obtained, or a null pointer if none. */
594 static const char *
595 do_repeat_name (const struct getl_interface *interface) 
596 {
597   struct repeat_line *line = current_line (interface);
598   return line ? line->file_name : NULL;
599 }
600
601 /* Returns the line number in the source file from which the
602    previous line was originally obtained, or -1 if none. */
603 static int
604 do_repeat_location (const struct getl_interface *interface) 
605 {
606   struct repeat_line *line = current_line (interface);
607   return line ? line->line_number : -1;
608 }