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