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