for.c revision 1.153 1 /* $NetBSD: for.c,v 1.153 2022/01/02 00:12:47 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
49 * variable names are replaced with expressions of the form ${:U...}. After
50 * 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.153 2022/01/02 00:12:47 rillig Exp $");
62
63
64 /* One of the variables to the left of the "in" in a .for loop. */
65 typedef struct ForVar {
66 char *name;
67 size_t nameLen;
68 } ForVar;
69
70 typedef struct ForLoop {
71 Buffer body; /* Unexpanded body of the loop */
72 Vector /* of ForVar */ vars; /* Iteration variables */
73 SubstringWords items; /* Substitution items */
74 Buffer curBody; /* Expanded body of the current iteration */
75 unsigned int nextItem; /* Where to continue iterating */
76 } ForLoop;
77
78
79 static ForLoop *accumFor; /* Loop being accumulated */
80 static int forLevel = 0; /* Nesting level */
81
82
83 static ForLoop *
84 ForLoop_New(void)
85 {
86 ForLoop *f = bmake_malloc(sizeof *f);
87
88 Buf_Init(&f->body);
89 Vector_Init(&f->vars, sizeof(ForVar));
90 SubstringWords_Init(&f->items);
91 Buf_Init(&f->curBody);
92 f->nextItem = 0;
93
94 return f;
95 }
96
97 static void
98 ForLoop_Free(ForLoop *f)
99 {
100 Buf_Done(&f->body);
101
102 while (f->vars.len > 0) {
103 ForVar *var = Vector_Pop(&f->vars);
104 free(var->name);
105 }
106 Vector_Done(&f->vars);
107
108 SubstringWords_Free(f->items);
109 Buf_Done(&f->curBody);
110
111 free(f);
112 }
113
114 static void
115 ForLoop_AddVar(ForLoop *f, const char *name, size_t len)
116 {
117 ForVar *var = Vector_Push(&f->vars);
118 var->name = bmake_strldup(name, len);
119 var->nameLen = len;
120 }
121
122 static bool
123 ForLoop_ParseVarnames(ForLoop *f, const char **pp)
124 {
125 const char *p = *pp;
126
127 for (;;) {
128 size_t len;
129
130 cpp_skip_whitespace(&p);
131 if (*p == '\0') {
132 Parse_Error(PARSE_FATAL, "missing `in' in for");
133 return false;
134 }
135
136 /*
137 * XXX: This allows arbitrary variable names;
138 * see directive-for.mk.
139 */
140 for (len = 1; p[len] != '\0' && !ch_isspace(p[len]); len++)
141 continue;
142
143 if (len == 2 && p[0] == 'i' && p[1] == 'n') {
144 p += 2;
145 break;
146 }
147
148 ForLoop_AddVar(f, p, len);
149 p += len;
150 }
151
152 if (f->vars.len == 0) {
153 Parse_Error(PARSE_FATAL, "no iteration variables in for");
154 return false;
155 }
156
157 *pp = p;
158 return true;
159 }
160
161 static bool
162 ForLoop_ParseItems(ForLoop *f, const char *p)
163 {
164 char *items;
165
166 cpp_skip_whitespace(&p);
167
168 if (Var_Subst(p, SCOPE_GLOBAL, VARE_WANTRES, &items) != VPR_OK) {
169 Parse_Error(PARSE_FATAL, "Error in .for loop items");
170 return false;
171 }
172
173 f->items = Substring_Words(items, false);
174 free(items);
175
176 if (f->items.len == 1 && Substring_IsEmpty(f->items.words[0]))
177 f->items.len = 0; /* .for var in ${:U} */
178
179 if (f->items.len != 0 && f->items.len % f->vars.len != 0) {
180 Parse_Error(PARSE_FATAL,
181 "Wrong number of words (%u) in .for "
182 "substitution list with %u variables",
183 (unsigned)f->items.len, (unsigned)f->vars.len);
184 return false;
185 }
186
187 return true;
188 }
189
190 static bool
191 IsFor(const char *p)
192 {
193 return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);
194 }
195
196 static bool
197 IsEndfor(const char *p)
198 {
199 return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&
200 (p[6] == '\0' || ch_isspace(p[6]));
201 }
202
203 /*
204 * Evaluate the for loop in the passed line. The line looks like this:
205 * .for <varname...> in <value...>
206 *
207 * Input:
208 * line Line to parse
209 *
210 * Results:
211 * 0: Not a .for statement, parse the line
212 * 1: We found a for loop
213 * -1: A .for statement with a bad syntax error, discard.
214 */
215 int
216 For_Eval(const char *line)
217 {
218 ForLoop *f;
219 const char *p;
220
221 p = line + 1; /* skip the '.' */
222 cpp_skip_whitespace(&p);
223
224 if (!IsFor(p)) {
225 if (IsEndfor(p)) {
226 Parse_Error(PARSE_FATAL, "for-less endfor");
227 return -1;
228 }
229 return 0;
230 }
231 p += 3;
232
233 f = ForLoop_New();
234
235 if (!ForLoop_ParseVarnames(f, &p)) {
236 ForLoop_Free(f);
237 return -1;
238 }
239
240 if (!ForLoop_ParseItems(f, p)) {
241 /* Continue parsing the .for loop, but don't iterate. */
242 f->items.len = 0;
243 }
244
245 accumFor = f;
246 forLevel = 1;
247 return 1;
248 }
249
250 /*
251 * Add another line to the .for loop that is being built up.
252 * Returns false when the matching .endfor is reached.
253 */
254 bool
255 For_Accum(const char *line)
256 {
257 const char *p = line;
258
259 if (*p == '.') {
260 p++;
261 cpp_skip_whitespace(&p);
262
263 if (IsEndfor(p)) {
264 DEBUG1(FOR, "For: end for %d\n", forLevel);
265 if (--forLevel <= 0)
266 return false;
267 } else if (IsFor(p)) {
268 forLevel++;
269 DEBUG1(FOR, "For: new loop %d\n", forLevel);
270 }
271 }
272
273 Buf_AddStr(&accumFor->body, line);
274 Buf_AddByte(&accumFor->body, '\n');
275 return true;
276 }
277
278
279 static size_t
280 ExprLen(const char *s, const char *e)
281 {
282 char expr_open, expr_close;
283 int depth;
284 const char *p;
285
286 if (s == e)
287 return 0; /* just escape the '$' */
288
289 expr_open = s[0];
290 if (expr_open == '(')
291 expr_close = ')';
292 else if (expr_open == '{')
293 expr_close = '}';
294 else
295 return 1; /* Single char variable */
296
297 depth = 1;
298 for (p = s + 1; p != e; p++) {
299 if (*p == expr_open)
300 depth++;
301 else if (*p == expr_close && --depth == 0)
302 return (size_t)(p + 1 - s);
303 }
304
305 /* Expression end not found, escape the $ */
306 return 0;
307 }
308
309 /*
310 * The .for loop substitutes the items as ${:U<value>...}, which means
311 * that characters that break this syntax must be backslash-escaped.
312 */
313 static bool
314 NeedsEscapes(Substring value, char endc)
315 {
316 const char *p;
317
318 for (p = value.start; p != value.end; p++) {
319 if (*p == ':' || *p == '$' || *p == '\\' || *p == endc ||
320 *p == '\n')
321 return true;
322 }
323 return false;
324 }
325
326 /*
327 * While expanding the body of a .for loop, write the item in the ${:U...}
328 * expression, escaping characters as needed.
329 *
330 * The result is later unescaped by ApplyModifier_Defined.
331 */
332 static void
333 Buf_AddEscaped(Buffer *cmds, Substring item, char endc)
334 {
335 const char *p;
336 char ch;
337
338 if (!NeedsEscapes(item, endc)) {
339 Buf_AddBytesBetween(cmds, item.start, item.end);
340 return;
341 }
342
343 /*
344 * Escape ':', '$', '\\' and 'endc' - these will be removed later by
345 * :U processing, see ApplyModifier_Defined.
346 */
347 for (p = item.start; p != item.end; p++) {
348 ch = *p;
349 if (ch == '$') {
350 size_t len = ExprLen(p + 1, item.end);
351 if (len != 0) {
352 /*
353 * XXX: Should a '\' be added here?
354 * See directive-for-escape.mk, ExprLen.
355 */
356 Buf_AddBytes(cmds, p, 1 + len);
357 p += len;
358 continue;
359 }
360 Buf_AddByte(cmds, '\\');
361 } else if (ch == ':' || ch == '\\' || ch == endc)
362 Buf_AddByte(cmds, '\\');
363 else if (ch == '\n') {
364 Parse_Error(PARSE_FATAL, "newline in .for value");
365 ch = ' '; /* prevent newline injection */
366 }
367 Buf_AddByte(cmds, ch);
368 }
369 }
370
371 /*
372 * When expanding the body of a .for loop, replace the variable name of an
373 * expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".
374 */
375 static void
376 ForLoop_SubstVarLong(ForLoop *f, Buffer *body, const char **pp,
377 const char *end, char endc, const char **inout_mark)
378 {
379 size_t i;
380 const char *p = *pp;
381
382 for (i = 0; i < f->vars.len; i++) {
383 const ForVar *forVar = Vector_Get(&f->vars, i);
384 const char *varname = forVar->name;
385 size_t varnameLen = forVar->nameLen;
386
387 if (varnameLen >= (size_t)(end - p))
388 continue;
389 if (memcmp(p, varname, varnameLen) != 0)
390 continue;
391 /* XXX: why test for backslash here? */
392 if (p[varnameLen] != ':' && p[varnameLen] != endc &&
393 p[varnameLen] != '\\')
394 continue;
395
396 /*
397 * Found a variable match. Skip over the variable name and
398 * instead add ':U<value>' to the current body.
399 */
400 Buf_AddBytesBetween(body, *inout_mark, p);
401 Buf_AddStr(body, ":U");
402 Buf_AddEscaped(body, f->items.words[f->nextItem + i], endc);
403
404 p += varnameLen;
405 *inout_mark = p;
406 *pp = p;
407 return;
408 }
409 }
410
411 /*
412 * When expanding the body of a .for loop, replace single-character
413 * variable expressions like $i with their ${:U...} expansion.
414 */
415 static void
416 ForLoop_SubstVarShort(ForLoop *f, Buffer *body,
417 const char *p, const char **inout_mark)
418 {
419 const char ch = *p;
420 const ForVar *vars;
421 size_t i;
422
423 /* Skip $$ and stupid ones. */
424 if (ch == '}' || ch == ')' || ch == ':' || ch == '$')
425 return;
426
427 vars = Vector_Get(&f->vars, 0);
428 for (i = 0; i < f->vars.len; i++) {
429 const char *varname = vars[i].name;
430 if (varname[0] == ch && varname[1] == '\0')
431 goto found;
432 }
433 return;
434
435 found:
436 Buf_AddBytesBetween(body, *inout_mark, p);
437 *inout_mark = p + 1;
438
439 /* Replace $<ch> with ${:U<value>} */
440 Buf_AddStr(body, "{:U");
441 Buf_AddEscaped(body, f->items.words[f->nextItem + i], '}');
442 Buf_AddByte(body, '}');
443 }
444
445 /*
446 * Compute the body for the current iteration by copying the unexpanded body,
447 * replacing the expressions for the iteration variables on the way.
448 *
449 * Using variable expressions ensures that the .for loop can't generate
450 * syntax, and that the later parsing will still see a variable.
451 * This code assumes that the variable with the empty name will never be
452 * defined, see unit-tests/varname-empty.mk for more details.
453 *
454 * The detection of substitutions of the loop control variables is naive.
455 * Many of the modifiers use '\$' instead of '$$' to escape '$', so it is
456 * possible to contrive a makefile where an unwanted substitution happens.
457 */
458 static void
459 ForLoop_SubstBody(ForLoop *f, Buffer *body)
460 {
461 const char *p, *end;
462 const char *mark; /* where the last substitution left off */
463
464 Buf_Empty(body);
465
466 mark = f->body.data;
467 end = f->body.data + f->body.len;
468 for (p = mark; (p = strchr(p, '$')) != NULL;) {
469 if (p[1] == '{' || p[1] == '(') {
470 char endc = p[1] == '{' ? '}' : ')';
471 p += 2;
472 ForLoop_SubstVarLong(f, body, &p, end, endc, &mark);
473 } else if (p[1] != '\0') {
474 ForLoop_SubstVarShort(f, body, p + 1, &mark);
475 p += 2;
476 } else
477 break;
478 }
479
480 Buf_AddBytesBetween(body, mark, end);
481 }
482
483 /*
484 * Compute the body for the current iteration by copying the unexpanded body,
485 * replacing the expressions for the iteration variables on the way.
486 */
487 static char *
488 ForReadMore(void *v_arg, size_t *out_len)
489 {
490 ForLoop *f = v_arg;
491
492 if (f->nextItem == f->items.len) {
493 /* No more iterations */
494 ForLoop_Free(f);
495 return NULL;
496 }
497
498 ForLoop_SubstBody(f, &f->curBody);
499 DEBUG1(FOR, "For: loop body:\n%s", f->curBody.data);
500 f->nextItem += (unsigned int)f->vars.len;
501
502 *out_len = f->curBody.len;
503 return f->curBody.data;
504 }
505
506 /* Run the .for loop, imitating the actions of an include file. */
507 void
508 For_Run(int lineno)
509 {
510 ForLoop *f = accumFor;
511 accumFor = NULL;
512
513 if (f->items.len == 0) {
514 /*
515 * Nothing to expand - possibly due to an earlier syntax
516 * error.
517 */
518 ForLoop_Free(f);
519 return;
520 }
521
522 Parse_PushInput(NULL, lineno, ForReadMore, f);
523 }
524