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