Home | History | Annotate | Line # | Download | only in make
for.c revision 1.94
      1 /*	$NetBSD: for.c,v 1.94 2020/10/18 17:19:54 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 #include    "strlist.h"
     62 
     63 /*	"@(#)for.c	8.1 (Berkeley) 6/6/93"	*/
     64 MAKE_RCSID("$NetBSD: for.c,v 1.94 2020/10/18 17:19:54 rillig Exp $");
     65 
     66 typedef enum ForEscapes {
     67     FOR_SUB_ESCAPE_CHAR = 0x0001,
     68     FOR_SUB_ESCAPE_BRACE = 0x0002,
     69     FOR_SUB_ESCAPE_PAREN = 0x0004
     70 } ForEscapes;
     71 
     72 static int forLevel = 0;	/* Nesting level */
     73 
     74 /*
     75  * State of a for loop.
     76  */
     77 typedef struct For {
     78     Buffer buf;			/* Body of loop */
     79     strlist_t vars;		/* Iteration variables */
     80     strlist_t items;		/* Substitution items */
     81     char *parse_buf;
     82     /* Is any of the names 1 character long? If so, when the variable values
     83      * are substituted, the parser must handle $V expressions as well, not
     84      * only ${V} and $(V). */
     85     Boolean short_var;
     86     unsigned int sub_next;
     87 } For;
     88 
     89 static For *accumFor;		/* Loop being accumulated */
     90 
     91 
     92 static void
     93 For_Free(For *arg)
     94 {
     95     Buf_Destroy(&arg->buf, TRUE);
     96     strlist_clean(&arg->vars);
     97     strlist_clean(&arg->items);
     98     free(arg->parse_buf);
     99 
    100     free(arg);
    101 }
    102 
    103 /* Evaluate the for loop in the passed line. The line looks like this:
    104  *	.for <varname...> in <value...>
    105  *
    106  * Input:
    107  *	line		Line to parse
    108  *
    109  * Results:
    110  *      0: Not a .for statement, parse the line
    111  *	1: We found a for loop
    112  *     -1: A .for statement with a bad syntax error, discard.
    113  */
    114 int
    115 For_Eval(const char *line)
    116 {
    117     For *new_for;
    118     const char *ptr;
    119     Words words;
    120 
    121     /* Skip the '.' and any following whitespace */
    122     ptr = line + 1;
    123     cpp_skip_whitespace(&ptr);
    124 
    125     /*
    126      * If we are not in a for loop quickly determine if the statement is
    127      * a for.
    128      */
    129     if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
    130 	!ch_isspace(ptr[3])) {
    131 	if (ptr[0] == 'e' && strncmp(ptr + 1, "ndfor", 5) == 0) {
    132 	    Parse_Error(PARSE_FATAL, "for-less endfor");
    133 	    return -1;
    134 	}
    135 	return 0;
    136     }
    137     ptr += 3;
    138 
    139     /*
    140      * we found a for loop, and now we are going to parse it.
    141      */
    142 
    143     new_for = bmake_malloc(sizeof *new_for);
    144     Buf_Init(&new_for->buf, 0);
    145     strlist_init(&new_for->vars);
    146     strlist_init(&new_for->items);
    147     new_for->parse_buf = NULL;
    148     new_for->short_var = FALSE;
    149     new_for->sub_next = 0;
    150 
    151     /* Grab the variables. Terminate on "in". */
    152     for (;;) {
    153 	size_t len;
    154 
    155 	cpp_skip_whitespace(&ptr);
    156 	if (*ptr == '\0') {
    157 	    Parse_Error(PARSE_FATAL, "missing `in' in for");
    158 	    For_Free(new_for);
    159 	    return -1;
    160 	}
    161 
    162 	for (len = 1; ptr[len] && !ch_isspace(ptr[len]); len++)
    163 	    continue;
    164 	if (len == 2 && ptr[0] == 'i' && ptr[1] == 'n') {
    165 	    ptr += 2;
    166 	    break;
    167 	}
    168 	if (len == 1)
    169 	    new_for->short_var = TRUE;
    170 
    171 	strlist_add_str(&new_for->vars, bmake_strldup(ptr, len),
    172 			(unsigned int)len);
    173 	ptr += len;
    174     }
    175 
    176     if (strlist_num(&new_for->vars) == 0) {
    177 	Parse_Error(PARSE_FATAL, "no iteration variables in for");
    178 	For_Free(new_for);
    179 	return -1;
    180     }
    181 
    182     cpp_skip_whitespace(&ptr);
    183 
    184     /*
    185      * Make a list with the remaining words.
    186      * The values are later substituted as ${:U<value>...} so we must
    187      * backslash-escape characters that break that syntax.
    188      * Variables are fully expanded - so it is safe for escape $.
    189      * We can't do the escapes here - because we don't know whether
    190      * we will be substituting into ${...} or $(...).
    191      */
    192     {
    193 	char *items;
    194 	(void)Var_Subst(ptr, VAR_GLOBAL, VARE_WANTRES, &items);
    195 	/* TODO: handle errors */
    196 	words = Str_Words(items, FALSE);
    197 	free(items);
    198     }
    199 
    200     {
    201 	size_t n;
    202 
    203 	for (n = 0; n < words.len; n++) {
    204 	    ForEscapes escapes;
    205 	    char ch;
    206 
    207 	    ptr = words.words[n];
    208 	    if (ptr[0] == '\0')
    209 		continue;
    210 	    escapes = 0;
    211 	    while ((ch = *ptr++)) {
    212 		switch (ch) {
    213 		case ':':
    214 		case '$':
    215 		case '\\':
    216 		    escapes |= FOR_SUB_ESCAPE_CHAR;
    217 		    break;
    218 		case ')':
    219 		    escapes |= FOR_SUB_ESCAPE_PAREN;
    220 		    break;
    221 		case '}':
    222 		    escapes |= FOR_SUB_ESCAPE_BRACE;
    223 		    break;
    224 		}
    225 	    }
    226 	    /*
    227 	     * We have to dup words[n] to maintain the semantics of
    228 	     * strlist.
    229 	     */
    230 	    strlist_add_str(&new_for->items, bmake_strdup(words.words[n]),
    231 			    escapes);
    232 	}
    233     }
    234 
    235     Words_Free(words);
    236 
    237     {
    238 	size_t len, n;
    239 
    240 	if ((len = strlist_num(&new_for->items)) > 0 &&
    241 	    len % (n = strlist_num(&new_for->vars))) {
    242 	    Parse_Error(PARSE_FATAL,
    243 			"Wrong number of words (%zu) in .for substitution list"
    244 			" with %zu vars", len, n);
    245 	    /*
    246 	     * Return 'success' so that the body of the .for loop is
    247 	     * accumulated.
    248 	     * Remove all items so that the loop doesn't iterate.
    249 	     */
    250 	    strlist_clean(&new_for->items);
    251 	}
    252     }
    253 
    254     accumFor = new_for;
    255     forLevel = 1;
    256     return 1;
    257 }
    258 
    259 /*
    260  * Add another line to a .for loop.
    261  * Returns FALSE when the matching .endfor is reached.
    262  */
    263 Boolean
    264 For_Accum(const char *line)
    265 {
    266     const char *ptr = line;
    267 
    268     if (*ptr == '.') {
    269 	ptr++;
    270 	cpp_skip_whitespace(&ptr);
    271 
    272 	if (strncmp(ptr, "endfor", 6) == 0 && (ch_isspace(ptr[6]) || !ptr[6])) {
    273 	    DEBUG1(FOR, "For: end for %d\n", forLevel);
    274 	    if (--forLevel <= 0)
    275 		return FALSE;
    276 	} else if (strncmp(ptr, "for", 3) == 0 && ch_isspace(ptr[3])) {
    277 	    forLevel++;
    278 	    DEBUG1(FOR, "For: new loop %d\n", forLevel);
    279 	}
    280     }
    281 
    282     Buf_AddStr(&accumFor->buf, line);
    283     Buf_AddByte(&accumFor->buf, '\n');
    284     return TRUE;
    285 }
    286 
    287 
    288 static size_t
    289 for_var_len(const char *var)
    290 {
    291     char ch, var_start, var_end;
    292     int depth;
    293     size_t len;
    294 
    295     var_start = *var;
    296     if (var_start == 0)
    297 	/* just escape the $ */
    298 	return 0;
    299 
    300     if (var_start == '(')
    301 	var_end = ')';
    302     else if (var_start == '{')
    303 	var_end = '}';
    304     else
    305 	/* Single char variable */
    306 	return 1;
    307 
    308     depth = 1;
    309     for (len = 1; (ch = var[len++]) != 0;) {
    310 	if (ch == var_start)
    311 	    depth++;
    312 	else if (ch == var_end && --depth == 0)
    313 	    return len;
    314     }
    315 
    316     /* Variable end not found, escape the $ */
    317     return 0;
    318 }
    319 
    320 static void
    321 for_substitute(Buffer *cmds, strlist_t *items, unsigned int item_no, char ech)
    322 {
    323     const char *item = strlist_str(items, item_no);
    324     ForEscapes escapes = strlist_info(items, item_no);
    325     char ch;
    326 
    327     /* If there were no escapes, or the only escape is the other variable
    328      * terminator, then just substitute the full string */
    329     if (!(escapes & (ech == ')' ? ~(unsigned)FOR_SUB_ESCAPE_BRACE
    330 				: ~(unsigned)FOR_SUB_ESCAPE_PAREN))) {
    331 	Buf_AddStr(cmds, item);
    332 	return;
    333     }
    334 
    335     /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
    336      * :U processing, see ApplyModifier_Defined. */
    337     while ((ch = *item++) != 0) {
    338 	if (ch == '$') {
    339 	    size_t len = for_var_len(item);
    340 	    if (len != 0) {
    341 		Buf_AddBytes(cmds, item - 1, len + 1);
    342 		item += len;
    343 		continue;
    344 	    }
    345 	    Buf_AddByte(cmds, '\\');
    346 	} else if (ch == ':' || ch == '\\' || ch == ech)
    347 	    Buf_AddByte(cmds, '\\');
    348 	Buf_AddByte(cmds, ch);
    349     }
    350 }
    351 
    352 static char *
    353 ForIterate(void *v_arg, size_t *ret_len)
    354 {
    355     For *arg = v_arg;
    356     unsigned int i;
    357     char *var;
    358     const char *cp;
    359     const char *cmd_cp;
    360     const char *body_end;
    361     char ch;
    362     Buffer cmds;
    363     char *cmds_str;
    364     size_t cmd_len;
    365 
    366     if (arg->sub_next + strlist_num(&arg->vars) > strlist_num(&arg->items)) {
    367 	/* No more iterations */
    368 	For_Free(arg);
    369 	return NULL;
    370     }
    371 
    372     free(arg->parse_buf);
    373     arg->parse_buf = NULL;
    374 
    375     /*
    376      * Scan the for loop body and replace references to the loop variables
    377      * with variable references that expand to the required text.
    378      * Using variable expansions ensures that the .for loop can't generate
    379      * syntax, and that the later parsing will still see a variable.
    380      * We assume that the null variable will never be defined.
    381      *
    382      * The detection of substitutions of the loop control variable is naive.
    383      * Many of the modifiers use \ to escape $ (not $) so it is possible
    384      * to contrive a makefile where an unwanted substitution happens.
    385      */
    386 
    387     cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
    388     body_end = cmd_cp + cmd_len;
    389     Buf_Init(&cmds, cmd_len + 256);
    390     for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
    391 	char ech;
    392 	ch = *++cp;
    393 	if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
    394 	    cp++;
    395 	    /* Check variable name against the .for loop variables */
    396 	    STRLIST_FOREACH(var, &arg->vars, i) {
    397 		size_t vlen = strlist_info(&arg->vars, i);
    398 		if (memcmp(cp, var, vlen) != 0)
    399 		    continue;
    400 		if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
    401 		    continue;
    402 		/* Found a variable match. Replace with :U<value> */
    403 		Buf_AddBytesBetween(&cmds, cmd_cp, cp);
    404 		Buf_AddStr(&cmds, ":U");
    405 		cp += vlen;
    406 		cmd_cp = cp;
    407 		for_substitute(&cmds, &arg->items, arg->sub_next + i, ech);
    408 		break;
    409 	    }
    410 	    continue;
    411 	}
    412 	if (ch == 0)
    413 	    break;
    414 	/* Probably a single character name, ignore $$ and stupid ones. {*/
    415 	if (!arg->short_var || strchr("}):$", ch) != NULL) {
    416 	    cp++;
    417 	    continue;
    418 	}
    419 	STRLIST_FOREACH(var, &arg->vars, i) {
    420 	    if (var[0] != ch || var[1] != 0)
    421 		continue;
    422 	    /* Found a variable match. Replace with ${:U<value>} */
    423 	    Buf_AddBytesBetween(&cmds, cmd_cp, cp);
    424 	    Buf_AddStr(&cmds, "{:U");
    425 	    cmd_cp = ++cp;
    426 	    for_substitute(&cmds, &arg->items, arg->sub_next + i, '}');
    427 	    Buf_AddByte(&cmds, '}');
    428 	    break;
    429 	}
    430     }
    431     Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
    432 
    433     *ret_len = Buf_Len(&cmds);
    434     cmds_str = Buf_Destroy(&cmds, FALSE);
    435     DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
    436 
    437     arg->sub_next += strlist_num(&arg->vars);
    438 
    439     arg->parse_buf = cmds_str;
    440     return cmds_str;
    441 }
    442 
    443 /* Run the for loop, imitating the actions of an include file. */
    444 void
    445 For_Run(int lineno)
    446 {
    447     For *arg;
    448 
    449     arg = accumFor;
    450     accumFor = NULL;
    451 
    452     if (strlist_num(&arg->items) == 0) {
    453 	/* Nothing to expand - possibly due to an earlier syntax error. */
    454 	For_Free(arg);
    455 	return;
    456     }
    457 
    458     Parse_SetInput(NULL, lineno, -1, ForIterate, arg);
    459 }
    460