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