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