1 /* $NetBSD: for.c,v 1.115 2020/11/07 21:04:43 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 * Handling of .for/.endfor loops in a makefile.
35 * For loops are of the form:
37 * .for <varname...> in <value...>
41 * When a .for line is parsed, all following lines are accumulated into a
42 * buffer, up to but excluding the corresponding .endfor line. To find the
43 * corresponding .endfor, the number of nested .for and .endfor directives
46 * During parsing, any nested .for loops are just passed through; they get
47 * handled recursively in For_Eval when the enclosing .for loop is evaluated
50 * When the .for loop has been parsed completely, the variable expressions
51 * for the iteration variables are replaced with expressions of the form
52 * ${:Uvalue}, and then this modified body is "included" as a special file.
55 * For_Eval Evaluate the loop in the passed line.
57 * For_Run Run accumulated loop
62 /* "@(#)for.c 8.1 (Berkeley) 6/6/93" */
63 MAKE_RCSID("$NetBSD: for.c,v 1.115 2020/11/07 21:04:43 rillig Exp $");
65 static int forLevel = 0; /* Nesting level */
67 /* One of the variables to the left of the "in" in a .for loop. */
68 typedef struct ForVar {
74 * State of a for loop.
77 Buffer body; /* Unexpanded body of the loop */
78 Vector /* of ForVar */ vars; /* Iteration variables */
79 Words items; /* Substitution items */
80 Buffer curBody; /* Expanded body of the current iteration */
81 /* Is any of the names 1 character long? If so, when the variable values
82 * are substituted, the parser must handle $V expressions as well, not
83 * only ${V} and $(V). */
85 unsigned int sub_next; /* Where to continue iterating */
88 static For *accumFor; /* Loop being accumulated */
91 ForAddVar(For *f, const char *name, size_t len)
93 ForVar *var = Vector_Push(&f->vars);
94 var->name = bmake_strldup(name, len);
101 Buf_Destroy(&f->body, TRUE);
103 while (f->vars.len > 0) {
104 ForVar *var = Vector_Pop(&f->vars);
107 Vector_Done(&f->vars);
109 Words_Free(f->items);
110 Buf_Destroy(&f->curBody, TRUE);
118 return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
122 IsEndfor(const char *p)
124 return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
125 (p[6] == '\0' || ch_isspace(p[6]));
128 /* Evaluate the for loop in the passed line. The line looks like this:
129 * .for <varname...> in <value...>
135 * 0: Not a .for statement, parse the line
136 * 1: We found a for loop
137 * -1: A .for statement with a bad syntax error, discard.
140 For_Eval(const char *line)
145 p = line + 1; /* skip the '.' */
146 cpp_skip_whitespace(&p);
150 Parse_Error(PARSE_FATAL, "for-less endfor");
158 * we found a for loop, and now we are going to parse it.
161 f = bmake_malloc(sizeof *f);
163 Vector_Init(&f->vars, sizeof(ForVar));
164 f->items.words = NULL;
165 f->items.freeIt = NULL;
166 Buf_Init(&f->curBody);
167 f->short_var = FALSE;
170 /* Grab the variables. Terminate on "in". */
174 cpp_skip_whitespace(&p);
176 Parse_Error(PARSE_FATAL, "missing `in' in for");
181 /* XXX: This allows arbitrary variable names; see directive-for.mk. */
182 for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
185 if (len == 2 && p[0] == 'i' && p[1] == 'n') {
192 ForAddVar(f, p, len);
196 if (f->vars.len == 0) {
197 Parse_Error(PARSE_FATAL, "no iteration variables in for");
202 cpp_skip_whitespace(&p);
206 (void)Var_Subst(p, VAR_GLOBAL, VARE_WANTRES, &items);
207 /* TODO: handle errors */
208 f->items = Str_Words(items, FALSE);
211 if (f->items.len == 1 && f->items.words[0][0] == '\0')
212 f->items.len = 0; /* .for var in ${:U} */
216 size_t nitems, nvars;
218 if ((nitems = f->items.len) > 0 && nitems % (nvars = f->vars.len)) {
219 Parse_Error(PARSE_FATAL,
220 "Wrong number of words (%zu) in .for substitution list"
221 " with %zu variables", nitems, nvars);
223 * Return 'success' so that the body of the .for loop is
225 * Remove all items so that the loop doesn't iterate.
237 * Add another line to a .for loop.
238 * Returns FALSE when the matching .endfor is reached.
241 For_Accum(const char *line)
243 const char *ptr = line;
247 cpp_skip_whitespace(&ptr);
250 DEBUG1(FOR, "For: end for %d\n", forLevel);
253 } else if (IsFor(ptr)) {
255 DEBUG1(FOR, "For: new loop %d\n", forLevel);
259 Buf_AddStr(&accumFor->body, line);
260 Buf_AddByte(&accumFor->body, '\n');
266 for_var_len(const char *var)
268 char ch, var_start, var_end;
273 if (var_start == '\0')
274 /* just escape the $ */
277 if (var_start == '(')
279 else if (var_start == '{')
282 /* Single char variable */
286 for (len = 1; (ch = var[len++]) != '\0';) {
289 else if (ch == var_end && --depth == 0)
293 /* Variable end not found, escape the $ */
297 /* The .for loop substitutes the items as ${:U<value>...}, which means
298 * that characters that break this syntax must be backslash-escaped. */
300 NeedsEscapes(const char *word, char endc)
304 for (p = word; *p != '\0'; p++) {
305 if (*p == ':' || *p == '$' || *p == '\\' || *p == endc)
311 /* While expanding the body of a .for loop, write the item in the ${:U...}
312 * expression, escaping characters as needed.
314 * The result is later unescaped by ApplyModifier_Defined. */
316 Buf_AddEscaped(Buffer *cmds, const char *item, char ech)
320 if (!NeedsEscapes(item, ech)) {
321 Buf_AddStr(cmds, item);
325 /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
326 * :U processing, see ApplyModifier_Defined. */
327 while ((ch = *item++) != '\0') {
329 size_t len = for_var_len(item);
331 Buf_AddBytes(cmds, item - 1, len + 1);
335 Buf_AddByte(cmds, '\\');
336 } else if (ch == ':' || ch == '\\' || ch == ech)
337 Buf_AddByte(cmds, '\\');
338 Buf_AddByte(cmds, ch);
342 /* While expanding the body of a .for loop, replace expressions like
343 * ${i}, ${i:...}, $(i) or $(i:...) with their ${:U...} expansion. */
345 SubstVarLong(For *f, const char **pp, const char **inout_mark, char ech)
350 for (i = 0; i < f->vars.len; i++) {
351 ForVar *forVar = Vector_Get(&f->vars, i);
352 char *var = forVar->name;
353 size_t vlen = forVar->len;
355 /* XXX: undefined behavior for p if vlen is longer than p? */
356 if (memcmp(p, var, vlen) != 0)
358 /* XXX: why test for backslash here? */
359 if (p[vlen] != ':' && p[vlen] != ech && p[vlen] != '\\')
362 /* Found a variable match. Replace with :U<value> */
363 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
364 Buf_AddStr(&f->curBody, ":U");
365 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], ech);
375 /* While expanding the body of a .for loop, replace single-character
376 * variable expressions like $i with their ${:U...} expansion. */
378 SubstVarShort(For *f, char const ch, const char **pp, const char **inout_mark)
383 /* Probably a single character name, ignore $$ and stupid ones. */
384 if (!f->short_var || strchr("}):$", ch) != NULL) {
390 for (i = 0; i < f->vars.len; i++) {
391 ForVar *var = Vector_Get(&f->vars, i);
392 const char *varname = var->name;
393 if (varname[0] != ch || varname[1] != '\0')
396 /* Found a variable match. Replace with ${:U<value>} */
397 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
398 Buf_AddStr(&f->curBody, "{:U");
399 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
400 Buf_AddByte(&f->curBody, '}');
410 * Scan the for loop body and replace references to the loop variables
411 * with variable references that expand to the required text.
413 * Using variable expansions ensures that the .for loop can't generate
414 * syntax, and that the later parsing will still see a variable.
415 * We assume that the null variable will never be defined.
417 * The detection of substitutions of the loop control variable is naive.
418 * Many of the modifiers use \ to escape $ (not $) so it is possible
419 * to contrive a makefile where an unwanted substitution happens.
422 ForIterate(void *v_arg, size_t *out_len)
426 const char *mark; /* where the last replacement left off */
427 const char *body_end;
430 if (f->sub_next + f->vars.len > f->items.len) {
431 /* No more iterations */
436 Buf_Empty(&f->curBody);
438 mark = Buf_GetAll(&f->body, NULL);
439 body_end = mark + Buf_Len(&f->body);
440 for (p = mark; (p = strchr(p, '$')) != NULL;) {
443 if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
445 /* Check variable name against the .for loop variables */
446 SubstVarLong(f, &p, &mark, ech);
452 SubstVarShort(f, ch, &p, &mark);
454 Buf_AddBytesBetween(&f->curBody, mark, body_end);
456 *out_len = Buf_Len(&f->curBody);
457 cmds_str = Buf_GetAll(&f->curBody, NULL);
458 DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
460 f->sub_next += f->vars.len;
465 /* Run the for loop, imitating the actions of an include file. */
472 if (f->items.len == 0) {
473 /* Nothing to expand - possibly due to an earlier syntax error. */
478 Parse_SetInput(NULL, lineno, -1, ForIterate, f);