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