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