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