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