1 /* $NetBSD: for.c,v 1.67 2020/08/30 19:56:02 rillig Exp $ */
4 * Copyright (c) 1992, The Regents of the University of California.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 static char rcsid[] = "$NetBSD: for.c,v 1.67 2020/08/30 19:56:02 rillig Exp $";
35 #include <sys/cdefs.h>
38 static char sccsid[] = "@(#)for.c 8.1 (Berkeley) 6/6/93";
40 __RCSID("$NetBSD: for.c,v 1.67 2020/08/30 19:56:02 rillig Exp $");
47 * Functions to handle loops in a makefile.
50 * For_Eval Evaluate the loop in the passed line.
51 * For_Run Run accumulated loop
58 #define FOR_SUB_ESCAPE_CHAR 1
59 #define FOR_SUB_ESCAPE_BRACE 2
60 #define FOR_SUB_ESCAPE_PAREN 4
63 * For statements are of the form:
65 * .for <variable> in <varlist>
69 * The trick is to look for the matching end inside for for loop
70 * To do that, we count the current nesting level of the for loops.
71 * and the .endfor statements, accumulating all the statements between
72 * the initial .for loop and the matching .endfor;
73 * then we evaluate the for loop for each variable in the varlist.
75 * Note that any nested fors are just passed through; they get handled
76 * recursively in For_Eval when we're expanding the enclosing for in
80 static int forLevel = 0; /* Nesting level */
83 * State of a for loop.
86 Buffer buf; /* Body of loop */
87 strlist_t vars; /* Iteration variables */
88 strlist_t items; /* Substitution items */
94 static For *accumFor; /* Loop being accumulated */
100 Buf_Destroy(&arg->buf, TRUE);
101 strlist_clean(&arg->vars);
102 strlist_clean(&arg->items);
103 free(arg->parse_buf);
109 *-----------------------------------------------------------------------
111 * Evaluate the for loop in the passed line. The line
113 * .for <variable> in <varlist>
119 * 0: Not a .for statement, parse the line
120 * 1: We found a for loop
121 * -1: A .for statement with a bad syntax error, discard.
126 *-----------------------------------------------------------------------
132 char *ptr = line, *sub;
138 /* Skip the '.' and any following whitespace */
139 for (ptr++; *ptr && isspace((unsigned char)*ptr); ptr++)
143 * If we are not in a for loop quickly determine if the statement is
146 if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
147 !isspace((unsigned char)ptr[3])) {
148 if (ptr[0] == 'e' && strncmp(ptr + 1, "ndfor", 5) == 0) {
149 Parse_Error(PARSE_FATAL, "for-less endfor");
157 * we found a for loop, and now we are going to parse it.
160 new_for = bmake_malloc(sizeof *new_for);
161 memset(new_for, 0, sizeof *new_for);
163 /* Grab the variables. Terminate on "in". */
164 for (;; ptr += len) {
165 while (*ptr && isspace((unsigned char)*ptr))
168 Parse_Error(PARSE_FATAL, "missing `in' in for");
172 for (len = 1; ptr[len] && !isspace((unsigned char)ptr[len]); len++)
174 if (len == 2 && ptr[0] == 'i' && ptr[1] == 'n') {
179 new_for->short_var = 1;
180 strlist_add_str(&new_for->vars, bmake_strldup(ptr, len), len);
183 if (strlist_num(&new_for->vars) == 0) {
184 Parse_Error(PARSE_FATAL, "no iteration variables in for");
189 while (*ptr && isspace((unsigned char)*ptr))
193 * Make a list with the remaining words
194 * The values are substituted as ${:U<value>...} so we must \ escape
195 * characters that break that syntax.
196 * Variables are fully expanded - so it is safe for escape $.
197 * We can't do the escapes here - because we don't know whether
198 * we are substuting into ${...} or $(...).
200 sub = Var_Subst(ptr, VAR_GLOBAL, VARE_WANTRES);
203 * Split into words allowing for quoted strings.
205 words = Str_Words(sub, FALSE);
212 for (n = 0; n < words.len; n++) {
213 ptr = words.words[n];
217 while ((ch = *ptr++)) {
222 escapes |= FOR_SUB_ESCAPE_CHAR;
225 escapes |= FOR_SUB_ESCAPE_PAREN;
228 escapes |= FOR_SUB_ESCAPE_BRACE;
233 * We have to dup words[n] to maintain the semantics of
236 strlist_add_str(&new_for->items, bmake_strdup(words.words[n]),
242 if ((len = strlist_num(&new_for->items)) > 0 &&
243 len % (n = strlist_num(&new_for->vars))) {
244 Parse_Error(PARSE_FATAL,
245 "Wrong number of words (%zu) in .for substitution list"
246 " with %zu vars", len, n);
248 * Return 'success' so that the body of the .for loop is
250 * Remove all items so that the loop doesn't iterate.
252 strlist_clean(&new_for->items);
256 Buf_Init(&new_for->buf, 0);
263 * Add another line to a .for loop.
264 * Returns 0 when the matching .endfor is reached.
268 For_Accum(char *line)
274 for (ptr++; *ptr && isspace((unsigned char)*ptr); ptr++)
277 if (strncmp(ptr, "endfor", 6) == 0 &&
278 (isspace((unsigned char)ptr[6]) || !ptr[6])) {
280 (void)fprintf(debug_file, "For: end for %d\n", forLevel);
283 } else if (strncmp(ptr, "for", 3) == 0 &&
284 isspace((unsigned char)ptr[3])) {
287 (void)fprintf(debug_file, "For: new loop %d\n", forLevel);
291 Buf_AddStr(&accumFor->buf, line);
292 Buf_AddByte(&accumFor->buf, '\n');
298 for_var_len(const char *var)
300 char ch, var_start, var_end;
306 /* just escape the $ */
309 if (var_start == '(')
311 else if (var_start == '{')
314 /* Single char variable */
318 for (len = 1; (ch = var[len++]) != 0;) {
321 else if (ch == var_end && --depth == 0)
325 /* Variable end not found, escape the $ */
330 for_substitute(Buffer *cmds, strlist_t *items, unsigned int item_no, char ech)
334 const char *item = strlist_str(items, item_no);
336 /* If there were no escapes, or the only escape is the other variable
337 * terminator, then just substitute the full string */
338 if (!(strlist_info(items, item_no) &
339 (ech == ')' ? ~FOR_SUB_ESCAPE_BRACE : ~FOR_SUB_ESCAPE_PAREN))) {
340 Buf_AddStr(cmds, item);
344 /* Escape ':', '$', '\\' and 'ech' - removed by :U processing */
345 while ((ch = *item++) != 0) {
347 size_t len = for_var_len(item);
349 Buf_AddBytes(cmds, item - 1, len + 1);
353 Buf_AddByte(cmds, '\\');
354 } else if (ch == ':' || ch == '\\' || ch == ech)
355 Buf_AddByte(cmds, '\\');
356 Buf_AddByte(cmds, ch);
361 For_Iterate(void *v_arg, size_t *ret_len)
373 if (arg->sub_next + strlist_num(&arg->vars) > strlist_num(&arg->items)) {
374 /* No more iterations */
379 free(arg->parse_buf);
380 arg->parse_buf = NULL;
383 * Scan the for loop body and replace references to the loop variables
384 * with variable references that expand to the required text.
385 * Using variable expansions ensures that the .for loop can't generate
386 * syntax, and that the later parsing will still see a variable.
387 * We assume that the null variable will never be defined.
389 * The detection of substitions of the loop control variable is naive.
390 * Many of the modifiers use \ to escape $ (not $) so it is possible
391 * to contrive a makefile where an unwanted substitution happens.
394 cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
395 body_end = cmd_cp + cmd_len;
396 Buf_Init(&cmds, cmd_len + 256);
397 for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
400 if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
402 /* Check variable name against the .for loop variables */
403 STRLIST_FOREACH(var, &arg->vars, i) {
404 size_t vlen = strlist_info(&arg->vars, i);
405 if (memcmp(cp, var, vlen) != 0)
407 if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
409 /* Found a variable match. Replace with :U<value> */
410 Buf_AddBytesBetween(&cmds, cmd_cp, cp);
411 Buf_AddStr(&cmds, ":U");
414 for_substitute(&cmds, &arg->items, arg->sub_next + i, ech);
421 /* Probably a single character name, ignore $$ and stupid ones. {*/
422 if (!arg->short_var || strchr("}):$", ch) != NULL) {
426 STRLIST_FOREACH(var, &arg->vars, i) {
427 if (var[0] != ch || var[1] != 0)
429 /* Found a variable match. Replace with ${:U<value>} */
430 Buf_AddBytesBetween(&cmds, cmd_cp, cp);
431 Buf_AddStr(&cmds, "{:U");
433 for_substitute(&cmds, &arg->items, arg->sub_next + i, /*{*/ '}');
434 Buf_AddByte(&cmds, '}');
438 Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
440 cp = Buf_Destroy(&cmds, FALSE);
442 (void)fprintf(debug_file, "For: loop body:\n%s", cp);
444 arg->sub_next += strlist_num(&arg->vars);
447 *ret_len = strlen(cp);
451 /* Run the for loop, imitating the actions of an include file. */
460 if (strlist_num(&arg->items) == 0) {
461 /* Nothing to expand - possibly due to an earlier syntax error. */
466 Parse_SetInput(NULL, lineno, -1, For_Iterate, arg);