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