for.c revision 1.85 1 /* $NetBSD: for.c,v 1.85 2020/09/22 20:19:46 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 * For_Run Run accumulated loop
57 */
58
59 #include "make.h"
60 #include "strlist.h"
61
62 /* "@(#)for.c 8.1 (Berkeley) 6/6/93" */
63 MAKE_RCSID("$NetBSD: for.c,v 1.85 2020/09/22 20:19:46 rillig Exp $");
64
65 typedef enum {
66 FOR_SUB_ESCAPE_CHAR = 0x0001,
67 FOR_SUB_ESCAPE_BRACE = 0x0002,
68 FOR_SUB_ESCAPE_PAREN = 0x0004
69 } ForEscapes;
70
71 static int forLevel = 0; /* Nesting level */
72
73 /*
74 * State of a for loop.
75 */
76 typedef struct {
77 Buffer buf; /* Body of loop */
78 strlist_t vars; /* Iteration variables */
79 strlist_t items; /* Substitution items */
80 char *parse_buf;
81 /* Is any of the names 1 character long? If so, when the variable values
82 * are substituted, the parser must handle $V expressions as well, not
83 * only ${V} and $(V). */
84 Boolean short_var;
85 int sub_next;
86 } For;
87
88 static For *accumFor; /* Loop being accumulated */
89
90
91 static void
92 For_Free(For *arg)
93 {
94 Buf_Destroy(&arg->buf, TRUE);
95 strlist_clean(&arg->vars);
96 strlist_clean(&arg->items);
97 free(arg->parse_buf);
98
99 free(arg);
100 }
101
102 /* Evaluate the for loop in the passed line. The line looks like this:
103 * .for <varname...> in <value...>
104 *
105 * Input:
106 * line Line to parse
107 *
108 * Results:
109 * 0: Not a .for statement, parse the line
110 * 1: We found a for loop
111 * -1: A .for statement with a bad syntax error, discard.
112 */
113 int
114 For_Eval(const char *line)
115 {
116 For *new_for;
117 const char *ptr;
118 Words words;
119
120 /* Skip the '.' and any following whitespace */
121 for (ptr = line + 1; ch_isspace(*ptr); ptr++)
122 continue;
123
124 /*
125 * If we are not in a for loop quickly determine if the statement is
126 * a for.
127 */
128 if (ptr[0] != 'f' || ptr[1] != 'o' || ptr[2] != 'r' ||
129 !ch_isspace(ptr[3])) {
130 if (ptr[0] == 'e' && strncmp(ptr + 1, "ndfor", 5) == 0) {
131 Parse_Error(PARSE_FATAL, "for-less endfor");
132 return -1;
133 }
134 return 0;
135 }
136 ptr += 3;
137
138 /*
139 * we found a for loop, and now we are going to parse it.
140 */
141
142 new_for = bmake_malloc(sizeof *new_for);
143 Buf_Init(&new_for->buf, 0);
144 strlist_init(&new_for->vars);
145 strlist_init(&new_for->items);
146 new_for->parse_buf = NULL;
147 new_for->short_var = FALSE;
148 new_for->sub_next = 0;
149
150 /* Grab the variables. Terminate on "in". */
151 while (TRUE) {
152 size_t len;
153
154 while (ch_isspace(*ptr))
155 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 while (ch_isspace(*ptr))
182 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
270 for (ptr++; *ptr && ch_isspace(*ptr); ptr++)
271 continue;
272
273 if (strncmp(ptr, "endfor", 6) == 0 && (ch_isspace(ptr[6]) || !ptr[6])) {
274 if (DEBUG(FOR))
275 (void)fprintf(debug_file, "For: end for %d\n", forLevel);
276 if (--forLevel <= 0)
277 return FALSE;
278 } else if (strncmp(ptr, "for", 3) == 0 && ch_isspace(ptr[3])) {
279 forLevel++;
280 if (DEBUG(FOR))
281 (void)fprintf(debug_file, "For: new loop %d\n", forLevel);
282 }
283 }
284
285 Buf_AddStr(&accumFor->buf, line);
286 Buf_AddByte(&accumFor->buf, '\n');
287 return TRUE;
288 }
289
290
291 static size_t
292 for_var_len(const char *var)
293 {
294 char ch, var_start, var_end;
295 int depth;
296 size_t len;
297
298 var_start = *var;
299 if (var_start == 0)
300 /* just escape the $ */
301 return 0;
302
303 if (var_start == '(')
304 var_end = ')';
305 else if (var_start == '{')
306 var_end = '}';
307 else
308 /* Single char variable */
309 return 1;
310
311 depth = 1;
312 for (len = 1; (ch = var[len++]) != 0;) {
313 if (ch == var_start)
314 depth++;
315 else if (ch == var_end && --depth == 0)
316 return len;
317 }
318
319 /* Variable end not found, escape the $ */
320 return 0;
321 }
322
323 static void
324 for_substitute(Buffer *cmds, strlist_t *items, unsigned int item_no, char ech)
325 {
326 const char *item = strlist_str(items, item_no);
327 ForEscapes escapes = strlist_info(items, item_no);
328 char ch;
329
330 /* If there were no escapes, or the only escape is the other variable
331 * terminator, then just substitute the full string */
332 if (!(escapes &
333 (ech == ')' ? ~FOR_SUB_ESCAPE_BRACE : ~FOR_SUB_ESCAPE_PAREN))) {
334 Buf_AddStr(cmds, item);
335 return;
336 }
337
338 /* Escape ':', '$', '\\' and 'ech' - these will be removed later by
339 * :U processing, see ApplyModifier_Defined. */
340 while ((ch = *item++) != 0) {
341 if (ch == '$') {
342 size_t len = for_var_len(item);
343 if (len != 0) {
344 Buf_AddBytes(cmds, item - 1, len + 1);
345 item += len;
346 continue;
347 }
348 Buf_AddByte(cmds, '\\');
349 } else if (ch == ':' || ch == '\\' || ch == ech)
350 Buf_AddByte(cmds, '\\');
351 Buf_AddByte(cmds, ch);
352 }
353 }
354
355 static char *
356 ForIterate(void *v_arg, size_t *ret_len)
357 {
358 For *arg = v_arg;
359 int i;
360 char *var;
361 const char *cp;
362 const char *cmd_cp;
363 const char *body_end;
364 char ch;
365 Buffer cmds;
366 char *cmds_str;
367 size_t cmd_len;
368
369 if (arg->sub_next + strlist_num(&arg->vars) > strlist_num(&arg->items)) {
370 /* No more iterations */
371 For_Free(arg);
372 return NULL;
373 }
374
375 free(arg->parse_buf);
376 arg->parse_buf = NULL;
377
378 /*
379 * Scan the for loop body and replace references to the loop variables
380 * with variable references that expand to the required text.
381 * Using variable expansions ensures that the .for loop can't generate
382 * syntax, and that the later parsing will still see a variable.
383 * We assume that the null variable will never be defined.
384 *
385 * The detection of substitutions of the loop control variable is naive.
386 * Many of the modifiers use \ to escape $ (not $) so it is possible
387 * to contrive a makefile where an unwanted substitution happens.
388 */
389
390 cmd_cp = Buf_GetAll(&arg->buf, &cmd_len);
391 body_end = cmd_cp + cmd_len;
392 Buf_Init(&cmds, cmd_len + 256);
393 for (cp = cmd_cp; (cp = strchr(cp, '$')) != NULL;) {
394 char ech;
395 ch = *++cp;
396 if ((ch == '(' && (ech = ')', 1)) || (ch == '{' && (ech = '}', 1))) {
397 cp++;
398 /* Check variable name against the .for loop variables */
399 STRLIST_FOREACH(var, &arg->vars, i) {
400 size_t vlen = strlist_info(&arg->vars, i);
401 if (memcmp(cp, var, vlen) != 0)
402 continue;
403 if (cp[vlen] != ':' && cp[vlen] != ech && cp[vlen] != '\\')
404 continue;
405 /* Found a variable match. Replace with :U<value> */
406 Buf_AddBytesBetween(&cmds, cmd_cp, cp);
407 Buf_AddStr(&cmds, ":U");
408 cp += vlen;
409 cmd_cp = cp;
410 for_substitute(&cmds, &arg->items, arg->sub_next + i, ech);
411 break;
412 }
413 continue;
414 }
415 if (ch == 0)
416 break;
417 /* Probably a single character name, ignore $$ and stupid ones. {*/
418 if (!arg->short_var || strchr("}):$", ch) != NULL) {
419 cp++;
420 continue;
421 }
422 STRLIST_FOREACH(var, &arg->vars, i) {
423 if (var[0] != ch || var[1] != 0)
424 continue;
425 /* Found a variable match. Replace with ${:U<value>} */
426 Buf_AddBytesBetween(&cmds, cmd_cp, cp);
427 Buf_AddStr(&cmds, "{:U");
428 cmd_cp = ++cp;
429 for_substitute(&cmds, &arg->items, arg->sub_next + i, '}');
430 Buf_AddByte(&cmds, '}');
431 break;
432 }
433 }
434 Buf_AddBytesBetween(&cmds, cmd_cp, body_end);
435
436 *ret_len = Buf_Size(&cmds);
437 cmds_str = Buf_Destroy(&cmds, FALSE);
438 if (DEBUG(FOR))
439 (void)fprintf(debug_file, "For: loop body:\n%s", cmds_str);
440
441 arg->sub_next += strlist_num(&arg->vars);
442
443 arg->parse_buf = cmds_str;
444 return cmds_str;
445 }
446
447 /* Run the for loop, imitating the actions of an include file. */
448 void
449 For_Run(int lineno)
450 {
451 For *arg;
452
453 arg = accumFor;
454 accumFor = NULL;
455
456 if (strlist_num(&arg->items) == 0) {
457 /* Nothing to expand - possibly due to an earlier syntax error. */
458 For_Free(arg);
459 return;
460 }
461
462 Parse_SetInput(NULL, lineno, -1, ForIterate, arg);
463 }
464