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