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