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