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