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