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