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