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