/* $NetBSD: for.c,v 1.186 2025/06/28 22:39:27 rillig Exp $ */12/*3* Copyright (c) 1992, The Regents of the University of California.4* All rights reserved.5*6* Redistribution and use in source and binary forms, with or without7* modification, are permitted provided that the following conditions8* are met:9* 1. Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11* 2. Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14* 3. Neither the name of the University nor the names of its contributors15* may be used to endorse or promote products derived from this software16* without specific prior written permission.17*18* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND19* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE20* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE21* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE22* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL23* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS24* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)25* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT26* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY27* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF28* SUCH DAMAGE.29*/3031/*32* Handling of .for/.endfor loops in a makefile.33*34* For loops have the form:35*36* .for <varname...> in <value...>37* # the body38* .endfor39*40* When a .for line is parsed, the following lines are copied to the body of41* the .for loop, until the corresponding .endfor line is reached. In this42* phase, the body is not yet evaluated. This also applies to any nested43* .for loops.44*45* After reaching the .endfor, the values from the .for line are grouped46* according to the number of variables. For each such group, the unexpanded47* body is scanned for expressions, and those that match the48* variable names are replaced with expressions of the form ${:U...}. After49* that, the body is treated like a file from an .include directive.50*51* Interface:52* For_Eval Evaluate the loop in the passed line.53*54* For_Run Run accumulated loop55*/5657#include "make.h"5859/* "@(#)for.c 8.1 (Berkeley) 6/6/93" */60MAKE_RCSID("$NetBSD: for.c,v 1.186 2025/06/28 22:39:27 rillig Exp $");616263typedef struct ForLoop {64Vector /* of 'char *' */ vars; /* Iteration variables */65SubstringWords items; /* Substitution items */66Buffer body; /* Unexpanded body of the loop */67unsigned nextItem; /* Where to continue iterating */68} ForLoop;697071static ForLoop *accumFor; /* Loop being accumulated */727374/* See LK_FOR_BODY. */75static void76skip_whitespace_or_line_continuation(const char **pp)77{78const char *p = *pp;79for (;;) {80if (ch_isspace(*p))81p++;82else if (p[0] == '\\' && p[1] == '\n')83p += 2;84else85break;86}87*pp = p;88}8990static ForLoop *91ForLoop_New(void)92{93ForLoop *f = bmake_malloc(sizeof *f);9495Vector_Init(&f->vars, sizeof(char *));96SubstringWords_Init(&f->items);97Buf_Init(&f->body);98f->nextItem = 0;99100return f;101}102103void104ForLoop_Free(ForLoop *f)105{106while (f->vars.len > 0)107free(*(char **)Vector_Pop(&f->vars));108Vector_Done(&f->vars);109110SubstringWords_Free(f->items);111Buf_Done(&f->body);112113free(f);114}115116char *117ForLoop_Details(const ForLoop *f)118{119size_t i, n;120const char **vars;121const Substring *items;122Buffer buf;123124n = f->vars.len;125vars = f->vars.items;126assert(f->nextItem >= n);127items = f->items.words + f->nextItem - n;128129Buf_Init(&buf);130for (i = 0; i < n; i++) {131if (i > 0)132Buf_AddStr(&buf, ", ");133Buf_AddStr(&buf, vars[i]);134Buf_AddStr(&buf, " = ");135Buf_AddRange(&buf, items[i].start, items[i].end);136}137return Buf_DoneData(&buf);138}139140static bool141IsValidInVarname(char c)142{143return c != '$' && c != ':' && c != '\\' &&144c != '(' && c != '{' && c != ')' && c != '}';145}146147static void148ForLoop_ParseVarnames(ForLoop *f, const char **pp)149{150const char *p = *pp, *start;151152for (;;) {153cpp_skip_whitespace(&p);154if (*p == '\0') {155Parse_Error(PARSE_FATAL,156"Missing \"in\" in .for loop");157goto cleanup;158}159160for (start = p; *p != '\0' && !ch_isspace(*p); p++)161if (!IsValidInVarname(*p))162goto invalid_variable_name;163164if (p - start == 2 && memcmp(start, "in", 2) == 0)165break;166167*(char **)Vector_Push(&f->vars) = bmake_strsedup(start, p);168}169170if (f->vars.len == 0) {171Parse_Error(PARSE_FATAL,172"Missing iteration variables in .for loop");173return;174}175176*pp = p;177return;178179invalid_variable_name:180Parse_Error(PARSE_FATAL,181"Invalid character \"%c\" in .for loop variable name", *p);182cleanup:183while (f->vars.len > 0)184free(*(char **)Vector_Pop(&f->vars));185}186187static bool188ForLoop_ParseItems(ForLoop *f, const char *p)189{190char *items;191int parseErrorsBefore = parseErrors;192193cpp_skip_whitespace(&p);194195items = Var_Subst(p, SCOPE_GLOBAL, VARE_EVAL);196f->items = Substring_Words(197parseErrors == parseErrorsBefore ? items : "", false);198free(items);199200if (f->items.len == 1 && Substring_IsEmpty(f->items.words[0]))201f->items.len = 0; /* .for var in ${:U} */202203if (f->items.len % f->vars.len != 0) {204Parse_Error(PARSE_FATAL,205"Wrong number of words (%u) in .for "206"substitution list with %u variables",207(unsigned)f->items.len, (unsigned)f->vars.len);208return false;209}210211return true;212}213214static bool215IsFor(const char *p)216{217return p[0] == 'f' && p[1] == 'o' && p[2] == 'r' && ch_isspace(p[3]);218}219220static bool221IsEndfor(const char *p)222{223return p[0] == 'e' && strncmp(p, "endfor", 6) == 0 &&224(p[6] == '\0' || ch_isspace(p[6]));225}226227/*228* Evaluate the for loop in the passed line. The line looks like this:229* .for <varname...> in <value...>230*231* Results:232* 0 not a .for directive233* 1 found a .for directive234* -1 erroneous .for directive235*/236int237For_Eval(const char *line)238{239const char *p;240ForLoop *f;241242p = line + 1; /* skip the '.' */243skip_whitespace_or_line_continuation(&p);244245if (IsFor(p)) {246p += 3;247248f = ForLoop_New();249ForLoop_ParseVarnames(f, &p);250if (f->vars.len > 0 && !ForLoop_ParseItems(f, p))251f->items.len = 0; /* don't iterate */252253accumFor = f;254return 1;255} else if (IsEndfor(p)) {256Parse_Error(PARSE_FATAL, "for-less endfor");257return -1;258} else259return 0;260}261262/*263* Add another line to the .for loop that is being built up.264* Returns false when the matching .endfor is reached.265*/266bool267For_Accum(const char *line, int *forLevel)268{269const char *p = line;270271if (*p == '.') {272p++;273skip_whitespace_or_line_continuation(&p);274275if (IsEndfor(p)) {276DEBUG1(FOR, "For: end for %d\n", *forLevel);277if (--*forLevel == 0)278return false;279} else if (IsFor(p)) {280(*forLevel)++;281DEBUG1(FOR, "For: new loop %d\n", *forLevel);282}283}284285Buf_AddStr(&accumFor->body, line);286Buf_AddByte(&accumFor->body, '\n');287return true;288}289290/*291* When the body of a '.for i' loop is prepared for an iteration, each292* occurrence of $i in the body is replaced with ${:U...}, inserting the293* value of the item. If this item contains a '$', it may be the start of an294* expression. This expression is copied verbatim, its length is295* determined here, in a rather naive way, ignoring escape characters and296* funny delimiters in modifiers like ':S}from}to}'.297*/298static size_t299ExprLen(const char *s, const char *e)300{301char expr_open, expr_close;302int depth;303const char *p;304305if (s == e)306return 0; /* just escape the '$' */307308expr_open = s[0];309if (expr_open == '(')310expr_close = ')';311else if (expr_open == '{')312expr_close = '}';313else314return 1; /* Single char variable */315316depth = 1;317for (p = s + 1; p != e; p++) {318if (*p == expr_open)319depth++;320else if (*p == expr_close && --depth == 0)321return (size_t)(p + 1 - s);322}323324/* Expression end not found, escape the $ */325return 0;326}327328/*329* While expanding the body of a .for loop, write the item as a ${:U...}330* expression, escaping characters as needed. The result is later unescaped331* by ApplyModifier_Defined.332*/333static void334AddEscaped(Buffer *body, Substring item, char endc)335{336const char *p;337char ch;338339for (p = item.start; p != item.end;) {340ch = *p;341if (ch == '$') {342size_t len = ExprLen(p + 1, item.end);343if (len != 0) {344/*345* XXX: Should a '\' be added here?346* See directive-for-escape.mk, ExprLen.347*/348Buf_AddBytes(body, p, 1 + len);349p += 1 + len;350continue;351}352Buf_AddByte(body, '\\');353} else if (ch == ':' || ch == '\\' || ch == endc)354Buf_AddByte(body, '\\');355else if (ch == '\n') {356Parse_Error(PARSE_FATAL, "newline in .for value");357ch = ' '; /* prevent newline injection */358}359Buf_AddByte(body, ch);360p++;361}362}363364/*365* While expanding the body of a .for loop, replace the variable name of an366* expression like ${i} or ${i:...} or $(i) or $(i:...) with ":Uvalue".367*/368static void369ForLoop_SubstVarLong(ForLoop *f, unsigned firstItem, Buffer *body,370const char **pp, char endc, const char **inout_mark)371{372size_t i;373const char *start = *pp;374const char **varnames = Vector_Get(&f->vars, 0);375376for (i = 0; i < f->vars.len; i++) {377const char *p = start;378379if (!cpp_skip_string(&p, varnames[i]))380continue;381/* XXX: why test for backslash here? */382if (*p != ':' && *p != endc && *p != '\\')383continue;384385/*386* Found a variable match. Skip over the variable name and387* instead add ':U<value>' to the current body.388*/389Buf_AddRange(body, *inout_mark, start);390Buf_AddStr(body, ":U");391AddEscaped(body, f->items.words[firstItem + i], endc);392393*inout_mark = p;394*pp = p;395return;396}397}398399/*400* While expanding the body of a .for loop, replace single-character401* expressions like $i with their ${:U...} expansion.402*/403static void404ForLoop_SubstVarShort(ForLoop *f, unsigned firstItem, Buffer *body,405const char *p, const char **inout_mark)406{407char ch = *p;408const char **vars;409size_t i;410411/* Skip $$ and stupid ones. */412if (ch == '}' || ch == ')' || ch == ':' || ch == '$')413return;414415vars = Vector_Get(&f->vars, 0);416for (i = 0; i < f->vars.len; i++) {417const char *varname = vars[i];418if (varname[0] == ch && varname[1] == '\0')419goto found;420}421return;422423found:424Buf_AddRange(body, *inout_mark, p);425*inout_mark = p + 1;426427/* Replace $<ch> with ${:U<value>} */428Buf_AddStr(body, "{:U");429AddEscaped(body, f->items.words[firstItem + i], '}');430Buf_AddByte(body, '}');431}432433/*434* Compute the body for the current iteration by copying the unexpanded body,435* replacing the expressions for the iteration variables on the way.436*437* Using expressions ensures that the .for loop can't generate438* syntax, and that the later parsing will still see an expression.439* This code assumes that the variable with the empty name is never defined,440* see unit-tests/varname-empty.mk.441*442* The detection of substitutions of the loop control variables is naive.443* Many of the modifiers use '\$' instead of '$$' to escape '$', so it is444* possible to contrive a makefile where an unwanted substitution happens.445* See unit-tests/directive-for-escape.mk.446*/447static void448ForLoop_SubstBody(ForLoop *f, unsigned firstItem, Buffer *body)449{450const char *p, *end;451const char *mark; /* where the last substitution left off */452453Buf_Clear(body);454455mark = f->body.data;456end = f->body.data + f->body.len;457for (p = mark; (p = strchr(p, '$')) != NULL;) {458if (p[1] == '{' || p[1] == '(') {459char endc = p[1] == '{' ? '}' : ')';460p += 2;461ForLoop_SubstVarLong(f, firstItem, body,462&p, endc, &mark);463} else {464ForLoop_SubstVarShort(f, firstItem, body,465p + 1, &mark);466p += 2;467}468}469470Buf_AddRange(body, mark, end);471}472473/*474* Compute the body for the current iteration by copying the unexpanded body,475* replacing the expressions for the iteration variables on the way.476*/477bool478For_NextIteration(ForLoop *f, Buffer *body)479{480if (f->nextItem == f->items.len)481return false;482483f->nextItem += (unsigned)f->vars.len;484ForLoop_SubstBody(f, f->nextItem - (unsigned)f->vars.len, body);485if (DEBUG(FOR)) {486char *details = ForLoop_Details(f);487debug_printf("For: loop body with %s:\n%s",488details, body->data);489free(details);490}491return true;492}493494/* Break out of the .for loop. */495void496For_Break(ForLoop *f)497{498f->nextItem = (unsigned)f->items.len;499}500501/* Run the .for loop, imitating the actions of an include file. */502void503For_Run(unsigned headLineno, unsigned bodyReadLines)504{505Buffer buf;506ForLoop *f = accumFor;507accumFor = NULL;508509if (f->items.len > 0) {510Buf_Init(&buf);511Parse_PushInput(NULL, headLineno, bodyReadLines, buf, f);512} else513ForLoop_Free(f);514}515516517