Sun Mar 14 18:23:44 2021 UTC ()
make: don't evaluate several simple modifiers in parse-only mode

This affects the modifiers ':E', ':H', ':P', ':Q', ':R', ':T', ':hash',
':q', ':range', ':tl', ':ts', ':tu', and ':u'.  All these modifiers are
side-effect free.

Skipping the evaluation for these modifiers is purely for code
consistency and performance.

No functional change.


(rillig)
diff -r1.872 -r1.873 src/usr.bin/make/var.c

cvs diff -r1.872 -r1.873 src/usr.bin/make/var.c (switch to unified diff)

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