for.c revision 1.131 1 /* $NetBSD: for.c,v 1.131 2020/12/31 13:56:56 rillig Exp $ */
2
3 /*
4 * Copyright (c) 1992, The Regents of the University of California.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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.
18 *
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
29 * SUCH DAMAGE.
30 */
31
32 /*-
33 * Handling of .for/.endfor loops in a makefile.
34 *
35 * For loops have the form:
36 *
37 * .for <varname...> in <value...>
38 * # the body
39 * .endfor
40 *
41 * When a .for line is parsed, the following lines are copied to the body of
42 * the .for loop, until the corresponding .endfor line is reached. In this
43 * phase, the body is not yet evaluated. This also applies to any nested
44 * .for loops.
45 *
46 * After reaching the .endfor, the values from the .for line are grouped
47 * according to the number of variables. For each such group, the unexpanded
48 * body is scanned for variable expressions, and those that match the variable
49 * names are replaced with expressions of the form ${:U...} or $(:U...).
50 * After that, the body is treated like a file from an .include directive.
51 *
52 * Interface:
53 * For_Eval Evaluate the loop in the passed line.
54 *
55 * For_Run Run accumulated loop
56 */
57
58 #include "make.h"
59
60 /* "@(#)for.c 8.1 (Berkeley) 6/6/93" */
61 MAKE_RCSID("$NetBSD: for.c,v 1.131 2020/12/31 13:56:56 rillig Exp $");
62
63 static int forLevel = 0; /* Nesting level */
64
65 /* One of the variables to the left of the "in" in a .for loop. */
66 typedef struct ForVar {
67 char *name;
68 size_t nameLen;
69 } ForVar;
70
71 /*
72 * State of a for loop.
73 */
74 typedef struct For {
75 Buffer body; /* Unexpanded body of the loop */
76 Vector /* of ForVar */ vars; /* Iteration variables */
77 Words items; /* Substitution items */
78 Buffer curBody; /* Expanded body of the current iteration */
79 /* Is any of the names 1 character long? If so, when the variable values
80 * are substituted, the parser must handle $V expressions as well, not
81 * only ${V} and $(V). */
82 Boolean short_var;
83 unsigned int sub_next; /* Where to continue iterating */
84 } For;
85
86 static For *accumFor; /* Loop being accumulated */
87
88 static void
89 ForAddVar(For *f, const char *name, size_t len)
90 {
91 ForVar *var = Vector_Push(&f->vars);
92 var->name = bmake_strldup(name, len);
93 var->nameLen = len;
94 }
95
96 static void
97 For_Free(For *f)
98 {
99 Buf_Destroy(&f->body, TRUE);
100
101 while (f->vars.len > 0) {
102 ForVar *var = Vector_Pop(&f->vars);
103 free(var->name);
104 }
105 Vector_Done(&f->vars);
106
107 Words_Free(f->items);
108 Buf_Destroy(&f->curBody, TRUE);
109
110 free(f);
111 }
112
113 static Boolean
114 IsFor(const char *p)
115 {
116 return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
117 }
118
119 static Boolean
120 IsEndfor(const char *p)
121 {
122 return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
123 (p[6] == '\0' || ch_isspace(p[6]));
124 }
125
126 /*
127 * Evaluate the for loop in the passed line. The line looks like this:
128 * .for <varname...> in <value...>
129 *
130 * Input:
131 * line Line to parse
132 *
133 * Results:
134 * 0: Not a .for statement, parse the line
135 * 1: We found a for loop
136 * -1: A .for statement with a bad syntax error, discard.
137 */
138 int
139 For_Eval(const char *line)
140 {
141 For *f;
142 const char *p;
143
144 p = line + 1; /* skip the '.' */
145 cpp_skip_whitespace(&p);
146
147 if (!IsFor(p)) {
148 if (IsEndfor(p)) {
149 Parse_Error(PARSE_FATAL, "for-less endfor");
150 return -1;
151 }
152 return 0;
153 }
154 p += 3;
155
156 /*
157 * we found a for loop, and now we are going to parse it.
158 */
159
160 f = bmake_malloc(sizeof *f);
161 Buf_Init(&f->body);
162 Vector_Init(&f->vars, sizeof(ForVar));
163 f->items.words = NULL;
164 f->items.freeIt = NULL;
165 Buf_Init(&f->curBody);
166 f->short_var = FALSE;
167 f->sub_next = 0;
168
169 /* Grab the variables. Terminate on "in". */
170 for (;;) {
171 size_t len;
172
173 cpp_skip_whitespace(&p);
174 if (*p == '\0') {
175 Parse_Error(PARSE_FATAL, "missing `in' in for");
176 For_Free(f);
177 return -1;
178 }
179
180 /*
181 * XXX: This allows arbitrary variable names;
182 * see directive-for.mk.
183 */
184 for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
185 continue;
186
187 if (len == 2 && p[0] == 'i' && p[1] == 'n') {
188 p += 2;
189 break;
190 }
191 if (len == 1)
192 f->short_var = TRUE;
193
194 ForAddVar(f, p, len);
195 p += len;
196 }
197
198 if (f->vars.len == 0) {
199 Parse_Error(PARSE_FATAL, "no iteration variables in for");
200 For_Free(f);
201 return -1;
202 }
203
204 cpp_skip_whitespace(&p);
205
206 {
207 char *items;
208 if (Var_Subst(p, VAR_GLOBAL, VARE_WANTRES, &items) != VPR_OK) {
209 Parse_Error(PARSE_FATAL, "Error in .for loop items");
210 f->items.len = 0;
211 goto done;
212 }
213
214 f->items = Str_Words(items, FALSE);
215 free(items);
216
217 if (f->items.len == 1 && f->items.words[0][0] == '\0')
218 f->items.len = 0; /* .for var in ${:U} */
219 }
220
221 {
222 size_t nitems, nvars;
223
224 if ((nitems = f->items.len) > 0 &&
225 nitems % (nvars = f->vars.len)) {
226 Parse_Error(PARSE_FATAL,
227 "Wrong number of words (%u) in .for "
228 "substitution list with %u variables",
229 (unsigned)nitems, (unsigned)nvars);
230 /*
231 * Return 'success' so that the body of the .for loop
232 * is accumulated.
233 * Remove all items so that the loop doesn't iterate.
234 */
235 f->items.len = 0;
236 }
237 }
238
239 done:
240 accumFor = f;
241 forLevel = 1;
242 return 1;
243 }
244
245 /*
246 * Add another line to a .for loop.
247 * Returns FALSE when the matching .endfor is reached.
248 */
249 Boolean
250 For_Accum(const char *line)
251 {
252 const char *ptr = line;
253
254 if (*ptr == '.') {
255 ptr++;
256 cpp_skip_whitespace(&ptr);
257
258 if (IsEndfor(ptr)) {
259 DEBUG1(FOR, "For: end for %d\n", forLevel);
260 if (--forLevel <= 0)
261 return FALSE;
262 } else if (IsFor(ptr)) {
263 forLevel++;
264 DEBUG1(FOR, "For: new loop %d\n", forLevel);
265 }
266 }
267
268 Buf_AddStr(&accumFor->body, line);
269 Buf_AddByte(&accumFor->body, '\n');
270 return TRUE;
271 }
272
273
274 static size_t
275 for_var_len(const char *var)
276 {
277 char ch, var_start, var_end;
278 int depth;
279 size_t len;
280
281 var_start = *var;
282 if (var_start == '\0')
283 /* just escape the $ */
284 return 0;
285
286 if (var_start == '(')
287 var_end = ')';
288 else if (var_start == '{')
289 var_end = '}';
290 else
291 return 1; /* Single char variable */
292
293 depth = 1;
294 for (len = 1; (ch = var[len++]) != '\0';) {
295 if (ch == var_start)
296 depth++;
297 else if (ch == var_end && --depth == 0)
298 return len;
299 }
300
301 /* Variable end not found, escape the $ */
302 return 0;
303 }
304
305 /*
306 * The .for loop substitutes the items as ${:U<value>...}, which means
307 * that characters that break this syntax must be backslash-escaped.
308 */
309 static Boolean
310 NeedsEscapes(const char *word, char endc)
311 {
312 const char *p;
313
314 for (p = word; *p != '\0'; p++) {
315 if (*p == ':' || *p == '$' || *p == '\\' || *p == endc)
316 return TRUE;
317 }
318 return FALSE;
319 }
320
321 /*
322 * While expanding the body of a .for loop, write the item in the ${:U...}
323 * expression, escaping characters as needed.
324 *
325 * The result is later unescaped by ApplyModifier_Defined.
326 */
327 static void
328 Buf_AddEscaped(Buffer *cmds, const char *item, char endc)
329 {
330 char ch;
331
332 if (!NeedsEscapes(item, endc)) {
333 Buf_AddStr(cmds, item);
334 return;
335 }
336
337 /* Escape ':', '$', '\\' and 'endc' - these will be removed later by
338 * :U processing, see ApplyModifier_Defined. */
339 while ((ch = *item++) != '\0') {
340 if (ch == '$') {
341 size_t len = for_var_len(item);
342 if (len != 0) {
343 Buf_AddBytes(cmds, item - 1, len + 1);
344 item += len;
345 continue;
346 }
347 Buf_AddByte(cmds, '\\');
348 } else if (ch == ':' || ch == '\\' || ch == endc)
349 Buf_AddByte(cmds, '\\');
350 Buf_AddByte(cmds, ch);
351 }
352 }
353
354 /*
355 * While expanding the body of a .for loop, replace the variable name of an
356 * expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".
357 */
358 static void
359 SubstVarLong(For *f, const char **pp, const char **inout_mark, char endc)
360 {
361 size_t i;
362 const char *p = *pp;
363
364 for (i = 0; i < f->vars.len; i++) {
365 ForVar *forVar = Vector_Get(&f->vars, i);
366 char *varname = forVar->name;
367 size_t varnameLen = forVar->nameLen;
368
369 /* XXX: undefined behavior for p if varname is longer than p? */
370 if (memcmp(p, varname, varnameLen) != 0)
371 continue;
372 /* XXX: why test for backslash here? */
373 if (p[varnameLen] != ':' && p[varnameLen] != endc &&
374 p[varnameLen] != '\\')
375 continue;
376
377 /*
378 * Found a variable match. Skip over the variable name and
379 * instead add ':U<value>' to the current body.
380 */
381 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
382 Buf_AddStr(&f->curBody, ":U");
383 Buf_AddEscaped(&f->curBody,
384 f->items.words[f->sub_next + i], endc);
385
386 p += varnameLen;
387 *inout_mark = p;
388 *pp = p;
389 return;
390 }
391 }
392
393 /*
394 * While expanding the body of a .for loop, replace single-character
395 * variable expressions like $i with their ${:U...} expansion.
396 */
397 static void
398 SubstVarShort(For *f, const char *p, const char **inout_mark)
399 {
400 const char ch = *p;
401 ForVar *vars;
402 size_t i;
403
404 /* Skip $$ and stupid ones. */
405 if (!f->short_var || strchr("}):$", ch) != NULL)
406 return;
407
408 vars = Vector_Get(&f->vars, 0);
409 for (i = 0; i < f->vars.len; i++) {
410 const char *varname = vars[i].name;
411 if (varname[0] == ch && varname[1] == '\0')
412 goto found;
413 }
414 return;
415
416 found:
417 /* Replace $<ch> with ${:U<value>} */
418 Buf_AddBytesBetween(&f->curBody, *inout_mark, p), *inout_mark = p + 1;
419 Buf_AddStr(&f->curBody, "{:U");
420 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
421 Buf_AddByte(&f->curBody, '}');
422 }
423
424 /*
425 * Compute the body for the current iteration by copying the unexpanded body,
426 * replacing the expressions for the iteration variables on the way.
427 *
428 * Using variable expressions ensures that the .for loop can't generate
429 * syntax, and that the later parsing will still see a variable.
430 * This code assumes that the variable with the empty name will never be
431 * defined, see unit-tests/varname-empty.mk for more details.
432 *
433 * The detection of substitutions of the loop control variable is naive.
434 * Many of the modifiers use \ to escape $ (not $) so it is possible
435 * to contrive a makefile where an unwanted substitution happens.
436 */
437 static void
438 ForSubstBody(For *f)
439 {
440 const char *p;
441 const char *mark; /* where the last replacement left off */
442
443 Buf_Empty(&f->curBody);
444
445 mark = f->body.data;
446 for (p = mark; (p = strchr(p, '$')) != NULL;) {
447 if (p[1] == '{' || p[1] == '(') {
448 p += 2;
449 SubstVarLong(f, &p, &mark, p[-1] == '{' ? '}' : ')');
450 } else if (p[1] != '\0') {
451 SubstVarShort(f, p + 1, &mark);
452 p += 2;
453 } else
454 break;
455 }
456
457 Buf_AddBytesBetween(&f->curBody, mark, f->body.data + f->body.len);
458 }
459
460 /*
461 * Compute the body for the current iteration by copying the unexpanded body,
462 * replacing the expressions for the iteration variables on the way.
463 */
464 static char *
465 ForReadMore(void *v_arg, size_t *out_len)
466 {
467 For *f = v_arg;
468
469 if (f->sub_next == f->items.len) {
470 /* No more iterations */
471 For_Free(f);
472 return NULL;
473 }
474
475 ForSubstBody(f);
476 DEBUG1(FOR, "For: loop body:\n%s", f->curBody.data);
477 f->sub_next += f->vars.len;
478
479 *out_len = f->curBody.len;
480 return f->curBody.data;
481 }
482
483 /* Run the .for loop, imitating the actions of an include file. */
484 void
485 For_Run(int lineno)
486 {
487 For *f = accumFor;
488 accumFor = NULL;
489
490 if (f->items.len == 0) {
491 /*
492 * Nothing to expand - possibly due to an earlier syntax
493 * error.
494 */
495 For_Free(f);
496 return;
497 }
498
499 Parse_SetInput(NULL, lineno, -1, ForReadMore, f);
500 }
501