Update all #include directives to the currently preferred style.
[pspp-builds.git] / src / language / control / repeat.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU 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, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "language/control/repeat.h"
20
21 #include <ctype.h>
22 #include <math.h>
23 #include <stdlib.h>
24
25 #include "data/dictionary.h"
26 #include "data/procedure.h"
27 #include "data/settings.h"
28 #include "libpspp/getl.h"
29 #include "language/command.h"
30 #include "language/lexer/lexer.h"
31 #include "language/lexer/variable-parser.h"
32 #include "libpspp/cast.h"
33 #include "libpspp/ll.h"
34 #include "libpspp/message.h"
35 #include "libpspp/misc.h"
36 #include "libpspp/pool.h"
37 #include "libpspp/str.h"
38 #include "data/variable.h"
39
40 #include "gl/intprops.h"
41 #include "gl/xalloc.h"
42
43 #include "gettext.h"
44 #define _(msgid) gettext (msgid)
45
46 /* A line repeated by DO REPEAT. */
47 struct repeat_line
48   {
49     struct ll ll;               /* In struct repeat_block line_list. */
50     const char *file_name;      /* File name. */
51     int line_number;            /* Line number. */
52     struct substring text;      /* Contents. */
53   };
54
55 /* The type of substitution made for a DO REPEAT macro. */
56 enum repeat_macro_type
57   {
58     VAR_NAMES,
59     OTHER
60   };
61
62 /* Describes one DO REPEAT macro. */
63 struct repeat_macro
64   {
65     struct ll ll;                       /* In struct repeat_block macros. */
66     enum repeat_macro_type type;        /* Types of replacements. */
67     struct substring name;              /* Macro name. */
68     struct substring *replacements;     /* Macro replacement. */
69   };
70
71 /* A DO REPEAT...END REPEAT block. */
72 struct repeat_block
73   {
74     struct getl_interface parent;
75
76     struct pool *pool;                  /* Pool used for storage. */
77     struct dataset *ds;                 /* The dataset for this block */
78
79     struct ll_list lines;               /* Lines in buffer. */
80     struct ll *cur_line;                /* Last line output. */
81     int loop_cnt;                       /* Number of loops. */
82     int loop_idx;                       /* Number of loops so far. */
83
84     struct ll_list macros;              /* Table of macros. */
85
86     bool print;                         /* Print lines as executed? */
87   };
88
89 static bool parse_specification (struct lexer *, struct repeat_block *);
90 static bool parse_lines (struct lexer *, struct repeat_block *);
91 static void create_vars (struct repeat_block *);
92
93 static struct repeat_macro *find_macro (struct repeat_block *,
94                                         struct substring name);
95
96 static int parse_ids (struct lexer *, const struct dictionary *dict,
97                       struct repeat_macro *, struct pool *);
98
99 static int parse_numbers (struct lexer *, struct repeat_macro *,
100                           struct pool *);
101
102 static int parse_strings (struct lexer *, struct repeat_macro *,
103                           struct pool *);
104
105 static void do_repeat_filter (struct getl_interface *,
106                               struct string *);
107 static bool do_repeat_read (struct getl_interface *,
108                             struct string *);
109 static void do_repeat_close (struct getl_interface *);
110 static bool always_false (const struct getl_interface *);
111 static const char *do_repeat_name (const struct getl_interface *);
112 static int do_repeat_location (const struct getl_interface *);
113
114 int
115 cmd_do_repeat (struct lexer *lexer, struct dataset *ds)
116 {
117   struct repeat_block *block;
118
119   block = pool_create_container (struct repeat_block, pool);
120   block->ds = ds;
121   ll_init (&block->lines);
122   block->cur_line = ll_null (&block->lines);
123   block->loop_idx = 0;
124   ll_init (&block->macros);
125
126   if (!parse_specification (lexer, block) || !parse_lines (lexer, block))
127     goto error;
128
129   create_vars (block);
130
131   block->parent.read = do_repeat_read;
132   block->parent.close = do_repeat_close;
133   block->parent.filter = do_repeat_filter;
134   block->parent.interactive = always_false;
135   block->parent.name = do_repeat_name;
136   block->parent.location = do_repeat_location;
137
138   if (!ll_is_empty (&block->lines))
139     getl_include_source (lex_get_source_stream (lexer),
140                          &block->parent,
141                          lex_current_syntax_mode (lexer),
142                          lex_current_error_mode (lexer)
143                          );
144   else
145     pool_destroy (block->pool);
146
147   return CMD_SUCCESS;
148
149  error:
150   pool_destroy (block->pool);
151   return CMD_CASCADING_FAILURE;
152 }
153
154 /* Parses the whole DO REPEAT command specification.
155    Returns success. */
156 static bool
157 parse_specification (struct lexer *lexer, struct repeat_block *block)
158 {
159   struct substring first_name;
160
161   block->loop_cnt = 0;
162   do
163     {
164       struct repeat_macro *macro;
165       struct dictionary *dict = dataset_dict (block->ds);
166       int count;
167
168       /* Get a stand-in variable name and make sure it's unique. */
169       if (!lex_force_id (lexer))
170         return false;
171       if (dict_lookup_var (dict, lex_tokcstr (lexer)))
172         msg (SW, _("Dummy variable name `%s' hides dictionary variable `%s'."),
173              lex_tokcstr (lexer), lex_tokcstr (lexer));
174       if (find_macro (block, lex_tokss (lexer)))
175           {
176             msg (SE, _("Dummy variable name `%s' is given twice."),
177                  lex_tokcstr (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, lex_tokss (lexer), 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, T_EQUALS))
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_is_string (lexer))
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) != T_SLASH && lex_token (lexer) != T_ENDCMD)
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, T_SLASH);
232     }
233   while (lex_token (lexer) != T_ENDCMD);
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_bytes (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       bool command_ends_before_line, command_ends_after_line;
304
305       /* Retrieve an input line and make a copy of it. */
306       if (!lex_get_line_raw (lexer))
307         {
308           msg (SE, _("DO REPEAT without END REPEAT."));
309           return false;
310         }
311       ds_init_string (&text, lex_entire_line_ds (lexer));
312
313       /* Record file name. */
314       cur_file_name = getl_source_name (lex_get_source_stream (lexer));
315       if (cur_file_name != NULL &&
316           (previous_file_name == NULL
317            || !strcmp (cur_file_name, previous_file_name)))
318         previous_file_name = pool_strdup (block->pool, cur_file_name);
319
320       /* Create a line structure. */
321       line = pool_alloc (block->pool, sizeof *line);
322       line->file_name = previous_file_name;
323       line->line_number = getl_source_location (lex_get_source_stream (lexer));
324       ss_alloc_substring_pool (&line->text, ds_ss (&text), block->pool);
325
326
327       /* Check whether the line contains a DO REPEAT or END
328          REPEAT command. */
329       lex_preprocess_line (&text,
330                            lex_current_syntax_mode (lexer),
331                            &command_ends_before_line,
332                            &command_ends_after_line);
333       if (recognize_do_repeat (ds_ss (&text)))
334         {
335           if (settings_get_syntax () == COMPATIBLE)
336             msg (SE, _("DO REPEAT may not nest in compatibility mode."));
337           else
338             nesting_level++;
339         }
340       else if (recognize_end_repeat (ds_ss (&text), &block->print)
341                && nesting_level-- == 0)
342         {
343           lex_discard_line (lexer);
344           ds_destroy (&text);
345           return true;
346         }
347       ds_destroy (&text);
348
349       /* Add the line to the list. */
350       ll_push_tail (&block->lines, &line->ll);
351     }
352 }
353
354 /* Creates variables for the given DO REPEAT. */
355 static void
356 create_vars (struct repeat_block *block)
357 {
358   struct repeat_macro *macro;
359
360   ll_for_each (macro, struct repeat_macro, ll, &block->macros)
361     if (macro->type == VAR_NAMES)
362       {
363         int i;
364
365         for (i = 0; i < block->loop_cnt; i++)
366           {
367             /* Ignore return value: if the variable already
368                exists there is no harm done. */
369             char *var_name = ss_xstrdup (macro->replacements[i]);
370             dict_create_var (dataset_dict (block->ds), var_name, 0);
371             free (var_name);
372           }
373       }
374 }
375
376 /* Parses a set of ids for DO REPEAT. */
377 static int
378 parse_ids (struct lexer *lexer, const struct dictionary *dict,
379            struct repeat_macro *macro, struct pool *pool)
380 {
381   char **replacements;
382   size_t n, i;
383
384   macro->type = VAR_NAMES;
385   if (!parse_mixed_vars_pool (lexer, dict, pool, &replacements, &n, PV_NONE))
386     return 0;
387
388   macro->replacements = pool_nalloc (pool, n, sizeof *macro->replacements);
389   for (i = 0; i < n; i++)
390     macro->replacements[i] = ss_cstr (replacements[i]);
391   return n;
392 }
393
394 /* Adds REPLACEMENT to MACRO's list of replacements, which has
395    *USED elements and has room for *ALLOCATED.  Allocates memory
396    from POOL. */
397 static void
398 add_replacement (struct substring replacement,
399                  struct repeat_macro *macro, struct pool *pool,
400                  size_t *used, size_t *allocated)
401 {
402   if (*used == *allocated)
403     macro->replacements = pool_2nrealloc (pool, macro->replacements, allocated,
404                                           sizeof *macro->replacements);
405   macro->replacements[(*used)++] = replacement;
406 }
407
408 /* Parses a list or range of numbers for DO REPEAT. */
409 static int
410 parse_numbers (struct lexer *lexer, struct repeat_macro *macro,
411                struct pool *pool)
412 {
413   size_t used = 0;
414   size_t allocated = 0;
415
416   macro->type = OTHER;
417   macro->replacements = NULL;
418
419   do
420     {
421       bool integer_value_seen;
422       double a, b, i;
423
424       /* Parse A TO B into a, b. */
425       if (!lex_force_num (lexer))
426         return 0;
427
428       if ( (integer_value_seen = lex_is_integer (lexer) ) )
429         a = lex_integer (lexer);
430       else
431         a = lex_number (lexer);
432
433       lex_get (lexer);
434       if (lex_token (lexer) == T_TO)
435         {
436           if ( !integer_value_seen )
437             {
438               msg (SE, _("Ranges may only have integer bounds"));
439               return 0;
440             }
441           lex_get (lexer);
442           if (!lex_force_int (lexer))
443             return 0;
444           b = lex_integer (lexer);
445           if (b < a)
446             {
447               msg (SE, _("%g TO %g is an invalid range."), a, b);
448               return 0;
449             }
450           lex_get (lexer);
451         }
452       else
453         b = a;
454
455       for (i = a; i <= b; i++)
456         add_replacement (ss_cstr (pool_asprintf (pool, "%g", i)),
457                          macro, pool, &used, &allocated);
458
459       lex_match (lexer, T_COMMA);
460     }
461   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD);
462
463   return used;
464 }
465
466 /* Parses a list of strings for DO REPEAT. */
467 int
468 parse_strings (struct lexer *lexer, struct repeat_macro *macro, struct pool *pool)
469 {
470   size_t used = 0;
471   size_t allocated = 0;
472
473   macro->type = OTHER;
474   macro->replacements = NULL;
475
476   do
477     {
478       char *string;
479
480       if (!lex_force_string (lexer))
481         {
482           msg (SE, _("String expected."));
483           return 0;
484         }
485
486       string = lex_token_representation (lexer);
487       pool_register (pool, free, string);
488       add_replacement (ss_cstr (string), macro, pool, &used, &allocated);
489
490       lex_get (lexer);
491       lex_match (lexer, T_COMMA);
492     }
493   while (lex_token (lexer) != T_SLASH && lex_token (lexer) != T_ENDCMD);
494
495   return used;
496 }
497 \f
498 int
499 cmd_end_repeat (struct lexer *lexer UNUSED, struct dataset *ds UNUSED)
500 {
501   msg (SE, _("No matching DO REPEAT."));
502   return CMD_CASCADING_FAILURE;
503 }
504 \f
505 /* Finds a DO REPEAT macro with the given NAME and returns the
506    appropriate substitution if found, or NAME otherwise. */
507 static struct substring
508 find_substitution (struct repeat_block *block, struct substring name)
509 {
510   struct repeat_macro *macro = find_macro (block, name);
511   return macro ? macro->replacements[block->loop_idx] : name;
512 }
513
514 /* Makes appropriate DO REPEAT macro substitutions within the
515    repeated lines. */
516 static void
517 do_repeat_filter (struct getl_interface *interface, struct string *line)
518 {
519   struct repeat_block *block
520     = UP_CAST (interface, struct repeat_block, parent);
521   bool in_apos, in_quote, dot;
522   struct substring input;
523   struct string output;
524   int c;
525
526   ds_init_empty (&output);
527
528   /* Strip trailing whitespace, check for & remove terminal dot. */
529   ds_rtrim (line, ss_cstr (CC_SPACES));
530   dot = ds_chomp (line, '.');
531   input = ds_ss (line);
532   in_apos = in_quote = false;
533   while ((c = ss_first (input)) != EOF)
534     {
535       if (c == '\'' && !in_quote)
536         in_apos = !in_apos;
537       else if (c == '"' && !in_apos)
538         in_quote = !in_quote;
539
540       if (in_quote || in_apos || !lex_is_id1 (c))
541         {
542           ds_put_byte (&output, c);
543           ss_advance (&input, 1);
544         }
545       else
546         {
547           struct substring id;
548           ss_get_bytes (&input, lex_id_get_length (input), &id);
549           ds_put_substring (&output, find_substitution (block, id));
550         }
551     }
552   if (dot)
553     ds_put_byte (&output, '.');
554
555   ds_swap (line, &output);
556   ds_destroy (&output);
557 }
558
559 static struct repeat_line *
560 current_line (const struct getl_interface *interface)
561 {
562   struct repeat_block *block
563     = UP_CAST (interface, struct repeat_block, parent);
564   return (block->cur_line != ll_null (&block->lines)
565           ? ll_data (block->cur_line, struct repeat_line, ll)
566           : NULL);
567 }
568
569 /* Function called by getl to read a line.  Puts the line in
570    OUTPUT and its syntax mode in *SYNTAX.  Returns true if a line
571    was obtained, false if the source is exhausted. */
572 static bool
573 do_repeat_read  (struct getl_interface *interface,
574                  struct string *output)
575 {
576   struct repeat_block *block
577     = UP_CAST (interface, struct repeat_block, parent);
578   struct repeat_line *line;
579
580   block->cur_line = ll_next (block->cur_line);
581   if (block->cur_line == ll_null (&block->lines))
582     {
583       block->loop_idx++;
584       if (block->loop_idx >= block->loop_cnt)
585         return false;
586
587       block->cur_line = ll_head (&block->lines);
588     }
589
590   line = current_line (interface);
591   ds_assign_substring (output, line->text);
592   return true;
593 }
594
595 /* Frees a DO REPEAT block.
596    Called by getl to close out the DO REPEAT block. */
597 static void
598 do_repeat_close (struct getl_interface *interface)
599 {
600   struct repeat_block *block
601     = UP_CAST (interface, struct repeat_block, parent);
602   pool_destroy (block->pool);
603 }
604
605
606 static bool
607 always_false (const struct getl_interface *i UNUSED)
608 {
609   return false;
610 }
611
612 /* Returns the name of the source file from which the previous
613    line was originally obtained, or a null pointer if none. */
614 static const char *
615 do_repeat_name (const struct getl_interface *interface)
616 {
617   struct repeat_line *line = current_line (interface);
618   return line ? line->file_name : NULL;
619 }
620
621 /* Returns the line number in the source file from which the
622    previous line was originally obtained, or 0 if none. */
623 static int
624 do_repeat_location (const struct getl_interface *interface)
625 {
626   struct repeat_line *line = current_line (interface);
627   return line ? line->line_number : 0;
628 }