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