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