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