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