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