Home | History | Annotate | Line # | Download | only in make
var.c revision 1.1112
      1 /*	$NetBSD: var.c,v 1.1112 2024/05/25 08:03:19 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 /*
     72  * Handling of variables and the expressions formed from them.
     73  *
     74  * Variables are set using lines of the form VAR=value.  Both the variable
     75  * name and the value can contain references to other variables, by using
     76  * expressions like ${VAR}, ${VAR:Modifiers}, ${${VARNAME}} or ${VAR:${MODS}}.
     77  *
     78  * Interface:
     79  *	Var_Init	Initialize this module.
     80  *
     81  *	Var_End		Clean up the module.
     82  *
     83  *	Var_Set
     84  *	Var_SetExpand	Set the value of the variable, creating it if
     85  *			necessary.
     86  *
     87  *	Var_Append
     88  *	Var_AppendExpand
     89  *			Append more characters to the variable, creating it if
     90  *			necessary. A space is placed between the old value and
     91  *			the new one.
     92  *
     93  *	Var_Exists
     94  *	Var_ExistsExpand
     95  *			See if a variable exists.
     96  *
     97  *	Var_Value	Return the unexpanded value of a variable, or NULL if
     98  *			the variable is undefined.
     99  *
    100  *	Var_Subst	Substitute all expressions in a string.
    101  *
    102  *	Var_Parse	Parse an expression such as ${VAR:Mpattern}.
    103  *
    104  *	Var_Delete	Delete a variable.
    105  *
    106  *	Var_ReexportVars
    107  *			Export some or even all variables to the environment
    108  *			of this process and its child processes.
    109  *
    110  *	Var_Export	Export the variable to the environment of this process
    111  *			and its child processes.
    112  *
    113  *	Var_UnExport	Don't export the variable anymore.
    114  *
    115  * Debugging:
    116  *	Var_Stats	Print out hashing statistics if in -dh mode.
    117  *
    118  *	Var_Dump	Print out all variables defined in the given scope.
    119  */
    120 
    121 #include <sys/stat.h>
    122 #include <sys/types.h>
    123 #include <regex.h>
    124 #include <errno.h>
    125 #include <inttypes.h>
    126 #include <limits.h>
    127 #include <time.h>
    128 
    129 #include "make.h"
    130 #include "dir.h"
    131 #include "job.h"
    132 #include "metachar.h"
    133 
    134 /*	"@(#)var.c	8.3 (Berkeley) 3/19/94" */
    135 MAKE_RCSID("$NetBSD: var.c,v 1.1112 2024/05/25 08:03:19 rillig Exp $");
    136 
    137 /*
    138  * Variables are defined using one of the VAR=value assignments.  Their
    139  * value can be queried by expressions such as $V, ${VAR}, or with modifiers
    140  * such as ${VAR:S,from,to,g:Q}.
    141  *
    142  * There are 3 kinds of variables: scope variables, environment variables,
    143  * undefined variables.
    144  *
    145  * Scope variables are stored in GNode.vars.  The only way to undefine
    146  * a scope variable is using the .undef directive.  In particular, it must
    147  * not be possible to undefine a variable during the evaluation of an
    148  * expression, or Var.name might point nowhere.  (There is another,
    149  * unintended way to undefine a scope variable, see varmod-loop-delete.mk.)
    150  *
    151  * Environment variables are short-lived.  They are returned by VarFind, and
    152  * after using them, they must be freed using VarFreeShortLived.
    153  *
    154  * Undefined variables occur during evaluation of expressions such
    155  * as ${UNDEF:Ufallback} in Var_Parse and ApplyModifiers.
    156  */
    157 typedef struct Var {
    158 	/*
    159 	 * The name of the variable, once set, doesn't change anymore.
    160 	 * For scope variables, it aliases the corresponding HashEntry name.
    161 	 * For environment and undefined variables, it is allocated.
    162 	 */
    163 	FStr name;
    164 
    165 	/* The unexpanded value of the variable. */
    166 	Buffer val;
    167 
    168 	/* The variable came from the command line. */
    169 	bool fromCmd:1;
    170 
    171 	/*
    172 	 * The variable is short-lived.
    173 	 * These variables are not registered in any GNode, therefore they
    174 	 * must be freed after use.
    175 	 */
    176 	bool shortLived:1;
    177 
    178 	/*
    179 	 * The variable comes from the environment.
    180 	 * Appending to its value depends on the scope, see var-op-append.mk.
    181 	 */
    182 	bool fromEnvironment:1;
    183 
    184 	/*
    185 	 * The variable value cannot be changed anymore, and the variable
    186 	 * cannot be deleted.  Any attempts to do so are silently ignored,
    187 	 * they are logged with -dv though.
    188 	 * Use .[NO]READONLY: to adjust.
    189 	 *
    190 	 * See VAR_SET_READONLY.
    191 	 */
    192 	bool readOnly:1;
    193 
    194 	/*
    195 	 * The variable is currently being accessed by Var_Parse or Var_Subst.
    196 	 * This temporary marker is used to avoid endless recursion.
    197 	 */
    198 	bool inUse:1;
    199 
    200 	/*
    201 	 * The variable is exported to the environment, to be used by child
    202 	 * processes.
    203 	 */
    204 	bool exported:1;
    205 
    206 	/*
    207 	 * At the point where this variable was exported, it contained an
    208 	 * unresolved reference to another variable.  Before any child
    209 	 * process is started, it needs to be actually exported, resolving
    210 	 * the referenced variable just in time.
    211 	 */
    212 	bool reexport:1;
    213 } Var;
    214 
    215 /*
    216  * Exporting variables is expensive and may leak memory, so skip it if we
    217  * can.
    218  */
    219 typedef enum VarExportedMode {
    220 	VAR_EXPORTED_NONE,
    221 	VAR_EXPORTED_SOME,
    222 	VAR_EXPORTED_ALL
    223 } VarExportedMode;
    224 
    225 typedef enum UnexportWhat {
    226 	/* Unexport the variables given by name. */
    227 	UNEXPORT_NAMED,
    228 	/*
    229 	 * Unexport all globals previously exported, but keep the environment
    230 	 * inherited from the parent.
    231 	 */
    232 	UNEXPORT_ALL,
    233 	/*
    234 	 * Unexport all globals previously exported and clear the environment
    235 	 * inherited from the parent.
    236 	 */
    237 	UNEXPORT_ENV
    238 } UnexportWhat;
    239 
    240 /* Flags for pattern matching in the :S and :C modifiers */
    241 typedef struct PatternFlags {
    242 	bool subGlobal:1;	/* 'g': replace as often as possible */
    243 	bool subOnce:1;		/* '1': replace only once */
    244 	bool anchorStart:1;	/* '^': match only at start of word */
    245 	bool anchorEnd:1;	/* '$': match only at end of word */
    246 } PatternFlags;
    247 
    248 /* SepBuf builds a string from words interleaved with separators. */
    249 typedef struct SepBuf {
    250 	Buffer buf;
    251 	bool needSep;
    252 	/* Usually ' ', but see the ':ts' modifier. */
    253 	char sep;
    254 } SepBuf;
    255 
    256 typedef struct {
    257 	const char *target;
    258 	const char *varname;
    259 	const char *expr;
    260 } EvalStackElement;
    261 
    262 typedef struct {
    263 	EvalStackElement *elems;
    264 	size_t len;
    265 	size_t cap;
    266 	Buffer details;
    267 } EvalStack;
    268 
    269 /* Whether we have replaced the original environ (which we cannot free). */
    270 char **savedEnv = NULL;
    271 
    272 /*
    273  * Special return value for Var_Parse, indicating a parse error.  It may be
    274  * caused by an undefined variable, a syntax error in a modifier or
    275  * something entirely different.
    276  */
    277 char var_Error[] = "";
    278 
    279 /*
    280  * Special return value for Var_Parse, indicating an undefined variable in
    281  * a case where VARE_UNDEFERR is not set.  This undefined variable is
    282  * typically a dynamic variable such as ${.TARGET}, whose expansion needs to
    283  * be deferred until it is defined in an actual target.
    284  *
    285  * See VARE_EVAL_KEEP_UNDEF.
    286  */
    287 static char varUndefined[] = "";
    288 
    289 /*
    290  * Traditionally this make consumed $$ during := like any other expansion.
    291  * Other make's do not, and this make follows straight since 2016-01-09.
    292  *
    293  * This knob allows controlling the behavior:
    294  *	false to consume $$ during := assignment.
    295  *	true to preserve $$ during := assignment.
    296  */
    297 #define MAKE_SAVE_DOLLARS ".MAKE.SAVE_DOLLARS"
    298 static bool save_dollars = true;
    299 
    300 /*
    301  * A scope collects variable names and their values.
    302  *
    303  * The main scope is SCOPE_GLOBAL, which contains the variables that are set
    304  * in the makefiles.  SCOPE_INTERNAL acts as a fallback for SCOPE_GLOBAL and
    305  * contains some internal make variables.  These internal variables can thus
    306  * be overridden, they can also be restored by undefining the overriding
    307  * variable.
    308  *
    309  * SCOPE_CMDLINE contains variables from the command line arguments.  These
    310  * override variables from SCOPE_GLOBAL.
    311  *
    312  * There is no scope for environment variables, these are generated on-the-fly
    313  * whenever they are referenced.
    314  *
    315  * Each target has its own scope, containing the 7 target-local variables
    316  * .TARGET, .ALLSRC, etc.  Variables set on dependency lines also go in
    317  * this scope.
    318  */
    319 
    320 GNode *SCOPE_CMDLINE;
    321 GNode *SCOPE_GLOBAL;
    322 GNode *SCOPE_INTERNAL;
    323 
    324 static VarExportedMode var_exportedVars = VAR_EXPORTED_NONE;
    325 
    326 static const char VarEvalMode_Name[][32] = {
    327 	"parse-only",
    328 	"parse-balanced",
    329 	"eval",
    330 	"eval-defined",
    331 	"eval-keep-dollar",
    332 	"eval-keep-undefined",
    333 	"eval-keep-dollar-and-undefined",
    334 };
    335 
    336 static EvalStack evalStack;
    337 
    338 
    339 void
    340 EvalStack_Push(const char *target, const char *expr, const char *varname)
    341 {
    342 	if (evalStack.len >= evalStack.cap) {
    343 		evalStack.cap = 16 + 2 * evalStack.cap;
    344 		evalStack.elems = bmake_realloc(evalStack.elems,
    345 		    evalStack.cap * sizeof(*evalStack.elems));
    346 	}
    347 	evalStack.elems[evalStack.len].target = target;
    348 	evalStack.elems[evalStack.len].expr = expr;
    349 	evalStack.elems[evalStack.len].varname = varname;
    350 	evalStack.len++;
    351 }
    352 
    353 void
    354 EvalStack_Pop(void)
    355 {
    356 	assert(evalStack.len > 0);
    357 	evalStack.len--;
    358 }
    359 
    360 const char *
    361 EvalStack_Details(void)
    362 {
    363 	size_t i;
    364 	Buffer *buf = &evalStack.details;
    365 
    366 
    367 	buf->len = 0;
    368 	for (i = 0; i < evalStack.len; i++) {
    369 		EvalStackElement *elem = evalStack.elems + i;
    370 		if (elem->target != NULL) {
    371 			Buf_AddStr(buf, "in target \"");
    372 			Buf_AddStr(buf, elem->target);
    373 			Buf_AddStr(buf, "\": ");
    374 		}
    375 		if (elem->expr != NULL) {
    376 			Buf_AddStr(buf, "while evaluating \"");
    377 			Buf_AddStr(buf, elem->expr);
    378 			Buf_AddStr(buf, "\": ");
    379 		}
    380 		if (elem->varname != NULL) {
    381 			Buf_AddStr(buf, "while evaluating variable \"");
    382 			Buf_AddStr(buf, elem->varname);
    383 			Buf_AddStr(buf, "\": ");
    384 		}
    385 	}
    386 	return buf->len > 0 ? buf->data : "";
    387 }
    388 
    389 static Var *
    390 VarNew(FStr name, const char *value,
    391        bool shortLived, bool fromEnvironment, bool readOnly)
    392 {
    393 	size_t value_len = strlen(value);
    394 	Var *var = bmake_malloc(sizeof *var);
    395 	var->name = name;
    396 	Buf_InitSize(&var->val, value_len + 1);
    397 	Buf_AddBytes(&var->val, value, value_len);
    398 	var->fromCmd = false;
    399 	var->shortLived = shortLived;
    400 	var->fromEnvironment = fromEnvironment;
    401 	var->readOnly = readOnly;
    402 	var->inUse = false;
    403 	var->exported = false;
    404 	var->reexport = false;
    405 	return var;
    406 }
    407 
    408 static Substring
    409 CanonicalVarname(Substring name)
    410 {
    411 
    412 	if (!(Substring_Length(name) > 0 && name.start[0] == '.'))
    413 		return name;
    414 
    415 	if (Substring_Equals(name, ".ALLSRC"))
    416 		return Substring_InitStr(ALLSRC);
    417 	if (Substring_Equals(name, ".ARCHIVE"))
    418 		return Substring_InitStr(ARCHIVE);
    419 	if (Substring_Equals(name, ".IMPSRC"))
    420 		return Substring_InitStr(IMPSRC);
    421 	if (Substring_Equals(name, ".MEMBER"))
    422 		return Substring_InitStr(MEMBER);
    423 	if (Substring_Equals(name, ".OODATE"))
    424 		return Substring_InitStr(OODATE);
    425 	if (Substring_Equals(name, ".PREFIX"))
    426 		return Substring_InitStr(PREFIX);
    427 	if (Substring_Equals(name, ".TARGET"))
    428 		return Substring_InitStr(TARGET);
    429 
    430 	/* GNU make has an additional alias $^ == ${.ALLSRC}. */
    431 
    432 	if (Substring_Equals(name, ".SHELL") && shellPath == NULL)
    433 		Shell_Init();
    434 
    435 	return name;
    436 }
    437 
    438 static Var *
    439 GNode_FindVar(GNode *scope, Substring varname, unsigned int hash)
    440 {
    441 	return HashTable_FindValueBySubstringHash(&scope->vars, varname, hash);
    442 }
    443 
    444 /*
    445  * Find the variable in the scope, and maybe in other scopes as well.
    446  *
    447  * Input:
    448  *	name		name to find, is not expanded any further
    449  *	scope		scope in which to look first
    450  *	elsewhere	true to look in other scopes as well
    451  *
    452  * Results:
    453  *	The found variable, or NULL if the variable does not exist.
    454  *	If the variable is short-lived (such as environment variables), it
    455  *	must be freed using VarFreeShortLived after use.
    456  */
    457 static Var *
    458 VarFindSubstring(Substring name, GNode *scope, bool elsewhere)
    459 {
    460 	Var *var;
    461 	unsigned int nameHash;
    462 
    463 	/* Replace '.TARGET' with '@', likewise for other local variables. */
    464 	name = CanonicalVarname(name);
    465 	nameHash = Hash_Substring(name);
    466 
    467 	var = GNode_FindVar(scope, name, nameHash);
    468 	if (!elsewhere)
    469 		return var;
    470 
    471 	if (var == NULL && scope != SCOPE_CMDLINE)
    472 		var = GNode_FindVar(SCOPE_CMDLINE, name, nameHash);
    473 
    474 	if (!opts.checkEnvFirst && var == NULL && scope != SCOPE_GLOBAL) {
    475 		var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    476 		if (var == NULL && scope != SCOPE_INTERNAL) {
    477 			/* SCOPE_INTERNAL is subordinate to SCOPE_GLOBAL */
    478 			var = GNode_FindVar(SCOPE_INTERNAL, name, nameHash);
    479 		}
    480 	}
    481 
    482 	if (var == NULL) {
    483 		FStr envName = Substring_Str(name);
    484 		const char *envValue = getenv(envName.str);
    485 		if (envValue != NULL)
    486 			return VarNew(envName, envValue, true, true, false);
    487 		FStr_Done(&envName);
    488 
    489 		if (opts.checkEnvFirst && scope != SCOPE_GLOBAL) {
    490 			var = GNode_FindVar(SCOPE_GLOBAL, name, nameHash);
    491 			if (var == NULL && scope != SCOPE_INTERNAL)
    492 				var = GNode_FindVar(SCOPE_INTERNAL, name,
    493 				    nameHash);
    494 			return var;
    495 		}
    496 
    497 		return NULL;
    498 	}
    499 
    500 	return var;
    501 }
    502 
    503 static Var *
    504 VarFind(const char *name, GNode *scope, bool elsewhere)
    505 {
    506 	return VarFindSubstring(Substring_InitStr(name), scope, elsewhere);
    507 }
    508 
    509 /* If the variable is short-lived, free it, including its value. */
    510 static void
    511 VarFreeShortLived(Var *v)
    512 {
    513 	if (!v->shortLived)
    514 		return;
    515 
    516 	FStr_Done(&v->name);
    517 	Buf_Done(&v->val);
    518 	free(v);
    519 }
    520 
    521 static const char *
    522 ValueDescription(const char *value)
    523 {
    524 	if (value[0] == '\0')
    525 		return "# (empty)";
    526 	if (ch_isspace(value[strlen(value) - 1]))
    527 		return "# (ends with space)";
    528 	return "";
    529 }
    530 
    531 /* Add a new variable of the given name and value to the given scope. */
    532 static Var *
    533 VarAdd(const char *name, const char *value, GNode *scope, VarSetFlags flags)
    534 {
    535 	HashEntry *he = HashTable_CreateEntry(&scope->vars, name, NULL);
    536 	Var *v = VarNew(FStr_InitRefer(/* aliased to */ he->key), value,
    537 	    false, false, (flags & VAR_SET_READONLY) != 0);
    538 	HashEntry_Set(he, v);
    539 	DEBUG4(VAR, "%s: %s = %s%s\n",
    540 	    scope->name, name, value, ValueDescription(value));
    541 	return v;
    542 }
    543 
    544 /*
    545  * Remove a variable from a scope, freeing all related memory as well.
    546  * The variable name is kept as-is, it is not expanded.
    547  */
    548 void
    549 Var_Delete(GNode *scope, const char *varname)
    550 {
    551 	HashEntry *he = HashTable_FindEntry(&scope->vars, varname);
    552 	Var *v;
    553 
    554 	if (he == NULL) {
    555 		DEBUG2(VAR, "%s: ignoring delete '%s' as it is not found\n",
    556 		    scope->name, varname);
    557 		return;
    558 	}
    559 
    560 	v = he->value;
    561 	if (v->readOnly) {
    562 		DEBUG2(VAR, "%s: ignoring delete '%s' as it is read-only\n",
    563 		    scope->name, varname);
    564 		return;
    565 	}
    566 	if (v->inUse) {
    567 		Parse_Error(PARSE_FATAL,
    568 		    "Cannot delete variable \"%s\" while it is used",
    569 		    v->name.str);
    570 		return;
    571 	}
    572 
    573 	DEBUG2(VAR, "%s: delete %s\n", scope->name, varname);
    574 	if (v->exported)
    575 		unsetenv(v->name.str);
    576 	if (strcmp(v->name.str, ".MAKE.EXPORTED") == 0)
    577 		var_exportedVars = VAR_EXPORTED_NONE;
    578 
    579 	assert(v->name.freeIt == NULL);
    580 	HashTable_DeleteEntry(&scope->vars, he);
    581 	Buf_Done(&v->val);
    582 	free(v);
    583 }
    584 
    585 #ifdef CLEANUP
    586 void
    587 Var_DeleteAll(GNode *scope)
    588 {
    589 	for (;;) {
    590 		HashIter hi;
    591 		HashIter_Init(&hi, &scope->vars);
    592 		if (HashIter_Next(&hi) == NULL)
    593 			return;
    594 		((Var *)hi.entry->value)->readOnly = false;
    595 		Var_Delete(scope, hi.entry->key);
    596 	}
    597 }
    598 #endif
    599 
    600 /*
    601  * Undefine one or more variables from the global scope.
    602  * The argument is expanded exactly once and then split into words.
    603  */
    604 void
    605 Var_Undef(const char *arg)
    606 {
    607 	char *expanded;
    608 	Words varnames;
    609 	size_t i;
    610 
    611 	if (arg[0] == '\0') {
    612 		Parse_Error(PARSE_FATAL,
    613 		    "The .undef directive requires an argument");
    614 		return;
    615 	}
    616 
    617 	expanded = Var_Subst(arg, SCOPE_GLOBAL, VARE_WANTRES);
    618 	if (expanded == var_Error) {
    619 		/* TODO: Make this part of the code reachable. */
    620 		Parse_Error(PARSE_FATAL,
    621 		    "Error in variable names to be undefined");
    622 		return;
    623 	}
    624 
    625 	varnames = Str_Words(expanded, false);
    626 	if (varnames.len == 1 && varnames.words[0][0] == '\0')
    627 		varnames.len = 0;
    628 
    629 	for (i = 0; i < varnames.len; i++) {
    630 		const char *varname = varnames.words[i];
    631 		Global_Delete(varname);
    632 	}
    633 
    634 	Words_Free(varnames);
    635 	free(expanded);
    636 }
    637 
    638 static bool
    639 MayExport(const char *name)
    640 {
    641 	if (name[0] == '.')
    642 		return false;	/* skip internals */
    643 	if (name[0] == '-')
    644 		return false;	/* skip misnamed variables */
    645 	if (name[1] == '\0') {
    646 		/*
    647 		 * A single char.
    648 		 * If it is one of the variables that should only appear in
    649 		 * local scope, skip it, else we can get Var_Subst
    650 		 * into a loop.
    651 		 */
    652 		switch (name[0]) {
    653 		case '@':
    654 		case '%':
    655 		case '*':
    656 		case '!':
    657 			return false;
    658 		}
    659 	}
    660 	return true;
    661 }
    662 
    663 static bool
    664 ExportVarEnv(Var *v, GNode *scope)
    665 {
    666 	const char *name = v->name.str;
    667 	char *val = v->val.data;
    668 	char *expr;
    669 
    670 	if (v->exported && !v->reexport)
    671 		return false;	/* nothing to do */
    672 
    673 	if (strchr(val, '$') == NULL) {
    674 		if (!v->exported)
    675 			setenv(name, val, 1);
    676 		return true;
    677 	}
    678 
    679 	if (v->inUse)
    680 		return false;	/* see EMPTY_SHELL in directive-export.mk */
    681 
    682 	/* XXX: name is injected without escaping it */
    683 	expr = str_concat3("${", name, "}");
    684 	val = Var_Subst(expr, scope, VARE_WANTRES);
    685 	if (scope != SCOPE_GLOBAL) {
    686 		/* we will need to re-export the global version */
    687 		v = VarFind(name, SCOPE_GLOBAL, false);
    688 		if (v != NULL)
    689 			v->exported = false;
    690 	}
    691 	/* TODO: handle errors */
    692 	setenv(name, val, 1);
    693 	free(val);
    694 	free(expr);
    695 	return true;
    696 }
    697 
    698 static bool
    699 ExportVarPlain(Var *v)
    700 {
    701 	if (strchr(v->val.data, '$') == NULL) {
    702 		setenv(v->name.str, v->val.data, 1);
    703 		v->exported = true;
    704 		v->reexport = false;
    705 		return true;
    706 	}
    707 
    708 	/*
    709 	 * Flag the variable as something we need to re-export.
    710 	 * No point actually exporting it now though,
    711 	 * the child process can do it at the last minute.
    712 	 * Avoid calling setenv more often than necessary since it can leak.
    713 	 */
    714 	v->exported = true;
    715 	v->reexport = true;
    716 	return true;
    717 }
    718 
    719 static bool
    720 ExportVarLiteral(Var *v)
    721 {
    722 	if (v->exported && !v->reexport)
    723 		return false;
    724 
    725 	if (!v->exported)
    726 		setenv(v->name.str, v->val.data, 1);
    727 
    728 	return true;
    729 }
    730 
    731 /*
    732  * Mark a single variable to be exported later for subprocesses.
    733  *
    734  * Internal variables are not exported.
    735  */
    736 static bool
    737 ExportVar(const char *name, GNode *scope, VarExportMode mode)
    738 {
    739 	Var *v;
    740 
    741 	if (!MayExport(name))
    742 		return false;
    743 
    744 	v = VarFind(name, scope, false);
    745 	if (v == NULL && scope != SCOPE_GLOBAL)
    746 		v = VarFind(name, SCOPE_GLOBAL, false);
    747 	if (v == NULL)
    748 		return false;
    749 
    750 	if (mode == VEM_ENV)
    751 		return ExportVarEnv(v, scope);
    752 	else if (mode == VEM_PLAIN)
    753 		return ExportVarPlain(v);
    754 	else
    755 		return ExportVarLiteral(v);
    756 }
    757 
    758 /*
    759  * Actually export the variables that have been marked as needing to be
    760  * re-exported.
    761  */
    762 void
    763 Var_ReexportVars(GNode *scope)
    764 {
    765 	char *xvarnames;
    766 
    767 	/*
    768 	 * Several make implementations support this sort of mechanism for
    769 	 * tracking recursion - but each uses a different name.
    770 	 * We allow the makefiles to update MAKELEVEL and ensure
    771 	 * children see a correctly incremented value.
    772 	 */
    773 	char level_buf[21];
    774 	snprintf(level_buf, sizeof level_buf, "%d", makelevel + 1);
    775 	setenv(MAKE_LEVEL_ENV, level_buf, 1);
    776 
    777 	if (var_exportedVars == VAR_EXPORTED_NONE)
    778 		return;
    779 
    780 	if (var_exportedVars == VAR_EXPORTED_ALL) {
    781 		HashIter hi;
    782 
    783 		/* Ouch! Exporting all variables at once is crazy. */
    784 		HashIter_Init(&hi, &SCOPE_GLOBAL->vars);
    785 		while (HashIter_Next(&hi) != NULL) {
    786 			Var *var = hi.entry->value;
    787 			ExportVar(var->name.str, scope, VEM_ENV);
    788 		}
    789 		return;
    790 	}
    791 
    792 	xvarnames = Var_Subst("${.MAKE.EXPORTED:O:u}", SCOPE_GLOBAL,
    793 	    VARE_WANTRES);
    794 	/* TODO: handle errors */
    795 	if (xvarnames[0] != '\0') {
    796 		Words varnames = Str_Words(xvarnames, false);
    797 		size_t i;
    798 
    799 		for (i = 0; i < varnames.len; i++)
    800 			ExportVar(varnames.words[i], scope, VEM_ENV);
    801 		Words_Free(varnames);
    802 	}
    803 	free(xvarnames);
    804 }
    805 
    806 static void
    807 ExportVars(const char *varnames, bool isExport, VarExportMode mode)
    808 /* TODO: try to combine the parameters 'isExport' and 'mode'. */
    809 {
    810 	Words words = Str_Words(varnames, false);
    811 	size_t i;
    812 
    813 	if (words.len == 1 && words.words[0][0] == '\0')
    814 		words.len = 0;
    815 
    816 	for (i = 0; i < words.len; i++) {
    817 		const char *varname = words.words[i];
    818 		if (!ExportVar(varname, SCOPE_GLOBAL, mode))
    819 			continue;
    820 
    821 		if (var_exportedVars == VAR_EXPORTED_NONE)
    822 			var_exportedVars = VAR_EXPORTED_SOME;
    823 
    824 		if (isExport && mode == VEM_PLAIN)
    825 			Global_Append(".MAKE.EXPORTED", varname);
    826 	}
    827 	Words_Free(words);
    828 }
    829 
    830 static void
    831 ExportVarsExpand(const char *uvarnames, bool isExport, VarExportMode mode)
    832 {
    833 	char *xvarnames = Var_Subst(uvarnames, SCOPE_GLOBAL, VARE_WANTRES);
    834 	/* TODO: handle errors */
    835 	ExportVars(xvarnames, isExport, mode);
    836 	free(xvarnames);
    837 }
    838 
    839 /* Export the named variables, or all variables. */
    840 void
    841 Var_Export(VarExportMode mode, const char *varnames)
    842 {
    843 	if (mode == VEM_PLAIN && varnames[0] == '\0') {
    844 		var_exportedVars = VAR_EXPORTED_ALL; /* use with caution! */
    845 		return;
    846 	}
    847 
    848 	ExportVarsExpand(varnames, true, mode);
    849 }
    850 
    851 void
    852 Var_ExportVars(const char *varnames)
    853 {
    854 	ExportVarsExpand(varnames, false, VEM_PLAIN);
    855 }
    856 
    857 
    858 static void
    859 ClearEnv(void)
    860 {
    861 	const char *level;
    862 	char **newenv;
    863 
    864 	level = getenv(MAKE_LEVEL_ENV);	/* we should preserve this */
    865 	if (environ == savedEnv) {
    866 		/* we have been here before! */
    867 		newenv = bmake_realloc(environ, 2 * sizeof(char *));
    868 	} else {
    869 		if (savedEnv != NULL) {
    870 			free(savedEnv);
    871 			savedEnv = NULL;
    872 		}
    873 		newenv = bmake_malloc(2 * sizeof(char *));
    874 	}
    875 
    876 	/* Note: we cannot safely free() the original environ. */
    877 	environ = savedEnv = newenv;
    878 	newenv[0] = NULL;
    879 	newenv[1] = NULL;
    880 	if (level != NULL && *level != '\0')
    881 		setenv(MAKE_LEVEL_ENV, level, 1);
    882 }
    883 
    884 static void
    885 GetVarnamesToUnexport(bool isEnv, const char *arg,
    886 		      FStr *out_varnames, UnexportWhat *out_what)
    887 {
    888 	UnexportWhat what;
    889 	FStr varnames = FStr_InitRefer("");
    890 
    891 	if (isEnv) {
    892 		if (arg[0] != '\0') {
    893 			Parse_Error(PARSE_FATAL,
    894 			    "The directive .unexport-env does not take "
    895 			    "arguments");
    896 			/* continue anyway */
    897 		}
    898 		what = UNEXPORT_ENV;
    899 
    900 	} else {
    901 		what = arg[0] != '\0' ? UNEXPORT_NAMED : UNEXPORT_ALL;
    902 		if (what == UNEXPORT_NAMED)
    903 			varnames = FStr_InitRefer(arg);
    904 	}
    905 
    906 	if (what != UNEXPORT_NAMED) {
    907 		char *expanded = Var_Subst("${.MAKE.EXPORTED:O:u}",
    908 		    SCOPE_GLOBAL, VARE_WANTRES);
    909 		/* TODO: handle errors */
    910 		varnames = FStr_InitOwn(expanded);
    911 	}
    912 
    913 	*out_varnames = varnames;
    914 	*out_what = what;
    915 }
    916 
    917 static void
    918 UnexportVar(Substring varname, UnexportWhat what)
    919 {
    920 	Var *v = VarFindSubstring(varname, SCOPE_GLOBAL, false);
    921 	if (v == NULL) {
    922 		DEBUG2(VAR, "Not unexporting \"%.*s\" (not found)\n",
    923 		    (int)Substring_Length(varname), varname.start);
    924 		return;
    925 	}
    926 
    927 	DEBUG2(VAR, "Unexporting \"%.*s\"\n",
    928 	    (int)Substring_Length(varname), varname.start);
    929 	if (what != UNEXPORT_ENV && v->exported && !v->reexport)
    930 		unsetenv(v->name.str);
    931 	v->exported = false;
    932 	v->reexport = false;
    933 
    934 	if (what == UNEXPORT_NAMED) {
    935 		/* Remove the variable names from .MAKE.EXPORTED. */
    936 		/* XXX: v->name is injected without escaping it */
    937 		char *expr = str_concat3(
    938 		    "${.MAKE.EXPORTED:N", v->name.str, "}");
    939 		char *filtered = Var_Subst(expr, SCOPE_GLOBAL, VARE_WANTRES);
    940 		/* TODO: handle errors */
    941 		Global_Set(".MAKE.EXPORTED", filtered);
    942 		free(filtered);
    943 		free(expr);
    944 	}
    945 }
    946 
    947 static void
    948 UnexportVars(FStr *varnames, UnexportWhat what)
    949 {
    950 	size_t i;
    951 	SubstringWords words;
    952 
    953 	if (what == UNEXPORT_ENV)
    954 		ClearEnv();
    955 
    956 	words = Substring_Words(varnames->str, false);
    957 	for (i = 0; i < words.len; i++)
    958 		UnexportVar(words.words[i], what);
    959 	SubstringWords_Free(words);
    960 
    961 	if (what != UNEXPORT_NAMED)
    962 		Global_Delete(".MAKE.EXPORTED");
    963 }
    964 
    965 /* Handle the .unexport and .unexport-env directives. */
    966 void
    967 Var_UnExport(bool isEnv, const char *arg)
    968 {
    969 	UnexportWhat what;
    970 	FStr varnames;
    971 
    972 	GetVarnamesToUnexport(isEnv, arg, &varnames, &what);
    973 	UnexportVars(&varnames, what);
    974 	FStr_Done(&varnames);
    975 }
    976 
    977 /* Set the variable to the value; the name is not expanded. */
    978 void
    979 Var_SetWithFlags(GNode *scope, const char *name, const char *val,
    980 		 VarSetFlags flags)
    981 {
    982 	Var *v;
    983 
    984 	assert(val != NULL);
    985 	if (name[0] == '\0') {
    986 		DEBUG3(VAR,
    987 		    "%s: ignoring '%s = %s' as the variable name is empty\n",
    988 		    scope->name, name, val);
    989 		return;
    990 	}
    991 
    992 	if (scope == SCOPE_GLOBAL
    993 	    && VarFind(name, SCOPE_CMDLINE, false) != NULL) {
    994 		/*
    995 		 * The global variable would not be visible anywhere.
    996 		 * Therefore, there is no point in setting it at all.
    997 		 */
    998 		DEBUG3(VAR,
    999 		    "%s: ignoring '%s = %s' "
   1000 		    "due to a command line variable of the same name\n",
   1001 		    scope->name, name, val);
   1002 		return;
   1003 	}
   1004 
   1005 	/*
   1006 	 * Only look for a variable in the given scope since anything set
   1007 	 * here will override anything in a lower scope, so there's not much
   1008 	 * point in searching them all.
   1009 	 */
   1010 	v = VarFind(name, scope, false);
   1011 	if (v == NULL) {
   1012 		if (scope == SCOPE_CMDLINE && !(flags & VAR_SET_NO_EXPORT)) {
   1013 			/*
   1014 			 * This variable would normally prevent the same name
   1015 			 * being added to SCOPE_GLOBAL, so delete it from
   1016 			 * there if needed. Otherwise -V name may show the
   1017 			 * wrong value.
   1018 			 *
   1019 			 * See ExistsInCmdline.
   1020 			 */
   1021 			Var_Delete(SCOPE_GLOBAL, name);
   1022 		}
   1023 		if (strcmp(name, ".SUFFIXES") == 0) {
   1024 			/* special: treat as read-only */
   1025 			DEBUG3(VAR,
   1026 			    "%s: ignoring '%s = %s' as it is read-only\n",
   1027 			    scope->name, name, val);
   1028 			return;
   1029 		}
   1030 		v = VarAdd(name, val, scope, flags);
   1031 	} else {
   1032 		if (v->readOnly && !(flags & VAR_SET_READONLY)) {
   1033 			DEBUG3(VAR,
   1034 			    "%s: ignoring '%s = %s' as it is read-only\n",
   1035 			    scope->name, name, val);
   1036 			return;
   1037 		}
   1038 		Buf_Clear(&v->val);
   1039 		Buf_AddStr(&v->val, val);
   1040 
   1041 		DEBUG4(VAR, "%s: %s = %s%s\n",
   1042 		    scope->name, name, val, ValueDescription(val));
   1043 		if (v->exported)
   1044 			ExportVar(name, scope, VEM_PLAIN);
   1045 	}
   1046 
   1047 	if (scope == SCOPE_CMDLINE) {
   1048 		v->fromCmd = true;
   1049 
   1050 		/*
   1051 		 * Any variables given on the command line are automatically
   1052 		 * exported to the environment (as per POSIX standard), except
   1053 		 * for internals.
   1054 		 */
   1055 		if (!(flags & VAR_SET_NO_EXPORT)) {
   1056 
   1057 			/*
   1058 			 * If requested, don't export these in the
   1059 			 * environment individually.  We still put
   1060 			 * them in .MAKEOVERRIDES so that the
   1061 			 * command-line settings continue to override
   1062 			 * Makefile settings.
   1063 			 */
   1064 			if (!opts.varNoExportEnv && name[0] != '.')
   1065 				setenv(name, val, 1);
   1066 
   1067 			if (!(flags & VAR_SET_INTERNAL))
   1068 				Global_Append(".MAKEOVERRIDES", name);
   1069 		}
   1070 	}
   1071 
   1072 	if (name[0] == '.' && strcmp(name, MAKE_SAVE_DOLLARS) == 0)
   1073 		save_dollars = ParseBoolean(val, save_dollars);
   1074 
   1075 	if (v != NULL)
   1076 		VarFreeShortLived(v);
   1077 }
   1078 
   1079 void
   1080 Var_Set(GNode *scope, const char *name, const char *val)
   1081 {
   1082 	Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1083 }
   1084 
   1085 /*
   1086  * In the scope, expand the variable name once, then create the variable or
   1087  * replace its value.
   1088  */
   1089 void
   1090 Var_SetExpand(GNode *scope, const char *name, const char *val)
   1091 {
   1092 	FStr varname = FStr_InitRefer(name);
   1093 
   1094 	assert(val != NULL);
   1095 
   1096 	Var_Expand(&varname, scope, VARE_WANTRES);
   1097 
   1098 	if (varname.str[0] == '\0') {
   1099 		DEBUG4(VAR,
   1100 		    "%s: ignoring '%s = %s' "
   1101 		    "as the variable name '%s' expands to empty\n",
   1102 		    scope->name, varname.str, val, name);
   1103 	} else
   1104 		Var_SetWithFlags(scope, varname.str, val, VAR_SET_NONE);
   1105 
   1106 	FStr_Done(&varname);
   1107 }
   1108 
   1109 void
   1110 Global_Set(const char *name, const char *value)
   1111 {
   1112 	Var_Set(SCOPE_GLOBAL, name, value);
   1113 }
   1114 
   1115 void
   1116 Global_Delete(const char *name)
   1117 {
   1118 	Var_Delete(SCOPE_GLOBAL, name);
   1119 }
   1120 
   1121 void
   1122 Global_Set_ReadOnly(const char *name, const char *value)
   1123 {
   1124 	Var_SetWithFlags(SCOPE_GLOBAL, name, value, VAR_SET_READONLY);
   1125 }
   1126 
   1127 /*
   1128  * Append the value to the named variable.
   1129  *
   1130  * If the variable doesn't exist, it is created.  Otherwise a single space
   1131  * and the given value are appended.
   1132  */
   1133 void
   1134 Var_Append(GNode *scope, const char *name, const char *val)
   1135 {
   1136 	Var *v;
   1137 
   1138 	v = VarFind(name, scope, scope == SCOPE_GLOBAL);
   1139 
   1140 	if (v == NULL) {
   1141 		Var_SetWithFlags(scope, name, val, VAR_SET_NONE);
   1142 	} else if (v->readOnly) {
   1143 		DEBUG3(VAR, "%s: ignoring '%s += %s' as it is read-only\n",
   1144 		    scope->name, name, val);
   1145 	} else if (scope == SCOPE_CMDLINE || !v->fromCmd) {
   1146 		Buf_AddByte(&v->val, ' ');
   1147 		Buf_AddStr(&v->val, val);
   1148 
   1149 		DEBUG3(VAR, "%s: %s = %s\n", scope->name, name, v->val.data);
   1150 
   1151 		if (v->fromEnvironment) {
   1152 			/* See VarAdd. */
   1153 			HashEntry *he =
   1154 			    HashTable_CreateEntry(&scope->vars, name, NULL);
   1155 			HashEntry_Set(he, v);
   1156 			FStr_Done(&v->name);
   1157 			v->name = FStr_InitRefer(/* aliased to */ he->key);
   1158 			v->shortLived = false;
   1159 			v->fromEnvironment = false;
   1160 		}
   1161 	}
   1162 }
   1163 
   1164 /*
   1165  * In the scope, expand the variable name once.  If the variable exists in the
   1166  * scope, add a space and the value, otherwise set the variable to the value.
   1167  *
   1168  * Appending to an environment variable only works in the global scope, that
   1169  * is, for variable assignments in makefiles, but not inside conditions or the
   1170  * commands of a target.
   1171  */
   1172 void
   1173 Var_AppendExpand(GNode *scope, const char *name, const char *val)
   1174 {
   1175 	FStr xname = FStr_InitRefer(name);
   1176 
   1177 	assert(val != NULL);
   1178 
   1179 	Var_Expand(&xname, scope, VARE_WANTRES);
   1180 	if (xname.str != name && xname.str[0] == '\0')
   1181 		DEBUG4(VAR,
   1182 		    "%s: ignoring '%s += %s' "
   1183 		    "as the variable name '%s' expands to empty\n",
   1184 		    scope->name, xname.str, val, name);
   1185 	else
   1186 		Var_Append(scope, xname.str, val);
   1187 
   1188 	FStr_Done(&xname);
   1189 }
   1190 
   1191 void
   1192 Global_Append(const char *name, const char *value)
   1193 {
   1194 	Var_Append(SCOPE_GLOBAL, name, value);
   1195 }
   1196 
   1197 bool
   1198 Var_Exists(GNode *scope, const char *name)
   1199 {
   1200 	Var *v = VarFind(name, scope, true);
   1201 	if (v == NULL)
   1202 		return false;
   1203 
   1204 	VarFreeShortLived(v);
   1205 	return true;
   1206 }
   1207 
   1208 /*
   1209  * See if the given variable exists, in the given scope or in other
   1210  * fallback scopes.
   1211  *
   1212  * Input:
   1213  *	scope		scope in which to start search
   1214  *	name		name of the variable to find, is expanded once
   1215  */
   1216 bool
   1217 Var_ExistsExpand(GNode *scope, const char *name)
   1218 {
   1219 	FStr varname = FStr_InitRefer(name);
   1220 	bool exists;
   1221 
   1222 	Var_Expand(&varname, scope, VARE_WANTRES);
   1223 	exists = Var_Exists(scope, varname.str);
   1224 	FStr_Done(&varname);
   1225 	return exists;
   1226 }
   1227 
   1228 /*
   1229  * Return the unexpanded value of the given variable in the given scope,
   1230  * falling back to the command, global and environment scopes, in this order,
   1231  * but see the -e option.
   1232  *
   1233  * Input:
   1234  *	name		the name to find, is not expanded any further
   1235  *
   1236  * Results:
   1237  *	The value if the variable exists, NULL if it doesn't.
   1238  *	The value is valid until the next modification to any variable.
   1239  */
   1240 FStr
   1241 Var_Value(GNode *scope, const char *name)
   1242 {
   1243 	Var *v = VarFind(name, scope, true);
   1244 	char *value;
   1245 
   1246 	if (v == NULL)
   1247 		return FStr_InitRefer(NULL);
   1248 
   1249 	if (!v->shortLived)
   1250 		return FStr_InitRefer(v->val.data);
   1251 
   1252 	value = v->val.data;
   1253 	v->val.data = NULL;
   1254 	VarFreeShortLived(v);
   1255 
   1256 	return FStr_InitOwn(value);
   1257 }
   1258 
   1259 /* Set or clear the read-only attribute of the variable if it exists. */
   1260 void
   1261 Var_ReadOnly(const char *name, bool bf)
   1262 {
   1263 	Var *v;
   1264 
   1265 	v = VarFind(name, SCOPE_GLOBAL, false);
   1266 	if (v == NULL) {
   1267 		DEBUG1(VAR, "Var_ReadOnly: %s not found\n", name);
   1268 		return;
   1269 	}
   1270 	v->readOnly = bf;
   1271 	DEBUG2(VAR, "Var_ReadOnly: %s %s\n", name, bf ? "true" : "false");
   1272 }
   1273 
   1274 /*
   1275  * Return the unexpanded variable value from this node, without trying to look
   1276  * up the variable in any other scope.
   1277  */
   1278 const char *
   1279 GNode_ValueDirect(GNode *gn, const char *name)
   1280 {
   1281 	Var *v = VarFind(name, gn, false);
   1282 	return v != NULL ? v->val.data : NULL;
   1283 }
   1284 
   1285 static VarEvalMode
   1286 VarEvalMode_WithoutKeepDollar(VarEvalMode emode)
   1287 {
   1288 	if (emode == VARE_KEEP_DOLLAR_UNDEF)
   1289 		return VARE_EVAL_KEEP_UNDEF;
   1290 	if (emode == VARE_EVAL_KEEP_DOLLAR)
   1291 		return VARE_WANTRES;
   1292 	return emode;
   1293 }
   1294 
   1295 static VarEvalMode
   1296 VarEvalMode_UndefOk(VarEvalMode emode)
   1297 {
   1298 	return emode == VARE_UNDEFERR ? VARE_WANTRES : emode;
   1299 }
   1300 
   1301 static bool
   1302 VarEvalMode_ShouldEval(VarEvalMode emode)
   1303 {
   1304 	return emode != VARE_PARSE_ONLY;
   1305 }
   1306 
   1307 static bool
   1308 VarEvalMode_ShouldKeepUndef(VarEvalMode emode)
   1309 {
   1310 	return emode == VARE_EVAL_KEEP_UNDEF ||
   1311 	       emode == VARE_KEEP_DOLLAR_UNDEF;
   1312 }
   1313 
   1314 static bool
   1315 VarEvalMode_ShouldKeepDollar(VarEvalMode emode)
   1316 {
   1317 	return emode == VARE_EVAL_KEEP_DOLLAR ||
   1318 	       emode == VARE_KEEP_DOLLAR_UNDEF;
   1319 }
   1320 
   1321 
   1322 static void
   1323 SepBuf_Init(SepBuf *buf, char sep)
   1324 {
   1325 	Buf_InitSize(&buf->buf, 32);
   1326 	buf->needSep = false;
   1327 	buf->sep = sep;
   1328 }
   1329 
   1330 static void
   1331 SepBuf_Sep(SepBuf *buf)
   1332 {
   1333 	buf->needSep = true;
   1334 }
   1335 
   1336 static void
   1337 SepBuf_AddBytes(SepBuf *buf, const char *mem, size_t mem_size)
   1338 {
   1339 	if (mem_size == 0)
   1340 		return;
   1341 	if (buf->needSep && buf->sep != '\0') {
   1342 		Buf_AddByte(&buf->buf, buf->sep);
   1343 		buf->needSep = false;
   1344 	}
   1345 	Buf_AddBytes(&buf->buf, mem, mem_size);
   1346 }
   1347 
   1348 static void
   1349 SepBuf_AddRange(SepBuf *buf, const char *start, const char *end)
   1350 {
   1351 	SepBuf_AddBytes(buf, start, (size_t)(end - start));
   1352 }
   1353 
   1354 static void
   1355 SepBuf_AddStr(SepBuf *buf, const char *str)
   1356 {
   1357 	SepBuf_AddBytes(buf, str, strlen(str));
   1358 }
   1359 
   1360 static void
   1361 SepBuf_AddSubstring(SepBuf *buf, Substring sub)
   1362 {
   1363 	SepBuf_AddRange(buf, sub.start, sub.end);
   1364 }
   1365 
   1366 static char *
   1367 SepBuf_DoneData(SepBuf *buf)
   1368 {
   1369 	return Buf_DoneData(&buf->buf);
   1370 }
   1371 
   1372 
   1373 /*
   1374  * This callback for ModifyWords gets a single word from an expression
   1375  * and typically adds a modification of this word to the buffer. It may also
   1376  * do nothing or add several words.
   1377  *
   1378  * For example, when evaluating the modifier ':M*b' in ${:Ua b c:M*b}, the
   1379  * callback is called 3 times, once for "a", "b" and "c".
   1380  *
   1381  * Some ModifyWord functions assume that they are always passed a
   1382  * null-terminated substring, which is currently guaranteed but may change in
   1383  * the future.
   1384  */
   1385 typedef void (*ModifyWordProc)(Substring word, SepBuf *buf, void *data);
   1386 
   1387 
   1388 /*ARGSUSED*/
   1389 static void
   1390 ModifyWord_Head(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1391 {
   1392 	SepBuf_AddSubstring(buf, Substring_Dirname(word));
   1393 }
   1394 
   1395 /*ARGSUSED*/
   1396 static void
   1397 ModifyWord_Tail(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1398 {
   1399 	SepBuf_AddSubstring(buf, Substring_Basename(word));
   1400 }
   1401 
   1402 /*ARGSUSED*/
   1403 static void
   1404 ModifyWord_Suffix(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1405 {
   1406 	const char *lastDot = Substring_FindLast(word, '.');
   1407 	if (lastDot != NULL)
   1408 		SepBuf_AddRange(buf, lastDot + 1, word.end);
   1409 }
   1410 
   1411 /*ARGSUSED*/
   1412 static void
   1413 ModifyWord_Root(Substring word, SepBuf *buf, void *dummy MAKE_ATTR_UNUSED)
   1414 {
   1415 	const char *lastDot, *end;
   1416 
   1417 	lastDot = Substring_FindLast(word, '.');
   1418 	end = lastDot != NULL ? lastDot : word.end;
   1419 	SepBuf_AddRange(buf, word.start, end);
   1420 }
   1421 
   1422 struct ModifyWord_SysVSubstArgs {
   1423 	GNode *scope;
   1424 	Substring lhsPrefix;
   1425 	bool lhsPercent;
   1426 	Substring lhsSuffix;
   1427 	const char *rhs;
   1428 };
   1429 
   1430 static void
   1431 ModifyWord_SysVSubst(Substring word, SepBuf *buf, void *data)
   1432 {
   1433 	const struct ModifyWord_SysVSubstArgs *args = data;
   1434 	FStr rhs;
   1435 	const char *percent;
   1436 
   1437 	if (Substring_IsEmpty(word))
   1438 		return;
   1439 
   1440 	if (!Substring_HasPrefix(word, args->lhsPrefix) ||
   1441 	    !Substring_HasSuffix(word, args->lhsSuffix)) {
   1442 		SepBuf_AddSubstring(buf, word);
   1443 		return;
   1444 	}
   1445 
   1446 	rhs = FStr_InitRefer(args->rhs);
   1447 	Var_Expand(&rhs, args->scope, VARE_WANTRES);
   1448 
   1449 	percent = args->lhsPercent ? strchr(rhs.str, '%') : NULL;
   1450 
   1451 	if (percent != NULL)
   1452 		SepBuf_AddRange(buf, rhs.str, percent);
   1453 	if (percent != NULL || !args->lhsPercent)
   1454 		SepBuf_AddRange(buf,
   1455 		    word.start + Substring_Length(args->lhsPrefix),
   1456 		    word.end - Substring_Length(args->lhsSuffix));
   1457 	SepBuf_AddStr(buf, percent != NULL ? percent + 1 : rhs.str);
   1458 
   1459 	FStr_Done(&rhs);
   1460 }
   1461 
   1462 static const char *
   1463 Substring_Find(Substring haystack, Substring needle)
   1464 {
   1465 	size_t len, needleLen, i;
   1466 
   1467 	len = Substring_Length(haystack);
   1468 	needleLen = Substring_Length(needle);
   1469 	for (i = 0; i + needleLen <= len; i++)
   1470 		if (memcmp(haystack.start + i, needle.start, needleLen) == 0)
   1471 			return haystack.start + i;
   1472 	return NULL;
   1473 }
   1474 
   1475 struct ModifyWord_SubstArgs {
   1476 	Substring lhs;
   1477 	Substring rhs;
   1478 	PatternFlags pflags;
   1479 	bool matched;
   1480 };
   1481 
   1482 static void
   1483 ModifyWord_Subst(Substring word, SepBuf *buf, void *data)
   1484 {
   1485 	struct ModifyWord_SubstArgs *args = data;
   1486 	size_t wordLen, lhsLen;
   1487 	const char *match;
   1488 
   1489 	wordLen = Substring_Length(word);
   1490 	if (args->pflags.subOnce && args->matched)
   1491 		goto nosub;
   1492 
   1493 	lhsLen = Substring_Length(args->lhs);
   1494 	if (args->pflags.anchorStart) {
   1495 		if (wordLen < lhsLen ||
   1496 		    memcmp(word.start, args->lhs.start, lhsLen) != 0)
   1497 			goto nosub;
   1498 
   1499 		if (args->pflags.anchorEnd && wordLen != lhsLen)
   1500 			goto nosub;
   1501 
   1502 		/* :S,^prefix,replacement, or :S,^whole$,replacement, */
   1503 		SepBuf_AddSubstring(buf, args->rhs);
   1504 		SepBuf_AddRange(buf, word.start + lhsLen, word.end);
   1505 		args->matched = true;
   1506 		return;
   1507 	}
   1508 
   1509 	if (args->pflags.anchorEnd) {
   1510 		if (wordLen < lhsLen)
   1511 			goto nosub;
   1512 		if (memcmp(word.end - lhsLen, args->lhs.start, lhsLen) != 0)
   1513 			goto nosub;
   1514 
   1515 		/* :S,suffix$,replacement, */
   1516 		SepBuf_AddRange(buf, word.start, word.end - lhsLen);
   1517 		SepBuf_AddSubstring(buf, args->rhs);
   1518 		args->matched = true;
   1519 		return;
   1520 	}
   1521 
   1522 	if (Substring_IsEmpty(args->lhs))
   1523 		goto nosub;
   1524 
   1525 	/* unanchored case, may match more than once */
   1526 	while ((match = Substring_Find(word, args->lhs)) != NULL) {
   1527 		SepBuf_AddRange(buf, word.start, match);
   1528 		SepBuf_AddSubstring(buf, args->rhs);
   1529 		args->matched = true;
   1530 		word.start = match + lhsLen;
   1531 		if (Substring_IsEmpty(word) || !args->pflags.subGlobal)
   1532 			break;
   1533 	}
   1534 nosub:
   1535 	SepBuf_AddSubstring(buf, word);
   1536 }
   1537 
   1538 /* Print the error caused by a regcomp or regexec call. */
   1539 static void
   1540 RegexError(int reerr, const regex_t *pat, const char *str)
   1541 {
   1542 	size_t errlen = regerror(reerr, pat, NULL, 0);
   1543 	char *errbuf = bmake_malloc(errlen);
   1544 	regerror(reerr, pat, errbuf, errlen);
   1545 	Error("%s: %s", str, errbuf);
   1546 	free(errbuf);
   1547 }
   1548 
   1549 /* In the modifier ':C', replace a backreference from \0 to \9. */
   1550 static void
   1551 RegexReplaceBackref(char ref, SepBuf *buf, const char *wp,
   1552 		    const regmatch_t *m, size_t nsub)
   1553 {
   1554 	unsigned int n = (unsigned)ref - '0';
   1555 
   1556 	if (n >= nsub)
   1557 		Error("No subexpression \\%u", n);
   1558 	else if (m[n].rm_so == -1) {
   1559 		if (opts.strict)
   1560 			Error("No match for subexpression \\%u", n);
   1561 	} else {
   1562 		SepBuf_AddRange(buf,
   1563 		    wp + (size_t)m[n].rm_so,
   1564 		    wp + (size_t)m[n].rm_eo);
   1565 	}
   1566 }
   1567 
   1568 /*
   1569  * The regular expression matches the word; now add the replacement to the
   1570  * buffer, taking back-references from 'wp'.
   1571  */
   1572 static void
   1573 RegexReplace(Substring replace, SepBuf *buf, const char *wp,
   1574 	     const regmatch_t *m, size_t nsub)
   1575 {
   1576 	const char *rp;
   1577 
   1578 	for (rp = replace.start; rp != replace.end; rp++) {
   1579 		if (*rp == '\\' && rp + 1 != replace.end &&
   1580 		    (rp[1] == '&' || rp[1] == '\\'))
   1581 			SepBuf_AddBytes(buf, ++rp, 1);
   1582 		else if (*rp == '\\' && rp + 1 != replace.end &&
   1583 			 ch_isdigit(rp[1]))
   1584 			RegexReplaceBackref(*++rp, buf, wp, m, nsub);
   1585 		else if (*rp == '&') {
   1586 			SepBuf_AddRange(buf,
   1587 			    wp + (size_t)m[0].rm_so,
   1588 			    wp + (size_t)m[0].rm_eo);
   1589 		} else
   1590 			SepBuf_AddBytes(buf, rp, 1);
   1591 	}
   1592 }
   1593 
   1594 struct ModifyWord_SubstRegexArgs {
   1595 	regex_t re;
   1596 	size_t nsub;
   1597 	Substring replace;
   1598 	PatternFlags pflags;
   1599 	bool matched;
   1600 };
   1601 
   1602 static void
   1603 ModifyWord_SubstRegex(Substring word, SepBuf *buf, void *data)
   1604 {
   1605 	struct ModifyWord_SubstRegexArgs *args = data;
   1606 	int xrv;
   1607 	const char *wp;
   1608 	int flags = 0;
   1609 	regmatch_t m[10];
   1610 
   1611 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1612 	wp = word.start;
   1613 	if (args->pflags.subOnce && args->matched)
   1614 		goto no_match;
   1615 
   1616 again:
   1617 	xrv = regexec(&args->re, wp, args->nsub, m, flags);
   1618 	if (xrv == 0)
   1619 		goto ok;
   1620 	if (xrv != REG_NOMATCH)
   1621 		RegexError(xrv, &args->re, "Unexpected regex error");
   1622 no_match:
   1623 	SepBuf_AddRange(buf, wp, word.end);
   1624 	return;
   1625 
   1626 ok:
   1627 	args->matched = true;
   1628 	SepBuf_AddBytes(buf, wp, (size_t)m[0].rm_so);
   1629 
   1630 	RegexReplace(args->replace, buf, wp, m, args->nsub);
   1631 
   1632 	wp += (size_t)m[0].rm_eo;
   1633 	if (args->pflags.subGlobal) {
   1634 		flags |= REG_NOTBOL;
   1635 		if (m[0].rm_so == 0 && m[0].rm_eo == 0 && *wp != '\0') {
   1636 			SepBuf_AddBytes(buf, wp, 1);
   1637 			wp++;
   1638 		}
   1639 		if (*wp != '\0')
   1640 			goto again;
   1641 	}
   1642 	if (*wp != '\0')
   1643 		SepBuf_AddStr(buf, wp);
   1644 }
   1645 
   1646 
   1647 struct ModifyWord_LoopArgs {
   1648 	GNode *scope;
   1649 	const char *var;	/* name of the temporary variable */
   1650 	const char *body;	/* string to expand */
   1651 	VarEvalMode emode;
   1652 };
   1653 
   1654 static void
   1655 ModifyWord_Loop(Substring word, SepBuf *buf, void *data)
   1656 {
   1657 	const struct ModifyWord_LoopArgs *args;
   1658 	char *s;
   1659 
   1660 	if (Substring_IsEmpty(word))
   1661 		return;
   1662 
   1663 	args = data;
   1664 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1665 	Var_SetWithFlags(args->scope, args->var, word.start,
   1666 	    VAR_SET_NO_EXPORT);
   1667 	s = Var_Subst(args->body, args->scope, args->emode);
   1668 	/* TODO: handle errors */
   1669 
   1670 	DEBUG2(VAR, "ModifyWord_Loop: expand \"%s\" to \"%s\"\n",
   1671 	    args->body, s);
   1672 
   1673 	if (s[0] == '\n' || Buf_EndsWith(&buf->buf, '\n'))
   1674 		buf->needSep = false;
   1675 	SepBuf_AddStr(buf, s);
   1676 	free(s);
   1677 }
   1678 
   1679 
   1680 /*
   1681  * The :[first..last] modifier selects words from the expression.
   1682  * It can also reverse the words.
   1683  */
   1684 static char *
   1685 VarSelectWords(const char *str, int first, int last,
   1686 	       char sep, bool oneBigWord)
   1687 {
   1688 	SubstringWords words;
   1689 	int len, start, end, step;
   1690 	int i;
   1691 
   1692 	SepBuf buf;
   1693 	SepBuf_Init(&buf, sep);
   1694 
   1695 	if (oneBigWord) {
   1696 		/* fake what Substring_Words() would do */
   1697 		words.len = 1;
   1698 		words.words = bmake_malloc(sizeof(words.words[0]));
   1699 		words.freeIt = NULL;
   1700 		words.words[0] = Substring_InitStr(str); /* no need to copy */
   1701 	} else {
   1702 		words = Substring_Words(str, false);
   1703 	}
   1704 
   1705 	/* Convert -1 to len, -2 to (len - 1), etc. */
   1706 	len = (int)words.len;
   1707 	if (first < 0)
   1708 		first += len + 1;
   1709 	if (last < 0)
   1710 		last += len + 1;
   1711 
   1712 	if (first > last) {
   1713 		start = (first > len ? len : first) - 1;
   1714 		end = last < 1 ? 0 : last - 1;
   1715 		step = -1;
   1716 	} else {
   1717 		start = first < 1 ? 0 : first - 1;
   1718 		end = last > len ? len : last;
   1719 		step = 1;
   1720 	}
   1721 
   1722 	for (i = start; (step < 0) == (i >= end); i += step) {
   1723 		SepBuf_AddSubstring(&buf, words.words[i]);
   1724 		SepBuf_Sep(&buf);
   1725 	}
   1726 
   1727 	SubstringWords_Free(words);
   1728 
   1729 	return SepBuf_DoneData(&buf);
   1730 }
   1731 
   1732 
   1733 /*ARGSUSED*/
   1734 static void
   1735 ModifyWord_Realpath(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   1736 {
   1737 	struct stat st;
   1738 	char rbuf[MAXPATHLEN];
   1739 	const char *rp;
   1740 
   1741 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   1742 	rp = cached_realpath(word.start, rbuf);
   1743 	if (rp != NULL && *rp == '/' && stat(rp, &st) == 0)
   1744 		SepBuf_AddStr(buf, rp);
   1745 	else
   1746 		SepBuf_AddSubstring(buf, word);
   1747 }
   1748 
   1749 
   1750 static char *
   1751 SubstringWords_JoinFree(SubstringWords words)
   1752 {
   1753 	Buffer buf;
   1754 	size_t i;
   1755 
   1756 	Buf_Init(&buf);
   1757 
   1758 	for (i = 0; i < words.len; i++) {
   1759 		if (i != 0) {
   1760 			/*
   1761 			 * XXX: Use ch->sep instead of ' ', for consistency.
   1762 			 */
   1763 			Buf_AddByte(&buf, ' ');
   1764 		}
   1765 		Buf_AddRange(&buf, words.words[i].start, words.words[i].end);
   1766 	}
   1767 
   1768 	SubstringWords_Free(words);
   1769 
   1770 	return Buf_DoneData(&buf);
   1771 }
   1772 
   1773 
   1774 /*
   1775  * Quote shell meta-characters and space characters in the string.
   1776  * If quoteDollar is set, also quote and double any '$' characters.
   1777  */
   1778 static void
   1779 QuoteShell(const char *str, bool quoteDollar, LazyBuf *buf)
   1780 {
   1781 	const char *p;
   1782 
   1783 	LazyBuf_Init(buf, str);
   1784 	for (p = str; *p != '\0'; p++) {
   1785 		if (*p == '\n') {
   1786 			const char *newline = Shell_GetNewline();
   1787 			if (newline == NULL)
   1788 				newline = "\\\n";
   1789 			LazyBuf_AddStr(buf, newline);
   1790 			continue;
   1791 		}
   1792 		if (ch_isspace(*p) || ch_is_shell_meta(*p))
   1793 			LazyBuf_Add(buf, '\\');
   1794 		LazyBuf_Add(buf, *p);
   1795 		if (quoteDollar && *p == '$')
   1796 			LazyBuf_AddStr(buf, "\\$");
   1797 	}
   1798 }
   1799 
   1800 /*
   1801  * Compute the 32-bit hash of the given string, using the MurmurHash3
   1802  * algorithm. Output is encoded as 8 hex digits, in Little Endian order.
   1803  */
   1804 static char *
   1805 Hash(const char *str)
   1806 {
   1807 	static const char hexdigits[16] = "0123456789abcdef";
   1808 	const unsigned char *ustr = (const unsigned char *)str;
   1809 
   1810 	uint32_t h = 0x971e137bU;
   1811 	uint32_t c1 = 0x95543787U;
   1812 	uint32_t c2 = 0x2ad7eb25U;
   1813 	size_t len2 = strlen(str);
   1814 
   1815 	char *buf;
   1816 	size_t i;
   1817 
   1818 	size_t len;
   1819 	for (len = len2; len != 0;) {
   1820 		uint32_t k = 0;
   1821 		switch (len) {
   1822 		default:
   1823 			k = ((uint32_t)ustr[3] << 24) |
   1824 			    ((uint32_t)ustr[2] << 16) |
   1825 			    ((uint32_t)ustr[1] << 8) |
   1826 			    (uint32_t)ustr[0];
   1827 			len -= 4;
   1828 			ustr += 4;
   1829 			break;
   1830 		case 3:
   1831 			k |= (uint32_t)ustr[2] << 16;
   1832 			/* FALLTHROUGH */
   1833 		case 2:
   1834 			k |= (uint32_t)ustr[1] << 8;
   1835 			/* FALLTHROUGH */
   1836 		case 1:
   1837 			k |= (uint32_t)ustr[0];
   1838 			len = 0;
   1839 		}
   1840 		c1 = c1 * 5 + 0x7b7d159cU;
   1841 		c2 = c2 * 5 + 0x6bce6396U;
   1842 		k *= c1;
   1843 		k = (k << 11) ^ (k >> 21);
   1844 		k *= c2;
   1845 		h = (h << 13) ^ (h >> 19);
   1846 		h = h * 5 + 0x52dce729U;
   1847 		h ^= k;
   1848 	}
   1849 	h ^= (uint32_t)len2;
   1850 	h *= 0x85ebca6b;
   1851 	h ^= h >> 13;
   1852 	h *= 0xc2b2ae35;
   1853 	h ^= h >> 16;
   1854 
   1855 	buf = bmake_malloc(9);
   1856 	for (i = 0; i < 8; i++) {
   1857 		buf[i] = hexdigits[h & 0x0f];
   1858 		h >>= 4;
   1859 	}
   1860 	buf[8] = '\0';
   1861 	return buf;
   1862 }
   1863 
   1864 static char *
   1865 FormatTime(const char *fmt, time_t t, bool gmt)
   1866 {
   1867 	char buf[BUFSIZ];
   1868 
   1869 	if (t == 0)
   1870 		time(&t);
   1871 	if (*fmt == '\0')
   1872 		fmt = "%c";
   1873 	if (gmt && strchr(fmt, 's') != NULL) {
   1874 		/* strftime "%s" only works with localtime, not with gmtime. */
   1875 		const char *prev_tz_env = getenv("TZ");
   1876 		char *prev_tz = prev_tz_env != NULL
   1877 		    ? bmake_strdup(prev_tz_env) : NULL;
   1878 		setenv("TZ", "UTC", 1);
   1879 		strftime(buf, sizeof buf, fmt, localtime(&t));
   1880 		if (prev_tz != NULL) {
   1881 			setenv("TZ", prev_tz, 1);
   1882 			free(prev_tz);
   1883 		} else
   1884 			unsetenv("TZ");
   1885 	} else
   1886 		strftime(buf, sizeof buf, fmt, (gmt ? gmtime : localtime)(&t));
   1887 
   1888 	buf[sizeof buf - 1] = '\0';
   1889 	return bmake_strdup(buf);
   1890 }
   1891 
   1892 /*
   1893  * The ApplyModifier functions take an expression that is being evaluated.
   1894  * Their task is to apply a single modifier to the expression.  This involves
   1895  * parsing the modifier, evaluating it and finally updating the value of the
   1896  * expression.
   1897  *
   1898  * Parsing the modifier
   1899  *
   1900  * If parsing succeeds, the parsing position *pp is updated to point to the
   1901  * first character following the modifier, which typically is either ':' or
   1902  * ch->endc.  The modifier doesn't have to check for this delimiter character,
   1903  * this is done by ApplyModifiers.
   1904  *
   1905  * XXX: As of 2020-11-15, some modifiers such as :S, :C, :P, :L do not
   1906  * need to be followed by a ':' or endc; this was an unintended mistake.
   1907  *
   1908  * If parsing fails because of a missing delimiter after a modifier part (as
   1909  * in the :S, :C or :@ modifiers), return AMR_CLEANUP.
   1910  *
   1911  * If parsing fails because the modifier is unknown, return AMR_UNKNOWN to
   1912  * try the SysV modifier ':from=to' as fallback.  This should only be
   1913  * done as long as there have been no side effects from evaluating nested
   1914  * variables, to avoid evaluating them more than once.  In this case, the
   1915  * parsing position may or may not be updated.  (XXX: Why not? The original
   1916  * parsing position is well-known in ApplyModifiers.)
   1917  *
   1918  * If parsing fails and the SysV modifier ${VAR:from=to} should not be used
   1919  * as a fallback, issue an error message using Parse_Error (preferred over
   1920  * Error) and then return AMR_CLEANUP, which stops processing the expression.
   1921  * (XXX: As of 2020-08-23, evaluation of the string continues nevertheless
   1922  * after skipping a few bytes, which results in garbage.)
   1923  *
   1924  * Evaluating the modifier
   1925  *
   1926  * After parsing, the modifier is evaluated.  The side effects from evaluating
   1927  * nested expressions in the modifier text often already happen
   1928  * during parsing though.  For most modifiers this doesn't matter since their
   1929  * only noticeable effect is that they update the value of the expression.
   1930  * Some modifiers such as ':sh' or '::=' have noticeable side effects though.
   1931  *
   1932  * Evaluating the modifier usually takes the current value of the
   1933  * expression from ch->expr->value, or the variable name from ch->var->name,
   1934  * and stores the result back in ch->expr->value via Expr_SetValueOwn or
   1935  * Expr_SetValueRefer.
   1936  *
   1937  * If evaluating fails, the fallback error message "Bad modifier" is printed
   1938  * using Error.  This function has no side effects, it really just prints the
   1939  * error message, continuing as if nothing had happened.  TODO: This should be
   1940  * fixed by adding proper error handling to Var_Subst, Var_Parse,
   1941  * ApplyModifiers and ModifyWords.
   1942  *
   1943  * Some modifiers such as :D and :U turn undefined expressions into defined
   1944  * expressions using Expr_Define.
   1945  */
   1946 
   1947 typedef enum ExprDefined {
   1948 	/* The expression is based on a regular, defined variable. */
   1949 	DEF_REGULAR,
   1950 	/* The expression is based on an undefined variable. */
   1951 	DEF_UNDEF,
   1952 	/*
   1953 	 * The expression started as an undefined expression, but one
   1954 	 * of the modifiers (such as ':D' or ':U') has turned the expression
   1955 	 * from undefined to defined.
   1956 	 */
   1957 	DEF_DEFINED
   1958 } ExprDefined;
   1959 
   1960 static const char ExprDefined_Name[][10] = {
   1961 	"regular",
   1962 	"undefined",
   1963 	"defined"
   1964 };
   1965 
   1966 #if __STDC_VERSION__ >= 199901L
   1967 #define const_member		const
   1968 #else
   1969 #define const_member		/* no const possible */
   1970 #endif
   1971 
   1972 /* An expression based on a variable, such as $@ or ${VAR:Mpattern:Q}. */
   1973 typedef struct Expr {
   1974 	const char *name;
   1975 	FStr value;
   1976 	VarEvalMode const_member emode;
   1977 	GNode *const_member scope;
   1978 	ExprDefined defined;
   1979 } Expr;
   1980 
   1981 /*
   1982  * The status of applying a chain of modifiers to an expression.
   1983  *
   1984  * The modifiers of an expression are broken into chains of modifiers,
   1985  * starting a new nested chain whenever an indirect modifier starts.  There
   1986  * are at most 2 nesting levels: the outer one for the direct modifiers, and
   1987  * the inner one for the indirect modifiers.
   1988  *
   1989  * For example, the expression ${VAR:M*:${IND1}:${IND2}:O:u} has 3 chains of
   1990  * modifiers:
   1991  *
   1992  *	Chain 1 starts with the single modifier ':M*'.
   1993  *	  Chain 2 starts with all modifiers from ${IND1}.
   1994  *	  Chain 2 ends at the ':' between ${IND1} and ${IND2}.
   1995  *	  Chain 3 starts with all modifiers from ${IND2}.
   1996  *	  Chain 3 ends at the ':' after ${IND2}.
   1997  *	Chain 1 continues with the 2 modifiers ':O' and ':u'.
   1998  *	Chain 1 ends at the final '}' of the expression.
   1999  *
   2000  * After such a chain ends, its properties no longer have any effect.
   2001  *
   2002  * See varmod-indirect.mk.
   2003  */
   2004 typedef struct ModChain {
   2005 	Expr *expr;
   2006 	/* '\0' or '{' or '(' */
   2007 	char const_member startc;
   2008 	/* '\0' or '}' or ')' */
   2009 	char const_member endc;
   2010 	/* Separator when joining words (see the :ts modifier). */
   2011 	char sep;
   2012 	/*
   2013 	 * Whether some modifiers that otherwise split the variable value
   2014 	 * into words, like :S and :C, treat the variable value as a single
   2015 	 * big word, possibly containing spaces.
   2016 	 */
   2017 	bool oneBigWord;
   2018 } ModChain;
   2019 
   2020 static void
   2021 Expr_Define(Expr *expr)
   2022 {
   2023 	if (expr->defined == DEF_UNDEF)
   2024 		expr->defined = DEF_DEFINED;
   2025 }
   2026 
   2027 static const char *
   2028 Expr_Str(const Expr *expr)
   2029 {
   2030 	return expr->value.str;
   2031 }
   2032 
   2033 static SubstringWords
   2034 Expr_Words(const Expr *expr)
   2035 {
   2036 	return Substring_Words(Expr_Str(expr), false);
   2037 }
   2038 
   2039 static void
   2040 Expr_SetValue(Expr *expr, FStr value)
   2041 {
   2042 	FStr_Done(&expr->value);
   2043 	expr->value = value;
   2044 }
   2045 
   2046 static void
   2047 Expr_SetValueOwn(Expr *expr, char *value)
   2048 {
   2049 	Expr_SetValue(expr, FStr_InitOwn(value));
   2050 }
   2051 
   2052 static void
   2053 Expr_SetValueRefer(Expr *expr, const char *value)
   2054 {
   2055 	Expr_SetValue(expr, FStr_InitRefer(value));
   2056 }
   2057 
   2058 static bool
   2059 Expr_ShouldEval(const Expr *expr)
   2060 {
   2061 	return VarEvalMode_ShouldEval(expr->emode);
   2062 }
   2063 
   2064 static bool
   2065 ModChain_ShouldEval(const ModChain *ch)
   2066 {
   2067 	return Expr_ShouldEval(ch->expr);
   2068 }
   2069 
   2070 
   2071 typedef enum ApplyModifierResult {
   2072 	/* Continue parsing */
   2073 	AMR_OK,
   2074 	/* Not a match, try the ':from=to' modifier as well. */
   2075 	AMR_UNKNOWN,
   2076 	/* Error out with "Bad modifier" message. */
   2077 	AMR_BAD,
   2078 	/* Error out without the standard error message. */
   2079 	AMR_CLEANUP
   2080 } ApplyModifierResult;
   2081 
   2082 /*
   2083  * Allow backslashes to escape the delimiter, $, and \, but don't touch other
   2084  * backslashes.
   2085  */
   2086 static bool
   2087 IsEscapedModifierPart(const char *p, char delim,
   2088 		      struct ModifyWord_SubstArgs *subst)
   2089 {
   2090 	if (p[0] != '\\')
   2091 		return false;
   2092 	if (p[1] == delim || p[1] == '\\' || p[1] == '$')
   2093 		return true;
   2094 	return p[1] == '&' && subst != NULL;
   2095 }
   2096 
   2097 /*
   2098  * In a part of a modifier, parse a subexpression and evaluate it.
   2099  */
   2100 static void
   2101 ParseModifierPartExpr(const char **pp, LazyBuf *part, const ModChain *ch,
   2102 		      VarEvalMode emode)
   2103 {
   2104 	const char *p = *pp;
   2105 	FStr nested_val = Var_Parse(&p, ch->expr->scope,
   2106 	    VarEvalMode_WithoutKeepDollar(emode));
   2107 	/* TODO: handle errors */
   2108 	if (VarEvalMode_ShouldEval(emode))
   2109 		LazyBuf_AddStr(part, nested_val.str);
   2110 	else
   2111 		LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
   2112 	FStr_Done(&nested_val);
   2113 	*pp = p;
   2114 }
   2115 
   2116 /*
   2117  * In a part of a modifier, parse some text that looks like a subexpression.
   2118  * If the text starts with '$(', any '(' and ')' must be balanced.
   2119  * If the text starts with '${', any '{' and '}' must be balanced.
   2120  * If the text starts with '$', that '$' is copied verbatim, it is not parsed
   2121  * as a short-name expression.
   2122  */
   2123 static void
   2124 ParseModifierPartBalanced(const char **pp, LazyBuf *part)
   2125 {
   2126 	const char *p = *pp;
   2127 
   2128 	if (p[1] == '(' || p[1] == '{') {
   2129 		char startc = p[1];
   2130 		int endc = startc == '(' ? ')' : '}';
   2131 		int depth = 1;
   2132 
   2133 		for (p += 2; *p != '\0' && depth > 0; p++) {
   2134 			if (p[-1] != '\\') {
   2135 				if (*p == startc)
   2136 					depth++;
   2137 				if (*p == endc)
   2138 					depth--;
   2139 			}
   2140 		}
   2141 		LazyBuf_AddSubstring(part, Substring_Init(*pp, p));
   2142 		*pp = p;
   2143 	} else {
   2144 		LazyBuf_Add(part, *p);
   2145 		*pp = p + 1;
   2146 	}
   2147 }
   2148 
   2149 /* See ParseModifierPart for the documentation. */
   2150 static bool
   2151 ParseModifierPartSubst(
   2152     const char **pp,
   2153     /* If true, parse up to but excluding the next ':' or ch->endc. */
   2154     bool whole,
   2155     char delim,
   2156     VarEvalMode emode,
   2157     ModChain *ch,
   2158     LazyBuf *part,
   2159     /*
   2160      * For the first part of the ':S' modifier, set anchorEnd if the last
   2161      * character of the pattern is a $.
   2162      */
   2163     PatternFlags *out_pflags,
   2164     /*
   2165      * For the second part of the ':S' modifier, allow ampersands to be
   2166      * escaped and replace unescaped ampersands with subst->lhs.
   2167      */
   2168     struct ModifyWord_SubstArgs *subst
   2169 )
   2170 {
   2171 	const char *p;
   2172 	char end1, end2;
   2173 
   2174 	p = *pp;
   2175 	LazyBuf_Init(part, p);
   2176 
   2177 	end1 = whole ? ':' : delim;
   2178 	end2 = whole ? ch->endc : delim;
   2179 	while (*p != '\0' && *p != end1 && *p != end2) {
   2180 		if (IsEscapedModifierPart(p, delim, subst)) {
   2181 			LazyBuf_Add(part, p[1]);
   2182 			p += 2;
   2183 		} else if (*p != '$') {	/* Unescaped, simple text */
   2184 			if (subst != NULL && *p == '&')
   2185 				LazyBuf_AddSubstring(part, subst->lhs);
   2186 			else
   2187 				LazyBuf_Add(part, *p);
   2188 			p++;
   2189 		} else if (p[1] == delim) {	/* Unescaped '$' at end */
   2190 			if (out_pflags != NULL)
   2191 				out_pflags->anchorEnd = true;
   2192 			else
   2193 				LazyBuf_Add(part, *p);
   2194 			p++;
   2195 		} else if (emode == VARE_PARSE_BALANCED)
   2196 			ParseModifierPartBalanced(&p, part);
   2197 		else
   2198 			ParseModifierPartExpr(&p, part, ch, emode);
   2199 	}
   2200 
   2201 	*pp = p;
   2202 	if (*p != end1 && *p != end2) {
   2203 		Error("Unfinished modifier for \"%s\" ('%c' missing)",
   2204 		    ch->expr->name, end2);
   2205 		LazyBuf_Done(part);
   2206 		return false;
   2207 	}
   2208 	if (!whole)
   2209 		(*pp)++;
   2210 
   2211 	{
   2212 		Substring sub = LazyBuf_Get(part);
   2213 		DEBUG2(VAR, "Modifier part: \"%.*s\"\n",
   2214 		    (int)Substring_Length(sub), sub.start);
   2215 	}
   2216 
   2217 	return true;
   2218 }
   2219 
   2220 /*
   2221  * Parse a part of a modifier such as the "from" and "to" in :S/from/to/ or
   2222  * the "var" or "replacement ${var}" in :@var@replacement ${var}@, up to and
   2223  * including the next unescaped delimiter.  The delimiter, as well as the
   2224  * backslash or the dollar, can be escaped with a backslash.
   2225  *
   2226  * Return true if parsing succeeded, together with the parsed (and possibly
   2227  * expanded) part.  In that case, pp points right after the delimiter.  The
   2228  * delimiter is not included in the part though.
   2229  */
   2230 static bool
   2231 ParseModifierPart(
   2232     /* The parsing position, updated upon return */
   2233     const char **pp,
   2234     /* Parsing stops at this delimiter */
   2235     char delim,
   2236     /* Mode for evaluating nested expressions. */
   2237     VarEvalMode emode,
   2238     ModChain *ch,
   2239     LazyBuf *part
   2240 )
   2241 {
   2242 	return ParseModifierPartSubst(pp, false, delim, emode, ch, part,
   2243 	    NULL, NULL);
   2244 }
   2245 
   2246 MAKE_INLINE bool
   2247 IsDelimiter(char c, const ModChain *ch)
   2248 {
   2249 	return c == ':' || c == ch->endc || c == '\0';
   2250 }
   2251 
   2252 /* Test whether mod starts with modname, followed by a delimiter. */
   2253 MAKE_INLINE bool
   2254 ModMatch(const char *mod, const char *modname, const ModChain *ch)
   2255 {
   2256 	size_t n = strlen(modname);
   2257 	return strncmp(mod, modname, n) == 0 && IsDelimiter(mod[n], ch);
   2258 }
   2259 
   2260 /* Test whether mod starts with modname, followed by a delimiter or '='. */
   2261 MAKE_INLINE bool
   2262 ModMatchEq(const char *mod, const char *modname, const ModChain *ch)
   2263 {
   2264 	size_t n = strlen(modname);
   2265 	return strncmp(mod, modname, n) == 0 &&
   2266 	       (IsDelimiter(mod[n], ch) || mod[n] == '=');
   2267 }
   2268 
   2269 static bool
   2270 TryParseIntBase0(const char **pp, int *out_num)
   2271 {
   2272 	char *end;
   2273 	long n;
   2274 
   2275 	errno = 0;
   2276 	n = strtol(*pp, &end, 0);
   2277 
   2278 	if (end == *pp)
   2279 		return false;
   2280 	if ((n == LONG_MIN || n == LONG_MAX) && errno == ERANGE)
   2281 		return false;
   2282 	if (n < INT_MIN || n > INT_MAX)
   2283 		return false;
   2284 
   2285 	*pp = end;
   2286 	*out_num = (int)n;
   2287 	return true;
   2288 }
   2289 
   2290 static bool
   2291 TryParseSize(const char **pp, size_t *out_num)
   2292 {
   2293 	char *end;
   2294 	unsigned long n;
   2295 
   2296 	if (!ch_isdigit(**pp))
   2297 		return false;
   2298 
   2299 	errno = 0;
   2300 	n = strtoul(*pp, &end, 10);
   2301 	if (n == ULONG_MAX && errno == ERANGE)
   2302 		return false;
   2303 	if (n > SIZE_MAX)
   2304 		return false;
   2305 
   2306 	*pp = end;
   2307 	*out_num = (size_t)n;
   2308 	return true;
   2309 }
   2310 
   2311 static bool
   2312 TryParseChar(const char **pp, int base, char *out_ch)
   2313 {
   2314 	char *end;
   2315 	unsigned long n;
   2316 
   2317 	if (!ch_isalnum(**pp))
   2318 		return false;
   2319 
   2320 	errno = 0;
   2321 	n = strtoul(*pp, &end, base);
   2322 	if (n == ULONG_MAX && errno == ERANGE)
   2323 		return false;
   2324 	if (n > UCHAR_MAX)
   2325 		return false;
   2326 
   2327 	*pp = end;
   2328 	*out_ch = (char)n;
   2329 	return true;
   2330 }
   2331 
   2332 /*
   2333  * Modify each word of the expression using the given function and place the
   2334  * result back in the expression.
   2335  */
   2336 static void
   2337 ModifyWords(ModChain *ch,
   2338 	    ModifyWordProc modifyWord, void *modifyWord_args,
   2339 	    bool oneBigWord)
   2340 {
   2341 	Expr *expr = ch->expr;
   2342 	const char *val = Expr_Str(expr);
   2343 	SepBuf result;
   2344 	SubstringWords words;
   2345 	size_t i;
   2346 	Substring word;
   2347 
   2348 	if (!ModChain_ShouldEval(ch))
   2349 		return;
   2350 
   2351 	if (oneBigWord) {
   2352 		SepBuf_Init(&result, ch->sep);
   2353 		/* XXX: performance: Substring_InitStr calls strlen */
   2354 		word = Substring_InitStr(val);
   2355 		modifyWord(word, &result, modifyWord_args);
   2356 		goto done;
   2357 	}
   2358 
   2359 	words = Substring_Words(val, false);
   2360 
   2361 	DEBUG3(VAR, "ModifyWords: split \"%s\" into %u %s\n",
   2362 	    val, (unsigned)words.len, words.len != 1 ? "words" : "word");
   2363 
   2364 	SepBuf_Init(&result, ch->sep);
   2365 	for (i = 0; i < words.len; i++) {
   2366 		modifyWord(words.words[i], &result, modifyWord_args);
   2367 		if (result.buf.len > 0)
   2368 			SepBuf_Sep(&result);
   2369 	}
   2370 
   2371 	SubstringWords_Free(words);
   2372 
   2373 done:
   2374 	Expr_SetValueOwn(expr, SepBuf_DoneData(&result));
   2375 }
   2376 
   2377 /* :@var (at) ...${var}...@ */
   2378 static ApplyModifierResult
   2379 ApplyModifier_Loop(const char **pp, ModChain *ch)
   2380 {
   2381 	Expr *expr = ch->expr;
   2382 	struct ModifyWord_LoopArgs args;
   2383 	char prev_sep;
   2384 	LazyBuf tvarBuf, strBuf;
   2385 	FStr tvar, str;
   2386 
   2387 	args.scope = expr->scope;
   2388 
   2389 	(*pp)++;		/* Skip the first '@' */
   2390 	if (!ParseModifierPart(pp, '@', VARE_PARSE_ONLY, ch, &tvarBuf))
   2391 		return AMR_CLEANUP;
   2392 	tvar = LazyBuf_DoneGet(&tvarBuf);
   2393 	args.var = tvar.str;
   2394 	if (strchr(args.var, '$') != NULL) {
   2395 		Parse_Error(PARSE_FATAL,
   2396 		    "In the :@ modifier, the variable name \"%s\" "
   2397 		    "must not contain a dollar",
   2398 		    args.var);
   2399 		goto cleanup_tvar;
   2400 	}
   2401 
   2402 	if (!ParseModifierPart(pp, '@', VARE_PARSE_BALANCED, ch, &strBuf))
   2403 		goto cleanup_tvar;
   2404 	str = LazyBuf_DoneGet(&strBuf);
   2405 	args.body = str.str;
   2406 
   2407 	if (!Expr_ShouldEval(expr))
   2408 		goto done;
   2409 
   2410 	args.emode = VarEvalMode_WithoutKeepDollar(expr->emode);
   2411 	prev_sep = ch->sep;
   2412 	ch->sep = ' ';		/* XXX: should be ch->sep for consistency */
   2413 	ModifyWords(ch, ModifyWord_Loop, &args, ch->oneBigWord);
   2414 	ch->sep = prev_sep;
   2415 	/* XXX: Consider restoring the previous value instead of deleting. */
   2416 	Var_Delete(expr->scope, args.var);
   2417 
   2418 done:
   2419 	FStr_Done(&tvar);
   2420 	FStr_Done(&str);
   2421 	return AMR_OK;
   2422 
   2423 cleanup_tvar:
   2424 	FStr_Done(&tvar);
   2425 	return AMR_CLEANUP;
   2426 }
   2427 
   2428 static void
   2429 ParseModifier_Defined(const char **pp, ModChain *ch, bool shouldEval,
   2430 		      LazyBuf *buf)
   2431 {
   2432 	const char *p;
   2433 
   2434 	p = *pp + 1;
   2435 	LazyBuf_Init(buf, p);
   2436 	while (!IsDelimiter(*p, ch)) {
   2437 
   2438 		/*
   2439 		 * XXX: This code is similar to the one in Var_Parse. See if
   2440 		 * the code can be merged. See also ParseModifier_Match and
   2441 		 * ParseModifierPart.
   2442 		 */
   2443 
   2444 		/* See Buf_AddEscaped in for.c for the counterpart. */
   2445 		if (*p == '\\') {
   2446 			char c = p[1];
   2447 			if ((IsDelimiter(c, ch) && c != '\0') ||
   2448 			    c == '$' || c == '\\') {
   2449 				if (shouldEval)
   2450 					LazyBuf_Add(buf, c);
   2451 				p += 2;
   2452 				continue;
   2453 			}
   2454 		}
   2455 
   2456 		if (*p == '$') {
   2457 			FStr val = Var_Parse(&p, ch->expr->scope,
   2458 			    shouldEval ? ch->expr->emode : VARE_PARSE_ONLY);
   2459 			/* TODO: handle errors */
   2460 			if (shouldEval)
   2461 				LazyBuf_AddStr(buf, val.str);
   2462 			FStr_Done(&val);
   2463 			continue;
   2464 		}
   2465 
   2466 		if (shouldEval)
   2467 			LazyBuf_Add(buf, *p);
   2468 		p++;
   2469 	}
   2470 	*pp = p;
   2471 }
   2472 
   2473 /* :Ddefined or :Uundefined */
   2474 static ApplyModifierResult
   2475 ApplyModifier_Defined(const char **pp, ModChain *ch)
   2476 {
   2477 	Expr *expr = ch->expr;
   2478 	LazyBuf buf;
   2479 	bool shouldEval =
   2480 	    Expr_ShouldEval(expr) &&
   2481 	    (**pp == 'D') == (expr->defined == DEF_REGULAR);
   2482 
   2483 	ParseModifier_Defined(pp, ch, shouldEval, &buf);
   2484 
   2485 	Expr_Define(expr);
   2486 	if (shouldEval)
   2487 		Expr_SetValue(expr, Substring_Str(LazyBuf_Get(&buf)));
   2488 	LazyBuf_Done(&buf);
   2489 
   2490 	return AMR_OK;
   2491 }
   2492 
   2493 /* :L */
   2494 static ApplyModifierResult
   2495 ApplyModifier_Literal(const char **pp, ModChain *ch)
   2496 {
   2497 	Expr *expr = ch->expr;
   2498 
   2499 	(*pp)++;
   2500 
   2501 	if (Expr_ShouldEval(expr)) {
   2502 		Expr_Define(expr);
   2503 		Expr_SetValueOwn(expr, bmake_strdup(expr->name));
   2504 	}
   2505 
   2506 	return AMR_OK;
   2507 }
   2508 
   2509 static bool
   2510 TryParseTime(const char **pp, time_t *out_time)
   2511 {
   2512 	char *end;
   2513 	unsigned long n;
   2514 
   2515 	if (!ch_isdigit(**pp))
   2516 		return false;
   2517 
   2518 	errno = 0;
   2519 	n = strtoul(*pp, &end, 10);
   2520 	if (n == ULONG_MAX && errno == ERANGE)
   2521 		return false;
   2522 
   2523 	*pp = end;
   2524 	*out_time = (time_t)n;	/* ignore possible truncation for now */
   2525 	return true;
   2526 }
   2527 
   2528 /* :gmtime and :localtime */
   2529 static ApplyModifierResult
   2530 ApplyModifier_Time(const char **pp, ModChain *ch)
   2531 {
   2532 	Expr *expr;
   2533 	time_t t;
   2534 	const char *args;
   2535 	const char *mod = *pp;
   2536 	bool gmt = mod[0] == 'g';
   2537 
   2538 	if (!ModMatchEq(mod, gmt ? "gmtime" : "localtime", ch))
   2539 		return AMR_UNKNOWN;
   2540 	args = mod + (gmt ? 6 : 9);
   2541 
   2542 	if (args[0] == '=') {
   2543 		const char *p = args + 1;
   2544 		LazyBuf buf;
   2545 		FStr arg;
   2546 		if (!ParseModifierPartSubst(&p, true, '\0', ch->expr->emode,
   2547 		    ch, &buf, NULL, NULL))
   2548 			return AMR_CLEANUP;
   2549 		arg = LazyBuf_DoneGet(&buf);
   2550 		if (ModChain_ShouldEval(ch)) {
   2551 			const char *arg_p = arg.str;
   2552 			if (!TryParseTime(&arg_p, &t) || *arg_p != '\0') {
   2553 				Parse_Error(PARSE_FATAL,
   2554 				    "Invalid time value \"%s\"", arg.str);
   2555 				FStr_Done(&arg);
   2556 				return AMR_CLEANUP;
   2557 			}
   2558 		} else
   2559 			t = 0;
   2560 		FStr_Done(&arg);
   2561 		*pp = p;
   2562 	} else {
   2563 		t = 0;
   2564 		*pp = args;
   2565 	}
   2566 
   2567 	expr = ch->expr;
   2568 	if (Expr_ShouldEval(expr))
   2569 		Expr_SetValueOwn(expr, FormatTime(Expr_Str(expr), t, gmt));
   2570 
   2571 	return AMR_OK;
   2572 }
   2573 
   2574 /* :hash */
   2575 static ApplyModifierResult
   2576 ApplyModifier_Hash(const char **pp, ModChain *ch)
   2577 {
   2578 	if (!ModMatch(*pp, "hash", ch))
   2579 		return AMR_UNKNOWN;
   2580 	*pp += 4;
   2581 
   2582 	if (ModChain_ShouldEval(ch))
   2583 		Expr_SetValueOwn(ch->expr, Hash(Expr_Str(ch->expr)));
   2584 
   2585 	return AMR_OK;
   2586 }
   2587 
   2588 /* :P */
   2589 static ApplyModifierResult
   2590 ApplyModifier_Path(const char **pp, ModChain *ch)
   2591 {
   2592 	Expr *expr = ch->expr;
   2593 	GNode *gn;
   2594 	char *path;
   2595 
   2596 	(*pp)++;
   2597 
   2598 	if (!Expr_ShouldEval(expr))
   2599 		return AMR_OK;
   2600 
   2601 	Expr_Define(expr);
   2602 
   2603 	gn = Targ_FindNode(expr->name);
   2604 	if (gn == NULL || gn->type & OP_NOPATH)
   2605 		path = NULL;
   2606 	else if (gn->path != NULL)
   2607 		path = bmake_strdup(gn->path);
   2608 	else {
   2609 		SearchPath *searchPath = Suff_FindPath(gn);
   2610 		path = Dir_FindFile(expr->name, searchPath);
   2611 	}
   2612 	if (path == NULL)
   2613 		path = bmake_strdup(expr->name);
   2614 	Expr_SetValueOwn(expr, path);
   2615 
   2616 	return AMR_OK;
   2617 }
   2618 
   2619 /* :!cmd! */
   2620 static ApplyModifierResult
   2621 ApplyModifier_ShellCommand(const char **pp, ModChain *ch)
   2622 {
   2623 	Expr *expr = ch->expr;
   2624 	LazyBuf cmdBuf;
   2625 	FStr cmd;
   2626 
   2627 	(*pp)++;
   2628 	if (!ParseModifierPart(pp, '!', expr->emode, ch, &cmdBuf))
   2629 		return AMR_CLEANUP;
   2630 	cmd = LazyBuf_DoneGet(&cmdBuf);
   2631 
   2632 	if (Expr_ShouldEval(expr)) {
   2633 		char *output, *error;
   2634 		output = Cmd_Exec(cmd.str, &error);
   2635 		Expr_SetValueOwn(expr, output);
   2636 		if (error != NULL) {
   2637 			/* XXX: why still return AMR_OK? */
   2638 			Error("%s", error);
   2639 			free(error);
   2640 		}
   2641 	} else
   2642 		Expr_SetValueRefer(expr, "");
   2643 
   2644 	FStr_Done(&cmd);
   2645 	Expr_Define(expr);
   2646 
   2647 	return AMR_OK;
   2648 }
   2649 
   2650 /*
   2651  * The :range modifier generates an integer sequence as long as the words.
   2652  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2653  */
   2654 static ApplyModifierResult
   2655 ApplyModifier_Range(const char **pp, ModChain *ch)
   2656 {
   2657 	size_t n;
   2658 	Buffer buf;
   2659 	size_t i;
   2660 
   2661 	const char *mod = *pp;
   2662 	if (!ModMatchEq(mod, "range", ch))
   2663 		return AMR_UNKNOWN;
   2664 
   2665 	if (mod[5] == '=') {
   2666 		const char *p = mod + 6;
   2667 		if (!TryParseSize(&p, &n)) {
   2668 			Parse_Error(PARSE_FATAL,
   2669 			    "Invalid number \"%s\" for ':range' modifier",
   2670 			    mod + 6);
   2671 			return AMR_CLEANUP;
   2672 		}
   2673 		*pp = p;
   2674 	} else {
   2675 		n = 0;
   2676 		*pp = mod + 5;
   2677 	}
   2678 
   2679 	if (!ModChain_ShouldEval(ch))
   2680 		return AMR_OK;
   2681 
   2682 	if (n == 0) {
   2683 		SubstringWords words = Expr_Words(ch->expr);
   2684 		n = words.len;
   2685 		SubstringWords_Free(words);
   2686 	}
   2687 
   2688 	Buf_Init(&buf);
   2689 
   2690 	for (i = 0; i < n; i++) {
   2691 		if (i != 0) {
   2692 			/*
   2693 			 * XXX: Use ch->sep instead of ' ', for consistency.
   2694 			 */
   2695 			Buf_AddByte(&buf, ' ');
   2696 		}
   2697 		Buf_AddInt(&buf, 1 + (int)i);
   2698 	}
   2699 
   2700 	Expr_SetValueOwn(ch->expr, Buf_DoneData(&buf));
   2701 	return AMR_OK;
   2702 }
   2703 
   2704 /* Parse a ':M' or ':N' modifier. */
   2705 static char *
   2706 ParseModifier_Match(const char **pp, const ModChain *ch)
   2707 {
   2708 	const char *mod = *pp;
   2709 	Expr *expr = ch->expr;
   2710 	bool copy = false;	/* pattern should be, or has been, copied */
   2711 	bool needSubst = false;
   2712 	const char *endpat;
   2713 	char *pattern;
   2714 
   2715 	/*
   2716 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2717 	 * original brace level.
   2718 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2719 	 */
   2720 	/*
   2721 	 * XXX: This code is similar to the one in Var_Parse.
   2722 	 * See if the code can be merged.
   2723 	 * See also ApplyModifier_Defined.
   2724 	 */
   2725 	int depth = 0;
   2726 	const char *p;
   2727 	for (p = mod + 1; *p != '\0' && !(*p == ':' && depth == 0); p++) {
   2728 		if (*p == '\\' && p[1] != '\0' &&
   2729 		    (IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
   2730 			if (!needSubst)
   2731 				copy = true;
   2732 			p++;
   2733 			continue;
   2734 		}
   2735 		if (*p == '$')
   2736 			needSubst = true;
   2737 		if (*p == '(' || *p == '{')
   2738 			depth++;
   2739 		if (*p == ')' || *p == '}') {
   2740 			depth--;
   2741 			if (depth < 0)
   2742 				break;
   2743 		}
   2744 	}
   2745 	*pp = p;
   2746 	endpat = p;
   2747 
   2748 	if (copy) {
   2749 		char *dst;
   2750 		const char *src;
   2751 
   2752 		/* Compress the \:'s out of the pattern. */
   2753 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2754 		dst = pattern;
   2755 		src = mod + 1;
   2756 		for (; src < endpat; src++, dst++) {
   2757 			if (src[0] == '\\' && src + 1 < endpat &&
   2758 			    /* XXX: ch->startc is missing here; see above */
   2759 			    IsDelimiter(src[1], ch))
   2760 				src++;
   2761 			*dst = *src;
   2762 		}
   2763 		*dst = '\0';
   2764 	} else {
   2765 		pattern = bmake_strsedup(mod + 1, endpat);
   2766 	}
   2767 
   2768 	if (needSubst) {
   2769 		char *old_pattern = pattern;
   2770 		/*
   2771 		 * XXX: Contrary to ParseModifierPart, a dollar in a ':M' or
   2772 		 * ':N' modifier must be escaped as '$$', not as '\$'.
   2773 		 */
   2774 		pattern = Var_Subst(pattern, expr->scope, expr->emode);
   2775 		/* TODO: handle errors */
   2776 		free(old_pattern);
   2777 	}
   2778 
   2779 	DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
   2780 
   2781 	return pattern;
   2782 }
   2783 
   2784 struct ModifyWord_MatchArgs {
   2785 	const char *pattern;
   2786 	bool neg;
   2787 	bool error_reported;
   2788 };
   2789 
   2790 static void
   2791 ModifyWord_Match(Substring word, SepBuf *buf, void *data)
   2792 {
   2793 	struct ModifyWord_MatchArgs *args = data;
   2794 	StrMatchResult res;
   2795 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2796 	res = Str_Match(word.start, args->pattern);
   2797 	if (res.error != NULL && !args->error_reported) {
   2798 		args->error_reported = true;
   2799 		Parse_Error(PARSE_WARNING,
   2800 		    "%s in pattern '%s' of modifier '%s'",
   2801 		    res.error, args->pattern, args->neg ? ":N" : ":M");
   2802 	}
   2803 	if (res.matched != args->neg)
   2804 		SepBuf_AddSubstring(buf, word);
   2805 }
   2806 
   2807 /* :Mpattern or :Npattern */
   2808 static ApplyModifierResult
   2809 ApplyModifier_Match(const char **pp, ModChain *ch)
   2810 {
   2811 	char mod = **pp;
   2812 	char *pattern;
   2813 
   2814 	pattern = ParseModifier_Match(pp, ch);
   2815 
   2816 	if (ModChain_ShouldEval(ch)) {
   2817 		struct ModifyWord_MatchArgs args;
   2818 		args.pattern = pattern;
   2819 		args.neg = mod == 'N';
   2820 		args.error_reported = false;
   2821 		ModifyWords(ch, ModifyWord_Match, &args, ch->oneBigWord);
   2822 	}
   2823 
   2824 	free(pattern);
   2825 	return AMR_OK;
   2826 }
   2827 
   2828 struct ModifyWord_MtimeArgs {
   2829 	bool error;
   2830 	bool use_fallback;
   2831 	ApplyModifierResult rc;
   2832 	time_t fallback;
   2833 };
   2834 
   2835 static void
   2836 ModifyWord_Mtime(Substring word, SepBuf *buf, void *data)
   2837 {
   2838 	struct ModifyWord_MtimeArgs *args = data;
   2839 	struct stat st;
   2840 	char tbuf[21];
   2841 
   2842 	if (Substring_IsEmpty(word))
   2843 		return;
   2844 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2845 	if (stat(word.start, &st) < 0) {
   2846 		if (args->error) {
   2847 			Parse_Error(PARSE_FATAL,
   2848 			    "Cannot determine mtime for '%s': %s",
   2849 			    word.start, strerror(errno));
   2850 			args->rc = AMR_CLEANUP;
   2851 			return;
   2852 		}
   2853 		if (args->use_fallback)
   2854 			st.st_mtime = args->fallback;
   2855 		else
   2856 			time(&st.st_mtime);
   2857 	}
   2858 	snprintf(tbuf, sizeof(tbuf), "%u", (unsigned)st.st_mtime);
   2859 	SepBuf_AddStr(buf, tbuf);
   2860 }
   2861 
   2862 /* :mtime */
   2863 static ApplyModifierResult
   2864 ApplyModifier_Mtime(const char **pp, ModChain *ch)
   2865 {
   2866 	const char *p, *mod = *pp;
   2867 	struct ModifyWord_MtimeArgs args;
   2868 
   2869 	if (!ModMatchEq(mod, "mtime", ch))
   2870 		return AMR_UNKNOWN;
   2871 	*pp += 5;
   2872 	p = *pp;
   2873 	args.error = false;
   2874 	args.use_fallback = p[0] == '=';
   2875 	args.rc = AMR_OK;
   2876 	if (args.use_fallback) {
   2877 		p++;
   2878 		if (TryParseTime(&p, &args.fallback)) {
   2879 		} else if (strncmp(p, "error", 5) == 0) {
   2880 			p += 5;
   2881 			args.error = true;
   2882 		} else
   2883 			goto invalid_argument;
   2884 		if (!IsDelimiter(*p, ch))
   2885 			goto invalid_argument;
   2886 		*pp = p;
   2887 	}
   2888 	ModifyWords(ch, ModifyWord_Mtime, &args, ch->oneBigWord);
   2889 	return args.rc;
   2890 
   2891 invalid_argument:
   2892 	Parse_Error(PARSE_FATAL,
   2893 	    "Invalid argument '%.*s' for modifier ':mtime'",
   2894 	    (int)strcspn(*pp + 1, ":{}()"), *pp + 1);
   2895 	return AMR_CLEANUP;
   2896 }
   2897 
   2898 static void
   2899 ParsePatternFlags(const char **pp, PatternFlags *pflags, bool *oneBigWord)
   2900 {
   2901 	for (;; (*pp)++) {
   2902 		if (**pp == 'g')
   2903 			pflags->subGlobal = true;
   2904 		else if (**pp == '1')
   2905 			pflags->subOnce = true;
   2906 		else if (**pp == 'W')
   2907 			*oneBigWord = true;
   2908 		else
   2909 			break;
   2910 	}
   2911 }
   2912 
   2913 MAKE_INLINE PatternFlags
   2914 PatternFlags_None(void)
   2915 {
   2916 	PatternFlags pflags = { false, false, false, false };
   2917 	return pflags;
   2918 }
   2919 
   2920 /* :S,from,to, */
   2921 static ApplyModifierResult
   2922 ApplyModifier_Subst(const char **pp, ModChain *ch)
   2923 {
   2924 	struct ModifyWord_SubstArgs args;
   2925 	bool oneBigWord;
   2926 	LazyBuf lhsBuf, rhsBuf;
   2927 
   2928 	char delim = (*pp)[1];
   2929 	if (delim == '\0') {
   2930 		Error("Missing delimiter for modifier ':S'");
   2931 		(*pp)++;
   2932 		return AMR_CLEANUP;
   2933 	}
   2934 
   2935 	*pp += 2;
   2936 
   2937 	args.pflags = PatternFlags_None();
   2938 	args.matched = false;
   2939 
   2940 	if (**pp == '^') {
   2941 		args.pflags.anchorStart = true;
   2942 		(*pp)++;
   2943 	}
   2944 
   2945 	if (!ParseModifierPartSubst(pp,
   2946 	    false, delim, ch->expr->emode, ch, &lhsBuf, &args.pflags, NULL))
   2947 		return AMR_CLEANUP;
   2948 	args.lhs = LazyBuf_Get(&lhsBuf);
   2949 
   2950 	if (!ParseModifierPartSubst(pp,
   2951 	    false, delim, ch->expr->emode, ch, &rhsBuf, NULL, &args)) {
   2952 		LazyBuf_Done(&lhsBuf);
   2953 		return AMR_CLEANUP;
   2954 	}
   2955 	args.rhs = LazyBuf_Get(&rhsBuf);
   2956 
   2957 	oneBigWord = ch->oneBigWord;
   2958 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2959 
   2960 	ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
   2961 
   2962 	LazyBuf_Done(&lhsBuf);
   2963 	LazyBuf_Done(&rhsBuf);
   2964 	return AMR_OK;
   2965 }
   2966 
   2967 /* :C,from,to, */
   2968 static ApplyModifierResult
   2969 ApplyModifier_Regex(const char **pp, ModChain *ch)
   2970 {
   2971 	struct ModifyWord_SubstRegexArgs args;
   2972 	bool oneBigWord;
   2973 	int error;
   2974 	LazyBuf reBuf, replaceBuf;
   2975 	FStr re;
   2976 
   2977 	char delim = (*pp)[1];
   2978 	if (delim == '\0') {
   2979 		Error("Missing delimiter for :C modifier");
   2980 		(*pp)++;
   2981 		return AMR_CLEANUP;
   2982 	}
   2983 
   2984 	*pp += 2;
   2985 
   2986 	if (!ParseModifierPart(pp, delim, ch->expr->emode, ch, &reBuf))
   2987 		return AMR_CLEANUP;
   2988 	re = LazyBuf_DoneGet(&reBuf);
   2989 
   2990 	if (!ParseModifierPart(pp, delim, ch->expr->emode, ch, &replaceBuf)) {
   2991 		FStr_Done(&re);
   2992 		return AMR_CLEANUP;
   2993 	}
   2994 	args.replace = LazyBuf_Get(&replaceBuf);
   2995 
   2996 	args.pflags = PatternFlags_None();
   2997 	args.matched = false;
   2998 	oneBigWord = ch->oneBigWord;
   2999 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   3000 
   3001 	if (!ModChain_ShouldEval(ch))
   3002 		goto done;
   3003 
   3004 	error = regcomp(&args.re, re.str, REG_EXTENDED);
   3005 	if (error != 0) {
   3006 		RegexError(error, &args.re, "Regex compilation error");
   3007 		LazyBuf_Done(&replaceBuf);
   3008 		FStr_Done(&re);
   3009 		return AMR_CLEANUP;
   3010 	}
   3011 
   3012 	args.nsub = args.re.re_nsub + 1;
   3013 	if (args.nsub > 10)
   3014 		args.nsub = 10;
   3015 
   3016 	ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
   3017 
   3018 	regfree(&args.re);
   3019 done:
   3020 	LazyBuf_Done(&replaceBuf);
   3021 	FStr_Done(&re);
   3022 	return AMR_OK;
   3023 }
   3024 
   3025 /* :Q, :q */
   3026 static ApplyModifierResult
   3027 ApplyModifier_Quote(const char **pp, ModChain *ch)
   3028 {
   3029 	LazyBuf buf;
   3030 	bool quoteDollar;
   3031 
   3032 	quoteDollar = **pp == 'q';
   3033 	if (!IsDelimiter((*pp)[1], ch))
   3034 		return AMR_UNKNOWN;
   3035 	(*pp)++;
   3036 
   3037 	if (!ModChain_ShouldEval(ch))
   3038 		return AMR_OK;
   3039 
   3040 	QuoteShell(Expr_Str(ch->expr), quoteDollar, &buf);
   3041 	if (buf.data != NULL)
   3042 		Expr_SetValue(ch->expr, LazyBuf_DoneGet(&buf));
   3043 	else
   3044 		LazyBuf_Done(&buf);
   3045 
   3046 	return AMR_OK;
   3047 }
   3048 
   3049 /*ARGSUSED*/
   3050 static void
   3051 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3052 {
   3053 	SepBuf_AddSubstring(buf, word);
   3054 }
   3055 
   3056 /* :ts<separator> */
   3057 static ApplyModifierResult
   3058 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3059 {
   3060 	const char *sep = *pp + 2;
   3061 
   3062 	/*
   3063 	 * Even in parse-only mode, apply the side effects, since the side
   3064 	 * effects are neither observable nor is there a performance penalty.
   3065 	 * Checking for wantRes for every single piece of code in here
   3066 	 * would make the code in this function too hard to read.
   3067 	 */
   3068 
   3069 	/* ":ts<any><endc>" or ":ts<any>:" */
   3070 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3071 		*pp = sep + 1;
   3072 		ch->sep = sep[0];
   3073 		goto ok;
   3074 	}
   3075 
   3076 	/* ":ts<endc>" or ":ts:" */
   3077 	if (IsDelimiter(sep[0], ch)) {
   3078 		*pp = sep;
   3079 		ch->sep = '\0';	/* no separator */
   3080 		goto ok;
   3081 	}
   3082 
   3083 	/* ":ts<unrecognized><unrecognized>". */
   3084 	if (sep[0] != '\\') {
   3085 		(*pp)++;	/* just for backwards compatibility */
   3086 		return AMR_BAD;
   3087 	}
   3088 
   3089 	/* ":ts\n" */
   3090 	if (sep[1] == 'n') {
   3091 		*pp = sep + 2;
   3092 		ch->sep = '\n';
   3093 		goto ok;
   3094 	}
   3095 
   3096 	/* ":ts\t" */
   3097 	if (sep[1] == 't') {
   3098 		*pp = sep + 2;
   3099 		ch->sep = '\t';
   3100 		goto ok;
   3101 	}
   3102 
   3103 	/* ":ts\x40" or ":ts\100" */
   3104 	{
   3105 		const char *p = sep + 1;
   3106 		int base = 8;	/* assume octal */
   3107 
   3108 		if (sep[1] == 'x') {
   3109 			base = 16;
   3110 			p++;
   3111 		} else if (!ch_isdigit(sep[1])) {
   3112 			(*pp)++;	/* just for backwards compatibility */
   3113 			return AMR_BAD;	/* ":ts<backslash><unrecognized>". */
   3114 		}
   3115 
   3116 		if (!TryParseChar(&p, base, &ch->sep)) {
   3117 			Parse_Error(PARSE_FATAL,
   3118 			    "Invalid character number at \"%s\"", p);
   3119 			return AMR_CLEANUP;
   3120 		}
   3121 		if (!IsDelimiter(*p, ch)) {
   3122 			(*pp)++;	/* just for backwards compatibility */
   3123 			return AMR_BAD;
   3124 		}
   3125 
   3126 		*pp = p;
   3127 	}
   3128 
   3129 ok:
   3130 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3131 	return AMR_OK;
   3132 }
   3133 
   3134 static char *
   3135 str_toupper(const char *str)
   3136 {
   3137 	size_t i, n = strlen(str) + 1;
   3138 	char *res = bmake_malloc(n);
   3139 	for (i = 0; i < n; i++)
   3140 		res[i] = ch_toupper(str[i]);
   3141 	return res;
   3142 }
   3143 
   3144 static char *
   3145 str_tolower(const char *str)
   3146 {
   3147 	size_t i, n = strlen(str) + 1;
   3148 	char *res = bmake_malloc(n);
   3149 	for (i = 0; i < n; i++)
   3150 		res[i] = ch_tolower(str[i]);
   3151 	return res;
   3152 }
   3153 
   3154 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3155 static ApplyModifierResult
   3156 ApplyModifier_To(const char **pp, ModChain *ch)
   3157 {
   3158 	Expr *expr = ch->expr;
   3159 	const char *mod = *pp;
   3160 	assert(mod[0] == 't');
   3161 
   3162 	if (IsDelimiter(mod[1], ch)) {
   3163 		*pp = mod + 1;
   3164 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3165 	}
   3166 
   3167 	if (mod[1] == 's')
   3168 		return ApplyModifier_ToSep(pp, ch);
   3169 
   3170 	if (!IsDelimiter(mod[2], ch)) {			/* :t<any><any> */
   3171 		*pp = mod + 1;
   3172 		return AMR_BAD;
   3173 	}
   3174 
   3175 	if (mod[1] == 'A') {				/* :tA */
   3176 		*pp = mod + 2;
   3177 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3178 		return AMR_OK;
   3179 	}
   3180 
   3181 	if (mod[1] == 'u') {				/* :tu */
   3182 		*pp = mod + 2;
   3183 		if (Expr_ShouldEval(expr))
   3184 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3185 		return AMR_OK;
   3186 	}
   3187 
   3188 	if (mod[1] == 'l') {				/* :tl */
   3189 		*pp = mod + 2;
   3190 		if (Expr_ShouldEval(expr))
   3191 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3192 		return AMR_OK;
   3193 	}
   3194 
   3195 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3196 		*pp = mod + 2;
   3197 		ch->oneBigWord = mod[1] == 'W';
   3198 		return AMR_OK;
   3199 	}
   3200 
   3201 	/* Found ":t<unrecognized>:" or ":t<unrecognized><endc>". */
   3202 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3203 	return AMR_BAD;
   3204 }
   3205 
   3206 /* :[#], :[1], :[-1..1], etc. */
   3207 static ApplyModifierResult
   3208 ApplyModifier_Words(const char **pp, ModChain *ch)
   3209 {
   3210 	Expr *expr = ch->expr;
   3211 	int first, last;
   3212 	const char *p;
   3213 	LazyBuf argBuf;
   3214 	FStr arg;
   3215 
   3216 	(*pp)++;		/* skip the '[' */
   3217 	if (!ParseModifierPart(pp, ']', expr->emode, ch, &argBuf))
   3218 		return AMR_CLEANUP;
   3219 	arg = LazyBuf_DoneGet(&argBuf);
   3220 	p = arg.str;
   3221 
   3222 	if (!IsDelimiter(**pp, ch))
   3223 		goto bad_modifier;		/* Found junk after ']' */
   3224 
   3225 	if (!ModChain_ShouldEval(ch))
   3226 		goto ok;
   3227 
   3228 	if (p[0] == '\0')
   3229 		goto bad_modifier;		/* Found ":[]". */
   3230 
   3231 	if (strcmp(p, "#") == 0) {		/* Found ":[#]" */
   3232 		if (ch->oneBigWord)
   3233 			Expr_SetValueRefer(expr, "1");
   3234 		else {
   3235 			Buffer buf;
   3236 
   3237 			SubstringWords words = Expr_Words(expr);
   3238 			size_t ac = words.len;
   3239 			SubstringWords_Free(words);
   3240 
   3241 			Buf_Init(&buf);
   3242 			Buf_AddInt(&buf, (int)ac);
   3243 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3244 		}
   3245 		goto ok;
   3246 	}
   3247 
   3248 	if (strcmp(p, "*") == 0) {		/* ":[*]" */
   3249 		ch->oneBigWord = true;
   3250 		goto ok;
   3251 	}
   3252 
   3253 	if (strcmp(p, "@") == 0) {		/* ":[@]" */
   3254 		ch->oneBigWord = false;
   3255 		goto ok;
   3256 	}
   3257 
   3258 	/* Expect ":[N]" or ":[start..end]" */
   3259 	if (!TryParseIntBase0(&p, &first))
   3260 		goto bad_modifier;
   3261 
   3262 	if (p[0] == '\0')			/* ":[N]" */
   3263 		last = first;
   3264 	else if (strncmp(p, "..", 2) == 0) {
   3265 		p += 2;
   3266 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3267 			goto bad_modifier;
   3268 	} else
   3269 		goto bad_modifier;
   3270 
   3271 	if (first == 0 && last == 0) {		/* ":[0]" or ":[0..0]" */
   3272 		ch->oneBigWord = true;
   3273 		goto ok;
   3274 	}
   3275 
   3276 	if (first == 0 || last == 0)		/* ":[0..N]" or ":[N..0]" */
   3277 		goto bad_modifier;
   3278 
   3279 	Expr_SetValueOwn(expr,
   3280 	    VarSelectWords(Expr_Str(expr), first, last,
   3281 		ch->sep, ch->oneBigWord));
   3282 
   3283 ok:
   3284 	FStr_Done(&arg);
   3285 	return AMR_OK;
   3286 
   3287 bad_modifier:
   3288 	FStr_Done(&arg);
   3289 	return AMR_BAD;
   3290 }
   3291 
   3292 #if __STDC_VERSION__ >= 199901L
   3293 # define NUM_TYPE long long
   3294 # define PARSE_NUM_TYPE strtoll
   3295 #else
   3296 # define NUM_TYPE long
   3297 # define PARSE_NUM_TYPE strtol
   3298 #endif
   3299 
   3300 static NUM_TYPE
   3301 num_val(Substring s)
   3302 {
   3303 	NUM_TYPE val;
   3304 	char *ep;
   3305 
   3306 	val = PARSE_NUM_TYPE(s.start, &ep, 0);
   3307 	if (ep != s.start) {
   3308 		switch (*ep) {
   3309 		case 'K':
   3310 		case 'k':
   3311 			val <<= 10;
   3312 			break;
   3313 		case 'M':
   3314 		case 'm':
   3315 			val <<= 20;
   3316 			break;
   3317 		case 'G':
   3318 		case 'g':
   3319 			val <<= 30;
   3320 			break;
   3321 		}
   3322 	}
   3323 	return val;
   3324 }
   3325 
   3326 static int
   3327 SubNumAsc(const void *sa, const void *sb)
   3328 {
   3329 	NUM_TYPE a, b;
   3330 
   3331 	a = num_val(*((const Substring *)sa));
   3332 	b = num_val(*((const Substring *)sb));
   3333 	return a > b ? 1 : b > a ? -1 : 0;
   3334 }
   3335 
   3336 static int
   3337 SubNumDesc(const void *sa, const void *sb)
   3338 {
   3339 	return SubNumAsc(sb, sa);
   3340 }
   3341 
   3342 static int
   3343 Substring_Cmp(Substring a, Substring b)
   3344 {
   3345 	for (; a.start < a.end && b.start < b.end; a.start++, b.start++)
   3346 		if (a.start[0] != b.start[0])
   3347 			return (unsigned char)a.start[0]
   3348 			    - (unsigned char)b.start[0];
   3349 	return (int)((a.end - a.start) - (b.end - b.start));
   3350 }
   3351 
   3352 static int
   3353 SubStrAsc(const void *sa, const void *sb)
   3354 {
   3355 	return Substring_Cmp(*(const Substring *)sa, *(const Substring *)sb);
   3356 }
   3357 
   3358 static int
   3359 SubStrDesc(const void *sa, const void *sb)
   3360 {
   3361 	return SubStrAsc(sb, sa);
   3362 }
   3363 
   3364 static void
   3365 ShuffleSubstrings(Substring *strs, size_t n)
   3366 {
   3367 	size_t i;
   3368 
   3369 	for (i = n - 1; i > 0; i--) {
   3370 		size_t rndidx = (size_t)random() % (i + 1);
   3371 		Substring t = strs[i];
   3372 		strs[i] = strs[rndidx];
   3373 		strs[rndidx] = t;
   3374 	}
   3375 }
   3376 
   3377 /*
   3378  * :O		order ascending
   3379  * :Or		order descending
   3380  * :Ox		shuffle
   3381  * :On		numeric ascending
   3382  * :Onr, :Orn	numeric descending
   3383  */
   3384 static ApplyModifierResult
   3385 ApplyModifier_Order(const char **pp, ModChain *ch)
   3386 {
   3387 	const char *mod = *pp;
   3388 	SubstringWords words;
   3389 	int (*cmp)(const void *, const void *);
   3390 
   3391 	if (IsDelimiter(mod[1], ch)) {
   3392 		cmp = SubStrAsc;
   3393 		(*pp)++;
   3394 	} else if (IsDelimiter(mod[2], ch)) {
   3395 		if (mod[1] == 'n')
   3396 			cmp = SubNumAsc;
   3397 		else if (mod[1] == 'r')
   3398 			cmp = SubStrDesc;
   3399 		else if (mod[1] == 'x')
   3400 			cmp = NULL;
   3401 		else
   3402 			goto bad;
   3403 		*pp += 2;
   3404 	} else if (IsDelimiter(mod[3], ch)) {
   3405 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3406 		    (mod[1] == 'r' && mod[2] == 'n'))
   3407 			cmp = SubNumDesc;
   3408 		else
   3409 			goto bad;
   3410 		*pp += 3;
   3411 	} else
   3412 		goto bad;
   3413 
   3414 	if (!ModChain_ShouldEval(ch))
   3415 		return AMR_OK;
   3416 
   3417 	words = Expr_Words(ch->expr);
   3418 	if (cmp == NULL)
   3419 		ShuffleSubstrings(words.words, words.len);
   3420 	else {
   3421 		assert(words.words[0].end[0] == '\0');
   3422 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3423 	}
   3424 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3425 
   3426 	return AMR_OK;
   3427 
   3428 bad:
   3429 	(*pp)++;
   3430 	return AMR_BAD;
   3431 }
   3432 
   3433 /* :? then : else */
   3434 static ApplyModifierResult
   3435 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3436 {
   3437 	Expr *expr = ch->expr;
   3438 	LazyBuf thenBuf;
   3439 	LazyBuf elseBuf;
   3440 
   3441 	VarEvalMode then_emode = VARE_PARSE_ONLY;
   3442 	VarEvalMode else_emode = VARE_PARSE_ONLY;
   3443 
   3444 	CondResult cond_rc = CR_TRUE;	/* just not CR_ERROR */
   3445 	if (Expr_ShouldEval(expr)) {
   3446 		cond_rc = Cond_EvalCondition(expr->name);
   3447 		if (cond_rc == CR_TRUE)
   3448 			then_emode = expr->emode;
   3449 		if (cond_rc == CR_FALSE)
   3450 			else_emode = expr->emode;
   3451 	}
   3452 
   3453 	(*pp)++;		/* skip past the '?' */
   3454 	if (!ParseModifierPart(pp, ':', then_emode, ch, &thenBuf))
   3455 		return AMR_CLEANUP;
   3456 
   3457 	if (!ParseModifierPart(pp, ch->endc, else_emode, ch, &elseBuf)) {
   3458 		LazyBuf_Done(&thenBuf);
   3459 		return AMR_CLEANUP;
   3460 	}
   3461 
   3462 	(*pp)--;		/* Go back to the ch->endc. */
   3463 
   3464 	if (cond_rc == CR_ERROR) {
   3465 		Substring thenExpr = LazyBuf_Get(&thenBuf);
   3466 		Substring elseExpr = LazyBuf_Get(&elseBuf);
   3467 		Error("Bad conditional expression '%s' before '?%.*s:%.*s'",
   3468 		    expr->name,
   3469 		    (int)Substring_Length(thenExpr), thenExpr.start,
   3470 		    (int)Substring_Length(elseExpr), elseExpr.start);
   3471 		LazyBuf_Done(&thenBuf);
   3472 		LazyBuf_Done(&elseBuf);
   3473 		return AMR_CLEANUP;
   3474 	}
   3475 
   3476 	if (!Expr_ShouldEval(expr)) {
   3477 		LazyBuf_Done(&thenBuf);
   3478 		LazyBuf_Done(&elseBuf);
   3479 	} else if (cond_rc == CR_TRUE) {
   3480 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3481 		LazyBuf_Done(&elseBuf);
   3482 	} else {
   3483 		LazyBuf_Done(&thenBuf);
   3484 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3485 	}
   3486 	Expr_Define(expr);
   3487 	return AMR_OK;
   3488 }
   3489 
   3490 /*
   3491  * The ::= modifiers are special in that they do not read the variable value
   3492  * but instead assign to that variable.  They always expand to an empty
   3493  * string.
   3494  *
   3495  * Their main purpose is in supporting .for loops that generate shell commands
   3496  * since an ordinary variable assignment at that point would terminate the
   3497  * dependency group for these targets.  For example:
   3498  *
   3499  * list-targets: .USE
   3500  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3501  *	@${t::=$i}
   3502  *	@echo 'The target is ${t:T}.'
   3503  * .endfor
   3504  *
   3505  *	  ::=<str>	Assigns <str> as the new value of variable.
   3506  *	  ::?=<str>	Assigns <str> as value of variable if
   3507  *			it was not already set.
   3508  *	  ::+=<str>	Appends <str> to variable.
   3509  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3510  *			variable.
   3511  */
   3512 static ApplyModifierResult
   3513 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3514 {
   3515 	Expr *expr = ch->expr;
   3516 	GNode *scope;
   3517 	FStr val;
   3518 	LazyBuf buf;
   3519 
   3520 	const char *mod = *pp;
   3521 	const char *op = mod + 1;
   3522 
   3523 	if (op[0] == '=')
   3524 		goto found_op;
   3525 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3526 		goto found_op;
   3527 	return AMR_UNKNOWN;	/* "::<unrecognized>" */
   3528 
   3529 found_op:
   3530 	if (expr->name[0] == '\0') {
   3531 		*pp = mod + 1;
   3532 		return AMR_BAD;
   3533 	}
   3534 
   3535 	*pp = mod + (op[0] != '=' ? 3 : 2);
   3536 
   3537 	if (!ParseModifierPart(pp, ch->endc, expr->emode, ch, &buf))
   3538 		return AMR_CLEANUP;
   3539 	val = LazyBuf_DoneGet(&buf);
   3540 
   3541 	(*pp)--;		/* Go back to the ch->endc. */
   3542 
   3543 	if (!Expr_ShouldEval(expr))
   3544 		goto done;
   3545 
   3546 	scope = expr->scope;	/* scope where v belongs */
   3547 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL
   3548 	    && VarFind(expr->name, expr->scope, false) == NULL)
   3549 		scope = SCOPE_GLOBAL;
   3550 
   3551 	if (op[0] == '+')
   3552 		Var_Append(scope, expr->name, val.str);
   3553 	else if (op[0] == '!') {
   3554 		char *output, *error;
   3555 		output = Cmd_Exec(val.str, &error);
   3556 		if (error != NULL) {
   3557 			Error("%s", error);
   3558 			free(error);
   3559 		} else
   3560 			Var_Set(scope, expr->name, output);
   3561 		free(output);
   3562 	} else if (op[0] == '?' && expr->defined == DEF_REGULAR) {
   3563 		/* Do nothing. */
   3564 	} else
   3565 		Var_Set(scope, expr->name, val.str);
   3566 
   3567 	Expr_SetValueRefer(expr, "");
   3568 
   3569 done:
   3570 	FStr_Done(&val);
   3571 	return AMR_OK;
   3572 }
   3573 
   3574 /*
   3575  * :_=...
   3576  * remember current value
   3577  */
   3578 static ApplyModifierResult
   3579 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3580 {
   3581 	Expr *expr = ch->expr;
   3582 	const char *mod = *pp;
   3583 	FStr name;
   3584 
   3585 	if (!ModMatchEq(mod, "_", ch))
   3586 		return AMR_UNKNOWN;
   3587 
   3588 	name = FStr_InitRefer("_");
   3589 	if (mod[1] == '=') {
   3590 		/*
   3591 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3592 		 * behavior defined in ParseModifierPart.  This creates an
   3593 		 * unnecessary and undocumented inconsistency in make.
   3594 		 */
   3595 		const char *arg = mod + 2;
   3596 		size_t argLen = strcspn(arg, ":)}");
   3597 		*pp = arg + argLen;
   3598 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3599 	} else
   3600 		*pp = mod + 1;
   3601 
   3602 	if (Expr_ShouldEval(expr))
   3603 		Var_Set(SCOPE_GLOBAL, name.str, Expr_Str(expr));
   3604 	FStr_Done(&name);
   3605 
   3606 	return AMR_OK;
   3607 }
   3608 
   3609 /*
   3610  * Apply the given function to each word of the variable value,
   3611  * for a single-letter modifier such as :H, :T.
   3612  */
   3613 static ApplyModifierResult
   3614 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3615 		       ModifyWordProc modifyWord)
   3616 {
   3617 	if (!IsDelimiter((*pp)[1], ch))
   3618 		return AMR_UNKNOWN;
   3619 	(*pp)++;
   3620 
   3621 	ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3622 
   3623 	return AMR_OK;
   3624 }
   3625 
   3626 /* Remove adjacent duplicate words. */
   3627 static ApplyModifierResult
   3628 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3629 {
   3630 	SubstringWords words;
   3631 
   3632 	if (!IsDelimiter((*pp)[1], ch))
   3633 		return AMR_UNKNOWN;
   3634 	(*pp)++;
   3635 
   3636 	if (!ModChain_ShouldEval(ch))
   3637 		return AMR_OK;
   3638 
   3639 	words = Expr_Words(ch->expr);
   3640 
   3641 	if (words.len > 1) {
   3642 		size_t di, si;
   3643 
   3644 		di = 0;
   3645 		for (si = 1; si < words.len; si++) {
   3646 			if (!Substring_Eq(words.words[si], words.words[di])) {
   3647 				di++;
   3648 				if (di != si)
   3649 					words.words[di] = words.words[si];
   3650 			}
   3651 		}
   3652 		words.len = di + 1;
   3653 	}
   3654 
   3655 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3656 
   3657 	return AMR_OK;
   3658 }
   3659 
   3660 /* Test whether the modifier has the form '<lhs>=<rhs>'. */
   3661 static bool
   3662 IsSysVModifier(const char *p, char startc, char endc)
   3663 {
   3664 	bool eqFound = false;
   3665 
   3666 	int depth = 1;
   3667 	while (*p != '\0' && depth > 0) {
   3668 		if (*p == '=')	/* XXX: should also test depth == 1 */
   3669 			eqFound = true;
   3670 		else if (*p == endc)
   3671 			depth--;
   3672 		else if (*p == startc)
   3673 			depth++;
   3674 		if (depth > 0)
   3675 			p++;
   3676 	}
   3677 	return *p == endc && eqFound;
   3678 }
   3679 
   3680 /* :from=to */
   3681 static ApplyModifierResult
   3682 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3683 {
   3684 	Expr *expr = ch->expr;
   3685 	LazyBuf lhsBuf, rhsBuf;
   3686 	FStr rhs;
   3687 	struct ModifyWord_SysVSubstArgs args;
   3688 	Substring lhs;
   3689 	const char *lhsSuffix;
   3690 
   3691 	const char *mod = *pp;
   3692 
   3693 	if (!IsSysVModifier(mod, ch->startc, ch->endc))
   3694 		return AMR_UNKNOWN;
   3695 
   3696 	if (!ParseModifierPart(pp, '=', expr->emode, ch, &lhsBuf))
   3697 		return AMR_CLEANUP;
   3698 
   3699 	/*
   3700 	 * The SysV modifier lasts until the end of the expression.
   3701 	 */
   3702 	if (!ParseModifierPart(pp, ch->endc, expr->emode, ch, &rhsBuf)) {
   3703 		LazyBuf_Done(&lhsBuf);
   3704 		return AMR_CLEANUP;
   3705 	}
   3706 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3707 
   3708 	(*pp)--;		/* Go back to the ch->endc. */
   3709 
   3710 	/* Do not turn an empty expression into non-empty. */
   3711 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3712 		goto done;
   3713 
   3714 	lhs = LazyBuf_Get(&lhsBuf);
   3715 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3716 
   3717 	args.scope = expr->scope;
   3718 	args.lhsPrefix = Substring_Init(lhs.start,
   3719 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3720 	args.lhsPercent = lhsSuffix != lhs.start;
   3721 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3722 	args.rhs = rhs.str;
   3723 
   3724 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3725 
   3726 done:
   3727 	LazyBuf_Done(&lhsBuf);
   3728 	FStr_Done(&rhs);
   3729 	return AMR_OK;
   3730 }
   3731 
   3732 /* :sh */
   3733 static ApplyModifierResult
   3734 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3735 {
   3736 	Expr *expr = ch->expr;
   3737 	const char *p = *pp;
   3738 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3739 		return AMR_UNKNOWN;
   3740 	*pp = p + 2;
   3741 
   3742 	if (Expr_ShouldEval(expr)) {
   3743 		char *output, *error;
   3744 		output = Cmd_Exec(Expr_Str(expr), &error);
   3745 		if (error != NULL) {
   3746 			Error("%s", error);
   3747 			free(error);
   3748 		}
   3749 		Expr_SetValueOwn(expr, output);
   3750 	}
   3751 
   3752 	return AMR_OK;
   3753 }
   3754 
   3755 /*
   3756  * In cases where the evaluation mode and the definedness are the "standard"
   3757  * ones, don't log them, to keep the logs readable.
   3758  */
   3759 static bool
   3760 ShouldLogInSimpleFormat(const Expr *expr)
   3761 {
   3762 	return (expr->emode == VARE_WANTRES ||
   3763 		expr->emode == VARE_UNDEFERR) &&
   3764 	       expr->defined == DEF_REGULAR;
   3765 }
   3766 
   3767 static void
   3768 LogBeforeApply(const ModChain *ch, const char *mod)
   3769 {
   3770 	const Expr *expr = ch->expr;
   3771 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3772 
   3773 	/*
   3774 	 * At this point, only the first character of the modifier can
   3775 	 * be used since the end of the modifier is not yet known.
   3776 	 */
   3777 
   3778 	if (!Expr_ShouldEval(expr)) {
   3779 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3780 		    expr->name, mod[0], is_single_char ? "" : "...");
   3781 		return;
   3782 	}
   3783 
   3784 	if (ShouldLogInSimpleFormat(expr)) {
   3785 		debug_printf(
   3786 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3787 		    expr->name, mod[0], is_single_char ? "" : "...",
   3788 		    Expr_Str(expr));
   3789 		return;
   3790 	}
   3791 
   3792 	debug_printf(
   3793 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3794 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3795 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3796 }
   3797 
   3798 static void
   3799 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3800 {
   3801 	const Expr *expr = ch->expr;
   3802 	const char *value = Expr_Str(expr);
   3803 	const char *quot = value == var_Error ? "" : "\"";
   3804 
   3805 	if (ShouldLogInSimpleFormat(expr)) {
   3806 		debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
   3807 		    expr->name, (int)(p - mod), mod,
   3808 		    quot, value == var_Error ? "error" : value, quot);
   3809 		return;
   3810 	}
   3811 
   3812 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
   3813 	    expr->name, (int)(p - mod), mod,
   3814 	    quot, value == var_Error ? "error" : value, quot,
   3815 	    VarEvalMode_Name[expr->emode],
   3816 	    ExprDefined_Name[expr->defined]);
   3817 }
   3818 
   3819 static ApplyModifierResult
   3820 ApplyModifier(const char **pp, ModChain *ch)
   3821 {
   3822 	switch (**pp) {
   3823 	case '!':
   3824 		return ApplyModifier_ShellCommand(pp, ch);
   3825 	case ':':
   3826 		return ApplyModifier_Assign(pp, ch);
   3827 	case '?':
   3828 		return ApplyModifier_IfElse(pp, ch);
   3829 	case '@':
   3830 		return ApplyModifier_Loop(pp, ch);
   3831 	case '[':
   3832 		return ApplyModifier_Words(pp, ch);
   3833 	case '_':
   3834 		return ApplyModifier_Remember(pp, ch);
   3835 	case 'C':
   3836 		return ApplyModifier_Regex(pp, ch);
   3837 	case 'D':
   3838 	case 'U':
   3839 		return ApplyModifier_Defined(pp, ch);
   3840 	case 'E':
   3841 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3842 	case 'g':
   3843 	case 'l':
   3844 		return ApplyModifier_Time(pp, ch);
   3845 	case 'H':
   3846 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3847 	case 'h':
   3848 		return ApplyModifier_Hash(pp, ch);
   3849 	case 'L':
   3850 		return ApplyModifier_Literal(pp, ch);
   3851 	case 'M':
   3852 	case 'N':
   3853 		return ApplyModifier_Match(pp, ch);
   3854 	case 'm':
   3855 		return ApplyModifier_Mtime(pp, ch);
   3856 	case 'O':
   3857 		return ApplyModifier_Order(pp, ch);
   3858 	case 'P':
   3859 		return ApplyModifier_Path(pp, ch);
   3860 	case 'Q':
   3861 	case 'q':
   3862 		return ApplyModifier_Quote(pp, ch);
   3863 	case 'R':
   3864 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3865 	case 'r':
   3866 		return ApplyModifier_Range(pp, ch);
   3867 	case 'S':
   3868 		return ApplyModifier_Subst(pp, ch);
   3869 	case 's':
   3870 		return ApplyModifier_SunShell(pp, ch);
   3871 	case 'T':
   3872 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3873 	case 't':
   3874 		return ApplyModifier_To(pp, ch);
   3875 	case 'u':
   3876 		return ApplyModifier_Unique(pp, ch);
   3877 	default:
   3878 		return AMR_UNKNOWN;
   3879 	}
   3880 }
   3881 
   3882 static void ApplyModifiers(Expr *, const char **, char, char);
   3883 
   3884 typedef enum ApplyModifiersIndirectResult {
   3885 	/* The indirect modifiers have been applied successfully. */
   3886 	AMIR_CONTINUE,
   3887 	/* Fall back to the SysV modifier. */
   3888 	AMIR_SYSV,
   3889 	/* Error out. */
   3890 	AMIR_OUT
   3891 } ApplyModifiersIndirectResult;
   3892 
   3893 /*
   3894  * While expanding an expression, expand and apply indirect modifiers,
   3895  * such as in ${VAR:${M_indirect}}.
   3896  *
   3897  * All indirect modifiers of a group must come from a single
   3898  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3899  *
   3900  * Multiple groups of indirect modifiers can be chained by separating them
   3901  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3902  *
   3903  * If the expression is not followed by ch->endc or ':', fall
   3904  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3905  */
   3906 static ApplyModifiersIndirectResult
   3907 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   3908 {
   3909 	Expr *expr = ch->expr;
   3910 	const char *p = *pp;
   3911 	FStr mods = Var_Parse(&p, expr->scope, expr->emode);
   3912 	/* TODO: handle errors */
   3913 
   3914 	if (mods.str[0] != '\0' && !IsDelimiter(*p, ch)) {
   3915 		FStr_Done(&mods);
   3916 		return AMIR_SYSV;
   3917 	}
   3918 
   3919 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3920 	    mods.str, (int)(p - *pp), *pp);
   3921 
   3922 	if (ModChain_ShouldEval(ch) && mods.str[0] != '\0') {
   3923 		const char *modsp = mods.str;
   3924 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3925 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   3926 			FStr_Done(&mods);
   3927 			*pp = p;
   3928 			return AMIR_OUT;	/* error already reported */
   3929 		}
   3930 	}
   3931 	FStr_Done(&mods);
   3932 
   3933 	if (*p == ':')
   3934 		p++;
   3935 	else if (*p == '\0' && ch->endc != '\0') {
   3936 		Error("Unclosed expression after indirect modifier, "
   3937 		      "expecting '%c' for variable \"%s\"",
   3938 		    ch->endc, expr->name);
   3939 		*pp = p;
   3940 		return AMIR_OUT;
   3941 	}
   3942 
   3943 	*pp = p;
   3944 	return AMIR_CONTINUE;
   3945 }
   3946 
   3947 static ApplyModifierResult
   3948 ApplySingleModifier(const char **pp, ModChain *ch)
   3949 {
   3950 	ApplyModifierResult res;
   3951 	const char *mod = *pp;
   3952 	const char *p = *pp;
   3953 
   3954 	if (DEBUG(VAR))
   3955 		LogBeforeApply(ch, mod);
   3956 
   3957 	res = ApplyModifier(&p, ch);
   3958 
   3959 	if (res == AMR_UNKNOWN) {
   3960 		assert(p == mod);
   3961 		res = ApplyModifier_SysV(&p, ch);
   3962 	}
   3963 
   3964 	if (res == AMR_UNKNOWN) {
   3965 		/*
   3966 		 * Guess the end of the current modifier.
   3967 		 * XXX: Skipping the rest of the modifier hides
   3968 		 * errors and leads to wrong results.
   3969 		 * Parsing should rather stop here.
   3970 		 */
   3971 		for (p++; !IsDelimiter(*p, ch); p++)
   3972 			continue;
   3973 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   3974 		    (int)(p - mod), mod);
   3975 		Expr_SetValueRefer(ch->expr, var_Error);
   3976 	}
   3977 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3978 		*pp = p;
   3979 		return res;
   3980 	}
   3981 
   3982 	if (DEBUG(VAR))
   3983 		LogAfterApply(ch, p, mod);
   3984 
   3985 	if (*p == '\0' && ch->endc != '\0') {
   3986 		Error(
   3987 		    "Unclosed expression, expecting '%c' for "
   3988 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   3989 		    ch->endc,
   3990 		    (int)(p - mod), mod,
   3991 		    ch->expr->name, Expr_Str(ch->expr));
   3992 	} else if (*p == ':') {
   3993 		p++;
   3994 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   3995 		Parse_Error(PARSE_FATAL,
   3996 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3997 		    (int)(p - mod), mod);
   3998 		/*
   3999 		 * TODO: propagate parse error to the enclosing
   4000 		 * expression
   4001 		 */
   4002 	}
   4003 	*pp = p;
   4004 	return AMR_OK;
   4005 }
   4006 
   4007 #if __STDC_VERSION__ >= 199901L
   4008 #define ModChain_Init(expr, startc, endc, sep, oneBigWord) \
   4009 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4010 #else
   4011 MAKE_INLINE ModChain
   4012 ModChain_Init(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4013 {
   4014 	ModChain ch;
   4015 	ch.expr = expr;
   4016 	ch.startc = startc;
   4017 	ch.endc = endc;
   4018 	ch.sep = sep;
   4019 	ch.oneBigWord = oneBigWord;
   4020 	return ch;
   4021 }
   4022 #endif
   4023 
   4024 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4025 static void
   4026 ApplyModifiers(
   4027     Expr *expr,
   4028     const char **pp,	/* the parsing position, updated upon return */
   4029     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4030     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4031 )
   4032 {
   4033 	ModChain ch = ModChain_Init(expr, startc, endc, ' ', false);
   4034 	const char *p;
   4035 	const char *mod;
   4036 
   4037 	assert(startc == '(' || startc == '{' || startc == '\0');
   4038 	assert(endc == ')' || endc == '}' || endc == '\0');
   4039 	assert(Expr_Str(expr) != NULL);
   4040 
   4041 	p = *pp;
   4042 
   4043 	if (*p == '\0' && endc != '\0') {
   4044 		Error(
   4045 		    "Unclosed expression, expecting '%c' for \"%s\"",
   4046 		    ch.endc, expr->name);
   4047 		goto cleanup;
   4048 	}
   4049 
   4050 	while (*p != '\0' && *p != endc) {
   4051 		ApplyModifierResult res;
   4052 
   4053 		if (*p == '$') {
   4054 			/*
   4055 			 * TODO: Only evaluate the expression once, no matter
   4056 			 * whether it's an indirect modifier or the initial
   4057 			 * part of a SysV modifier.
   4058 			 */
   4059 			ApplyModifiersIndirectResult amir =
   4060 			    ApplyModifiersIndirect(&ch, &p);
   4061 			if (amir == AMIR_CONTINUE)
   4062 				continue;
   4063 			if (amir == AMIR_OUT)
   4064 				break;
   4065 		}
   4066 
   4067 		mod = p;
   4068 
   4069 		res = ApplySingleModifier(&p, &ch);
   4070 		if (res == AMR_CLEANUP)
   4071 			goto cleanup;
   4072 		if (res == AMR_BAD)
   4073 			goto bad_modifier;
   4074 	}
   4075 
   4076 	*pp = p;
   4077 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4078 	return;
   4079 
   4080 bad_modifier:
   4081 	/* Take a guess at where the modifier ends. */
   4082 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   4083 	    (int)strcspn(mod, ":)}"), mod, expr->name);
   4084 
   4085 cleanup:
   4086 	/*
   4087 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4088 	 *
   4089 	 * In the unit tests, this generates a few shell commands with
   4090 	 * unbalanced quotes.  Instead of producing these incomplete strings,
   4091 	 * commands with evaluation errors should not be run at all.
   4092 	 *
   4093 	 * To make that happen, Var_Subst must report the actual errors
   4094 	 * instead of returning the resulting string unconditionally.
   4095 	 */
   4096 	*pp = p;
   4097 	Expr_SetValueRefer(expr, var_Error);
   4098 }
   4099 
   4100 /*
   4101  * Only 4 of the 7 built-in local variables are treated specially as they are
   4102  * the only ones that will be set when dynamic sources are expanded.
   4103  */
   4104 static bool
   4105 VarnameIsDynamic(Substring varname)
   4106 {
   4107 	const char *name;
   4108 	size_t len;
   4109 
   4110 	name = varname.start;
   4111 	len = Substring_Length(varname);
   4112 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4113 		switch (name[0]) {
   4114 		case '@':
   4115 		case '%':
   4116 		case '*':
   4117 		case '!':
   4118 			return true;
   4119 		}
   4120 		return false;
   4121 	}
   4122 
   4123 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4124 		return Substring_Equals(varname, ".TARGET") ||
   4125 		       Substring_Equals(varname, ".ARCHIVE") ||
   4126 		       Substring_Equals(varname, ".PREFIX") ||
   4127 		       Substring_Equals(varname, ".MEMBER");
   4128 	}
   4129 
   4130 	return false;
   4131 }
   4132 
   4133 static const char *
   4134 UndefinedShortVarValue(char varname, const GNode *scope)
   4135 {
   4136 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4137 		/*
   4138 		 * If substituting a local variable in a non-local scope,
   4139 		 * assume it's for dynamic source stuff. We have to handle
   4140 		 * this specially and return the longhand for the variable
   4141 		 * with the dollar sign escaped so it makes it back to the
   4142 		 * caller. Only four of the local variables are treated
   4143 		 * specially as they are the only four that will be set
   4144 		 * when dynamic sources are expanded.
   4145 		 */
   4146 		switch (varname) {
   4147 		case '@':
   4148 			return "$(.TARGET)";
   4149 		case '%':
   4150 			return "$(.MEMBER)";
   4151 		case '*':
   4152 			return "$(.PREFIX)";
   4153 		case '!':
   4154 			return "$(.ARCHIVE)";
   4155 		}
   4156 	}
   4157 	return NULL;
   4158 }
   4159 
   4160 /*
   4161  * Parse a variable name, until the end character or a colon, whichever
   4162  * comes first.
   4163  */
   4164 static void
   4165 ParseVarname(const char **pp, char startc, char endc,
   4166 	     GNode *scope, VarEvalMode emode,
   4167 	     LazyBuf *buf)
   4168 {
   4169 	const char *p = *pp;
   4170 	int depth = 0;
   4171 
   4172 	LazyBuf_Init(buf, p);
   4173 
   4174 	while (*p != '\0') {
   4175 		if ((*p == endc || *p == ':') && depth == 0)
   4176 			break;
   4177 		if (*p == startc)
   4178 			depth++;
   4179 		if (*p == endc)
   4180 			depth--;
   4181 
   4182 		if (*p == '$') {
   4183 			FStr nested_val = Var_Parse(&p, scope, emode);
   4184 			/* TODO: handle errors */
   4185 			LazyBuf_AddStr(buf, nested_val.str);
   4186 			FStr_Done(&nested_val);
   4187 		} else {
   4188 			LazyBuf_Add(buf, *p);
   4189 			p++;
   4190 		}
   4191 	}
   4192 	*pp = p;
   4193 }
   4194 
   4195 static bool
   4196 IsShortVarnameValid(char varname, const char *start)
   4197 {
   4198 	if (varname != '$' && varname != ':' && varname != '}' &&
   4199 	    varname != ')' && varname != '\0')
   4200 		return true;
   4201 
   4202 	if (!opts.strict)
   4203 		return false;	/* XXX: Missing error message */
   4204 
   4205 	if (varname == '$' && save_dollars)
   4206 		Parse_Error(PARSE_FATAL,
   4207 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4208 	else if (varname == '\0')
   4209 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4210 	else if (save_dollars)
   4211 		Parse_Error(PARSE_FATAL,
   4212 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4213 
   4214 	return false;
   4215 }
   4216 
   4217 /*
   4218  * Parse a single-character variable name such as in $V or $@.
   4219  * Return whether to continue parsing.
   4220  */
   4221 static bool
   4222 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4223 		  VarEvalMode emode,
   4224 		  const char **out_false_val,
   4225 		  Var **out_true_var)
   4226 {
   4227 	char name[2];
   4228 	Var *v;
   4229 	const char *val;
   4230 
   4231 	if (!IsShortVarnameValid(varname, *pp)) {
   4232 		(*pp)++;	/* only skip the '$' */
   4233 		*out_false_val = var_Error;
   4234 		return false;
   4235 	}
   4236 
   4237 	name[0] = varname;
   4238 	name[1] = '\0';
   4239 	v = VarFind(name, scope, true);
   4240 	if (v != NULL) {
   4241 		/* No need to advance *pp, the calling code handles this. */
   4242 		*out_true_var = v;
   4243 		return true;
   4244 	}
   4245 
   4246 	*pp += 2;
   4247 
   4248 	val = UndefinedShortVarValue(varname, scope);
   4249 	if (val == NULL)
   4250 		val = emode == VARE_UNDEFERR ? var_Error : varUndefined;
   4251 
   4252 	if (opts.strict && val == var_Error) {
   4253 		Parse_Error(PARSE_FATAL,
   4254 		    "Variable \"%s\" is undefined", name);
   4255 	}
   4256 
   4257 	*out_false_val = val;
   4258 	return false;
   4259 }
   4260 
   4261 /* Find variables like @F or <D. */
   4262 static Var *
   4263 FindLocalLegacyVar(Substring varname, GNode *scope,
   4264 		   const char **out_extraModifiers)
   4265 {
   4266 	Var *v;
   4267 
   4268 	/* Only resolve these variables if scope is a "real" target. */
   4269 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4270 		return NULL;
   4271 
   4272 	if (Substring_Length(varname) != 2)
   4273 		return NULL;
   4274 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4275 		return NULL;
   4276 	if (strchr("@%?*!<>", varname.start[0]) == NULL)
   4277 		return NULL;
   4278 
   4279 	v = VarFindSubstring(Substring_Init(varname.start, varname.start + 1),
   4280 	    scope, false);
   4281 	if (v == NULL)
   4282 		return NULL;
   4283 
   4284 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4285 	return v;
   4286 }
   4287 
   4288 static FStr
   4289 EvalUndefined(bool dynamic, const char *start, const char *p,
   4290 	      Substring varname, VarEvalMode emode)
   4291 {
   4292 	if (dynamic)
   4293 		return FStr_InitOwn(bmake_strsedup(start, p));
   4294 
   4295 	if (emode == VARE_UNDEFERR && opts.strict) {
   4296 		Parse_Error(PARSE_FATAL,
   4297 		    "Variable \"%.*s\" is undefined",
   4298 		    (int)Substring_Length(varname), varname.start);
   4299 		return FStr_InitRefer(var_Error);
   4300 	}
   4301 
   4302 	return FStr_InitRefer(
   4303 	    emode == VARE_UNDEFERR ? var_Error : varUndefined);
   4304 }
   4305 
   4306 /*
   4307  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4308  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4309  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4310  * Return whether to continue parsing.
   4311  */
   4312 static bool
   4313 ParseVarnameLong(
   4314 	const char **pp,
   4315 	char startc,
   4316 	GNode *scope,
   4317 	VarEvalMode emode,
   4318 
   4319 	const char **out_false_pp,
   4320 	FStr *out_false_val,
   4321 
   4322 	char *out_true_endc,
   4323 	Var **out_true_v,
   4324 	bool *out_true_haveModifier,
   4325 	const char **out_true_extraModifiers,
   4326 	bool *out_true_dynamic,
   4327 	ExprDefined *out_true_exprDefined
   4328 )
   4329 {
   4330 	LazyBuf varname;
   4331 	Substring name;
   4332 	Var *v;
   4333 	bool haveModifier;
   4334 	bool dynamic = false;
   4335 
   4336 	const char *p = *pp;
   4337 	const char *start = p;
   4338 	char endc = startc == '(' ? ')' : '}';
   4339 
   4340 	p += 2;			/* skip "${" or "$(" or "y(" */
   4341 	ParseVarname(&p, startc, endc, scope, emode, &varname);
   4342 	name = LazyBuf_Get(&varname);
   4343 
   4344 	if (*p == ':')
   4345 		haveModifier = true;
   4346 	else if (*p == endc)
   4347 		haveModifier = false;
   4348 	else {
   4349 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4350 		    (int)Substring_Length(name), name.start);
   4351 		LazyBuf_Done(&varname);
   4352 		*out_false_pp = p;
   4353 		*out_false_val = FStr_InitRefer(var_Error);
   4354 		return false;
   4355 	}
   4356 
   4357 	v = VarFindSubstring(name, scope, true);
   4358 
   4359 	/*
   4360 	 * At this point, p points just after the variable name, either at
   4361 	 * ':' or at endc.
   4362 	 */
   4363 
   4364 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4365 		char *suffixes = Suff_NamesStr();
   4366 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4367 		    true, false, true);
   4368 		free(suffixes);
   4369 	} else if (v == NULL)
   4370 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4371 
   4372 	if (v == NULL) {
   4373 		/*
   4374 		 * Defer expansion of dynamic variables if they appear in
   4375 		 * non-local scope since they are not defined there.
   4376 		 */
   4377 		dynamic = VarnameIsDynamic(name) &&
   4378 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4379 
   4380 		if (!haveModifier) {
   4381 			p++;	/* skip endc */
   4382 			*out_false_pp = p;
   4383 			*out_false_val = EvalUndefined(dynamic, start, p,
   4384 			    name, emode);
   4385 			LazyBuf_Done(&varname);
   4386 			return false;
   4387 		}
   4388 
   4389 		/*
   4390 		 * The expression is based on an undefined variable.
   4391 		 * Nevertheless it needs a Var, for modifiers that access the
   4392 		 * variable name, such as :L or :?.
   4393 		 *
   4394 		 * Most modifiers leave this expression in the "undefined"
   4395 		 * state (DEF_UNDEF), only a few modifiers like :D, :U, :L,
   4396 		 * :P turn this undefined expression into a defined
   4397 		 * expression (DEF_DEFINED).
   4398 		 *
   4399 		 * In the end, after applying all modifiers, if the expression
   4400 		 * is still undefined, Var_Parse will return an empty string
   4401 		 * instead of the actually computed value.
   4402 		 */
   4403 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4404 		    true, false, false);
   4405 		*out_true_exprDefined = DEF_UNDEF;
   4406 	} else
   4407 		LazyBuf_Done(&varname);
   4408 
   4409 	*pp = p;
   4410 	*out_true_endc = endc;
   4411 	*out_true_v = v;
   4412 	*out_true_haveModifier = haveModifier;
   4413 	*out_true_dynamic = dynamic;
   4414 	return true;
   4415 }
   4416 
   4417 #if __STDC_VERSION__ >= 199901L
   4418 #define Expr_Init(name, value, emode, scope, defined) \
   4419 	(Expr) { name, value, emode, scope, defined }
   4420 #else
   4421 MAKE_INLINE Expr
   4422 Expr_Init(const char *name, FStr value,
   4423 	  VarEvalMode emode, GNode *scope, ExprDefined defined)
   4424 {
   4425 	Expr expr;
   4426 
   4427 	expr.name = name;
   4428 	expr.value = value;
   4429 	expr.emode = emode;
   4430 	expr.scope = scope;
   4431 	expr.defined = defined;
   4432 	return expr;
   4433 }
   4434 #endif
   4435 
   4436 /*
   4437  * Expressions of the form ${:U...} with a trivial value are often generated
   4438  * by .for loops and are boring, so evaluate them without debug logging.
   4439  */
   4440 static bool
   4441 Var_Parse_U(const char **pp, VarEvalMode emode, FStr *out_value)
   4442 {
   4443 	const char *p;
   4444 
   4445 	p = *pp;
   4446 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4447 		return false;
   4448 
   4449 	p += 4;
   4450 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4451 	       *p != '}' && *p != '\0')
   4452 		p++;
   4453 	if (*p != '}')
   4454 		return false;
   4455 
   4456 	*out_value = emode == VARE_PARSE_ONLY
   4457 	    ? FStr_InitRefer("")
   4458 	    : FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4459 	*pp = p + 1;
   4460 	return true;
   4461 }
   4462 
   4463 /*
   4464  * Given the start of an expression (such as $v, $(VAR), ${VAR:Mpattern}),
   4465  * extract the variable name and the modifiers, if any.  While parsing, apply
   4466  * the modifiers to the value of the expression.
   4467  *
   4468  * Input:
   4469  *	*pp		The string to parse.
   4470  *			When called from CondParser_FuncCallEmpty, it can
   4471  *			also point to the "y" of "empty(VARNAME:Modifiers)".
   4472  *	scope		The scope for finding variables.
   4473  *	emode		Controls the exact details of parsing and evaluation.
   4474  *
   4475  * Output:
   4476  *	*pp		The position where to continue parsing.
   4477  *			TODO: After a parse error, the value of *pp is
   4478  *			unspecified.  It may not have been updated at all,
   4479  *			point to some random character in the string, to the
   4480  *			location of the parse error, or at the end of the
   4481  *			string.
   4482  *	return		The value of the expression, never NULL.
   4483  *	return		var_Error if there was a parse error.
   4484  *	return		var_Error if the base variable of the expression was
   4485  *			undefined, emode is VARE_UNDEFERR, and none of
   4486  *			the modifiers turned the undefined expression into a
   4487  *			defined expression.
   4488  *			XXX: It is not guaranteed that an error message has
   4489  *			been printed.
   4490  *	return		varUndefined if the base variable of the expression
   4491  *			was undefined, emode was not VARE_UNDEFERR,
   4492  *			and none of the modifiers turned the undefined
   4493  *			expression into a defined expression.
   4494  *			XXX: It is not guaranteed that an error message has
   4495  *			been printed.
   4496  */
   4497 FStr
   4498 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode)
   4499 {
   4500 	const char *start, *p;
   4501 	bool haveModifier;	/* true for ${VAR:...}, false for ${VAR} */
   4502 	char startc;		/* the actual '{' or '(' or '\0' */
   4503 	char endc;		/* the expected '}' or ')' or '\0' */
   4504 	/*
   4505 	 * true if the expression is based on one of the 7 predefined
   4506 	 * variables that are local to a target, and the expression is
   4507 	 * expanded in a non-local scope.  The result is the text of the
   4508 	 * expression, unaltered.  This is needed to support dynamic sources.
   4509 	 */
   4510 	bool dynamic;
   4511 	const char *extramodifiers;
   4512 	Var *v;
   4513 	Expr expr = Expr_Init(NULL, FStr_InitRefer(NULL), emode,
   4514 	    scope, DEF_REGULAR);
   4515 	FStr val;
   4516 
   4517 	if (Var_Parse_U(pp, emode, &val))
   4518 		return val;
   4519 
   4520 	p = *pp;
   4521 	start = p;
   4522 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4523 
   4524 	val = FStr_InitRefer(NULL);
   4525 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4526 	dynamic = false;
   4527 
   4528 	endc = '\0';		/* Appease GCC. */
   4529 
   4530 	startc = p[1];
   4531 	if (startc != '(' && startc != '{') {
   4532 		if (!ParseVarnameShort(startc, pp, scope, emode, &val.str, &v))
   4533 			return val;
   4534 		haveModifier = false;
   4535 		p++;
   4536 	} else {
   4537 		if (!ParseVarnameLong(&p, startc, scope, emode,
   4538 		    pp, &val,
   4539 		    &endc, &v, &haveModifier, &extramodifiers,
   4540 		    &dynamic, &expr.defined))
   4541 			return val;
   4542 	}
   4543 
   4544 	expr.name = v->name.str;
   4545 	if (v->inUse && VarEvalMode_ShouldEval(emode)) {
   4546 		if (scope->fname != NULL) {
   4547 			fprintf(stderr, "In a command near ");
   4548 			PrintLocation(stderr, false, scope);
   4549 		}
   4550 		Fatal("Variable %s is recursive.", v->name.str);
   4551 	}
   4552 
   4553 	/*
   4554 	 * FIXME: This assignment creates an alias to the current value of the
   4555 	 * variable.  This means that as long as the value of the expression
   4556 	 * stays the same, the value of the variable must not change, and the
   4557 	 * variable must not be deleted.  Using the ':@' modifier, it is
   4558 	 * possible (since var.c 1.212 from 2017-02-01) to delete the variable
   4559 	 * while its value is still being used:
   4560 	 *
   4561 	 *	VAR=	value
   4562 	 *	_:=	${VAR:${:U:@VAR@@}:S,^,prefix,}
   4563 	 *
   4564 	 * The same effect might be achievable using the '::=' or the ':_'
   4565 	 * modifiers.
   4566 	 *
   4567 	 * At the bottom of this function, the resulting value is compared to
   4568 	 * the then-current value of the variable.  This might also invoke
   4569 	 * undefined behavior.
   4570 	 */
   4571 	expr.value = FStr_InitRefer(v->val.data);
   4572 
   4573 	if (expr.name[0] != '\0')
   4574 		EvalStack_Push(NULL, NULL, expr.name);
   4575 	else
   4576 		EvalStack_Push(NULL, start, NULL);
   4577 
   4578 	/*
   4579 	 * Before applying any modifiers, expand any nested expressions from
   4580 	 * the variable value.
   4581 	 */
   4582 	if (VarEvalMode_ShouldEval(emode) &&
   4583 	    strchr(Expr_Str(&expr), '$') != NULL) {
   4584 		char *expanded;
   4585 		VarEvalMode nested_emode = emode;
   4586 		if (opts.strict)
   4587 			nested_emode = VarEvalMode_UndefOk(nested_emode);
   4588 		v->inUse = true;
   4589 		expanded = Var_Subst(Expr_Str(&expr), scope, nested_emode);
   4590 		v->inUse = false;
   4591 		/* TODO: handle errors */
   4592 		Expr_SetValueOwn(&expr, expanded);
   4593 	}
   4594 
   4595 	if (extramodifiers != NULL) {
   4596 		const char *em = extramodifiers;
   4597 		ApplyModifiers(&expr, &em, '\0', '\0');
   4598 	}
   4599 
   4600 	if (haveModifier) {
   4601 		p++;		/* Skip initial colon. */
   4602 		ApplyModifiers(&expr, &p, startc, endc);
   4603 	}
   4604 
   4605 	if (*p != '\0')		/* Skip past endc if possible. */
   4606 		p++;
   4607 
   4608 	*pp = p;
   4609 
   4610 	if (expr.defined == DEF_UNDEF) {
   4611 		if (dynamic)
   4612 			Expr_SetValueOwn(&expr, bmake_strsedup(start, p));
   4613 		else {
   4614 			/*
   4615 			 * The expression is still undefined, therefore
   4616 			 * discard the actual value and return an error marker
   4617 			 * instead.
   4618 			 */
   4619 			Expr_SetValueRefer(&expr,
   4620 			    emode == VARE_UNDEFERR
   4621 				? var_Error : varUndefined);
   4622 		}
   4623 	}
   4624 
   4625 	if (v->shortLived) {
   4626 		if (expr.value.str == v->val.data) {
   4627 			/* move ownership */
   4628 			expr.value.freeIt = v->val.data;
   4629 			v->val.data = NULL;
   4630 		}
   4631 		VarFreeShortLived(v);
   4632 	}
   4633 
   4634 	EvalStack_Pop();
   4635 	return expr.value;
   4636 }
   4637 
   4638 static void
   4639 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4640 {
   4641 	/* A dollar sign may be escaped with another dollar sign. */
   4642 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4643 		Buf_AddByte(res, '$');
   4644 	Buf_AddByte(res, '$');
   4645 	*pp += 2;
   4646 }
   4647 
   4648 static void
   4649 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4650 	     VarEvalMode emode, bool *inout_errorReported)
   4651 {
   4652 	const char *p = *pp;
   4653 	const char *nested_p = p;
   4654 	FStr val = Var_Parse(&nested_p, scope, emode);
   4655 	/* TODO: handle errors */
   4656 
   4657 	if (val.str == var_Error || val.str == varUndefined) {
   4658 		if (!VarEvalMode_ShouldKeepUndef(emode)) {
   4659 			p = nested_p;
   4660 		} else if (val.str == var_Error) {
   4661 
   4662 			/*
   4663 			 * FIXME: The condition 'val.str == var_Error' doesn't
   4664 			 * mean there was an undefined variable.  It could
   4665 			 * equally well be a parse error; see
   4666 			 * unit-tests/varmod-order.mk.
   4667 			 */
   4668 
   4669 			/*
   4670 			 * If variable is undefined, complain and skip the
   4671 			 * variable. The complaint will stop us from doing
   4672 			 * anything when the file is parsed.
   4673 			 */
   4674 			if (!*inout_errorReported) {
   4675 				Parse_Error(PARSE_FATAL,
   4676 				    "Undefined variable \"%.*s\"",
   4677 				    (int)(nested_p - p), p);
   4678 				*inout_errorReported = true;
   4679 			}
   4680 			p = nested_p;
   4681 		} else {
   4682 			/*
   4683 			 * Copy the initial '$' of the undefined expression,
   4684 			 * thereby deferring expansion of the expression, but
   4685 			 * expand nested expressions if already possible. See
   4686 			 * unit-tests/varparse-undef-partial.mk.
   4687 			 */
   4688 			Buf_AddByte(buf, *p);
   4689 			p++;
   4690 		}
   4691 	} else {
   4692 		p = nested_p;
   4693 		Buf_AddStr(buf, val.str);
   4694 	}
   4695 
   4696 	FStr_Done(&val);
   4697 
   4698 	*pp = p;
   4699 }
   4700 
   4701 /*
   4702  * Skip as many characters as possible -- either to the end of the string,
   4703  * or to the next dollar sign, which may start an expression.
   4704  */
   4705 static void
   4706 VarSubstPlain(const char **pp, Buffer *res)
   4707 {
   4708 	const char *p = *pp;
   4709 	const char *start = p;
   4710 
   4711 	for (p++; *p != '$' && *p != '\0'; p++)
   4712 		continue;
   4713 	Buf_AddRange(res, start, p);
   4714 	*pp = p;
   4715 }
   4716 
   4717 /*
   4718  * Expand all expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4719  * given string.
   4720  *
   4721  * Input:
   4722  *	str		The string in which the expressions are expanded.
   4723  *	scope		The scope in which to start searching for variables.
   4724  *			The other scopes are searched as well.
   4725  *	emode		The mode for parsing or evaluating subexpressions.
   4726  */
   4727 char *
   4728 Var_Subst(const char *str, GNode *scope, VarEvalMode emode)
   4729 {
   4730 	const char *p = str;
   4731 	Buffer res;
   4732 
   4733 	/*
   4734 	 * Set true if an error has already been reported, to prevent a
   4735 	 * plethora of messages when recursing
   4736 	 */
   4737 	static bool errorReported;
   4738 
   4739 	Buf_Init(&res);
   4740 	errorReported = false;
   4741 
   4742 	while (*p != '\0') {
   4743 		if (p[0] == '$' && p[1] == '$')
   4744 			VarSubstDollarDollar(&p, &res, emode);
   4745 		else if (p[0] == '$')
   4746 			VarSubstExpr(&p, &res, scope, emode, &errorReported);
   4747 		else
   4748 			VarSubstPlain(&p, &res);
   4749 	}
   4750 
   4751 	return Buf_DoneData(&res);
   4752 }
   4753 
   4754 void
   4755 Var_Expand(FStr *str, GNode *scope, VarEvalMode emode)
   4756 {
   4757 	char *expanded;
   4758 
   4759 	if (strchr(str->str, '$') == NULL)
   4760 		return;
   4761 	expanded = Var_Subst(str->str, scope, emode);
   4762 	/* TODO: handle errors */
   4763 	FStr_Done(str);
   4764 	*str = FStr_InitOwn(expanded);
   4765 }
   4766 
   4767 /* Initialize the variables module. */
   4768 void
   4769 Var_Init(void)
   4770 {
   4771 	SCOPE_INTERNAL = GNode_New("Internal");
   4772 	SCOPE_GLOBAL = GNode_New("Global");
   4773 	SCOPE_CMDLINE = GNode_New("Command");
   4774 }
   4775 
   4776 /* Clean up the variables module. */
   4777 void
   4778 Var_End(void)
   4779 {
   4780 	Var_Stats();
   4781 }
   4782 
   4783 void
   4784 Var_Stats(void)
   4785 {
   4786 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4787 }
   4788 
   4789 static int
   4790 StrAsc(const void *sa, const void *sb)
   4791 {
   4792 	return strcmp(
   4793 	    *((const char *const *)sa), *((const char *const *)sb));
   4794 }
   4795 
   4796 
   4797 /* Print all variables in a scope, sorted by name. */
   4798 void
   4799 Var_Dump(GNode *scope)
   4800 {
   4801 	Vector /* of const char * */ vec;
   4802 	HashIter hi;
   4803 	size_t i;
   4804 	const char **varnames;
   4805 
   4806 	Vector_Init(&vec, sizeof(const char *));
   4807 
   4808 	HashIter_Init(&hi, &scope->vars);
   4809 	while (HashIter_Next(&hi) != NULL)
   4810 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4811 	varnames = vec.items;
   4812 
   4813 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4814 
   4815 	for (i = 0; i < vec.len; i++) {
   4816 		const char *varname = varnames[i];
   4817 		const Var *var = HashTable_FindValue(&scope->vars, varname);
   4818 		debug_printf("%-16s = %s%s\n", varname,
   4819 		    var->val.data, ValueDescription(var->val.data));
   4820 	}
   4821 
   4822 	Vector_Done(&vec);
   4823 }
   4824