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