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