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