Home | History | Annotate | Line # | Download | only in make
var.c revision 1.1111
      1 /*	$NetBSD: var.c,v 1.1111 2024/05/25 00:00:25 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.1111 2024/05/25 00:00:25 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 		return AMR_CLEANUP;
   2400 	}
   2401 
   2402 	if (!ParseModifierPart(pp, '@', VARE_PARSE_BALANCED, ch, &strBuf))
   2403 		return AMR_CLEANUP;
   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 
   2424 static void
   2425 ParseModifier_Defined(const char **pp, ModChain *ch, bool shouldEval,
   2426 		      LazyBuf *buf)
   2427 {
   2428 	const char *p;
   2429 
   2430 	p = *pp + 1;
   2431 	LazyBuf_Init(buf, p);
   2432 	while (!IsDelimiter(*p, ch)) {
   2433 
   2434 		/*
   2435 		 * XXX: This code is similar to the one in Var_Parse. See if
   2436 		 * the code can be merged. See also ParseModifier_Match and
   2437 		 * ParseModifierPart.
   2438 		 */
   2439 
   2440 		/* See Buf_AddEscaped in for.c for the counterpart. */
   2441 		if (*p == '\\') {
   2442 			char c = p[1];
   2443 			if ((IsDelimiter(c, ch) && c != '\0') ||
   2444 			    c == '$' || c == '\\') {
   2445 				if (shouldEval)
   2446 					LazyBuf_Add(buf, c);
   2447 				p += 2;
   2448 				continue;
   2449 			}
   2450 		}
   2451 
   2452 		if (*p == '$') {
   2453 			FStr val = Var_Parse(&p, ch->expr->scope,
   2454 			    shouldEval ? ch->expr->emode : VARE_PARSE_ONLY);
   2455 			/* TODO: handle errors */
   2456 			if (shouldEval)
   2457 				LazyBuf_AddStr(buf, val.str);
   2458 			FStr_Done(&val);
   2459 			continue;
   2460 		}
   2461 
   2462 		if (shouldEval)
   2463 			LazyBuf_Add(buf, *p);
   2464 		p++;
   2465 	}
   2466 	*pp = p;
   2467 }
   2468 
   2469 /* :Ddefined or :Uundefined */
   2470 static ApplyModifierResult
   2471 ApplyModifier_Defined(const char **pp, ModChain *ch)
   2472 {
   2473 	Expr *expr = ch->expr;
   2474 	LazyBuf buf;
   2475 	bool shouldEval =
   2476 	    Expr_ShouldEval(expr) &&
   2477 	    (**pp == 'D') == (expr->defined == DEF_REGULAR);
   2478 
   2479 	ParseModifier_Defined(pp, ch, shouldEval, &buf);
   2480 
   2481 	Expr_Define(expr);
   2482 	if (shouldEval)
   2483 		Expr_SetValue(expr, Substring_Str(LazyBuf_Get(&buf)));
   2484 	LazyBuf_Done(&buf);
   2485 
   2486 	return AMR_OK;
   2487 }
   2488 
   2489 /* :L */
   2490 static ApplyModifierResult
   2491 ApplyModifier_Literal(const char **pp, ModChain *ch)
   2492 {
   2493 	Expr *expr = ch->expr;
   2494 
   2495 	(*pp)++;
   2496 
   2497 	if (Expr_ShouldEval(expr)) {
   2498 		Expr_Define(expr);
   2499 		Expr_SetValueOwn(expr, bmake_strdup(expr->name));
   2500 	}
   2501 
   2502 	return AMR_OK;
   2503 }
   2504 
   2505 static bool
   2506 TryParseTime(const char **pp, time_t *out_time)
   2507 {
   2508 	char *end;
   2509 	unsigned long n;
   2510 
   2511 	if (!ch_isdigit(**pp))
   2512 		return false;
   2513 
   2514 	errno = 0;
   2515 	n = strtoul(*pp, &end, 10);
   2516 	if (n == ULONG_MAX && errno == ERANGE)
   2517 		return false;
   2518 
   2519 	*pp = end;
   2520 	*out_time = (time_t)n;	/* ignore possible truncation for now */
   2521 	return true;
   2522 }
   2523 
   2524 /* :gmtime and :localtime */
   2525 static ApplyModifierResult
   2526 ApplyModifier_Time(const char **pp, ModChain *ch)
   2527 {
   2528 	Expr *expr;
   2529 	time_t t;
   2530 	const char *args;
   2531 	const char *mod = *pp;
   2532 	bool gmt = mod[0] == 'g';
   2533 
   2534 	if (!ModMatchEq(mod, gmt ? "gmtime" : "localtime", ch))
   2535 		return AMR_UNKNOWN;
   2536 	args = mod + (gmt ? 6 : 9);
   2537 
   2538 	if (args[0] == '=') {
   2539 		const char *p = args + 1;
   2540 		LazyBuf buf;
   2541 		FStr arg;
   2542 		if (!ParseModifierPartSubst(&p, true, '\0', ch->expr->emode,
   2543 		    ch, &buf, NULL, NULL))
   2544 			return AMR_CLEANUP;
   2545 		arg = LazyBuf_DoneGet(&buf);
   2546 		if (ModChain_ShouldEval(ch)) {
   2547 			const char *arg_p = arg.str;
   2548 			if (!TryParseTime(&arg_p, &t) || *arg_p != '\0') {
   2549 				Parse_Error(PARSE_FATAL,
   2550 				    "Invalid time value \"%s\"", arg.str);
   2551 				FStr_Done(&arg);
   2552 				return AMR_CLEANUP;
   2553 			}
   2554 		} else
   2555 			t = 0;
   2556 		FStr_Done(&arg);
   2557 		*pp = p;
   2558 	} else {
   2559 		t = 0;
   2560 		*pp = args;
   2561 	}
   2562 
   2563 	expr = ch->expr;
   2564 	if (Expr_ShouldEval(expr))
   2565 		Expr_SetValueOwn(expr, FormatTime(Expr_Str(expr), t, gmt));
   2566 
   2567 	return AMR_OK;
   2568 }
   2569 
   2570 /* :hash */
   2571 static ApplyModifierResult
   2572 ApplyModifier_Hash(const char **pp, ModChain *ch)
   2573 {
   2574 	if (!ModMatch(*pp, "hash", ch))
   2575 		return AMR_UNKNOWN;
   2576 	*pp += 4;
   2577 
   2578 	if (ModChain_ShouldEval(ch))
   2579 		Expr_SetValueOwn(ch->expr, Hash(Expr_Str(ch->expr)));
   2580 
   2581 	return AMR_OK;
   2582 }
   2583 
   2584 /* :P */
   2585 static ApplyModifierResult
   2586 ApplyModifier_Path(const char **pp, ModChain *ch)
   2587 {
   2588 	Expr *expr = ch->expr;
   2589 	GNode *gn;
   2590 	char *path;
   2591 
   2592 	(*pp)++;
   2593 
   2594 	if (!Expr_ShouldEval(expr))
   2595 		return AMR_OK;
   2596 
   2597 	Expr_Define(expr);
   2598 
   2599 	gn = Targ_FindNode(expr->name);
   2600 	if (gn == NULL || gn->type & OP_NOPATH)
   2601 		path = NULL;
   2602 	else if (gn->path != NULL)
   2603 		path = bmake_strdup(gn->path);
   2604 	else {
   2605 		SearchPath *searchPath = Suff_FindPath(gn);
   2606 		path = Dir_FindFile(expr->name, searchPath);
   2607 	}
   2608 	if (path == NULL)
   2609 		path = bmake_strdup(expr->name);
   2610 	Expr_SetValueOwn(expr, path);
   2611 
   2612 	return AMR_OK;
   2613 }
   2614 
   2615 /* :!cmd! */
   2616 static ApplyModifierResult
   2617 ApplyModifier_ShellCommand(const char **pp, ModChain *ch)
   2618 {
   2619 	Expr *expr = ch->expr;
   2620 	LazyBuf cmdBuf;
   2621 	FStr cmd;
   2622 
   2623 	(*pp)++;
   2624 	if (!ParseModifierPart(pp, '!', expr->emode, ch, &cmdBuf))
   2625 		return AMR_CLEANUP;
   2626 	cmd = LazyBuf_DoneGet(&cmdBuf);
   2627 
   2628 	if (Expr_ShouldEval(expr)) {
   2629 		char *output, *error;
   2630 		output = Cmd_Exec(cmd.str, &error);
   2631 		Expr_SetValueOwn(expr, output);
   2632 		if (error != NULL) {
   2633 			/* XXX: why still return AMR_OK? */
   2634 			Error("%s", error);
   2635 			free(error);
   2636 		}
   2637 	} else
   2638 		Expr_SetValueRefer(expr, "");
   2639 
   2640 	FStr_Done(&cmd);
   2641 	Expr_Define(expr);
   2642 
   2643 	return AMR_OK;
   2644 }
   2645 
   2646 /*
   2647  * The :range modifier generates an integer sequence as long as the words.
   2648  * The :range=7 modifier generates an integer sequence from 1 to 7.
   2649  */
   2650 static ApplyModifierResult
   2651 ApplyModifier_Range(const char **pp, ModChain *ch)
   2652 {
   2653 	size_t n;
   2654 	Buffer buf;
   2655 	size_t i;
   2656 
   2657 	const char *mod = *pp;
   2658 	if (!ModMatchEq(mod, "range", ch))
   2659 		return AMR_UNKNOWN;
   2660 
   2661 	if (mod[5] == '=') {
   2662 		const char *p = mod + 6;
   2663 		if (!TryParseSize(&p, &n)) {
   2664 			Parse_Error(PARSE_FATAL,
   2665 			    "Invalid number \"%s\" for ':range' modifier",
   2666 			    mod + 6);
   2667 			return AMR_CLEANUP;
   2668 		}
   2669 		*pp = p;
   2670 	} else {
   2671 		n = 0;
   2672 		*pp = mod + 5;
   2673 	}
   2674 
   2675 	if (!ModChain_ShouldEval(ch))
   2676 		return AMR_OK;
   2677 
   2678 	if (n == 0) {
   2679 		SubstringWords words = Expr_Words(ch->expr);
   2680 		n = words.len;
   2681 		SubstringWords_Free(words);
   2682 	}
   2683 
   2684 	Buf_Init(&buf);
   2685 
   2686 	for (i = 0; i < n; i++) {
   2687 		if (i != 0) {
   2688 			/*
   2689 			 * XXX: Use ch->sep instead of ' ', for consistency.
   2690 			 */
   2691 			Buf_AddByte(&buf, ' ');
   2692 		}
   2693 		Buf_AddInt(&buf, 1 + (int)i);
   2694 	}
   2695 
   2696 	Expr_SetValueOwn(ch->expr, Buf_DoneData(&buf));
   2697 	return AMR_OK;
   2698 }
   2699 
   2700 /* Parse a ':M' or ':N' modifier. */
   2701 static char *
   2702 ParseModifier_Match(const char **pp, const ModChain *ch)
   2703 {
   2704 	const char *mod = *pp;
   2705 	Expr *expr = ch->expr;
   2706 	bool copy = false;	/* pattern should be, or has been, copied */
   2707 	bool needSubst = false;
   2708 	const char *endpat;
   2709 	char *pattern;
   2710 
   2711 	/*
   2712 	 * In the loop below, ignore ':' unless we are at (or back to) the
   2713 	 * original brace level.
   2714 	 * XXX: This will likely not work right if $() and ${} are intermixed.
   2715 	 */
   2716 	/*
   2717 	 * XXX: This code is similar to the one in Var_Parse.
   2718 	 * See if the code can be merged.
   2719 	 * See also ApplyModifier_Defined.
   2720 	 */
   2721 	int depth = 0;
   2722 	const char *p;
   2723 	for (p = mod + 1; *p != '\0' && !(*p == ':' && depth == 0); p++) {
   2724 		if (*p == '\\' && p[1] != '\0' &&
   2725 		    (IsDelimiter(p[1], ch) || p[1] == ch->startc)) {
   2726 			if (!needSubst)
   2727 				copy = true;
   2728 			p++;
   2729 			continue;
   2730 		}
   2731 		if (*p == '$')
   2732 			needSubst = true;
   2733 		if (*p == '(' || *p == '{')
   2734 			depth++;
   2735 		if (*p == ')' || *p == '}') {
   2736 			depth--;
   2737 			if (depth < 0)
   2738 				break;
   2739 		}
   2740 	}
   2741 	*pp = p;
   2742 	endpat = p;
   2743 
   2744 	if (copy) {
   2745 		char *dst;
   2746 		const char *src;
   2747 
   2748 		/* Compress the \:'s out of the pattern. */
   2749 		pattern = bmake_malloc((size_t)(endpat - (mod + 1)) + 1);
   2750 		dst = pattern;
   2751 		src = mod + 1;
   2752 		for (; src < endpat; src++, dst++) {
   2753 			if (src[0] == '\\' && src + 1 < endpat &&
   2754 			    /* XXX: ch->startc is missing here; see above */
   2755 			    IsDelimiter(src[1], ch))
   2756 				src++;
   2757 			*dst = *src;
   2758 		}
   2759 		*dst = '\0';
   2760 	} else {
   2761 		pattern = bmake_strsedup(mod + 1, endpat);
   2762 	}
   2763 
   2764 	if (needSubst) {
   2765 		char *old_pattern = pattern;
   2766 		/*
   2767 		 * XXX: Contrary to ParseModifierPart, a dollar in a ':M' or
   2768 		 * ':N' modifier must be escaped as '$$', not as '\$'.
   2769 		 */
   2770 		pattern = Var_Subst(pattern, expr->scope, expr->emode);
   2771 		/* TODO: handle errors */
   2772 		free(old_pattern);
   2773 	}
   2774 
   2775 	DEBUG2(VAR, "Pattern for ':%c' is \"%s\"\n", mod[0], pattern);
   2776 
   2777 	return pattern;
   2778 }
   2779 
   2780 struct ModifyWord_MatchArgs {
   2781 	const char *pattern;
   2782 	bool neg;
   2783 	bool error_reported;
   2784 };
   2785 
   2786 static void
   2787 ModifyWord_Match(Substring word, SepBuf *buf, void *data)
   2788 {
   2789 	struct ModifyWord_MatchArgs *args = data;
   2790 	StrMatchResult res;
   2791 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2792 	res = Str_Match(word.start, args->pattern);
   2793 	if (res.error != NULL && !args->error_reported) {
   2794 		args->error_reported = true;
   2795 		Parse_Error(PARSE_WARNING,
   2796 		    "%s in pattern '%s' of modifier '%s'",
   2797 		    res.error, args->pattern, args->neg ? ":N" : ":M");
   2798 	}
   2799 	if (res.matched != args->neg)
   2800 		SepBuf_AddSubstring(buf, word);
   2801 }
   2802 
   2803 /* :Mpattern or :Npattern */
   2804 static ApplyModifierResult
   2805 ApplyModifier_Match(const char **pp, ModChain *ch)
   2806 {
   2807 	char mod = **pp;
   2808 	char *pattern;
   2809 
   2810 	pattern = ParseModifier_Match(pp, ch);
   2811 
   2812 	if (ModChain_ShouldEval(ch)) {
   2813 		struct ModifyWord_MatchArgs args;
   2814 		args.pattern = pattern;
   2815 		args.neg = mod == 'N';
   2816 		args.error_reported = false;
   2817 		ModifyWords(ch, ModifyWord_Match, &args, ch->oneBigWord);
   2818 	}
   2819 
   2820 	free(pattern);
   2821 	return AMR_OK;
   2822 }
   2823 
   2824 struct ModifyWord_MtimeArgs {
   2825 	bool error;
   2826 	bool use_fallback;
   2827 	ApplyModifierResult rc;
   2828 	time_t fallback;
   2829 };
   2830 
   2831 static void
   2832 ModifyWord_Mtime(Substring word, SepBuf *buf, void *data)
   2833 {
   2834 	struct ModifyWord_MtimeArgs *args = data;
   2835 	struct stat st;
   2836 	char tbuf[21];
   2837 
   2838 	if (Substring_IsEmpty(word))
   2839 		return;
   2840 	assert(word.end[0] == '\0');	/* assume null-terminated word */
   2841 	if (stat(word.start, &st) < 0) {
   2842 		if (args->error) {
   2843 			Parse_Error(PARSE_FATAL,
   2844 			    "Cannot determine mtime for '%s': %s",
   2845 			    word.start, strerror(errno));
   2846 			args->rc = AMR_CLEANUP;
   2847 			return;
   2848 		}
   2849 		if (args->use_fallback)
   2850 			st.st_mtime = args->fallback;
   2851 		else
   2852 			time(&st.st_mtime);
   2853 	}
   2854 	snprintf(tbuf, sizeof(tbuf), "%u", (unsigned)st.st_mtime);
   2855 	SepBuf_AddStr(buf, tbuf);
   2856 }
   2857 
   2858 /* :mtime */
   2859 static ApplyModifierResult
   2860 ApplyModifier_Mtime(const char **pp, ModChain *ch)
   2861 {
   2862 	const char *p, *mod = *pp;
   2863 	struct ModifyWord_MtimeArgs args;
   2864 
   2865 	if (!ModMatchEq(mod, "mtime", ch))
   2866 		return AMR_UNKNOWN;
   2867 	*pp += 5;
   2868 	p = *pp;
   2869 	args.error = false;
   2870 	args.use_fallback = p[0] == '=';
   2871 	args.rc = AMR_OK;
   2872 	if (args.use_fallback) {
   2873 		p++;
   2874 		if (TryParseTime(&p, &args.fallback)) {
   2875 		} else if (strncmp(p, "error", 5) == 0) {
   2876 			p += 5;
   2877 			args.error = true;
   2878 		} else
   2879 			goto invalid_argument;
   2880 		if (!IsDelimiter(*p, ch))
   2881 			goto invalid_argument;
   2882 		*pp = p;
   2883 	}
   2884 	ModifyWords(ch, ModifyWord_Mtime, &args, ch->oneBigWord);
   2885 	return args.rc;
   2886 
   2887 invalid_argument:
   2888 	Parse_Error(PARSE_FATAL,
   2889 	    "Invalid argument '%.*s' for modifier ':mtime'",
   2890 	    (int)strcspn(*pp + 1, ":{}()"), *pp + 1);
   2891 	return AMR_CLEANUP;
   2892 }
   2893 
   2894 static void
   2895 ParsePatternFlags(const char **pp, PatternFlags *pflags, bool *oneBigWord)
   2896 {
   2897 	for (;; (*pp)++) {
   2898 		if (**pp == 'g')
   2899 			pflags->subGlobal = true;
   2900 		else if (**pp == '1')
   2901 			pflags->subOnce = true;
   2902 		else if (**pp == 'W')
   2903 			*oneBigWord = true;
   2904 		else
   2905 			break;
   2906 	}
   2907 }
   2908 
   2909 MAKE_INLINE PatternFlags
   2910 PatternFlags_None(void)
   2911 {
   2912 	PatternFlags pflags = { false, false, false, false };
   2913 	return pflags;
   2914 }
   2915 
   2916 /* :S,from,to, */
   2917 static ApplyModifierResult
   2918 ApplyModifier_Subst(const char **pp, ModChain *ch)
   2919 {
   2920 	struct ModifyWord_SubstArgs args;
   2921 	bool oneBigWord;
   2922 	LazyBuf lhsBuf, rhsBuf;
   2923 
   2924 	char delim = (*pp)[1];
   2925 	if (delim == '\0') {
   2926 		Error("Missing delimiter for modifier ':S'");
   2927 		(*pp)++;
   2928 		return AMR_CLEANUP;
   2929 	}
   2930 
   2931 	*pp += 2;
   2932 
   2933 	args.pflags = PatternFlags_None();
   2934 	args.matched = false;
   2935 
   2936 	if (**pp == '^') {
   2937 		args.pflags.anchorStart = true;
   2938 		(*pp)++;
   2939 	}
   2940 
   2941 	if (!ParseModifierPartSubst(pp,
   2942 	    false, delim, ch->expr->emode, ch, &lhsBuf, &args.pflags, NULL))
   2943 		return AMR_CLEANUP;
   2944 	args.lhs = LazyBuf_Get(&lhsBuf);
   2945 
   2946 	if (!ParseModifierPartSubst(pp,
   2947 	    false, delim, ch->expr->emode, ch, &rhsBuf, NULL, &args)) {
   2948 		LazyBuf_Done(&lhsBuf);
   2949 		return AMR_CLEANUP;
   2950 	}
   2951 	args.rhs = LazyBuf_Get(&rhsBuf);
   2952 
   2953 	oneBigWord = ch->oneBigWord;
   2954 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2955 
   2956 	ModifyWords(ch, ModifyWord_Subst, &args, oneBigWord);
   2957 
   2958 	LazyBuf_Done(&lhsBuf);
   2959 	LazyBuf_Done(&rhsBuf);
   2960 	return AMR_OK;
   2961 }
   2962 
   2963 /* :C,from,to, */
   2964 static ApplyModifierResult
   2965 ApplyModifier_Regex(const char **pp, ModChain *ch)
   2966 {
   2967 	struct ModifyWord_SubstRegexArgs args;
   2968 	bool oneBigWord;
   2969 	int error;
   2970 	LazyBuf reBuf, replaceBuf;
   2971 	FStr re;
   2972 
   2973 	char delim = (*pp)[1];
   2974 	if (delim == '\0') {
   2975 		Error("Missing delimiter for :C modifier");
   2976 		(*pp)++;
   2977 		return AMR_CLEANUP;
   2978 	}
   2979 
   2980 	*pp += 2;
   2981 
   2982 	if (!ParseModifierPart(pp, delim, ch->expr->emode, ch, &reBuf))
   2983 		return AMR_CLEANUP;
   2984 	re = LazyBuf_DoneGet(&reBuf);
   2985 
   2986 	if (!ParseModifierPart(pp, delim, ch->expr->emode, ch, &replaceBuf)) {
   2987 		FStr_Done(&re);
   2988 		return AMR_CLEANUP;
   2989 	}
   2990 	args.replace = LazyBuf_Get(&replaceBuf);
   2991 
   2992 	args.pflags = PatternFlags_None();
   2993 	args.matched = false;
   2994 	oneBigWord = ch->oneBigWord;
   2995 	ParsePatternFlags(pp, &args.pflags, &oneBigWord);
   2996 
   2997 	if (!ModChain_ShouldEval(ch))
   2998 		goto done;
   2999 
   3000 	error = regcomp(&args.re, re.str, REG_EXTENDED);
   3001 	if (error != 0) {
   3002 		RegexError(error, &args.re, "Regex compilation error");
   3003 		LazyBuf_Done(&replaceBuf);
   3004 		FStr_Done(&re);
   3005 		return AMR_CLEANUP;
   3006 	}
   3007 
   3008 	args.nsub = args.re.re_nsub + 1;
   3009 	if (args.nsub > 10)
   3010 		args.nsub = 10;
   3011 
   3012 	ModifyWords(ch, ModifyWord_SubstRegex, &args, oneBigWord);
   3013 
   3014 	regfree(&args.re);
   3015 done:
   3016 	LazyBuf_Done(&replaceBuf);
   3017 	FStr_Done(&re);
   3018 	return AMR_OK;
   3019 }
   3020 
   3021 /* :Q, :q */
   3022 static ApplyModifierResult
   3023 ApplyModifier_Quote(const char **pp, ModChain *ch)
   3024 {
   3025 	LazyBuf buf;
   3026 	bool quoteDollar;
   3027 
   3028 	quoteDollar = **pp == 'q';
   3029 	if (!IsDelimiter((*pp)[1], ch))
   3030 		return AMR_UNKNOWN;
   3031 	(*pp)++;
   3032 
   3033 	if (!ModChain_ShouldEval(ch))
   3034 		return AMR_OK;
   3035 
   3036 	QuoteShell(Expr_Str(ch->expr), quoteDollar, &buf);
   3037 	if (buf.data != NULL)
   3038 		Expr_SetValue(ch->expr, LazyBuf_DoneGet(&buf));
   3039 	else
   3040 		LazyBuf_Done(&buf);
   3041 
   3042 	return AMR_OK;
   3043 }
   3044 
   3045 /*ARGSUSED*/
   3046 static void
   3047 ModifyWord_Copy(Substring word, SepBuf *buf, void *data MAKE_ATTR_UNUSED)
   3048 {
   3049 	SepBuf_AddSubstring(buf, word);
   3050 }
   3051 
   3052 /* :ts<separator> */
   3053 static ApplyModifierResult
   3054 ApplyModifier_ToSep(const char **pp, ModChain *ch)
   3055 {
   3056 	const char *sep = *pp + 2;
   3057 
   3058 	/*
   3059 	 * Even in parse-only mode, apply the side effects, since the side
   3060 	 * effects are neither observable nor is there a performance penalty.
   3061 	 * Checking for wantRes for every single piece of code in here
   3062 	 * would make the code in this function too hard to read.
   3063 	 */
   3064 
   3065 	/* ":ts<any><endc>" or ":ts<any>:" */
   3066 	if (sep[0] != ch->endc && IsDelimiter(sep[1], ch)) {
   3067 		*pp = sep + 1;
   3068 		ch->sep = sep[0];
   3069 		goto ok;
   3070 	}
   3071 
   3072 	/* ":ts<endc>" or ":ts:" */
   3073 	if (IsDelimiter(sep[0], ch)) {
   3074 		*pp = sep;
   3075 		ch->sep = '\0';	/* no separator */
   3076 		goto ok;
   3077 	}
   3078 
   3079 	/* ":ts<unrecognized><unrecognized>". */
   3080 	if (sep[0] != '\\') {
   3081 		(*pp)++;	/* just for backwards compatibility */
   3082 		return AMR_BAD;
   3083 	}
   3084 
   3085 	/* ":ts\n" */
   3086 	if (sep[1] == 'n') {
   3087 		*pp = sep + 2;
   3088 		ch->sep = '\n';
   3089 		goto ok;
   3090 	}
   3091 
   3092 	/* ":ts\t" */
   3093 	if (sep[1] == 't') {
   3094 		*pp = sep + 2;
   3095 		ch->sep = '\t';
   3096 		goto ok;
   3097 	}
   3098 
   3099 	/* ":ts\x40" or ":ts\100" */
   3100 	{
   3101 		const char *p = sep + 1;
   3102 		int base = 8;	/* assume octal */
   3103 
   3104 		if (sep[1] == 'x') {
   3105 			base = 16;
   3106 			p++;
   3107 		} else if (!ch_isdigit(sep[1])) {
   3108 			(*pp)++;	/* just for backwards compatibility */
   3109 			return AMR_BAD;	/* ":ts<backslash><unrecognized>". */
   3110 		}
   3111 
   3112 		if (!TryParseChar(&p, base, &ch->sep)) {
   3113 			Parse_Error(PARSE_FATAL,
   3114 			    "Invalid character number at \"%s\"", p);
   3115 			return AMR_CLEANUP;
   3116 		}
   3117 		if (!IsDelimiter(*p, ch)) {
   3118 			(*pp)++;	/* just for backwards compatibility */
   3119 			return AMR_BAD;
   3120 		}
   3121 
   3122 		*pp = p;
   3123 	}
   3124 
   3125 ok:
   3126 	ModifyWords(ch, ModifyWord_Copy, NULL, ch->oneBigWord);
   3127 	return AMR_OK;
   3128 }
   3129 
   3130 static char *
   3131 str_toupper(const char *str)
   3132 {
   3133 	size_t i, n = strlen(str) + 1;
   3134 	char *res = bmake_malloc(n);
   3135 	for (i = 0; i < n; i++)
   3136 		res[i] = ch_toupper(str[i]);
   3137 	return res;
   3138 }
   3139 
   3140 static char *
   3141 str_tolower(const char *str)
   3142 {
   3143 	size_t i, n = strlen(str) + 1;
   3144 	char *res = bmake_malloc(n);
   3145 	for (i = 0; i < n; i++)
   3146 		res[i] = ch_tolower(str[i]);
   3147 	return res;
   3148 }
   3149 
   3150 /* :tA, :tu, :tl, :ts<separator>, etc. */
   3151 static ApplyModifierResult
   3152 ApplyModifier_To(const char **pp, ModChain *ch)
   3153 {
   3154 	Expr *expr = ch->expr;
   3155 	const char *mod = *pp;
   3156 	assert(mod[0] == 't');
   3157 
   3158 	if (IsDelimiter(mod[1], ch)) {
   3159 		*pp = mod + 1;
   3160 		return AMR_BAD;	/* Found ":t<endc>" or ":t:". */
   3161 	}
   3162 
   3163 	if (mod[1] == 's')
   3164 		return ApplyModifier_ToSep(pp, ch);
   3165 
   3166 	if (!IsDelimiter(mod[2], ch)) {			/* :t<any><any> */
   3167 		*pp = mod + 1;
   3168 		return AMR_BAD;
   3169 	}
   3170 
   3171 	if (mod[1] == 'A') {				/* :tA */
   3172 		*pp = mod + 2;
   3173 		ModifyWords(ch, ModifyWord_Realpath, NULL, ch->oneBigWord);
   3174 		return AMR_OK;
   3175 	}
   3176 
   3177 	if (mod[1] == 'u') {				/* :tu */
   3178 		*pp = mod + 2;
   3179 		if (Expr_ShouldEval(expr))
   3180 			Expr_SetValueOwn(expr, str_toupper(Expr_Str(expr)));
   3181 		return AMR_OK;
   3182 	}
   3183 
   3184 	if (mod[1] == 'l') {				/* :tl */
   3185 		*pp = mod + 2;
   3186 		if (Expr_ShouldEval(expr))
   3187 			Expr_SetValueOwn(expr, str_tolower(Expr_Str(expr)));
   3188 		return AMR_OK;
   3189 	}
   3190 
   3191 	if (mod[1] == 'W' || mod[1] == 'w') {		/* :tW, :tw */
   3192 		*pp = mod + 2;
   3193 		ch->oneBigWord = mod[1] == 'W';
   3194 		return AMR_OK;
   3195 	}
   3196 
   3197 	/* Found ":t<unrecognized>:" or ":t<unrecognized><endc>". */
   3198 	*pp = mod + 1;		/* XXX: unnecessary but observable */
   3199 	return AMR_BAD;
   3200 }
   3201 
   3202 /* :[#], :[1], :[-1..1], etc. */
   3203 static ApplyModifierResult
   3204 ApplyModifier_Words(const char **pp, ModChain *ch)
   3205 {
   3206 	Expr *expr = ch->expr;
   3207 	int first, last;
   3208 	const char *p;
   3209 	LazyBuf argBuf;
   3210 	FStr arg;
   3211 
   3212 	(*pp)++;		/* skip the '[' */
   3213 	if (!ParseModifierPart(pp, ']', expr->emode, ch, &argBuf))
   3214 		return AMR_CLEANUP;
   3215 	arg = LazyBuf_DoneGet(&argBuf);
   3216 	p = arg.str;
   3217 
   3218 	if (!IsDelimiter(**pp, ch))
   3219 		goto bad_modifier;		/* Found junk after ']' */
   3220 
   3221 	if (!ModChain_ShouldEval(ch))
   3222 		goto ok;
   3223 
   3224 	if (p[0] == '\0')
   3225 		goto bad_modifier;		/* Found ":[]". */
   3226 
   3227 	if (strcmp(p, "#") == 0) {		/* Found ":[#]" */
   3228 		if (ch->oneBigWord)
   3229 			Expr_SetValueRefer(expr, "1");
   3230 		else {
   3231 			Buffer buf;
   3232 
   3233 			SubstringWords words = Expr_Words(expr);
   3234 			size_t ac = words.len;
   3235 			SubstringWords_Free(words);
   3236 
   3237 			Buf_Init(&buf);
   3238 			Buf_AddInt(&buf, (int)ac);
   3239 			Expr_SetValueOwn(expr, Buf_DoneData(&buf));
   3240 		}
   3241 		goto ok;
   3242 	}
   3243 
   3244 	if (strcmp(p, "*") == 0) {		/* ":[*]" */
   3245 		ch->oneBigWord = true;
   3246 		goto ok;
   3247 	}
   3248 
   3249 	if (strcmp(p, "@") == 0) {		/* ":[@]" */
   3250 		ch->oneBigWord = false;
   3251 		goto ok;
   3252 	}
   3253 
   3254 	/* Expect ":[N]" or ":[start..end]" */
   3255 	if (!TryParseIntBase0(&p, &first))
   3256 		goto bad_modifier;
   3257 
   3258 	if (p[0] == '\0')			/* ":[N]" */
   3259 		last = first;
   3260 	else if (strncmp(p, "..", 2) == 0) {
   3261 		p += 2;
   3262 		if (!TryParseIntBase0(&p, &last) || *p != '\0')
   3263 			goto bad_modifier;
   3264 	} else
   3265 		goto bad_modifier;
   3266 
   3267 	if (first == 0 && last == 0) {		/* ":[0]" or ":[0..0]" */
   3268 		ch->oneBigWord = true;
   3269 		goto ok;
   3270 	}
   3271 
   3272 	if (first == 0 || last == 0)		/* ":[0..N]" or ":[N..0]" */
   3273 		goto bad_modifier;
   3274 
   3275 	Expr_SetValueOwn(expr,
   3276 	    VarSelectWords(Expr_Str(expr), first, last,
   3277 		ch->sep, ch->oneBigWord));
   3278 
   3279 ok:
   3280 	FStr_Done(&arg);
   3281 	return AMR_OK;
   3282 
   3283 bad_modifier:
   3284 	FStr_Done(&arg);
   3285 	return AMR_BAD;
   3286 }
   3287 
   3288 #if __STDC_VERSION__ >= 199901L
   3289 # define NUM_TYPE long long
   3290 # define PARSE_NUM_TYPE strtoll
   3291 #else
   3292 # define NUM_TYPE long
   3293 # define PARSE_NUM_TYPE strtol
   3294 #endif
   3295 
   3296 static NUM_TYPE
   3297 num_val(Substring s)
   3298 {
   3299 	NUM_TYPE val;
   3300 	char *ep;
   3301 
   3302 	val = PARSE_NUM_TYPE(s.start, &ep, 0);
   3303 	if (ep != s.start) {
   3304 		switch (*ep) {
   3305 		case 'K':
   3306 		case 'k':
   3307 			val <<= 10;
   3308 			break;
   3309 		case 'M':
   3310 		case 'm':
   3311 			val <<= 20;
   3312 			break;
   3313 		case 'G':
   3314 		case 'g':
   3315 			val <<= 30;
   3316 			break;
   3317 		}
   3318 	}
   3319 	return val;
   3320 }
   3321 
   3322 static int
   3323 SubNumAsc(const void *sa, const void *sb)
   3324 {
   3325 	NUM_TYPE a, b;
   3326 
   3327 	a = num_val(*((const Substring *)sa));
   3328 	b = num_val(*((const Substring *)sb));
   3329 	return a > b ? 1 : b > a ? -1 : 0;
   3330 }
   3331 
   3332 static int
   3333 SubNumDesc(const void *sa, const void *sb)
   3334 {
   3335 	return SubNumAsc(sb, sa);
   3336 }
   3337 
   3338 static int
   3339 Substring_Cmp(Substring a, Substring b)
   3340 {
   3341 	for (; a.start < a.end && b.start < b.end; a.start++, b.start++)
   3342 		if (a.start[0] != b.start[0])
   3343 			return (unsigned char)a.start[0]
   3344 			    - (unsigned char)b.start[0];
   3345 	return (int)((a.end - a.start) - (b.end - b.start));
   3346 }
   3347 
   3348 static int
   3349 SubStrAsc(const void *sa, const void *sb)
   3350 {
   3351 	return Substring_Cmp(*(const Substring *)sa, *(const Substring *)sb);
   3352 }
   3353 
   3354 static int
   3355 SubStrDesc(const void *sa, const void *sb)
   3356 {
   3357 	return SubStrAsc(sb, sa);
   3358 }
   3359 
   3360 static void
   3361 ShuffleSubstrings(Substring *strs, size_t n)
   3362 {
   3363 	size_t i;
   3364 
   3365 	for (i = n - 1; i > 0; i--) {
   3366 		size_t rndidx = (size_t)random() % (i + 1);
   3367 		Substring t = strs[i];
   3368 		strs[i] = strs[rndidx];
   3369 		strs[rndidx] = t;
   3370 	}
   3371 }
   3372 
   3373 /*
   3374  * :O		order ascending
   3375  * :Or		order descending
   3376  * :Ox		shuffle
   3377  * :On		numeric ascending
   3378  * :Onr, :Orn	numeric descending
   3379  */
   3380 static ApplyModifierResult
   3381 ApplyModifier_Order(const char **pp, ModChain *ch)
   3382 {
   3383 	const char *mod = *pp;
   3384 	SubstringWords words;
   3385 	int (*cmp)(const void *, const void *);
   3386 
   3387 	if (IsDelimiter(mod[1], ch)) {
   3388 		cmp = SubStrAsc;
   3389 		(*pp)++;
   3390 	} else if (IsDelimiter(mod[2], ch)) {
   3391 		if (mod[1] == 'n')
   3392 			cmp = SubNumAsc;
   3393 		else if (mod[1] == 'r')
   3394 			cmp = SubStrDesc;
   3395 		else if (mod[1] == 'x')
   3396 			cmp = NULL;
   3397 		else
   3398 			goto bad;
   3399 		*pp += 2;
   3400 	} else if (IsDelimiter(mod[3], ch)) {
   3401 		if ((mod[1] == 'n' && mod[2] == 'r') ||
   3402 		    (mod[1] == 'r' && mod[2] == 'n'))
   3403 			cmp = SubNumDesc;
   3404 		else
   3405 			goto bad;
   3406 		*pp += 3;
   3407 	} else
   3408 		goto bad;
   3409 
   3410 	if (!ModChain_ShouldEval(ch))
   3411 		return AMR_OK;
   3412 
   3413 	words = Expr_Words(ch->expr);
   3414 	if (cmp == NULL)
   3415 		ShuffleSubstrings(words.words, words.len);
   3416 	else {
   3417 		assert(words.words[0].end[0] == '\0');
   3418 		qsort(words.words, words.len, sizeof(words.words[0]), cmp);
   3419 	}
   3420 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3421 
   3422 	return AMR_OK;
   3423 
   3424 bad:
   3425 	(*pp)++;
   3426 	return AMR_BAD;
   3427 }
   3428 
   3429 /* :? then : else */
   3430 static ApplyModifierResult
   3431 ApplyModifier_IfElse(const char **pp, ModChain *ch)
   3432 {
   3433 	Expr *expr = ch->expr;
   3434 	LazyBuf thenBuf;
   3435 	LazyBuf elseBuf;
   3436 
   3437 	VarEvalMode then_emode = VARE_PARSE_ONLY;
   3438 	VarEvalMode else_emode = VARE_PARSE_ONLY;
   3439 
   3440 	CondResult cond_rc = CR_TRUE;	/* just not CR_ERROR */
   3441 	if (Expr_ShouldEval(expr)) {
   3442 		cond_rc = Cond_EvalCondition(expr->name);
   3443 		if (cond_rc == CR_TRUE)
   3444 			then_emode = expr->emode;
   3445 		if (cond_rc == CR_FALSE)
   3446 			else_emode = expr->emode;
   3447 	}
   3448 
   3449 	(*pp)++;		/* skip past the '?' */
   3450 	if (!ParseModifierPart(pp, ':', then_emode, ch, &thenBuf))
   3451 		return AMR_CLEANUP;
   3452 
   3453 	if (!ParseModifierPart(pp, ch->endc, else_emode, ch, &elseBuf)) {
   3454 		LazyBuf_Done(&thenBuf);
   3455 		return AMR_CLEANUP;
   3456 	}
   3457 
   3458 	(*pp)--;		/* Go back to the ch->endc. */
   3459 
   3460 	if (cond_rc == CR_ERROR) {
   3461 		Substring thenExpr = LazyBuf_Get(&thenBuf);
   3462 		Substring elseExpr = LazyBuf_Get(&elseBuf);
   3463 		Error("Bad conditional expression '%s' before '?%.*s:%.*s'",
   3464 		    expr->name,
   3465 		    (int)Substring_Length(thenExpr), thenExpr.start,
   3466 		    (int)Substring_Length(elseExpr), elseExpr.start);
   3467 		LazyBuf_Done(&thenBuf);
   3468 		LazyBuf_Done(&elseBuf);
   3469 		return AMR_CLEANUP;
   3470 	}
   3471 
   3472 	if (!Expr_ShouldEval(expr)) {
   3473 		LazyBuf_Done(&thenBuf);
   3474 		LazyBuf_Done(&elseBuf);
   3475 	} else if (cond_rc == CR_TRUE) {
   3476 		Expr_SetValue(expr, LazyBuf_DoneGet(&thenBuf));
   3477 		LazyBuf_Done(&elseBuf);
   3478 	} else {
   3479 		LazyBuf_Done(&thenBuf);
   3480 		Expr_SetValue(expr, LazyBuf_DoneGet(&elseBuf));
   3481 	}
   3482 	Expr_Define(expr);
   3483 	return AMR_OK;
   3484 }
   3485 
   3486 /*
   3487  * The ::= modifiers are special in that they do not read the variable value
   3488  * but instead assign to that variable.  They always expand to an empty
   3489  * string.
   3490  *
   3491  * Their main purpose is in supporting .for loops that generate shell commands
   3492  * since an ordinary variable assignment at that point would terminate the
   3493  * dependency group for these targets.  For example:
   3494  *
   3495  * list-targets: .USE
   3496  * .for i in ${.TARGET} ${.TARGET:R}.gz
   3497  *	@${t::=$i}
   3498  *	@echo 'The target is ${t:T}.'
   3499  * .endfor
   3500  *
   3501  *	  ::=<str>	Assigns <str> as the new value of variable.
   3502  *	  ::?=<str>	Assigns <str> as value of variable if
   3503  *			it was not already set.
   3504  *	  ::+=<str>	Appends <str> to variable.
   3505  *	  ::!=<cmd>	Assigns output of <cmd> as the new value of
   3506  *			variable.
   3507  */
   3508 static ApplyModifierResult
   3509 ApplyModifier_Assign(const char **pp, ModChain *ch)
   3510 {
   3511 	Expr *expr = ch->expr;
   3512 	GNode *scope;
   3513 	FStr val;
   3514 	LazyBuf buf;
   3515 
   3516 	const char *mod = *pp;
   3517 	const char *op = mod + 1;
   3518 
   3519 	if (op[0] == '=')
   3520 		goto found_op;
   3521 	if ((op[0] == '+' || op[0] == '?' || op[0] == '!') && op[1] == '=')
   3522 		goto found_op;
   3523 	return AMR_UNKNOWN;	/* "::<unrecognized>" */
   3524 
   3525 found_op:
   3526 	if (expr->name[0] == '\0') {
   3527 		*pp = mod + 1;
   3528 		return AMR_BAD;
   3529 	}
   3530 
   3531 	*pp = mod + (op[0] != '=' ? 3 : 2);
   3532 
   3533 	if (!ParseModifierPart(pp, ch->endc, expr->emode, ch, &buf))
   3534 		return AMR_CLEANUP;
   3535 	val = LazyBuf_DoneGet(&buf);
   3536 
   3537 	(*pp)--;		/* Go back to the ch->endc. */
   3538 
   3539 	if (!Expr_ShouldEval(expr))
   3540 		goto done;
   3541 
   3542 	scope = expr->scope;	/* scope where v belongs */
   3543 	if (expr->defined == DEF_REGULAR && expr->scope != SCOPE_GLOBAL
   3544 	    && VarFind(expr->name, expr->scope, false) == NULL)
   3545 		scope = SCOPE_GLOBAL;
   3546 
   3547 	if (op[0] == '+')
   3548 		Var_Append(scope, expr->name, val.str);
   3549 	else if (op[0] == '!') {
   3550 		char *output, *error;
   3551 		output = Cmd_Exec(val.str, &error);
   3552 		if (error != NULL) {
   3553 			Error("%s", error);
   3554 			free(error);
   3555 		} else
   3556 			Var_Set(scope, expr->name, output);
   3557 		free(output);
   3558 	} else if (op[0] == '?' && expr->defined == DEF_REGULAR) {
   3559 		/* Do nothing. */
   3560 	} else
   3561 		Var_Set(scope, expr->name, val.str);
   3562 
   3563 	Expr_SetValueRefer(expr, "");
   3564 
   3565 done:
   3566 	FStr_Done(&val);
   3567 	return AMR_OK;
   3568 }
   3569 
   3570 /*
   3571  * :_=...
   3572  * remember current value
   3573  */
   3574 static ApplyModifierResult
   3575 ApplyModifier_Remember(const char **pp, ModChain *ch)
   3576 {
   3577 	Expr *expr = ch->expr;
   3578 	const char *mod = *pp;
   3579 	FStr name;
   3580 
   3581 	if (!ModMatchEq(mod, "_", ch))
   3582 		return AMR_UNKNOWN;
   3583 
   3584 	name = FStr_InitRefer("_");
   3585 	if (mod[1] == '=') {
   3586 		/*
   3587 		 * XXX: This ad-hoc call to strcspn deviates from the usual
   3588 		 * behavior defined in ParseModifierPart.  This creates an
   3589 		 * unnecessary and undocumented inconsistency in make.
   3590 		 */
   3591 		const char *arg = mod + 2;
   3592 		size_t argLen = strcspn(arg, ":)}");
   3593 		*pp = arg + argLen;
   3594 		name = FStr_InitOwn(bmake_strldup(arg, argLen));
   3595 	} else
   3596 		*pp = mod + 1;
   3597 
   3598 	if (Expr_ShouldEval(expr))
   3599 		Var_Set(SCOPE_GLOBAL, name.str, Expr_Str(expr));
   3600 	FStr_Done(&name);
   3601 
   3602 	return AMR_OK;
   3603 }
   3604 
   3605 /*
   3606  * Apply the given function to each word of the variable value,
   3607  * for a single-letter modifier such as :H, :T.
   3608  */
   3609 static ApplyModifierResult
   3610 ApplyModifier_WordFunc(const char **pp, ModChain *ch,
   3611 		       ModifyWordProc modifyWord)
   3612 {
   3613 	if (!IsDelimiter((*pp)[1], ch))
   3614 		return AMR_UNKNOWN;
   3615 	(*pp)++;
   3616 
   3617 	ModifyWords(ch, modifyWord, NULL, ch->oneBigWord);
   3618 
   3619 	return AMR_OK;
   3620 }
   3621 
   3622 /* Remove adjacent duplicate words. */
   3623 static ApplyModifierResult
   3624 ApplyModifier_Unique(const char **pp, ModChain *ch)
   3625 {
   3626 	SubstringWords words;
   3627 
   3628 	if (!IsDelimiter((*pp)[1], ch))
   3629 		return AMR_UNKNOWN;
   3630 	(*pp)++;
   3631 
   3632 	if (!ModChain_ShouldEval(ch))
   3633 		return AMR_OK;
   3634 
   3635 	words = Expr_Words(ch->expr);
   3636 
   3637 	if (words.len > 1) {
   3638 		size_t di, si;
   3639 
   3640 		di = 0;
   3641 		for (si = 1; si < words.len; si++) {
   3642 			if (!Substring_Eq(words.words[si], words.words[di])) {
   3643 				di++;
   3644 				if (di != si)
   3645 					words.words[di] = words.words[si];
   3646 			}
   3647 		}
   3648 		words.len = di + 1;
   3649 	}
   3650 
   3651 	Expr_SetValueOwn(ch->expr, SubstringWords_JoinFree(words));
   3652 
   3653 	return AMR_OK;
   3654 }
   3655 
   3656 /* Test whether the modifier has the form '<lhs>=<rhs>'. */
   3657 static bool
   3658 IsSysVModifier(const char *p, char startc, char endc)
   3659 {
   3660 	bool eqFound = false;
   3661 
   3662 	int depth = 1;
   3663 	while (*p != '\0' && depth > 0) {
   3664 		if (*p == '=')	/* XXX: should also test depth == 1 */
   3665 			eqFound = true;
   3666 		else if (*p == endc)
   3667 			depth--;
   3668 		else if (*p == startc)
   3669 			depth++;
   3670 		if (depth > 0)
   3671 			p++;
   3672 	}
   3673 	return *p == endc && eqFound;
   3674 }
   3675 
   3676 /* :from=to */
   3677 static ApplyModifierResult
   3678 ApplyModifier_SysV(const char **pp, ModChain *ch)
   3679 {
   3680 	Expr *expr = ch->expr;
   3681 	LazyBuf lhsBuf, rhsBuf;
   3682 	FStr rhs;
   3683 	struct ModifyWord_SysVSubstArgs args;
   3684 	Substring lhs;
   3685 	const char *lhsSuffix;
   3686 
   3687 	const char *mod = *pp;
   3688 
   3689 	if (!IsSysVModifier(mod, ch->startc, ch->endc))
   3690 		return AMR_UNKNOWN;
   3691 
   3692 	if (!ParseModifierPart(pp, '=', expr->emode, ch, &lhsBuf))
   3693 		return AMR_CLEANUP;
   3694 
   3695 	/*
   3696 	 * The SysV modifier lasts until the end of the expression.
   3697 	 */
   3698 	if (!ParseModifierPart(pp, ch->endc, expr->emode, ch, &rhsBuf)) {
   3699 		LazyBuf_Done(&lhsBuf);
   3700 		return AMR_CLEANUP;
   3701 	}
   3702 	rhs = LazyBuf_DoneGet(&rhsBuf);
   3703 
   3704 	(*pp)--;		/* Go back to the ch->endc. */
   3705 
   3706 	/* Do not turn an empty expression into non-empty. */
   3707 	if (lhsBuf.len == 0 && Expr_Str(expr)[0] == '\0')
   3708 		goto done;
   3709 
   3710 	lhs = LazyBuf_Get(&lhsBuf);
   3711 	lhsSuffix = Substring_SkipFirst(lhs, '%');
   3712 
   3713 	args.scope = expr->scope;
   3714 	args.lhsPrefix = Substring_Init(lhs.start,
   3715 	    lhsSuffix != lhs.start ? lhsSuffix - 1 : lhs.start);
   3716 	args.lhsPercent = lhsSuffix != lhs.start;
   3717 	args.lhsSuffix = Substring_Init(lhsSuffix, lhs.end);
   3718 	args.rhs = rhs.str;
   3719 
   3720 	ModifyWords(ch, ModifyWord_SysVSubst, &args, ch->oneBigWord);
   3721 
   3722 done:
   3723 	LazyBuf_Done(&lhsBuf);
   3724 	FStr_Done(&rhs);
   3725 	return AMR_OK;
   3726 }
   3727 
   3728 /* :sh */
   3729 static ApplyModifierResult
   3730 ApplyModifier_SunShell(const char **pp, ModChain *ch)
   3731 {
   3732 	Expr *expr = ch->expr;
   3733 	const char *p = *pp;
   3734 	if (!(p[1] == 'h' && IsDelimiter(p[2], ch)))
   3735 		return AMR_UNKNOWN;
   3736 	*pp = p + 2;
   3737 
   3738 	if (Expr_ShouldEval(expr)) {
   3739 		char *output, *error;
   3740 		output = Cmd_Exec(Expr_Str(expr), &error);
   3741 		if (error != NULL) {
   3742 			Error("%s", error);
   3743 			free(error);
   3744 		}
   3745 		Expr_SetValueOwn(expr, output);
   3746 	}
   3747 
   3748 	return AMR_OK;
   3749 }
   3750 
   3751 /*
   3752  * In cases where the evaluation mode and the definedness are the "standard"
   3753  * ones, don't log them, to keep the logs readable.
   3754  */
   3755 static bool
   3756 ShouldLogInSimpleFormat(const Expr *expr)
   3757 {
   3758 	return (expr->emode == VARE_WANTRES ||
   3759 		expr->emode == VARE_UNDEFERR) &&
   3760 	       expr->defined == DEF_REGULAR;
   3761 }
   3762 
   3763 static void
   3764 LogBeforeApply(const ModChain *ch, const char *mod)
   3765 {
   3766 	const Expr *expr = ch->expr;
   3767 	bool is_single_char = mod[0] != '\0' && IsDelimiter(mod[1], ch);
   3768 
   3769 	/*
   3770 	 * At this point, only the first character of the modifier can
   3771 	 * be used since the end of the modifier is not yet known.
   3772 	 */
   3773 
   3774 	if (!Expr_ShouldEval(expr)) {
   3775 		debug_printf("Parsing modifier ${%s:%c%s}\n",
   3776 		    expr->name, mod[0], is_single_char ? "" : "...");
   3777 		return;
   3778 	}
   3779 
   3780 	if (ShouldLogInSimpleFormat(expr)) {
   3781 		debug_printf(
   3782 		    "Evaluating modifier ${%s:%c%s} on value \"%s\"\n",
   3783 		    expr->name, mod[0], is_single_char ? "" : "...",
   3784 		    Expr_Str(expr));
   3785 		return;
   3786 	}
   3787 
   3788 	debug_printf(
   3789 	    "Evaluating modifier ${%s:%c%s} on value \"%s\" (%s, %s)\n",
   3790 	    expr->name, mod[0], is_single_char ? "" : "...", Expr_Str(expr),
   3791 	    VarEvalMode_Name[expr->emode], ExprDefined_Name[expr->defined]);
   3792 }
   3793 
   3794 static void
   3795 LogAfterApply(const ModChain *ch, const char *p, const char *mod)
   3796 {
   3797 	const Expr *expr = ch->expr;
   3798 	const char *value = Expr_Str(expr);
   3799 	const char *quot = value == var_Error ? "" : "\"";
   3800 
   3801 	if (ShouldLogInSimpleFormat(expr)) {
   3802 		debug_printf("Result of ${%s:%.*s} is %s%s%s\n",
   3803 		    expr->name, (int)(p - mod), mod,
   3804 		    quot, value == var_Error ? "error" : value, quot);
   3805 		return;
   3806 	}
   3807 
   3808 	debug_printf("Result of ${%s:%.*s} is %s%s%s (%s, %s)\n",
   3809 	    expr->name, (int)(p - mod), mod,
   3810 	    quot, value == var_Error ? "error" : value, quot,
   3811 	    VarEvalMode_Name[expr->emode],
   3812 	    ExprDefined_Name[expr->defined]);
   3813 }
   3814 
   3815 static ApplyModifierResult
   3816 ApplyModifier(const char **pp, ModChain *ch)
   3817 {
   3818 	switch (**pp) {
   3819 	case '!':
   3820 		return ApplyModifier_ShellCommand(pp, ch);
   3821 	case ':':
   3822 		return ApplyModifier_Assign(pp, ch);
   3823 	case '?':
   3824 		return ApplyModifier_IfElse(pp, ch);
   3825 	case '@':
   3826 		return ApplyModifier_Loop(pp, ch);
   3827 	case '[':
   3828 		return ApplyModifier_Words(pp, ch);
   3829 	case '_':
   3830 		return ApplyModifier_Remember(pp, ch);
   3831 	case 'C':
   3832 		return ApplyModifier_Regex(pp, ch);
   3833 	case 'D':
   3834 	case 'U':
   3835 		return ApplyModifier_Defined(pp, ch);
   3836 	case 'E':
   3837 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Suffix);
   3838 	case 'g':
   3839 	case 'l':
   3840 		return ApplyModifier_Time(pp, ch);
   3841 	case 'H':
   3842 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Head);
   3843 	case 'h':
   3844 		return ApplyModifier_Hash(pp, ch);
   3845 	case 'L':
   3846 		return ApplyModifier_Literal(pp, ch);
   3847 	case 'M':
   3848 	case 'N':
   3849 		return ApplyModifier_Match(pp, ch);
   3850 	case 'm':
   3851 		return ApplyModifier_Mtime(pp, ch);
   3852 	case 'O':
   3853 		return ApplyModifier_Order(pp, ch);
   3854 	case 'P':
   3855 		return ApplyModifier_Path(pp, ch);
   3856 	case 'Q':
   3857 	case 'q':
   3858 		return ApplyModifier_Quote(pp, ch);
   3859 	case 'R':
   3860 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Root);
   3861 	case 'r':
   3862 		return ApplyModifier_Range(pp, ch);
   3863 	case 'S':
   3864 		return ApplyModifier_Subst(pp, ch);
   3865 	case 's':
   3866 		return ApplyModifier_SunShell(pp, ch);
   3867 	case 'T':
   3868 		return ApplyModifier_WordFunc(pp, ch, ModifyWord_Tail);
   3869 	case 't':
   3870 		return ApplyModifier_To(pp, ch);
   3871 	case 'u':
   3872 		return ApplyModifier_Unique(pp, ch);
   3873 	default:
   3874 		return AMR_UNKNOWN;
   3875 	}
   3876 }
   3877 
   3878 static void ApplyModifiers(Expr *, const char **, char, char);
   3879 
   3880 typedef enum ApplyModifiersIndirectResult {
   3881 	/* The indirect modifiers have been applied successfully. */
   3882 	AMIR_CONTINUE,
   3883 	/* Fall back to the SysV modifier. */
   3884 	AMIR_SYSV,
   3885 	/* Error out. */
   3886 	AMIR_OUT
   3887 } ApplyModifiersIndirectResult;
   3888 
   3889 /*
   3890  * While expanding an expression, expand and apply indirect modifiers,
   3891  * such as in ${VAR:${M_indirect}}.
   3892  *
   3893  * All indirect modifiers of a group must come from a single
   3894  * expression.  ${VAR:${M1}} is valid but ${VAR:${M1}${M2}} is not.
   3895  *
   3896  * Multiple groups of indirect modifiers can be chained by separating them
   3897  * with colons.  ${VAR:${M1}:${M2}} contains 2 indirect modifiers.
   3898  *
   3899  * If the expression is not followed by ch->endc or ':', fall
   3900  * back to trying the SysV modifier, such as in ${VAR:${FROM}=${TO}}.
   3901  */
   3902 static ApplyModifiersIndirectResult
   3903 ApplyModifiersIndirect(ModChain *ch, const char **pp)
   3904 {
   3905 	Expr *expr = ch->expr;
   3906 	const char *p = *pp;
   3907 	FStr mods = Var_Parse(&p, expr->scope, expr->emode);
   3908 	/* TODO: handle errors */
   3909 
   3910 	if (mods.str[0] != '\0' && !IsDelimiter(*p, ch)) {
   3911 		FStr_Done(&mods);
   3912 		return AMIR_SYSV;
   3913 	}
   3914 
   3915 	DEBUG3(VAR, "Indirect modifier \"%s\" from \"%.*s\"\n",
   3916 	    mods.str, (int)(p - *pp), *pp);
   3917 
   3918 	if (ModChain_ShouldEval(ch) && mods.str[0] != '\0') {
   3919 		const char *modsp = mods.str;
   3920 		ApplyModifiers(expr, &modsp, '\0', '\0');
   3921 		if (Expr_Str(expr) == var_Error || *modsp != '\0') {
   3922 			FStr_Done(&mods);
   3923 			*pp = p;
   3924 			return AMIR_OUT;	/* error already reported */
   3925 		}
   3926 	}
   3927 	FStr_Done(&mods);
   3928 
   3929 	if (*p == ':')
   3930 		p++;
   3931 	else if (*p == '\0' && ch->endc != '\0') {
   3932 		Error("Unclosed expression after indirect modifier, "
   3933 		      "expecting '%c' for variable \"%s\"",
   3934 		    ch->endc, expr->name);
   3935 		*pp = p;
   3936 		return AMIR_OUT;
   3937 	}
   3938 
   3939 	*pp = p;
   3940 	return AMIR_CONTINUE;
   3941 }
   3942 
   3943 static ApplyModifierResult
   3944 ApplySingleModifier(const char **pp, ModChain *ch)
   3945 {
   3946 	ApplyModifierResult res;
   3947 	const char *mod = *pp;
   3948 	const char *p = *pp;
   3949 
   3950 	if (DEBUG(VAR))
   3951 		LogBeforeApply(ch, mod);
   3952 
   3953 	res = ApplyModifier(&p, ch);
   3954 
   3955 	if (res == AMR_UNKNOWN) {
   3956 		assert(p == mod);
   3957 		res = ApplyModifier_SysV(&p, ch);
   3958 	}
   3959 
   3960 	if (res == AMR_UNKNOWN) {
   3961 		/*
   3962 		 * Guess the end of the current modifier.
   3963 		 * XXX: Skipping the rest of the modifier hides
   3964 		 * errors and leads to wrong results.
   3965 		 * Parsing should rather stop here.
   3966 		 */
   3967 		for (p++; !IsDelimiter(*p, ch); p++)
   3968 			continue;
   3969 		Parse_Error(PARSE_FATAL, "Unknown modifier \"%.*s\"",
   3970 		    (int)(p - mod), mod);
   3971 		Expr_SetValueRefer(ch->expr, var_Error);
   3972 	}
   3973 	if (res == AMR_CLEANUP || res == AMR_BAD) {
   3974 		*pp = p;
   3975 		return res;
   3976 	}
   3977 
   3978 	if (DEBUG(VAR))
   3979 		LogAfterApply(ch, p, mod);
   3980 
   3981 	if (*p == '\0' && ch->endc != '\0') {
   3982 		Error(
   3983 		    "Unclosed expression, expecting '%c' for "
   3984 		    "modifier \"%.*s\" of variable \"%s\" with value \"%s\"",
   3985 		    ch->endc,
   3986 		    (int)(p - mod), mod,
   3987 		    ch->expr->name, Expr_Str(ch->expr));
   3988 	} else if (*p == ':') {
   3989 		p++;
   3990 	} else if (opts.strict && *p != '\0' && *p != ch->endc) {
   3991 		Parse_Error(PARSE_FATAL,
   3992 		    "Missing delimiter ':' after modifier \"%.*s\"",
   3993 		    (int)(p - mod), mod);
   3994 		/*
   3995 		 * TODO: propagate parse error to the enclosing
   3996 		 * expression
   3997 		 */
   3998 	}
   3999 	*pp = p;
   4000 	return AMR_OK;
   4001 }
   4002 
   4003 #if __STDC_VERSION__ >= 199901L
   4004 #define ModChain_Init(expr, startc, endc, sep, oneBigWord) \
   4005 	(ModChain) { expr, startc, endc, sep, oneBigWord }
   4006 #else
   4007 MAKE_INLINE ModChain
   4008 ModChain_Init(Expr *expr, char startc, char endc, char sep, bool oneBigWord)
   4009 {
   4010 	ModChain ch;
   4011 	ch.expr = expr;
   4012 	ch.startc = startc;
   4013 	ch.endc = endc;
   4014 	ch.sep = sep;
   4015 	ch.oneBigWord = oneBigWord;
   4016 	return ch;
   4017 }
   4018 #endif
   4019 
   4020 /* Apply any modifiers (such as :Mpattern or :@var@loop@ or :Q or ::=value). */
   4021 static void
   4022 ApplyModifiers(
   4023     Expr *expr,
   4024     const char **pp,	/* the parsing position, updated upon return */
   4025     char startc,	/* '(' or '{'; or '\0' for indirect modifiers */
   4026     char endc		/* ')' or '}'; or '\0' for indirect modifiers */
   4027 )
   4028 {
   4029 	ModChain ch = ModChain_Init(expr, startc, endc, ' ', false);
   4030 	const char *p;
   4031 	const char *mod;
   4032 
   4033 	assert(startc == '(' || startc == '{' || startc == '\0');
   4034 	assert(endc == ')' || endc == '}' || endc == '\0');
   4035 	assert(Expr_Str(expr) != NULL);
   4036 
   4037 	p = *pp;
   4038 
   4039 	if (*p == '\0' && endc != '\0') {
   4040 		Error(
   4041 		    "Unclosed expression, expecting '%c' for \"%s\"",
   4042 		    ch.endc, expr->name);
   4043 		goto cleanup;
   4044 	}
   4045 
   4046 	while (*p != '\0' && *p != endc) {
   4047 		ApplyModifierResult res;
   4048 
   4049 		if (*p == '$') {
   4050 			/*
   4051 			 * TODO: Only evaluate the expression once, no matter
   4052 			 * whether it's an indirect modifier or the initial
   4053 			 * part of a SysV modifier.
   4054 			 */
   4055 			ApplyModifiersIndirectResult amir =
   4056 			    ApplyModifiersIndirect(&ch, &p);
   4057 			if (amir == AMIR_CONTINUE)
   4058 				continue;
   4059 			if (amir == AMIR_OUT)
   4060 				break;
   4061 		}
   4062 
   4063 		mod = p;
   4064 
   4065 		res = ApplySingleModifier(&p, &ch);
   4066 		if (res == AMR_CLEANUP)
   4067 			goto cleanup;
   4068 		if (res == AMR_BAD)
   4069 			goto bad_modifier;
   4070 	}
   4071 
   4072 	*pp = p;
   4073 	assert(Expr_Str(expr) != NULL);	/* Use var_Error or varUndefined. */
   4074 	return;
   4075 
   4076 bad_modifier:
   4077 	/* Take a guess at where the modifier ends. */
   4078 	Error("Bad modifier \":%.*s\" for variable \"%s\"",
   4079 	    (int)strcspn(mod, ":)}"), mod, expr->name);
   4080 
   4081 cleanup:
   4082 	/*
   4083 	 * TODO: Use p + strlen(p) instead, to stop parsing immediately.
   4084 	 *
   4085 	 * In the unit tests, this generates a few shell commands with
   4086 	 * unbalanced quotes.  Instead of producing these incomplete strings,
   4087 	 * commands with evaluation errors should not be run at all.
   4088 	 *
   4089 	 * To make that happen, Var_Subst must report the actual errors
   4090 	 * instead of returning the resulting string unconditionally.
   4091 	 */
   4092 	*pp = p;
   4093 	Expr_SetValueRefer(expr, var_Error);
   4094 }
   4095 
   4096 /*
   4097  * Only 4 of the 7 built-in local variables are treated specially as they are
   4098  * the only ones that will be set when dynamic sources are expanded.
   4099  */
   4100 static bool
   4101 VarnameIsDynamic(Substring varname)
   4102 {
   4103 	const char *name;
   4104 	size_t len;
   4105 
   4106 	name = varname.start;
   4107 	len = Substring_Length(varname);
   4108 	if (len == 1 || (len == 2 && (name[1] == 'F' || name[1] == 'D'))) {
   4109 		switch (name[0]) {
   4110 		case '@':
   4111 		case '%':
   4112 		case '*':
   4113 		case '!':
   4114 			return true;
   4115 		}
   4116 		return false;
   4117 	}
   4118 
   4119 	if ((len == 7 || len == 8) && name[0] == '.' && ch_isupper(name[1])) {
   4120 		return Substring_Equals(varname, ".TARGET") ||
   4121 		       Substring_Equals(varname, ".ARCHIVE") ||
   4122 		       Substring_Equals(varname, ".PREFIX") ||
   4123 		       Substring_Equals(varname, ".MEMBER");
   4124 	}
   4125 
   4126 	return false;
   4127 }
   4128 
   4129 static const char *
   4130 UndefinedShortVarValue(char varname, const GNode *scope)
   4131 {
   4132 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL) {
   4133 		/*
   4134 		 * If substituting a local variable in a non-local scope,
   4135 		 * assume it's for dynamic source stuff. We have to handle
   4136 		 * this specially and return the longhand for the variable
   4137 		 * with the dollar sign escaped so it makes it back to the
   4138 		 * caller. Only four of the local variables are treated
   4139 		 * specially as they are the only four that will be set
   4140 		 * when dynamic sources are expanded.
   4141 		 */
   4142 		switch (varname) {
   4143 		case '@':
   4144 			return "$(.TARGET)";
   4145 		case '%':
   4146 			return "$(.MEMBER)";
   4147 		case '*':
   4148 			return "$(.PREFIX)";
   4149 		case '!':
   4150 			return "$(.ARCHIVE)";
   4151 		}
   4152 	}
   4153 	return NULL;
   4154 }
   4155 
   4156 /*
   4157  * Parse a variable name, until the end character or a colon, whichever
   4158  * comes first.
   4159  */
   4160 static void
   4161 ParseVarname(const char **pp, char startc, char endc,
   4162 	     GNode *scope, VarEvalMode emode,
   4163 	     LazyBuf *buf)
   4164 {
   4165 	const char *p = *pp;
   4166 	int depth = 0;
   4167 
   4168 	LazyBuf_Init(buf, p);
   4169 
   4170 	while (*p != '\0') {
   4171 		if ((*p == endc || *p == ':') && depth == 0)
   4172 			break;
   4173 		if (*p == startc)
   4174 			depth++;
   4175 		if (*p == endc)
   4176 			depth--;
   4177 
   4178 		if (*p == '$') {
   4179 			FStr nested_val = Var_Parse(&p, scope, emode);
   4180 			/* TODO: handle errors */
   4181 			LazyBuf_AddStr(buf, nested_val.str);
   4182 			FStr_Done(&nested_val);
   4183 		} else {
   4184 			LazyBuf_Add(buf, *p);
   4185 			p++;
   4186 		}
   4187 	}
   4188 	*pp = p;
   4189 }
   4190 
   4191 static bool
   4192 IsShortVarnameValid(char varname, const char *start)
   4193 {
   4194 	if (varname != '$' && varname != ':' && varname != '}' &&
   4195 	    varname != ')' && varname != '\0')
   4196 		return true;
   4197 
   4198 	if (!opts.strict)
   4199 		return false;	/* XXX: Missing error message */
   4200 
   4201 	if (varname == '$' && save_dollars)
   4202 		Parse_Error(PARSE_FATAL,
   4203 		    "To escape a dollar, use \\$, not $$, at \"%s\"", start);
   4204 	else if (varname == '\0')
   4205 		Parse_Error(PARSE_FATAL, "Dollar followed by nothing");
   4206 	else if (save_dollars)
   4207 		Parse_Error(PARSE_FATAL,
   4208 		    "Invalid variable name '%c', at \"%s\"", varname, start);
   4209 
   4210 	return false;
   4211 }
   4212 
   4213 /*
   4214  * Parse a single-character variable name such as in $V or $@.
   4215  * Return whether to continue parsing.
   4216  */
   4217 static bool
   4218 ParseVarnameShort(char varname, const char **pp, GNode *scope,
   4219 		  VarEvalMode emode,
   4220 		  const char **out_false_val,
   4221 		  Var **out_true_var)
   4222 {
   4223 	char name[2];
   4224 	Var *v;
   4225 	const char *val;
   4226 
   4227 	if (!IsShortVarnameValid(varname, *pp)) {
   4228 		(*pp)++;	/* only skip the '$' */
   4229 		*out_false_val = var_Error;
   4230 		return false;
   4231 	}
   4232 
   4233 	name[0] = varname;
   4234 	name[1] = '\0';
   4235 	v = VarFind(name, scope, true);
   4236 	if (v != NULL) {
   4237 		/* No need to advance *pp, the calling code handles this. */
   4238 		*out_true_var = v;
   4239 		return true;
   4240 	}
   4241 
   4242 	*pp += 2;
   4243 
   4244 	val = UndefinedShortVarValue(varname, scope);
   4245 	if (val == NULL)
   4246 		val = emode == VARE_UNDEFERR ? var_Error : varUndefined;
   4247 
   4248 	if (opts.strict && val == var_Error) {
   4249 		Parse_Error(PARSE_FATAL,
   4250 		    "Variable \"%s\" is undefined", name);
   4251 	}
   4252 
   4253 	*out_false_val = val;
   4254 	return false;
   4255 }
   4256 
   4257 /* Find variables like @F or <D. */
   4258 static Var *
   4259 FindLocalLegacyVar(Substring varname, GNode *scope,
   4260 		   const char **out_extraModifiers)
   4261 {
   4262 	Var *v;
   4263 
   4264 	/* Only resolve these variables if scope is a "real" target. */
   4265 	if (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL)
   4266 		return NULL;
   4267 
   4268 	if (Substring_Length(varname) != 2)
   4269 		return NULL;
   4270 	if (varname.start[1] != 'F' && varname.start[1] != 'D')
   4271 		return NULL;
   4272 	if (strchr("@%?*!<>", varname.start[0]) == NULL)
   4273 		return NULL;
   4274 
   4275 	v = VarFindSubstring(Substring_Init(varname.start, varname.start + 1),
   4276 	    scope, false);
   4277 	if (v == NULL)
   4278 		return NULL;
   4279 
   4280 	*out_extraModifiers = varname.start[1] == 'D' ? "H:" : "T:";
   4281 	return v;
   4282 }
   4283 
   4284 static FStr
   4285 EvalUndefined(bool dynamic, const char *start, const char *p,
   4286 	      Substring varname, VarEvalMode emode)
   4287 {
   4288 	if (dynamic)
   4289 		return FStr_InitOwn(bmake_strsedup(start, p));
   4290 
   4291 	if (emode == VARE_UNDEFERR && opts.strict) {
   4292 		Parse_Error(PARSE_FATAL,
   4293 		    "Variable \"%.*s\" is undefined",
   4294 		    (int)Substring_Length(varname), varname.start);
   4295 		return FStr_InitRefer(var_Error);
   4296 	}
   4297 
   4298 	return FStr_InitRefer(
   4299 	    emode == VARE_UNDEFERR ? var_Error : varUndefined);
   4300 }
   4301 
   4302 /*
   4303  * Parse a long variable name enclosed in braces or parentheses such as $(VAR)
   4304  * or ${VAR}, up to the closing brace or parenthesis, or in the case of
   4305  * ${VAR:Modifiers}, up to the ':' that starts the modifiers.
   4306  * Return whether to continue parsing.
   4307  */
   4308 static bool
   4309 ParseVarnameLong(
   4310 	const char **pp,
   4311 	char startc,
   4312 	GNode *scope,
   4313 	VarEvalMode emode,
   4314 
   4315 	const char **out_false_pp,
   4316 	FStr *out_false_val,
   4317 
   4318 	char *out_true_endc,
   4319 	Var **out_true_v,
   4320 	bool *out_true_haveModifier,
   4321 	const char **out_true_extraModifiers,
   4322 	bool *out_true_dynamic,
   4323 	ExprDefined *out_true_exprDefined
   4324 )
   4325 {
   4326 	LazyBuf varname;
   4327 	Substring name;
   4328 	Var *v;
   4329 	bool haveModifier;
   4330 	bool dynamic = false;
   4331 
   4332 	const char *p = *pp;
   4333 	const char *start = p;
   4334 	char endc = startc == '(' ? ')' : '}';
   4335 
   4336 	p += 2;			/* skip "${" or "$(" or "y(" */
   4337 	ParseVarname(&p, startc, endc, scope, emode, &varname);
   4338 	name = LazyBuf_Get(&varname);
   4339 
   4340 	if (*p == ':')
   4341 		haveModifier = true;
   4342 	else if (*p == endc)
   4343 		haveModifier = false;
   4344 	else {
   4345 		Parse_Error(PARSE_FATAL, "Unclosed variable \"%.*s\"",
   4346 		    (int)Substring_Length(name), name.start);
   4347 		LazyBuf_Done(&varname);
   4348 		*out_false_pp = p;
   4349 		*out_false_val = FStr_InitRefer(var_Error);
   4350 		return false;
   4351 	}
   4352 
   4353 	v = VarFindSubstring(name, scope, true);
   4354 
   4355 	/*
   4356 	 * At this point, p points just after the variable name, either at
   4357 	 * ':' or at endc.
   4358 	 */
   4359 
   4360 	if (v == NULL && Substring_Equals(name, ".SUFFIXES")) {
   4361 		char *suffixes = Suff_NamesStr();
   4362 		v = VarNew(FStr_InitRefer(".SUFFIXES"), suffixes,
   4363 		    true, false, true);
   4364 		free(suffixes);
   4365 	} else if (v == NULL)
   4366 		v = FindLocalLegacyVar(name, scope, out_true_extraModifiers);
   4367 
   4368 	if (v == NULL) {
   4369 		/*
   4370 		 * Defer expansion of dynamic variables if they appear in
   4371 		 * non-local scope since they are not defined there.
   4372 		 */
   4373 		dynamic = VarnameIsDynamic(name) &&
   4374 			  (scope == SCOPE_CMDLINE || scope == SCOPE_GLOBAL);
   4375 
   4376 		if (!haveModifier) {
   4377 			p++;	/* skip endc */
   4378 			*out_false_pp = p;
   4379 			*out_false_val = EvalUndefined(dynamic, start, p,
   4380 			    name, emode);
   4381 			LazyBuf_Done(&varname);
   4382 			return false;
   4383 		}
   4384 
   4385 		/*
   4386 		 * The expression is based on an undefined variable.
   4387 		 * Nevertheless it needs a Var, for modifiers that access the
   4388 		 * variable name, such as :L or :?.
   4389 		 *
   4390 		 * Most modifiers leave this expression in the "undefined"
   4391 		 * state (DEF_UNDEF), only a few modifiers like :D, :U, :L,
   4392 		 * :P turn this undefined expression into a defined
   4393 		 * expression (DEF_DEFINED).
   4394 		 *
   4395 		 * In the end, after applying all modifiers, if the expression
   4396 		 * is still undefined, Var_Parse will return an empty string
   4397 		 * instead of the actually computed value.
   4398 		 */
   4399 		v = VarNew(LazyBuf_DoneGet(&varname), "",
   4400 		    true, false, false);
   4401 		*out_true_exprDefined = DEF_UNDEF;
   4402 	} else
   4403 		LazyBuf_Done(&varname);
   4404 
   4405 	*pp = p;
   4406 	*out_true_endc = endc;
   4407 	*out_true_v = v;
   4408 	*out_true_haveModifier = haveModifier;
   4409 	*out_true_dynamic = dynamic;
   4410 	return true;
   4411 }
   4412 
   4413 #if __STDC_VERSION__ >= 199901L
   4414 #define Expr_Init(name, value, emode, scope, defined) \
   4415 	(Expr) { name, value, emode, scope, defined }
   4416 #else
   4417 MAKE_INLINE Expr
   4418 Expr_Init(const char *name, FStr value,
   4419 	  VarEvalMode emode, GNode *scope, ExprDefined defined)
   4420 {
   4421 	Expr expr;
   4422 
   4423 	expr.name = name;
   4424 	expr.value = value;
   4425 	expr.emode = emode;
   4426 	expr.scope = scope;
   4427 	expr.defined = defined;
   4428 	return expr;
   4429 }
   4430 #endif
   4431 
   4432 /*
   4433  * Expressions of the form ${:U...} with a trivial value are often generated
   4434  * by .for loops and are boring, so evaluate them without debug logging.
   4435  */
   4436 static bool
   4437 Var_Parse_U(const char **pp, VarEvalMode emode, FStr *out_value)
   4438 {
   4439 	const char *p;
   4440 
   4441 	p = *pp;
   4442 	if (!(p[0] == '$' && p[1] == '{' && p[2] == ':' && p[3] == 'U'))
   4443 		return false;
   4444 
   4445 	p += 4;
   4446 	while (*p != '$' && *p != '{' && *p != ':' && *p != '\\' &&
   4447 	       *p != '}' && *p != '\0')
   4448 		p++;
   4449 	if (*p != '}')
   4450 		return false;
   4451 
   4452 	*out_value = emode == VARE_PARSE_ONLY
   4453 	    ? FStr_InitRefer("")
   4454 	    : FStr_InitOwn(bmake_strsedup(*pp + 4, p));
   4455 	*pp = p + 1;
   4456 	return true;
   4457 }
   4458 
   4459 /*
   4460  * Given the start of an expression (such as $v, $(VAR), ${VAR:Mpattern}),
   4461  * extract the variable name and the modifiers, if any.  While parsing, apply
   4462  * the modifiers to the value of the expression.
   4463  *
   4464  * Input:
   4465  *	*pp		The string to parse.
   4466  *			When called from CondParser_FuncCallEmpty, it can
   4467  *			also point to the "y" of "empty(VARNAME:Modifiers)".
   4468  *	scope		The scope for finding variables.
   4469  *	emode		Controls the exact details of parsing and evaluation.
   4470  *
   4471  * Output:
   4472  *	*pp		The position where to continue parsing.
   4473  *			TODO: After a parse error, the value of *pp is
   4474  *			unspecified.  It may not have been updated at all,
   4475  *			point to some random character in the string, to the
   4476  *			location of the parse error, or at the end of the
   4477  *			string.
   4478  *	return		The value of the expression, never NULL.
   4479  *	return		var_Error if there was a parse error.
   4480  *	return		var_Error if the base variable of the expression was
   4481  *			undefined, emode is VARE_UNDEFERR, and none of
   4482  *			the modifiers turned the undefined expression into a
   4483  *			defined expression.
   4484  *			XXX: It is not guaranteed that an error message has
   4485  *			been printed.
   4486  *	return		varUndefined if the base variable of the expression
   4487  *			was undefined, emode was not VARE_UNDEFERR,
   4488  *			and none of the modifiers turned the undefined
   4489  *			expression into a defined expression.
   4490  *			XXX: It is not guaranteed that an error message has
   4491  *			been printed.
   4492  */
   4493 FStr
   4494 Var_Parse(const char **pp, GNode *scope, VarEvalMode emode)
   4495 {
   4496 	const char *start, *p;
   4497 	bool haveModifier;	/* true for ${VAR:...}, false for ${VAR} */
   4498 	char startc;		/* the actual '{' or '(' or '\0' */
   4499 	char endc;		/* the expected '}' or ')' or '\0' */
   4500 	/*
   4501 	 * true if the expression is based on one of the 7 predefined
   4502 	 * variables that are local to a target, and the expression is
   4503 	 * expanded in a non-local scope.  The result is the text of the
   4504 	 * expression, unaltered.  This is needed to support dynamic sources.
   4505 	 */
   4506 	bool dynamic;
   4507 	const char *extramodifiers;
   4508 	Var *v;
   4509 	Expr expr = Expr_Init(NULL, FStr_InitRefer(NULL), emode,
   4510 	    scope, DEF_REGULAR);
   4511 	FStr val;
   4512 
   4513 	if (Var_Parse_U(pp, emode, &val))
   4514 		return val;
   4515 
   4516 	p = *pp;
   4517 	start = p;
   4518 	DEBUG2(VAR, "Var_Parse: %s (%s)\n", start, VarEvalMode_Name[emode]);
   4519 
   4520 	val = FStr_InitRefer(NULL);
   4521 	extramodifiers = NULL;	/* extra modifiers to apply first */
   4522 	dynamic = false;
   4523 
   4524 	endc = '\0';		/* Appease GCC. */
   4525 
   4526 	startc = p[1];
   4527 	if (startc != '(' && startc != '{') {
   4528 		if (!ParseVarnameShort(startc, pp, scope, emode, &val.str, &v))
   4529 			return val;
   4530 		haveModifier = false;
   4531 		p++;
   4532 	} else {
   4533 		if (!ParseVarnameLong(&p, startc, scope, emode,
   4534 		    pp, &val,
   4535 		    &endc, &v, &haveModifier, &extramodifiers,
   4536 		    &dynamic, &expr.defined))
   4537 			return val;
   4538 	}
   4539 
   4540 	expr.name = v->name.str;
   4541 	if (v->inUse && VarEvalMode_ShouldEval(emode)) {
   4542 		if (scope->fname != NULL) {
   4543 			fprintf(stderr, "In a command near ");
   4544 			PrintLocation(stderr, false, scope);
   4545 		}
   4546 		Fatal("Variable %s is recursive.", v->name.str);
   4547 	}
   4548 
   4549 	/*
   4550 	 * FIXME: This assignment creates an alias to the current value of the
   4551 	 * variable.  This means that as long as the value of the expression
   4552 	 * stays the same, the value of the variable must not change, and the
   4553 	 * variable must not be deleted.  Using the ':@' modifier, it is
   4554 	 * possible (since var.c 1.212 from 2017-02-01) to delete the variable
   4555 	 * while its value is still being used:
   4556 	 *
   4557 	 *	VAR=	value
   4558 	 *	_:=	${VAR:${:U:@VAR@@}:S,^,prefix,}
   4559 	 *
   4560 	 * The same effect might be achievable using the '::=' or the ':_'
   4561 	 * modifiers.
   4562 	 *
   4563 	 * At the bottom of this function, the resulting value is compared to
   4564 	 * the then-current value of the variable.  This might also invoke
   4565 	 * undefined behavior.
   4566 	 */
   4567 	expr.value = FStr_InitRefer(v->val.data);
   4568 
   4569 	if (expr.name[0] != '\0')
   4570 		EvalStack_Push(NULL, NULL, expr.name);
   4571 	else
   4572 		EvalStack_Push(NULL, start, NULL);
   4573 
   4574 	/*
   4575 	 * Before applying any modifiers, expand any nested expressions from
   4576 	 * the variable value.
   4577 	 */
   4578 	if (VarEvalMode_ShouldEval(emode) &&
   4579 	    strchr(Expr_Str(&expr), '$') != NULL) {
   4580 		char *expanded;
   4581 		VarEvalMode nested_emode = emode;
   4582 		if (opts.strict)
   4583 			nested_emode = VarEvalMode_UndefOk(nested_emode);
   4584 		v->inUse = true;
   4585 		expanded = Var_Subst(Expr_Str(&expr), scope, nested_emode);
   4586 		v->inUse = false;
   4587 		/* TODO: handle errors */
   4588 		Expr_SetValueOwn(&expr, expanded);
   4589 	}
   4590 
   4591 	if (extramodifiers != NULL) {
   4592 		const char *em = extramodifiers;
   4593 		ApplyModifiers(&expr, &em, '\0', '\0');
   4594 	}
   4595 
   4596 	if (haveModifier) {
   4597 		p++;		/* Skip initial colon. */
   4598 		ApplyModifiers(&expr, &p, startc, endc);
   4599 	}
   4600 
   4601 	if (*p != '\0')		/* Skip past endc if possible. */
   4602 		p++;
   4603 
   4604 	*pp = p;
   4605 
   4606 	if (expr.defined == DEF_UNDEF) {
   4607 		if (dynamic)
   4608 			Expr_SetValueOwn(&expr, bmake_strsedup(start, p));
   4609 		else {
   4610 			/*
   4611 			 * The expression is still undefined, therefore
   4612 			 * discard the actual value and return an error marker
   4613 			 * instead.
   4614 			 */
   4615 			Expr_SetValueRefer(&expr,
   4616 			    emode == VARE_UNDEFERR
   4617 				? var_Error : varUndefined);
   4618 		}
   4619 	}
   4620 
   4621 	if (v->shortLived) {
   4622 		if (expr.value.str == v->val.data) {
   4623 			/* move ownership */
   4624 			expr.value.freeIt = v->val.data;
   4625 			v->val.data = NULL;
   4626 		}
   4627 		VarFreeShortLived(v);
   4628 	}
   4629 
   4630 	EvalStack_Pop();
   4631 	return expr.value;
   4632 }
   4633 
   4634 static void
   4635 VarSubstDollarDollar(const char **pp, Buffer *res, VarEvalMode emode)
   4636 {
   4637 	/* A dollar sign may be escaped with another dollar sign. */
   4638 	if (save_dollars && VarEvalMode_ShouldKeepDollar(emode))
   4639 		Buf_AddByte(res, '$');
   4640 	Buf_AddByte(res, '$');
   4641 	*pp += 2;
   4642 }
   4643 
   4644 static void
   4645 VarSubstExpr(const char **pp, Buffer *buf, GNode *scope,
   4646 	     VarEvalMode emode, bool *inout_errorReported)
   4647 {
   4648 	const char *p = *pp;
   4649 	const char *nested_p = p;
   4650 	FStr val = Var_Parse(&nested_p, scope, emode);
   4651 	/* TODO: handle errors */
   4652 
   4653 	if (val.str == var_Error || val.str == varUndefined) {
   4654 		if (!VarEvalMode_ShouldKeepUndef(emode)) {
   4655 			p = nested_p;
   4656 		} else if (val.str == var_Error) {
   4657 
   4658 			/*
   4659 			 * FIXME: The condition 'val.str == var_Error' doesn't
   4660 			 * mean there was an undefined variable.  It could
   4661 			 * equally well be a parse error; see
   4662 			 * unit-tests/varmod-order.mk.
   4663 			 */
   4664 
   4665 			/*
   4666 			 * If variable is undefined, complain and skip the
   4667 			 * variable. The complaint will stop us from doing
   4668 			 * anything when the file is parsed.
   4669 			 */
   4670 			if (!*inout_errorReported) {
   4671 				Parse_Error(PARSE_FATAL,
   4672 				    "Undefined variable \"%.*s\"",
   4673 				    (int)(nested_p - p), p);
   4674 				*inout_errorReported = true;
   4675 			}
   4676 			p = nested_p;
   4677 		} else {
   4678 			/*
   4679 			 * Copy the initial '$' of the undefined expression,
   4680 			 * thereby deferring expansion of the expression, but
   4681 			 * expand nested expressions if already possible. See
   4682 			 * unit-tests/varparse-undef-partial.mk.
   4683 			 */
   4684 			Buf_AddByte(buf, *p);
   4685 			p++;
   4686 		}
   4687 	} else {
   4688 		p = nested_p;
   4689 		Buf_AddStr(buf, val.str);
   4690 	}
   4691 
   4692 	FStr_Done(&val);
   4693 
   4694 	*pp = p;
   4695 }
   4696 
   4697 /*
   4698  * Skip as many characters as possible -- either to the end of the string,
   4699  * or to the next dollar sign, which may start an expression.
   4700  */
   4701 static void
   4702 VarSubstPlain(const char **pp, Buffer *res)
   4703 {
   4704 	const char *p = *pp;
   4705 	const char *start = p;
   4706 
   4707 	for (p++; *p != '$' && *p != '\0'; p++)
   4708 		continue;
   4709 	Buf_AddRange(res, start, p);
   4710 	*pp = p;
   4711 }
   4712 
   4713 /*
   4714  * Expand all expressions like $V, ${VAR}, $(VAR:Modifiers) in the
   4715  * given string.
   4716  *
   4717  * Input:
   4718  *	str		The string in which the expressions are expanded.
   4719  *	scope		The scope in which to start searching for variables.
   4720  *			The other scopes are searched as well.
   4721  *	emode		The mode for parsing or evaluating subexpressions.
   4722  */
   4723 char *
   4724 Var_Subst(const char *str, GNode *scope, VarEvalMode emode)
   4725 {
   4726 	const char *p = str;
   4727 	Buffer res;
   4728 
   4729 	/*
   4730 	 * Set true if an error has already been reported, to prevent a
   4731 	 * plethora of messages when recursing
   4732 	 */
   4733 	static bool errorReported;
   4734 
   4735 	Buf_Init(&res);
   4736 	errorReported = false;
   4737 
   4738 	while (*p != '\0') {
   4739 		if (p[0] == '$' && p[1] == '$')
   4740 			VarSubstDollarDollar(&p, &res, emode);
   4741 		else if (p[0] == '$')
   4742 			VarSubstExpr(&p, &res, scope, emode, &errorReported);
   4743 		else
   4744 			VarSubstPlain(&p, &res);
   4745 	}
   4746 
   4747 	return Buf_DoneData(&res);
   4748 }
   4749 
   4750 void
   4751 Var_Expand(FStr *str, GNode *scope, VarEvalMode emode)
   4752 {
   4753 	char *expanded;
   4754 
   4755 	if (strchr(str->str, '$') == NULL)
   4756 		return;
   4757 	expanded = Var_Subst(str->str, scope, emode);
   4758 	/* TODO: handle errors */
   4759 	FStr_Done(str);
   4760 	*str = FStr_InitOwn(expanded);
   4761 }
   4762 
   4763 /* Initialize the variables module. */
   4764 void
   4765 Var_Init(void)
   4766 {
   4767 	SCOPE_INTERNAL = GNode_New("Internal");
   4768 	SCOPE_GLOBAL = GNode_New("Global");
   4769 	SCOPE_CMDLINE = GNode_New("Command");
   4770 }
   4771 
   4772 /* Clean up the variables module. */
   4773 void
   4774 Var_End(void)
   4775 {
   4776 	Var_Stats();
   4777 }
   4778 
   4779 void
   4780 Var_Stats(void)
   4781 {
   4782 	HashTable_DebugStats(&SCOPE_GLOBAL->vars, "Global variables");
   4783 }
   4784 
   4785 static int
   4786 StrAsc(const void *sa, const void *sb)
   4787 {
   4788 	return strcmp(
   4789 	    *((const char *const *)sa), *((const char *const *)sb));
   4790 }
   4791 
   4792 
   4793 /* Print all variables in a scope, sorted by name. */
   4794 void
   4795 Var_Dump(GNode *scope)
   4796 {
   4797 	Vector /* of const char * */ vec;
   4798 	HashIter hi;
   4799 	size_t i;
   4800 	const char **varnames;
   4801 
   4802 	Vector_Init(&vec, sizeof(const char *));
   4803 
   4804 	HashIter_Init(&hi, &scope->vars);
   4805 	while (HashIter_Next(&hi) != NULL)
   4806 		*(const char **)Vector_Push(&vec) = hi.entry->key;
   4807 	varnames = vec.items;
   4808 
   4809 	qsort(varnames, vec.len, sizeof varnames[0], StrAsc);
   4810 
   4811 	for (i = 0; i < vec.len; i++) {
   4812 		const char *varname = varnames[i];
   4813 		const Var *var = HashTable_FindValue(&scope->vars, varname);
   4814 		debug_printf("%-16s = %s%s\n", varname,
   4815 		    var->val.data, ValueDescription(var->val.data));
   4816 	}
   4817 
   4818 	Vector_Done(&vec);
   4819 }
   4820