Home | History | Annotate | Line # | Download | only in make
parse.c revision 1.578
      1 /*	$NetBSD: parse.c,v 1.578 2021/12/14 00:02:57 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.578 2021/12/14 00:02:57 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 GNodeType
   1269 ParseDependencyOp(char **pp)
   1270 {
   1271 	if (**pp == '!')
   1272 		return (*pp)++, OP_FORCE;
   1273 	if ((*pp)[1] == ':')
   1274 		return (*pp) += 2, OP_DOUBLEDEP;
   1275 	else
   1276 		return (*pp)++, OP_DEPENDS;
   1277 }
   1278 
   1279 static void
   1280 ClearPaths(SearchPathList *paths)
   1281 {
   1282 	if (paths != NULL) {
   1283 		SearchPathListNode *ln;
   1284 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1285 			SearchPath_Clear(ln->datum);
   1286 	}
   1287 
   1288 	Dir_SetPATH();
   1289 }
   1290 
   1291 /*
   1292  * Several special targets take different actions if present with no
   1293  * sources:
   1294  *	a .SUFFIXES line with no sources clears out all old suffixes
   1295  *	a .PRECIOUS line makes all targets precious
   1296  *	a .IGNORE line ignores errors for all targets
   1297  *	a .SILENT line creates silence when making all targets
   1298  *	a .PATH removes all directories from the search path(s).
   1299  */
   1300 static void
   1301 ParseDependencySourcesEmpty(ParseSpecial specType, SearchPathList *paths)
   1302 {
   1303 	switch (specType) {
   1304 	case SP_SUFFIXES:
   1305 		Suff_ClearSuffixes();
   1306 		break;
   1307 	case SP_PRECIOUS:
   1308 		allPrecious = true;
   1309 		break;
   1310 	case SP_IGNORE:
   1311 		opts.ignoreErrors = true;
   1312 		break;
   1313 	case SP_SILENT:
   1314 		opts.beSilent = true;
   1315 		break;
   1316 	case SP_PATH:
   1317 		ClearPaths(paths);
   1318 		break;
   1319 #ifdef POSIX
   1320 	case SP_POSIX:
   1321 		Global_Set("%POSIX", "1003.2");
   1322 		break;
   1323 #endif
   1324 	default:
   1325 		break;
   1326 	}
   1327 }
   1328 
   1329 static void
   1330 AddToPaths(const char *dir, SearchPathList *paths)
   1331 {
   1332 	if (paths != NULL) {
   1333 		SearchPathListNode *ln;
   1334 		for (ln = paths->first; ln != NULL; ln = ln->next)
   1335 			(void)SearchPath_Add(ln->datum, dir);
   1336 	}
   1337 }
   1338 
   1339 /*
   1340  * If the target was one that doesn't take files as its sources
   1341  * but takes something like suffixes, we take each
   1342  * space-separated word on the line as a something and deal
   1343  * with it accordingly.
   1344  *
   1345  * If the target was .SUFFIXES, we take each source as a
   1346  * suffix and add it to the list of suffixes maintained by the
   1347  * Suff module.
   1348  *
   1349  * If the target was a .PATH, we add the source as a directory
   1350  * to search on the search path.
   1351  *
   1352  * If it was .INCLUDES, the source is taken to be the suffix of
   1353  * files which will be #included and whose search path should
   1354  * be present in the .INCLUDES variable.
   1355  *
   1356  * If it was .LIBS, the source is taken to be the suffix of
   1357  * files which are considered libraries and whose search path
   1358  * should be present in the .LIBS variable.
   1359  *
   1360  * If it was .NULL, the source is the suffix to use when a file
   1361  * has no valid suffix.
   1362  *
   1363  * If it was .OBJDIR, the source is a new definition for .OBJDIR,
   1364  * and will cause make to do a new chdir to that path.
   1365  */
   1366 static void
   1367 ParseDependencySourceSpecial(ParseSpecial specType, char *word,
   1368 			     SearchPathList *paths)
   1369 {
   1370 	switch (specType) {
   1371 	case SP_SUFFIXES:
   1372 		Suff_AddSuffix(word, &mainNode);
   1373 		break;
   1374 	case SP_PATH:
   1375 		AddToPaths(word, paths);
   1376 		break;
   1377 	case SP_INCLUDES:
   1378 		Suff_AddInclude(word);
   1379 		break;
   1380 	case SP_LIBS:
   1381 		Suff_AddLib(word);
   1382 		break;
   1383 	case SP_NULL:
   1384 		Suff_SetNull(word);
   1385 		break;
   1386 	case SP_OBJDIR:
   1387 		Main_SetObjdir(false, "%s", word);
   1388 		break;
   1389 	default:
   1390 		break;
   1391 	}
   1392 }
   1393 
   1394 static bool
   1395 ParseDependencyTargets(char **inout_cp,
   1396 		       char **inout_line,
   1397 		       const char *lstart,
   1398 		       ParseSpecial *inout_specType,
   1399 		       GNodeType *inout_tOp,
   1400 		       SearchPathList **inout_paths,
   1401 		       StringList *curTargs)
   1402 {
   1403 	char *cp;
   1404 	char *tgt = *inout_line;
   1405 	char savec;
   1406 	const char *p;
   1407 
   1408 	for (;;) {
   1409 		/*
   1410 		 * Here LINE points to the beginning of the next word, and
   1411 		 * LSTART points to the actual beginning of the line.
   1412 		 */
   1413 
   1414 		/* Find the end of the next word. */
   1415 		cp = tgt;
   1416 		p = cp;
   1417 		ParseDependencyTargetWord(&p, lstart);
   1418 		cp += p - cp;
   1419 
   1420 		/*
   1421 		 * If the word is followed by a left parenthesis, it's the
   1422 		 * name of an object file inside an archive (ar file).
   1423 		 */
   1424 		if (!ParseIsEscaped(lstart, cp) && *cp == '(') {
   1425 			/*
   1426 			 * Archives must be handled specially to make sure the
   1427 			 * OP_ARCHV flag is set in their 'type' field, for one
   1428 			 * thing, and because things like "archive(file1.o
   1429 			 * file2.o file3.o)" are permissible.
   1430 			 *
   1431 			 * Arch_ParseArchive will set 'line' to be the first
   1432 			 * non-blank after the archive-spec. It creates/finds
   1433 			 * nodes for the members and places them on the given
   1434 			 * list, returning true if all went well and false if
   1435 			 * there was an error in the specification. On error,
   1436 			 * line should remain untouched.
   1437 			 */
   1438 			if (!Arch_ParseArchive(&tgt, targets, SCOPE_CMDLINE)) {
   1439 				Parse_Error(PARSE_FATAL,
   1440 				    "Error in archive specification: \"%s\"",
   1441 				    tgt);
   1442 				return false;
   1443 			}
   1444 
   1445 			cp = tgt;
   1446 			continue;
   1447 		}
   1448 
   1449 		if (*cp == '\0') {
   1450 			ParseErrorNoDependency(lstart);
   1451 			return false;
   1452 		}
   1453 
   1454 		/* Insert a null terminator. */
   1455 		savec = *cp;
   1456 		*cp = '\0';
   1457 
   1458 		if (!ParseDependencyTarget(tgt, inout_specType, inout_tOp,
   1459 		    inout_paths))
   1460 			return false;
   1461 
   1462 		/*
   1463 		 * Have word in line. Get or create its node and stick it at
   1464 		 * the end of the targets list
   1465 		 */
   1466 		if (*inout_specType == SP_NOT && *tgt != '\0')
   1467 			ParseDependencyTargetMundane(tgt, curTargs);
   1468 		else if (*inout_specType == SP_PATH && *tgt != '.' &&
   1469 			 *tgt != '\0')
   1470 			Parse_Error(PARSE_WARNING, "Extra target (%s) ignored",
   1471 			    tgt);
   1472 
   1473 		/* Don't need the inserted null terminator any more. */
   1474 		*cp = savec;
   1475 
   1476 		/*
   1477 		 * If it is a special type and not .PATH, it's the only target
   1478 		 * we allow on this line.
   1479 		 */
   1480 		if (*inout_specType != SP_NOT && *inout_specType != SP_PATH)
   1481 			ParseDependencyTargetExtraWarn(&cp, lstart);
   1482 		else
   1483 			pp_skip_whitespace(&cp);
   1484 
   1485 		tgt = cp;
   1486 		if (*tgt == '\0')
   1487 			break;
   1488 		if ((*tgt == '!' || *tgt == ':') &&
   1489 		    !ParseIsEscaped(lstart, tgt))
   1490 			break;
   1491 	}
   1492 
   1493 	*inout_cp = cp;
   1494 	*inout_line = tgt;
   1495 	return true;
   1496 }
   1497 
   1498 static void
   1499 ParseDependencySourcesSpecial(char *start, char *end,
   1500 			      ParseSpecial specType, SearchPathList *paths)
   1501 {
   1502 	char savec;
   1503 
   1504 	while (*start != '\0') {
   1505 		while (*end != '\0' && !ch_isspace(*end))
   1506 			end++;
   1507 		savec = *end;
   1508 		*end = '\0';
   1509 		ParseDependencySourceSpecial(specType, start, paths);
   1510 		*end = savec;
   1511 		if (savec != '\0')
   1512 			end++;
   1513 		pp_skip_whitespace(&end);
   1514 		start = end;
   1515 	}
   1516 }
   1517 
   1518 static bool
   1519 ParseDependencySourcesMundane(char *start, char *end,
   1520 			      ParseSpecial specType, GNodeType tOp)
   1521 {
   1522 	while (*start != '\0') {
   1523 		/*
   1524 		 * The targets take real sources, so we must beware of archive
   1525 		 * specifications (i.e. things with left parentheses in them)
   1526 		 * and handle them accordingly.
   1527 		 */
   1528 		for (; *end != '\0' && !ch_isspace(*end); end++) {
   1529 			if (*end == '(' && end > start && end[-1] != '$') {
   1530 				/*
   1531 				 * Only stop for a left parenthesis if it
   1532 				 * isn't at the start of a word (that'll be
   1533 				 * for variable changes later) and isn't
   1534 				 * preceded by a dollar sign (a dynamic
   1535 				 * source).
   1536 				 */
   1537 				break;
   1538 			}
   1539 		}
   1540 
   1541 		if (*end == '(') {
   1542 			GNodeList sources = LST_INIT;
   1543 			if (!Arch_ParseArchive(&start, &sources,
   1544 			    SCOPE_CMDLINE)) {
   1545 				Parse_Error(PARSE_FATAL,
   1546 				    "Error in source archive spec \"%s\"",
   1547 				    start);
   1548 				return false;
   1549 			}
   1550 
   1551 			while (!Lst_IsEmpty(&sources)) {
   1552 				GNode *gn = Lst_Dequeue(&sources);
   1553 				ParseDependencySource(tOp, gn->name, specType);
   1554 			}
   1555 			Lst_Done(&sources);
   1556 			end = start;
   1557 		} else {
   1558 			if (*end != '\0') {
   1559 				*end = '\0';
   1560 				end++;
   1561 			}
   1562 
   1563 			ParseDependencySource(tOp, start, specType);
   1564 		}
   1565 		pp_skip_whitespace(&end);
   1566 		start = end;
   1567 	}
   1568 	return true;
   1569 }
   1570 
   1571 /*
   1572  * In a dependency line like 'targets: sources', parse the sources.
   1573  *
   1574  * See the tests depsrc-*.mk.
   1575  */
   1576 static void
   1577 ParseDependencySources(char *line, char *cp, GNodeType tOp,
   1578 		       ParseSpecial specType, SearchPathList **inout_paths)
   1579 {
   1580 	if (line[0] == '\0') {
   1581 		ParseDependencySourcesEmpty(specType, *inout_paths);
   1582 	} else if (specType == SP_MFLAGS) {
   1583 		Main_ParseArgLine(line);
   1584 		/*
   1585 		 * Set the initial character to a null-character so the loop
   1586 		 * to get sources won't get anything.
   1587 		 */
   1588 		*line = '\0';
   1589 	} else if (specType == SP_SHELL) {
   1590 		if (!Job_ParseShell(line)) {
   1591 			Parse_Error(PARSE_FATAL,
   1592 			    "improper shell specification");
   1593 			return;
   1594 		}
   1595 		*line = '\0';
   1596 	} else if (specType == SP_NOTPARALLEL || specType == SP_SINGLESHELL ||
   1597 		   specType == SP_DELETE_ON_ERROR) {
   1598 		*line = '\0';
   1599 	}
   1600 
   1601 	/* Now go for the sources. */
   1602 	if (specType == SP_SUFFIXES || specType == SP_PATH ||
   1603 	    specType == SP_INCLUDES || specType == SP_LIBS ||
   1604 	    specType == SP_NULL || specType == SP_OBJDIR) {
   1605 		ParseDependencySourcesSpecial(line, cp, specType,
   1606 		    *inout_paths);
   1607 		if (*inout_paths != NULL) {
   1608 			Lst_Free(*inout_paths);
   1609 			*inout_paths = NULL;
   1610 		}
   1611 		if (specType == SP_PATH)
   1612 			Dir_SetPATH();
   1613 	} else {
   1614 		assert(*inout_paths == NULL);
   1615 		if (!ParseDependencySourcesMundane(line, cp, specType, tOp))
   1616 			return;
   1617 	}
   1618 
   1619 	FindMainTarget();
   1620 }
   1621 
   1622 /*
   1623  * Parse a dependency line consisting of targets, followed by a dependency
   1624  * operator, optionally followed by sources.
   1625  *
   1626  * The nodes of the sources are linked as children to the nodes of the
   1627  * targets. Nodes are created as necessary.
   1628  *
   1629  * The operator is applied to each node in the global 'targets' list,
   1630  * which is where the nodes found for the targets are kept, by means of
   1631  * the ParseOp function.
   1632  *
   1633  * The sources are parsed in much the same way as the targets, except
   1634  * that they are expanded using the wildcarding scheme of the C-Shell,
   1635  * and a target is created for each expanded word. Each of the resulting
   1636  * nodes is then linked to each of the targets as one of its children.
   1637  *
   1638  * Certain targets and sources such as .PHONY or .PRECIOUS are handled
   1639  * specially. These are the ones detailed by the specType variable.
   1640  *
   1641  * The storing of transformation rules such as '.c.o' is also taken care of
   1642  * here. A target is recognized as a transformation rule by calling
   1643  * Suff_IsTransform. If it is a transformation rule, its node is gotten
   1644  * from the suffix module via Suff_AddTransform rather than the standard
   1645  * Targ_FindNode in the target module.
   1646  *
   1647  * Upon return, the value of the line is unspecified.
   1648  */
   1649 static void
   1650 ParseDependency(char *line)
   1651 {
   1652 	char *cp;		/* our current position */
   1653 	GNodeType op;		/* the operator on the line */
   1654 	SearchPathList *paths;	/* search paths to alter when parsing
   1655 				 * a list of .PATH targets */
   1656 	GNodeType tOp;		/* operator from special target */
   1657 	/* target names to be found and added to the targets list */
   1658 	StringList curTargs = LST_INIT;
   1659 	char *lstart = line;
   1660 
   1661 	/*
   1662 	 * specType contains the SPECial TYPE of the current target. It is
   1663 	 * SP_NOT if the target is unspecial. If it *is* special, however, the
   1664 	 * children are linked as children of the parent but not vice versa.
   1665 	 */
   1666 	ParseSpecial specType = SP_NOT;
   1667 
   1668 	DEBUG1(PARSE, "ParseDependency(%s)\n", line);
   1669 	tOp = OP_NONE;
   1670 
   1671 	paths = NULL;
   1672 
   1673 	/*
   1674 	 * First, grind through the targets.
   1675 	 */
   1676 	/* XXX: don't use 'line' as an iterator variable */
   1677 	if (!ParseDependencyTargets(&cp, &line, lstart, &specType, &tOp,
   1678 	    &paths, &curTargs))
   1679 		goto out;
   1680 
   1681 	/*
   1682 	 * Don't need the list of target names anymore.
   1683 	 * The targets themselves are now in the global variable 'targets'.
   1684 	 */
   1685 	Lst_Done(&curTargs);
   1686 	Lst_Init(&curTargs);
   1687 
   1688 	if (!Lst_IsEmpty(targets))
   1689 		ParseDependencyCheckSpec(specType);
   1690 
   1691 	/*
   1692 	 * Apply the operator to the target. This is how we remember which
   1693 	 * operator a target was defined with. It fails if the operator
   1694 	 * used isn't consistent across all references.
   1695 	 */
   1696 	op = ParseDependencyOp(&cp);
   1697 	ApplyDependencyOperator(op);
   1698 
   1699 	/*
   1700 	 * Onward to the sources.
   1701 	 *
   1702 	 * LINE will now point to the first source word, if any, or the
   1703 	 * end of the string if not.
   1704 	 */
   1705 	pp_skip_whitespace(&cp);
   1706 	line = cp;		/* XXX: 'line' is an inappropriate name */
   1707 
   1708 	ParseDependencySources(line, cp, tOp, specType, &paths);
   1709 
   1710 out:
   1711 	if (paths != NULL)
   1712 		Lst_Free(paths);
   1713 	Lst_Done(&curTargs);
   1714 }
   1715 
   1716 typedef struct VarAssignParsed {
   1717 	const char *nameStart;	/* unexpanded */
   1718 	const char *nameEnd;	/* before operator adjustment */
   1719 	const char *eq;		/* the '=' of the assignment operator */
   1720 } VarAssignParsed;
   1721 
   1722 /*
   1723  * Determine the assignment operator and adjust the end of the variable
   1724  * name accordingly.
   1725  */
   1726 static void
   1727 AdjustVarassignOp(const VarAssignParsed *pvar, const char *value,
   1728 		  VarAssign *out_var)
   1729 {
   1730 	const char *op = pvar->eq;
   1731 	const char *const name = pvar->nameStart;
   1732 	VarAssignOp type;
   1733 
   1734 	if (op > name && op[-1] == '+') {
   1735 		type = VAR_APPEND;
   1736 		op--;
   1737 
   1738 	} else if (op > name && op[-1] == '?') {
   1739 		op--;
   1740 		type = VAR_DEFAULT;
   1741 
   1742 	} else if (op > name && op[-1] == ':') {
   1743 		op--;
   1744 		type = VAR_SUBST;
   1745 
   1746 	} else if (op > name && op[-1] == '!') {
   1747 		op--;
   1748 		type = VAR_SHELL;
   1749 
   1750 	} else {
   1751 		type = VAR_NORMAL;
   1752 #ifdef SUNSHCMD
   1753 		while (op > name && ch_isspace(op[-1]))
   1754 			op--;
   1755 
   1756 		if (op >= name + 3 && op[-3] == ':' && op[-2] == 's' &&
   1757 		    op[-1] == 'h') {
   1758 			type = VAR_SHELL;
   1759 			op -= 3;
   1760 		}
   1761 #endif
   1762 	}
   1763 
   1764 	{
   1765 		const char *nameEnd = pvar->nameEnd < op ? pvar->nameEnd : op;
   1766 		out_var->varname = bmake_strsedup(pvar->nameStart, nameEnd);
   1767 		out_var->op = type;
   1768 		out_var->value = value;
   1769 	}
   1770 }
   1771 
   1772 /*
   1773  * Parse a variable assignment, consisting of a single-word variable name,
   1774  * optional whitespace, an assignment operator, optional whitespace and the
   1775  * variable value.
   1776  *
   1777  * Note: There is a lexical ambiguity with assignment modifier characters
   1778  * in variable names. This routine interprets the character before the =
   1779  * as a modifier. Therefore, an assignment like
   1780  *	C++=/usr/bin/CC
   1781  * is interpreted as "C+ +=" instead of "C++ =".
   1782  *
   1783  * Used for both lines in a file and command line arguments.
   1784  */
   1785 bool
   1786 Parse_IsVar(const char *p, VarAssign *out_var)
   1787 {
   1788 	VarAssignParsed pvar;
   1789 	const char *firstSpace = NULL;
   1790 	int level = 0;
   1791 
   1792 	cpp_skip_hspace(&p);	/* Skip to variable name */
   1793 
   1794 	/*
   1795 	 * During parsing, the '+' of the '+=' operator is initially parsed
   1796 	 * as part of the variable name.  It is later corrected, as is the
   1797 	 * ':sh' modifier. Of these two (nameEnd and op), the earlier one
   1798 	 * determines the actual end of the variable name.
   1799 	 */
   1800 	pvar.nameStart = p;
   1801 #ifdef CLEANUP
   1802 	pvar.nameEnd = NULL;
   1803 	pvar.eq = NULL;
   1804 #endif
   1805 
   1806 	/*
   1807 	 * Scan for one of the assignment operators outside a variable
   1808 	 * expansion.
   1809 	 */
   1810 	while (*p != '\0') {
   1811 		char ch = *p++;
   1812 		if (ch == '(' || ch == '{') {
   1813 			level++;
   1814 			continue;
   1815 		}
   1816 		if (ch == ')' || ch == '}') {
   1817 			level--;
   1818 			continue;
   1819 		}
   1820 
   1821 		if (level != 0)
   1822 			continue;
   1823 
   1824 		if (ch == ' ' || ch == '\t')
   1825 			if (firstSpace == NULL)
   1826 				firstSpace = p - 1;
   1827 		while (ch == ' ' || ch == '\t')
   1828 			ch = *p++;
   1829 
   1830 #ifdef SUNSHCMD
   1831 		if (ch == ':' && p[0] == 's' && p[1] == 'h') {
   1832 			p += 2;
   1833 			continue;
   1834 		}
   1835 #endif
   1836 		if (ch == '=') {
   1837 			pvar.eq = p - 1;
   1838 			pvar.nameEnd = firstSpace != NULL ? firstSpace : p - 1;
   1839 			cpp_skip_whitespace(&p);
   1840 			AdjustVarassignOp(&pvar, p, out_var);
   1841 			return true;
   1842 		}
   1843 		if (*p == '=' &&
   1844 		    (ch == '+' || ch == ':' || ch == '?' || ch == '!')) {
   1845 			pvar.eq = p;
   1846 			pvar.nameEnd = firstSpace != NULL ? firstSpace : p;
   1847 			p++;
   1848 			cpp_skip_whitespace(&p);
   1849 			AdjustVarassignOp(&pvar, p, out_var);
   1850 			return true;
   1851 		}
   1852 		if (firstSpace != NULL)
   1853 			return false;
   1854 	}
   1855 
   1856 	return false;
   1857 }
   1858 
   1859 /*
   1860  * Check for syntax errors such as unclosed expressions or unknown modifiers.
   1861  */
   1862 static void
   1863 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
   1864 {
   1865 	if (opts.strict) {
   1866 		if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
   1867 			char *expandedValue;
   1868 
   1869 			(void)Var_Subst(uvalue, scope, VARE_PARSE_ONLY,
   1870 			    &expandedValue);
   1871 			/* TODO: handle errors */
   1872 			free(expandedValue);
   1873 		}
   1874 	}
   1875 }
   1876 
   1877 static void
   1878 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
   1879 		    FStr *out_avalue)
   1880 {
   1881 	char *evalue;
   1882 
   1883 	/*
   1884 	 * make sure that we set the variable the first time to nothing
   1885 	 * so that it gets substituted.
   1886 	 *
   1887 	 * TODO: Add a test that demonstrates why this code is needed,
   1888 	 *  apart from making the debug log longer.
   1889 	 */
   1890 	if (!Var_ExistsExpand(scope, name))
   1891 		Var_SetExpand(scope, name, "");
   1892 
   1893 	(void)Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF, &evalue);
   1894 	/* TODO: handle errors */
   1895 
   1896 	Var_SetExpand(scope, name, evalue);
   1897 
   1898 	*out_avalue = FStr_InitOwn(evalue);
   1899 }
   1900 
   1901 static void
   1902 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
   1903 		    FStr *out_avalue)
   1904 {
   1905 	FStr cmd;
   1906 	const char *errfmt;
   1907 	char *cmdOut;
   1908 
   1909 	cmd = FStr_InitRefer(uvalue);
   1910 	if (strchr(cmd.str, '$') != NULL) {
   1911 		char *expanded;
   1912 		(void)Var_Subst(cmd.str, SCOPE_CMDLINE, VARE_UNDEFERR,
   1913 		    &expanded);
   1914 		/* TODO: handle errors */
   1915 		cmd = FStr_InitOwn(expanded);
   1916 	}
   1917 
   1918 	cmdOut = Cmd_Exec(cmd.str, &errfmt);
   1919 	Var_SetExpand(scope, name, cmdOut);
   1920 	*out_avalue = FStr_InitOwn(cmdOut);
   1921 
   1922 	if (errfmt != NULL)
   1923 		Parse_Error(PARSE_WARNING, errfmt, cmd.str);
   1924 
   1925 	FStr_Done(&cmd);
   1926 }
   1927 
   1928 /*
   1929  * Perform a variable assignment.
   1930  *
   1931  * The actual value of the variable is returned in *out_true_avalue.
   1932  * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
   1933  * value.
   1934  *
   1935  * Return whether the assignment was actually performed, which is usually
   1936  * the case.  It is only skipped if the operator is '?=' and the variable
   1937  * already exists.
   1938  */
   1939 static bool
   1940 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
   1941 	       GNode *scope, FStr *out_true_avalue)
   1942 {
   1943 	FStr avalue = FStr_InitRefer(uvalue);
   1944 
   1945 	if (op == VAR_APPEND)
   1946 		Var_AppendExpand(scope, name, uvalue);
   1947 	else if (op == VAR_SUBST)
   1948 		VarAssign_EvalSubst(scope, name, uvalue, &avalue);
   1949 	else if (op == VAR_SHELL)
   1950 		VarAssign_EvalShell(name, uvalue, scope, &avalue);
   1951 	else {
   1952 		if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
   1953 			return false;
   1954 
   1955 		/* Normal assignment -- just do it. */
   1956 		Var_SetExpand(scope, name, uvalue);
   1957 	}
   1958 
   1959 	*out_true_avalue = avalue;
   1960 	return true;
   1961 }
   1962 
   1963 static void
   1964 VarAssignSpecial(const char *name, const char *avalue)
   1965 {
   1966 	if (strcmp(name, MAKEOVERRIDES) == 0)
   1967 		Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */
   1968 	else if (strcmp(name, ".CURDIR") == 0) {
   1969 		/*
   1970 		 * Someone is being (too?) clever...
   1971 		 * Let's pretend they know what they are doing and
   1972 		 * re-initialize the 'cur' CachedDir.
   1973 		 */
   1974 		Dir_InitCur(avalue);
   1975 		Dir_SetPATH();
   1976 	} else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
   1977 		Job_SetPrefix();
   1978 	else if (strcmp(name, MAKE_EXPORTED) == 0)
   1979 		Var_ExportVars(avalue);
   1980 }
   1981 
   1982 /* Perform the variable variable assignment in the given scope. */
   1983 void
   1984 Parse_Var(VarAssign *var, GNode *scope)
   1985 {
   1986 	FStr avalue;	/* actual value (maybe expanded) */
   1987 
   1988 	VarCheckSyntax(var->op, var->value, scope);
   1989 	if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
   1990 		VarAssignSpecial(var->varname, avalue.str);
   1991 		FStr_Done(&avalue);
   1992 	}
   1993 
   1994 	free(var->varname);
   1995 }
   1996 
   1997 
   1998 /*
   1999  * See if the command possibly calls a sub-make by using the variable
   2000  * expressions ${.MAKE}, ${MAKE} or the plain word "make".
   2001  */
   2002 static bool
   2003 MaybeSubMake(const char *cmd)
   2004 {
   2005 	const char *start;
   2006 
   2007 	for (start = cmd; *start != '\0'; start++) {
   2008 		const char *p = start;
   2009 		char endc;
   2010 
   2011 		/* XXX: What if progname != "make"? */
   2012 		if (p[0] == 'm' && p[1] == 'a' && p[2] == 'k' && p[3] == 'e')
   2013 			if (start == cmd || !ch_isalnum(p[-1]))
   2014 				if (!ch_isalnum(p[4]))
   2015 					return true;
   2016 
   2017 		if (*p != '$')
   2018 			continue;
   2019 		p++;
   2020 
   2021 		if (*p == '{')
   2022 			endc = '}';
   2023 		else if (*p == '(')
   2024 			endc = ')';
   2025 		else
   2026 			continue;
   2027 		p++;
   2028 
   2029 		if (*p == '.')	/* Accept either ${.MAKE} or ${MAKE}. */
   2030 			p++;
   2031 
   2032 		if (p[0] == 'M' && p[1] == 'A' && p[2] == 'K' && p[3] == 'E')
   2033 			if (p[4] == endc)
   2034 				return true;
   2035 	}
   2036 	return false;
   2037 }
   2038 
   2039 /*
   2040  * Append the command to the target node.
   2041  *
   2042  * The node may be marked as a submake node if the command is determined to
   2043  * be that.
   2044  */
   2045 static void
   2046 ParseAddCmd(GNode *gn, char *cmd)
   2047 {
   2048 	/* Add to last (ie current) cohort for :: targets */
   2049 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
   2050 		gn = gn->cohorts.last->datum;
   2051 
   2052 	/* if target already supplied, ignore commands */
   2053 	if (!(gn->type & OP_HAS_COMMANDS)) {
   2054 		Lst_Append(&gn->commands, cmd);
   2055 		if (MaybeSubMake(cmd))
   2056 			gn->type |= OP_SUBMAKE;
   2057 		RememberLocation(gn);
   2058 	} else {
   2059 #if 0
   2060 		/* XXX: We cannot do this until we fix the tree */
   2061 		Lst_Append(&gn->commands, cmd);
   2062 		Parse_Error(PARSE_WARNING,
   2063 		    "overriding commands for target \"%s\"; "
   2064 		    "previous commands defined at %s: %d ignored",
   2065 		    gn->name, gn->fname, gn->lineno);
   2066 #else
   2067 		Parse_Error(PARSE_WARNING,
   2068 		    "duplicate script for target \"%s\" ignored",
   2069 		    gn->name);
   2070 		ParseErrorInternal(gn->fname, (size_t)gn->lineno, PARSE_WARNING,
   2071 		    "using previous script for \"%s\" defined here",
   2072 		    gn->name);
   2073 #endif
   2074 	}
   2075 }
   2076 
   2077 /*
   2078  * Add a directory to the path searched for included makefiles bracketed
   2079  * by double-quotes.
   2080  */
   2081 void
   2082 Parse_AddIncludeDir(const char *dir)
   2083 {
   2084 	(void)SearchPath_Add(parseIncPath, dir);
   2085 }
   2086 
   2087 /*
   2088  * Handle one of the .[-ds]include directives by remembering the current file
   2089  * and pushing the included file on the stack.  After the included file has
   2090  * finished, parsing continues with the including file; see Parse_PushInput
   2091  * and ParseEOF.
   2092  *
   2093  * System includes are looked up in sysIncPath, any other includes are looked
   2094  * up in the parsedir and then in the directories specified by the -I command
   2095  * line options.
   2096  */
   2097 static void
   2098 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
   2099 {
   2100 	struct loadedfile *lf;
   2101 	char *fullname;		/* full pathname of file */
   2102 	char *newName;
   2103 	char *slash, *incdir;
   2104 	int fd;
   2105 	int i;
   2106 
   2107 	fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
   2108 
   2109 	if (fullname == NULL && !isSystem) {
   2110 		/*
   2111 		 * Include files contained in double-quotes are first searched
   2112 		 * relative to the including file's location. We don't want to
   2113 		 * cd there, of course, so we just tack on the old file's
   2114 		 * leading path components and call Dir_FindFile to see if
   2115 		 * we can locate the file.
   2116 		 */
   2117 
   2118 		incdir = bmake_strdup(CurFile()->name.str);
   2119 		slash = strrchr(incdir, '/');
   2120 		if (slash != NULL) {
   2121 			*slash = '\0';
   2122 			/*
   2123 			 * Now do lexical processing of leading "../" on the
   2124 			 * filename.
   2125 			 */
   2126 			for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
   2127 				slash = strrchr(incdir + 1, '/');
   2128 				if (slash == NULL || strcmp(slash, "/..") == 0)
   2129 					break;
   2130 				*slash = '\0';
   2131 			}
   2132 			newName = str_concat3(incdir, "/", file + i);
   2133 			fullname = Dir_FindFile(newName, parseIncPath);
   2134 			if (fullname == NULL)
   2135 				fullname = Dir_FindFile(newName,
   2136 				    &dirSearchPath);
   2137 			free(newName);
   2138 		}
   2139 		free(incdir);
   2140 
   2141 		if (fullname == NULL) {
   2142 			/*
   2143 			 * Makefile wasn't found in same directory as included
   2144 			 * makefile.
   2145 			 *
   2146 			 * Search for it first on the -I search path, then on
   2147 			 * the .PATH search path, if not found in a -I
   2148 			 * directory. If we have a suffix-specific path, we
   2149 			 * should use that.
   2150 			 */
   2151 			const char *suff;
   2152 			SearchPath *suffPath = NULL;
   2153 
   2154 			if ((suff = strrchr(file, '.')) != NULL) {
   2155 				suffPath = Suff_GetPath(suff);
   2156 				if (suffPath != NULL)
   2157 					fullname = Dir_FindFile(file, suffPath);
   2158 			}
   2159 			if (fullname == NULL) {
   2160 				fullname = Dir_FindFile(file, parseIncPath);
   2161 				if (fullname == NULL)
   2162 					fullname = Dir_FindFile(file,
   2163 					    &dirSearchPath);
   2164 			}
   2165 		}
   2166 	}
   2167 
   2168 	/* Looking for a system file or file still not found */
   2169 	if (fullname == NULL) {
   2170 		/*
   2171 		 * Look for it on the system path
   2172 		 */
   2173 		SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
   2174 		    ? defSysIncPath : sysIncPath;
   2175 		fullname = Dir_FindFile(file, path);
   2176 	}
   2177 
   2178 	if (fullname == NULL) {
   2179 		if (!silent)
   2180 			Parse_Error(PARSE_FATAL, "Could not find %s", file);
   2181 		return;
   2182 	}
   2183 
   2184 	/* Actually open the file... */
   2185 	fd = open(fullname, O_RDONLY);
   2186 	if (fd == -1) {
   2187 		if (!silent)
   2188 			Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
   2189 		free(fullname);
   2190 		return;
   2191 	}
   2192 
   2193 	/* load it */
   2194 	lf = loadfile(fullname, fd);
   2195 
   2196 	/* Start reading from this file next */
   2197 	Parse_PushInput(fullname, 0, -1, loadedfile_readMore, lf);
   2198 	CurFile()->lf = lf;
   2199 	if (depinc)
   2200 		doing_depend = depinc;	/* only turn it on */
   2201 	free(fullname);
   2202 }
   2203 
   2204 /*
   2205  * Parse a directive like '.include' or '.-include'.
   2206  *
   2207  * .include "user-makefile.mk"
   2208  * .include <system-makefile.mk>
   2209  */
   2210 static void
   2211 ParseInclude(char *directive)
   2212 {
   2213 	char endc;		/* '>' or '"' */
   2214 	char *p;
   2215 	bool silent = directive[0] != 'i';
   2216 	FStr file;
   2217 
   2218 	p = directive + (silent ? 8 : 7);
   2219 	pp_skip_hspace(&p);
   2220 
   2221 	if (*p != '"' && *p != '<') {
   2222 		Parse_Error(PARSE_FATAL,
   2223 		    ".include filename must be delimited by '\"' or '<'");
   2224 		return;
   2225 	}
   2226 
   2227 	if (*p++ == '<')
   2228 		endc = '>';
   2229 	else
   2230 		endc = '"';
   2231 	file = FStr_InitRefer(p);
   2232 
   2233 	/* Skip to matching delimiter */
   2234 	while (*p != '\0' && *p != endc)
   2235 		p++;
   2236 
   2237 	if (*p != endc) {
   2238 		Parse_Error(PARSE_FATAL,
   2239 		    "Unclosed .include filename. '%c' expected", endc);
   2240 		return;
   2241 	}
   2242 
   2243 	*p = '\0';
   2244 
   2245 	if (strchr(file.str, '$') != NULL) {
   2246 		char *xfile;
   2247 		Var_Subst(file.str, SCOPE_CMDLINE, VARE_WANTRES, &xfile);
   2248 		/* TODO: handle errors */
   2249 		file = FStr_InitOwn(xfile);
   2250 	}
   2251 
   2252 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
   2253 	FStr_Done(&file);
   2254 }
   2255 
   2256 /*
   2257  * Split filename into dirname + basename, then assign these to the
   2258  * given variables.
   2259  */
   2260 static void
   2261 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
   2262 {
   2263 	const char *slash, *basename;
   2264 	FStr dirname;
   2265 
   2266 	slash = strrchr(filename, '/');
   2267 	if (slash == NULL) {
   2268 		dirname = FStr_InitRefer(curdir);
   2269 		basename = filename;
   2270 	} else {
   2271 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
   2272 		basename = slash + 1;
   2273 	}
   2274 
   2275 	Global_Set(dirvar, dirname.str);
   2276 	Global_Set(filevar, basename);
   2277 
   2278 	DEBUG5(PARSE, "%s: ${%s} = `%s' ${%s} = `%s'\n",
   2279 	    __func__, dirvar, dirname.str, filevar, basename);
   2280 	FStr_Done(&dirname);
   2281 }
   2282 
   2283 /*
   2284  * Return the immediately including file.
   2285  *
   2286  * This is made complicated since the .for loop is implemented as a special
   2287  * kind of .include; see For_Run.
   2288  */
   2289 static const char *
   2290 GetActuallyIncludingFile(void)
   2291 {
   2292 	size_t i;
   2293 	const IFile *incs = GetInclude(0);
   2294 
   2295 	for (i = includes.len; i >= 2; i--)
   2296 		if (!incs[i - 1].fromForLoop)
   2297 			return incs[i - 2].name.str;
   2298 	return NULL;
   2299 }
   2300 
   2301 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
   2302 static void
   2303 ParseSetParseFile(const char *filename)
   2304 {
   2305 	const char *including;
   2306 
   2307 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
   2308 
   2309 	including = GetActuallyIncludingFile();
   2310 	if (including != NULL) {
   2311 		SetFilenameVars(including,
   2312 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
   2313 	} else {
   2314 		Global_Delete(".INCLUDEDFROMDIR");
   2315 		Global_Delete(".INCLUDEDFROMFILE");
   2316 	}
   2317 }
   2318 
   2319 static bool
   2320 StrContainsWord(const char *str, const char *word)
   2321 {
   2322 	size_t strLen = strlen(str);
   2323 	size_t wordLen = strlen(word);
   2324 	const char *p, *end;
   2325 
   2326 	if (strLen < wordLen)
   2327 		return false;	/* str is too short to contain word */
   2328 
   2329 	end = str + strLen - wordLen;
   2330 	for (p = str; p != NULL; p = strchr(p, ' ')) {
   2331 		if (*p == ' ')
   2332 			p++;
   2333 		if (p > end)
   2334 			return false;	/* cannot contain word */
   2335 
   2336 		if (memcmp(p, word, wordLen) == 0 &&
   2337 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
   2338 			return true;
   2339 	}
   2340 	return false;
   2341 }
   2342 
   2343 /*
   2344  * XXX: Searching through a set of words with this linear search is
   2345  * inefficient for variables that contain thousands of words.
   2346  *
   2347  * XXX: The paths in this list don't seem to be normalized in any way.
   2348  */
   2349 static bool
   2350 VarContainsWord(const char *varname, const char *word)
   2351 {
   2352 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
   2353 	bool found = val.str != NULL && StrContainsWord(val.str, word);
   2354 	FStr_Done(&val);
   2355 	return found;
   2356 }
   2357 
   2358 /*
   2359  * Track the makefiles we read - so makefiles can set dependencies on them.
   2360  * Avoid adding anything more than once.
   2361  *
   2362  * Time complexity: O(n) per call, in total O(n^2), where n is the number
   2363  * of makefiles that have been loaded.
   2364  */
   2365 static void
   2366 ParseTrackInput(const char *name)
   2367 {
   2368 	if (!VarContainsWord(MAKE_MAKEFILES, name))
   2369 		Global_Append(MAKE_MAKEFILES, name);
   2370 }
   2371 
   2372 
   2373 /*
   2374  * Start parsing from the given source.
   2375  *
   2376  * The given file is added to the includes stack.
   2377  */
   2378 void
   2379 Parse_PushInput(const char *name, int lineno, int fd,
   2380 	       ReadMoreProc readMore, void *readMoreArg)
   2381 {
   2382 	IFile *curFile;
   2383 	char *buf;
   2384 	size_t len;
   2385 	bool fromForLoop = name == NULL;
   2386 
   2387 	if (fromForLoop)
   2388 		name = CurFile()->name.str;
   2389 	else
   2390 		ParseTrackInput(name);
   2391 
   2392 	DEBUG3(PARSE, "Parse_PushInput: %s %s, line %d\n",
   2393 	    readMore == loadedfile_readMore ? "file" : ".for loop in",
   2394 	    name, lineno);
   2395 
   2396 	if (fd == -1 && readMore == NULL)
   2397 		/* sanity */
   2398 		return;
   2399 
   2400 	curFile = Vector_Push(&includes);
   2401 	curFile->name = FStr_InitOwn(bmake_strdup(name));
   2402 	curFile->fromForLoop = fromForLoop;
   2403 	curFile->lineno = lineno;
   2404 	curFile->first_lineno = lineno;
   2405 	curFile->readMore = readMore;
   2406 	curFile->readMoreArg = readMoreArg;
   2407 	curFile->lf = NULL;
   2408 	curFile->depending = doing_depend;	/* restore this on EOF */
   2409 
   2410 	assert(readMore != NULL);
   2411 
   2412 	/* Get first block of input data */
   2413 	buf = curFile->readMore(curFile->readMoreArg, &len);
   2414 	if (buf == NULL) {
   2415 		/* Was all a waste of time ... */
   2416 		FStr_Done(&curFile->name);
   2417 		free(curFile);
   2418 		return;
   2419 	}
   2420 	curFile->buf_freeIt = buf;
   2421 	curFile->buf_ptr = buf;
   2422 	curFile->buf_end = buf + len;
   2423 
   2424 	curFile->cond_depth = Cond_save_depth();
   2425 	ParseSetParseFile(name);
   2426 }
   2427 
   2428 /* Check if the directive is an include directive. */
   2429 static bool
   2430 IsInclude(const char *dir, bool sysv)
   2431 {
   2432 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
   2433 		dir++;
   2434 
   2435 	if (strncmp(dir, "include", 7) != 0)
   2436 		return false;
   2437 
   2438 	/* Space is not mandatory for BSD .include */
   2439 	return !sysv || ch_isspace(dir[7]);
   2440 }
   2441 
   2442 
   2443 #ifdef SYSVINCLUDE
   2444 /* Check if the line is a SYSV include directive. */
   2445 static bool
   2446 IsSysVInclude(const char *line)
   2447 {
   2448 	const char *p;
   2449 
   2450 	if (!IsInclude(line, true))
   2451 		return false;
   2452 
   2453 	/* Avoid interpreting a dependency line as an include */
   2454 	for (p = line; (p = strchr(p, ':')) != NULL;) {
   2455 
   2456 		/* end of line -> it's a dependency */
   2457 		if (*++p == '\0')
   2458 			return false;
   2459 
   2460 		/* '::' operator or ': ' -> it's a dependency */
   2461 		if (*p == ':' || ch_isspace(*p))
   2462 			return false;
   2463 	}
   2464 	return true;
   2465 }
   2466 
   2467 /* Push to another file.  The line points to the word "include". */
   2468 static void
   2469 ParseTraditionalInclude(char *line)
   2470 {
   2471 	char *cp;		/* current position in file spec */
   2472 	bool done = false;
   2473 	bool silent = line[0] != 'i';
   2474 	char *file = line + (silent ? 8 : 7);
   2475 	char *all_files;
   2476 
   2477 	DEBUG2(PARSE, "%s: %s\n", __func__, file);
   2478 
   2479 	pp_skip_whitespace(&file);
   2480 
   2481 	/*
   2482 	 * Substitute for any variables in the file name before trying to
   2483 	 * find the thing.
   2484 	 */
   2485 	(void)Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES, &all_files);
   2486 	/* TODO: handle errors */
   2487 
   2488 	if (*file == '\0') {
   2489 		Parse_Error(PARSE_FATAL, "Filename missing from \"include\"");
   2490 		goto out;
   2491 	}
   2492 
   2493 	for (file = all_files; !done; file = cp + 1) {
   2494 		/* Skip to end of line or next whitespace */
   2495 		for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
   2496 			continue;
   2497 
   2498 		if (*cp != '\0')
   2499 			*cp = '\0';
   2500 		else
   2501 			done = true;
   2502 
   2503 		IncludeFile(file, false, false, silent);
   2504 	}
   2505 out:
   2506 	free(all_files);
   2507 }
   2508 #endif
   2509 
   2510 #ifdef GMAKEEXPORT
   2511 /* Parse "export <variable>=<value>", and actually export it. */
   2512 static void
   2513 ParseGmakeExport(char *line)
   2514 {
   2515 	char *variable = line + 6;
   2516 	char *value;
   2517 
   2518 	DEBUG2(PARSE, "%s: %s\n", __func__, variable);
   2519 
   2520 	pp_skip_whitespace(&variable);
   2521 
   2522 	for (value = variable; *value != '\0' && *value != '='; value++)
   2523 		continue;
   2524 
   2525 	if (*value != '=') {
   2526 		Parse_Error(PARSE_FATAL,
   2527 		    "Variable/Value missing from \"export\"");
   2528 		return;
   2529 	}
   2530 	*value++ = '\0';	/* terminate variable */
   2531 
   2532 	/*
   2533 	 * Expand the value before putting it in the environment.
   2534 	 */
   2535 	(void)Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES, &value);
   2536 	/* TODO: handle errors */
   2537 
   2538 	setenv(variable, value, 1);
   2539 	free(value);
   2540 }
   2541 #endif
   2542 
   2543 /*
   2544  * Called when EOF is reached in the current file. If we were reading an
   2545  * include file or a .for loop, the includes stack is popped and things set
   2546  * up to go back to reading the previous file at the previous location.
   2547  *
   2548  * Results:
   2549  *	true to continue parsing, i.e. it had only reached the end of an
   2550  *	included file, false if the main file has been parsed completely.
   2551  */
   2552 static bool
   2553 ParseEOF(void)
   2554 {
   2555 	char *ptr;
   2556 	size_t len;
   2557 	IFile *curFile = CurFile();
   2558 
   2559 	assert(curFile->readMore != NULL);
   2560 
   2561 	doing_depend = curFile->depending;	/* restore this */
   2562 	/* get next input buffer, if any */
   2563 	ptr = curFile->readMore(curFile->readMoreArg, &len);
   2564 	curFile->buf_ptr = ptr;
   2565 	curFile->buf_freeIt = ptr;
   2566 	curFile->buf_end = ptr == NULL ? NULL : ptr + len;
   2567 	curFile->lineno = curFile->first_lineno;
   2568 	if (ptr != NULL)
   2569 		return true;	/* Iterate again */
   2570 
   2571 	/* Ensure the makefile (or loop) didn't have mismatched conditionals */
   2572 	Cond_restore_depth(curFile->cond_depth);
   2573 
   2574 	if (curFile->lf != NULL) {
   2575 		loadedfile_destroy(curFile->lf);
   2576 		curFile->lf = NULL;
   2577 	}
   2578 
   2579 	FStr_Done(&curFile->name);
   2580 	free(curFile->buf_freeIt);
   2581 	Vector_Pop(&includes);
   2582 
   2583 	if (includes.len == 0) {
   2584 		/* We've run out of input */
   2585 		Global_Delete(".PARSEDIR");
   2586 		Global_Delete(".PARSEFILE");
   2587 		Global_Delete(".INCLUDEDFROMDIR");
   2588 		Global_Delete(".INCLUDEDFROMFILE");
   2589 		return false;
   2590 	}
   2591 
   2592 	curFile = CurFile();
   2593 	DEBUG2(PARSE, "ParseEOF: returning to file %s, line %d\n",
   2594 	    curFile->name.str, curFile->lineno);
   2595 
   2596 	ParseSetParseFile(curFile->name.str);
   2597 	return true;
   2598 }
   2599 
   2600 typedef enum ParseRawLineResult {
   2601 	PRLR_LINE,
   2602 	PRLR_EOF,
   2603 	PRLR_ERROR
   2604 } ParseRawLineResult;
   2605 
   2606 /*
   2607  * Parse until the end of a line, taking into account lines that end with
   2608  * backslash-newline.  The resulting line goes from out_line to out_line_end;
   2609  * the line is not null-terminated.
   2610  */
   2611 static ParseRawLineResult
   2612 ParseRawLine(IFile *curFile, char **out_line, char **out_line_end,
   2613 	     char **out_firstBackslash, char **out_firstComment)
   2614 {
   2615 	char *line = curFile->buf_ptr;
   2616 	char *buf_end = curFile->buf_end;
   2617 	char *p = line;
   2618 	char *line_end = line;
   2619 	char *firstBackslash = NULL;
   2620 	char *firstComment = NULL;
   2621 	ParseRawLineResult res = PRLR_LINE;
   2622 
   2623 	curFile->lineno++;
   2624 
   2625 	for (;;) {
   2626 		char ch;
   2627 
   2628 		if (p == buf_end) {
   2629 			res = PRLR_EOF;
   2630 			break;
   2631 		}
   2632 
   2633 		ch = *p;
   2634 		if (ch == '\0' ||
   2635 		    (ch == '\\' && p + 1 < buf_end && p[1] == '\0')) {
   2636 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
   2637 			return PRLR_ERROR;
   2638 		}
   2639 
   2640 		/* Treat next character after '\' as literal. */
   2641 		if (ch == '\\') {
   2642 			if (firstBackslash == NULL)
   2643 				firstBackslash = p;
   2644 			if (p[1] == '\n') {
   2645 				curFile->lineno++;
   2646 				if (p + 2 == buf_end) {
   2647 					line_end = p;
   2648 					*line_end = '\n';
   2649 					p += 2;
   2650 					continue;
   2651 				}
   2652 			}
   2653 			p += 2;
   2654 			line_end = p;
   2655 			assert(p <= buf_end);
   2656 			continue;
   2657 		}
   2658 
   2659 		/*
   2660 		 * Remember the first '#' for comment stripping, unless
   2661 		 * the previous char was '[', as in the modifier ':[#]'.
   2662 		 */
   2663 		if (ch == '#' && firstComment == NULL &&
   2664 		    !(p > line && p[-1] == '['))
   2665 			firstComment = line_end;
   2666 
   2667 		p++;
   2668 		if (ch == '\n')
   2669 			break;
   2670 
   2671 		/* We are not interested in trailing whitespace. */
   2672 		if (!ch_isspace(ch))
   2673 			line_end = p;
   2674 	}
   2675 
   2676 	*out_line = line;
   2677 	curFile->buf_ptr = p;
   2678 	*out_line_end = line_end;
   2679 	*out_firstBackslash = firstBackslash;
   2680 	*out_firstComment = firstComment;
   2681 	return res;
   2682 }
   2683 
   2684 /*
   2685  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
   2686  * with a single space.
   2687  */
   2688 static void
   2689 UnescapeBackslash(char *line, char *start)
   2690 {
   2691 	char *src = start;
   2692 	char *dst = start;
   2693 	char *spaceStart = line;
   2694 
   2695 	for (;;) {
   2696 		char ch = *src++;
   2697 		if (ch != '\\') {
   2698 			if (ch == '\0')
   2699 				break;
   2700 			*dst++ = ch;
   2701 			continue;
   2702 		}
   2703 
   2704 		ch = *src++;
   2705 		if (ch == '\0') {
   2706 			/* Delete '\\' at end of buffer */
   2707 			dst--;
   2708 			break;
   2709 		}
   2710 
   2711 		/* Delete '\\' from before '#' on non-command lines */
   2712 		if (ch == '#' && line[0] != '\t') {
   2713 			*dst++ = ch;
   2714 			continue;
   2715 		}
   2716 
   2717 		if (ch != '\n') {
   2718 			/* Leave '\\' in buffer for later */
   2719 			*dst++ = '\\';
   2720 			/*
   2721 			 * Make sure we don't delete an escaped ' ' from the
   2722 			 * line end.
   2723 			 */
   2724 			spaceStart = dst + 1;
   2725 			*dst++ = ch;
   2726 			continue;
   2727 		}
   2728 
   2729 		/*
   2730 		 * Escaped '\n' -- replace following whitespace with a single
   2731 		 * ' '.
   2732 		 */
   2733 		pp_skip_hspace(&src);
   2734 		*dst++ = ' ';
   2735 	}
   2736 
   2737 	/* Delete any trailing spaces - eg from empty continuations */
   2738 	while (dst > spaceStart && ch_isspace(dst[-1]))
   2739 		dst--;
   2740 	*dst = '\0';
   2741 }
   2742 
   2743 typedef enum GetLineMode {
   2744 	/*
   2745 	 * Return the next line that is neither empty nor a comment.
   2746 	 * Backslash line continuations are folded into a single space.
   2747 	 * A trailing comment, if any, is discarded.
   2748 	 */
   2749 	GLM_NONEMPTY,
   2750 
   2751 	/*
   2752 	 * Return the next line, even if it is empty or a comment.
   2753 	 * Preserve backslash-newline to keep the line numbers correct.
   2754 	 *
   2755 	 * Used in .for loops to collect the body of the loop while waiting
   2756 	 * for the corresponding .endfor.
   2757 	 */
   2758 	GLM_FOR_BODY,
   2759 
   2760 	/*
   2761 	 * Return the next line that starts with a dot.
   2762 	 * Backslash line continuations are folded into a single space.
   2763 	 * A trailing comment, if any, is discarded.
   2764 	 *
   2765 	 * Used in .if directives to skip over irrelevant branches while
   2766 	 * waiting for the corresponding .endif.
   2767 	 */
   2768 	GLM_DOT
   2769 } GetLineMode;
   2770 
   2771 /* Return the next "interesting" logical line from the current file. */
   2772 static char *
   2773 ParseGetLine(GetLineMode mode)
   2774 {
   2775 	IFile *curFile = CurFile();
   2776 	char *line;
   2777 	char *line_end;
   2778 	char *firstBackslash;
   2779 	char *firstComment;
   2780 
   2781 	for (;;) {
   2782 		ParseRawLineResult res = ParseRawLine(curFile,
   2783 		    &line, &line_end, &firstBackslash, &firstComment);
   2784 		if (res == PRLR_ERROR)
   2785 			return NULL;
   2786 
   2787 		if (line_end == line || firstComment == line) {
   2788 			if (res == PRLR_EOF)
   2789 				return NULL;
   2790 			if (mode != GLM_FOR_BODY)
   2791 				continue;
   2792 		}
   2793 
   2794 		/* We now have a line of data */
   2795 		assert(ch_isspace(*line_end));
   2796 		*line_end = '\0';
   2797 
   2798 		if (mode == GLM_FOR_BODY)
   2799 			return line;	/* Don't join the physical lines. */
   2800 
   2801 		if (mode == GLM_DOT && line[0] != '.')
   2802 			continue;
   2803 		break;
   2804 	}
   2805 
   2806 	/* Brutally ignore anything after a non-escaped '#' in non-commands. */
   2807 	if (firstComment != NULL && line[0] != '\t')
   2808 		*firstComment = '\0';
   2809 
   2810 	/* If we didn't see a '\\' then the in-situ data is fine. */
   2811 	if (firstBackslash == NULL)
   2812 		return line;
   2813 
   2814 	/* Remove escapes from '\n' and '#' */
   2815 	UnescapeBackslash(line, firstBackslash);
   2816 
   2817 	return line;
   2818 }
   2819 
   2820 static bool
   2821 ParseSkippedBranches(void)
   2822 {
   2823 	char *line;
   2824 
   2825 	while ((line = ParseGetLine(GLM_DOT)) != NULL) {
   2826 		if (Cond_EvalLine(line) == COND_PARSE)
   2827 			break;
   2828 		/*
   2829 		 * TODO: Check for typos in .elif directives
   2830 		 * such as .elsif or .elseif.
   2831 		 *
   2832 		 * This check will probably duplicate some of
   2833 		 * the code in ParseLine.  Most of the code
   2834 		 * there cannot apply, only ParseVarassign and
   2835 		 * ParseDependencyLine can, and to prevent code
   2836 		 * duplication, these would need to be called
   2837 		 * with a flag called onlyCheckSyntax.
   2838 		 *
   2839 		 * See directive-elif.mk for details.
   2840 		 */
   2841 	}
   2842 
   2843 	return line != NULL;
   2844 }
   2845 
   2846 static bool
   2847 ParseForLoop(const char *line)
   2848 {
   2849 	int rval;
   2850 	int firstLineno;
   2851 
   2852 	rval = For_Eval(line);
   2853 	if (rval == 0)
   2854 		return false;	/* Not a .for line */
   2855 	if (rval < 0)
   2856 		return true;	/* Syntax error - error printed, ignore line */
   2857 
   2858 	firstLineno = CurFile()->lineno;
   2859 
   2860 	/* Accumulate loop lines until matching .endfor */
   2861 	do {
   2862 		line = ParseGetLine(GLM_FOR_BODY);
   2863 		if (line == NULL) {
   2864 			Parse_Error(PARSE_FATAL,
   2865 			    "Unexpected end of file in .for loop");
   2866 			break;
   2867 		}
   2868 	} while (For_Accum(line));
   2869 
   2870 	For_Run(firstLineno);	/* Stash each iteration as a new 'input file' */
   2871 
   2872 	return true;		/* Read next line from for-loop buffer */
   2873 }
   2874 
   2875 /*
   2876  * Read an entire line from the input file.
   2877  *
   2878  * Empty lines, .if and .for are completely handled by this function,
   2879  * leaving only variable assignments, other directives, dependency lines
   2880  * and shell commands to the caller.
   2881  *
   2882  * Results:
   2883  *	A line without its newline and without any trailing whitespace,
   2884  *	or NULL.
   2885  */
   2886 static char *
   2887 ParseReadLine(void)
   2888 {
   2889 	char *line;
   2890 
   2891 	for (;;) {
   2892 		line = ParseGetLine(GLM_NONEMPTY);
   2893 		if (line == NULL)
   2894 			return NULL;
   2895 
   2896 		if (line[0] != '.')
   2897 			return line;
   2898 
   2899 		/*
   2900 		 * The line might be a conditional. Ask the conditional module
   2901 		 * about it and act accordingly
   2902 		 */
   2903 		switch (Cond_EvalLine(line)) {
   2904 		case COND_SKIP:
   2905 			if (!ParseSkippedBranches())
   2906 				return NULL;
   2907 			continue;
   2908 		case COND_PARSE:
   2909 			continue;
   2910 		case COND_INVALID:	/* Not a conditional line */
   2911 			if (ParseForLoop(line))
   2912 				continue;
   2913 			break;
   2914 		}
   2915 		return line;
   2916 	}
   2917 }
   2918 
   2919 static void
   2920 FinishDependencyGroup(void)
   2921 {
   2922 	GNodeListNode *ln;
   2923 
   2924 	if (targets == NULL)
   2925 		return;
   2926 
   2927 	for (ln = targets->first; ln != NULL; ln = ln->next) {
   2928 		GNode *gn = ln->datum;
   2929 
   2930 		Suff_EndTransform(gn);
   2931 
   2932 		/*
   2933 		 * Mark the target as already having commands if it does, to
   2934 		 * keep from having shell commands on multiple dependency
   2935 		 * lines.
   2936 		 */
   2937 		if (!Lst_IsEmpty(&gn->commands))
   2938 			gn->type |= OP_HAS_COMMANDS;
   2939 	}
   2940 
   2941 	Lst_Free(targets);
   2942 	targets = NULL;
   2943 }
   2944 
   2945 /* Add the command to each target from the current dependency spec. */
   2946 static void
   2947 ParseLine_ShellCommand(const char *p)
   2948 {
   2949 	cpp_skip_whitespace(&p);
   2950 	if (*p == '\0')
   2951 		return;		/* skip empty commands */
   2952 
   2953 	if (targets == NULL) {
   2954 		Parse_Error(PARSE_FATAL,
   2955 		    "Unassociated shell command \"%s\"", p);
   2956 		return;
   2957 	}
   2958 
   2959 	{
   2960 		char *cmd = bmake_strdup(p);
   2961 		GNodeListNode *ln;
   2962 
   2963 		for (ln = targets->first; ln != NULL; ln = ln->next) {
   2964 			GNode *gn = ln->datum;
   2965 			ParseAddCmd(gn, cmd);
   2966 		}
   2967 #ifdef CLEANUP
   2968 		Lst_Append(&targCmds, cmd);
   2969 #endif
   2970 	}
   2971 }
   2972 
   2973 /*
   2974  * See if the line starts with one of the known directives, and if so, handle
   2975  * the directive.
   2976  */
   2977 static bool
   2978 ParseDirective(char *line)
   2979 {
   2980 	char *cp = line + 1;
   2981 	const char *arg;
   2982 	Substring dir;
   2983 
   2984 	pp_skip_whitespace(&cp);
   2985 	if (IsInclude(cp, false)) {
   2986 		ParseInclude(cp);
   2987 		return true;
   2988 	}
   2989 
   2990 	dir.start = cp;
   2991 	while (ch_isalpha(*cp) || *cp == '-')
   2992 		cp++;
   2993 	dir.end = cp;
   2994 
   2995 	if (*cp != '\0' && !ch_isspace(*cp))
   2996 		return false;
   2997 
   2998 	pp_skip_whitespace(&cp);
   2999 	arg = cp;
   3000 
   3001 	if (Substring_Equals(dir, "undef")) {
   3002 		Var_Undef(arg);
   3003 		return true;
   3004 	} else if (Substring_Equals(dir, "export")) {
   3005 		Var_Export(VEM_PLAIN, arg);
   3006 		return true;
   3007 	} else if (Substring_Equals(dir, "export-env")) {
   3008 		Var_Export(VEM_ENV, arg);
   3009 		return true;
   3010 	} else if (Substring_Equals(dir, "export-literal")) {
   3011 		Var_Export(VEM_LITERAL, arg);
   3012 		return true;
   3013 	} else if (Substring_Equals(dir, "unexport")) {
   3014 		Var_UnExport(false, arg);
   3015 		return true;
   3016 	} else if (Substring_Equals(dir, "unexport-env")) {
   3017 		Var_UnExport(true, arg);
   3018 		return true;
   3019 	} else if (Substring_Equals(dir, "info")) {
   3020 		ParseMessage(PARSE_INFO, "info", arg);
   3021 		return true;
   3022 	} else if (Substring_Equals(dir, "warning")) {
   3023 		ParseMessage(PARSE_WARNING, "warning", arg);
   3024 		return true;
   3025 	} else if (Substring_Equals(dir, "error")) {
   3026 		ParseMessage(PARSE_FATAL, "error", arg);
   3027 		return true;
   3028 	}
   3029 	return false;
   3030 }
   3031 
   3032 static bool
   3033 ParseVarassign(const char *line)
   3034 {
   3035 	VarAssign var;
   3036 
   3037 	if (!Parse_IsVar(line, &var))
   3038 		return false;
   3039 
   3040 	FinishDependencyGroup();
   3041 	Parse_Var(&var, SCOPE_GLOBAL);
   3042 	return true;
   3043 }
   3044 
   3045 static char *
   3046 FindSemicolon(char *p)
   3047 {
   3048 	int level = 0;
   3049 
   3050 	for (; *p != '\0'; p++) {
   3051 		if (*p == '\\' && p[1] != '\0') {
   3052 			p++;
   3053 			continue;
   3054 		}
   3055 
   3056 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
   3057 			level++;
   3058 		else if (level > 0 && (*p == ')' || *p == '}'))
   3059 			level--;
   3060 		else if (level == 0 && *p == ';')
   3061 			break;
   3062 	}
   3063 	return p;
   3064 }
   3065 
   3066 /*
   3067  * dependency	-> target... op [source...] [';' command]
   3068  * op		-> ':' | '::' | '!'
   3069  */
   3070 static void
   3071 ParseDependencyLine(char *line)
   3072 {
   3073 	VarEvalMode emode;
   3074 	char *expanded_line;
   3075 	const char *shellcmd = NULL;
   3076 
   3077 	/*
   3078 	 * For some reason - probably to make the parser impossible -
   3079 	 * a ';' can be used to separate commands from dependencies.
   3080 	 * Attempt to avoid ';' inside substitution patterns.
   3081 	 */
   3082 	{
   3083 		char *semicolon = FindSemicolon(line);
   3084 		if (*semicolon != '\0') {
   3085 			/* Terminate the dependency list at the ';' */
   3086 			*semicolon = '\0';
   3087 			shellcmd = semicolon + 1;
   3088 		}
   3089 	}
   3090 
   3091 	/*
   3092 	 * We now know it's a dependency line so it needs to have all
   3093 	 * variables expanded before being parsed.
   3094 	 *
   3095 	 * XXX: Ideally the dependency line would first be split into
   3096 	 * its left-hand side, dependency operator and right-hand side,
   3097 	 * and then each side would be expanded on its own.  This would
   3098 	 * allow for the left-hand side to allow only defined variables
   3099 	 * and to allow variables on the right-hand side to be undefined
   3100 	 * as well.
   3101 	 *
   3102 	 * Parsing the line first would also prevent that targets
   3103 	 * generated from variable expressions are interpreted as the
   3104 	 * dependency operator, such as in "target${:U\:} middle: source",
   3105 	 * in which the middle is interpreted as a source, not a target.
   3106 	 */
   3107 
   3108 	/* In lint mode, allow undefined variables to appear in
   3109 	 * dependency lines.
   3110 	 *
   3111 	 * Ideally, only the right-hand side would allow undefined
   3112 	 * variables since it is common to have optional dependencies.
   3113 	 * Having undefined variables on the left-hand side is more
   3114 	 * unusual though.  Since both sides are expanded in a single
   3115 	 * pass, there is not much choice what to do here.
   3116 	 *
   3117 	 * In normal mode, it does not matter whether undefined
   3118 	 * variables are allowed or not since as of 2020-09-14,
   3119 	 * Var_Parse does not print any parse errors in such a case.
   3120 	 * It simply returns the special empty string var_Error,
   3121 	 * which cannot be detected in the result of Var_Subst. */
   3122 	emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
   3123 	(void)Var_Subst(line, SCOPE_CMDLINE, emode, &expanded_line);
   3124 	/* TODO: handle errors */
   3125 
   3126 	/* Need a fresh list for the target nodes */
   3127 	if (targets != NULL)
   3128 		Lst_Free(targets);
   3129 	targets = Lst_New();
   3130 
   3131 	ParseDependency(expanded_line);
   3132 	free(expanded_line);
   3133 
   3134 	if (shellcmd != NULL)
   3135 		ParseLine_ShellCommand(shellcmd);
   3136 }
   3137 
   3138 static void
   3139 ParseLine(char *line)
   3140 {
   3141 	/*
   3142 	 * Lines that begin with '.' can be pretty much anything:
   3143 	 *	- directives like '.include' or '.if',
   3144 	 *	- suffix rules like '.c.o:',
   3145 	 *	- dependencies for filenames that start with '.',
   3146 	 *	- variable assignments like '.tmp=value'.
   3147 	 */
   3148 	if (line[0] == '.' && ParseDirective(line))
   3149 		return;
   3150 
   3151 	if (line[0] == '\t') {
   3152 		ParseLine_ShellCommand(line + 1);
   3153 		return;
   3154 	}
   3155 
   3156 #ifdef SYSVINCLUDE
   3157 	if (IsSysVInclude(line)) {
   3158 		/*
   3159 		 * It's an S3/S5-style "include".
   3160 		 */
   3161 		ParseTraditionalInclude(line);
   3162 		return;
   3163 	}
   3164 #endif
   3165 
   3166 #ifdef GMAKEEXPORT
   3167 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
   3168 	    strchr(line, ':') == NULL) {
   3169 		/*
   3170 		 * It's a Gmake "export".
   3171 		 */
   3172 		ParseGmakeExport(line);
   3173 		return;
   3174 	}
   3175 #endif
   3176 
   3177 	if (ParseVarassign(line))
   3178 		return;
   3179 
   3180 	FinishDependencyGroup();
   3181 
   3182 	ParseDependencyLine(line);
   3183 }
   3184 
   3185 /*
   3186  * Parse a top-level makefile, incorporating its content into the global
   3187  * dependency graph.
   3188  *
   3189  * Input:
   3190  *	name		The name of the file being read
   3191  *	fd		The open file to parse; will be closed at the end
   3192  */
   3193 void
   3194 Parse_File(const char *name, int fd)
   3195 {
   3196 	char *line;		/* the line we're working on */
   3197 	struct loadedfile *lf;
   3198 
   3199 	lf = loadfile(name, fd);
   3200 
   3201 	assert(targets == NULL);
   3202 
   3203 	if (name == NULL)
   3204 		name = "(stdin)";
   3205 
   3206 	Parse_PushInput(name, 0, -1, loadedfile_readMore, lf);
   3207 	CurFile()->lf = lf;
   3208 
   3209 	do {
   3210 		while ((line = ParseReadLine()) != NULL) {
   3211 			DEBUG2(PARSE, "ParseReadLine (%d): '%s'\n",
   3212 			    CurFile()->lineno, line);
   3213 			ParseLine(line);
   3214 		}
   3215 		/* Reached EOF, but it may be just EOF of an include file. */
   3216 	} while (ParseEOF());
   3217 
   3218 	FinishDependencyGroup();
   3219 
   3220 	if (parseErrors != 0) {
   3221 		(void)fflush(stdout);
   3222 		(void)fprintf(stderr,
   3223 		    "%s: Fatal errors encountered -- cannot continue",
   3224 		    progname);
   3225 		PrintOnError(NULL, NULL);
   3226 		exit(1);
   3227 	}
   3228 }
   3229 
   3230 /* Initialize the parsing module. */
   3231 void
   3232 Parse_Init(void)
   3233 {
   3234 	mainNode = NULL;
   3235 	parseIncPath = SearchPath_New();
   3236 	sysIncPath = SearchPath_New();
   3237 	defSysIncPath = SearchPath_New();
   3238 	Vector_Init(&includes, sizeof(IFile));
   3239 }
   3240 
   3241 /* Clean up the parsing module. */
   3242 void
   3243 Parse_End(void)
   3244 {
   3245 #ifdef CLEANUP
   3246 	Lst_DoneCall(&targCmds, free);
   3247 	assert(targets == NULL);
   3248 	SearchPath_Free(defSysIncPath);
   3249 	SearchPath_Free(sysIncPath);
   3250 	SearchPath_Free(parseIncPath);
   3251 	assert(includes.len == 0);
   3252 	Vector_Done(&includes);
   3253 #endif
   3254 }
   3255 
   3256 
   3257 /*
   3258  * Return a list containing the single main target to create.
   3259  * If no such target exists, we Punt with an obnoxious error message.
   3260  */
   3261 void
   3262 Parse_MainName(GNodeList *mainList)
   3263 {
   3264 	if (mainNode == NULL)
   3265 		Punt("no target to make.");
   3266 
   3267 	Lst_Append(mainList, mainNode);
   3268 	if (mainNode->type & OP_DOUBLEDEP)
   3269 		Lst_AppendAll(mainList, &mainNode->cohorts);
   3270 
   3271 	Global_Append(".TARGETS", mainNode->name);
   3272 }
   3273 
   3274 int
   3275 Parse_NumErrors(void)
   3276 {
   3277 	return parseErrors;
   3278 }
   3279