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