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