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