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