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