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