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