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