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