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