xref: /netbsd-src/usr.bin/make/parse.c (revision 5b239d0be1d6682ecf6030411841b40cc91e8b34)
1 /*	$NetBSD: parse.c,v 1.119 2006/10/27 21:00:19 dsl 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.119 2006/10/27 21:00:19 dsl 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.119 2006/10/27 21:00:19 dsl 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		curSrcs;
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, cgn);
515     if (specType == Not)
516 	    (void)Lst_AtEnd(cgn->parents, pgn);
517     pgn->unmade += 1;
518     if (DEBUG(PARSE)) {
519 	fprintf(debug_file, "# 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, 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 	fprintf(debug_file, "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, s);
639     (void)Lst_AtEnd(s->preds, p);
640     (void)Lst_AtEnd(s->recpreds, p);
641     if (DEBUG(PARSE)) {
642 	fprintf(debug_file, "# 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->curSrcs, FALSE); /* don't come back */
685 	return 0;
686     }
687 
688     /* Expand the variables that depend on the current target just in case */
689     Var_Set(TARGET, tn->name, tn, 0);
690 
691     /* Get the filename part of the target name, excluding all suffixes */
692     if ((pref = strrchr(tn->name, '/')))
693 	pref++;
694     else
695 	pref = tn->name;
696     if ((cp2 = strchr(pref, '.')) > pref) {
697 	cp = estrdup(pref);
698 	cp[cp2 - pref] = '\0';
699 	Var_Set(PREFIX, cp, tn, 0);
700 	free(cp);
701     } else
702 	Var_Set(PREFIX, pref, tn, 0);
703 
704     /* Now we can expant the name itself */
705     cp = Var_Subst(NULL, ss->src, tn, FALSE);
706     /* XXX, better not need to have $ in a filesname! */
707     if (strchr(cp, '$')) {
708 	Parse_Error(PARSE_WARNING, "Cannot resolve '%s' here", ss->src);
709 	ParseDoSrc(ss->op, ss->src, ss->curSrcs, FALSE); /* don't come back */
710 	return 1;			/* stop list traversal */
711     }
712 
713     /*
714      * We don't want to make every target dependent on sources for
715      * other targets.  This is the bit of ParseDoSrc which is relevant.
716      * The main difference is we don't link the resolved src to all targets.
717      */
718     gn = Targ_FindNode(cp, TARG_CREATE);
719     if (ss->op) {
720 	gn->type |= ss->op;
721     } else {
722 	ParseLinkSrc(tn, gn);
723     }
724     if (DEBUG(PARSE))
725 	fprintf(debug_file, "ParseDoSpecialSrc: set %p(%s):%d (was %d)\n",
726 		gn, gn->name, waiting, gn->order);
727     gn->order = waiting;
728     (void)Lst_AtEnd(ss->curSrcs, gn);
729     if (waiting)
730 	Lst_ForEach(ss->curSrcs, ParseAddDep, gn);
731     return 0;
732 }
733 
734 
735 /*-
736  *---------------------------------------------------------------------
737  * ParseDoSrc  --
738  *	Given the name of a source, figure out if it is an attribute
739  *	and apply it to the targets if it is. Else decide if there is
740  *	some attribute which should be applied *to* the source because
741  *	of some special target and apply it if so. Otherwise, make the
742  *	source be a child of the targets in the list 'targets'
743  *
744  * Input:
745  *	tOp		operator (if any) from special targets
746  *	src		name of the source to handle
747  *	curSrcs		List of all sources to wait for
748  *	resolve		boolean - should we try and resolve .TARGET refs.
749  *
750  * Results:
751  *	None
752  *
753  * Side Effects:
754  *	Operator bits may be added to the list of targets or to the source.
755  *	The targets may have a new source added to their lists of children.
756  *---------------------------------------------------------------------
757  */
758 static void
759 ParseDoSrc(int tOp, char *src, Lst curSrcs, Boolean resolve)
760 {
761     GNode	*gn = NULL;
762 
763     if (*src == '.' && isupper ((unsigned char)src[1])) {
764 	int keywd = ParseFindKeyword(src);
765 	if (keywd != -1) {
766 	    int op = parseKeywords[keywd].op;
767 	    if (op != 0) {
768 		Lst_ForEach(targets, ParseDoOp, &op);
769 		return;
770 	    }
771 	    if (parseKeywords[keywd].spec == Wait) {
772 		waiting++;
773 		return;
774 	    }
775 	}
776     }
777 
778     switch (specType) {
779     case Main:
780 	/*
781 	 * If we have noted the existence of a .MAIN, it means we need
782 	 * to add the sources of said target to the list of things
783 	 * to create. The string 'src' is likely to be free, so we
784 	 * must make a new copy of it. Note that this will only be
785 	 * invoked if the user didn't specify a target on the command
786 	 * line. This is to allow #ifmake's to succeed, or something...
787 	 */
788 	(void)Lst_AtEnd(create, estrdup(src));
789 	/*
790 	 * Add the name to the .TARGETS variable as well, so the user can
791 	 * employ that, if desired.
792 	 */
793 	Var_Append(".TARGETS", src, VAR_GLOBAL);
794 	return;
795 
796     case Order:
797 	/*
798 	 * Create proper predecessor/successor links between the previous
799 	 * source and the current one.
800 	 */
801 	gn = Targ_FindNode(src, TARG_CREATE);
802 	if (predecessor != NILGNODE) {
803 	    (void)Lst_AtEnd(predecessor->successors, gn);
804 	    (void)Lst_AtEnd(gn->preds, predecessor);
805 	    if (DEBUG(PARSE)) {
806 		fprintf(debug_file, "# ParseDoSrc: added Order dependency %s - %s\n",
807 			predecessor->name, gn->name);
808 		Targ_PrintNode(predecessor, 0);
809 		Targ_PrintNode(gn, 0);
810 	    }
811 	}
812 	/*
813 	 * The current source now becomes the predecessor for the next one.
814 	 */
815 	predecessor = gn;
816 	break;
817 
818     default:
819 	/*
820 	 * If the source is not an attribute, we need to find/create
821 	 * a node for it. After that we can apply any operator to it
822 	 * from a special target or link it to its parents, as
823 	 * appropriate.
824 	 *
825 	 * In the case of a source that was the object of a :: operator,
826 	 * the attribute is applied to all of its instances (as kept in
827 	 * the 'cohorts' list of the node) or all the cohorts are linked
828 	 * to all the targets.
829 	 */
830 	if (resolve && strchr(src, '$')) {
831 	    /*
832 	     * If the 'src' needs expanding, and we have a .WAIT in the
833 	     * list of sources, then we expand 'src' with respect to each
834 	     * of the targets and add the modified nodes separately to
835 	     * their own target.
836 	     * This only makes a difference if the 'src' has a dynamic
837 	     * dependency against .TARGET (etc), and even then it is probably
838 	     * not a very useful optimisation.
839 	     */
840 	    SpecialSrc ss;
841 
842 	    ss.op = tOp;
843 	    ss.src = src;
844 	    ss.curSrcs = curSrcs;
845 
846 	    /*
847 	     * If src cannot be fully resolved, we'll be called again
848 	     * with resolve==FALSE.
849 	     */
850 	    Lst_ForEach(targets, ParseDoSpecialSrc, &ss);
851 	    return;
852 	}
853 
854 	/* Find/create the 'src' node and attach to all targets */
855 	gn = Targ_FindNode(src, TARG_CREATE);
856 	if (tOp) {
857 	    gn->type |= tOp;
858 	} else {
859 	    Lst_ForEach(targets, ParseLinkSrc, gn);
860 	}
861 	break;
862     }
863 
864     if (DEBUG(PARSE))
865 	fprintf(debug_file, "ParseDoSrc: set %p(%s):%d (was %d)\n",
866 		gn, gn->name, waiting, gn->order);
867     gn->order = waiting;
868 
869     /* Keep a list of the 'src' on this dependence line for .WAIT below */
870     (void)Lst_AtEnd(curSrcs, gn);
871 
872     /*
873      * If we have passed a .WAIT, then make this 'src' depend on all the
874      * earlier 'src' of the current dependency line that preceed the last
875      * .WAIT directive.
876      */
877     if (waiting)
878 	Lst_ForEach(curSrcs, ParseAddDep, gn);
879 }
880 
881 /*-
882  *-----------------------------------------------------------------------
883  * ParseFindMain --
884  *	Find a real target in the list and set it to be the main one.
885  *	Called by ParseDoDependency when a main target hasn't been found
886  *	yet.
887  *
888  * Input:
889  *	gnp		Node to examine
890  *
891  * Results:
892  *	0 if main not found yet, 1 if it is.
893  *
894  * Side Effects:
895  *	mainNode is changed and Targ_SetMain is called.
896  *
897  *-----------------------------------------------------------------------
898  */
899 static int
900 ParseFindMain(ClientData gnp, ClientData dummy)
901 {
902     GNode   	  *gn = (GNode *)gnp;
903     if ((gn->type & OP_NOTARGET) == 0) {
904 	mainNode = gn;
905 	Targ_SetMain(gn);
906 	return (dummy ? 1 : 1);
907     } else {
908 	return (dummy ? 0 : 0);
909     }
910 }
911 
912 /*-
913  *-----------------------------------------------------------------------
914  * ParseAddDir --
915  *	Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
916  *
917  * Results:
918  *	=== 0
919  *
920  * Side Effects:
921  *	See Dir_AddDir.
922  *
923  *-----------------------------------------------------------------------
924  */
925 static int
926 ParseAddDir(ClientData path, ClientData name)
927 {
928     (void)Dir_AddDir((Lst) path, (char *)name);
929     return(0);
930 }
931 
932 /*-
933  *-----------------------------------------------------------------------
934  * ParseClearPath --
935  *	Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
936  *
937  * Results:
938  *	=== 0
939  *
940  * Side Effects:
941  *	See Dir_ClearPath
942  *
943  *-----------------------------------------------------------------------
944  */
945 static int
946 ParseClearPath(ClientData path, ClientData dummy)
947 {
948     Dir_ClearPath((Lst) path);
949     return(dummy ? 0 : 0);
950 }
951 
952 /*-
953  *---------------------------------------------------------------------
954  * ParseDoDependency  --
955  *	Parse the dependency line in line.
956  *
957  * Input:
958  *	line		the line to parse
959  *
960  * Results:
961  *	None
962  *
963  * Side Effects:
964  *	The nodes of the sources are linked as children to the nodes of the
965  *	targets. Some nodes may be created.
966  *
967  *	We parse a dependency line by first extracting words from the line and
968  * finding nodes in the list of all targets with that name. This is done
969  * until a character is encountered which is an operator character. Currently
970  * these are only ! and :. At this point the operator is parsed and the
971  * pointer into the line advanced until the first source is encountered.
972  * 	The parsed operator is applied to each node in the 'targets' list,
973  * which is where the nodes found for the targets are kept, by means of
974  * the ParseDoOp function.
975  *	The sources are read in much the same way as the targets were except
976  * that now they are expanded using the wildcarding scheme of the C-Shell
977  * and all instances of the resulting words in the list of all targets
978  * are found. Each of the resulting nodes is then linked to each of the
979  * targets as one of its children.
980  *	Certain targets are handled specially. These are the ones detailed
981  * by the specType variable.
982  *	The storing of transformation rules is also taken care of here.
983  * A target is recognized as a transformation rule by calling
984  * Suff_IsTransform. If it is a transformation rule, its node is gotten
985  * from the suffix module via Suff_AddTransform rather than the standard
986  * Targ_FindNode in the target module.
987  *---------------------------------------------------------------------
988  */
989 static void
990 ParseDoDependency(char *line)
991 {
992     char  	   *cp;		/* our current position */
993     GNode 	   *gn = NULL;	/* a general purpose temporary node */
994     int             op;		/* the operator on the line */
995     char            savec;	/* a place to save a character */
996     Lst    	    paths;   	/* List of search paths to alter when parsing
997 				 * a list of .PATH targets */
998     int	    	    tOp;    	/* operator from special target */
999     Lst	    	    sources;	/* list of archive source names after
1000 				 * expansion */
1001     Lst 	    curTargs;	/* list of target names to be found and added
1002 				 * to the targets list */
1003     Lst		    curSrcs;	/* list of sources in order */
1004     char	   *lstart = line;
1005     Boolean	    hasWait;	/* is .WAIT present in srcs */
1006 
1007     tOp = 0;
1008 
1009     specType = Not;
1010     waiting = 0;
1011     paths = (Lst)NULL;
1012 
1013     curTargs = Lst_Init(FALSE);
1014     curSrcs = Lst_Init(FALSE);
1015 
1016     do {
1017 	for (cp = line;
1018 	     *cp && (ParseIsEscaped(lstart, cp) ||
1019 	     (!isspace ((unsigned char)*cp) &&
1020 	     (*cp != '!') && (*cp != ':') && (*cp != LPAREN)));
1021 	     cp++)
1022 	{
1023 	    if (*cp == '$') {
1024 		/*
1025 		 * Must be a dynamic source (would have been expanded
1026 		 * otherwise), so call the Var module to parse the puppy
1027 		 * so we can safely advance beyond it...There should be
1028 		 * no errors in this, as they would have been discovered
1029 		 * in the initial Var_Subst and we wouldn't be here.
1030 		 */
1031 		int 	length;
1032 		void    *freeIt;
1033 		char	*result;
1034 
1035 		result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
1036 		if (freeIt)
1037 		    free(freeIt);
1038 		cp += length-1;
1039 	    }
1040 	    continue;
1041 	}
1042 	if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1043 	    /*
1044 	     * Archives must be handled specially to make sure the OP_ARCHV
1045 	     * flag is set in their 'type' field, for one thing, and because
1046 	     * things like "archive(file1.o file2.o file3.o)" are permissible.
1047 	     * Arch_ParseArchive will set 'line' to be the first non-blank
1048 	     * after the archive-spec. It creates/finds nodes for the members
1049 	     * and places them on the given list, returning SUCCESS if all
1050 	     * went well and FAILURE if there was an error in the
1051 	     * specification. On error, line should remain untouched.
1052 	     */
1053 	    if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1054 		Parse_Error(PARSE_FATAL,
1055 			     "Error in archive specification: \"%s\"", line);
1056 		goto out;
1057 	    } else {
1058 		continue;
1059 	    }
1060 	}
1061 	savec = *cp;
1062 
1063 	if (!*cp) {
1064 	    /*
1065 	     * Ending a dependency line without an operator is a Bozo
1066 	     * no-no.  As a heuristic, this is also often triggered by
1067 	     * undetected conflicts from cvs/rcs merges.
1068 	     */
1069 	    if ((strncmp(line, "<<<<<<", 6) == 0) ||
1070 		(strncmp(line, "======", 6) == 0) ||
1071 		(strncmp(line, ">>>>>>", 6) == 0))
1072 		Parse_Error(PARSE_FATAL,
1073 		    "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1074 	    else
1075 		Parse_Error(PARSE_FATAL, "Need an operator");
1076 	    goto out;
1077 	}
1078 	*cp = '\0';
1079 
1080 	/*
1081 	 * Have a word in line. See if it's a special target and set
1082 	 * specType to match it.
1083 	 */
1084 	if (*line == '.' && isupper ((unsigned char)line[1])) {
1085 	    /*
1086 	     * See if the target is a special target that must have it
1087 	     * or its sources handled specially.
1088 	     */
1089 	    int keywd = ParseFindKeyword(line);
1090 	    if (keywd != -1) {
1091 		if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1092 		    Parse_Error(PARSE_FATAL, "Mismatched special targets");
1093 		    goto out;
1094 		}
1095 
1096 		specType = parseKeywords[keywd].spec;
1097 		tOp = parseKeywords[keywd].op;
1098 
1099 		/*
1100 		 * Certain special targets have special semantics:
1101 		 *	.PATH		Have to set the dirSearchPath
1102 		 *			variable too
1103 		 *	.MAIN		Its sources are only used if
1104 		 *			nothing has been specified to
1105 		 *			create.
1106 		 *	.DEFAULT    	Need to create a node to hang
1107 		 *			commands on, but we don't want
1108 		 *			it in the graph, nor do we want
1109 		 *			it to be the Main Target, so we
1110 		 *			create it, set OP_NOTMAIN and
1111 		 *			add it to the list, setting
1112 		 *			DEFAULT to the new node for
1113 		 *			later use. We claim the node is
1114 		 *	    	    	A transformation rule to make
1115 		 *	    	    	life easier later, when we'll
1116 		 *	    	    	use Make_HandleUse to actually
1117 		 *	    	    	apply the .DEFAULT commands.
1118 		 *	.PHONY		The list of targets
1119 		 *	.NOPATH		Don't search for file in the path
1120 		 *	.BEGIN
1121 		 *	.END
1122 		 *	.INTERRUPT  	Are not to be considered the
1123 		 *			main target.
1124 		 *  	.NOTPARALLEL	Make only one target at a time.
1125 		 *  	.SINGLESHELL	Create a shell for each command.
1126 		 *  	.ORDER	    	Must set initial predecessor to NIL
1127 		 */
1128 		switch (specType) {
1129 		    case ExPath:
1130 			if (paths == NULL) {
1131 			    paths = Lst_Init(FALSE);
1132 			}
1133 			(void)Lst_AtEnd(paths, dirSearchPath);
1134 			break;
1135 		    case Main:
1136 			if (!Lst_IsEmpty(create)) {
1137 			    specType = Not;
1138 			}
1139 			break;
1140 		    case Begin:
1141 		    case End:
1142 		    case Interrupt:
1143 			gn = Targ_FindNode(line, TARG_CREATE);
1144 			gn->type |= OP_NOTMAIN|OP_SPECIAL;
1145 			(void)Lst_AtEnd(targets, gn);
1146 			break;
1147 		    case Default:
1148 			gn = Targ_NewGN(".DEFAULT");
1149 			gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1150 			(void)Lst_AtEnd(targets, gn);
1151 			DEFAULT = gn;
1152 			break;
1153 		    case NotParallel:
1154 			maxJobs = 1;
1155 			break;
1156 		    case SingleShell:
1157 			compatMake = TRUE;
1158 			break;
1159 		    case Order:
1160 			predecessor = NILGNODE;
1161 			break;
1162 		    default:
1163 			break;
1164 		}
1165 	    } else if (strncmp(line, ".PATH", 5) == 0) {
1166 		/*
1167 		 * .PATH<suffix> has to be handled specially.
1168 		 * Call on the suffix module to give us a path to
1169 		 * modify.
1170 		 */
1171 		Lst 	path;
1172 
1173 		specType = ExPath;
1174 		path = Suff_GetPath(&line[5]);
1175 		if (path == NILLST) {
1176 		    Parse_Error(PARSE_FATAL,
1177 				 "Suffix '%s' not defined (yet)",
1178 				 &line[5]);
1179 		    goto out;
1180 		} else {
1181 		    if (paths == (Lst)NULL) {
1182 			paths = Lst_Init(FALSE);
1183 		    }
1184 		    (void)Lst_AtEnd(paths, path);
1185 		}
1186 	    }
1187 	}
1188 
1189 	/*
1190 	 * Have word in line. Get or create its node and stick it at
1191 	 * the end of the targets list
1192 	 */
1193 	if ((specType == Not) && (*line != '\0')) {
1194 	    if (Dir_HasWildcards(line)) {
1195 		/*
1196 		 * Targets are to be sought only in the current directory,
1197 		 * so create an empty path for the thing. Note we need to
1198 		 * use Dir_Destroy in the destruction of the path as the
1199 		 * Dir module could have added a directory to the path...
1200 		 */
1201 		Lst	    emptyPath = Lst_Init(FALSE);
1202 
1203 		Dir_Expand(line, emptyPath, curTargs);
1204 
1205 		Lst_Destroy(emptyPath, Dir_Destroy);
1206 	    } else {
1207 		/*
1208 		 * No wildcards, but we want to avoid code duplication,
1209 		 * so create a list with the word on it.
1210 		 */
1211 		(void)Lst_AtEnd(curTargs, line);
1212 	    }
1213 
1214 	    while(!Lst_IsEmpty(curTargs)) {
1215 		char	*targName = (char *)Lst_DeQueue(curTargs);
1216 
1217 		if (!Suff_IsTransform (targName)) {
1218 		    gn = Targ_FindNode(targName, TARG_CREATE);
1219 		} else {
1220 		    gn = Suff_AddTransform(targName);
1221 		}
1222 
1223 		(void)Lst_AtEnd(targets, gn);
1224 	    }
1225 	} else if (specType == ExPath && *line != '.' && *line != '\0') {
1226 	    Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1227 	}
1228 
1229 	*cp = savec;
1230 	/*
1231 	 * If it is a special type and not .PATH, it's the only target we
1232 	 * allow on this line...
1233 	 */
1234 	if (specType != Not && specType != ExPath) {
1235 	    Boolean warning = FALSE;
1236 
1237 	    while (*cp && (ParseIsEscaped(lstart, cp) ||
1238 		((*cp != '!') && (*cp != ':')))) {
1239 		if (ParseIsEscaped(lstart, cp) ||
1240 		    (*cp != ' ' && *cp != '\t')) {
1241 		    warning = TRUE;
1242 		}
1243 		cp++;
1244 	    }
1245 	    if (warning) {
1246 		Parse_Error(PARSE_WARNING, "Extra target ignored");
1247 	    }
1248 	} else {
1249 	    while (*cp && isspace ((unsigned char)*cp)) {
1250 		cp++;
1251 	    }
1252 	}
1253 	line = cp;
1254     } while (*line && (ParseIsEscaped(lstart, line) ||
1255 	((*line != '!') && (*line != ':'))));
1256 
1257     /*
1258      * Don't need the list of target names anymore...
1259      */
1260     Lst_Destroy(curTargs, NOFREE);
1261     curTargs = NULL;
1262 
1263     if (!Lst_IsEmpty(targets)) {
1264 	switch(specType) {
1265 	    default:
1266 		Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1267 		break;
1268 	    case Default:
1269 	    case Begin:
1270 	    case End:
1271 	    case Interrupt:
1272 		/*
1273 		 * These four create nodes on which to hang commands, so
1274 		 * targets shouldn't be empty...
1275 		 */
1276 	    case Not:
1277 		/*
1278 		 * Nothing special here -- targets can be empty if it wants.
1279 		 */
1280 		break;
1281 	}
1282     }
1283 
1284     /*
1285      * Have now parsed all the target names. Must parse the operator next. The
1286      * result is left in  op .
1287      */
1288     if (*cp == '!') {
1289 	op = OP_FORCE;
1290     } else if (*cp == ':') {
1291 	if (cp[1] == ':') {
1292 	    op = OP_DOUBLEDEP;
1293 	    cp++;
1294 	} else {
1295 	    op = OP_DEPENDS;
1296 	}
1297     } else {
1298 	Parse_Error(PARSE_FATAL, "Missing dependency operator");
1299 	goto out;
1300     }
1301 
1302     cp++;			/* Advance beyond operator */
1303 
1304     Lst_ForEach(targets, ParseDoOp, &op);
1305 
1306     /*
1307      * Get to the first source
1308      */
1309     while (*cp && isspace ((unsigned char)*cp)) {
1310 	cp++;
1311     }
1312     line = cp;
1313 
1314     /*
1315      * Several special targets take different actions if present with no
1316      * sources:
1317      *	a .SUFFIXES line with no sources clears out all old suffixes
1318      *	a .PRECIOUS line makes all targets precious
1319      *	a .IGNORE line ignores errors for all targets
1320      *	a .SILENT line creates silence when making all targets
1321      *	a .PATH removes all directories from the search path(s).
1322      */
1323     if (!*line) {
1324 	switch (specType) {
1325 	    case Suffixes:
1326 		Suff_ClearSuffixes();
1327 		break;
1328 	    case Precious:
1329 		allPrecious = TRUE;
1330 		break;
1331 	    case Ignore:
1332 		ignoreErrors = TRUE;
1333 		break;
1334 	    case Silent:
1335 		beSilent = TRUE;
1336 		break;
1337 	    case ExPath:
1338 		Lst_ForEach(paths, ParseClearPath, NULL);
1339 		Dir_SetPATH();
1340 		break;
1341 #ifdef POSIX
1342             case Posix:
1343                 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1344                 break;
1345 #endif
1346 	    default:
1347 		break;
1348 	}
1349     } else if (specType == MFlags) {
1350 	/*
1351 	 * Call on functions in main.c to deal with these arguments and
1352 	 * set the initial character to a null-character so the loop to
1353 	 * get sources won't get anything
1354 	 */
1355 	Main_ParseArgLine(line);
1356 	*line = '\0';
1357     } else if (specType == ExShell) {
1358 	if (Job_ParseShell(line) != SUCCESS) {
1359 	    Parse_Error(PARSE_FATAL, "improper shell specification");
1360 	    goto out;
1361 	}
1362 	*line = '\0';
1363     } else if ((specType == NotParallel) || (specType == SingleShell)) {
1364 	*line = '\0';
1365     }
1366 
1367     /*
1368      * NOW GO FOR THE SOURCES
1369      */
1370     if ((specType == Suffixes) || (specType == ExPath) ||
1371 	(specType == Includes) || (specType == Libs) ||
1372 	(specType == Null) || (specType == ExObjdir))
1373     {
1374 	while (*line) {
1375 	    /*
1376 	     * If the target was one that doesn't take files as its sources
1377 	     * but takes something like suffixes, we take each
1378 	     * space-separated word on the line as a something and deal
1379 	     * with it accordingly.
1380 	     *
1381 	     * If the target was .SUFFIXES, we take each source as a
1382 	     * suffix and add it to the list of suffixes maintained by the
1383 	     * Suff module.
1384 	     *
1385 	     * If the target was a .PATH, we add the source as a directory
1386 	     * to search on the search path.
1387 	     *
1388 	     * If it was .INCLUDES, the source is taken to be the suffix of
1389 	     * files which will be #included and whose search path should
1390 	     * be present in the .INCLUDES variable.
1391 	     *
1392 	     * If it was .LIBS, the source is taken to be the suffix of
1393 	     * files which are considered libraries and whose search path
1394 	     * should be present in the .LIBS variable.
1395 	     *
1396 	     * If it was .NULL, the source is the suffix to use when a file
1397 	     * has no valid suffix.
1398 	     *
1399 	     * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1400 	     * and will cause make to do a new chdir to that path.
1401 	     */
1402 	    while (*cp && !isspace ((unsigned char)*cp)) {
1403 		cp++;
1404 	    }
1405 	    savec = *cp;
1406 	    *cp = '\0';
1407 	    switch (specType) {
1408 		case Suffixes:
1409 		    Suff_AddSuffix(line, &mainNode);
1410 		    break;
1411 		case ExPath:
1412 		    Lst_ForEach(paths, ParseAddDir, line);
1413 		    break;
1414 		case Includes:
1415 		    Suff_AddInclude(line);
1416 		    break;
1417 		case Libs:
1418 		    Suff_AddLib(line);
1419 		    break;
1420 		case Null:
1421 		    Suff_SetNull(line);
1422 		    break;
1423 		case ExObjdir:
1424 		    Main_SetObjdir(line);
1425 		    break;
1426 		default:
1427 		    break;
1428 	    }
1429 	    *cp = savec;
1430 	    if (savec != '\0') {
1431 		cp++;
1432 	    }
1433 	    while (*cp && isspace ((unsigned char)*cp)) {
1434 		cp++;
1435 	    }
1436 	    line = cp;
1437 	}
1438 	if (paths) {
1439 	    Lst_Destroy(paths, NOFREE);
1440 	}
1441 	if (specType == ExPath)
1442 	    Dir_SetPATH();
1443     } else {
1444 	/*
1445 	 * We don't need ParseDoSpecialSrc unless .WAIT is present.
1446 	 */
1447 	hasWait = (strstr(line, ".WAIT") != NULL);
1448 
1449 	while (*line) {
1450 	    /*
1451 	     * The targets take real sources, so we must beware of archive
1452 	     * specifications (i.e. things with left parentheses in them)
1453 	     * and handle them accordingly.
1454 	     */
1455 	    for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1456 		if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1457 		    /*
1458 		     * Only stop for a left parenthesis if it isn't at the
1459 		     * start of a word (that'll be for variable changes
1460 		     * later) and isn't preceded by a dollar sign (a dynamic
1461 		     * source).
1462 		     */
1463 		    break;
1464 		}
1465 	    }
1466 
1467 	    if (*cp == LPAREN) {
1468 		sources = Lst_Init(FALSE);
1469 		if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1470 		    Parse_Error(PARSE_FATAL,
1471 				 "Error in source archive spec \"%s\"", line);
1472 		    goto out;
1473 		}
1474 
1475 		while (!Lst_IsEmpty (sources)) {
1476 		    gn = (GNode *)Lst_DeQueue(sources);
1477 		    ParseDoSrc(tOp, gn->name, curSrcs, hasWait);
1478 		}
1479 		Lst_Destroy(sources, NOFREE);
1480 		cp = line;
1481 	    } else {
1482 		if (*cp) {
1483 		    *cp = '\0';
1484 		    cp += 1;
1485 		}
1486 
1487 		ParseDoSrc(tOp, line, curSrcs, hasWait);
1488 	    }
1489 	    while (*cp && isspace ((unsigned char)*cp)) {
1490 		cp++;
1491 	    }
1492 	    line = cp;
1493 	}
1494     }
1495 
1496     if (mainNode == NILGNODE) {
1497 	/*
1498 	 * If we have yet to decide on a main target to make, in the
1499 	 * absence of any user input, we want the first target on
1500 	 * the first dependency line that is actually a real target
1501 	 * (i.e. isn't a .USE or .EXEC rule) to be made.
1502 	 */
1503 	Lst_ForEach(targets, ParseFindMain, NULL);
1504     }
1505 
1506 out:
1507     if (curTargs)
1508 	    Lst_Destroy(curTargs, NOFREE);
1509     /*
1510      * Finally, destroy the list of sources
1511      */
1512     Lst_Destroy(curSrcs, NOFREE);
1513 }
1514 
1515 /*-
1516  *---------------------------------------------------------------------
1517  * Parse_IsVar  --
1518  *	Return TRUE if the passed line is a variable assignment. A variable
1519  *	assignment consists of a single word followed by optional whitespace
1520  *	followed by either a += or an = operator.
1521  *	This function is used both by the Parse_File function and main when
1522  *	parsing the command-line arguments.
1523  *
1524  * Input:
1525  *	line		the line to check
1526  *
1527  * Results:
1528  *	TRUE if it is. FALSE if it ain't
1529  *
1530  * Side Effects:
1531  *	none
1532  *---------------------------------------------------------------------
1533  */
1534 Boolean
1535 Parse_IsVar(char *line)
1536 {
1537     Boolean wasSpace = FALSE;	/* set TRUE if found a space */
1538     Boolean haveName = FALSE;	/* Set TRUE if have a variable name */
1539     int level = 0;
1540 #define ISEQOPERATOR(c) \
1541 	(((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1542 
1543     /*
1544      * Skip to variable name
1545      */
1546     for (;(*line == ' ') || (*line == '\t'); line++)
1547 	continue;
1548 
1549     for (; *line != '=' || level != 0; line++)
1550 	switch (*line) {
1551 	case '\0':
1552 	    /*
1553 	     * end-of-line -- can't be a variable assignment.
1554 	     */
1555 	    return FALSE;
1556 
1557 	case ' ':
1558 	case '\t':
1559 	    /*
1560 	     * there can be as much white space as desired so long as there is
1561 	     * only one word before the operator
1562 	     */
1563 	    wasSpace = TRUE;
1564 	    break;
1565 
1566 	case LPAREN:
1567 	case '{':
1568 	    level++;
1569 	    break;
1570 
1571 	case '}':
1572 	case RPAREN:
1573 	    level--;
1574 	    break;
1575 
1576 	default:
1577 	    if (wasSpace && haveName) {
1578 		    if (ISEQOPERATOR(*line)) {
1579 			/*
1580 			 * We must have a finished word
1581 			 */
1582 			if (level != 0)
1583 			    return FALSE;
1584 
1585 			/*
1586 			 * When an = operator [+?!:] is found, the next
1587 			 * character must be an = or it ain't a valid
1588 			 * assignment.
1589 			 */
1590 			if (line[1] == '=')
1591 			    return haveName;
1592 #ifdef SUNSHCMD
1593 			/*
1594 			 * This is a shell command
1595 			 */
1596 			if (strncmp(line, ":sh", 3) == 0)
1597 			    return haveName;
1598 #endif
1599 		    }
1600 		    /*
1601 		     * This is the start of another word, so not assignment.
1602 		     */
1603 		    return FALSE;
1604 	    }
1605 	    else {
1606 		haveName = TRUE;
1607 		wasSpace = FALSE;
1608 	    }
1609 	    break;
1610 	}
1611 
1612     return haveName;
1613 }
1614 
1615 /*-
1616  *---------------------------------------------------------------------
1617  * Parse_DoVar  --
1618  *	Take the variable assignment in the passed line and do it in the
1619  *	global context.
1620  *
1621  *	Note: There is a lexical ambiguity with assignment modifier characters
1622  *	in variable names. This routine interprets the character before the =
1623  *	as a modifier. Therefore, an assignment like
1624  *	    C++=/usr/bin/CC
1625  *	is interpreted as "C+ +=" instead of "C++ =".
1626  *
1627  * Input:
1628  *	line		a line guaranteed to be a variable assignment.
1629  *			This reduces error checks
1630  *	ctxt		Context in which to do the assignment
1631  *
1632  * Results:
1633  *	none
1634  *
1635  * Side Effects:
1636  *	the variable structure of the given variable name is altered in the
1637  *	global context.
1638  *---------------------------------------------------------------------
1639  */
1640 void
1641 Parse_DoVar(char *line, GNode *ctxt)
1642 {
1643     char	   *cp;	/* pointer into line */
1644     enum {
1645 	VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1646     }	    	    type;   	/* Type of assignment */
1647     char            *opc;	/* ptr to operator character to
1648 				 * null-terminate the variable name */
1649     Boolean	   freeCp = FALSE; /* TRUE if cp needs to be freed,
1650 				    * i.e. if any variable expansion was
1651 				    * performed */
1652     /*
1653      * Avoid clobbered variable warnings by forcing the compiler
1654      * to ``unregister'' variables
1655      */
1656 #if __GNUC__
1657     (void) &cp;
1658     (void) &line;
1659 #endif
1660 
1661     /*
1662      * Skip to variable name
1663      */
1664     while ((*line == ' ') || (*line == '\t')) {
1665 	line++;
1666     }
1667 
1668     /*
1669      * Skip to operator character, nulling out whitespace as we go
1670      */
1671     for (cp = line + 1; *cp != '='; cp++) {
1672 	if (isspace ((unsigned char)*cp)) {
1673 	    *cp = '\0';
1674 	}
1675     }
1676     opc = cp-1;		/* operator is the previous character */
1677     *cp++ = '\0';	/* nuke the = */
1678 
1679     /*
1680      * Check operator type
1681      */
1682     switch (*opc) {
1683 	case '+':
1684 	    type = VAR_APPEND;
1685 	    *opc = '\0';
1686 	    break;
1687 
1688 	case '?':
1689 	    /*
1690 	     * If the variable already has a value, we don't do anything.
1691 	     */
1692 	    *opc = '\0';
1693 	    if (Var_Exists(line, ctxt)) {
1694 		return;
1695 	    } else {
1696 		type = VAR_NORMAL;
1697 	    }
1698 	    break;
1699 
1700 	case ':':
1701 	    type = VAR_SUBST;
1702 	    *opc = '\0';
1703 	    break;
1704 
1705 	case '!':
1706 	    type = VAR_SHELL;
1707 	    *opc = '\0';
1708 	    break;
1709 
1710 	default:
1711 #ifdef SUNSHCMD
1712 	    while (opc > line && *opc != ':')
1713 		opc--;
1714 
1715 	    if (strncmp(opc, ":sh", 3) == 0) {
1716 		type = VAR_SHELL;
1717 		*opc = '\0';
1718 		break;
1719 	    }
1720 #endif
1721 	    type = VAR_NORMAL;
1722 	    break;
1723     }
1724 
1725     while (isspace ((unsigned char)*cp)) {
1726 	cp++;
1727     }
1728 
1729     if (type == VAR_APPEND) {
1730 	Var_Append(line, cp, ctxt);
1731     } else if (type == VAR_SUBST) {
1732 	/*
1733 	 * Allow variables in the old value to be undefined, but leave their
1734 	 * invocation alone -- this is done by forcing oldVars to be false.
1735 	 * XXX: This can cause recursive variables, but that's not hard to do,
1736 	 * and this allows someone to do something like
1737 	 *
1738 	 *  CFLAGS = $(.INCLUDES)
1739 	 *  CFLAGS := -I.. $(CFLAGS)
1740 	 *
1741 	 * And not get an error.
1742 	 */
1743 	Boolean	  oldOldVars = oldVars;
1744 
1745 	oldVars = FALSE;
1746 
1747 	/*
1748 	 * make sure that we set the variable the first time to nothing
1749 	 * so that it gets substituted!
1750 	 */
1751 	if (!Var_Exists(line, ctxt))
1752 	    Var_Set(line, "", ctxt, 0);
1753 
1754 	cp = Var_Subst(NULL, cp, ctxt, FALSE);
1755 	oldVars = oldOldVars;
1756 	freeCp = TRUE;
1757 
1758 	Var_Set(line, cp, ctxt, 0);
1759     } else if (type == VAR_SHELL) {
1760 	char *res;
1761 	const char *error;
1762 
1763 	if (strchr(cp, '$') != NULL) {
1764 	    /*
1765 	     * There's a dollar sign in the command, so perform variable
1766 	     * expansion on the whole thing. The resulting string will need
1767 	     * freeing when we're done, so set freeCmd to TRUE.
1768 	     */
1769 	    cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1770 	    freeCp = TRUE;
1771 	}
1772 
1773 	res = Cmd_Exec(cp, &error);
1774 	Var_Set(line, res, ctxt, 0);
1775 	free(res);
1776 
1777 	if (error)
1778 	    Parse_Error(PARSE_WARNING, error, cp);
1779     } else {
1780 	/*
1781 	 * Normal assignment -- just do it.
1782 	 */
1783 	Var_Set(line, cp, ctxt, 0);
1784     }
1785     if (strcmp(line, MAKEOVERRIDES) == 0)
1786 	Main_ExportMAKEFLAGS(FALSE);	/* re-export MAKEFLAGS */
1787     else if (strcmp(line, ".CURDIR") == 0) {
1788 	/*
1789 	 * Somone is being (too?) clever...
1790 	 * Let's pretend they know what they are doing and
1791 	 * re-initialize the 'cur' Path.
1792 	 */
1793 	Dir_InitCur(cp);
1794 	Dir_SetPATH();
1795     }
1796     if (freeCp)
1797 	free(cp);
1798 }
1799 
1800 
1801 /*-
1802  * ParseAddCmd  --
1803  *	Lst_ForEach function to add a command line to all targets
1804  *
1805  * Input:
1806  *	gnp		the node to which the command is to be added
1807  *	cmd		the command to add
1808  *
1809  * Results:
1810  *	Always 0
1811  *
1812  * Side Effects:
1813  *	A new element is added to the commands list of the node.
1814  */
1815 static int
1816 ParseAddCmd(ClientData gnp, ClientData cmd)
1817 {
1818     GNode *gn = (GNode *)gnp;
1819     /* if target already supplied, ignore commands */
1820     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1821 	gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1822     if (!(gn->type & OP_HAS_COMMANDS)) {
1823 	(void)Lst_AtEnd(gn->commands, cmd);
1824 	ParseMark(gn);
1825     } else {
1826 #ifdef notyet
1827 	/* XXX: We cannot do this until we fix the tree */
1828 	(void)Lst_AtEnd(gn->commands, cmd);
1829 	Parse_Error(PARSE_WARNING,
1830 		     "overriding commands for target \"%s\"; "
1831 		     "previous commands defined at %s: %d ignored",
1832 		     gn->name, gn->fname, gn->lineno);
1833 #else
1834 	Parse_Error(PARSE_WARNING,
1835 		     "duplicate script for target \"%s\" ignored",
1836 		     gn->name);
1837 	ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1838 			    "using previous script for \"%s\" defined here",
1839 			    gn->name);
1840 #endif
1841     }
1842     return(0);
1843 }
1844 
1845 /*-
1846  *-----------------------------------------------------------------------
1847  * ParseHasCommands --
1848  *	Callback procedure for Parse_File when destroying the list of
1849  *	targets on the last dependency line. Marks a target as already
1850  *	having commands if it does, to keep from having shell commands
1851  *	on multiple dependency lines.
1852  *
1853  * Input:
1854  *	gnp		Node to examine
1855  *
1856  * Results:
1857  *	None
1858  *
1859  * Side Effects:
1860  *	OP_HAS_COMMANDS may be set for the target.
1861  *
1862  *-----------------------------------------------------------------------
1863  */
1864 static void
1865 ParseHasCommands(ClientData gnp)
1866 {
1867     GNode *gn = (GNode *)gnp;
1868     if (!Lst_IsEmpty(gn->commands)) {
1869 	gn->type |= OP_HAS_COMMANDS;
1870     }
1871 }
1872 
1873 /*-
1874  *-----------------------------------------------------------------------
1875  * Parse_AddIncludeDir --
1876  *	Add a directory to the path searched for included makefiles
1877  *	bracketed by double-quotes. Used by functions in main.c
1878  *
1879  * Input:
1880  *	dir		The name of the directory to add
1881  *
1882  * Results:
1883  *	None.
1884  *
1885  * Side Effects:
1886  *	The directory is appended to the list.
1887  *
1888  *-----------------------------------------------------------------------
1889  */
1890 void
1891 Parse_AddIncludeDir(char *dir)
1892 {
1893     (void)Dir_AddDir(parseIncPath, dir);
1894 }
1895 
1896 /*-
1897  *---------------------------------------------------------------------
1898  * ParseDoInclude  --
1899  *	Push to another file.
1900  *
1901  *	The input is the line minus the `.'. A file spec is a string
1902  *	enclosed in <> or "". The former is looked for only in sysIncPath.
1903  *	The latter in . and the directories specified by -I command line
1904  *	options
1905  *
1906  * Results:
1907  *	None
1908  *
1909  * Side Effects:
1910  *	A structure is added to the includes Lst and readProc, lineno,
1911  *	fname and curFILE are altered for the new file
1912  *---------------------------------------------------------------------
1913  */
1914 static void
1915 ParseDoInclude(char *line)
1916 {
1917     char          *fullname;	/* full pathname of file */
1918     IFile         *oldFile;	/* state associated with current file */
1919     char          endc;	    	/* the character which ends the file spec */
1920     char          *cp;		/* current position in file spec */
1921     Boolean 	  isSystem; 	/* TRUE if makefile is a system makefile */
1922     int		  silent = (*line != 'i') ? 1 : 0;
1923     char	  *file = &line[7 + silent];
1924 
1925     /*
1926      * Skip to delimiter character so we know where to look
1927      */
1928     while ((*file == ' ') || (*file == '\t')) {
1929 	file++;
1930     }
1931 
1932     if ((*file != '"') && (*file != '<')) {
1933 	Parse_Error(PARSE_FATAL,
1934 	    ".include filename must be delimited by '\"' or '<'");
1935 	return;
1936     }
1937 
1938     /*
1939      * Set the search path on which to find the include file based on the
1940      * characters which bracket its name. Angle-brackets imply it's
1941      * a system Makefile while double-quotes imply it's a user makefile
1942      */
1943     if (*file == '<') {
1944 	isSystem = TRUE;
1945 	endc = '>';
1946     } else {
1947 	isSystem = FALSE;
1948 	endc = '"';
1949     }
1950 
1951     /*
1952      * Skip to matching delimiter
1953      */
1954     for (cp = ++file; *cp && *cp != endc; cp++) {
1955 	continue;
1956     }
1957 
1958     if (*cp != endc) {
1959 	Parse_Error(PARSE_FATAL,
1960 		     "Unclosed %cinclude filename. '%c' expected",
1961 		     '.', endc);
1962 	return;
1963     }
1964     *cp = '\0';
1965 
1966     /*
1967      * Substitute for any variables in the file name before trying to
1968      * find the thing.
1969      */
1970     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1971 
1972     /*
1973      * Now we know the file's name and its search path, we attempt to
1974      * find the durn thing. A return of NULL indicates the file don't
1975      * exist.
1976      */
1977     fullname = NULL;
1978 
1979     if (!isSystem) {
1980 	/*
1981 	 * Include files contained in double-quotes are first searched for
1982 	 * relative to the including file's location. We don't want to
1983 	 * cd there, of course, so we just tack on the old file's
1984 	 * leading path components and call Dir_FindFile to see if
1985 	 * we can locate the beast.
1986 	 */
1987 	char	  *prefEnd, *Fname;
1988 
1989 	/* Make a temporary copy of this, to be safe. */
1990 	Fname = estrdup(curFile.fname);
1991 
1992 	prefEnd = strrchr(Fname, '/');
1993 	if (prefEnd != NULL) {
1994 	    char  	*newName;
1995 
1996 	    *prefEnd = '\0';
1997 	    if (file[0] == '/')
1998 		newName = estrdup(file);
1999 	    else
2000 		newName = str_concat(Fname, file, STR_ADDSLASH);
2001 	    fullname = Dir_FindFile(newName, parseIncPath);
2002 	    if (fullname == NULL) {
2003 		fullname = Dir_FindFile(newName, dirSearchPath);
2004 	    }
2005 	    free(newName);
2006 	    *prefEnd = '/';
2007 	} else {
2008 	    fullname = NULL;
2009 	}
2010 	free(Fname);
2011         if (fullname == NULL) {
2012 	    /*
2013     	     * Makefile wasn't found in same directory as included makefile.
2014 	     * Search for it first on the -I search path,
2015 	     * then on the .PATH search path, if not found in a -I directory.
2016 	     * XXX: Suffix specific?
2017 	     */
2018 	    fullname = Dir_FindFile(file, parseIncPath);
2019 	    if (fullname == NULL) {
2020 	        fullname = Dir_FindFile(file, dirSearchPath);
2021 	    }
2022         }
2023     }
2024 
2025     /* Looking for a system file or file still not found */
2026     if (fullname == NULL) {
2027 	/*
2028 	 * Look for it on the system path
2029 	 */
2030 	fullname = Dir_FindFile(file, Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2031     }
2032 
2033     if (fullname == NULL) {
2034 	*cp = endc;
2035 	if (!silent)
2036 	    Parse_Error(PARSE_FATAL, "Could not find %s", file);
2037 	return;
2038     }
2039 
2040     free(file);
2041 
2042     /*
2043      * Once we find the absolute path to the file, we get to save all the
2044      * state from the current file before we can start reading this
2045      * include file. The state is stored in an IFile structure which
2046      * is placed on a list with other IFile structures. The list makes
2047      * a very nice stack to track how we got here...
2048      */
2049     oldFile = emalloc(sizeof(IFile));
2050 
2051     memcpy(oldFile, &curFile, sizeof(IFile));
2052 
2053     (void)Lst_AtFront(includes, oldFile);
2054 
2055     /*
2056      * Once the previous state has been saved, we can get down to reading
2057      * the new file. We set up the name of the file to be the absolute
2058      * name of the include file so error messages refer to the right
2059      * place. Naturally enough, we start reading at line number 0.
2060      */
2061     curFile.fname = fullname;
2062     curFile.lineno = 0;
2063 
2064     ParseSetParseFile(curFile.fname);
2065 
2066     curFile.F = fopen(fullname, "r");
2067     curFile.P = NULL;
2068 
2069     if (curFile.F == (FILE * ) NULL) {
2070 	if (!silent)
2071 	    Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2072 	/*
2073 	 * Pop to previous file
2074 	 */
2075 	(void)ParseEOF(0);
2076     }
2077 }
2078 
2079 
2080 /*-
2081  *---------------------------------------------------------------------
2082  * ParseSetParseFile  --
2083  *	Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2084  *	basename of the given filename
2085  *
2086  * Results:
2087  *	None
2088  *
2089  * Side Effects:
2090  *	The .PARSEDIR and .PARSEFILE variables are overwritten by the
2091  *	dirname and basename of the given filename.
2092  *---------------------------------------------------------------------
2093  */
2094 static void
2095 ParseSetParseFile(char *filename)
2096 {
2097     char *slash;
2098 
2099     slash = strrchr(filename, '/');
2100     if (slash == 0) {
2101 	Var_Set(".PARSEDIR", ".", VAR_GLOBAL, 0);
2102 	Var_Set(".PARSEFILE", filename, VAR_GLOBAL, 0);
2103     } else {
2104 	*slash = '\0';
2105 	Var_Set(".PARSEDIR", filename, VAR_GLOBAL, 0);
2106 	Var_Set(".PARSEFILE", slash+1, VAR_GLOBAL, 0);
2107 	*slash = '/';
2108     }
2109 }
2110 
2111 
2112 /*-
2113  *---------------------------------------------------------------------
2114  * Parse_FromString  --
2115  *	Start Parsing from the given string
2116  *
2117  * Results:
2118  *	None
2119  *
2120  * Side Effects:
2121  *	A structure is added to the includes Lst and readProc, lineno,
2122  *	fname and curFILE are altered for the new file
2123  *---------------------------------------------------------------------
2124  */
2125 void
2126 Parse_FromString(char *str, int lineno)
2127 {
2128     IFile         *oldFile;	/* state associated with this file */
2129 
2130     if (DEBUG(FOR))
2131 	(void)fprintf(debug_file, "%s\n---- at line %d\n", str, lineno);
2132 
2133     oldFile = emalloc(sizeof(IFile));
2134     memcpy(oldFile, &curFile, sizeof(IFile));
2135 
2136     (void)Lst_AtFront(includes, oldFile);
2137 
2138     curFile.F = NULL;
2139     curFile.P = emalloc(sizeof(PTR));
2140     curFile.P->str = curFile.P->ptr = str;
2141     curFile.lineno = lineno;
2142     curFile.fname = estrdup(curFile.fname);
2143 }
2144 
2145 
2146 #ifdef SYSVINCLUDE
2147 /*-
2148  *---------------------------------------------------------------------
2149  * ParseTraditionalInclude  --
2150  *	Push to another file.
2151  *
2152  *	The input is the current line. The file name(s) are
2153  *	following the "include".
2154  *
2155  * Results:
2156  *	None
2157  *
2158  * Side Effects:
2159  *	A structure is added to the includes Lst and readProc, lineno,
2160  *	fname and curFILE are altered for the new file
2161  *---------------------------------------------------------------------
2162  */
2163 static void
2164 ParseTraditionalInclude(char *line)
2165 {
2166     char          *fullname;	/* full pathname of file */
2167     IFile         *oldFile;	/* state associated with current file */
2168     char          *cp;		/* current position in file spec */
2169     char	  *prefEnd;
2170     int		   done = 0;
2171     int		   silent = (line[0] != 'i') ? 1 : 0;
2172     char	  *file = &line[silent + 7];
2173     char	  *cfname;
2174     size_t	   clineno;
2175 
2176     cfname  = curFile.fname;
2177     clineno = curFile.lineno;
2178 
2179     if (DEBUG(PARSE)) {
2180 	    fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2181     }
2182 
2183     /*
2184      * Skip over whitespace
2185      */
2186     while (isspace((unsigned char)*file))
2187 	file++;
2188 
2189     /*
2190      * Substitute for any variables in the file name before trying to
2191      * find the thing.
2192      */
2193     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
2194 
2195     if (*file == '\0') {
2196 	Parse_Error(PARSE_FATAL,
2197 		     "Filename missing from \"include\"");
2198 	return;
2199     }
2200 
2201     for (; !done; file = cp + 1) {
2202 	/*
2203 	 * Skip to end of line or next whitespace
2204 	 */
2205 	for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2206 	    continue;
2207 
2208 	if (*cp)
2209 	    *cp = '\0';
2210 	else
2211 	    done = 1;
2212 
2213 	/*
2214 	 * Now we know the file's name, we attempt to find the durn thing.
2215 	 * A return of NULL indicates the file don't exist.
2216 	 *
2217 	 * Include files are first searched for relative to the including
2218 	 * file's location. We don't want to cd there, of course, so we
2219 	 * just tack on the old file's leading path components and call
2220 	 * Dir_FindFile to see if we can locate the beast.
2221 	 * XXX - this *does* search in the current directory, right?
2222 	 */
2223 
2224 	prefEnd = strrchr(cfname, '/');
2225 	if (prefEnd != NULL) {
2226 	    char  	*newName;
2227 
2228 	    *prefEnd = '\0';
2229 	    newName = str_concat(cfname, file, STR_ADDSLASH);
2230 	    fullname = Dir_FindFile(newName, parseIncPath);
2231 	    if (fullname == NULL) {
2232 		fullname = Dir_FindFile(newName, dirSearchPath);
2233 	    }
2234 	    free(newName);
2235 	    *prefEnd = '/';
2236 	} else {
2237 	    fullname = NULL;
2238 	}
2239 
2240 	if (fullname == NULL) {
2241 	    /*
2242 	     * System makefile or makefile wasn't found in same directory as
2243 	     * included makefile. Search for it first on the -I search path,
2244 	     * then on the .PATH search path, if not found in a
2245 	     * -I directory. XXX: Suffix specific?
2246 	     */
2247 	    fullname = Dir_FindFile(file, parseIncPath);
2248 	    if (fullname == NULL) {
2249 		fullname = Dir_FindFile(file, dirSearchPath);
2250 	    }
2251 	}
2252 
2253 	if (fullname == NULL) {
2254 	    /*
2255 	     * Still haven't found the makefile. Look for it on the system
2256 	     * path as a last resort.
2257 	     */
2258 	    fullname = Dir_FindFile(file,
2259 			Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2260 	}
2261 
2262 	if (fullname == NULL) {
2263 	    if (!silent)
2264 		ParseErrorInternal(cfname, clineno, PARSE_FATAL,
2265 		    "Could not find %s", file);
2266 	    free(file);
2267 	    continue;
2268 	}
2269 
2270 	free(file);
2271 
2272 	/*
2273 	 * Once we find the absolute path to the file, we get to save all
2274 	 * the state from the current file before we can start reading this
2275 	 * include file. The state is stored in an IFile structure which
2276 	 * is placed on a list with other IFile structures. The list makes
2277 	 * a very nice stack to track how we got here...
2278 	 */
2279 	oldFile = emalloc(sizeof(IFile));
2280 	memcpy(oldFile, &curFile, sizeof(IFile));
2281 
2282 	(void)Lst_AtFront(includes, oldFile);
2283 
2284 	/*
2285 	 * Once the previous state has been saved, we can get down to
2286 	 * reading the new file. We set up the name of the file to be the
2287 	 * absolute name of the include file so error messages refer to the
2288 	 * right place. Naturally enough, we start reading at line number 0.
2289 	 */
2290 	curFile.fname = fullname;
2291 	curFile.lineno = 0;
2292 
2293 	curFile.F = fopen(fullname, "r");
2294 	curFile.P = NULL;
2295 
2296 	if (curFile.F == NULL) {
2297 	    if (!silent)
2298 		ParseErrorInternal(cfname, clineno, PARSE_FATAL,
2299 		    "Cannot open %s", fullname);
2300 	    /*
2301 	     * Pop to previous file
2302 	     */
2303 	    (void)ParseEOF(1);
2304 	}
2305     }
2306 }
2307 #endif
2308 
2309 /*-
2310  *---------------------------------------------------------------------
2311  * ParseEOF  --
2312  *	Called when EOF is reached in the current file. If we were reading
2313  *	an include file, the includes stack is popped and things set up
2314  *	to go back to reading the previous file at the previous location.
2315  *
2316  * Results:
2317  *	CONTINUE if there's more to do. DONE if not.
2318  *
2319  * Side Effects:
2320  *	The old curFILE, is closed. The includes list is shortened.
2321  *	lineno, curFILE, and fname are changed if CONTINUE is returned.
2322  *---------------------------------------------------------------------
2323  */
2324 static int
2325 ParseEOF(int opened)
2326 {
2327     IFile     *ifile;	/* the state on the top of the includes stack */
2328 
2329     if (Lst_IsEmpty(includes)) {
2330 	Var_Delete(".PARSEDIR", VAR_GLOBAL);
2331 	Var_Delete(".PARSEFILE", VAR_GLOBAL);
2332 	return (DONE);
2333     }
2334 
2335     ifile = (IFile *)Lst_DeQueue(includes);
2336 
2337     /* XXX dispose of curFile info */
2338     free( curFile.fname);
2339     if (opened && curFile.F)
2340 	(void)fclose(curFile.F);
2341     if (curFile.P) {
2342 	free(curFile.P->str);
2343 	free(curFile.P);
2344     }
2345 
2346     memcpy(&curFile, ifile, sizeof(IFile));
2347 
2348     free(ifile);
2349 
2350     /* pop the PARSEDIR/PARSEFILE variables */
2351     ParseSetParseFile(curFile.fname);
2352     return (CONTINUE);
2353 }
2354 
2355 /*-
2356  *---------------------------------------------------------------------
2357  * ParseReadc  --
2358  *	Read a character from the current file
2359  *
2360  * Results:
2361  *	The character that was read
2362  *
2363  * Side Effects:
2364  *---------------------------------------------------------------------
2365  */
2366 static inline int
2367 ParseReadc(void)
2368 {
2369     if (curFile.F)
2370 	return fgetc(curFile.F);
2371 
2372     if (curFile.P && *curFile.P->ptr)
2373 	return *curFile.P->ptr++;
2374     return EOF;
2375 }
2376 
2377 
2378 /*-
2379  *---------------------------------------------------------------------
2380  * ParseUnreadc  --
2381  *	Put back a character to the current file
2382  *
2383  * Results:
2384  *	None.
2385  *
2386  * Side Effects:
2387  *---------------------------------------------------------------------
2388  */
2389 static void
2390 ParseUnreadc(int c)
2391 {
2392     if (curFile.F) {
2393 	ungetc(c, curFile.F);
2394 	return;
2395     }
2396     if (curFile.P) {
2397 	*--(curFile.P->ptr) = c;
2398 	return;
2399     }
2400 }
2401 
2402 
2403 /* ParseSkipLine():
2404  *	Grab the next line
2405  *
2406  * Input:
2407  *	skip		Skip lines that don't start with .
2408  *	keep_newline	Keep newline character as is.
2409  *
2410  */
2411 static char *
2412 ParseSkipLine(int skip, int keep_newline)
2413 {
2414     char *line;
2415     int c, lastc, lineLength = 0;
2416     Buffer buf;
2417 
2418     buf = Buf_Init(MAKE_BSIZE);
2419 
2420     do {
2421         Buf_Discard(buf, lineLength);
2422         lastc = '\0';
2423 
2424         while (((c = ParseReadc()) != '\n' || lastc == '\\')
2425                && c != EOF) {
2426             if (c == '\n') {
2427                 if (keep_newline)
2428                     Buf_AddByte(buf, (Byte)c);
2429                 else
2430                     Buf_ReplaceLastByte(buf, (Byte)' ');
2431                 curFile.lineno++;
2432 
2433                 while ((c = ParseReadc()) == ' ' || c == '\t');
2434 
2435                 if (c == EOF)
2436                     break;
2437             }
2438 
2439             Buf_AddByte(buf, (Byte)c);
2440             lastc = c;
2441         }
2442 
2443         if (c == EOF) {
2444             Parse_Error(PARSE_FATAL, "Unclosed conditional/for loop");
2445             Buf_Destroy(buf, TRUE);
2446             return(NULL);
2447         }
2448 
2449         curFile.lineno++;
2450         Buf_AddByte(buf, (Byte)'\0');
2451         line = (char *)Buf_GetAll(buf, &lineLength);
2452     } while (skip == 1 && line[0] != '.');
2453 
2454     Buf_Destroy(buf, FALSE);
2455     return line;
2456 }
2457 
2458 
2459 /*-
2460  *---------------------------------------------------------------------
2461  * ParseReadLine --
2462  *	Read an entire line from the input file. Called only by Parse_File.
2463  *	To facilitate escaped newlines and what have you, a character is
2464  *	buffered in 'lastc', which is '\0' when no characters have been
2465  *	read. When we break out of the loop, c holds the terminating
2466  *	character and lastc holds a character that should be added to
2467  *	the line (unless we don't read anything but a terminator).
2468  *
2469  * Results:
2470  *	A line w/o its newline
2471  *
2472  * Side Effects:
2473  *	Only those associated with reading a character
2474  *---------------------------------------------------------------------
2475  */
2476 static char *
2477 ParseReadLine(void)
2478 {
2479     Buffer  	  buf;	    	/* Buffer for current line */
2480     int		  c;	      	/* the current character */
2481     int		  lastc;    	/* The most-recent character */
2482     Boolean	  semiNL;     	/* treat semi-colons as newlines */
2483     Boolean	  ignDepOp;   	/* TRUE if should ignore dependency operators
2484 				 * for the purposes of setting semiNL */
2485     Boolean 	  ignComment;	/* TRUE if should ignore comments (in a
2486 				 * shell command */
2487     char 	  *line;    	/* Result */
2488     char          *ep;		/* to strip trailing blanks */
2489     int	    	  lineLength;	/* Length of result */
2490     int	    	  lineno;	/* Saved line # */
2491 
2492     semiNL = FALSE;
2493     ignDepOp = FALSE;
2494     ignComment = FALSE;
2495 
2496     /*
2497      * Handle special-characters at the beginning of the line. Either a
2498      * leading tab (shell command) or pound-sign (possible conditional)
2499      * forces us to ignore comments and dependency operators and treat
2500      * semi-colons as semi-colons (by leaving semiNL FALSE). This also
2501      * discards completely blank lines.
2502      */
2503     for (;;) {
2504 	c = ParseReadc();
2505 
2506 	if (c == '\t') {
2507 	    ignComment = ignDepOp = TRUE;
2508 	    break;
2509 	} else if (c == '\n') {
2510 	    curFile.lineno++;
2511 	} else if (c == '#') {
2512 	    ParseUnreadc(c);
2513 	    break;
2514 	} else {
2515 	    /*
2516 	     * Anything else breaks out without doing anything
2517 	     */
2518 	    break;
2519 	}
2520     }
2521 
2522     if (c != EOF) {
2523 	lastc = c;
2524 	buf = Buf_Init(MAKE_BSIZE);
2525 
2526 	while (((c = ParseReadc()) != '\n' || (lastc == '\\')) &&
2527 	       (c != EOF))
2528 	{
2529 test_char:
2530 	    switch(c) {
2531 	    case '\n':
2532 		/*
2533 		 * Escaped newline: read characters until a non-space or an
2534 		 * unescaped newline and replace them all by a single space.
2535 		 * This is done by storing the space over the backslash and
2536 		 * dropping through with the next nonspace. If it is a
2537 		 * semi-colon and semiNL is TRUE, it will be recognized as a
2538 		 * newline in the code below this...
2539 		 */
2540 		curFile.lineno++;
2541 		lastc = ' ';
2542 		while ((c = ParseReadc()) == ' ' || c == '\t') {
2543 		    continue;
2544 		}
2545 		if (c == EOF || c == '\n') {
2546 		    goto line_read;
2547 		} else {
2548 		    /*
2549 		     * Check for comments, semiNL's, etc. -- easier than
2550 		     * ParseUnreadc(c); continue;
2551 		     */
2552 		    goto test_char;
2553 		}
2554 		/*NOTREACHED*/
2555 		break;
2556 
2557 	    case ';':
2558 		/*
2559 		 * Semi-colon: Need to see if it should be interpreted as a
2560 		 * newline
2561 		 */
2562 		if (semiNL) {
2563 		    /*
2564 		     * To make sure the command that may be following this
2565 		     * semi-colon begins with a tab, we push one back into the
2566 		     * input stream. This will overwrite the semi-colon in the
2567 		     * buffer. If there is no command following, this does no
2568 		     * harm, since the newline remains in the buffer and the
2569 		     * whole line is ignored.
2570 		     */
2571 		    ParseUnreadc('\t');
2572 		    goto line_read;
2573 		}
2574 		break;
2575 	    case '=':
2576 		if (!semiNL) {
2577 		    /*
2578 		     * Haven't seen a dependency operator before this, so this
2579 		     * must be a variable assignment -- don't pay attention to
2580 		     * dependency operators after this.
2581 		     */
2582 		    ignDepOp = TRUE;
2583 		} else if (lastc == ':' || lastc == '!') {
2584 		    /*
2585 		     * Well, we've seen a dependency operator already, but it
2586 		     * was the previous character, so this is really just an
2587 		     * expanded variable assignment. Revert semi-colons to
2588 		     * being just semi-colons again and ignore any more
2589 		     * dependency operators.
2590 		     *
2591 		     * XXX: Note that a line like "foo : a:=b" will blow up,
2592 		     * but who'd write a line like that anyway?
2593 		     */
2594 		    ignDepOp = TRUE; semiNL = FALSE;
2595 		}
2596 		break;
2597 	    case '#':
2598 		if (!ignComment) {
2599 		    if (
2600 #if 0
2601 		    compatMake &&
2602 #endif
2603 		    (lastc != '\\')) {
2604 			/*
2605 			 * If the character is a hash mark and it isn't escaped
2606 			 * (or we're being compatible), the thing is a comment.
2607 			 * Skip to the end of the line.
2608 			 */
2609 			do {
2610 			    c = ParseReadc();
2611 			    /*
2612 			     * If we found a backslash not escaped
2613 			     * itself it means that the comment is
2614 			     * going to continue in the next line.
2615 			     */
2616 			    if (c == '\\')
2617 				ParseReadc();
2618 			} while ((c != '\n') && (c != EOF));
2619 			goto line_read;
2620 		    } else {
2621 			/*
2622 			 * Don't add the backslash. Just let the # get copied
2623 			 * over.
2624 			 */
2625 			lastc = c;
2626 			continue;
2627 		    }
2628 		}
2629 		break;
2630 	    case ':':
2631 	    case '!':
2632 		if (!ignDepOp && (c == ':' || c == '!')) {
2633 		    /*
2634 		     * A semi-colon is recognized as a newline only on
2635 		     * dependency lines. Dependency lines are lines with a
2636 		     * colon or an exclamation point. Ergo...
2637 		     */
2638 		    semiNL = TRUE;
2639 		}
2640 		break;
2641 	    }
2642 	    /*
2643 	     * Copy in the previous character and save this one in lastc.
2644 	     */
2645 	    Buf_AddByte(buf, (Byte)lastc);
2646 	    lastc = c;
2647 
2648 	}
2649     line_read:
2650 	curFile.lineno++;
2651 
2652 	if (lastc != '\0') {
2653 	    Buf_AddByte(buf, (Byte)lastc);
2654 	}
2655 	Buf_AddByte(buf, (Byte)'\0');
2656 	line = (char *)Buf_GetAll(buf, &lineLength);
2657 	Buf_Destroy(buf, FALSE);
2658 
2659 	/*
2660 	 * Strip trailing blanks and tabs from the line.
2661 	 * Do not strip a blank or tab that is preceded by
2662 	 * a '\'
2663 	 */
2664 	ep = line;
2665 	while (*ep)
2666 	    ++ep;
2667 	while (ep > line + 1 && (ep[-1] == ' ' || ep[-1] == '\t')) {
2668 	    if (ep > line + 1 && ep[-2] == '\\')
2669 		break;
2670 	    --ep;
2671 	}
2672 	*ep = 0;
2673 
2674 	if (line[0] == '.') {
2675 	    /*
2676 	     * The line might be a conditional. Ask the conditional module
2677 	     * about it and act accordingly
2678 	     */
2679 	    switch (Cond_Eval(line)) {
2680 	    case COND_SKIP:
2681 		/*
2682 		 * Skip to next conditional that evaluates to COND_PARSE.
2683 		 */
2684 		do {
2685 		    free(line);
2686 		    line = ParseSkipLine(1, 0);
2687 		} while (line && Cond_Eval(line) != COND_PARSE);
2688 		if (line == NULL)
2689 		    break;
2690 		/*FALLTHRU*/
2691 	    case COND_PARSE:
2692 		free(line);
2693 		line = ParseReadLine();
2694 		break;
2695 	    case COND_INVALID:
2696 		lineno = curFile.lineno;
2697 		if (For_Eval(line)) {
2698 		    int ok;
2699 		    free(line);
2700 		    do {
2701 			/*
2702 			 * Skip after the matching end
2703 			 */
2704 			line = ParseSkipLine(0, 1);
2705 			if (line == NULL) {
2706 			    Parse_Error(PARSE_FATAL,
2707 				     "Unexpected end of file in for loop.\n");
2708 			    break;
2709 			}
2710 			ok = For_Eval(line);
2711 			free(line);
2712 		    }
2713 		    while (ok);
2714 		    if (line != NULL)
2715 			For_Run(lineno);
2716 		    line = ParseReadLine();
2717 		}
2718 		break;
2719 	    }
2720 	}
2721 	return (line);
2722 
2723     } else {
2724 	/*
2725 	 * Hit end-of-file, so return a NULL line to indicate this.
2726 	 */
2727 	return(NULL);
2728     }
2729 }
2730 
2731 /*-
2732  *-----------------------------------------------------------------------
2733  * ParseFinishLine --
2734  *	Handle the end of a dependency group.
2735  *
2736  * Results:
2737  *	Nothing.
2738  *
2739  * Side Effects:
2740  *	inLine set FALSE. 'targets' list destroyed.
2741  *
2742  *-----------------------------------------------------------------------
2743  */
2744 static void
2745 ParseFinishLine(void)
2746 {
2747     if (inLine) {
2748 	Lst_ForEach(targets, Suff_EndTransform, NULL);
2749 	Lst_Destroy(targets, ParseHasCommands);
2750 	targets = NULL;
2751 	inLine = FALSE;
2752     }
2753 }
2754 
2755 
2756 /*-
2757  *---------------------------------------------------------------------
2758  * Parse_File --
2759  *	Parse a file into its component parts, incorporating it into the
2760  *	current dependency graph. This is the main function and controls
2761  *	almost every other function in this module
2762  *
2763  * Input:
2764  *	name		the name of the file being read
2765  *	stream		Stream open to makefile to parse
2766  *
2767  * Results:
2768  *	None
2769  *
2770  * Side Effects:
2771  *	Loads. Nodes are added to the list of all targets, nodes and links
2772  *	are added to the dependency graph. etc. etc. etc.
2773  *---------------------------------------------------------------------
2774  */
2775 void
2776 Parse_File(const char *name, FILE *stream)
2777 {
2778     char	  *cp;		/* pointer into the line */
2779     char          *line;	/* the line we're working on */
2780 #ifndef POSIX
2781     Boolean	nonSpace;
2782 #endif
2783 
2784     inLine = FALSE;
2785     fatals = 0;
2786 
2787     curFile.fname = UNCONST(name);
2788     curFile.F = stream;
2789     curFile.lineno = 0;
2790 
2791     ParseSetParseFile(curFile.fname);
2792 
2793     do {
2794 	for (; (line = ParseReadLine()) != NULL; free(line)) {
2795 	    if (*line == '.') {
2796 		/*
2797 		 * Lines that begin with the special character are either
2798 		 * include or undef directives.
2799 		 */
2800 		for (cp = line + 1; isspace ((unsigned char)*cp); cp++) {
2801 		    continue;
2802 		}
2803 		if (strncmp(cp, "include", 7) == 0 ||
2804 	    	    ((cp[0] == 's' || cp[0] == '-') &&
2805 		    strncmp(&cp[1], "include", 7) == 0)) {
2806 		    ParseDoInclude(cp);
2807 		    continue;
2808 		}
2809 		if (strncmp(cp, "undef", 5) == 0) {
2810 		    char *cp2;
2811 		    for (cp += 5; isspace((unsigned char) *cp); cp++) {
2812 			continue;
2813 		    }
2814 
2815 		    for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2816 				   (*cp2 != '\0'); cp2++) {
2817 			continue;
2818 		    }
2819 
2820 		    *cp2 = '\0';
2821 
2822 		    Var_Delete(cp, VAR_GLOBAL);
2823 		    continue;
2824 		}
2825 	    }
2826 	    if (*line == '#') {
2827 		/* If we're this far, the line must be a comment. */
2828 		continue;
2829 	    }
2830 
2831 	    if (*line == '\t') {
2832 		/*
2833 		 * If a line starts with a tab, it can only hope to be
2834 		 * a creation command.
2835 		 */
2836 #ifndef POSIX
2837 	    shellCommand:
2838 #endif
2839 		for (cp = line + 1; isspace ((unsigned char)*cp); cp++) {
2840 		    continue;
2841 		}
2842 		if (*cp) {
2843 		    if (!inLine)
2844 			Parse_Error(PARSE_FATAL,
2845 				     "Unassociated shell command \"%s\"",
2846 				     cp);
2847 		    /*
2848 		     * So long as it's not a blank line and we're actually
2849 		     * in a dependency spec, add the command to the list of
2850 		     * commands of all targets in the dependency spec
2851 		     */
2852 		    Lst_ForEach(targets, ParseAddCmd, cp);
2853 #ifdef CLEANUP
2854 		    Lst_AtEnd(targCmds, line);
2855 #endif
2856 		    line = 0;
2857 		}
2858 		continue;
2859 	    }
2860 
2861 #ifdef SYSVINCLUDE
2862 	    if (((strncmp(line, "include", 7) == 0 &&
2863 		    isspace((unsigned char) line[7])) ||
2864 			((line[0] == 's' || line[0] == '-') &&
2865 			    strncmp(&line[1], "include", 7) == 0 &&
2866 			    isspace((unsigned char) line[8]))) &&
2867 		    strchr(line, ':') == NULL) {
2868 		/*
2869 		 * It's an S3/S5-style "include".
2870 		 */
2871 		ParseTraditionalInclude(line);
2872 		continue;
2873 	    }
2874 #endif
2875 	    if (Parse_IsVar(line)) {
2876 		ParseFinishLine();
2877 		Parse_DoVar(line, VAR_GLOBAL);
2878 		continue;
2879 	    }
2880 
2881 	    /*
2882 	     * We now know it's a dependency line so it needs to have all
2883 	     * variables expanded before being parsed. Tell the variable
2884 	     * module to complain if some variable is undefined...
2885 	     * To make life easier on novices, if the line is indented we
2886 	     * first make sure the line has a dependency operator in it.
2887 	     * If it doesn't have an operator and we're in a dependency
2888 	     * line's script, we assume it's actually a shell command
2889 	     * and add it to the current list of targets.
2890 	     */
2891 #ifndef POSIX
2892 	    nonSpace = FALSE;
2893 #endif
2894 
2895 	    cp = line;
2896 	    if (isspace((unsigned char) line[0])) {
2897 		while ((*cp != '\0') && isspace((unsigned char) *cp)) {
2898 		    cp++;
2899 		}
2900 		if (*cp == '\0') {
2901 		    /* Ignore blank line in commands */
2902 		    continue;
2903 		}
2904 #ifndef POSIX
2905 		while (*cp && (ParseIsEscaped(line, cp) ||
2906 			(*cp != ':') && (*cp != '!'))) {
2907 		    nonSpace = TRUE;
2908 		    cp++;
2909 		}
2910 #endif
2911 	    }
2912 
2913 #ifndef POSIX
2914 	    if (*cp == '\0') {
2915 		if (inLine) {
2916 		    Parse_Error(PARSE_WARNING,
2917 				 "Shell command needs a leading tab");
2918 		    goto shellCommand;
2919 		} else if (nonSpace) {
2920 		    Parse_Error(PARSE_FATAL, "Missing operator");
2921 		}
2922 		continue;
2923 	    }
2924 #endif
2925 	    ParseFinishLine();
2926 
2927 	    cp = Var_Subst(NULL, line, VAR_CMD, TRUE);
2928 	    free(line);
2929 	    line = cp;
2930 
2931 	    /*
2932 	     * Need a non-circular list for the target nodes
2933 	     */
2934 	    if (targets)
2935 		Lst_Destroy(targets, NOFREE);
2936 
2937 	    targets = Lst_Init(FALSE);
2938 	    inLine = TRUE;
2939 
2940 	    ParseDoDependency(line);
2941 	}
2942 	/*
2943 	 * Reached EOF, but it may be just EOF of an include file...
2944 	 */
2945     } while (ParseEOF(1) == CONTINUE);
2946 
2947     /*
2948      * Make sure conditionals are clean
2949      */
2950     Cond_End();
2951 
2952     if (fatals) {
2953 	(void)fprintf(stderr,
2954 	    "%s: Fatal errors encountered -- cannot continue\n",
2955 	    progname);
2956 	PrintOnError(NULL);
2957 	exit(1);
2958     }
2959 }
2960 
2961 /*-
2962  *---------------------------------------------------------------------
2963  * Parse_Init --
2964  *	initialize the parsing module
2965  *
2966  * Results:
2967  *	none
2968  *
2969  * Side Effects:
2970  *	the parseIncPath list is initialized...
2971  *---------------------------------------------------------------------
2972  */
2973 void
2974 Parse_Init(void)
2975 {
2976     mainNode = NILGNODE;
2977     parseIncPath = Lst_Init(FALSE);
2978     sysIncPath = Lst_Init(FALSE);
2979     defIncPath = Lst_Init(FALSE);
2980     includes = Lst_Init(FALSE);
2981 #ifdef CLEANUP
2982     targCmds = Lst_Init(FALSE);
2983 #endif
2984 }
2985 
2986 void
2987 Parse_End(void)
2988 {
2989 #ifdef CLEANUP
2990     Lst_Destroy(targCmds, (FreeProc *)free);
2991     if (targets)
2992 	Lst_Destroy(targets, NOFREE);
2993     Lst_Destroy(defIncPath, Dir_Destroy);
2994     Lst_Destroy(sysIncPath, Dir_Destroy);
2995     Lst_Destroy(parseIncPath, Dir_Destroy);
2996     Lst_Destroy(includes, NOFREE);	/* Should be empty now */
2997 #endif
2998 }
2999 
3000 
3001 /*-
3002  *-----------------------------------------------------------------------
3003  * Parse_MainName --
3004  *	Return a Lst of the main target to create for main()'s sake. If
3005  *	no such target exists, we Punt with an obnoxious error message.
3006  *
3007  * Results:
3008  *	A Lst of the single node to create.
3009  *
3010  * Side Effects:
3011  *	None.
3012  *
3013  *-----------------------------------------------------------------------
3014  */
3015 Lst
3016 Parse_MainName(void)
3017 {
3018     Lst           mainList;	/* result list */
3019 
3020     mainList = Lst_Init(FALSE);
3021 
3022     if (mainNode == NILGNODE) {
3023 	Punt("no target to make.");
3024     	/*NOTREACHED*/
3025     } else if (mainNode->type & OP_DOUBLEDEP) {
3026 	(void)Lst_AtEnd(mainList, mainNode);
3027 	Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3028     }
3029     else
3030 	(void)Lst_AtEnd(mainList, mainNode);
3031     Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3032     return (mainList);
3033 }
3034 
3035 /*-
3036  *-----------------------------------------------------------------------
3037  * ParseMark --
3038  *	Add the filename and lineno to the GNode so that we remember
3039  *	where it was first defined.
3040  *
3041  * Side Effects:
3042  *	None.
3043  *
3044  *-----------------------------------------------------------------------
3045  */
3046 static void
3047 ParseMark(GNode *gn)
3048 {
3049     gn->fname = strdup(curFile.fname);
3050     gn->lineno = curFile.lineno;
3051 }
3052