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