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