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