Home | History | Annotate | Line # | Download | only in make
parse.c revision 1.724
      1 /*	$NetBSD: parse.c,v 1.724 2024/05/25 00:00:25 rillig Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1988, 1989, 1990, 1993
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Adam de Boor.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. Neither the name of the University nor the names of its contributors
     19  *    may be used to endorse or promote products derived from this software
     20  *    without specific prior written permission.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     32  * SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1989 by Berkeley Softworks
     37  * All rights reserved.
     38  *
     39  * This code is derived from software contributed to Berkeley by
     40  * Adam de Boor.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. All advertising materials mentioning features or use of this software
     51  *    must display the following acknowledgement:
     52  *	This product includes software developed by the University of
     53  *	California, Berkeley and its contributors.
     54  * 4. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 /*
     72  * Parsing of makefiles.
     73  *
     74  * Parse_File is the main entry point and controls most of the other
     75  * functions in this module.
     76  *
     77  * Interface:
     78  *	Parse_Init	Initialize the module
     79  *
     80  *	Parse_End	Clean up the module
     81  *
     82  *	Parse_File	Parse a top-level makefile.  Included files are
     83  *			handled by IncludeFile instead.
     84  *
     85  *	Parse_VarAssign
     86  *			Try to parse the given line as a variable assignment.
     87  *			Used by MainParseArgs to determine if an argument is
     88  *			a target or a variable assignment.  Used internally
     89  *			for pretty much the same thing.
     90  *
     91  *	Parse_Error	Report a parse error, a warning or an informational
     92  *			message.
     93  *
     94  *	Parse_MainName	Populate the list of targets to create.
     95  */
     96 
     97 #include <sys/types.h>
     98 #include <sys/stat.h>
     99 #include <errno.h>
    100 #include <stdarg.h>
    101 
    102 #include "make.h"
    103 #include "dir.h"
    104 #include "job.h"
    105 #include "pathnames.h"
    106 
    107 /*	"@(#)parse.c	8.3 (Berkeley) 3/19/94"	*/
    108 MAKE_RCSID("$NetBSD: parse.c,v 1.724 2024/05/25 00:00:25 rillig Exp $");
    109 
    110 /* Detects a multiple-inclusion guard in a makefile. */
    111 typedef enum {
    112 	GS_START,		/* at the beginning of the file */
    113 	GS_COND,		/* after the guard condition */
    114 	GS_DONE,		/* after the closing .endif */
    115 	GS_NO			/* the file is not guarded */
    116 } GuardState;
    117 
    118 /* A file being parsed. */
    119 typedef struct IncludedFile {
    120 	FStr name;		/* absolute or relative to the cwd */
    121 	unsigned lineno;	/* 1-based */
    122 	unsigned readLines;	/* the number of physical lines that have
    123 				 * been read from the file */
    124 	unsigned forHeadLineno;	/* 1-based */
    125 	unsigned forBodyReadLines; /* the number of physical lines that have
    126 				 * been read from the file above the body of
    127 				 * the .for loop */
    128 	unsigned int condMinDepth; /* depth of nested 'if' directives, at the
    129 				 * beginning of the file */
    130 	bool depending;		/* state of doing_depend on EOF */
    131 
    132 	Buffer buf;		/* the file's content or the body of the .for
    133 				 * loop; either empty or ends with '\n' */
    134 	char *buf_ptr;		/* next char to be read from buf */
    135 	char *buf_end;		/* buf_end[-1] == '\n' */
    136 
    137 	GuardState guardState;
    138 	Guard *guard;
    139 
    140 	struct ForLoop *forLoop;
    141 } IncludedFile;
    142 
    143 /* Special attributes for target nodes. */
    144 typedef enum ParseSpecial {
    145 	SP_ATTRIBUTE,	/* Generic attribute */
    146 	SP_BEGIN,	/* .BEGIN */
    147 	SP_DEFAULT,	/* .DEFAULT */
    148 	SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
    149 	SP_END,		/* .END */
    150 	SP_ERROR,	/* .ERROR */
    151 	SP_IGNORE,	/* .IGNORE */
    152 	SP_INCLUDES,	/* .INCLUDES; not mentioned in the manual page */
    153 	SP_INTERRUPT,	/* .INTERRUPT */
    154 	SP_LIBS,	/* .LIBS; not mentioned in the manual page */
    155 	SP_MAIN,	/* .MAIN and no user-specified targets to make */
    156 	SP_META,	/* .META */
    157 	SP_MFLAGS,	/* .MFLAGS or .MAKEFLAGS */
    158 	SP_NOMETA,	/* .NOMETA */
    159 	SP_NOMETA_CMP,	/* .NOMETA_CMP */
    160 	SP_NOPATH,	/* .NOPATH */
    161 	SP_NOREADONLY,	/* .NOREADONLY */
    162 	SP_NOT,		/* Not special */
    163 	SP_NOTPARALLEL,	/* .NOTPARALLEL or .NO_PARALLEL */
    164 	SP_NULL,	/* .NULL; not mentioned in the manual page */
    165 	SP_OBJDIR,	/* .OBJDIR */
    166 	SP_ORDER,	/* .ORDER */
    167 	SP_PARALLEL,	/* .PARALLEL; not mentioned in the manual page */
    168 	SP_PATH,	/* .PATH or .PATH.suffix */
    169 	SP_PHONY,	/* .PHONY */
    170 	SP_POSIX,	/* .POSIX; not mentioned in the manual page */
    171 	SP_PRECIOUS,	/* .PRECIOUS */
    172 	SP_READONLY,	/* .READONLY */
    173 	SP_SHELL,	/* .SHELL */
    174 	SP_SILENT,	/* .SILENT */
    175 	SP_SINGLESHELL,	/* .SINGLESHELL; not mentioned in the manual page */
    176 	SP_STALE,	/* .STALE */
    177 	SP_SUFFIXES,	/* .SUFFIXES */
    178 	SP_SYSPATH,	/* .SYSPATH */
    179 	SP_WAIT		/* .WAIT */
    180 } ParseSpecial;
    181 
    182 typedef List SearchPathList;
    183 typedef ListNode SearchPathListNode;
    184 
    185 
    186 typedef enum VarAssignOp {
    187 	VAR_NORMAL,		/* = */
    188 	VAR_APPEND,		/* += */
    189 	VAR_DEFAULT,		/* ?= */
    190 	VAR_SUBST,		/* := */
    191 	VAR_SHELL		/* != or :sh= */
    192 } VarAssignOp;
    193 
    194 typedef struct VarAssign {
    195 	char *varname;		/* unexpanded */
    196 	VarAssignOp op;
    197 	const char *value;	/* unexpanded */
    198 } VarAssign;
    199 
    200 static bool Parse_IsVar(const char *, VarAssign *);
    201 static void Parse_Var(VarAssign *, GNode *);
    202 
    203 /*
    204  * The target to be made if no targets are specified in the command line.
    205  * This is the first target defined in any of the makefiles.
    206  */
    207 GNode *mainNode;
    208 
    209 /*
    210  * During parsing, the targets from the left-hand side of the currently
    211  * active dependency line, or NULL if the current line does not belong to a
    212  * dependency line, for example because it is a variable assignment.
    213  *
    214  * See unit-tests/deptgt.mk, keyword "parse.c:targets".
    215  */
    216 static GNodeList *targets;
    217 
    218 #ifdef CLEANUP
    219 /*
    220  * All shell commands for all targets, in no particular order and possibly
    221  * with duplicates.  Kept in a separate list since the commands from .USE or
    222  * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
    223  * easily understandable ownership over the allocated strings.
    224  */
    225 static StringList targCmds = LST_INIT;
    226 #endif
    227 
    228 /*
    229  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
    230  * is seen, then set to each successive source on the line.
    231  */
    232 static GNode *order_pred;
    233 
    234 static int parseErrors;
    235 
    236 /*
    237  * The include chain of makefiles.  At index 0 is the top-level makefile from
    238  * the command line, followed by the included files or .for loops, up to and
    239  * including the current file.
    240  *
    241  * See PrintStackTrace for how to interpret the data.
    242  */
    243 static Vector /* of IncludedFile */ includes;
    244 
    245 SearchPath *parseIncPath;	/* directories for "..." includes */
    246 SearchPath *sysIncPath;		/* directories for <...> includes */
    247 SearchPath *defSysIncPath;	/* default for sysIncPath */
    248 
    249 /*
    250  * The parseKeywords table is searched using binary search when deciding
    251  * if a target or source is special.
    252  */
    253 static const struct {
    254 	const char name[17];
    255 	ParseSpecial special;	/* when used as a target */
    256 	GNodeType targetAttr;	/* when used as a source */
    257 } parseKeywords[] = {
    258     { ".BEGIN",		SP_BEGIN,	OP_NONE },
    259     { ".DEFAULT",	SP_DEFAULT,	OP_NONE },
    260     { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
    261     { ".END",		SP_END,		OP_NONE },
    262     { ".ERROR",		SP_ERROR,	OP_NONE },
    263     { ".EXEC",		SP_ATTRIBUTE,	OP_EXEC },
    264     { ".IGNORE",	SP_IGNORE,	OP_IGNORE },
    265     { ".INCLUDES",	SP_INCLUDES,	OP_NONE },
    266     { ".INTERRUPT",	SP_INTERRUPT,	OP_NONE },
    267     { ".INVISIBLE",	SP_ATTRIBUTE,	OP_INVISIBLE },
    268     { ".JOIN",		SP_ATTRIBUTE,	OP_JOIN },
    269     { ".LIBS",		SP_LIBS,	OP_NONE },
    270     { ".MADE",		SP_ATTRIBUTE,	OP_MADE },
    271     { ".MAIN",		SP_MAIN,	OP_NONE },
    272     { ".MAKE",		SP_ATTRIBUTE,	OP_MAKE },
    273     { ".MAKEFLAGS",	SP_MFLAGS,	OP_NONE },
    274     { ".META",		SP_META,	OP_META },
    275     { ".MFLAGS",	SP_MFLAGS,	OP_NONE },
    276     { ".NOMETA",	SP_NOMETA,	OP_NOMETA },
    277     { ".NOMETA_CMP",	SP_NOMETA_CMP,	OP_NOMETA_CMP },
    278     { ".NOPATH",	SP_NOPATH,	OP_NOPATH },
    279     { ".NOREADONLY",	SP_NOREADONLY,	OP_NONE },
    280     { ".NOTMAIN",	SP_ATTRIBUTE,	OP_NOTMAIN },
    281     { ".NOTPARALLEL",	SP_NOTPARALLEL,	OP_NONE },
    282     { ".NO_PARALLEL",	SP_NOTPARALLEL,	OP_NONE },
    283     { ".NULL",		SP_NULL,	OP_NONE },
    284     { ".OBJDIR",	SP_OBJDIR,	OP_NONE },
    285     { ".OPTIONAL",	SP_ATTRIBUTE,	OP_OPTIONAL },
    286     { ".ORDER",		SP_ORDER,	OP_NONE },
    287     { ".PARALLEL",	SP_PARALLEL,	OP_NONE },
    288     { ".PATH",		SP_PATH,	OP_NONE },
    289     { ".PHONY",		SP_PHONY,	OP_PHONY },
    290     { ".POSIX",		SP_POSIX,	OP_NONE },
    291     { ".PRECIOUS",	SP_PRECIOUS,	OP_PRECIOUS },
    292     { ".READONLY",	SP_READONLY,	OP_NONE },
    293     { ".RECURSIVE",	SP_ATTRIBUTE,	OP_MAKE },
    294     { ".SHELL",		SP_SHELL,	OP_NONE },
    295     { ".SILENT",	SP_SILENT,	OP_SILENT },
    296     { ".SINGLESHELL",	SP_SINGLESHELL,	OP_NONE },
    297     { ".STALE",		SP_STALE,	OP_NONE },
    298     { ".SUFFIXES",	SP_SUFFIXES,	OP_NONE },
    299     { ".SYSPATH",	SP_SYSPATH,	OP_NONE },
    300     { ".USE",		SP_ATTRIBUTE,	OP_USE },
    301     { ".USEBEFORE",	SP_ATTRIBUTE,	OP_USEBEFORE },
    302     { ".WAIT",		SP_WAIT,	OP_NONE },
    303 };
    304 
    305 enum PosixState posix_state = PS_NOT_YET;
    306 
    307 static HashTable /* full file name -> Guard */ guards;
    308 
    309 
    310 static List *
    311 Lst_New(void)
    312 {
    313 	List *list = bmake_malloc(sizeof *list);
    314 	Lst_Init(list);
    315 	return list;
    316 }
    317 
    318 static void
    319 Lst_Free(List *list)
    320 {
    321 
    322 	Lst_Done(list);
    323 	free(list);
    324 }
    325 
    326 static IncludedFile *
    327 GetInclude(size_t i)
    328 {
    329 	assert(i < includes.len);
    330 	return Vector_Get(&includes, i);
    331 }
    332 
    333 /* The makefile or the body of a .for loop that is currently being read. */
    334 static IncludedFile *
    335 CurFile(void)
    336 {
    337 	return GetInclude(includes.len - 1);
    338 }
    339 
    340 unsigned int
    341 CurFile_CondMinDepth(void)
    342 {
    343 	return CurFile()->condMinDepth;
    344 }
    345 
    346 static Buffer
    347 LoadFile(const char *path, int fd)
    348 {
    349 	ssize_t n;
    350 	Buffer buf;
    351 	size_t bufSize;
    352 	struct stat st;
    353 
    354 	bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
    355 		  st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
    356 	    ? (size_t)st.st_size : 1024;
    357 	Buf_InitSize(&buf, bufSize);
    358 
    359 	for (;;) {
    360 		if (buf.len == buf.cap) {
    361 			if (buf.cap >= 512 * 1024 * 1024) {
    362 				Error("%s: file too large", path);
    363 				exit(2); /* Not 1 so -q can distinguish error */
    364 			}
    365 			Buf_Expand(&buf);
    366 		}
    367 		assert(buf.len < buf.cap);
    368 		n = read(fd, buf.data + buf.len, buf.cap - buf.len);
    369 		if (n < 0) {
    370 			Error("%s: read error: %s", path, strerror(errno));
    371 			exit(2);	/* Not 1 so -q can distinguish error */
    372 		}
    373 		if (n == 0)
    374 			break;
    375 
    376 		buf.len += (size_t)n;
    377 	}
    378 	assert(buf.len <= buf.cap);
    379 
    380 	if (buf.len > 0 && !Buf_EndsWith(&buf, '\n'))
    381 		Buf_AddByte(&buf, '\n');
    382 
    383 	return buf;		/* may not be null-terminated */
    384 }
    385 
    386 /*
    387  * Print the current chain of .include and .for directives.  In Parse_Fatal
    388  * or other functions that already print the location, includingInnermost
    389  * would be redundant, but in other cases like Error or Fatal it needs to be
    390  * included.
    391  */
    392 void
    393 PrintStackTrace(bool includingInnermost)
    394 {
    395 	const IncludedFile *entries;
    396 	size_t i, n;
    397 
    398 	n = includes.len;
    399 	if (n == 0)
    400 		return;
    401 
    402 	entries = GetInclude(0);
    403 	if (!includingInnermost && entries[n - 1].forLoop == NULL)
    404 		n--;		/* already in the diagnostic */
    405 
    406 	for (i = n; i-- > 0;) {
    407 		const IncludedFile *entry = entries + i;
    408 		const char *fname = entry->name.str;
    409 		char dirbuf[MAXPATHLEN + 1];
    410 
    411 		if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0) {
    412 			const char *realPath = realpath(fname, dirbuf);
    413 			if (realPath != NULL)
    414 				fname = realPath;
    415 		}
    416 
    417 		if (entry->forLoop != NULL) {
    418 			char *details = ForLoop_Details(entry->forLoop);
    419 			debug_printf("\tin .for loop from %s:%u with %s\n",
    420 			    fname, entry->forHeadLineno, details);
    421 			free(details);
    422 		} else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
    423 			/* entry->lineno is not a useful line number */
    424 		} else
    425 			debug_printf("\tin %s:%u\n", fname, entry->lineno);
    426 	}
    427 }
    428 
    429 /* Check if the current character is escaped on the current line. */
    430 static bool
    431 IsEscaped(const char *line, const char *p)
    432 {
    433 	bool escaped = false;
    434 	while (p > line && *--p == '\\')
    435 		escaped = !escaped;
    436 	return escaped;
    437 }
    438 
    439 /*
    440  * Remember the location (filename and lineno) where the last command was
    441  * added or where the node was mentioned in a .depend file.
    442  */
    443 static void
    444 RememberLocation(GNode *gn)
    445 {
    446 	IncludedFile *curFile = CurFile();
    447 	gn->fname = Str_Intern(curFile->name.str);
    448 	gn->lineno = curFile->lineno;
    449 }
    450 
    451 /*
    452  * Look in the table of keywords for one matching the given string.
    453  * Return the index of the keyword, or -1 if it isn't there.
    454  */
    455 static int
    456 FindKeyword(const char *str)
    457 {
    458 	int start = 0;
    459 	int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
    460 
    461 	while (start <= end) {
    462 		int curr = start + (end - start) / 2;
    463 		int diff = strcmp(str, parseKeywords[curr].name);
    464 
    465 		if (diff == 0)
    466 			return curr;
    467 		if (diff < 0)
    468 			end = curr - 1;
    469 		else
    470 			start = curr + 1;
    471 	}
    472 
    473 	return -1;
    474 }
    475 
    476 void
    477 PrintLocation(FILE *f, bool useVars, const GNode *gn)
    478 {
    479 	char dirbuf[MAXPATHLEN + 1];
    480 	FStr dir, base;
    481 	const char *fname;
    482 	unsigned lineno;
    483 
    484 	if (gn != NULL) {
    485 		fname = gn->fname;
    486 		lineno = gn->lineno;
    487 	} else if (includes.len > 0) {
    488 		IncludedFile *curFile = CurFile();
    489 		fname = curFile->name.str;
    490 		lineno = curFile->lineno;
    491 	} else
    492 		return;
    493 
    494 	if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
    495 		(void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
    496 		return;
    497 	}
    498 
    499 	dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
    500 	if (dir.str == NULL)
    501 		dir.str = ".";
    502 	if (dir.str[0] != '/')
    503 		dir.str = realpath(dir.str, dirbuf);
    504 
    505 	base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
    506 	if (base.str == NULL)
    507 		base.str = str_basename(fname);
    508 
    509 	(void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
    510 
    511 	FStr_Done(&base);
    512 	FStr_Done(&dir);
    513 }
    514 
    515 static void MAKE_ATTR_PRINTFLIKE(5, 0)
    516 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
    517 		    ParseErrorLevel level, const char *fmt, va_list ap)
    518 {
    519 	static bool fatal_warning_error_printed = false;
    520 
    521 	(void)fprintf(f, "%s: ", progname);
    522 
    523 	PrintLocation(f, useVars, gn);
    524 	fprintf(f, "%s", EvalStack_Details());
    525 	if (level == PARSE_WARNING)
    526 		(void)fprintf(f, "warning: ");
    527 	(void)vfprintf(f, fmt, ap);
    528 	(void)fprintf(f, "\n");
    529 	(void)fflush(f);
    530 
    531 	if (level == PARSE_FATAL)
    532 		parseErrors++;
    533 	if (level == PARSE_WARNING && opts.parseWarnFatal) {
    534 		if (!fatal_warning_error_printed) {
    535 			Error("parsing warnings being treated as errors");
    536 			fatal_warning_error_printed = true;
    537 		}
    538 		parseErrors++;
    539 	}
    540 
    541 	if (DEBUG(PARSE))
    542 		PrintStackTrace(false);
    543 }
    544 
    545 static void MAKE_ATTR_PRINTFLIKE(3, 4)
    546 ParseErrorInternal(const GNode *gn,
    547 		   ParseErrorLevel level, const char *fmt, ...)
    548 {
    549 	va_list ap;
    550 
    551 	(void)fflush(stdout);
    552 	va_start(ap, fmt);
    553 	ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
    554 	va_end(ap);
    555 
    556 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
    557 		va_start(ap, fmt);
    558 		ParseVErrorInternal(opts.debug_file, false, gn,
    559 		    level, fmt, ap);
    560 		va_end(ap);
    561 	}
    562 }
    563 
    564 /*
    565  * Print a message, including location information.
    566  *
    567  * If the level is PARSE_FATAL, continue parsing until the end of the
    568  * current top-level makefile, then exit (see Parse_File).
    569  *
    570  * Fmt is given without a trailing newline.
    571  */
    572 void
    573 Parse_Error(ParseErrorLevel level, const char *fmt, ...)
    574 {
    575 	va_list ap;
    576 
    577 	(void)fflush(stdout);
    578 	va_start(ap, fmt);
    579 	ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
    580 	va_end(ap);
    581 
    582 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
    583 		va_start(ap, fmt);
    584 		ParseVErrorInternal(opts.debug_file, true, NULL,
    585 		    level, fmt, ap);
    586 		va_end(ap);
    587 	}
    588 }
    589 
    590 
    591 /*
    592  * Handle an .info, .warning or .error directive.  For an .error directive,
    593  * exit immediately.
    594  */
    595 static void
    596 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
    597 {
    598 	char *xmsg;
    599 
    600 	if (umsg[0] == '\0') {
    601 		Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
    602 		    levelName);
    603 		return;
    604 	}
    605 
    606 	xmsg = Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES);
    607 	/* TODO: handle errors */
    608 
    609 	Parse_Error(level, "%s", xmsg);
    610 	free(xmsg);
    611 
    612 	if (level == PARSE_FATAL) {
    613 		PrintOnError(NULL, "\n");
    614 		exit(1);
    615 	}
    616 }
    617 
    618 /*
    619  * Add the child to the parent's children, and for non-special targets, vice
    620  * versa.
    621  */
    622 static void
    623 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
    624 {
    625 	if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
    626 		pgn = pgn->cohorts.last->datum;
    627 
    628 	Lst_Append(&pgn->children, cgn);
    629 	pgn->unmade++;
    630 
    631 	/*
    632 	 * Special targets like .END do not need to be informed once the child
    633 	 * target has been made.
    634 	 */
    635 	if (!isSpecial)
    636 		Lst_Append(&cgn->parents, pgn);
    637 
    638 	if (DEBUG(PARSE)) {
    639 		debug_printf("# LinkSource: added child %s - %s\n",
    640 		    pgn->name, cgn->name);
    641 		Targ_PrintNode(pgn, 0);
    642 		Targ_PrintNode(cgn, 0);
    643 	}
    644 }
    645 
    646 /* Add the node to each target from the current dependency group. */
    647 static void
    648 LinkToTargets(GNode *gn, bool isSpecial)
    649 {
    650 	GNodeListNode *ln;
    651 
    652 	for (ln = targets->first; ln != NULL; ln = ln->next)
    653 		LinkSource(ln->datum, gn, isSpecial);
    654 }
    655 
    656 static bool
    657 TryApplyDependencyOperator(GNode *gn, GNodeType op)
    658 {
    659 	/*
    660 	 * If the node occurred on the left-hand side of a dependency and the
    661 	 * operator also defines a dependency, they must match.
    662 	 */
    663 	if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
    664 	    ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
    665 		Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
    666 		    gn->name);
    667 		return false;
    668 	}
    669 
    670 	if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
    671 		/*
    672 		 * If the node was on the left-hand side of a '::' operator,
    673 		 * create a new node for the children and commands on this
    674 		 * dependency line, since each of these dependency groups has
    675 		 * its own attributes and commands, separate from the others.
    676 		 *
    677 		 * The new instance is placed on the 'cohorts' list of the
    678 		 * initial one (note the initial one is not on its own
    679 		 * cohorts list) and the new instance is linked to all
    680 		 * parents of the initial instance.
    681 		 */
    682 		GNode *cohort;
    683 
    684 		/*
    685 		 * Propagate copied bits to the initial node.  They'll be
    686 		 * propagated back to the rest of the cohorts later.
    687 		 */
    688 		gn->type |= op & (unsigned)~OP_OPMASK;
    689 
    690 		cohort = Targ_NewInternalNode(gn->name);
    691 		if (doing_depend)
    692 			RememberLocation(cohort);
    693 		/*
    694 		 * Make the cohort invisible to avoid duplicating it
    695 		 * into other variables. True, parents of this target won't
    696 		 * tend to do anything with their local variables, but better
    697 		 * safe than sorry.
    698 		 *
    699 		 * (I think this is pointless now, since the relevant list
    700 		 * traversals will no longer see this node anyway. -mycroft)
    701 		 */
    702 		cohort->type = op | OP_INVISIBLE;
    703 		Lst_Append(&gn->cohorts, cohort);
    704 		cohort->centurion = gn;
    705 		gn->unmade_cohorts++;
    706 		snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
    707 		    (unsigned int)gn->unmade_cohorts % 1000000);
    708 	} else {
    709 		gn->type |= op;	/* preserve any previous flags */
    710 	}
    711 
    712 	return true;
    713 }
    714 
    715 static void
    716 ApplyDependencyOperator(GNodeType op)
    717 {
    718 	GNodeListNode *ln;
    719 
    720 	for (ln = targets->first; ln != NULL; ln = ln->next)
    721 		if (!TryApplyDependencyOperator(ln->datum, op))
    722 			break;
    723 }
    724 
    725 /*
    726  * Add a .WAIT node in the dependency list. After any dynamic dependencies
    727  * (and filename globbing) have happened, it is given a dependency on each
    728  * previous child, back until the previous .WAIT node. The next child won't
    729  * be scheduled until the .WAIT node is built.
    730  *
    731  * Give each .WAIT node a unique name (mainly for diagnostics).
    732  */
    733 static void
    734 ApplyDependencySourceWait(bool isSpecial)
    735 {
    736 	static unsigned wait_number = 0;
    737 	char name[6 + 10 + 1];
    738 	GNode *gn;
    739 
    740 	snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
    741 	gn = Targ_NewInternalNode(name);
    742 	if (doing_depend)
    743 		RememberLocation(gn);
    744 	gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
    745 	LinkToTargets(gn, isSpecial);
    746 }
    747 
    748 static bool
    749 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
    750 {
    751 	int keywd;
    752 	GNodeType targetAttr;
    753 
    754 	if (*src != '.' || !ch_isupper(src[1]))
    755 		return false;
    756 
    757 	keywd = FindKeyword(src);
    758 	if (keywd == -1)
    759 		return false;
    760 
    761 	targetAttr = parseKeywords[keywd].targetAttr;
    762 	if (targetAttr != OP_NONE) {
    763 		ApplyDependencyOperator(targetAttr);
    764 		return true;
    765 	}
    766 	if (parseKeywords[keywd].special == SP_WAIT) {
    767 		ApplyDependencySourceWait(special != SP_NOT);
    768 		return true;
    769 	}
    770 	return false;
    771 }
    772 
    773 /*
    774  * In a line like ".MAIN: source1 source2", add all sources to the list of
    775  * things to create, but only if the user didn't specify a target on the
    776  * command line and .MAIN occurs for the first time.
    777  *
    778  * See HandleDependencyTargetSpecial, branch SP_MAIN.
    779  * See unit-tests/cond-func-make-main.mk.
    780  */
    781 static void
    782 ApplyDependencySourceMain(const char *src)
    783 {
    784 	Lst_Append(&opts.create, bmake_strdup(src));
    785 	/*
    786 	 * Add the name to the .TARGETS variable as well, so the user can
    787 	 * employ that, if desired.
    788 	 */
    789 	Global_Append(".TARGETS", src);
    790 }
    791 
    792 /*
    793  * For the sources of a .ORDER target, create predecessor/successor links
    794  * between the previous source and the current one.
    795  */
    796 static void
    797 ApplyDependencySourceOrder(const char *src)
    798 {
    799 	GNode *gn;
    800 
    801 	gn = Targ_GetNode(src);
    802 	if (doing_depend)
    803 		RememberLocation(gn);
    804 	if (order_pred != NULL) {
    805 		Lst_Append(&order_pred->order_succ, gn);
    806 		Lst_Append(&gn->order_pred, order_pred);
    807 		if (DEBUG(PARSE)) {
    808 			debug_printf(
    809 			    "# .ORDER forces '%s' to be made before '%s'\n",
    810 			    order_pred->name, gn->name);
    811 			Targ_PrintNode(order_pred, 0);
    812 			Targ_PrintNode(gn, 0);
    813 		}
    814 	}
    815 	/* The current source now becomes the predecessor for the next one. */
    816 	order_pred = gn;
    817 }
    818 
    819 /* The source is not an attribute, so find/create a node for it. */
    820 static void
    821 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
    822 			   ParseSpecial special)
    823 {
    824 	GNode *gn;
    825 
    826 	gn = Targ_GetNode(src);
    827 	if (doing_depend)
    828 		RememberLocation(gn);
    829 	if (targetAttr != OP_NONE)
    830 		gn->type |= targetAttr;
    831 	else
    832 		LinkToTargets(gn, special != SP_NOT);
    833 }
    834 
    835 /*
    836  * Given the name of a source in a dependency line, figure out if it is an
    837  * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
    838  * decide if there is some attribute which should be applied *to* the source
    839  * because of some special target (such as .PHONY) and apply it if so.
    840  * Otherwise, make the source a child of the targets.
    841  */
    842 static void
    843 ApplyDependencySource(GNodeType targetAttr, const char *src,
    844 		      ParseSpecial special)
    845 {
    846 	if (ApplyDependencySourceKeyword(src, special))
    847 		return;
    848 
    849 	if (special == SP_MAIN)
    850 		ApplyDependencySourceMain(src);
    851 	else if (special == SP_ORDER)
    852 		ApplyDependencySourceOrder(src);
    853 	else
    854 		ApplyDependencySourceOther(src, targetAttr, special);
    855 }
    856 
    857 /*
    858  * If we have yet to decide on a main target to make, in the absence of any
    859  * user input, we want the first target on the first dependency line that is
    860  * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
    861  */
    862 static void
    863 MaybeUpdateMainTarget(void)
    864 {
    865 	GNodeListNode *ln;
    866 
    867 	if (mainNode != NULL)
    868 		return;
    869 
    870 	for (ln = targets->first; ln != NULL; ln = ln->next) {
    871 		GNode *gn = ln->datum;
    872 		if (GNode_IsMainCandidate(gn)) {
    873 			DEBUG1(MAKE, "Setting main node to \"%s\"\n",
    874 			    gn->name);
    875 			mainNode = gn;
    876 			return;
    877 		}
    878 	}
    879 }
    880 
    881 static void
    882 InvalidLineType(const char *line, const char *unexpanded_line)
    883 {
    884 	if (unexpanded_line[0] == '.') {
    885 		const char *dirstart = unexpanded_line + 1;
    886 		const char *dirend;
    887 		cpp_skip_whitespace(&dirstart);
    888 		dirend = dirstart;
    889 		while (ch_isalnum(*dirend) || *dirend == '-')
    890 			dirend++;
    891 		Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
    892 		    (int)(dirend - dirstart), dirstart);
    893 	} else if (strcmp(line, unexpanded_line) == 0)
    894 		Parse_Error(PARSE_FATAL, "Invalid line '%s'", line);
    895 	else
    896 		Parse_Error(PARSE_FATAL,
    897 		    "Invalid line '%s', expanded to '%s'",
    898 		    unexpanded_line, line);
    899 }
    900 
    901 static void
    902 ParseDependencyTargetWord(char **pp, const char *lstart)
    903 {
    904 	const char *p = *pp;
    905 
    906 	while (*p != '\0') {
    907 		if ((ch_isspace(*p) || *p == '!' || *p == ':' || *p == '(')
    908 		    && !IsEscaped(lstart, p))
    909 			break;
    910 
    911 		if (*p == '$') {
    912 			FStr val = Var_Parse(&p, SCOPE_CMDLINE,
    913 			    VARE_PARSE_ONLY);
    914 			/* TODO: handle errors */
    915 			FStr_Done(&val);
    916 		} else
    917 			p++;
    918 	}
    919 
    920 	*pp += p - *pp;
    921 }
    922 
    923 /*
    924  * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
    925  *
    926  * See the tests deptgt-*.mk.
    927  */
    928 static void
    929 HandleDependencyTargetSpecial(const char *targetName,
    930 			      ParseSpecial *inout_special,
    931 			      SearchPathList **inout_paths)
    932 {
    933 	switch (*inout_special) {
    934 	case SP_PATH:
    935 		if (*inout_paths == NULL)
    936 			*inout_paths = Lst_New();
    937 		Lst_Append(*inout_paths, &dirSearchPath);
    938 		break;
    939 	case SP_SYSPATH:
    940 		if (*inout_paths == NULL)
    941 			*inout_paths = Lst_New();
    942 		Lst_Append(*inout_paths, sysIncPath);
    943 		break;
    944 	case SP_MAIN:
    945 		/*
    946 		 * Allow targets from the command line to override the
    947 		 * .MAIN node.
    948 		 */
    949 		if (!Lst_IsEmpty(&opts.create))
    950 			*inout_special = SP_NOT;
    951 		break;
    952 	case SP_BEGIN:
    953 	case SP_END:
    954 	case SP_STALE:
    955 	case SP_ERROR:
    956 	case SP_INTERRUPT: {
    957 		GNode *gn = Targ_GetNode(targetName);
    958 		if (doing_depend)
    959 			RememberLocation(gn);
    960 		gn->type |= OP_NOTMAIN | OP_SPECIAL;
    961 		Lst_Append(targets, gn);
    962 		break;
    963 	}
    964 	case SP_DEFAULT: {
    965 		/*
    966 		 * Need to create a node to hang commands on, but we don't
    967 		 * want it in the graph, nor do we want it to be the Main
    968 		 * Target. We claim the node is a transformation rule to make
    969 		 * life easier later, when we'll use Make_HandleUse to
    970 		 * actually apply the .DEFAULT commands.
    971 		 */
    972 		GNode *gn = GNode_New(".DEFAULT");
    973 		gn->type |= OP_NOTMAIN | OP_TRANSFORM;
    974 		Lst_Append(targets, gn);
    975 		defaultNode = gn;
    976 		break;
    977 	}
    978 	case SP_DELETE_ON_ERROR:
    979 		deleteOnError = true;
    980 		break;
    981 	case SP_NOTPARALLEL:
    982 		opts.maxJobs = 1;
    983 		break;
    984 	case SP_SINGLESHELL:
    985 		opts.compatMake = true;
    986 		break;
    987 	case SP_ORDER:
    988 		order_pred = NULL;
    989 		break;
    990 	default:
    991 		break;
    992 	}
    993 }
    994 
    995 static bool
    996 HandleDependencyTargetPath(const char *suffixName,
    997 			   SearchPathList **inout_paths)
    998 {
    999 	SearchPath *path;
   1000 
   1001 	path = Suff_GetPath(suffixName);
   1002 	if (path == NULL) {
   1003 		Parse_Error(PARSE_FATAL,
   1004 		    "Suffix '%s' not defined (yet)", suffixName);
   1005 		return false;
   1006 	}
   1007 
   1008 	if (*inout_paths == NULL)
   1009 		*inout_paths = Lst_New();
   1010 	Lst_Append(*inout_paths, path);
   1011 
   1012 	return true;
   1013 }
   1014 
   1015 /* See if it's a special target and if so set inout_special to match it. */
   1016 static bool
   1017 HandleDependencyTarget(const char *targetName,
   1018 		       ParseSpecial *inout_special,
   1019 		       GNodeType *inout_targetAttr,
   1020 		       SearchPathList **inout_paths)
   1021 {
   1022 	int keywd;
   1023 
   1024 	if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
   1025 		return true;
   1026 
   1027 	/*
   1028 	 * See if the target is a special target that must have it
   1029 	 * or its sources handled specially.
   1030 	 */
   1031 	keywd = FindKeyword(targetName);
   1032 	if (keywd != -1) {
   1033 		if (*inout_special == SP_PATH &&
   1034 		    parseKeywords[keywd].special != SP_PATH) {
   1035 			Parse_Error(PARSE_FATAL, "Mismatched special targets");
   1036 			return false;
   1037 		}
   1038 
   1039 		*inout_special = parseKeywords[keywd].special;
   1040 		*inout_targetAttr = parseKeywords[keywd].targetAttr;
   1041 
   1042 		HandleDependencyTargetSpecial(targetName, inout_special,
   1043 		    inout_paths);
   1044 
   1045 	} else if (strncmp(targetName, ".PATH", 5) == 0) {
   1046 		*inout_special = SP_PATH;
   1047 		if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
   1048 			return false;
   1049 	}
   1050 	return true;
   1051 }
   1052 
   1053 static void
   1054 HandleSingleDependencyTargetMundane(const char *name)
   1055 {
   1056 	GNode *gn = Suff_IsTransform(name)
   1057 	    ? Suff_AddTransform(name)
   1058 	    : Targ_GetNode(name);
   1059 	if (doing_depend)
   1060 		RememberLocation(gn);
   1061 
   1062 	Lst_Append(targets, gn);
   1063 }
   1064 
   1065 static void
   1066 HandleDependencyTargetMundane(const char *targetName)
   1067 {
   1068 	if (Dir_HasWildcards(targetName)) {
   1069 		StringList targetNames = LST_INIT;
   1070 
   1071 		SearchPath *emptyPath = SearchPath_New();
   1072 		SearchPath_Expand(emptyPath, targetName, &targetNames);
   1073 		SearchPath_Free(emptyPath);
   1074 
   1075 		while (!Lst_IsEmpty(&targetNames)) {
   1076 			char *targName = Lst_Dequeue(&targetNames);
   1077 			HandleSingleDependencyTargetMundane(targName);
   1078 			free(targName);
   1079 		}
   1080 	} else
   1081 		HandleSingleDependencyTargetMundane(targetName);
   1082 }
   1083 
   1084 static void
   1085 SkipExtraTargets(char **pp, const char *lstart)
   1086 {
   1087 	bool warning = false;
   1088 	const char *p = *pp;
   1089 
   1090 	while (*p != '\0') {
   1091 		if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
   1092 			break;
   1093 		if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
   1094 			warning = true;
   1095 		p++;
   1096 	}
   1097 	if (warning) {
   1098 		const char *start = *pp;
   1099 		cpp_skip_whitespace(&start);
   1100 		Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
   1101 		    (int)(p - start), start);
   1102 	}
   1103 
   1104 	*pp += p - *pp;
   1105 }
   1106 
   1107 static void
   1108 CheckSpecialMundaneMixture(ParseSpecial special)
   1109 {
   1110 	switch (special) {
   1111 	case SP_DEFAULT:
   1112 	case SP_STALE:
   1113 	case SP_BEGIN:
   1114 	case SP_END:
   1115 	case SP_ERROR:
   1116 	case SP_INTERRUPT:
   1117 		/*
   1118 		 * These create nodes on which to hang commands, so targets
   1119 		 * shouldn't be empty.
   1120 		 */
   1121 	case SP_NOT:
   1122 		/* Nothing special here -- targets may be empty. */
   1123 		break;
   1124 	default:
   1125 		Parse_Error(PARSE_WARNING,
   1126 		    "Special and mundane targets don't mix. "
   1127 		    "Mundane ones ignored");
   1128 		break;
   1129 	}
   1130 }
   1131 
   1132 /*
   1133  * In a dependency line like 'targets: sources' or 'targets! sources', parse
   1134  * the operator ':', '::' or '!' from between the targets and the sources.
   1135  */
   1136 static GNodeType
   1137 ParseDependencyOp(char **pp)
   1138 {
   1139 	if (**pp == '!')
   1140 		return (*pp)++, OP_FORCE;
   1141 	if (**pp == ':' && (*pp)[1] == ':')
   1142 		return *pp += 2, OP_DOUBLEDEP;
   1143 	else if (**pp == ':')
   1144 		return (*pp)++, OP_DEPENDS;
   1145 	else
   1146 		return OP_NONE;
   1147 }
   1148 
   1149 static void
   1150 ClearPaths(ParseSpecial special, SearchPathList *paths)
   1151 {
   1152 	if (paths != NULL) {
   1153 		SearchPathListNode *ln;
   1154 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1155 			SearchPath_Clear(ln->datum);
   1156 	}
   1157 	if (special == SP_SYSPATH)
   1158 		Dir_SetSYSPATH();
   1159 	else
   1160 		Dir_SetPATH();
   1161 }
   1162 
   1163 static char *
   1164 FindInDirOfIncludingFile(const char *file)
   1165 {
   1166 	char *fullname, *incdir, *slash, *newName;
   1167 	int i;
   1168 
   1169 	fullname = NULL;
   1170 	incdir = bmake_strdup(CurFile()->name.str);
   1171 	slash = strrchr(incdir, '/');
   1172 	if (slash != NULL) {
   1173 		*slash = '\0';
   1174 		/*
   1175 		 * Now do lexical processing of leading "../" on the
   1176 		 * filename.
   1177 		 */
   1178 		for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
   1179 			slash = strrchr(incdir + 1, '/');
   1180 			if (slash == NULL || strcmp(slash, "/..") == 0)
   1181 				break;
   1182 			*slash = '\0';
   1183 		}
   1184 		newName = str_concat3(incdir, "/", file + i);
   1185 		fullname = Dir_FindFile(newName, parseIncPath);
   1186 		if (fullname == NULL)
   1187 			fullname = Dir_FindFile(newName, &dirSearchPath);
   1188 		free(newName);
   1189 	}
   1190 	free(incdir);
   1191 	return fullname;
   1192 }
   1193 
   1194 static char *
   1195 FindInQuotPath(const char *file)
   1196 {
   1197 	const char *suff;
   1198 	SearchPath *suffPath;
   1199 	char *fullname;
   1200 
   1201 	fullname = FindInDirOfIncludingFile(file);
   1202 	if (fullname == NULL &&
   1203 	    (suff = strrchr(file, '.')) != NULL &&
   1204 	    (suffPath = Suff_GetPath(suff)) != NULL)
   1205 		fullname = Dir_FindFile(file, suffPath);
   1206 	if (fullname == NULL)
   1207 		fullname = Dir_FindFile(file, parseIncPath);
   1208 	if (fullname == NULL)
   1209 		fullname = Dir_FindFile(file, &dirSearchPath);
   1210 	return fullname;
   1211 }
   1212 
   1213 static bool
   1214 SkipGuarded(const char *fullname)
   1215 {
   1216 	Guard *guard = HashTable_FindValue(&guards, fullname);
   1217 	if (guard != NULL && guard->kind == GK_VARIABLE
   1218 	    && GNode_ValueDirect(SCOPE_GLOBAL, guard->name) != NULL)
   1219 		goto skip;
   1220 	if (guard != NULL && guard->kind == GK_TARGET
   1221 	    && Targ_FindNode(guard->name) != NULL)
   1222 		goto skip;
   1223 	return false;
   1224 
   1225 skip:
   1226 	DEBUG2(PARSE, "Skipping '%s' because '%s' is defined\n",
   1227 	    fullname, guard->name);
   1228 	return true;
   1229 }
   1230 
   1231 /*
   1232  * Handle one of the .[-ds]include directives by remembering the current file
   1233  * and pushing the included file on the stack.  After the included file has
   1234  * finished, parsing continues with the including file; see Parse_PushInput
   1235  * and ParseEOF.
   1236  *
   1237  * System includes are looked up in sysIncPath, any other includes are looked
   1238  * up in the parsedir and then in the directories specified by the -I command
   1239  * line options.
   1240  */
   1241 static void
   1242 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
   1243 {
   1244 	Buffer buf;
   1245 	char *fullname;		/* full pathname of file */
   1246 	int fd;
   1247 
   1248 	fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
   1249 
   1250 	if (fullname == NULL && !isSystem)
   1251 		fullname = FindInQuotPath(file);
   1252 
   1253 	if (fullname == NULL) {
   1254 		SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
   1255 		    ? defSysIncPath : sysIncPath;
   1256 		fullname = Dir_FindInclude(file, path);
   1257 	}
   1258 
   1259 	if (fullname == NULL) {
   1260 		if (!silent)
   1261 			Parse_Error(PARSE_FATAL, "Could not find %s", file);
   1262 		return;
   1263 	}
   1264 
   1265 	if (SkipGuarded(fullname))
   1266 		goto done;
   1267 
   1268 	if ((fd = open(fullname, O_RDONLY)) == -1) {
   1269 		if (!silent)
   1270 			Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
   1271 		goto done;
   1272 	}
   1273 
   1274 	buf = LoadFile(fullname, fd);
   1275 	(void)close(fd);
   1276 
   1277 	Parse_PushInput(fullname, 1, 0, buf, NULL);
   1278 	if (depinc)
   1279 		doing_depend = depinc;	/* only turn it on */
   1280 done:
   1281 	free(fullname);
   1282 }
   1283 
   1284 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
   1285 static void
   1286 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
   1287 {
   1288 	switch (special) {
   1289 	case SP_SUFFIXES:
   1290 		Suff_ClearSuffixes();
   1291 		break;
   1292 	case SP_PRECIOUS:
   1293 		allPrecious = true;
   1294 		break;
   1295 	case SP_IGNORE:
   1296 		opts.ignoreErrors = true;
   1297 		break;
   1298 	case SP_SILENT:
   1299 		opts.silent = true;
   1300 		break;
   1301 	case SP_PATH:
   1302 	case SP_SYSPATH:
   1303 		ClearPaths(special, paths);
   1304 		break;
   1305 	case SP_POSIX:
   1306 		if (posix_state == PS_NOW_OR_NEVER) {
   1307 			/*
   1308 			 * With '-r', 'posix.mk' (if it exists)
   1309 			 * can effectively substitute for 'sys.mk',
   1310 			 * otherwise it is an extension.
   1311 			 */
   1312 			Global_Set("%POSIX", "1003.2");
   1313 			IncludeFile("posix.mk", true, false, true);
   1314 		}
   1315 		break;
   1316 	default:
   1317 		break;
   1318 	}
   1319 }
   1320 
   1321 static void
   1322 AddToPaths(const char *dir, SearchPathList *paths)
   1323 {
   1324 	if (paths != NULL) {
   1325 		SearchPathListNode *ln;
   1326 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1327 			(void)SearchPath_Add(ln->datum, dir);
   1328 	}
   1329 }
   1330 
   1331 /*
   1332  * If the target was one that doesn't take files as its sources but takes
   1333  * something like suffixes, we take each space-separated word on the line as
   1334  * a something and deal with it accordingly.
   1335  */
   1336 static void
   1337 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
   1338 			     SearchPathList *paths)
   1339 {
   1340 	switch (special) {
   1341 	case SP_SUFFIXES:
   1342 		Suff_AddSuffix(word);
   1343 		break;
   1344 	case SP_PATH:
   1345 	case SP_SYSPATH:
   1346 		AddToPaths(word, paths);
   1347 		break;
   1348 	case SP_INCLUDES:
   1349 		Suff_AddInclude(word);
   1350 		break;
   1351 	case SP_LIBS:
   1352 		Suff_AddLib(word);
   1353 		break;
   1354 	case SP_NOREADONLY:
   1355 		Var_ReadOnly(word, false);
   1356 		break;
   1357 	case SP_NULL:
   1358 		Suff_SetNull(word);
   1359 		break;
   1360 	case SP_OBJDIR:
   1361 		Main_SetObjdir(false, "%s", word);
   1362 		break;
   1363 	case SP_READONLY:
   1364 		Var_ReadOnly(word, true);
   1365 		break;
   1366 	default:
   1367 		break;
   1368 	}
   1369 }
   1370 
   1371 static bool
   1372 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
   1373 		      GNodeType *inout_targetAttr,
   1374 		      SearchPathList **inout_paths)
   1375 {
   1376 	char savedNameEnd = *nameEnd;
   1377 	*nameEnd = '\0';
   1378 
   1379 	if (!HandleDependencyTarget(name, inout_special,
   1380 	    inout_targetAttr, inout_paths))
   1381 		return false;
   1382 
   1383 	if (*inout_special == SP_NOT && *name != '\0')
   1384 		HandleDependencyTargetMundane(name);
   1385 	else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
   1386 		Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
   1387 
   1388 	*nameEnd = savedNameEnd;
   1389 	return true;
   1390 }
   1391 
   1392 static bool
   1393 ParseDependencyTargets(char **pp,
   1394 		       const char *lstart,
   1395 		       ParseSpecial *inout_special,
   1396 		       GNodeType *inout_targetAttr,
   1397 		       SearchPathList **inout_paths,
   1398 		       const char *unexpanded_line)
   1399 {
   1400 	char *p = *pp;
   1401 
   1402 	for (;;) {
   1403 		char *tgt = p;
   1404 
   1405 		ParseDependencyTargetWord(&p, lstart);
   1406 
   1407 		/*
   1408 		 * If the word is followed by a left parenthesis, it's the
   1409 		 * name of one or more files inside an archive.
   1410 		 */
   1411 		if (!IsEscaped(lstart, p) && *p == '(') {
   1412 			p = tgt;
   1413 			if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
   1414 				Parse_Error(PARSE_FATAL,
   1415 				    "Error in archive specification: \"%s\"",
   1416 				    tgt);
   1417 				return false;
   1418 			}
   1419 			continue;
   1420 		}
   1421 
   1422 		if (*p == '\0') {
   1423 			InvalidLineType(lstart, unexpanded_line);
   1424 			return false;
   1425 		}
   1426 
   1427 		if (!ApplyDependencyTarget(tgt, p, inout_special,
   1428 		    inout_targetAttr, inout_paths))
   1429 			return false;
   1430 
   1431 		if (*inout_special != SP_NOT && *inout_special != SP_PATH)
   1432 			SkipExtraTargets(&p, lstart);
   1433 		else
   1434 			pp_skip_whitespace(&p);
   1435 
   1436 		if (*p == '\0')
   1437 			break;
   1438 		if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
   1439 			break;
   1440 	}
   1441 
   1442 	*pp = p;
   1443 	return true;
   1444 }
   1445 
   1446 static void
   1447 ParseDependencySourcesSpecial(char *start,
   1448 			      ParseSpecial special, SearchPathList *paths)
   1449 {
   1450 
   1451 	while (*start != '\0') {
   1452 		char savedEnd;
   1453 		char *end = start;
   1454 		while (*end != '\0' && !ch_isspace(*end))
   1455 			end++;
   1456 		savedEnd = *end;
   1457 		*end = '\0';
   1458 		ParseDependencySourceSpecial(special, start, paths);
   1459 		*end = savedEnd;
   1460 		if (savedEnd != '\0')
   1461 			end++;
   1462 		pp_skip_whitespace(&end);
   1463 		start = end;
   1464 	}
   1465 }
   1466 
   1467 static void
   1468 LinkVarToTargets(VarAssign *var)
   1469 {
   1470 	GNodeListNode *ln;
   1471 
   1472 	for (ln = targets->first; ln != NULL; ln = ln->next)
   1473 		Parse_Var(var, ln->datum);
   1474 }
   1475 
   1476 static bool
   1477 ParseDependencySourcesMundane(char *start,
   1478 			      ParseSpecial special, GNodeType targetAttr)
   1479 {
   1480 	while (*start != '\0') {
   1481 		char *end = start;
   1482 		VarAssign var;
   1483 
   1484 		/*
   1485 		 * Check for local variable assignment,
   1486 		 * rest of the line is the value.
   1487 		 */
   1488 		if (Parse_IsVar(start, &var)) {
   1489 			bool targetVarsEnabled = GetBooleanExpr(
   1490 			    "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
   1491 
   1492 			if (targetVarsEnabled)
   1493 				LinkVarToTargets(&var);
   1494 			free(var.varname);
   1495 			if (targetVarsEnabled)
   1496 				return true;
   1497 		}
   1498 
   1499 		/*
   1500 		 * The targets take real sources, so we must beware of archive
   1501 		 * specifications (i.e. things with left parentheses in them)
   1502 		 * and handle them accordingly.
   1503 		 */
   1504 		for (; *end != '\0' && !ch_isspace(*end); end++) {
   1505 			if (*end == '(' && end > start && end[-1] != '$') {
   1506 				/*
   1507 				 * Only stop for a left parenthesis if it
   1508 				 * isn't at the start of a word (that'll be
   1509 				 * for variable changes later) and isn't
   1510 				 * preceded by a dollar sign (a dynamic
   1511 				 * source).
   1512 				 */
   1513 				break;
   1514 			}
   1515 		}
   1516 
   1517 		if (*end == '(') {
   1518 			GNodeList sources = LST_INIT;
   1519 			if (!Arch_ParseArchive(&start, &sources,
   1520 			    SCOPE_CMDLINE)) {
   1521 				Parse_Error(PARSE_FATAL,
   1522 				    "Error in source archive spec \"%s\"",
   1523 				    start);
   1524 				return false;
   1525 			}
   1526 
   1527 			while (!Lst_IsEmpty(&sources)) {
   1528 				GNode *gn = Lst_Dequeue(&sources);
   1529 				ApplyDependencySource(targetAttr, gn->name,
   1530 				    special);
   1531 			}
   1532 			Lst_Done(&sources);
   1533 			end = start;
   1534 		} else {
   1535 			if (*end != '\0') {
   1536 				*end = '\0';
   1537 				end++;
   1538 			}
   1539 
   1540 			ApplyDependencySource(targetAttr, start, special);
   1541 		}
   1542 		pp_skip_whitespace(&end);
   1543 		start = end;
   1544 	}
   1545 	return true;
   1546 }
   1547 
   1548 /*
   1549  * From a dependency line like 'targets: sources', parse the sources.
   1550  *
   1551  * See the tests depsrc-*.mk.
   1552  */
   1553 static void
   1554 ParseDependencySources(char *p, GNodeType targetAttr,
   1555 		       ParseSpecial special, SearchPathList **inout_paths)
   1556 {
   1557 	if (*p == '\0') {
   1558 		HandleDependencySourcesEmpty(special, *inout_paths);
   1559 	} else if (special == SP_MFLAGS) {
   1560 		Main_ParseArgLine(p);
   1561 		return;
   1562 	} else if (special == SP_SHELL) {
   1563 		if (!Job_ParseShell(p)) {
   1564 			Parse_Error(PARSE_FATAL,
   1565 			    "improper shell specification");
   1566 			return;
   1567 		}
   1568 		return;
   1569 	} else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
   1570 		   special == SP_DELETE_ON_ERROR) {
   1571 		return;
   1572 	}
   1573 
   1574 	switch (special) {
   1575 	case SP_INCLUDES:
   1576 	case SP_LIBS:
   1577 	case SP_NOREADONLY:
   1578 	case SP_NULL:
   1579 	case SP_OBJDIR:
   1580 	case SP_PATH:
   1581 	case SP_READONLY:
   1582 	case SP_SUFFIXES:
   1583 	case SP_SYSPATH:
   1584 		ParseDependencySourcesSpecial(p, special, *inout_paths);
   1585 		if (*inout_paths != NULL) {
   1586 			Lst_Free(*inout_paths);
   1587 			*inout_paths = NULL;
   1588 		}
   1589 		if (special == SP_PATH)
   1590 			Dir_SetPATH();
   1591 		if (special == SP_SYSPATH)
   1592 			Dir_SetSYSPATH();
   1593 		break;
   1594 	default:
   1595 		assert(*inout_paths == NULL);
   1596 		if (!ParseDependencySourcesMundane(p, special, targetAttr))
   1597 			return;
   1598 		break;
   1599 	}
   1600 
   1601 	MaybeUpdateMainTarget();
   1602 }
   1603 
   1604 /*
   1605  * Parse a dependency line consisting of targets, followed by a dependency
   1606  * operator, optionally followed by sources.
   1607  *
   1608  * The nodes of the sources are linked as children to the nodes of the
   1609  * targets. Nodes are created as necessary.
   1610  *
   1611  * The operator is applied to each node in the global 'targets' list,
   1612  * which is where the nodes found for the targets are kept.
   1613  *
   1614  * The sources are parsed in much the same way as the targets, except
   1615  * that they are expanded using the wildcarding scheme of the C-Shell,
   1616  * and a target is created for each expanded word. Each of the resulting
   1617  * nodes is then linked to each of the targets as one of its children.
   1618  *
   1619  * Certain targets and sources such as .PHONY or .PRECIOUS are handled
   1620  * specially, see ParseSpecial.
   1621  *
   1622  * Transformation rules such as '.c.o' are also handled here, see
   1623  * Suff_AddTransform.
   1624  *
   1625  * Upon return, the value of expandedLine is unspecified.
   1626  */
   1627 static void
   1628 ParseDependency(char *expandedLine, const char *unexpandedLine)
   1629 {
   1630 	char *p;
   1631 	SearchPathList *paths;	/* search paths to alter when parsing a list
   1632 				 * of .PATH targets */
   1633 	GNodeType targetAttr;	/* from special sources */
   1634 	ParseSpecial special;	/* in special targets, the children are
   1635 				 * linked as children of the parent but not
   1636 				 * vice versa */
   1637 	GNodeType op;
   1638 
   1639 	DEBUG1(PARSE, "ParseDependency(%s)\n", expandedLine);
   1640 	p = expandedLine;
   1641 	paths = NULL;
   1642 	targetAttr = OP_NONE;
   1643 	special = SP_NOT;
   1644 
   1645 	if (!ParseDependencyTargets(&p, expandedLine, &special, &targetAttr,
   1646 	    &paths, unexpandedLine))
   1647 		goto out;
   1648 
   1649 	if (!Lst_IsEmpty(targets))
   1650 		CheckSpecialMundaneMixture(special);
   1651 
   1652 	op = ParseDependencyOp(&p);
   1653 	if (op == OP_NONE) {
   1654 		InvalidLineType(expandedLine, unexpandedLine);
   1655 		goto out;
   1656 	}
   1657 	ApplyDependencyOperator(op);
   1658 
   1659 	pp_skip_whitespace(&p);
   1660 
   1661 	ParseDependencySources(p, targetAttr, special, &paths);
   1662 
   1663 out:
   1664 	if (paths != NULL)
   1665 		Lst_Free(paths);
   1666 }
   1667 
   1668 /*
   1669  * Determine the assignment operator and adjust the end of the variable
   1670  * name accordingly.
   1671  */
   1672 static VarAssign
   1673 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
   1674 		  const char *value)
   1675 {
   1676 	VarAssignOp type;
   1677 	VarAssign va;
   1678 
   1679 	if (op > name && op[-1] == '+') {
   1680 		op--;
   1681 		type = VAR_APPEND;
   1682 
   1683 	} else if (op > name && op[-1] == '?') {
   1684 		op--;
   1685 		type = VAR_DEFAULT;
   1686 
   1687 	} else if (op > name && op[-1] == ':') {
   1688 		op--;
   1689 		type = VAR_SUBST;
   1690 
   1691 	} else if (op > name && op[-1] == '!') {
   1692 		op--;
   1693 		type = VAR_SHELL;
   1694 
   1695 	} else {
   1696 		type = VAR_NORMAL;
   1697 		while (op > name && ch_isspace(op[-1]))
   1698 			op--;
   1699 
   1700 		if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
   1701 			op -= 3;
   1702 			type = VAR_SHELL;
   1703 		}
   1704 	}
   1705 
   1706 	va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
   1707 	va.op = type;
   1708 	va.value = value;
   1709 	return va;
   1710 }
   1711 
   1712 /*
   1713  * Parse a variable assignment, consisting of a single-word variable name,
   1714  * optional whitespace, an assignment operator, optional whitespace and the
   1715  * variable value.
   1716  *
   1717  * Note: There is a lexical ambiguity with assignment modifier characters
   1718  * in variable names. This routine interprets the character before the =
   1719  * as a modifier. Therefore, an assignment like
   1720  *	C++=/usr/bin/CC
   1721  * is interpreted as "C+ +=" instead of "C++ =".
   1722  *
   1723  * Used for both lines in a file and command line arguments.
   1724  */
   1725 static bool
   1726 Parse_IsVar(const char *p, VarAssign *out_var)
   1727 {
   1728 	const char *nameStart, *nameEnd, *firstSpace, *eq;
   1729 	int level = 0;
   1730 
   1731 	cpp_skip_hspace(&p);	/* Skip to variable name */
   1732 
   1733 	/*
   1734 	 * During parsing, the '+' of the operator '+=' is initially parsed
   1735 	 * as part of the variable name.  It is later corrected, as is the
   1736 	 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
   1737 	 * determines the actual end of the variable name.
   1738 	 */
   1739 
   1740 	nameStart = p;
   1741 	firstSpace = NULL;
   1742 
   1743 	/* Scan for one of the assignment operators outside an expression. */
   1744 	while (*p != '\0') {
   1745 		char ch = *p++;
   1746 		if (ch == '(' || ch == '{') {
   1747 			level++;
   1748 			continue;
   1749 		}
   1750 		if (ch == ')' || ch == '}') {
   1751 			level--;
   1752 			continue;
   1753 		}
   1754 
   1755 		if (level != 0)
   1756 			continue;
   1757 
   1758 		if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
   1759 			firstSpace = p - 1;
   1760 		while (ch == ' ' || ch == '\t')
   1761 			ch = *p++;
   1762 
   1763 		if (ch == '\0')
   1764 			return false;
   1765 		if (ch == ':' && p[0] == 's' && p[1] == 'h') {
   1766 			p += 2;
   1767 			continue;
   1768 		}
   1769 		if (ch == '=')
   1770 			eq = p - 1;
   1771 		else if (*p == '=' &&
   1772 		    (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
   1773 			eq = p;
   1774 		else if (firstSpace != NULL)
   1775 			return false;
   1776 		else
   1777 			continue;
   1778 
   1779 		nameEnd = firstSpace != NULL ? firstSpace : eq;
   1780 		p = eq + 1;
   1781 		cpp_skip_whitespace(&p);
   1782 		*out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
   1783 		return true;
   1784 	}
   1785 
   1786 	return false;
   1787 }
   1788 
   1789 /*
   1790  * Check for syntax errors such as unclosed expressions or unknown modifiers.
   1791  */
   1792 static void
   1793 VarCheckSyntax(VarAssignOp op, const char *uvalue, GNode *scope)
   1794 {
   1795 	if (opts.strict) {
   1796 		if (op != VAR_SUBST && strchr(uvalue, '$') != NULL) {
   1797 			char *parsedValue = Var_Subst(uvalue,
   1798 			    scope, VARE_PARSE_ONLY);
   1799 			/* TODO: handle errors */
   1800 			free(parsedValue);
   1801 		}
   1802 	}
   1803 }
   1804 
   1805 /* Perform a variable assignment that uses the operator ':='. */
   1806 static void
   1807 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
   1808 		    FStr *out_avalue)
   1809 {
   1810 	char *evalue;
   1811 
   1812 	/*
   1813 	 * Make sure that we set the variable the first time to nothing
   1814 	 * so that it gets substituted.
   1815 	 *
   1816 	 * TODO: Add a test that demonstrates why this code is needed,
   1817 	 *  apart from making the debug log longer.
   1818 	 *
   1819 	 * XXX: The variable name is expanded up to 3 times.
   1820 	 */
   1821 	if (!Var_ExistsExpand(scope, name))
   1822 		Var_SetExpand(scope, name, "");
   1823 
   1824 	evalue = Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF);
   1825 	/* TODO: handle errors */
   1826 
   1827 	Var_SetExpand(scope, name, evalue);
   1828 
   1829 	*out_avalue = FStr_InitOwn(evalue);
   1830 }
   1831 
   1832 /* Perform a variable assignment that uses the operator '!='. */
   1833 static void
   1834 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
   1835 		    FStr *out_avalue)
   1836 {
   1837 	FStr cmd;
   1838 	char *output, *error;
   1839 
   1840 	cmd = FStr_InitRefer(uvalue);
   1841 	Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
   1842 
   1843 	output = Cmd_Exec(cmd.str, &error);
   1844 	Var_SetExpand(scope, name, output);
   1845 	*out_avalue = FStr_InitOwn(output);
   1846 	if (error != NULL) {
   1847 		Parse_Error(PARSE_WARNING, "%s", error);
   1848 		free(error);
   1849 	}
   1850 
   1851 	FStr_Done(&cmd);
   1852 }
   1853 
   1854 /*
   1855  * Perform a variable assignment.
   1856  *
   1857  * The actual value of the variable is returned in *out_true_avalue.
   1858  * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
   1859  * value.
   1860  *
   1861  * Return whether the assignment was actually performed, which is usually
   1862  * the case.  It is only skipped if the operator is '?=' and the variable
   1863  * already exists.
   1864  */
   1865 static bool
   1866 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
   1867 	       GNode *scope, FStr *out_true_avalue)
   1868 {
   1869 	FStr avalue = FStr_InitRefer(uvalue);
   1870 
   1871 	if (op == VAR_APPEND)
   1872 		Var_AppendExpand(scope, name, uvalue);
   1873 	else if (op == VAR_SUBST)
   1874 		VarAssign_EvalSubst(scope, name, uvalue, &avalue);
   1875 	else if (op == VAR_SHELL)
   1876 		VarAssign_EvalShell(name, uvalue, scope, &avalue);
   1877 	else {
   1878 		/* XXX: The variable name is expanded up to 2 times. */
   1879 		if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
   1880 			return false;
   1881 
   1882 		/* Normal assignment -- just do it. */
   1883 		Var_SetExpand(scope, name, uvalue);
   1884 	}
   1885 
   1886 	*out_true_avalue = avalue;
   1887 	return true;
   1888 }
   1889 
   1890 static void
   1891 VarAssignSpecial(const char *name, const char *avalue)
   1892 {
   1893 	if (strcmp(name, ".MAKEOVERRIDES") == 0)
   1894 		Main_ExportMAKEFLAGS(false);	/* re-export MAKEFLAGS */
   1895 	else if (strcmp(name, ".CURDIR") == 0) {
   1896 		/*
   1897 		 * Someone is being (too?) clever...
   1898 		 * Let's pretend they know what they are doing and
   1899 		 * re-initialize the 'cur' CachedDir.
   1900 		 */
   1901 		Dir_InitCur(avalue);
   1902 		Dir_SetPATH();
   1903 	} else if (strcmp(name, ".MAKE.JOB.PREFIX") == 0)
   1904 		Job_SetPrefix();
   1905 	else if (strcmp(name, ".MAKE.EXPORTED") == 0)
   1906 		Var_ExportVars(avalue);
   1907 }
   1908 
   1909 /* Perform the variable assignment in the given scope. */
   1910 static void
   1911 Parse_Var(VarAssign *var, GNode *scope)
   1912 {
   1913 	FStr avalue;		/* actual value (maybe expanded) */
   1914 
   1915 	VarCheckSyntax(var->op, var->value, scope);
   1916 	if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
   1917 		VarAssignSpecial(var->varname, avalue.str);
   1918 		FStr_Done(&avalue);
   1919 	}
   1920 }
   1921 
   1922 
   1923 /*
   1924  * See if the command possibly calls a sub-make by using the
   1925  * expressions ${.MAKE}, ${MAKE} or the plain word "make".
   1926  */
   1927 static bool
   1928 MaybeSubMake(const char *cmd)
   1929 {
   1930 	const char *start;
   1931 
   1932 	for (start = cmd; *start != '\0'; start++) {
   1933 		const char *p = start;
   1934 		char endc;
   1935 
   1936 		/* XXX: What if progname != "make"? */
   1937 		if (strncmp(p, "make", 4) == 0)
   1938 			if (start == cmd || !ch_isalnum(p[-1]))
   1939 				if (!ch_isalnum(p[4]))
   1940 					return true;
   1941 
   1942 		if (*p != '$')
   1943 			continue;
   1944 		p++;
   1945 
   1946 		if (*p == '{')
   1947 			endc = '}';
   1948 		else if (*p == '(')
   1949 			endc = ')';
   1950 		else
   1951 			continue;
   1952 		p++;
   1953 
   1954 		if (*p == '.')	/* Accept either ${.MAKE} or ${MAKE}. */
   1955 			p++;
   1956 
   1957 		if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
   1958 			return true;
   1959 	}
   1960 	return false;
   1961 }
   1962 
   1963 /* Append the command to the target node. */
   1964 static void
   1965 GNode_AddCommand(GNode *gn, char *cmd)
   1966 {
   1967 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
   1968 		gn = gn->cohorts.last->datum;
   1969 
   1970 	/* if target already supplied, ignore commands */
   1971 	if (!(gn->type & OP_HAS_COMMANDS)) {
   1972 		Lst_Append(&gn->commands, cmd);
   1973 		if (MaybeSubMake(cmd))
   1974 			gn->type |= OP_SUBMAKE;
   1975 		RememberLocation(gn);
   1976 	} else {
   1977 		Parse_Error(PARSE_WARNING,
   1978 		    "duplicate script for target \"%s\" ignored",
   1979 		    gn->name);
   1980 		ParseErrorInternal(gn, PARSE_WARNING,
   1981 		    "using previous script for \"%s\" defined here",
   1982 		    gn->name);
   1983 	}
   1984 }
   1985 
   1986 /*
   1987  * Parse a directive like '.include' or '.-include'.
   1988  *
   1989  * .include "user-makefile.mk"
   1990  * .include <system-makefile.mk>
   1991  */
   1992 static void
   1993 ParseInclude(char *directive)
   1994 {
   1995 	char endc;		/* '>' or '"' */
   1996 	char *p;
   1997 	bool silent = directive[0] != 'i';
   1998 	FStr file;
   1999 
   2000 	p = directive + (silent ? 8 : 7);
   2001 	pp_skip_hspace(&p);
   2002 
   2003 	if (*p != '"' && *p != '<') {
   2004 		Parse_Error(PARSE_FATAL,
   2005 		    ".include filename must be delimited by '\"' or '<'");
   2006 		return;
   2007 	}
   2008 
   2009 	endc = *p++ == '<' ? '>' : '"';
   2010 	file = FStr_InitRefer(p);
   2011 
   2012 	while (*p != '\0' && *p != endc)
   2013 		p++;
   2014 
   2015 	if (*p != endc) {
   2016 		Parse_Error(PARSE_FATAL,
   2017 		    "Unclosed .include filename. '%c' expected", endc);
   2018 		return;
   2019 	}
   2020 
   2021 	*p = '\0';
   2022 
   2023 	Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
   2024 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
   2025 	FStr_Done(&file);
   2026 }
   2027 
   2028 /*
   2029  * Split filename into dirname + basename, then assign these to the
   2030  * given variables.
   2031  */
   2032 static void
   2033 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
   2034 {
   2035 	const char *slash, *basename;
   2036 	FStr dirname;
   2037 
   2038 	slash = strrchr(filename, '/');
   2039 	if (slash == NULL) {
   2040 		dirname = FStr_InitRefer(curdir);
   2041 		basename = filename;
   2042 	} else {
   2043 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
   2044 		basename = slash + 1;
   2045 	}
   2046 
   2047 	Global_Set(dirvar, dirname.str);
   2048 	Global_Set(filevar, basename);
   2049 
   2050 	DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
   2051 	    dirvar, dirname.str, filevar, basename);
   2052 	FStr_Done(&dirname);
   2053 }
   2054 
   2055 /*
   2056  * Return the immediately including file.
   2057  *
   2058  * This is made complicated since the .for loop is implemented as a special
   2059  * kind of .include; see For_Run.
   2060  */
   2061 static const char *
   2062 GetActuallyIncludingFile(void)
   2063 {
   2064 	size_t i;
   2065 	const IncludedFile *incs = GetInclude(0);
   2066 
   2067 	for (i = includes.len; i >= 2; i--)
   2068 		if (incs[i - 1].forLoop == NULL)
   2069 			return incs[i - 2].name.str;
   2070 	return NULL;
   2071 }
   2072 
   2073 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
   2074 static void
   2075 SetParseFile(const char *filename)
   2076 {
   2077 	const char *including;
   2078 
   2079 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
   2080 
   2081 	including = GetActuallyIncludingFile();
   2082 	if (including != NULL) {
   2083 		SetFilenameVars(including,
   2084 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
   2085 	} else {
   2086 		Global_Delete(".INCLUDEDFROMDIR");
   2087 		Global_Delete(".INCLUDEDFROMFILE");
   2088 	}
   2089 }
   2090 
   2091 static bool
   2092 StrContainsWord(const char *str, const char *word)
   2093 {
   2094 	size_t strLen = strlen(str);
   2095 	size_t wordLen = strlen(word);
   2096 	const char *p;
   2097 
   2098 	if (strLen < wordLen)
   2099 		return false;
   2100 
   2101 	for (p = str; p != NULL; p = strchr(p, ' ')) {
   2102 		if (*p == ' ')
   2103 			p++;
   2104 		if (p > str + strLen - wordLen)
   2105 			return false;
   2106 
   2107 		if (memcmp(p, word, wordLen) == 0 &&
   2108 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
   2109 			return true;
   2110 	}
   2111 	return false;
   2112 }
   2113 
   2114 /*
   2115  * XXX: Searching through a set of words with this linear search is
   2116  * inefficient for variables that contain thousands of words.
   2117  *
   2118  * XXX: The paths in this list don't seem to be normalized in any way.
   2119  */
   2120 static bool
   2121 VarContainsWord(const char *varname, const char *word)
   2122 {
   2123 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
   2124 	bool found = val.str != NULL && StrContainsWord(val.str, word);
   2125 	FStr_Done(&val);
   2126 	return found;
   2127 }
   2128 
   2129 /*
   2130  * Track the makefiles we read - so makefiles can set dependencies on them.
   2131  * Avoid adding anything more than once.
   2132  *
   2133  * Time complexity: O(n) per call, in total O(n^2), where n is the number
   2134  * of makefiles that have been loaded.
   2135  */
   2136 static void
   2137 TrackInput(const char *name)
   2138 {
   2139 	if (!VarContainsWord(".MAKE.MAKEFILES", name))
   2140 		Global_Append(".MAKE.MAKEFILES", name);
   2141 }
   2142 
   2143 
   2144 /* Parse from the given buffer, later return to the current file. */
   2145 void
   2146 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
   2147 		Buffer buf, struct ForLoop *forLoop)
   2148 {
   2149 	IncludedFile *curFile;
   2150 
   2151 	if (forLoop != NULL)
   2152 		name = CurFile()->name.str;
   2153 	else
   2154 		TrackInput(name);
   2155 
   2156 	DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
   2157 	    forLoop != NULL ? ".for loop in": "file", name, lineno);
   2158 
   2159 	curFile = Vector_Push(&includes);
   2160 	curFile->name = FStr_InitOwn(bmake_strdup(name));
   2161 	curFile->lineno = lineno;
   2162 	curFile->readLines = readLines;
   2163 	curFile->forHeadLineno = lineno;
   2164 	curFile->forBodyReadLines = readLines;
   2165 	curFile->buf = buf;
   2166 	curFile->depending = doing_depend;	/* restore this on EOF */
   2167 	curFile->guardState = forLoop == NULL ? GS_START : GS_NO;
   2168 	curFile->guard = NULL;
   2169 	curFile->forLoop = forLoop;
   2170 
   2171 	if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
   2172 		abort();	/* see For_Run */
   2173 
   2174 	curFile->buf_ptr = curFile->buf.data;
   2175 	curFile->buf_end = curFile->buf.data + curFile->buf.len;
   2176 	curFile->condMinDepth = cond_depth;
   2177 	SetParseFile(name);
   2178 }
   2179 
   2180 /* Check if the directive is an include directive. */
   2181 static bool
   2182 IsInclude(const char *dir, bool sysv)
   2183 {
   2184 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
   2185 		dir++;
   2186 
   2187 	if (strncmp(dir, "include", 7) != 0)
   2188 		return false;
   2189 
   2190 	/* Space is not mandatory for BSD .include */
   2191 	return !sysv || ch_isspace(dir[7]);
   2192 }
   2193 
   2194 
   2195 /* Check if the line is a SYSV include directive. */
   2196 static bool
   2197 IsSysVInclude(const char *line)
   2198 {
   2199 	const char *p;
   2200 
   2201 	if (!IsInclude(line, true))
   2202 		return false;
   2203 
   2204 	/* Avoid interpreting a dependency line as an include */
   2205 	for (p = line; (p = strchr(p, ':')) != NULL;) {
   2206 
   2207 		/* end of line -> it's a dependency */
   2208 		if (*++p == '\0')
   2209 			return false;
   2210 
   2211 		/* '::' operator or ': ' -> it's a dependency */
   2212 		if (*p == ':' || ch_isspace(*p))
   2213 			return false;
   2214 	}
   2215 	return true;
   2216 }
   2217 
   2218 /* Push to another file.  The line points to the word "include". */
   2219 static void
   2220 ParseTraditionalInclude(char *line)
   2221 {
   2222 	char *p;		/* current position in file spec */
   2223 	bool done = false;
   2224 	bool silent = line[0] != 'i';
   2225 	char *file = line + (silent ? 8 : 7);
   2226 	char *all_files;
   2227 
   2228 	DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
   2229 
   2230 	pp_skip_whitespace(&file);
   2231 
   2232 	all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES);
   2233 	/* TODO: handle errors */
   2234 
   2235 	for (file = all_files; !done; file = p + 1) {
   2236 		/* Skip to end of line or next whitespace */
   2237 		for (p = file; *p != '\0' && !ch_isspace(*p); p++)
   2238 			continue;
   2239 
   2240 		if (*p != '\0')
   2241 			*p = '\0';
   2242 		else
   2243 			done = true;
   2244 
   2245 		IncludeFile(file, false, false, silent);
   2246 	}
   2247 
   2248 	free(all_files);
   2249 }
   2250 
   2251 /* Parse "export <variable>=<value>", and actually export it. */
   2252 static void
   2253 ParseGmakeExport(char *line)
   2254 {
   2255 	char *variable = line + 6;
   2256 	char *value;
   2257 
   2258 	DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
   2259 
   2260 	pp_skip_whitespace(&variable);
   2261 
   2262 	for (value = variable; *value != '\0' && *value != '='; value++)
   2263 		continue;
   2264 
   2265 	if (*value != '=') {
   2266 		Parse_Error(PARSE_FATAL,
   2267 		    "Variable/Value missing from \"export\"");
   2268 		return;
   2269 	}
   2270 	*value++ = '\0';	/* terminate variable */
   2271 
   2272 	/*
   2273 	 * Expand the value before putting it in the environment.
   2274 	 */
   2275 	value = Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES);
   2276 	/* TODO: handle errors */
   2277 
   2278 	setenv(variable, value, 1);
   2279 	free(value);
   2280 }
   2281 
   2282 /*
   2283  * When the end of the current file or .for loop is reached, continue reading
   2284  * the previous file at the previous location.
   2285  *
   2286  * Results:
   2287  *	true to continue parsing, i.e. it had only reached the end of an
   2288  *	included file, false if the main file has been parsed completely.
   2289  */
   2290 static bool
   2291 ParseEOF(void)
   2292 {
   2293 	IncludedFile *curFile = CurFile();
   2294 
   2295 	doing_depend = curFile->depending;
   2296 	if (curFile->forLoop != NULL &&
   2297 	    For_NextIteration(curFile->forLoop, &curFile->buf)) {
   2298 		curFile->buf_ptr = curFile->buf.data;
   2299 		curFile->buf_end = curFile->buf.data + curFile->buf.len;
   2300 		curFile->readLines = curFile->forBodyReadLines;
   2301 		return true;
   2302 	}
   2303 
   2304 	Cond_EndFile();
   2305 
   2306 	if (curFile->guardState == GS_DONE)
   2307 		HashTable_Set(&guards, curFile->name.str, curFile->guard);
   2308 	else if (curFile->guard != NULL) {
   2309 		free(curFile->guard->name);
   2310 		free(curFile->guard);
   2311 	}
   2312 
   2313 	FStr_Done(&curFile->name);
   2314 	Buf_Done(&curFile->buf);
   2315 	if (curFile->forLoop != NULL)
   2316 		ForLoop_Free(curFile->forLoop);
   2317 	Vector_Pop(&includes);
   2318 
   2319 	if (includes.len == 0) {
   2320 		/* We've run out of input */
   2321 		Global_Delete(".PARSEDIR");
   2322 		Global_Delete(".PARSEFILE");
   2323 		Global_Delete(".INCLUDEDFROMDIR");
   2324 		Global_Delete(".INCLUDEDFROMFILE");
   2325 		return false;
   2326 	}
   2327 
   2328 	curFile = CurFile();
   2329 	DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
   2330 	    curFile->name.str, curFile->readLines + 1);
   2331 
   2332 	SetParseFile(curFile->name.str);
   2333 	return true;
   2334 }
   2335 
   2336 typedef enum ParseRawLineResult {
   2337 	PRLR_LINE,
   2338 	PRLR_EOF,
   2339 	PRLR_ERROR
   2340 } ParseRawLineResult;
   2341 
   2342 /*
   2343  * Parse until the end of a line, taking into account lines that end with
   2344  * backslash-newline.  The resulting line goes from out_line to out_line_end;
   2345  * the line is not null-terminated.
   2346  */
   2347 static ParseRawLineResult
   2348 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
   2349 	     char **out_firstBackslash, char **out_commentLineEnd)
   2350 {
   2351 	char *line = curFile->buf_ptr;
   2352 	char *buf_end = curFile->buf_end;
   2353 	char *p = line;
   2354 	char *line_end = line;
   2355 	char *firstBackslash = NULL;
   2356 	char *commentLineEnd = NULL;
   2357 	ParseRawLineResult res = PRLR_LINE;
   2358 
   2359 	curFile->readLines++;
   2360 
   2361 	for (;;) {
   2362 		char ch;
   2363 
   2364 		if (p == buf_end) {
   2365 			res = PRLR_EOF;
   2366 			break;
   2367 		}
   2368 
   2369 		ch = *p;
   2370 		if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
   2371 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
   2372 			exit(2);
   2373 		}
   2374 
   2375 		/* Treat next character after '\' as literal. */
   2376 		if (ch == '\\') {
   2377 			if (firstBackslash == NULL)
   2378 				firstBackslash = p;
   2379 			if (p[1] == '\n') {
   2380 				curFile->readLines++;
   2381 				if (p + 2 == buf_end) {
   2382 					line_end = p;
   2383 					*line_end = '\n';
   2384 					p += 2;
   2385 					continue;
   2386 				}
   2387 			}
   2388 			p += 2;
   2389 			line_end = p;
   2390 			assert(p <= buf_end);
   2391 			continue;
   2392 		}
   2393 
   2394 		/*
   2395 		 * Remember the first '#' for comment stripping, unless
   2396 		 * the previous char was '[', as in the modifier ':[#]'.
   2397 		 */
   2398 		if (ch == '#' && commentLineEnd == NULL &&
   2399 		    !(p > line && p[-1] == '['))
   2400 			commentLineEnd = line_end;
   2401 
   2402 		p++;
   2403 		if (ch == '\n')
   2404 			break;
   2405 
   2406 		/* We are not interested in trailing whitespace. */
   2407 		if (!ch_isspace(ch))
   2408 			line_end = p;
   2409 	}
   2410 
   2411 	curFile->buf_ptr = p;
   2412 	*out_line = line;
   2413 	*out_line_end = line_end;
   2414 	*out_firstBackslash = firstBackslash;
   2415 	*out_commentLineEnd = commentLineEnd;
   2416 	return res;
   2417 }
   2418 
   2419 /*
   2420  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
   2421  * with a single space.
   2422  */
   2423 static void
   2424 UnescapeBackslash(char *line, char *start)
   2425 {
   2426 	const char *src = start;
   2427 	char *dst = start;
   2428 	char *spaceStart = line;
   2429 
   2430 	for (;;) {
   2431 		char ch = *src++;
   2432 		if (ch != '\\') {
   2433 			if (ch == '\0')
   2434 				break;
   2435 			*dst++ = ch;
   2436 			continue;
   2437 		}
   2438 
   2439 		ch = *src++;
   2440 		if (ch == '\0') {
   2441 			/* Delete '\\' at the end of the buffer. */
   2442 			dst--;
   2443 			break;
   2444 		}
   2445 
   2446 		/* Delete '\\' from before '#' on non-command lines. */
   2447 		if (ch == '#' && line[0] != '\t')
   2448 			*dst++ = ch;
   2449 		else if (ch == '\n') {
   2450 			cpp_skip_hspace(&src);
   2451 			*dst++ = ' ';
   2452 		} else {
   2453 			/* Leave '\\' in the buffer for later. */
   2454 			*dst++ = '\\';
   2455 			*dst++ = ch;
   2456 			/* Keep an escaped ' ' at the line end. */
   2457 			spaceStart = dst;
   2458 		}
   2459 	}
   2460 
   2461 	/* Delete any trailing spaces - eg from empty continuations */
   2462 	while (dst > spaceStart && ch_isspace(dst[-1]))
   2463 		dst--;
   2464 	*dst = '\0';
   2465 }
   2466 
   2467 typedef enum LineKind {
   2468 	/*
   2469 	 * Return the next line that is neither empty nor a comment.
   2470 	 * Backslash line continuations are folded into a single space.
   2471 	 * A trailing comment, if any, is discarded.
   2472 	 */
   2473 	LK_NONEMPTY,
   2474 
   2475 	/*
   2476 	 * Return the next line, even if it is empty or a comment.
   2477 	 * Preserve backslash-newline to keep the line numbers correct.
   2478 	 *
   2479 	 * Used in .for loops to collect the body of the loop while waiting
   2480 	 * for the corresponding .endfor.
   2481 	 */
   2482 	LK_FOR_BODY,
   2483 
   2484 	/*
   2485 	 * Return the next line that starts with a dot.
   2486 	 * Backslash line continuations are folded into a single space.
   2487 	 * A trailing comment, if any, is discarded.
   2488 	 *
   2489 	 * Used in .if directives to skip over irrelevant branches while
   2490 	 * waiting for the corresponding .endif.
   2491 	 */
   2492 	LK_DOT
   2493 } LineKind;
   2494 
   2495 /*
   2496  * Return the next "interesting" logical line from the current file.  The
   2497  * returned string will be freed at the end of including the file.
   2498  */
   2499 static char *
   2500 ReadLowLevelLine(LineKind kind)
   2501 {
   2502 	IncludedFile *curFile = CurFile();
   2503 	ParseRawLineResult res;
   2504 	char *line;
   2505 	char *line_end;
   2506 	char *firstBackslash;
   2507 	char *commentLineEnd;
   2508 
   2509 	for (;;) {
   2510 		curFile->lineno = curFile->readLines + 1;
   2511 		res = ParseRawLine(curFile,
   2512 		    &line, &line_end, &firstBackslash, &commentLineEnd);
   2513 		if (res == PRLR_ERROR)
   2514 			return NULL;
   2515 
   2516 		if (line == line_end || line == commentLineEnd) {
   2517 			if (res == PRLR_EOF)
   2518 				return NULL;
   2519 			if (kind != LK_FOR_BODY)
   2520 				continue;
   2521 		}
   2522 
   2523 		/* We now have a line of data */
   2524 		assert(ch_isspace(*line_end));
   2525 		*line_end = '\0';
   2526 
   2527 		if (kind == LK_FOR_BODY)
   2528 			return line;	/* Don't join the physical lines. */
   2529 
   2530 		if (kind == LK_DOT && line[0] != '.')
   2531 			continue;
   2532 		break;
   2533 	}
   2534 
   2535 	if (commentLineEnd != NULL && line[0] != '\t')
   2536 		*commentLineEnd = '\0';
   2537 	if (firstBackslash != NULL)
   2538 		UnescapeBackslash(line, firstBackslash);
   2539 	return line;
   2540 }
   2541 
   2542 static bool
   2543 SkipIrrelevantBranches(void)
   2544 {
   2545 	const char *line;
   2546 
   2547 	while ((line = ReadLowLevelLine(LK_DOT)) != NULL)
   2548 		if (Cond_EvalLine(line) == CR_TRUE)
   2549 			return true;
   2550 	return false;
   2551 }
   2552 
   2553 static bool
   2554 ParseForLoop(const char *line)
   2555 {
   2556 	int rval;
   2557 	unsigned forHeadLineno;
   2558 	unsigned bodyReadLines;
   2559 	int forLevel;
   2560 
   2561 	rval = For_Eval(line);
   2562 	if (rval == 0)
   2563 		return false;	/* Not a .for line */
   2564 	if (rval < 0)
   2565 		return true;	/* Syntax error - error printed, ignore line */
   2566 
   2567 	forHeadLineno = CurFile()->lineno;
   2568 	bodyReadLines = CurFile()->readLines;
   2569 
   2570 	/* Accumulate the loop body until the matching '.endfor'. */
   2571 	forLevel = 1;
   2572 	do {
   2573 		line = ReadLowLevelLine(LK_FOR_BODY);
   2574 		if (line == NULL) {
   2575 			Parse_Error(PARSE_FATAL,
   2576 			    "Unexpected end of file in .for loop");
   2577 			break;
   2578 		}
   2579 	} while (For_Accum(line, &forLevel));
   2580 
   2581 	For_Run(forHeadLineno, bodyReadLines);
   2582 	return true;
   2583 }
   2584 
   2585 /*
   2586  * Read an entire line from the input file.
   2587  *
   2588  * Empty lines, .if and .for are handled by this function, while variable
   2589  * assignments, other directives, dependency lines and shell commands are
   2590  * handled by the caller.
   2591  *
   2592  * Return a line without trailing whitespace, or NULL for EOF.  The returned
   2593  * string will be freed at the end of including the file.
   2594  */
   2595 static char *
   2596 ReadHighLevelLine(void)
   2597 {
   2598 	char *line;
   2599 	CondResult condResult;
   2600 
   2601 	for (;;) {
   2602 		IncludedFile *curFile = CurFile();
   2603 		line = ReadLowLevelLine(LK_NONEMPTY);
   2604 		if (posix_state == PS_MAYBE_NEXT_LINE)
   2605 			posix_state = PS_NOW_OR_NEVER;
   2606 		else
   2607 			posix_state = PS_TOO_LATE;
   2608 		if (line == NULL)
   2609 			return NULL;
   2610 
   2611 		DEBUG2(PARSE, "Parsing line %u: %s\n", curFile->lineno, line);
   2612 		if (curFile->guardState != GS_NO
   2613 		    && ((curFile->guardState == GS_START && line[0] != '.')
   2614 			|| curFile->guardState == GS_DONE))
   2615 			curFile->guardState = GS_NO;
   2616 		if (line[0] != '.')
   2617 			return line;
   2618 
   2619 		condResult = Cond_EvalLine(line);
   2620 		if (curFile->guardState == GS_START) {
   2621 			Guard *guard;
   2622 			if (condResult != CR_ERROR
   2623 			    && (guard = Cond_ExtractGuard(line)) != NULL) {
   2624 				curFile->guardState = GS_COND;
   2625 				curFile->guard = guard;
   2626 			} else
   2627 				curFile->guardState = GS_NO;
   2628 		}
   2629 		switch (condResult) {
   2630 		case CR_FALSE:	/* May also mean a syntax error. */
   2631 			if (!SkipIrrelevantBranches())
   2632 				return NULL;
   2633 			continue;
   2634 		case CR_TRUE:
   2635 			continue;
   2636 		case CR_ERROR:	/* Not a conditional line */
   2637 			if (ParseForLoop(line))
   2638 				continue;
   2639 			break;
   2640 		}
   2641 		return line;
   2642 	}
   2643 }
   2644 
   2645 static void
   2646 FinishDependencyGroup(void)
   2647 {
   2648 	GNodeListNode *ln;
   2649 
   2650 	if (targets == NULL)
   2651 		return;
   2652 
   2653 	for (ln = targets->first; ln != NULL; ln = ln->next) {
   2654 		GNode *gn = ln->datum;
   2655 
   2656 		Suff_EndTransform(gn);
   2657 
   2658 		/*
   2659 		 * Mark the target as already having commands if it does, to
   2660 		 * keep from having shell commands on multiple dependency
   2661 		 * lines.
   2662 		 */
   2663 		if (!Lst_IsEmpty(&gn->commands))
   2664 			gn->type |= OP_HAS_COMMANDS;
   2665 	}
   2666 
   2667 	Lst_Free(targets);
   2668 	targets = NULL;
   2669 }
   2670 
   2671 /* Add the command to each target from the current dependency spec. */
   2672 static void
   2673 ParseLine_ShellCommand(const char *p)
   2674 {
   2675 	cpp_skip_whitespace(&p);
   2676 	if (*p == '\0')
   2677 		return;		/* skip empty commands */
   2678 
   2679 	if (targets == NULL) {
   2680 		Parse_Error(PARSE_FATAL,
   2681 		    "Unassociated shell command \"%s\"", p);
   2682 		return;
   2683 	}
   2684 
   2685 	{
   2686 		char *cmd = bmake_strdup(p);
   2687 		GNodeListNode *ln;
   2688 
   2689 		for (ln = targets->first; ln != NULL; ln = ln->next) {
   2690 			GNode *gn = ln->datum;
   2691 			GNode_AddCommand(gn, cmd);
   2692 		}
   2693 #ifdef CLEANUP
   2694 		Lst_Append(&targCmds, cmd);
   2695 #endif
   2696 	}
   2697 }
   2698 
   2699 static void
   2700 HandleBreak(const char *arg)
   2701 {
   2702 	IncludedFile *curFile = CurFile();
   2703 
   2704 	if (arg[0] != '\0')
   2705 		Parse_Error(PARSE_FATAL,
   2706 		    "The .break directive does not take arguments");
   2707 
   2708 	if (curFile->forLoop != NULL) {
   2709 		/* pretend we reached EOF */
   2710 		For_Break(curFile->forLoop);
   2711 		cond_depth = CurFile_CondMinDepth();
   2712 		ParseEOF();
   2713 	} else
   2714 		Parse_Error(PARSE_FATAL, "break outside of for loop");
   2715 }
   2716 
   2717 /*
   2718  * See if the line starts with one of the known directives, and if so, handle
   2719  * the directive.
   2720  */
   2721 static bool
   2722 ParseDirective(char *line)
   2723 {
   2724 	char *p = line + 1;
   2725 	const char *arg;
   2726 	Substring dir;
   2727 
   2728 	pp_skip_whitespace(&p);
   2729 	if (IsInclude(p, false)) {
   2730 		ParseInclude(p);
   2731 		return true;
   2732 	}
   2733 
   2734 	dir.start = p;
   2735 	while (ch_islower(*p) || *p == '-')
   2736 		p++;
   2737 	dir.end = p;
   2738 
   2739 	if (*p != '\0' && !ch_isspace(*p))
   2740 		return false;
   2741 
   2742 	pp_skip_whitespace(&p);
   2743 	arg = p;
   2744 
   2745 	if (Substring_Equals(dir, "break"))
   2746 		HandleBreak(arg);
   2747 	else if (Substring_Equals(dir, "undef"))
   2748 		Var_Undef(arg);
   2749 	else if (Substring_Equals(dir, "export"))
   2750 		Var_Export(VEM_PLAIN, arg);
   2751 	else if (Substring_Equals(dir, "export-env"))
   2752 		Var_Export(VEM_ENV, arg);
   2753 	else if (Substring_Equals(dir, "export-literal"))
   2754 		Var_Export(VEM_LITERAL, arg);
   2755 	else if (Substring_Equals(dir, "unexport"))
   2756 		Var_UnExport(false, arg);
   2757 	else if (Substring_Equals(dir, "unexport-env"))
   2758 		Var_UnExport(true, arg);
   2759 	else if (Substring_Equals(dir, "info"))
   2760 		HandleMessage(PARSE_INFO, "info", arg);
   2761 	else if (Substring_Equals(dir, "warning"))
   2762 		HandleMessage(PARSE_WARNING, "warning", arg);
   2763 	else if (Substring_Equals(dir, "error"))
   2764 		HandleMessage(PARSE_FATAL, "error", arg);
   2765 	else
   2766 		return false;
   2767 	return true;
   2768 }
   2769 
   2770 bool
   2771 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
   2772 {
   2773 	VarAssign var;
   2774 
   2775 	if (!Parse_IsVar(line, &var))
   2776 		return false;
   2777 	if (finishDependencyGroup)
   2778 		FinishDependencyGroup();
   2779 	Parse_Var(&var, scope);
   2780 	free(var.varname);
   2781 	return true;
   2782 }
   2783 
   2784 void
   2785 Parse_GuardElse(void)
   2786 {
   2787 	IncludedFile *curFile = CurFile();
   2788 	if (cond_depth == curFile->condMinDepth + 1)
   2789 		curFile->guardState = GS_NO;
   2790 }
   2791 
   2792 void
   2793 Parse_GuardEndif(void)
   2794 {
   2795 	IncludedFile *curFile = CurFile();
   2796 	if (cond_depth == curFile->condMinDepth
   2797 	    && curFile->guardState == GS_COND)
   2798 		curFile->guardState = GS_DONE;
   2799 }
   2800 
   2801 static char *
   2802 FindSemicolon(char *p)
   2803 {
   2804 	int depth = 0;
   2805 
   2806 	for (; *p != '\0'; p++) {
   2807 		if (*p == '\\' && p[1] != '\0') {
   2808 			p++;
   2809 			continue;
   2810 		}
   2811 
   2812 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
   2813 			depth++;
   2814 		else if (depth > 0 && (*p == ')' || *p == '}'))
   2815 			depth--;
   2816 		else if (depth == 0 && *p == ';')
   2817 			break;
   2818 	}
   2819 	return p;
   2820 }
   2821 
   2822 static void
   2823 ParseDependencyLine(char *line)
   2824 {
   2825 	VarEvalMode emode;
   2826 	char *expanded_line;
   2827 	const char *shellcmd = NULL;
   2828 
   2829 	{
   2830 		char *semicolon = FindSemicolon(line);
   2831 		if (*semicolon != '\0') {
   2832 			/* Terminate the dependency list at the ';' */
   2833 			*semicolon = '\0';
   2834 			shellcmd = semicolon + 1;
   2835 		}
   2836 	}
   2837 
   2838 	/*
   2839 	 * We now know it's a dependency line, so it needs to have all
   2840 	 * variables expanded before being parsed.
   2841 	 *
   2842 	 * XXX: Ideally the dependency line would first be split into
   2843 	 * its left-hand side, dependency operator and right-hand side,
   2844 	 * and then each side would be expanded on its own.  This would
   2845 	 * allow for the left-hand side to allow only defined variables
   2846 	 * and to allow variables on the right-hand side to be undefined
   2847 	 * as well.
   2848 	 *
   2849 	 * Parsing the line first would also prevent that targets
   2850 	 * generated from expressions are interpreted as the
   2851 	 * dependency operator, such as in "target${:U\:} middle: source",
   2852 	 * in which the middle is interpreted as a source, not a target.
   2853 	 */
   2854 
   2855 	/*
   2856 	 * In lint mode, allow undefined variables to appear in dependency
   2857 	 * lines.
   2858 	 *
   2859 	 * Ideally, only the right-hand side would allow undefined variables
   2860 	 * since it is common to have optional dependencies. Having undefined
   2861 	 * variables on the left-hand side is more unusual though.  Since
   2862 	 * both sides are expanded in a single pass, there is not much choice
   2863 	 * what to do here.
   2864 	 *
   2865 	 * In normal mode, it does not matter whether undefined variables are
   2866 	 * allowed or not since as of 2020-09-14, Var_Parse does not print
   2867 	 * any parse errors in such a case. It simply returns the special
   2868 	 * empty string var_Error, which cannot be detected in the result of
   2869 	 * Var_Subst.
   2870 	 */
   2871 	emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
   2872 	expanded_line = Var_Subst(line, SCOPE_CMDLINE, emode);
   2873 	/* TODO: handle errors */
   2874 
   2875 	/* Need a fresh list for the target nodes */
   2876 	if (targets != NULL)
   2877 		Lst_Free(targets);
   2878 	targets = Lst_New();
   2879 
   2880 	ParseDependency(expanded_line, line);
   2881 	free(expanded_line);
   2882 
   2883 	if (shellcmd != NULL)
   2884 		ParseLine_ShellCommand(shellcmd);
   2885 }
   2886 
   2887 static void
   2888 ParseLine(char *line)
   2889 {
   2890 	if (line[0] == '.' && ParseDirective(line))
   2891 		return;
   2892 
   2893 	if (line[0] == '\t') {
   2894 		ParseLine_ShellCommand(line + 1);
   2895 		return;
   2896 	}
   2897 
   2898 	if (IsSysVInclude(line)) {
   2899 		ParseTraditionalInclude(line);
   2900 		return;
   2901 	}
   2902 
   2903 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
   2904 	    strchr(line, ':') == NULL) {
   2905 		ParseGmakeExport(line);
   2906 		return;
   2907 	}
   2908 
   2909 	if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
   2910 		return;
   2911 
   2912 	FinishDependencyGroup();
   2913 
   2914 	ParseDependencyLine(line);
   2915 }
   2916 
   2917 /* Interpret a top-level makefile. */
   2918 void
   2919 Parse_File(const char *name, int fd)
   2920 {
   2921 	char *line;
   2922 	Buffer buf;
   2923 
   2924 	buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
   2925 	if (fd != -1)
   2926 		(void)close(fd);
   2927 
   2928 	assert(targets == NULL);
   2929 
   2930 	Parse_PushInput(name, 1, 0, buf, NULL);
   2931 
   2932 	do {
   2933 		while ((line = ReadHighLevelLine()) != NULL) {
   2934 			ParseLine(line);
   2935 		}
   2936 	} while (ParseEOF());
   2937 
   2938 	FinishDependencyGroup();
   2939 
   2940 	if (parseErrors != 0) {
   2941 		(void)fflush(stdout);
   2942 		(void)fprintf(stderr,
   2943 		    "%s: Fatal errors encountered -- cannot continue\n",
   2944 		    progname);
   2945 		PrintOnError(NULL, "");
   2946 		exit(1);
   2947 	}
   2948 }
   2949 
   2950 /* Initialize the parsing module. */
   2951 void
   2952 Parse_Init(void)
   2953 {
   2954 	mainNode = NULL;
   2955 	parseIncPath = SearchPath_New();
   2956 	sysIncPath = SearchPath_New();
   2957 	defSysIncPath = SearchPath_New();
   2958 	Vector_Init(&includes, sizeof(IncludedFile));
   2959 	HashTable_Init(&guards);
   2960 }
   2961 
   2962 /* Clean up the parsing module. */
   2963 void
   2964 Parse_End(void)
   2965 {
   2966 #ifdef CLEANUP
   2967 	HashIter hi;
   2968 
   2969 	Lst_DoneFree(&targCmds);
   2970 	assert(targets == NULL);
   2971 	SearchPath_Free(defSysIncPath);
   2972 	SearchPath_Free(sysIncPath);
   2973 	SearchPath_Free(parseIncPath);
   2974 	assert(includes.len == 0);
   2975 	Vector_Done(&includes);
   2976 	HashIter_Init(&hi, &guards);
   2977 	while (HashIter_Next(&hi) != NULL) {
   2978 		Guard *guard = hi.entry->value;
   2979 		free(guard->name);
   2980 		free(guard);
   2981 	}
   2982 	HashTable_Done(&guards);
   2983 #endif
   2984 }
   2985 
   2986 
   2987 /* Populate the list with the single main target to create, or error out. */
   2988 void
   2989 Parse_MainName(GNodeList *mainList)
   2990 {
   2991 	if (mainNode == NULL)
   2992 		Punt("no target to make.");
   2993 
   2994 	Lst_Append(mainList, mainNode);
   2995 	if (mainNode->type & OP_DOUBLEDEP)
   2996 		Lst_AppendAll(mainList, &mainNode->cohorts);
   2997 
   2998 	Global_Append(".TARGETS", mainNode->name);
   2999 }
   3000 
   3001 int
   3002 Parse_NumErrors(void)
   3003 {
   3004 	return parseErrors;
   3005 }
   3006