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