Home | History | Annotate | Line # | Download | only in make
for.c revision 1.100
      1 /*	$NetBSD: for.c,v 1.100 2020/10/25 14:58:23 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 are of the form:
     36  *
     37  * .for <varname...> in <value...>
     38  * ...
     39  * .endfor
     40  *
     41  * When a .for line is parsed, all following lines are accumulated into a
     42  * buffer, up to but excluding the corresponding .endfor line.  To find the
     43  * corresponding .endfor, the number of nested .for and .endfor directives
     44  * are counted.
     45  *
     46  * During parsing, any nested .for loops are just passed through; they get
     47  * handled recursively in For_Eval when the enclosing .for loop is evaluated
     48  * in For_Run.
     49  *
     50  * When the .for loop has been parsed completely, the variable expressions
     51  * for the iteration variables are replaced with expressions of the form
     52  * ${:Uvalue}, and then this modified body is "included" as a special file.
     53  *
     54  * Interface:
     55  *	For_Eval	Evaluate the loop in the passed line.
     56  *
     57  *	For_Run		Run accumulated loop
     58  */
     59 
     60 #include    "make.h"
     61 
     62 /*	"@(#)for.c	8.1 (Berkeley) 6/6/93"	*/
     63 MAKE_RCSID("$NetBSD: for.c,v 1.100 2020/10/25 14:58:23 rillig Exp $");
     64 
     65 typedef enum ForEscapes {
     66     FOR_SUB_ESCAPE_CHAR = 0x0001,
     67     FOR_SUB_ESCAPE_BRACE = 0x0002,
     68     FOR_SUB_ESCAPE_PAREN = 0x0004
     69 } ForEscapes;
     70 
     71 static int forLevel = 0;	/* Nesting level */
     72 
     73 /* One of the variables to the left of the "in" in a .for loop. */
     74 typedef struct ForVar {
     75     char *name;
     76     size_t len;
     77 } ForVar;
     78 
     79 /* One of the items to the right of the "in" in a .for loop. */
     80 typedef struct ForItem {
     81     char *value;
     82 } ForItem;
     83 
     84 /*
     85  * State of a for loop.
     86  */
     87 typedef struct For {
     88     Buffer buf;			/* Body of loop */
     89     Vector /* of ForVar */ vars;
     90     Vector /* of ForItem */ items;	/* Substitution items */
     91     char *parse_buf;
     92     /* Is any of the names 1 character long? If so, when the variable values
     93      * are substituted, the parser must handle $V expressions as well, not
     94      * only ${V} and $(V). */
     95     Boolean short_var;
     96     unsigned int sub_next;
     97 } For;
     98 
     99 static For *accumFor;		/* Loop being accumulated */
    100 
    101 static void
    102 ForAddVar(For *f, const char *name, size_t len)
    103 {
    104     ForVar *var = Vector_Push(&f->vars);
    105     var->name = bmake_strldup(name, len);
    106     var->len = len;
    107 }
    108 
    109 static void
    110 ForVarDone(ForVar *var)
    111 {
    112     free(var->name);
    113 }
    114 
    115 static void
    116 ForAddItem(For *f, const char *value)
    117 {
    118     ForItem *item = Vector_Push(&f->items);
    119     item->value = bmake_strdup(value);
    120 }
    121 
    122 static void
    123 ForItemDone(ForItem *item)
    124 {
    125     free(item->value);
    126 }
    127 
    128 static void
    129 For_Free(For *arg)
    130 {
    131     Buf_Destroy(&arg->buf, TRUE);
    132 
    133     while (arg->vars.len > 0)
    134         ForVarDone(Vector_Pop(&arg->vars));
    135     Vector_Done(&arg->vars);
    136 
    137     while (arg->items.len > 0)
    138 	ForItemDone(Vector_Pop(&arg->items));
    139     Vector_Done(&arg->items);
    140 
    141     free(arg->parse_buf);
    142 
    143     free(arg);
    144 }
    145 
    146 static ForEscapes
    147 GetEscapes(const char *word)
    148 {
    149     const char *p;
    150     ForEscapes escapes = 0;
    151 
    152     for (p = word; *p != '\0'; p++) {
    153 	switch (*p) {
    154 	case ':':
    155 	case '$':
    156 	case '\\':
    157 	    escapes |= FOR_SUB_ESCAPE_CHAR;
    158 	    break;
    159 	case ')':
    160 	    escapes |= FOR_SUB_ESCAPE_PAREN;
    161 	    break;
    162 	case '}':
    163 	    escapes |= FOR_SUB_ESCAPE_BRACE;
    164 	    break;
    165 	}
    166     }
    167     return escapes;
    168 }
    169 
    170 /* Evaluate the for loop in the passed line. The line looks like this:
    171  *	.for <varname...> in <value...>
    172  *
    173  * Input:
    174  *	line		Line to parse
    175  *
    176  * Results:
    177  *      0: Not a .for statement, parse the line
    178  *	1: We found a for loop
    179  *     -1: A .for statement with a bad syntax error, discard.
    180  */
    181 int
    182 For_Eval(const char *line)
    183 {
    184     For *new_for;
    185     const char *ptr;
    186     Words words;
    187 
    188     /* Skip the '.' and any following whitespace */
    189     ptr = line + 1;
    190     cpp_skip_whitespace(&ptr);
    191 
    192     /*
    193      * If we are not in a for loop quickly determine if the statement is
    194      * a for.
    195      */
    196     if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
    197 	!ch_isspace(ptr[3])) {
    198 	if (ptr[0] == 'e' && strncmp(ptr + 1, "ndfor", 5) == 0) {
    199 	    Parse_Error(PARSE_FATAL, "for-less endfor");
    200 	    return -1;
    201 	}
    202 	return 0;
    203     }
    204     ptr += 3;
    205 
    206     /*
    207      * we found a for loop, and now we are going to parse it.
    208      */
    209 
    210     new_for = bmake_malloc(sizeof *new_for);
    211     Buf_Init(&new_for->buf, 0);
    212     Vector_Init(&new_for->vars, sizeof(ForVar));
    213     Vector_Init(&new_for->items, sizeof(ForItem));
    214     new_for->parse_buf = NULL;
    215     new_for->short_var = FALSE;
    216     new_for->sub_next = 0;
    217 
    218     /* Grab the variables. Terminate on "in". */
    219     for (;;) {
    220 	size_t len;
    221 
    222 	cpp_skip_whitespace(&ptr);
    223 	if (*ptr == '\0') {
    224 	    Parse_Error(PARSE_FATAL, "missing `in' in for");
    225 	    For_Free(new_for);
    226 	    return -1;
    227 	}
    228 
    229 	for (len = 1; ptr[len] && !ch_isspace(ptr[len]); len++)
    230 	    continue;
    231 	if (len == 2 && ptr[0] == 'i' && ptr[1] == 'n') {
    232 	    ptr += 2;
    233 	    break;
    234 	}
    235 	if (len == 1)
    236 	    new_for->short_var = TRUE;
    237 
    238 	ForAddVar(new_for, ptr, len);
    239 	ptr += len;
    240     }
    241 
    242     if (new_for->vars.len == 0) {
    243 	Parse_Error(PARSE_FATAL, "no iteration variables in for");
    244 	For_Free(new_for);
    245 	return -1;
    246     }
    247 
    248     cpp_skip_whitespace(&ptr);
    249 
    250     /*
    251      * Make a list with the remaining words.
    252      * The values are later substituted as ${:U<value>...} so we must
    253      * backslash-escape characters that break that syntax.
    254      * Variables are fully expanded - so it is safe for escape $.
    255      * We can't do the escapes here - because we don't know whether
    256      * we will be substituting into ${...} or $(...).
    257      */
    258     {
    259 	char *items;
    260 	(void)Var_Subst(ptr, VAR_GLOBAL, VARE_WANTRES, &items);
    261 	/* TODO: handle errors */
    262 	words = Str_Words(items, FALSE);
    263 	free(items);
    264     }
    265 
    266     {
    267 	size_t i;
    268 
    269 	for (i = 0; i < words.len; i++) {
    270 	    const char *word = words.words[i];
    271 
    272 	    if (word[0] == '\0')
    273 		continue;	/* .for var in ${:U} */
    274 
    275 	    ForAddItem(new_for, word);
    276 	}
    277     }
    278 
    279     Words_Free(words);
    280 
    281     {
    282 	size_t nitems, nvars;
    283 
    284 	if ((nitems = new_for->items.len) > 0 &&
    285 	    nitems % (nvars = new_for->vars.len)) {
    286 	    Parse_Error(PARSE_FATAL,
    287 			"Wrong number of words (%zu) in .for substitution list"
    288 			" with %zu vars", nitems, nvars);
    289 	    /*
    290 	     * Return 'success' so that the body of the .for loop is
    291 	     * accumulated.
    292 	     * Remove all items so that the loop doesn't iterate.
    293 	     */
    294 	    while (new_for->items.len > 0)
    295 		ForItemDone(Vector_Pop(&new_for->items));
    296 	}
    297     }
    298 
    299     accumFor = new_for;
    300     forLevel = 1;
    301     return 1;
    302 }
    303 
    304 /*
    305  * Add another line to a .for loop.
    306  * Returns FALSE when the matching .endfor is reached.
    307  */
    308 Boolean
    309 For_Accum(const char *line)
    310 {
    311     const char *ptr = line;
    312 
    313     if (*ptr == '.') {
    314 	ptr++;
    315 	cpp_skip_whitespace(&ptr);
    316 
    317 	if (strncmp(ptr, "endfor", 6) == 0 && (ch_isspace(ptr[6]) || !ptr[6])) {
    318 	    DEBUG1(FOR, "For: end for %d\n", forLevel);
    319 	    if (--forLevel <= 0)
    320 		return FALSE;
    321 	} else if (strncmp(ptr, "for", 3) == 0 && ch_isspace(ptr[3])) {
    322 	    forLevel++;
    323 	    DEBUG1(FOR, "For: new loop %d\n", forLevel);
    324 	}
    325     }
    326 
    327     Buf_AddStr(&accumFor->buf, line);
    328     Buf_AddByte(&accumFor->buf, '\n');
    329     return TRUE;
    330 }
    331 
    332 
    333 static size_t
    334 for_var_len(const char *var)
    335 {
    336     char ch, var_start, var_end;
    337     int depth;
    338     size_t len;
    339 
    340     var_start = *var;
    341     if (var_start == 0)
    342 	/* just escape the $ */
    343 	return 0;
    344 
    345     if (var_start == '(')
    346 	var_end = ')';
    347     else if (var_start == '{')
    348 	var_end = '}';
    349     else
    350 	/* Single char variable */
    351 	return 1;
    352 
    353     depth = 1;
    354     for (len = 1; (ch = var[len++]) != 0;) {
    355 	if (ch == var_start)
    356 	    depth++;
    357 	else if (ch == var_end && --depth == 0)
    358 	    return len;
    359     }
    360 
    361     /* Variable end not found, escape the $ */
    362     return 0;
    363 }
    364 
    365 static void
    366 for_substitute(Buffer *cmds, ForItem *forItem, char ech)
    367 {
    368     const char *item = forItem->value;
    369     ForEscapes escapes = GetEscapes(item);
    370     char ch;
    371 
    372     /* If there were no escapes, or the only escape is the other variable
    373      * terminator, then just substitute the full string */
    374     if (!(escapes & (ech == ')' ? ~(unsigned)FOR_SUB_ESCAPE_BRACE
    375 				: ~(unsigned)FOR_SUB_ESCAPE_PAREN))) {
    376 	Buf_AddStr(cmds, item);
    377 	return;
    378     }
    379 
    380     /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
    381      * :U processing, see ApplyModifier_Defined. */
    382     while ((ch = *item++) != '\0') {
    383 	if (ch == '$') {
    384 	    size_t len = for_var_len(item);
    385 	    if (len != 0) {
    386 		Buf_AddBytes(cmds, item - 1, len + 1);
    387 		item += len;
    388 		continue;
    389 	    }
    390 	    Buf_AddByte(cmds, '\\');
    391 	} else if (ch == ':' || ch == '\\' || ch == ech)
    392 	    Buf_AddByte(cmds, '\\');
    393 	Buf_AddByte(cmds, ch);
    394     }
    395 }
    396 
    397 static void
    398 SubstVarLong(For *arg, const char **inout_cp, const char **inout_cmd_cp,
    399 	     Buffer *cmds, char ech)
    400 {
    401     size_t i;
    402     const char *cp = *inout_cp;
    403     const char *cmd_cp = *inout_cmd_cp;
    404 
    405     for (i = 0; i < arg->vars.len; i++) {
    406 	ForVar *forVar = Vector_Get(&arg->vars, i);
    407 	char *var = forVar->name;
    408 	size_t vlen = forVar->len;
    409 
    410 	/* XXX: undefined behavior for cp if vlen is longer than cp? */
    411 	if (memcmp(cp, var, vlen) != 0)
    412 	    continue;
    413 	/* XXX: why test for backslash here? */
    414 	if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
    415 	    continue;
    416 
    417 	/* Found a variable match. Replace with :U<value> */
    418 	Buf_AddBytesBetween(cmds, cmd_cp, cp);
    419 	Buf_AddStr(cmds, ":U");
    420 	cp += vlen;
    421 	cmd_cp = cp;
    422 	for_substitute(cmds, Vector_Get(&arg->items, arg->sub_next + i), ech);
    423 	break;
    424     }
    425 
    426     *inout_cp = cp;
    427     *inout_cmd_cp = cmd_cp;
    428 }
    429 
    430 static void
    431 SubstVarShort(For *arg, char const ch,
    432 	      const char **inout_cp, const char **input_cmd_cp, Buffer *cmds)
    433 {
    434     const char *cp = *inout_cp;
    435     const char *cmd_cp = *input_cmd_cp;
    436     size_t i;
    437 
    438     /* Probably a single character name, ignore $$ and stupid ones. {*/
    439     if (!arg->short_var || strchr("}):$", ch) != NULL) {
    440 	cp++;
    441 	*inout_cp = cp;
    442 	return;
    443     }
    444 
    445     for (i = 0; i < arg->vars.len; i++) {
    446 	ForVar *forVar = Vector_Get(&arg->vars, i);
    447 	char *var = forVar->name;
    448 	if (var[0] != ch || var[1] != 0)
    449 	    continue;
    450 
    451 	/* Found a variable match. Replace with ${:U<value>} */
    452 	Buf_AddBytesBetween(cmds, cmd_cp, cp);
    453 	Buf_AddStr(cmds, "{:U");
    454 	cmd_cp = ++cp;
    455 	for_substitute(cmds, Vector_Get(&arg->items, arg->sub_next + i), '}');
    456 	Buf_AddByte(cmds, '}');
    457 	break;
    458     }
    459 
    460     *inout_cp = cp;
    461     *input_cmd_cp = cmd_cp;
    462 }
    463 
    464 /*
    465  * Scan the for loop body and replace references to the loop variables
    466  * with variable references that expand to the required text.
    467  *
    468  * Using variable expansions ensures that the .for loop can't generate
    469  * syntax, and that the later parsing will still see a variable.
    470  * We assume that the null variable will never be defined.
    471  *
    472  * The detection of substitutions of the loop control variable is naive.
    473  * Many of the modifiers use \ to escape $ (not $) so it is possible
    474  * to contrive a makefile where an unwanted substitution happens.
    475  */
    476 static char *
    477 ForIterate(void *v_arg, size_t *ret_len)
    478 {
    479     For *arg = v_arg;
    480     const char *cp;
    481     const char *cmd_cp;
    482     const char *body_end;
    483     Buffer cmds;
    484     char *cmds_str;
    485     size_t cmd_len;
    486 
    487     if (arg->sub_next + arg->vars.len > arg->items.len) {
    488 	/* No more iterations */
    489 	For_Free(arg);
    490 	return NULL;
    491     }
    492 
    493     free(arg->parse_buf);
    494     arg->parse_buf = NULL;
    495 
    496     cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
    497     body_end = cmd_cp + cmd_len;
    498     Buf_Init(&cmds, cmd_len + 256);
    499     for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
    500 	char ch, ech;
    501 	ch = *++cp;
    502 	if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
    503 	    cp++;
    504 	    /* Check variable name against the .for loop variables */
    505 	    SubstVarLong(arg, &cp, &cmd_cp, &cmds, ech);
    506 	    continue;
    507 	}
    508 	if (ch == '\0')
    509 	    break;
    510 
    511 	SubstVarShort(arg, ch, &cp, &cmd_cp, &cmds);
    512     }
    513     Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
    514 
    515     *ret_len = Buf_Len(&cmds);
    516     cmds_str = Buf_Destroy(&cmds, FALSE);
    517     DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
    518 
    519     arg->sub_next += arg->vars.len;
    520 
    521     arg->parse_buf = cmds_str;
    522     return cmds_str;
    523 }
    524 
    525 /* Run the for loop, imitating the actions of an include file. */
    526 void
    527 For_Run(int lineno)
    528 {
    529     For *arg;
    530 
    531     arg = accumFor;
    532     accumFor = NULL;
    533 
    534     if (arg->items.len == 0) {
    535 	/* Nothing to expand - possibly due to an earlier syntax error. */
    536 	For_Free(arg);
    537 	return;
    538     }
    539 
    540     Parse_SetInput(NULL, lineno, -1, ForIterate, arg);
    541 }
    542