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