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