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