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