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