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