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