for.c revision 1.135 1 /* $NetBSD: for.c,v 1.135 2021/01/19 20:51:46 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.135 2021/01/19 20:51:46 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) != 0) {
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 *bodyEnd, char endc,
360 const char **inout_mark)
361 {
362 size_t i;
363 const char *p = *pp;
364
365 for (i = 0; i < f->vars.len; i++) {
366 ForVar *forVar = Vector_Get(&f->vars, i);
367 char *varname = forVar->name;
368 size_t varnameLen = forVar->nameLen;
369
370 if (varnameLen >= (size_t)(bodyEnd - p))
371 continue;
372 if (memcmp(p, varname, varnameLen) != 0)
373 continue;
374 /* XXX: why test for backslash here? */
375 if (p[varnameLen] != ':' && p[varnameLen] != endc &&
376 p[varnameLen] != '\\')
377 continue;
378
379 /*
380 * Found a variable match. Skip over the variable name and
381 * instead add ':U<value>' to the current body.
382 */
383 Buf_AddBytesBetween(&f->curBody, *inout_mark, p);
384 Buf_AddStr(&f->curBody, ":U");
385 Buf_AddEscaped(&f->curBody,
386 f->items.words[f->sub_next + i], endc);
387
388 p += varnameLen;
389 *inout_mark = p;
390 *pp = p;
391 return;
392 }
393 }
394
395 /*
396 * While expanding the body of a .for loop, replace single-character
397 * variable expressions like $i with their ${:U...} expansion.
398 */
399 static void
400 SubstVarShort(For *f, const char *p, const char **inout_mark)
401 {
402 const char ch = *p;
403 ForVar *vars;
404 size_t i;
405
406 /* Skip $$ and stupid ones. */
407 if (!f->short_var || strchr("}):$", ch) != NULL)
408 return;
409
410 vars = Vector_Get(&f->vars, 0);
411 for (i = 0; i < f->vars.len; i++) {
412 const char *varname = vars[i].name;
413 if (varname[0] == ch && varname[1] == '\0')
414 goto found;
415 }
416 return;
417
418 found:
419 /* Replace $<ch> with ${:U<value>} */
420 Buf_AddBytesBetween(&f->curBody, *inout_mark, p), *inout_mark = p + 1;
421 Buf_AddStr(&f->curBody, "{:U");
422 Buf_AddEscaped(&f->curBody, f->items.words[f->sub_next + i], '}');
423 Buf_AddByte(&f->curBody, '}');
424 }
425
426 /*
427 * Compute the body for the current iteration by copying the unexpanded body,
428 * replacing the expressions for the iteration variables on the way.
429 *
430 * Using variable expressions ensures that the .for loop can't generate
431 * syntax, and that the later parsing will still see a variable.
432 * This code assumes that the variable with the empty name will never be
433 * defined, see unit-tests/varname-empty.mk for more details.
434 *
435 * The detection of substitutions of the loop control variable is naive.
436 * Many of the modifiers use \ to escape $ (not $) so it is possible
437 * to contrive a makefile where an unwanted substitution happens.
438 */
439 static void
440 ForSubstBody(For *f)
441 {
442 const char *p, *bodyEnd;
443 const char *mark; /* where the last replacement left off */
444
445 Buf_Empty(&f->curBody);
446
447 mark = f->body.data;
448 bodyEnd = f->body.data + f->body.len;
449 for (p = mark; (p = strchr(p, '$')) != NULL;) {
450 if (p[1] == '{' || p[1] == '(') {
451 p += 2;
452 SubstVarLong(f, &p, bodyEnd, p[-1] == '{' ? '}' : ')',
453 &mark);
454 } else if (p[1] != '\0') {
455 SubstVarShort(f, p + 1, &mark);
456 p += 2;
457 } else
458 break;
459 }
460
461 Buf_AddBytesBetween(&f->curBody, mark, bodyEnd);
462 }
463
464 /*
465 * Compute the body for the current iteration by copying the unexpanded body,
466 * replacing the expressions for the iteration variables on the way.
467 */
468 static char *
469 ForReadMore(void *v_arg, size_t *out_len)
470 {
471 For *f = v_arg;
472
473 if (f->sub_next == f->items.len) {
474 /* No more iterations */
475 For_Free(f);
476 return NULL;
477 }
478
479 ForSubstBody(f);
480 DEBUG1(FOR, "For: loop body:\n%s", f->curBody.data);
481 f->sub_next += (unsigned int)f->vars.len;
482
483 *out_len = f->curBody.len;
484 return f->curBody.data;
485 }
486
487 /* Run the .for loop, imitating the actions of an include file. */
488 void
489 For_Run(int lineno)
490 {
491 For *f = accumFor;
492 accumFor = NULL;
493
494 if (f->items.len == 0) {
495 /*
496 * Nothing to expand - possibly due to an earlier syntax
497 * error.
498 */
499 For_Free(f);
500 return;
501 }
502
503 Parse_SetInput(NULL, lineno, -1, ForReadMore, f);
504 }
505