5a1ad08ddb743ba2a0e2e99674757eb791d4beea
[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 (lex_get_source_stream (lexer), &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 (lex_get_source_stream (lexer));
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 (lex_get_source_stream (lexer));
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         {
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 of numbers for DO REPEAT. */
407 static int
408 parse_numbers (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
409 {
410   size_t used = 0;
411   size_t allocated = 0;
412   
413   macro->type = OTHER;
414   macro->replacements = NULL;
415
416   do
417     {
418       long a, b, i;
419
420       /* Parse A TO B into a, b. */
421       if (!lex_force_int (lexer))
422         return 0;
423       a = lex_integer (lexer);
424
425       lex_get (lexer);
426       if (lex_token (lexer) == T_TO)
427         {
428           lex_get (lexer);
429           if (!lex_force_int (lexer))
430             return 0;
431           b = lex_integer (lexer);
432           if (b < a) 
433             {
434               msg (SE, _("%ld TO %ld is an invalid range."), a, b);
435               return 0;
436             }
437           lex_get (lexer);
438         }
439       else
440         b = a;
441
442       for (i = a; i <= b; i++)
443         add_replacement (ss_cstr (pool_asprintf (pool, "%ld", i)),
444                          macro, pool, &used, &allocated);
445
446       lex_match (lexer, ',');
447     }
448   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
449
450   return used;
451 }
452
453 /* Parses a list of strings for DO REPEAT. */
454 int
455 parse_strings (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
456 {
457   size_t used = 0;
458   size_t allocated = 0;
459   
460   macro->type = OTHER;
461   macro->replacements = NULL;
462
463   do
464     {
465       char *string;
466       
467       if (lex_token (lexer) != T_STRING)
468         {
469           msg (SE, _("String expected."));
470           return 0;
471         }
472
473       string = lex_token_representation (lexer);
474       pool_register (pool, free, string);
475       add_replacement (ss_cstr (string), macro, pool, &used, &allocated);
476
477       lex_get (lexer);
478       lex_match (lexer, ',');
479     }
480   while (lex_token (lexer) != '/' && lex_token (lexer) != '.');
481
482   return used;
483 }
484 \f
485 int
486 cmd_end_repeat (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
487 {
488   msg (SE, _("No matching DO REPEAT."));
489   return CMD_CASCADING_FAILURE;
490 }
491 \f
492 /* Finds a DO REPEAT macro with the given NAME and returns the
493    appropriate substitution if found, or NAME otherwise. */
494 static struct substring
495 find_substitution (struct repeat_block *block, struct substring name)
496 {
497   struct repeat_macro *macro = find_macro (block, name);
498   return macro ? macro->replacements[block->loop_idx] : name;
499 }
500
501 /* Makes appropriate DO REPEAT macro substitutions within the 
502    repeated lines. */
503 static void
504 do_repeat_filter (struct getl_interface *block_,
505                   struct string *line, enum getl_syntax syntax UNUSED)
506 {
507   struct repeat_block *block = (struct repeat_block *) block_;
508   bool in_apos, in_quote, dot;
509   struct substring input;
510   struct string output;
511   int c;
512
513   ds_init_empty (&output);
514
515   /* Strip trailing whitespace, check for & remove terminal dot. */
516   ds_rtrim (line, ss_cstr (CC_SPACES));
517   dot = ds_chomp (line, get_endcmd ());
518
519   input = ds_ss (line);
520   in_apos = in_quote = false;
521   while ((c = ss_first (input)) != EOF)
522     {
523       if (c == '\'' && !in_quote)
524         in_apos = !in_apos;
525       else if (c == '"' && !in_apos)
526         in_quote = !in_quote;
527       
528       if (in_quote || in_apos || !lex_is_id1 (c)) 
529         {
530           ds_put_char (&output, c);
531           ss_advance (&input, 1); 
532         }
533       else 
534         {
535           struct substring id;
536           ss_get_chars (&input, lex_id_get_length (input), &id);
537           ds_put_substring (&output, find_substitution (block, id));
538         }
539     }
540   if (dot)
541     ds_put_char (&output, get_endcmd ());
542
543   ds_swap (line, &output);
544   ds_destroy (&output);
545 }
546
547 static struct repeat_line *
548 current_line (const struct getl_interface *interface) 
549 {
550   struct repeat_block *block = (struct repeat_block *) interface;
551   return (block->cur_line != ll_null (&block->lines)
552           ? ll_data (block->cur_line, struct repeat_line, ll)
553           : NULL);
554 }
555
556 /* Function called by getl to read a line.  Puts the line in
557    OUTPUT and its syntax mode in *SYNTAX.  Returns true if a line
558    was obtained, false if the source is exhausted. */
559 static bool  
560 do_repeat_read  (struct getl_interface *interface,
561                  struct string *output, enum getl_syntax *syntax)
562 {
563   struct repeat_block *block = (struct repeat_block *) interface;
564   struct repeat_line *line;
565
566   block->cur_line = ll_next (block->cur_line);
567   if (block->cur_line == ll_null (&block->lines)) 
568     {
569       block->loop_idx++;
570       if (block->loop_idx >= block->loop_cnt)
571         return false;
572
573       block->cur_line = ll_head (&block->lines);
574     }
575
576   line = current_line (interface);
577   ds_assign_substring (output, line->text);
578   *syntax = line->syntax;
579   return true;
580 }
581
582 /* Frees a DO REPEAT block.
583    Called by getl to close out the DO REPEAT block. */
584 static void
585 do_repeat_close (struct getl_interface *block_)
586 {
587   struct repeat_block *block = (struct repeat_block *) block_;
588   pool_destroy (block->pool);
589 }
590
591
592 static bool 
593 always_false (const struct getl_interface *i UNUSED)
594 {
595   return false;
596 }
597
598 /* Returns the name of the source file from which the previous
599    line was originally obtained, or a null pointer if none. */
600 static const char *
601 do_repeat_name (const struct getl_interface *interface) 
602 {
603   struct repeat_line *line = current_line (interface);
604   return line ? line->file_name : NULL;
605 }
606
607 /* Returns the line number in the source file from which the
608    previous line was originally obtained, or -1 if none. */
609 static int
610 do_repeat_location (const struct getl_interface *interface) 
611 {
612   struct repeat_line *line = current_line (interface);
613   return line ? line->line_number : -1;
614 }