1 /* $NetBSD: for.c,v 1.112 2020/10/31 18:41:07 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.112 2020/10/31 18:41:07 rillig Exp $");
65 /* The .for loop substitutes the items as ${:U<value>...}, which means
66 * that characters that break this syntax must be backslash-escaped. */
67 typedef enum ForEscapes {
68 FOR_SUB_ESCAPE_CHAR = 0x0001,
69 FOR_SUB_ESCAPE_BRACE = 0x0002,
70 FOR_SUB_ESCAPE_PAREN = 0x0004
73 static int forLevel = 0; /* Nesting level */
75 /* One of the variables to the left of the "in" in a .for loop. */
76 typedef struct ForVar {
82 * State of a for loop.
85 Buffer body; /* Unexpanded body of the loop */
86 Vector /* of ForVar */ vars; /* Iteration variables */
87 Words items; /* Substitution items */
88 Buffer curBody; /* Expanded body of the current iteration */
89 /* Is any of the names 1 character long? If so, when the variable values
90 * are substituted, the parser must handle $V expressions as well, not
91 * only ${V} and $(V). */
93 unsigned int sub_next; /* Where to continue iterating */
96 static For *accumFor; /* Loop being accumulated */
99 ForAddVar(For *f, const char *name, size_t len)
101 ForVar *var = Vector_Push(&f->vars);
102 var->name = bmake_strldup(name, len);
109 Buf_Destroy(&f->body, TRUE);
111 while (f->vars.len > 0) {
112 ForVar *var = Vector_Pop(&f->vars);
115 Vector_Done(&f->vars);
117 Words_Free(f->items);
118 Buf_Destroy(&f->curBody, TRUE);
124 GetEscapes(const char *word)
127 ForEscapes escapes = 0;
129 for (p = word; *p != '\0'; p++) {
134 escapes |= FOR_SUB_ESCAPE_CHAR;
137 escapes |= FOR_SUB_ESCAPE_PAREN;
140 escapes |= FOR_SUB_ESCAPE_BRACE;
150 return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
154 IsEndfor(const char *p)
156 return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
157 (p[6] == '\0' || ch_isspace(p[6]));
160 /* Evaluate the for loop in the passed line. The line looks like this:
161 * .for <varname...> in <value...>
167 * 0: Not a .for statement, parse the line
168 * 1: We found a for loop
169 * -1: A .for statement with a bad syntax error, discard.
172 For_Eval(const char *line)
177 p = line + 1; /* skip the '.' */
178 cpp_skip_whitespace(&p);
182 Parse_Error(PARSE_FATAL, "for-less endfor");
190 * we found a for loop, and now we are going to parse it.
193 f = bmake_malloc(sizeof *f);
194 Buf_Init(&f->body, 0);
195 Vector_Init(&f->vars, sizeof(ForVar));
196 f->items.words = NULL;
197 f->items.freeIt = NULL;
198 Buf_Init(&f->curBody, 0);
199 f->short_var = FALSE;
202 /* Grab the variables. Terminate on "in". */
206 cpp_skip_whitespace(&p);
208 Parse_Error(PARSE_FATAL, "missing `in' in for");
213 /* XXX: This allows arbitrary variable names; see directive-for.mk. */
214 for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
217 if (len == 2 && p[0] == 'i' && p[1] == 'n') {
224 ForAddVar(f, p, len);
228 if (f->vars.len == 0) {
229 Parse_Error(PARSE_FATAL, "no iteration variables in for");
234 cpp_skip_whitespace(&p);
238 (void)Var_Subst(p, VAR_GLOBAL, VARE_WANTRES, &items);
239 /* TODO: handle errors */
240 f->items = Str_Words(items, FALSE);
243 if (f->items.len == 1 && f->items.words[0][0] == '\0')
244 f->items.len = 0; /* .for var in ${:U} */
248 size_t nitems, nvars;
250 if ((nitems = f->items.len) > 0 && nitems % (nvars = f->vars.len)) {
251 Parse_Error(PARSE_FATAL,
252 "Wrong number of words (%zu) in .for substitution list"
253 " with %zu variables", nitems, nvars);
255 * Return 'success' so that the body of the .for loop is
257 * Remove all items so that the loop doesn't iterate.
269 * Add another line to a .for loop.
270 * Returns FALSE when the matching .endfor is reached.
273 For_Accum(const char *line)
275 const char *ptr = line;
279 cpp_skip_whitespace(&ptr);
282 DEBUG1(FOR, "For: end for %d\n", forLevel);
285 } else if (IsFor(ptr)) {
287 DEBUG1(FOR, "For: new loop %d\n", forLevel);
291 Buf_AddStr(&accumFor->body, line);
292 Buf_AddByte(&accumFor->body, '\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 $ */
329 /* While expanding the body of a .for loop, write the item in the ${:U...}
330 * expression, escaping characters as needed. See ApplyModifier_Defined. */
332 Buf_AddEscaped(Buffer *cmds, const char *item, char ech)
334 ForEscapes escapes = GetEscapes(item);
337 /* If there were no escapes, or the only escape is the other variable
338 * terminator, then just substitute the full string */
339 if (!(escapes & (ech == ')' ? ~(unsigned)FOR_SUB_ESCAPE_BRACE
340 : ~(unsigned)FOR_SUB_ESCAPE_PAREN))) {
341 Buf_AddStr(cmds, item);
345 /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
346 * :U processing, see ApplyModifier_Defined. */
347 while ((ch = *item++) != '\0') {
349 size_t len = for_var_len(item);
351 Buf_AddBytes(cmds, item - 1, len + 1);
355 Buf_AddByte(cmds, '\\');
356 } else if (ch == ':' || ch == '\\' || ch == ech)
357 Buf_AddByte(cmds, '\\');
358 Buf_AddByte(cmds, ch);
362 /* While expanding the body of a .for loop, replace expressions like
363 * ${i}, ${i:...}, $(i) or $(i:...) with their ${:U...} expansion. */
365 SubstVarLong(For *f, const char **pp, const char **inout_mark, char ech)
370 for (i = 0; i < f->vars.len; i++) {
371 ForVar *forVar = Vector_Get(&f->vars, i);
372 char *var = forVar->name;
373 size_t vlen = forVar->len;
375 /* XXX: undefined behavior for p if vlen is longer than p? */
376 if (memcmp(p, var, vlen) != 0)
378 /* XXX: why test for backslash here? */
379 if (p[vlen] != ':' && p[vlen] != ech && p[vlen] != '\\')
382 /* Found a variable match. Replace with :U<value> */
383 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
384 Buf_AddStr(&f->curBody, ":U");
385 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], ech);
395 /* While expanding the body of a .for loop, replace single-character
396 * variable expressions like $i with their ${:U...} expansion. */
398 SubstVarShort(For *f, char const ch, const char **pp, const char **inout_mark)
403 /* Probably a single character name, ignore $$ and stupid ones. */
404 if (!f->short_var || strchr("}):$", ch) != NULL) {
410 for (i = 0; i < f->vars.len; i++) {
411 ForVar *var = Vector_Get(&f->vars, i);
412 const char *varname = var->name;
413 if (varname[0] != ch || varname[1] != '\0')
416 /* Found a variable match. Replace with ${:U<value>} */
417 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
418 Buf_AddStr(&f->curBody, "{:U");
419 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
420 Buf_AddByte(&f->curBody, '}');
430 * Scan the for loop body and replace references to the loop variables
431 * with variable references that expand to the required text.
433 * Using variable expansions ensures that the .for loop can't generate
434 * syntax, and that the later parsing will still see a variable.
435 * We assume that the null variable will never be defined.
437 * The detection of substitutions of the loop control variable is naive.
438 * Many of the modifiers use \ to escape $ (not $) so it is possible
439 * to contrive a makefile where an unwanted substitution happens.
442 ForIterate(void *v_arg, size_t *out_len)
446 const char *mark; /* where the last replacement left off */
447 const char *body_end;
450 if (f->sub_next + f->vars.len > f->items.len) {
451 /* No more iterations */
456 Buf_Empty(&f->curBody);
458 mark = Buf_GetAll(&f->body, NULL);
459 body_end = mark + Buf_Len(&f->body);
460 for (p = mark; (p = strchr(p, '$')) != NULL;) {
463 if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
465 /* Check variable name against the .for loop variables */
466 SubstVarLong(f, &p, &mark, ech);
472 SubstVarShort(f, ch, &p, &mark);
474 Buf_AddBytesBetween(&f->curBody, mark, body_end);
476 *out_len = Buf_Len(&f->curBody);
477 cmds_str = Buf_GetAll(&f->curBody, NULL);
478 DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
480 f->sub_next += f->vars.len;
485 /* Run the for loop, imitating the actions of an include file. */
492 if (f->items.len == 0) {
493 /* Nothing to expand - possibly due to an earlier syntax error. */
498 Parse_SetInput(NULL, lineno, -1, ForIterate, f);