Home | History | Annotate | Line # | Download | only in make
for.c revision 1.92
      1 /*	$NetBSD: for.c,v 1.92 2020/10/05 19:27:47 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.92 2020/10/05 19:27:47 rillig Exp $");
     65 
     66 typedef enum {
     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     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     while (TRUE) {
    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), len);
    172 	ptr += len;
    173     }
    174 
    175     if (strlist_num(&new_for->vars) == 0) {
    176 	Parse_Error(PARSE_FATAL, "no iteration variables in for");
    177 	For_Free(new_for);
    178 	return -1;
    179     }
    180 
    181     cpp_skip_whitespace(&ptr);
    182 
    183     /*
    184      * Make a list with the remaining words.
    185      * The values are later substituted as ${:U<value>...} so we must
    186      * backslash-escape characters that break that syntax.
    187      * Variables are fully expanded - so it is safe for escape $.
    188      * We can't do the escapes here - because we don't know whether
    189      * we will be substituting into ${...} or $(...).
    190      */
    191     {
    192 	char *items;
    193 	(void)Var_Subst(ptr, VAR_GLOBAL, VARE_WANTRES, &items);
    194 	/* TODO: handle errors */
    195 	words = Str_Words(items, FALSE);
    196 	free(items);
    197     }
    198 
    199     {
    200 	size_t n;
    201 
    202 	for (n = 0; n < words.len; n++) {
    203 	    ForEscapes escapes;
    204 	    char ch;
    205 
    206 	    ptr = words.words[n];
    207 	    if (ptr[0] == '\0')
    208 		continue;
    209 	    escapes = 0;
    210 	    while ((ch = *ptr++)) {
    211 		switch (ch) {
    212 		case ':':
    213 		case '$':
    214 		case '\\':
    215 		    escapes |= FOR_SUB_ESCAPE_CHAR;
    216 		    break;
    217 		case ')':
    218 		    escapes |= FOR_SUB_ESCAPE_PAREN;
    219 		    break;
    220 		case '}':
    221 		    escapes |= FOR_SUB_ESCAPE_BRACE;
    222 		    break;
    223 		}
    224 	    }
    225 	    /*
    226 	     * We have to dup words[n] to maintain the semantics of
    227 	     * strlist.
    228 	     */
    229 	    strlist_add_str(&new_for->items, bmake_strdup(words.words[n]),
    230 			    escapes);
    231 	}
    232     }
    233 
    234     Words_Free(words);
    235 
    236     {
    237 	size_t len, n;
    238 
    239 	if ((len = strlist_num(&new_for->items)) > 0 &&
    240 	    len % (n = strlist_num(&new_for->vars))) {
    241 	    Parse_Error(PARSE_FATAL,
    242 			"Wrong number of words (%zu) in .for substitution list"
    243 			" with %zu vars", len, n);
    244 	    /*
    245 	     * Return 'success' so that the body of the .for loop is
    246 	     * accumulated.
    247 	     * Remove all items so that the loop doesn't iterate.
    248 	     */
    249 	    strlist_clean(&new_for->items);
    250 	}
    251     }
    252 
    253     accumFor = new_for;
    254     forLevel = 1;
    255     return 1;
    256 }
    257 
    258 /*
    259  * Add another line to a .for loop.
    260  * Returns FALSE when the matching .endfor is reached.
    261  */
    262 Boolean
    263 For_Accum(const char *line)
    264 {
    265     const char *ptr = line;
    266 
    267     if (*ptr == '.') {
    268 	ptr++;
    269 	cpp_skip_whitespace(&ptr);
    270 
    271 	if (strncmp(ptr, "endfor", 6) == 0 && (ch_isspace(ptr[6]) || !ptr[6])) {
    272 	    DEBUG1(FOR, "For: end for %d\n", forLevel);
    273 	    if (--forLevel <= 0)
    274 		return FALSE;
    275 	} else if (strncmp(ptr, "for", 3) == 0 && ch_isspace(ptr[3])) {
    276 	    forLevel++;
    277 	    DEBUG1(FOR, "For: new loop %d\n", forLevel);
    278 	}
    279     }
    280 
    281     Buf_AddStr(&accumFor->buf, line);
    282     Buf_AddByte(&accumFor->buf, '\n');
    283     return TRUE;
    284 }
    285 
    286 
    287 static size_t
    288 for_var_len(const char *var)
    289 {
    290     char ch, var_start, var_end;
    291     int depth;
    292     size_t len;
    293 
    294     var_start = *var;
    295     if (var_start == 0)
    296 	/* just escape the $ */
    297 	return 0;
    298 
    299     if (var_start == '(')
    300 	var_end = ')';
    301     else if (var_start == '{')
    302 	var_end = '}';
    303     else
    304 	/* Single char variable */
    305 	return 1;
    306 
    307     depth = 1;
    308     for (len = 1; (ch = var[len++]) != 0;) {
    309 	if (ch == var_start)
    310 	    depth++;
    311 	else if (ch == var_end && --depth == 0)
    312 	    return len;
    313     }
    314 
    315     /* Variable end not found, escape the $ */
    316     return 0;
    317 }
    318 
    319 static void
    320 for_substitute(Buffer *cmds, strlist_t *items, unsigned int item_no, char ech)
    321 {
    322     const char *item = strlist_str(items, item_no);
    323     ForEscapes escapes = strlist_info(items, item_no);
    324     char ch;
    325 
    326     /* If there were no escapes, or the only escape is the other variable
    327      * terminator, then just substitute the full string */
    328     if (!(escapes &
    329 	  (ech == ')' ? ~FOR_SUB_ESCAPE_BRACE : ~FOR_SUB_ESCAPE_PAREN))) {
    330 	Buf_AddStr(cmds, item);
    331 	return;
    332     }
    333 
    334     /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
    335      * :U processing, see ApplyModifier_Defined. */
    336     while ((ch = *item++) != 0) {
    337 	if (ch == '$') {
    338 	    size_t len = for_var_len(item);
    339 	    if (len != 0) {
    340 		Buf_AddBytes(cmds, item - 1, len + 1);
    341 		item += len;
    342 		continue;
    343 	    }
    344 	    Buf_AddByte(cmds, '\\');
    345 	} else if (ch == ':' || ch == '\\' || ch == ech)
    346 	    Buf_AddByte(cmds, '\\');
    347 	Buf_AddByte(cmds, ch);
    348     }
    349 }
    350 
    351 static char *
    352 ForIterate(void *v_arg, size_t *ret_len)
    353 {
    354     For *arg = v_arg;
    355     int i;
    356     char *var;
    357     const char *cp;
    358     const char *cmd_cp;
    359     const char *body_end;
    360     char ch;
    361     Buffer cmds;
    362     char *cmds_str;
    363     size_t cmd_len;
    364 
    365     if (arg->sub_next + strlist_num(&arg->vars) > strlist_num(&arg->items)) {
    366 	/* No more iterations */
    367 	For_Free(arg);
    368 	return NULL;
    369     }
    370 
    371     free(arg->parse_buf);
    372     arg->parse_buf = NULL;
    373 
    374     /*
    375      * Scan the for loop body and replace references to the loop variables
    376      * with variable references that expand to the required text.
    377      * Using variable expansions ensures that the .for loop can't generate
    378      * syntax, and that the later parsing will still see a variable.
    379      * We assume that the null variable will never be defined.
    380      *
    381      * The detection of substitutions of the loop control variable is naive.
    382      * Many of the modifiers use \ to escape $ (not $) so it is possible
    383      * to contrive a makefile where an unwanted substitution happens.
    384      */
    385 
    386     cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
    387     body_end = cmd_cp + cmd_len;
    388     Buf_Init(&cmds, cmd_len + 256);
    389     for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
    390 	char ech;
    391 	ch = *++cp;
    392 	if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
    393 	    cp++;
    394 	    /* Check variable name against the .for loop variables */
    395 	    STRLIST_FOREACH(var, &arg->vars, i) {
    396 		size_t vlen = strlist_info(&arg->vars, i);
    397 		if (memcmp(cp, var, vlen) != 0)
    398 		    continue;
    399 		if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
    400 		    continue;
    401 		/* Found a variable match. Replace with :U<value> */
    402 		Buf_AddBytesBetween(&cmds, cmd_cp, cp);
    403 		Buf_AddStr(&cmds, ":U");
    404 		cp += vlen;
    405 		cmd_cp = cp;
    406 		for_substitute(&cmds, &arg->items, arg->sub_next + i, ech);
    407 		break;
    408 	    }
    409 	    continue;
    410 	}
    411 	if (ch == 0)
    412 	    break;
    413 	/* Probably a single character name, ignore $$ and stupid ones. {*/
    414 	if (!arg->short_var || strchr("}):$", ch) != NULL) {
    415 	    cp++;
    416 	    continue;
    417 	}
    418 	STRLIST_FOREACH(var, &arg->vars, i) {
    419 	    if (var[0] != ch || var[1] != 0)
    420 		continue;
    421 	    /* Found a variable match. Replace with ${:U<value>} */
    422 	    Buf_AddBytesBetween(&cmds, cmd_cp, cp);
    423 	    Buf_AddStr(&cmds, "{:U");
    424 	    cmd_cp = ++cp;
    425 	    for_substitute(&cmds, &arg->items, arg->sub_next + i, '}');
    426 	    Buf_AddByte(&cmds, '}');
    427 	    break;
    428 	}
    429     }
    430     Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
    431 
    432     *ret_len = Buf_Len(&cmds);
    433     cmds_str = Buf_Destroy(&cmds, FALSE);
    434     DEBUG1(FOR, "For: loop body:\n%s", cmds_str);
    435 
    436     arg->sub_next += strlist_num(&arg->vars);
    437 
    438     arg->parse_buf = cmds_str;
    439     return cmds_str;
    440 }
    441 
    442 /* Run the for loop, imitating the actions of an include file. */
    443 void
    444 For_Run(int lineno)
    445 {
    446     For *arg;
    447 
    448     arg = accumFor;
    449     accumFor = NULL;
    450 
    451     if (strlist_num(&arg->items) == 0) {
    452 	/* Nothing to expand - possibly due to an earlier syntax error. */
    453 	For_Free(arg);
    454 	return;
    455     }
    456 
    457     Parse_SetInput(NULL, lineno, -1, ForIterate, arg);
    458 }
    459