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