xref: /freebsd/contrib/bmake/parse.c (revision 3a9fd8242b35884921dfc4e886f284a75870a536)
1 /*	$NetBSD: parse.c,v 1.662 2022/02/05 00:37:19 sjg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *	The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *	This product includes software developed by the University of
53  *	California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 /*
72  * Parsing of makefiles.
73  *
74  * Parse_File is the main entry point and controls most of the other
75  * functions in this module.
76  *
77  * Interface:
78  *	Parse_Init	Initialize the module
79  *
80  *	Parse_End	Clean up the module
81  *
82  *	Parse_File	Parse a top-level makefile.  Included files are
83  *			handled by IncludeFile instead.
84  *
85  *	Parse_VarAssign
86  *			Try to parse the given line as a variable assignment.
87  *			Used by MainParseArgs to determine if an argument is
88  *			a target or a variable assignment.  Used internally
89  *			for pretty much the same thing.
90  *
91  *	Parse_Error	Report a parse error, a warning or an informational
92  *			message.
93  *
94  *	Parse_MainName	Returns a list of the single main target to create.
95  */
96 
97 #include <sys/types.h>
98 #include <sys/stat.h>
99 #include <errno.h>
100 #include <stdarg.h>
101 
102 #include "make.h"
103 
104 #ifdef HAVE_STDINT_H
105 #include <stdint.h>
106 #endif
107 
108 #ifdef HAVE_MMAP
109 #include <sys/mman.h>
110 
111 #ifndef MAP_COPY
112 #define MAP_COPY MAP_PRIVATE
113 #endif
114 #ifndef MAP_FILE
115 #define MAP_FILE 0
116 #endif
117 #endif
118 
119 #include "dir.h"
120 #include "job.h"
121 #include "pathnames.h"
122 
123 /*	"@(#)parse.c	8.3 (Berkeley) 3/19/94"	*/
124 MAKE_RCSID("$NetBSD: parse.c,v 1.662 2022/02/05 00:37:19 sjg Exp $");
125 
126 /*
127  * A file being read.
128  */
129 typedef struct IncludedFile {
130 	FStr name;		/* absolute or relative to the cwd */
131 	unsigned lineno;	/* 1-based */
132 	unsigned readLines;	/* the number of physical lines that have
133 				 * been read from the file */
134 	unsigned forHeadLineno;	/* 1-based */
135 	unsigned forBodyReadLines; /* the number of physical lines that have
136 				 * been read from the file above the body of
137 				 * the .for loop */
138 	unsigned int cond_depth; /* 'if' nesting when file opened */
139 	bool depending;		/* state of doing_depend on EOF */
140 
141 	Buffer buf;		/* the file's content or the body of the .for
142 				 * loop; always ends with '\n' */
143 	char *buf_ptr;		/* next char to be read */
144 	char *buf_end;		/* buf_end[-1] == '\n' */
145 
146 	struct ForLoop *forLoop;
147 } IncludedFile;
148 
149 /* Special attributes for target nodes. */
150 typedef enum ParseSpecial {
151 	SP_ATTRIBUTE,	/* Generic attribute */
152 	SP_BEGIN,	/* .BEGIN */
153 	SP_DEFAULT,	/* .DEFAULT */
154 	SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
155 	SP_END,		/* .END */
156 	SP_ERROR,	/* .ERROR */
157 	SP_IGNORE,	/* .IGNORE */
158 	SP_INCLUDES,	/* .INCLUDES; not mentioned in the manual page */
159 	SP_INTERRUPT,	/* .INTERRUPT */
160 	SP_LIBS,	/* .LIBS; not mentioned in the manual page */
161 	SP_MAIN,	/* .MAIN and no user-specified targets to make */
162 	SP_META,	/* .META */
163 	SP_MFLAGS,	/* .MFLAGS or .MAKEFLAGS */
164 	SP_NOMETA,	/* .NOMETA */
165 	SP_NOMETA_CMP,	/* .NOMETA_CMP */
166 	SP_NOPATH,	/* .NOPATH */
167 	SP_NOT,		/* Not special */
168 	SP_NOTPARALLEL,	/* .NOTPARALLEL or .NO_PARALLEL */
169 	SP_NULL,	/* .NULL; not mentioned in the manual page */
170 	SP_OBJDIR,	/* .OBJDIR */
171 	SP_ORDER,	/* .ORDER */
172 	SP_PARALLEL,	/* .PARALLEL; not mentioned in the manual page */
173 	SP_PATH,	/* .PATH or .PATH.suffix */
174 	SP_PHONY,	/* .PHONY */
175 #ifdef POSIX
176 	SP_POSIX,	/* .POSIX; not mentioned in the manual page */
177 #endif
178 	SP_PRECIOUS,	/* .PRECIOUS */
179 	SP_SHELL,	/* .SHELL */
180 	SP_SILENT,	/* .SILENT */
181 	SP_SINGLESHELL,	/* .SINGLESHELL; not mentioned in the manual page */
182 	SP_STALE,	/* .STALE */
183 	SP_SUFFIXES,	/* .SUFFIXES */
184 	SP_WAIT		/* .WAIT */
185 } ParseSpecial;
186 
187 typedef List SearchPathList;
188 typedef ListNode SearchPathListNode;
189 
190 
191 typedef enum VarAssignOp {
192 	VAR_NORMAL,		/* = */
193 	VAR_APPEND,		/* += */
194 	VAR_DEFAULT,		/* ?= */
195 	VAR_SUBST,		/* := */
196 	VAR_SHELL		/* != or :sh= */
197 } VarAssignOp;
198 
199 typedef struct VarAssign {
200 	char *varname;		/* unexpanded */
201 	VarAssignOp op;
202 	const char *value;	/* unexpanded */
203 } VarAssign;
204 
205 static bool Parse_IsVar(const char *, VarAssign *);
206 static void Parse_Var(VarAssign *, GNode *);
207 
208 /*
209  * The target to be made if no targets are specified in the command line.
210  * This is the first target defined in any of the makefiles.
211  */
212 GNode *mainNode;
213 
214 /*
215  * During parsing, the targets from the left-hand side of the currently
216  * active dependency line, or NULL if the current line does not belong to a
217  * dependency line, for example because it is a variable assignment.
218  *
219  * See unit-tests/deptgt.mk, keyword "parse.c:targets".
220  */
221 static GNodeList *targets;
222 
223 #ifdef CLEANUP
224 /*
225  * All shell commands for all targets, in no particular order and possibly
226  * with duplicates.  Kept in a separate list since the commands from .USE or
227  * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
228  * easily understandable ownership over the allocated strings.
229  */
230 static StringList targCmds = LST_INIT;
231 #endif
232 
233 /*
234  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
235  * is seen, then set to each successive source on the line.
236  */
237 static GNode *order_pred;
238 
239 static int parseErrors = 0;
240 
241 /*
242  * The include chain of makefiles.  At index 0 is the top-level makefile from
243  * the command line, followed by the included files or .for loops, up to and
244  * including the current file.
245  *
246  * See PrintStackTrace for how to interpret the data.
247  */
248 static Vector /* of IncludedFile */ includes;
249 
250 SearchPath *parseIncPath;	/* directories for "..." includes */
251 SearchPath *sysIncPath;		/* directories for <...> includes */
252 SearchPath *defSysIncPath;	/* default for sysIncPath */
253 
254 /*
255  * The parseKeywords table is searched using binary search when deciding
256  * if a target or source is special. The 'spec' field is the ParseSpecial
257  * type of the keyword (SP_NOT if the keyword isn't special as a target) while
258  * the 'op' field is the operator to apply to the list of targets if the
259  * keyword is used as a source ("0" if the keyword isn't special as a source)
260  */
261 static const struct {
262 	const char name[17];
263 	ParseSpecial special;	/* when used as a target */
264 	GNodeType targetAttr;	/* when used as a source */
265 } parseKeywords[] = {
266     { ".BEGIN",		SP_BEGIN,	OP_NONE },
267     { ".DEFAULT",	SP_DEFAULT,	OP_NONE },
268     { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
269     { ".END",		SP_END,		OP_NONE },
270     { ".ERROR",		SP_ERROR,	OP_NONE },
271     { ".EXEC",		SP_ATTRIBUTE,	OP_EXEC },
272     { ".IGNORE",	SP_IGNORE,	OP_IGNORE },
273     { ".INCLUDES",	SP_INCLUDES,	OP_NONE },
274     { ".INTERRUPT",	SP_INTERRUPT,	OP_NONE },
275     { ".INVISIBLE",	SP_ATTRIBUTE,	OP_INVISIBLE },
276     { ".JOIN",		SP_ATTRIBUTE,	OP_JOIN },
277     { ".LIBS",		SP_LIBS,	OP_NONE },
278     { ".MADE",		SP_ATTRIBUTE,	OP_MADE },
279     { ".MAIN",		SP_MAIN,	OP_NONE },
280     { ".MAKE",		SP_ATTRIBUTE,	OP_MAKE },
281     { ".MAKEFLAGS",	SP_MFLAGS,	OP_NONE },
282     { ".META",		SP_META,	OP_META },
283     { ".MFLAGS",	SP_MFLAGS,	OP_NONE },
284     { ".NOMETA",	SP_NOMETA,	OP_NOMETA },
285     { ".NOMETA_CMP",	SP_NOMETA_CMP,	OP_NOMETA_CMP },
286     { ".NOPATH",	SP_NOPATH,	OP_NOPATH },
287     { ".NOTMAIN",	SP_ATTRIBUTE,	OP_NOTMAIN },
288     { ".NOTPARALLEL",	SP_NOTPARALLEL,	OP_NONE },
289     { ".NO_PARALLEL",	SP_NOTPARALLEL,	OP_NONE },
290     { ".NULL",		SP_NULL,	OP_NONE },
291     { ".OBJDIR",	SP_OBJDIR,	OP_NONE },
292     { ".OPTIONAL",	SP_ATTRIBUTE,	OP_OPTIONAL },
293     { ".ORDER",		SP_ORDER,	OP_NONE },
294     { ".PARALLEL",	SP_PARALLEL,	OP_NONE },
295     { ".PATH",		SP_PATH,	OP_NONE },
296     { ".PHONY",		SP_PHONY,	OP_PHONY },
297 #ifdef POSIX
298     { ".POSIX",		SP_POSIX,	OP_NONE },
299 #endif
300     { ".PRECIOUS",	SP_PRECIOUS,	OP_PRECIOUS },
301     { ".RECURSIVE",	SP_ATTRIBUTE,	OP_MAKE },
302     { ".SHELL",		SP_SHELL,	OP_NONE },
303     { ".SILENT",	SP_SILENT,	OP_SILENT },
304     { ".SINGLESHELL",	SP_SINGLESHELL,	OP_NONE },
305     { ".STALE",		SP_STALE,	OP_NONE },
306     { ".SUFFIXES",	SP_SUFFIXES,	OP_NONE },
307     { ".USE",		SP_ATTRIBUTE,	OP_USE },
308     { ".USEBEFORE",	SP_ATTRIBUTE,	OP_USEBEFORE },
309     { ".WAIT",		SP_WAIT,	OP_NONE },
310 };
311 
312 
313 static IncludedFile *
314 GetInclude(size_t i)
315 {
316 	return Vector_Get(&includes, i);
317 }
318 
319 /* The file that is currently being read. */
320 static IncludedFile *
321 CurFile(void)
322 {
323 	return GetInclude(includes.len - 1);
324 }
325 
326 static Buffer
327 loadfile(const char *path, int fd)
328 {
329 	ssize_t n;
330 	Buffer buf;
331 	size_t bufSize;
332 	struct stat st;
333 
334 	bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
335 		  st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
336 	    ? (size_t)st.st_size : 1024;
337 	Buf_InitSize(&buf, bufSize);
338 
339 	for (;;) {
340 		if (buf.len == buf.cap) {
341 			if (buf.cap >= 512 * 1024 * 1024) {
342 				Error("%s: file too large", path);
343 				exit(2); /* Not 1 so -q can distinguish error */
344 			}
345 			Buf_Expand(&buf);
346 		}
347 		assert(buf.len < buf.cap);
348 		n = read(fd, buf.data + buf.len, buf.cap - buf.len);
349 		if (n < 0) {
350 			Error("%s: read error: %s", path, strerror(errno));
351 			exit(2);	/* Not 1 so -q can distinguish error */
352 		}
353 		if (n == 0)
354 			break;
355 
356 		buf.len += (size_t)n;
357 	}
358 	assert(buf.len <= buf.cap);
359 
360 	if (!Buf_EndsWith(&buf, '\n'))
361 		Buf_AddByte(&buf, '\n');
362 
363 	return buf;		/* may not be null-terminated */
364 }
365 
366 /*
367  * Print the current chain of .include and .for directives.  In Parse_Fatal
368  * or other functions that already print the location, includingInnermost
369  * would be redundant, but in other cases like Error or Fatal it needs to be
370  * included.
371  */
372 void
373 PrintStackTrace(bool includingInnermost)
374 {
375 	const IncludedFile *entries;
376 	size_t i, n;
377 
378 	entries = GetInclude(0);
379 	n = includes.len;
380 	if (n == 0)
381 		return;
382 
383 	if (!includingInnermost && entries[n - 1].forLoop == NULL)
384 		n--;		/* already in the diagnostic */
385 
386 	for (i = n; i-- > 0;) {
387 		const IncludedFile *entry = entries + i;
388 		const char *fname = entry->name.str;
389 		char dirbuf[MAXPATHLEN + 1];
390 
391 		if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0)
392 			fname = realpath(fname, dirbuf);
393 
394 		if (entry->forLoop != NULL) {
395 			char *details = ForLoop_Details(entry->forLoop);
396 			debug_printf("\tin .for loop from %s:%u with %s\n",
397 			    fname, entry->forHeadLineno, details);
398 			free(details);
399 		} else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
400 			/* entry->lineno is not a useful line number */
401 		} else
402 			debug_printf("\tin %s:%u\n", fname, entry->lineno);
403 	}
404 }
405 
406 /* Check if the current character is escaped on the current line. */
407 static bool
408 IsEscaped(const char *line, const char *p)
409 {
410 	bool escaped = false;
411 	while (p > line && *--p == '\\')
412 		escaped = !escaped;
413 	return escaped;
414 }
415 
416 /*
417  * Add the filename and lineno to the GNode so that we remember where it
418  * was first defined.
419  */
420 static void
421 RememberLocation(GNode *gn)
422 {
423 	IncludedFile *curFile = CurFile();
424 	gn->fname = Str_Intern(curFile->name.str);
425 	gn->lineno = curFile->lineno;
426 }
427 
428 /*
429  * Look in the table of keywords for one matching the given string.
430  * Return the index of the keyword, or -1 if it isn't there.
431  */
432 static int
433 FindKeyword(const char *str)
434 {
435 	int start = 0;
436 	int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
437 
438 	while (start <= end) {
439 		int curr = start + (end - start) / 2;
440 		int diff = strcmp(str, parseKeywords[curr].name);
441 
442 		if (diff == 0)
443 			return curr;
444 		if (diff < 0)
445 			end = curr - 1;
446 		else
447 			start = curr + 1;
448 	}
449 
450 	return -1;
451 }
452 
453 void
454 PrintLocation(FILE *f, bool useVars, const char *fname, unsigned lineno)
455 {
456 	char dirbuf[MAXPATHLEN + 1];
457 	FStr dir, base;
458 
459 	if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
460 		(void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
461 		return;
462 	}
463 
464 	dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
465 	if (dir.str == NULL)
466 		dir.str = ".";
467 	if (dir.str[0] != '/')
468 		dir.str = realpath(dir.str, dirbuf);
469 
470 	base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
471 	if (base.str == NULL)
472 		base.str = str_basename(fname);
473 
474 	(void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
475 
476 	FStr_Done(&base);
477 	FStr_Done(&dir);
478 }
479 
480 static void MAKE_ATTR_PRINTFLIKE(6, 0)
481 ParseVErrorInternal(FILE *f, bool useVars, const char *fname, unsigned lineno,
482 		    ParseErrorLevel type, const char *fmt, va_list ap)
483 {
484 	static bool fatal_warning_error_printed = false;
485 
486 	(void)fprintf(f, "%s: ", progname);
487 
488 	if (fname != NULL)
489 		PrintLocation(f, useVars, fname, lineno);
490 	if (type == PARSE_WARNING)
491 		(void)fprintf(f, "warning: ");
492 	(void)vfprintf(f, fmt, ap);
493 	(void)fprintf(f, "\n");
494 	(void)fflush(f);
495 
496 	if (type == PARSE_FATAL)
497 		parseErrors++;
498 	if (type == PARSE_WARNING && opts.parseWarnFatal) {
499 		if (!fatal_warning_error_printed) {
500 			Error("parsing warnings being treated as errors");
501 			fatal_warning_error_printed = true;
502 		}
503 		parseErrors++;
504 	}
505 
506 	if (DEBUG(PARSE))
507 		PrintStackTrace(false);
508 }
509 
510 static void MAKE_ATTR_PRINTFLIKE(4, 5)
511 ParseErrorInternal(const char *fname, unsigned lineno,
512 		   ParseErrorLevel type, const char *fmt, ...)
513 {
514 	va_list ap;
515 
516 	(void)fflush(stdout);
517 	va_start(ap, fmt);
518 	ParseVErrorInternal(stderr, false, fname, lineno, type, fmt, ap);
519 	va_end(ap);
520 
521 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
522 		va_start(ap, fmt);
523 		ParseVErrorInternal(opts.debug_file, false, fname, lineno,
524 		    type, fmt, ap);
525 		va_end(ap);
526 	}
527 }
528 
529 /*
530  * Print a parse error message, including location information.
531  *
532  * If the level is PARSE_FATAL, continue parsing until the end of the
533  * current top-level makefile, then exit (see Parse_File).
534  *
535  * Fmt is given without a trailing newline.
536  */
537 void
538 Parse_Error(ParseErrorLevel type, const char *fmt, ...)
539 {
540 	va_list ap;
541 	const char *fname;
542 	unsigned lineno;
543 
544 	if (includes.len == 0) {
545 		fname = NULL;
546 		lineno = 0;
547 	} else {
548 		IncludedFile *curFile = CurFile();
549 		fname = curFile->name.str;
550 		lineno = curFile->lineno;
551 	}
552 
553 	(void)fflush(stdout);
554 	va_start(ap, fmt);
555 	ParseVErrorInternal(stderr, true, fname, lineno, type, fmt, ap);
556 	va_end(ap);
557 
558 	if (opts.debug_file != stdout && opts.debug_file != stderr) {
559 		va_start(ap, fmt);
560 		ParseVErrorInternal(opts.debug_file, true, fname, lineno,
561 		    type, fmt, ap);
562 		va_end(ap);
563 	}
564 }
565 
566 
567 /*
568  * Handle an .info, .warning or .error directive.  For an .error directive,
569  * exit immediately.
570  */
571 static void
572 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
573 {
574 	char *xmsg;
575 
576 	if (umsg[0] == '\0') {
577 		Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
578 		    levelName);
579 		return;
580 	}
581 
582 	(void)Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES, &xmsg);
583 	/* TODO: handle errors */
584 
585 	Parse_Error(level, "%s", xmsg);
586 	free(xmsg);
587 
588 	if (level == PARSE_FATAL) {
589 		PrintOnError(NULL, "\n");
590 		exit(1);
591 	}
592 }
593 
594 /*
595  * Add the child to the parent's children, and for non-special targets, vice
596  * versa.  Special targets such as .END do not need to be informed once the
597  * child target has been made.
598  */
599 static void
600 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
601 {
602 	if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
603 		pgn = pgn->cohorts.last->datum;
604 
605 	Lst_Append(&pgn->children, cgn);
606 	pgn->unmade++;
607 
608 	/* Special targets like .END don't need any children. */
609 	if (!isSpecial)
610 		Lst_Append(&cgn->parents, pgn);
611 
612 	if (DEBUG(PARSE)) {
613 		debug_printf("# LinkSource: added child %s - %s\n",
614 		    pgn->name, cgn->name);
615 		Targ_PrintNode(pgn, 0);
616 		Targ_PrintNode(cgn, 0);
617 	}
618 }
619 
620 /* Add the node to each target from the current dependency group. */
621 static void
622 LinkToTargets(GNode *gn, bool isSpecial)
623 {
624 	GNodeListNode *ln;
625 
626 	for (ln = targets->first; ln != NULL; ln = ln->next)
627 		LinkSource(ln->datum, gn, isSpecial);
628 }
629 
630 static bool
631 TryApplyDependencyOperator(GNode *gn, GNodeType op)
632 {
633 	/*
634 	 * If the node occurred on the left-hand side of a dependency and the
635 	 * operator also defines a dependency, they must match.
636 	 */
637 	if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
638 	    ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
639 		Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
640 		    gn->name);
641 		return false;
642 	}
643 
644 	if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
645 		/*
646 		 * If the node was of the left-hand side of a '::' operator,
647 		 * we need to create a new instance of it for the children
648 		 * and commands on this dependency line since each of these
649 		 * dependency groups has its own attributes and commands,
650 		 * separate from the others.
651 		 *
652 		 * The new instance is placed on the 'cohorts' list of the
653 		 * initial one (note the initial one is not on its own
654 		 * cohorts list) and the new instance is linked to all
655 		 * parents of the initial instance.
656 		 */
657 		GNode *cohort;
658 
659 		/*
660 		 * Propagate copied bits to the initial node.  They'll be
661 		 * propagated back to the rest of the cohorts later.
662 		 */
663 		gn->type |= op & ~OP_OPMASK;
664 
665 		cohort = Targ_NewInternalNode(gn->name);
666 		if (doing_depend)
667 			RememberLocation(cohort);
668 		/*
669 		 * Make the cohort invisible as well to avoid duplicating it
670 		 * into other variables. True, parents of this target won't
671 		 * tend to do anything with their local variables, but better
672 		 * safe than sorry.
673 		 *
674 		 * (I think this is pointless now, since the relevant list
675 		 * traversals will no longer see this node anyway. -mycroft)
676 		 */
677 		cohort->type = op | OP_INVISIBLE;
678 		Lst_Append(&gn->cohorts, cohort);
679 		cohort->centurion = gn;
680 		gn->unmade_cohorts++;
681 		snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
682 		    (unsigned int)gn->unmade_cohorts % 1000000);
683 	} else {
684 		/*
685 		 * We don't want to nuke any previous flags (whatever they
686 		 * were) so we just OR the new operator into the old.
687 		 */
688 		gn->type |= op;
689 	}
690 
691 	return true;
692 }
693 
694 static void
695 ApplyDependencyOperator(GNodeType op)
696 {
697 	GNodeListNode *ln;
698 
699 	for (ln = targets->first; ln != NULL; ln = ln->next)
700 		if (!TryApplyDependencyOperator(ln->datum, op))
701 			break;
702 }
703 
704 /*
705  * We add a .WAIT node in the dependency list. After any dynamic dependencies
706  * (and filename globbing) have happened, it is given a dependency on each
707  * previous child, back until the previous .WAIT node. The next child won't
708  * be scheduled until the .WAIT node is built.
709  *
710  * We give each .WAIT node a unique name (mainly for diagnostics).
711  */
712 static void
713 ApplyDependencySourceWait(bool isSpecial)
714 {
715 	static unsigned wait_number = 0;
716 	char wait_src[16];
717 	GNode *gn;
718 
719 	snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
720 	gn = Targ_NewInternalNode(wait_src);
721 	if (doing_depend)
722 		RememberLocation(gn);
723 	gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
724 	LinkToTargets(gn, isSpecial);
725 
726 }
727 
728 static bool
729 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
730 {
731 	int keywd;
732 	GNodeType targetAttr;
733 
734 	if (*src != '.' || !ch_isupper(src[1]))
735 		return false;
736 
737 	keywd = FindKeyword(src);
738 	if (keywd == -1)
739 		return false;
740 
741 	targetAttr = parseKeywords[keywd].targetAttr;
742 	if (targetAttr != OP_NONE) {
743 		ApplyDependencyOperator(targetAttr);
744 		return true;
745 	}
746 	if (parseKeywords[keywd].special == SP_WAIT) {
747 		ApplyDependencySourceWait(special != SP_NOT);
748 		return true;
749 	}
750 	return false;
751 }
752 
753 /*
754  * In a line like ".MAIN: source1 source2", add all sources to the list of
755  * things to create, but only if the user didn't specify a target on the
756  * command line and .MAIN occurs for the first time.
757  *
758  * See HandleDependencyTargetSpecial, branch SP_MAIN.
759  * See unit-tests/cond-func-make-main.mk.
760  */
761 static void
762 ApplyDependencySourceMain(const char *src)
763 {
764 	Lst_Append(&opts.create, bmake_strdup(src));
765 	/*
766 	 * Add the name to the .TARGETS variable as well, so the user can
767 	 * employ that, if desired.
768 	 */
769 	Global_Append(".TARGETS", src);
770 }
771 
772 static void
773 ApplyDependencySourceOrder(const char *src)
774 {
775 	GNode *gn;
776 	/*
777 	 * Create proper predecessor/successor links between the previous
778 	 * source and the current one.
779 	 */
780 	gn = Targ_GetNode(src);
781 	if (doing_depend)
782 		RememberLocation(gn);
783 	if (order_pred != NULL) {
784 		Lst_Append(&order_pred->order_succ, gn);
785 		Lst_Append(&gn->order_pred, order_pred);
786 		if (DEBUG(PARSE)) {
787 			debug_printf(
788 			    "# .ORDER forces '%s' to be made before '%s'\n",
789 			    order_pred->name, gn->name);
790 			Targ_PrintNode(order_pred, 0);
791 			Targ_PrintNode(gn, 0);
792 		}
793 	}
794 	/*
795 	 * The current source now becomes the predecessor for the next one.
796 	 */
797 	order_pred = gn;
798 }
799 
800 /* The source is not an attribute, so find/create a node for it. */
801 static void
802 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
803 			   ParseSpecial special)
804 {
805 	GNode *gn;
806 
807 	gn = Targ_GetNode(src);
808 	if (doing_depend)
809 		RememberLocation(gn);
810 	if (targetAttr != OP_NONE)
811 		gn->type |= targetAttr;
812 	else
813 		LinkToTargets(gn, special != SP_NOT);
814 }
815 
816 /*
817  * Given the name of a source in a dependency line, figure out if it is an
818  * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
819  * decide if there is some attribute which should be applied *to* the source
820  * because of some special target (such as .PHONY) and apply it if so.
821  * Otherwise, make the source a child of the targets.
822  */
823 static void
824 ApplyDependencySource(GNodeType targetAttr, const char *src,
825 		      ParseSpecial special)
826 {
827 	if (ApplyDependencySourceKeyword(src, special))
828 		return;
829 
830 	if (special == SP_MAIN)
831 		ApplyDependencySourceMain(src);
832 	else if (special == SP_ORDER)
833 		ApplyDependencySourceOrder(src);
834 	else
835 		ApplyDependencySourceOther(src, targetAttr, special);
836 }
837 
838 /*
839  * If we have yet to decide on a main target to make, in the absence of any
840  * user input, we want the first target on the first dependency line that is
841  * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
842  */
843 static void
844 MaybeUpdateMainTarget(void)
845 {
846 	GNodeListNode *ln;
847 
848 	if (mainNode != NULL)
849 		return;
850 
851 	for (ln = targets->first; ln != NULL; ln = ln->next) {
852 		GNode *gn = ln->datum;
853 		if (GNode_IsMainCandidate(gn)) {
854 			DEBUG1(MAKE, "Setting main node to \"%s\"\n", gn->name);
855 			mainNode = gn;
856 			return;
857 		}
858 	}
859 }
860 
861 static void
862 InvalidLineType(const char *line)
863 {
864 	if (strncmp(line, "<<<<<<", 6) == 0 ||
865 	    strncmp(line, "======", 6) == 0 ||
866 	    strncmp(line, ">>>>>>", 6) == 0)
867 		Parse_Error(PARSE_FATAL,
868 		    "Makefile appears to contain unresolved CVS/RCS/??? merge conflicts");
869 	else if (line[0] == '.') {
870 		const char *dirstart = line + 1;
871 		const char *dirend;
872 		cpp_skip_whitespace(&dirstart);
873 		dirend = dirstart;
874 		while (ch_isalnum(*dirend) || *dirend == '-')
875 			dirend++;
876 		Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
877 		    (int)(dirend - dirstart), dirstart);
878 	} else
879 		Parse_Error(PARSE_FATAL, "Invalid line type");
880 }
881 
882 static void
883 ParseDependencyTargetWord(char **pp, const char *lstart)
884 {
885 	const char *cp = *pp;
886 
887 	while (*cp != '\0') {
888 		if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' ||
889 		     *cp == '(') &&
890 		    !IsEscaped(lstart, cp))
891 			break;
892 
893 		if (*cp == '$') {
894 			/*
895 			 * Must be a dynamic source (would have been expanded
896 			 * otherwise).
897 			 *
898 			 * There should be no errors in this, as they would
899 			 * have been discovered in the initial Var_Subst and
900 			 * we wouldn't be here.
901 			 */
902 			FStr val;
903 
904 			(void)Var_Parse(&cp, SCOPE_CMDLINE,
905 			    VARE_PARSE_ONLY, &val);
906 			FStr_Done(&val);
907 		} else
908 			cp++;
909 	}
910 
911 	*pp += cp - *pp;
912 }
913 
914 /*
915  * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
916  *
917  * See the tests deptgt-*.mk.
918  */
919 static void
920 HandleDependencyTargetSpecial(const char *targetName,
921 			      ParseSpecial *inout_special,
922 			      SearchPathList **inout_paths)
923 {
924 	switch (*inout_special) {
925 	case SP_PATH:
926 		if (*inout_paths == NULL)
927 			*inout_paths = Lst_New();
928 		Lst_Append(*inout_paths, &dirSearchPath);
929 		break;
930 	case SP_MAIN:
931 		/*
932 		 * Allow targets from the command line to override the
933 		 * .MAIN node.
934 		 */
935 		if (!Lst_IsEmpty(&opts.create))
936 			*inout_special = SP_NOT;
937 		break;
938 	case SP_BEGIN:
939 	case SP_END:
940 	case SP_STALE:
941 	case SP_ERROR:
942 	case SP_INTERRUPT: {
943 		GNode *gn = Targ_GetNode(targetName);
944 		if (doing_depend)
945 			RememberLocation(gn);
946 		gn->type |= OP_NOTMAIN | OP_SPECIAL;
947 		Lst_Append(targets, gn);
948 		break;
949 	}
950 	case SP_DEFAULT: {
951 		/*
952 		 * Need to create a node to hang commands on, but we don't
953 		 * want it in the graph, nor do we want it to be the Main
954 		 * Target. We claim the node is a transformation rule to make
955 		 * life easier later, when we'll use Make_HandleUse to
956 		 * actually apply the .DEFAULT commands.
957 		 */
958 		GNode *gn = GNode_New(".DEFAULT");
959 		gn->type |= OP_NOTMAIN | OP_TRANSFORM;
960 		Lst_Append(targets, gn);
961 		defaultNode = gn;
962 		break;
963 	}
964 	case SP_DELETE_ON_ERROR:
965 		deleteOnError = true;
966 		break;
967 	case SP_NOTPARALLEL:
968 		opts.maxJobs = 1;
969 		break;
970 	case SP_SINGLESHELL:
971 		opts.compatMake = true;
972 		break;
973 	case SP_ORDER:
974 		order_pred = NULL;
975 		break;
976 	default:
977 		break;
978 	}
979 }
980 
981 static bool
982 HandleDependencyTargetPath(const char *suffixName,
983 			   SearchPathList **inout_paths)
984 {
985 	SearchPath *path;
986 
987 	path = Suff_GetPath(suffixName);
988 	if (path == NULL) {
989 		Parse_Error(PARSE_FATAL,
990 		    "Suffix '%s' not defined (yet)", suffixName);
991 		return false;
992 	}
993 
994 	if (*inout_paths == NULL)
995 		*inout_paths = Lst_New();
996 	Lst_Append(*inout_paths, path);
997 
998 	return true;
999 }
1000 
1001 /* See if it's a special target and if so set inout_special to match it. */
1002 static bool
1003 HandleDependencyTarget(const char *targetName,
1004 		       ParseSpecial *inout_special,
1005 		       GNodeType *inout_targetAttr,
1006 		       SearchPathList **inout_paths)
1007 {
1008 	int keywd;
1009 
1010 	if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
1011 		return true;
1012 
1013 	/*
1014 	 * See if the target is a special target that must have it
1015 	 * or its sources handled specially.
1016 	 */
1017 	keywd = FindKeyword(targetName);
1018 	if (keywd != -1) {
1019 		if (*inout_special == SP_PATH &&
1020 		    parseKeywords[keywd].special != SP_PATH) {
1021 			Parse_Error(PARSE_FATAL, "Mismatched special targets");
1022 			return false;
1023 		}
1024 
1025 		*inout_special = parseKeywords[keywd].special;
1026 		*inout_targetAttr = parseKeywords[keywd].targetAttr;
1027 
1028 		HandleDependencyTargetSpecial(targetName, inout_special,
1029 		    inout_paths);
1030 
1031 	} else if (strncmp(targetName, ".PATH", 5) == 0) {
1032 		*inout_special = SP_PATH;
1033 		if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
1034 			return false;
1035 	}
1036 	return true;
1037 }
1038 
1039 static void
1040 HandleDependencyTargetMundane(char *targetName)
1041 {
1042 	StringList targetNames = LST_INIT;
1043 
1044 	if (Dir_HasWildcards(targetName)) {
1045 		SearchPath *emptyPath = SearchPath_New();
1046 		SearchPath_Expand(emptyPath, targetName, &targetNames);
1047 		SearchPath_Free(emptyPath);
1048 	} else
1049 		Lst_Append(&targetNames, targetName);
1050 
1051 	while (!Lst_IsEmpty(&targetNames)) {
1052 		char *targName = Lst_Dequeue(&targetNames);
1053 		GNode *gn = Suff_IsTransform(targName)
1054 		    ? Suff_AddTransform(targName)
1055 		    : Targ_GetNode(targName);
1056 		if (doing_depend)
1057 			RememberLocation(gn);
1058 
1059 		Lst_Append(targets, gn);
1060 	}
1061 }
1062 
1063 static void
1064 SkipExtraTargets(char **pp, const char *lstart)
1065 {
1066 	bool warning = false;
1067 	const char *p = *pp;
1068 
1069 	while (*p != '\0') {
1070 		if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
1071 			break;
1072 		if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
1073 			warning = true;
1074 		p++;
1075 	}
1076 	if (warning)
1077 		Parse_Error(PARSE_WARNING, "Extra target ignored");
1078 
1079 	*pp += p - *pp;
1080 }
1081 
1082 static void
1083 CheckSpecialMundaneMixture(ParseSpecial special)
1084 {
1085 	switch (special) {
1086 	case SP_DEFAULT:
1087 	case SP_STALE:
1088 	case SP_BEGIN:
1089 	case SP_END:
1090 	case SP_ERROR:
1091 	case SP_INTERRUPT:
1092 		/*
1093 		 * These create nodes on which to hang commands, so targets
1094 		 * shouldn't be empty.
1095 		 */
1096 	case SP_NOT:
1097 		/*
1098 		 * Nothing special here -- targets can be empty if it wants.
1099 		 */
1100 		break;
1101 	default:
1102 		Parse_Error(PARSE_WARNING,
1103 		    "Special and mundane targets don't mix. "
1104 		    "Mundane ones ignored");
1105 		break;
1106 	}
1107 }
1108 
1109 /*
1110  * In a dependency line like 'targets: sources' or 'targets! sources', parse
1111  * the operator ':', '::' or '!' from between the targets and the sources.
1112  */
1113 static GNodeType
1114 ParseDependencyOp(char **pp)
1115 {
1116 	if (**pp == '!')
1117 		return (*pp)++, OP_FORCE;
1118 	if ((*pp)[1] == ':')
1119 		return *pp += 2, OP_DOUBLEDEP;
1120 	else
1121 		return (*pp)++, OP_DEPENDS;
1122 }
1123 
1124 static void
1125 ClearPaths(SearchPathList *paths)
1126 {
1127 	if (paths != NULL) {
1128 		SearchPathListNode *ln;
1129 		for (ln = paths->first; ln != NULL; ln = ln->next)
1130 			SearchPath_Clear(ln->datum);
1131 	}
1132 
1133 	Dir_SetPATH();
1134 }
1135 
1136 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
1137 static void
1138 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
1139 {
1140 	switch (special) {
1141 	case SP_SUFFIXES:
1142 		Suff_ClearSuffixes();
1143 		break;
1144 	case SP_PRECIOUS:
1145 		allPrecious = true;
1146 		break;
1147 	case SP_IGNORE:
1148 		opts.ignoreErrors = true;
1149 		break;
1150 	case SP_SILENT:
1151 		opts.silent = true;
1152 		break;
1153 	case SP_PATH:
1154 		ClearPaths(paths);
1155 		break;
1156 #ifdef POSIX
1157 	case SP_POSIX:
1158 		Global_Set("%POSIX", "1003.2");
1159 		break;
1160 #endif
1161 	default:
1162 		break;
1163 	}
1164 }
1165 
1166 static void
1167 AddToPaths(const char *dir, SearchPathList *paths)
1168 {
1169 	if (paths != NULL) {
1170 		SearchPathListNode *ln;
1171 		for (ln = paths->first; ln != NULL; ln = ln->next)
1172 			(void)SearchPath_Add(ln->datum, dir);
1173 	}
1174 }
1175 
1176 /*
1177  * If the target was one that doesn't take files as its sources but takes
1178  * something like suffixes, we take each space-separated word on the line as
1179  * a something and deal with it accordingly.
1180  */
1181 static void
1182 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
1183 			     SearchPathList *paths)
1184 {
1185 	switch (special) {
1186 	case SP_SUFFIXES:
1187 		Suff_AddSuffix(word);
1188 		break;
1189 	case SP_PATH:
1190 		AddToPaths(word, paths);
1191 		break;
1192 	case SP_INCLUDES:
1193 		Suff_AddInclude(word);
1194 		break;
1195 	case SP_LIBS:
1196 		Suff_AddLib(word);
1197 		break;
1198 	case SP_NULL:
1199 		Suff_SetNull(word);
1200 		break;
1201 	case SP_OBJDIR:
1202 		Main_SetObjdir(false, "%s", word);
1203 		break;
1204 	default:
1205 		break;
1206 	}
1207 }
1208 
1209 static bool
1210 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
1211 		      GNodeType *inout_targetAttr,
1212 		      SearchPathList **inout_paths)
1213 {
1214 	char savec = *nameEnd;
1215 	*nameEnd = '\0';
1216 
1217 	if (!HandleDependencyTarget(name, inout_special,
1218 	    inout_targetAttr, inout_paths))
1219 		return false;
1220 
1221 	if (*inout_special == SP_NOT && *name != '\0')
1222 		HandleDependencyTargetMundane(name);
1223 	else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
1224 		Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
1225 
1226 	*nameEnd = savec;
1227 	return true;
1228 }
1229 
1230 static bool
1231 ParseDependencyTargets(char **inout_cp,
1232 		       const char *lstart,
1233 		       ParseSpecial *inout_special,
1234 		       GNodeType *inout_targetAttr,
1235 		       SearchPathList **inout_paths)
1236 {
1237 	char *cp = *inout_cp;
1238 
1239 	for (;;) {
1240 		char *tgt = cp;
1241 
1242 		ParseDependencyTargetWord(&cp, lstart);
1243 
1244 		/*
1245 		 * If the word is followed by a left parenthesis, it's the
1246 		 * name of one or more files inside an archive.
1247 		 */
1248 		if (!IsEscaped(lstart, cp) && *cp == '(') {
1249 			cp = tgt;
1250 			if (!Arch_ParseArchive(&cp, targets, SCOPE_CMDLINE)) {
1251 				Parse_Error(PARSE_FATAL,
1252 				    "Error in archive specification: \"%s\"",
1253 				    tgt);
1254 				return false;
1255 			}
1256 			continue;
1257 		}
1258 
1259 		if (*cp == '\0') {
1260 			InvalidLineType(lstart);
1261 			return false;
1262 		}
1263 
1264 		if (!ApplyDependencyTarget(tgt, cp, inout_special,
1265 		    inout_targetAttr, inout_paths))
1266 			return false;
1267 
1268 		if (*inout_special != SP_NOT && *inout_special != SP_PATH)
1269 			SkipExtraTargets(&cp, lstart);
1270 		else
1271 			pp_skip_whitespace(&cp);
1272 
1273 		if (*cp == '\0')
1274 			break;
1275 		if ((*cp == '!' || *cp == ':') && !IsEscaped(lstart, cp))
1276 			break;
1277 	}
1278 
1279 	*inout_cp = cp;
1280 	return true;
1281 }
1282 
1283 static void
1284 ParseDependencySourcesSpecial(char *start,
1285 			      ParseSpecial special, SearchPathList *paths)
1286 {
1287 	char savec;
1288 
1289 	while (*start != '\0') {
1290 		char *end = start;
1291 		while (*end != '\0' && !ch_isspace(*end))
1292 			end++;
1293 		savec = *end;
1294 		*end = '\0';
1295 		ParseDependencySourceSpecial(special, start, paths);
1296 		*end = savec;
1297 		if (savec != '\0')
1298 			end++;
1299 		pp_skip_whitespace(&end);
1300 		start = end;
1301 	}
1302 }
1303 
1304 static void
1305 LinkVarToTargets(VarAssign *var)
1306 {
1307 	GNodeListNode *ln;
1308 
1309 	for (ln = targets->first; ln != NULL; ln = ln->next)
1310 		Parse_Var(var, ln->datum);
1311 }
1312 
1313 static bool
1314 ParseDependencySourcesMundane(char *start,
1315 			      ParseSpecial special, GNodeType targetAttr)
1316 {
1317 	while (*start != '\0') {
1318 		char *end = start;
1319 		VarAssign var;
1320 
1321 		/*
1322 		 * Check for local variable assignment,
1323 		 * rest of the line is the value.
1324 		 */
1325 		if (Parse_IsVar(start, &var)) {
1326 			/*
1327 			 * Check if this makefile has disabled
1328 			 * setting local variables.
1329 			 */
1330 			bool target_vars = GetBooleanExpr(
1331 			    "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
1332 
1333 			if (target_vars)
1334 				LinkVarToTargets(&var);
1335 			free(var.varname);
1336 			if (target_vars)
1337 				return true;
1338 		}
1339 
1340 		/*
1341 		 * The targets take real sources, so we must beware of archive
1342 		 * specifications (i.e. things with left parentheses in them)
1343 		 * and handle them accordingly.
1344 		 */
1345 		for (; *end != '\0' && !ch_isspace(*end); end++) {
1346 			if (*end == '(' && end > start && end[-1] != '$') {
1347 				/*
1348 				 * Only stop for a left parenthesis if it
1349 				 * isn't at the start of a word (that'll be
1350 				 * for variable changes later) and isn't
1351 				 * preceded by a dollar sign (a dynamic
1352 				 * source).
1353 				 */
1354 				break;
1355 			}
1356 		}
1357 
1358 		if (*end == '(') {
1359 			GNodeList sources = LST_INIT;
1360 			if (!Arch_ParseArchive(&start, &sources,
1361 			    SCOPE_CMDLINE)) {
1362 				Parse_Error(PARSE_FATAL,
1363 				    "Error in source archive spec \"%s\"",
1364 				    start);
1365 				return false;
1366 			}
1367 
1368 			while (!Lst_IsEmpty(&sources)) {
1369 				GNode *gn = Lst_Dequeue(&sources);
1370 				ApplyDependencySource(targetAttr, gn->name,
1371 				    special);
1372 			}
1373 			Lst_Done(&sources);
1374 			end = start;
1375 		} else {
1376 			if (*end != '\0') {
1377 				*end = '\0';
1378 				end++;
1379 			}
1380 
1381 			ApplyDependencySource(targetAttr, start, special);
1382 		}
1383 		pp_skip_whitespace(&end);
1384 		start = end;
1385 	}
1386 	return true;
1387 }
1388 
1389 /*
1390  * From a dependency line like 'targets: sources', parse the sources.
1391  *
1392  * See the tests depsrc-*.mk.
1393  */
1394 static void
1395 ParseDependencySources(char *p, GNodeType targetAttr,
1396 		       ParseSpecial special, SearchPathList **inout_paths)
1397 {
1398 	if (*p == '\0') {
1399 		HandleDependencySourcesEmpty(special, *inout_paths);
1400 	} else if (special == SP_MFLAGS) {
1401 		Main_ParseArgLine(p);
1402 		return;
1403 	} else if (special == SP_SHELL) {
1404 		if (!Job_ParseShell(p)) {
1405 			Parse_Error(PARSE_FATAL,
1406 			    "improper shell specification");
1407 			return;
1408 		}
1409 		return;
1410 	} else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
1411 		   special == SP_DELETE_ON_ERROR) {
1412 		return;
1413 	}
1414 
1415 	/* Now go for the sources. */
1416 	if (special == SP_SUFFIXES || special == SP_PATH ||
1417 	    special == SP_INCLUDES || special == SP_LIBS ||
1418 	    special == SP_NULL || special == SP_OBJDIR) {
1419 		ParseDependencySourcesSpecial(p, special, *inout_paths);
1420 		if (*inout_paths != NULL) {
1421 			Lst_Free(*inout_paths);
1422 			*inout_paths = NULL;
1423 		}
1424 		if (special == SP_PATH)
1425 			Dir_SetPATH();
1426 	} else {
1427 		assert(*inout_paths == NULL);
1428 		if (!ParseDependencySourcesMundane(p, special, targetAttr))
1429 			return;
1430 	}
1431 
1432 	MaybeUpdateMainTarget();
1433 }
1434 
1435 /*
1436  * Parse a dependency line consisting of targets, followed by a dependency
1437  * operator, optionally followed by sources.
1438  *
1439  * The nodes of the sources are linked as children to the nodes of the
1440  * targets. Nodes are created as necessary.
1441  *
1442  * The operator is applied to each node in the global 'targets' list,
1443  * which is where the nodes found for the targets are kept.
1444  *
1445  * The sources are parsed in much the same way as the targets, except
1446  * that they are expanded using the wildcarding scheme of the C-Shell,
1447  * and a target is created for each expanded word. Each of the resulting
1448  * nodes is then linked to each of the targets as one of its children.
1449  *
1450  * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1451  * specially, see ParseSpecial.
1452  *
1453  * Transformation rules such as '.c.o' are also handled here, see
1454  * Suff_AddTransform.
1455  *
1456  * Upon return, the value of the line is unspecified.
1457  */
1458 static void
1459 ParseDependency(char *line)
1460 {
1461 	char *p;
1462 	SearchPathList *paths;	/* search paths to alter when parsing a list
1463 				 * of .PATH targets */
1464 	GNodeType targetAttr;	/* from special sources */
1465 	ParseSpecial special;	/* in special targets, the children are
1466 				 * linked as children of the parent but not
1467 				 * vice versa */
1468 
1469 	DEBUG1(PARSE, "ParseDependency(%s)\n", line);
1470 	p = line;
1471 	paths = NULL;
1472 	targetAttr = OP_NONE;
1473 	special = SP_NOT;
1474 
1475 	if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths))
1476 		goto out;
1477 
1478 	if (!Lst_IsEmpty(targets))
1479 		CheckSpecialMundaneMixture(special);
1480 
1481 	ApplyDependencyOperator(ParseDependencyOp(&p));
1482 
1483 	pp_skip_whitespace(&p);
1484 
1485 	ParseDependencySources(p, targetAttr, special, &paths);
1486 
1487 out:
1488 	if (paths != NULL)
1489 		Lst_Free(paths);
1490 }
1491 
1492 /*
1493  * Determine the assignment operator and adjust the end of the variable
1494  * name accordingly.
1495  */
1496 static VarAssign
1497 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
1498 		  const char *value)
1499 {
1500 	VarAssignOp type;
1501 	VarAssign va;
1502 
1503 	if (op > name && op[-1] == '+') {
1504 		op--;
1505 		type = VAR_APPEND;
1506 
1507 	} else if (op > name && op[-1] == '?') {
1508 		op--;
1509 		type = VAR_DEFAULT;
1510 
1511 	} else if (op > name && op[-1] == ':') {
1512 		op--;
1513 		type = VAR_SUBST;
1514 
1515 	} else if (op > name && op[-1] == '!') {
1516 		op--;
1517 		type = VAR_SHELL;
1518 
1519 	} else {
1520 		type = VAR_NORMAL;
1521 #ifdef SUNSHCMD
1522 		while (op > name && ch_isspace(op[-1]))
1523 			op--;
1524 
1525 		if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
1526 			op -= 3;
1527 			type = VAR_SHELL;
1528 		}
1529 #endif
1530 	}
1531 
1532 	va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
1533 	va.op = type;
1534 	va.value = value;
1535 	return va;
1536 }
1537 
1538 /*
1539  * Parse a variable assignment, consisting of a single-word variable name,
1540  * optional whitespace, an assignment operator, optional whitespace and the
1541  * variable value.
1542  *
1543  * Note: There is a lexical ambiguity with assignment modifier characters
1544  * in variable names. This routine interprets the character before the =
1545  * as a modifier. Therefore, an assignment like
1546  *	C++=/usr/bin/CC
1547  * is interpreted as "C+ +=" instead of "C++ =".
1548  *
1549  * Used for both lines in a file and command line arguments.
1550  */
1551 static bool
1552 Parse_IsVar(const char *p, VarAssign *out_var)
1553 {
1554 	const char *nameStart, *nameEnd, *firstSpace, *eq;
1555 	int level = 0;
1556 
1557 	cpp_skip_hspace(&p);	/* Skip to variable name */
1558 
1559 	/*
1560 	 * During parsing, the '+' of the '+=' operator is initially parsed
1561 	 * as part of the variable name.  It is later corrected, as is the
1562 	 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
1563 	 * determines the actual end of the variable name.
1564 	 */
1565 
1566 	nameStart = p;
1567 	firstSpace = NULL;
1568 
1569 	/*
1570 	 * Scan for one of the assignment operators outside a variable
1571 	 * expansion.
1572 	 */
1573 	while (*p != '\0') {
1574 		char ch = *p++;
1575 		if (ch == '(' || ch == '{') {
1576 			level++;
1577 			continue;
1578 		}
1579 		if (ch == ')' || ch == '}') {
1580 			level--;
1581 			continue;
1582 		}
1583 
1584 		if (level != 0)
1585 			continue;
1586 
1587 		if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
1588 			firstSpace = p - 1;
1589 		while (ch == ' ' || ch == '\t')
1590 			ch = *p++;
1591 
1592 		if (ch == '\0')
1593 			return false;
1594 #ifdef SUNSHCMD
1595 		if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1596 			p += 2;
1597 			continue;
1598 		}
1599 #endif
1600 		if (ch == '=')
1601 			eq = p - 1;
1602 		else if (*p == '=' &&
1603 		    (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
1604 			eq = p;
1605 		else if (firstSpace != NULL)
1606 			return false;
1607 		else
1608 			continue;
1609 
1610 		nameEnd = firstSpace != NULL ? firstSpace : eq;
1611 		p = eq + 1;
1612 		cpp_skip_whitespace(&p);
1613 		*out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
1614 		return true;
1615 	}
1616 
1617 	return false;
1618 }
1619 
1620 /*
1621  * Check for syntax errors such as unclosed expressions or unknown modifiers.
1622  */
1623 static void
1624 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
1625 {
1626 	if (opts.strict) {
1627 		if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1628 			char *expandedValue;
1629 
1630 			(void)Var_Subst(uvalue, scope, VARE_PARSE_ONLY,
1631 			    &expandedValue);
1632 			/* TODO: handle errors */
1633 			free(expandedValue);
1634 		}
1635 	}
1636 }
1637 
1638 /* Perform a variable assignment that uses the operator ':='. */
1639 static void
1640 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1641 		    FStr *out_avalue)
1642 {
1643 	char *evalue;
1644 
1645 	/*
1646 	 * make sure that we set the variable the first time to nothing
1647 	 * so that it gets substituted.
1648 	 *
1649 	 * TODO: Add a test that demonstrates why this code is needed,
1650 	 *  apart from making the debug log longer.
1651 	 *
1652 	 * XXX: The variable name is expanded up to 3 times.
1653 	 */
1654 	if (!Var_ExistsExpand(scope, name))
1655 		Var_SetExpand(scope, name, "");
1656 
1657 	(void)Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF, &evalue);
1658 	/* TODO: handle errors */
1659 
1660 	Var_SetExpand(scope, name, evalue);
1661 
1662 	*out_avalue = FStr_InitOwn(evalue);
1663 }
1664 
1665 /* Perform a variable assignment that uses the operator '!='. */
1666 static void
1667 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1668 		    FStr *out_avalue)
1669 {
1670 	FStr cmd;
1671 	char *output, *error;
1672 
1673 	cmd = FStr_InitRefer(uvalue);
1674 	Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
1675 
1676 	output = Cmd_Exec(cmd.str, &error);
1677 	Var_SetExpand(scope, name, output);
1678 	*out_avalue = FStr_InitOwn(output);
1679 	if (error != NULL) {
1680 		Parse_Error(PARSE_WARNING, "%s", error);
1681 		free(error);
1682 	}
1683 
1684 	FStr_Done(&cmd);
1685 }
1686 
1687 /*
1688  * Perform a variable assignment.
1689  *
1690  * The actual value of the variable is returned in *out_true_avalue.
1691  * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1692  * value.
1693  *
1694  * Return whether the assignment was actually performed, which is usually
1695  * the case.  It is only skipped if the operator is '?=' and the variable
1696  * already exists.
1697  */
1698 static bool
1699 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1700 	       GNode *scope, FStr *out_true_avalue)
1701 {
1702 	FStr avalue = FStr_InitRefer(uvalue);
1703 
1704 	if (op == VAR_APPEND)
1705 		Var_AppendExpand(scope, name, uvalue);
1706 	else if (op == VAR_SUBST)
1707 		VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1708 	else if (op == VAR_SHELL)
1709 		VarAssign_EvalShell(name, uvalue, scope, &avalue);
1710 	else {
1711 		/* XXX: The variable name is expanded up to 2 times. */
1712 		if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1713 			return false;
1714 
1715 		/* Normal assignment -- just do it. */
1716 		Var_SetExpand(scope, name, uvalue);
1717 	}
1718 
1719 	*out_true_avalue = avalue;
1720 	return true;
1721 }
1722 
1723 static void
1724 VarAssignSpecial(const char *name, const char *avalue)
1725 {
1726 	if (strcmp(name, MAKEOVERRIDES) == 0)
1727 		Main_ExportMAKEFLAGS(false);	/* re-export MAKEFLAGS */
1728 	else if (strcmp(name, ".CURDIR") == 0) {
1729 		/*
1730 		 * Someone is being (too?) clever...
1731 		 * Let's pretend they know what they are doing and
1732 		 * re-initialize the 'cur' CachedDir.
1733 		 */
1734 		Dir_InitCur(avalue);
1735 		Dir_SetPATH();
1736 	} else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
1737 		Job_SetPrefix();
1738 	else if (strcmp(name, MAKE_EXPORTED) == 0)
1739 		Var_ExportVars(avalue);
1740 }
1741 
1742 /* Perform the variable assignment in the given scope. */
1743 static void
1744 Parse_Var(VarAssign *var, GNode *scope)
1745 {
1746 	FStr avalue;		/* actual value (maybe expanded) */
1747 
1748 	VarCheckSyntax(var->op, var->value, scope);
1749 	if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1750 		VarAssignSpecial(var->varname, avalue.str);
1751 		FStr_Done(&avalue);
1752 	}
1753 }
1754 
1755 
1756 /*
1757  * See if the command possibly calls a sub-make by using the variable
1758  * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1759  */
1760 static bool
1761 MaybeSubMake(const char *cmd)
1762 {
1763 	const char *start;
1764 
1765 	for (start = cmd; *start != '\0'; start++) {
1766 		const char *p = start;
1767 		char endc;
1768 
1769 		/* XXX: What if progname != "make"? */
1770 		if (strncmp(p, "make", 4) == 0)
1771 			if (start == cmd || !ch_isalnum(p[-1]))
1772 				if (!ch_isalnum(p[4]))
1773 					return true;
1774 
1775 		if (*p != '$')
1776 			continue;
1777 		p++;
1778 
1779 		if (*p == '{')
1780 			endc = '}';
1781 		else if (*p == '(')
1782 			endc = ')';
1783 		else
1784 			continue;
1785 		p++;
1786 
1787 		if (*p == '.')	/* Accept either ${.MAKE} or ${MAKE}. */
1788 			p++;
1789 
1790 		if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
1791 			return true;
1792 	}
1793 	return false;
1794 }
1795 
1796 /*
1797  * Append the command to the target node.
1798  *
1799  * The node may be marked as a submake node if the command is determined to
1800  * be that.
1801  */
1802 static void
1803 GNode_AddCommand(GNode *gn, char *cmd)
1804 {
1805 	/* Add to last (ie current) cohort for :: targets */
1806 	if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1807 		gn = gn->cohorts.last->datum;
1808 
1809 	/* if target already supplied, ignore commands */
1810 	if (!(gn->type & OP_HAS_COMMANDS)) {
1811 		Lst_Append(&gn->commands, cmd);
1812 		if (MaybeSubMake(cmd))
1813 			gn->type |= OP_SUBMAKE;
1814 		RememberLocation(gn);
1815 	} else {
1816 #if 0
1817 		/* XXX: We cannot do this until we fix the tree */
1818 		Lst_Append(&gn->commands, cmd);
1819 		Parse_Error(PARSE_WARNING,
1820 		    "overriding commands for target \"%s\"; "
1821 		    "previous commands defined at %s: %u ignored",
1822 		    gn->name, gn->fname, gn->lineno);
1823 #else
1824 		Parse_Error(PARSE_WARNING,
1825 		    "duplicate script for target \"%s\" ignored",
1826 		    gn->name);
1827 		ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1828 		    "using previous script for \"%s\" defined here",
1829 		    gn->name);
1830 #endif
1831 	}
1832 }
1833 
1834 /*
1835  * Add a directory to the path searched for included makefiles bracketed
1836  * by double-quotes.
1837  */
1838 void
1839 Parse_AddIncludeDir(const char *dir)
1840 {
1841 	(void)SearchPath_Add(parseIncPath, dir);
1842 }
1843 
1844 /*
1845  * Handle one of the .[-ds]include directives by remembering the current file
1846  * and pushing the included file on the stack.  After the included file has
1847  * finished, parsing continues with the including file; see Parse_PushInput
1848  * and ParseEOF.
1849  *
1850  * System includes are looked up in sysIncPath, any other includes are looked
1851  * up in the parsedir and then in the directories specified by the -I command
1852  * line options.
1853  */
1854 static void
1855 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
1856 {
1857 	Buffer buf;
1858 	char *fullname;		/* full pathname of file */
1859 	char *newName;
1860 	char *slash, *incdir;
1861 	int fd;
1862 	int i;
1863 
1864 	fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1865 
1866 	if (fullname == NULL && !isSystem) {
1867 		/*
1868 		 * Include files contained in double-quotes are first searched
1869 		 * relative to the including file's location. We don't want to
1870 		 * cd there, of course, so we just tack on the old file's
1871 		 * leading path components and call Dir_FindFile to see if
1872 		 * we can locate the file.
1873 		 */
1874 
1875 		incdir = bmake_strdup(CurFile()->name.str);
1876 		slash = strrchr(incdir, '/');
1877 		if (slash != NULL) {
1878 			*slash = '\0';
1879 			/*
1880 			 * Now do lexical processing of leading "../" on the
1881 			 * filename.
1882 			 */
1883 			for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1884 				slash = strrchr(incdir + 1, '/');
1885 				if (slash == NULL || strcmp(slash, "/..") == 0)
1886 					break;
1887 				*slash = '\0';
1888 			}
1889 			newName = str_concat3(incdir, "/", file + i);
1890 			fullname = Dir_FindFile(newName, parseIncPath);
1891 			if (fullname == NULL)
1892 				fullname = Dir_FindFile(newName,
1893 				    &dirSearchPath);
1894 			free(newName);
1895 		}
1896 		free(incdir);
1897 
1898 		if (fullname == NULL) {
1899 			/*
1900 			 * Makefile wasn't found in same directory as included
1901 			 * makefile.
1902 			 *
1903 			 * Search for it first on the -I search path, then on
1904 			 * the .PATH search path, if not found in a -I
1905 			 * directory. If we have a suffix-specific path, we
1906 			 * should use that.
1907 			 */
1908 			const char *suff;
1909 			SearchPath *suffPath = NULL;
1910 
1911 			if ((suff = strrchr(file, '.')) != NULL) {
1912 				suffPath = Suff_GetPath(suff);
1913 				if (suffPath != NULL)
1914 					fullname = Dir_FindFile(file, suffPath);
1915 			}
1916 			if (fullname == NULL) {
1917 				fullname = Dir_FindFile(file, parseIncPath);
1918 				if (fullname == NULL)
1919 					fullname = Dir_FindFile(file,
1920 					    &dirSearchPath);
1921 			}
1922 		}
1923 	}
1924 
1925 	/* Looking for a system file or file still not found */
1926 	if (fullname == NULL) {
1927 		/*
1928 		 * Look for it on the system path
1929 		 */
1930 		SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
1931 		    ? defSysIncPath : sysIncPath;
1932 		fullname = Dir_FindFile(file, path);
1933 	}
1934 
1935 	if (fullname == NULL) {
1936 		if (!silent)
1937 			Parse_Error(PARSE_FATAL, "Could not find %s", file);
1938 		return;
1939 	}
1940 
1941 	/* Actually open the file... */
1942 	fd = open(fullname, O_RDONLY);
1943 	if (fd == -1) {
1944 		if (!silent)
1945 			Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1946 		free(fullname);
1947 		return;
1948 	}
1949 
1950 	buf = loadfile(fullname, fd);
1951 	(void)close(fd);
1952 
1953 	Parse_PushInput(fullname, 1, 0, buf, NULL);
1954 	if (depinc)
1955 		doing_depend = depinc;	/* only turn it on */
1956 	free(fullname);
1957 }
1958 
1959 /*
1960  * Parse a directive like '.include' or '.-include'.
1961  *
1962  * .include "user-makefile.mk"
1963  * .include <system-makefile.mk>
1964  */
1965 static void
1966 ParseInclude(char *directive)
1967 {
1968 	char endc;		/* '>' or '"' */
1969 	char *p;
1970 	bool silent = directive[0] != 'i';
1971 	FStr file;
1972 
1973 	p = directive + (silent ? 8 : 7);
1974 	pp_skip_hspace(&p);
1975 
1976 	if (*p != '"' && *p != '<') {
1977 		Parse_Error(PARSE_FATAL,
1978 		    ".include filename must be delimited by '\"' or '<'");
1979 		return;
1980 	}
1981 
1982 	if (*p++ == '<')
1983 		endc = '>';
1984 	else
1985 		endc = '"';
1986 	file = FStr_InitRefer(p);
1987 
1988 	/* Skip to matching delimiter */
1989 	while (*p != '\0' && *p != endc)
1990 		p++;
1991 
1992 	if (*p != endc) {
1993 		Parse_Error(PARSE_FATAL,
1994 		    "Unclosed .include filename. '%c' expected", endc);
1995 		return;
1996 	}
1997 
1998 	*p = '\0';
1999 
2000 	Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
2001 	IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2002 	FStr_Done(&file);
2003 }
2004 
2005 /*
2006  * Split filename into dirname + basename, then assign these to the
2007  * given variables.
2008  */
2009 static void
2010 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2011 {
2012 	const char *slash, *basename;
2013 	FStr dirname;
2014 
2015 	slash = strrchr(filename, '/');
2016 	if (slash == NULL) {
2017 		dirname = FStr_InitRefer(curdir);
2018 		basename = filename;
2019 	} else {
2020 		dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2021 		basename = slash + 1;
2022 	}
2023 
2024 	Global_Set(dirvar, dirname.str);
2025 	Global_Set(filevar, basename);
2026 
2027 	DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2028 	    dirvar, dirname.str, filevar, basename);
2029 	FStr_Done(&dirname);
2030 }
2031 
2032 /*
2033  * Return the immediately including file.
2034  *
2035  * This is made complicated since the .for loop is implemented as a special
2036  * kind of .include; see For_Run.
2037  */
2038 static const char *
2039 GetActuallyIncludingFile(void)
2040 {
2041 	size_t i;
2042 	const IncludedFile *incs = GetInclude(0);
2043 
2044 	for (i = includes.len; i >= 2; i--)
2045 		if (incs[i - 1].forLoop == NULL)
2046 			return incs[i - 2].name.str;
2047 	return NULL;
2048 }
2049 
2050 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2051 static void
2052 SetParseFile(const char *filename)
2053 {
2054 	const char *including;
2055 
2056 	SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2057 
2058 	including = GetActuallyIncludingFile();
2059 	if (including != NULL) {
2060 		SetFilenameVars(including,
2061 		    ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2062 	} else {
2063 		Global_Delete(".INCLUDEDFROMDIR");
2064 		Global_Delete(".INCLUDEDFROMFILE");
2065 	}
2066 }
2067 
2068 static bool
2069 StrContainsWord(const char *str, const char *word)
2070 {
2071 	size_t strLen = strlen(str);
2072 	size_t wordLen = strlen(word);
2073 	const char *p;
2074 
2075 	if (strLen < wordLen)
2076 		return false;
2077 
2078 	for (p = str; p != NULL; p = strchr(p, ' ')) {
2079 		if (*p == ' ')
2080 			p++;
2081 		if (p > str + strLen - wordLen)
2082 			return false;
2083 
2084 		if (memcmp(p, word, wordLen) == 0 &&
2085 		    (p[wordLen] == '\0' || p[wordLen] == ' '))
2086 			return true;
2087 	}
2088 	return false;
2089 }
2090 
2091 /*
2092  * XXX: Searching through a set of words with this linear search is
2093  * inefficient for variables that contain thousands of words.
2094  *
2095  * XXX: The paths in this list don't seem to be normalized in any way.
2096  */
2097 static bool
2098 VarContainsWord(const char *varname, const char *word)
2099 {
2100 	FStr val = Var_Value(SCOPE_GLOBAL, varname);
2101 	bool found = val.str != NULL && StrContainsWord(val.str, word);
2102 	FStr_Done(&val);
2103 	return found;
2104 }
2105 
2106 /*
2107  * Track the makefiles we read - so makefiles can set dependencies on them.
2108  * Avoid adding anything more than once.
2109  *
2110  * Time complexity: O(n) per call, in total O(n^2), where n is the number
2111  * of makefiles that have been loaded.
2112  */
2113 static void
2114 TrackInput(const char *name)
2115 {
2116 	if (!VarContainsWord(MAKE_MAKEFILES, name))
2117 		Global_Append(MAKE_MAKEFILES, name);
2118 }
2119 
2120 
2121 /* Parse from the given buffer, later return to the current file. */
2122 void
2123 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2124 		Buffer buf, struct ForLoop *forLoop)
2125 {
2126 	IncludedFile *curFile;
2127 
2128 	if (forLoop != NULL)
2129 		name = CurFile()->name.str;
2130 	else
2131 		TrackInput(name);
2132 
2133 	DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
2134 	    forLoop != NULL ? ".for loop in": "file", name, lineno);
2135 
2136 	curFile = Vector_Push(&includes);
2137 	curFile->name = FStr_InitOwn(bmake_strdup(name));
2138 	curFile->lineno = lineno;
2139 	curFile->readLines = readLines;
2140 	curFile->forHeadLineno = lineno;
2141 	curFile->forBodyReadLines = readLines;
2142 	curFile->buf = buf;
2143 	curFile->depending = doing_depend;	/* restore this on EOF */
2144 	curFile->forLoop = forLoop;
2145 
2146 	if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2147 		abort();	/* see For_Run */
2148 
2149 	curFile->buf_ptr = curFile->buf.data;
2150 	curFile->buf_end = curFile->buf.data + curFile->buf.len;
2151 	curFile->cond_depth = Cond_save_depth();
2152 	SetParseFile(name);
2153 }
2154 
2155 /* Check if the directive is an include directive. */
2156 static bool
2157 IsInclude(const char *dir, bool sysv)
2158 {
2159 	if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2160 		dir++;
2161 
2162 	if (strncmp(dir, "include", 7) != 0)
2163 		return false;
2164 
2165 	/* Space is not mandatory for BSD .include */
2166 	return !sysv || ch_isspace(dir[7]);
2167 }
2168 
2169 
2170 #ifdef SYSVINCLUDE
2171 /* Check if the line is a SYSV include directive. */
2172 static bool
2173 IsSysVInclude(const char *line)
2174 {
2175 	const char *p;
2176 
2177 	if (!IsInclude(line, true))
2178 		return false;
2179 
2180 	/* Avoid interpreting a dependency line as an include */
2181 	for (p = line; (p = strchr(p, ':')) != NULL;) {
2182 
2183 		/* end of line -> it's a dependency */
2184 		if (*++p == '\0')
2185 			return false;
2186 
2187 		/* '::' operator or ': ' -> it's a dependency */
2188 		if (*p == ':' || ch_isspace(*p))
2189 			return false;
2190 	}
2191 	return true;
2192 }
2193 
2194 /* Push to another file.  The line points to the word "include". */
2195 static void
2196 ParseTraditionalInclude(char *line)
2197 {
2198 	char *cp;		/* current position in file spec */
2199 	bool done = false;
2200 	bool silent = line[0] != 'i';
2201 	char *file = line + (silent ? 8 : 7);
2202 	char *all_files;
2203 
2204 	DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2205 
2206 	pp_skip_whitespace(&file);
2207 
2208 	(void)Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES, &all_files);
2209 	/* TODO: handle errors */
2210 
2211 	for (file = all_files; !done; file = cp + 1) {
2212 		/* Skip to end of line or next whitespace */
2213 		for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
2214 			continue;
2215 
2216 		if (*cp != '\0')
2217 			*cp = '\0';
2218 		else
2219 			done = true;
2220 
2221 		IncludeFile(file, false, false, silent);
2222 	}
2223 
2224 	free(all_files);
2225 }
2226 #endif
2227 
2228 #ifdef GMAKEEXPORT
2229 /* Parse "export <variable>=<value>", and actually export it. */
2230 static void
2231 ParseGmakeExport(char *line)
2232 {
2233 	char *variable = line + 6;
2234 	char *value;
2235 
2236 	DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2237 
2238 	pp_skip_whitespace(&variable);
2239 
2240 	for (value = variable; *value != '\0' && *value != '='; value++)
2241 		continue;
2242 
2243 	if (*value != '=') {
2244 		Parse_Error(PARSE_FATAL,
2245 		    "Variable/Value missing from \"export\"");
2246 		return;
2247 	}
2248 	*value++ = '\0';	/* terminate variable */
2249 
2250 	/*
2251 	 * Expand the value before putting it in the environment.
2252 	 */
2253 	(void)Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES, &value);
2254 	/* TODO: handle errors */
2255 
2256 	setenv(variable, value, 1);
2257 	free(value);
2258 }
2259 #endif
2260 
2261 /*
2262  * Called when EOF is reached in the current file. If we were reading an
2263  * include file or a .for loop, the includes stack is popped and things set
2264  * up to go back to reading the previous file at the previous location.
2265  *
2266  * Results:
2267  *	true to continue parsing, i.e. it had only reached the end of an
2268  *	included file, false if the main file has been parsed completely.
2269  */
2270 static bool
2271 ParseEOF(void)
2272 {
2273 	IncludedFile *curFile = CurFile();
2274 
2275 	doing_depend = curFile->depending;
2276 	if (curFile->forLoop != NULL &&
2277 	    For_NextIteration(curFile->forLoop, &curFile->buf)) {
2278 		curFile->buf_ptr = curFile->buf.data;
2279 		curFile->buf_end = curFile->buf.data + curFile->buf.len;
2280 		curFile->readLines = curFile->forBodyReadLines;
2281 		return true;
2282 	}
2283 
2284 	/*
2285 	 * Ensure the makefile (or .for loop) didn't have mismatched
2286 	 * conditionals.
2287 	 */
2288 	Cond_restore_depth(curFile->cond_depth);
2289 
2290 	FStr_Done(&curFile->name);
2291 	Buf_Done(&curFile->buf);
2292 	if (curFile->forLoop != NULL)
2293 		ForLoop_Free(curFile->forLoop);
2294 	Vector_Pop(&includes);
2295 
2296 	if (includes.len == 0) {
2297 		/* We've run out of input */
2298 		Global_Delete(".PARSEDIR");
2299 		Global_Delete(".PARSEFILE");
2300 		Global_Delete(".INCLUDEDFROMDIR");
2301 		Global_Delete(".INCLUDEDFROMFILE");
2302 		return false;
2303 	}
2304 
2305 	curFile = CurFile();
2306 	DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
2307 	    curFile->name.str, curFile->readLines + 1);
2308 
2309 	SetParseFile(curFile->name.str);
2310 	return true;
2311 }
2312 
2313 typedef enum ParseRawLineResult {
2314 	PRLR_LINE,
2315 	PRLR_EOF,
2316 	PRLR_ERROR
2317 } ParseRawLineResult;
2318 
2319 /*
2320  * Parse until the end of a line, taking into account lines that end with
2321  * backslash-newline.  The resulting line goes from out_line to out_line_end;
2322  * the line is not null-terminated.
2323  */
2324 static ParseRawLineResult
2325 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2326 	     char **out_firstBackslash, char **out_commentLineEnd)
2327 {
2328 	char *line = curFile->buf_ptr;
2329 	char *buf_end = curFile->buf_end;
2330 	char *p = line;
2331 	char *line_end = line;
2332 	char *firstBackslash = NULL;
2333 	char *commentLineEnd = NULL;
2334 	ParseRawLineResult res = PRLR_LINE;
2335 
2336 	curFile->readLines++;
2337 
2338 	for (;;) {
2339 		char ch;
2340 
2341 		if (p == buf_end) {
2342 			res = PRLR_EOF;
2343 			break;
2344 		}
2345 
2346 		ch = *p;
2347 		if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2348 			Parse_Error(PARSE_FATAL, "Zero byte read from file");
2349 			return PRLR_ERROR;
2350 		}
2351 
2352 		/* Treat next character after '\' as literal. */
2353 		if (ch == '\\') {
2354 			if (firstBackslash == NULL)
2355 				firstBackslash = p;
2356 			if (p[1] == '\n') {
2357 				curFile->readLines++;
2358 				if (p + 2 == buf_end) {
2359 					line_end = p;
2360 					*line_end = '\n';
2361 					p += 2;
2362 					continue;
2363 				}
2364 			}
2365 			p += 2;
2366 			line_end = p;
2367 			assert(p <= buf_end);
2368 			continue;
2369 		}
2370 
2371 		/*
2372 		 * Remember the first '#' for comment stripping, unless
2373 		 * the previous char was '[', as in the modifier ':[#]'.
2374 		 */
2375 		if (ch == '#' && commentLineEnd == NULL &&
2376 		    !(p > line && p[-1] == '['))
2377 			commentLineEnd = line_end;
2378 
2379 		p++;
2380 		if (ch == '\n')
2381 			break;
2382 
2383 		/* We are not interested in trailing whitespace. */
2384 		if (!ch_isspace(ch))
2385 			line_end = p;
2386 	}
2387 
2388 	curFile->buf_ptr = p;
2389 	*out_line = line;
2390 	*out_line_end = line_end;
2391 	*out_firstBackslash = firstBackslash;
2392 	*out_commentLineEnd = commentLineEnd;
2393 	return res;
2394 }
2395 
2396 /*
2397  * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2398  * with a single space.
2399  */
2400 static void
2401 UnescapeBackslash(char *line, char *start)
2402 {
2403 	const char *src = start;
2404 	char *dst = start;
2405 	char *spaceStart = line;
2406 
2407 	for (;;) {
2408 		char ch = *src++;
2409 		if (ch != '\\') {
2410 			if (ch == '\0')
2411 				break;
2412 			*dst++ = ch;
2413 			continue;
2414 		}
2415 
2416 		ch = *src++;
2417 		if (ch == '\0') {
2418 			/* Delete '\\' at the end of the buffer. */
2419 			dst--;
2420 			break;
2421 		}
2422 
2423 		/* Delete '\\' from before '#' on non-command lines. */
2424 		if (ch == '#' && line[0] != '\t')
2425 			*dst++ = ch;
2426 		else if (ch == '\n') {
2427 			cpp_skip_hspace(&src);
2428 			*dst++ = ' ';
2429 		} else {
2430 			/* Leave '\\' in the buffer for later. */
2431 			*dst++ = '\\';
2432 			*dst++ = ch;
2433 			/* Keep an escaped ' ' at the line end. */
2434 			spaceStart = dst;
2435 		}
2436 	}
2437 
2438 	/* Delete any trailing spaces - eg from empty continuations */
2439 	while (dst > spaceStart && ch_isspace(dst[-1]))
2440 		dst--;
2441 	*dst = '\0';
2442 }
2443 
2444 typedef enum LineKind {
2445 	/*
2446 	 * Return the next line that is neither empty nor a comment.
2447 	 * Backslash line continuations are folded into a single space.
2448 	 * A trailing comment, if any, is discarded.
2449 	 */
2450 	LK_NONEMPTY,
2451 
2452 	/*
2453 	 * Return the next line, even if it is empty or a comment.
2454 	 * Preserve backslash-newline to keep the line numbers correct.
2455 	 *
2456 	 * Used in .for loops to collect the body of the loop while waiting
2457 	 * for the corresponding .endfor.
2458 	 */
2459 	LK_FOR_BODY,
2460 
2461 	/*
2462 	 * Return the next line that starts with a dot.
2463 	 * Backslash line continuations are folded into a single space.
2464 	 * A trailing comment, if any, is discarded.
2465 	 *
2466 	 * Used in .if directives to skip over irrelevant branches while
2467 	 * waiting for the corresponding .endif.
2468 	 */
2469 	LK_DOT
2470 } LineKind;
2471 
2472 /*
2473  * Return the next "interesting" logical line from the current file.  The
2474  * returned string will be freed at the end of including the file.
2475  */
2476 static char *
2477 ReadLowLevelLine(LineKind kind)
2478 {
2479 	IncludedFile *curFile = CurFile();
2480 	ParseRawLineResult res;
2481 	char *line;
2482 	char *line_end;
2483 	char *firstBackslash;
2484 	char *commentLineEnd;
2485 
2486 	for (;;) {
2487 		curFile->lineno = curFile->readLines + 1;
2488 		res = ParseRawLine(curFile,
2489 		    &line, &line_end, &firstBackslash, &commentLineEnd);
2490 		if (res == PRLR_ERROR)
2491 			return NULL;
2492 
2493 		if (line == line_end || line == commentLineEnd) {
2494 			if (res == PRLR_EOF)
2495 				return NULL;
2496 			if (kind != LK_FOR_BODY)
2497 				continue;
2498 		}
2499 
2500 		/* We now have a line of data */
2501 		assert(ch_isspace(*line_end));
2502 		*line_end = '\0';
2503 
2504 		if (kind == LK_FOR_BODY)
2505 			return line;	/* Don't join the physical lines. */
2506 
2507 		if (kind == LK_DOT && line[0] != '.')
2508 			continue;
2509 		break;
2510 	}
2511 
2512 	if (commentLineEnd != NULL && line[0] != '\t')
2513 		*commentLineEnd = '\0';
2514 	if (firstBackslash != NULL)
2515 		UnescapeBackslash(line, firstBackslash);
2516 	return line;
2517 }
2518 
2519 static bool
2520 SkipIrrelevantBranches(void)
2521 {
2522 	const char *line;
2523 
2524 	while ((line = ReadLowLevelLine(LK_DOT)) != NULL) {
2525 		if (Cond_EvalLine(line) == CR_TRUE)
2526 			return true;
2527 		/*
2528 		 * TODO: Check for typos in .elif directives such as .elsif
2529 		 * or .elseif.
2530 		 *
2531 		 * This check will probably duplicate some of the code in
2532 		 * ParseLine.  Most of the code there cannot apply, only
2533 		 * ParseVarassign and ParseDependencyLine can, and to prevent
2534 		 * code duplication, these would need to be called with a
2535 		 * flag called onlyCheckSyntax.
2536 		 *
2537 		 * See directive-elif.mk for details.
2538 		 */
2539 	}
2540 
2541 	return false;
2542 }
2543 
2544 static bool
2545 ParseForLoop(const char *line)
2546 {
2547 	int rval;
2548 	unsigned forHeadLineno;
2549 	unsigned bodyReadLines;
2550 	int forLevel;
2551 
2552 	rval = For_Eval(line);
2553 	if (rval == 0)
2554 		return false;	/* Not a .for line */
2555 	if (rval < 0)
2556 		return true;	/* Syntax error - error printed, ignore line */
2557 
2558 	forHeadLineno = CurFile()->lineno;
2559 	bodyReadLines = CurFile()->readLines;
2560 
2561 	/* Accumulate the loop body until the matching '.endfor'. */
2562 	forLevel = 1;
2563 	do {
2564 		line = ReadLowLevelLine(LK_FOR_BODY);
2565 		if (line == NULL) {
2566 			Parse_Error(PARSE_FATAL,
2567 			    "Unexpected end of file in .for loop");
2568 			break;
2569 		}
2570 	} while (For_Accum(line, &forLevel));
2571 
2572 	For_Run(forHeadLineno, bodyReadLines);
2573 	return true;
2574 }
2575 
2576 /*
2577  * Read an entire line from the input file.
2578  *
2579  * Empty lines, .if and .for are completely handled by this function,
2580  * leaving only variable assignments, other directives, dependency lines
2581  * and shell commands to the caller.
2582  *
2583  * Return a line without trailing whitespace, or NULL for EOF.  The returned
2584  * string will be freed at the end of including the file.
2585  */
2586 static char *
2587 ReadHighLevelLine(void)
2588 {
2589 	char *line;
2590 
2591 	for (;;) {
2592 		line = ReadLowLevelLine(LK_NONEMPTY);
2593 		if (line == NULL)
2594 			return NULL;
2595 
2596 		if (line[0] != '.')
2597 			return line;
2598 
2599 		switch (Cond_EvalLine(line)) {
2600 		case CR_FALSE:	/* May also mean a syntax error. */
2601 			if (!SkipIrrelevantBranches())
2602 				return NULL;
2603 			continue;
2604 		case CR_TRUE:
2605 			continue;
2606 		case CR_ERROR:	/* Not a conditional line */
2607 			if (ParseForLoop(line))
2608 				continue;
2609 			break;
2610 		}
2611 		return line;
2612 	}
2613 }
2614 
2615 static void
2616 FinishDependencyGroup(void)
2617 {
2618 	GNodeListNode *ln;
2619 
2620 	if (targets == NULL)
2621 		return;
2622 
2623 	for (ln = targets->first; ln != NULL; ln = ln->next) {
2624 		GNode *gn = ln->datum;
2625 
2626 		Suff_EndTransform(gn);
2627 
2628 		/*
2629 		 * Mark the target as already having commands if it does, to
2630 		 * keep from having shell commands on multiple dependency
2631 		 * lines.
2632 		 */
2633 		if (!Lst_IsEmpty(&gn->commands))
2634 			gn->type |= OP_HAS_COMMANDS;
2635 	}
2636 
2637 	Lst_Free(targets);
2638 	targets = NULL;
2639 }
2640 
2641 /* Add the command to each target from the current dependency spec. */
2642 static void
2643 ParseLine_ShellCommand(const char *p)
2644 {
2645 	cpp_skip_whitespace(&p);
2646 	if (*p == '\0')
2647 		return;		/* skip empty commands */
2648 
2649 	if (targets == NULL) {
2650 		Parse_Error(PARSE_FATAL,
2651 		    "Unassociated shell command \"%s\"", p);
2652 		return;
2653 	}
2654 
2655 	{
2656 		char *cmd = bmake_strdup(p);
2657 		GNodeListNode *ln;
2658 
2659 		for (ln = targets->first; ln != NULL; ln = ln->next) {
2660 			GNode *gn = ln->datum;
2661 			GNode_AddCommand(gn, cmd);
2662 		}
2663 #ifdef CLEANUP
2664 		Lst_Append(&targCmds, cmd);
2665 #endif
2666 	}
2667 }
2668 
2669 /*
2670  * See if the line starts with one of the known directives, and if so, handle
2671  * the directive.
2672  */
2673 static bool
2674 ParseDirective(char *line)
2675 {
2676 	char *cp = line + 1;
2677 	const char *arg;
2678 	Substring dir;
2679 
2680 	pp_skip_whitespace(&cp);
2681 	if (IsInclude(cp, false)) {
2682 		ParseInclude(cp);
2683 		return true;
2684 	}
2685 
2686 	dir.start = cp;
2687 	while (ch_islower(*cp) || *cp == '-')
2688 		cp++;
2689 	dir.end = cp;
2690 
2691 	if (*cp != '\0' && !ch_isspace(*cp))
2692 		return false;
2693 
2694 	pp_skip_whitespace(&cp);
2695 	arg = cp;
2696 
2697 	if (Substring_Equals(dir, "undef"))
2698 		Var_Undef(arg);
2699 	else if (Substring_Equals(dir, "export"))
2700 		Var_Export(VEM_PLAIN, arg);
2701 	else if (Substring_Equals(dir, "export-env"))
2702 		Var_Export(VEM_ENV, arg);
2703 	else if (Substring_Equals(dir, "export-literal"))
2704 		Var_Export(VEM_LITERAL, arg);
2705 	else if (Substring_Equals(dir, "unexport"))
2706 		Var_UnExport(false, arg);
2707 	else if (Substring_Equals(dir, "unexport-env"))
2708 		Var_UnExport(true, arg);
2709 	else if (Substring_Equals(dir, "info"))
2710 		HandleMessage(PARSE_INFO, "info", arg);
2711 	else if (Substring_Equals(dir, "warning"))
2712 		HandleMessage(PARSE_WARNING, "warning", arg);
2713 	else if (Substring_Equals(dir, "error"))
2714 		HandleMessage(PARSE_FATAL, "error", arg);
2715 	else
2716 		return false;
2717 	return true;
2718 }
2719 
2720 bool
2721 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2722 {
2723 	VarAssign var;
2724 
2725 	if (!Parse_IsVar(line, &var))
2726 		return false;
2727 	if (finishDependencyGroup)
2728 		FinishDependencyGroup();
2729 	Parse_Var(&var, scope);
2730 	free(var.varname);
2731 	return true;
2732 }
2733 
2734 static char *
2735 FindSemicolon(char *p)
2736 {
2737 	int level = 0;
2738 
2739 	for (; *p != '\0'; p++) {
2740 		if (*p == '\\' && p[1] != '\0') {
2741 			p++;
2742 			continue;
2743 		}
2744 
2745 		if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2746 			level++;
2747 		else if (level > 0 && (*p == ')' || *p == '}'))
2748 			level--;
2749 		else if (level == 0 && *p == ';')
2750 			break;
2751 	}
2752 	return p;
2753 }
2754 
2755 /*
2756  * dependency	-> [target...] op [source...] [';' command]
2757  * op		-> ':' | '::' | '!'
2758  */
2759 static void
2760 ParseDependencyLine(char *line)
2761 {
2762 	VarEvalMode emode;
2763 	char *expanded_line;
2764 	const char *shellcmd = NULL;
2765 
2766 	/*
2767 	 * For some reason - probably to make the parser impossible -
2768 	 * a ';' can be used to separate commands from dependencies.
2769 	 * Attempt to skip over ';' inside substitution patterns.
2770 	 */
2771 	{
2772 		char *semicolon = FindSemicolon(line);
2773 		if (*semicolon != '\0') {
2774 			/* Terminate the dependency list at the ';' */
2775 			*semicolon = '\0';
2776 			shellcmd = semicolon + 1;
2777 		}
2778 	}
2779 
2780 	/*
2781 	 * We now know it's a dependency line so it needs to have all
2782 	 * variables expanded before being parsed.
2783 	 *
2784 	 * XXX: Ideally the dependency line would first be split into
2785 	 * its left-hand side, dependency operator and right-hand side,
2786 	 * and then each side would be expanded on its own.  This would
2787 	 * allow for the left-hand side to allow only defined variables
2788 	 * and to allow variables on the right-hand side to be undefined
2789 	 * as well.
2790 	 *
2791 	 * Parsing the line first would also prevent that targets
2792 	 * generated from variable expressions are interpreted as the
2793 	 * dependency operator, such as in "target${:U\:} middle: source",
2794 	 * in which the middle is interpreted as a source, not a target.
2795 	 */
2796 
2797 	/*
2798 	 * In lint mode, allow undefined variables to appear in dependency
2799 	 * lines.
2800 	 *
2801 	 * Ideally, only the right-hand side would allow undefined variables
2802 	 * since it is common to have optional dependencies. Having undefined
2803 	 * variables on the left-hand side is more unusual though.  Since
2804 	 * both sides are expanded in a single pass, there is not much choice
2805 	 * what to do here.
2806 	 *
2807 	 * In normal mode, it does not matter whether undefined variables are
2808 	 * allowed or not since as of 2020-09-14, Var_Parse does not print
2809 	 * any parse errors in such a case. It simply returns the special
2810 	 * empty string var_Error, which cannot be detected in the result of
2811 	 * Var_Subst.
2812 	 */
2813 	emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
2814 	(void)Var_Subst(line, SCOPE_CMDLINE, emode, &expanded_line);
2815 	/* TODO: handle errors */
2816 
2817 	/* Need a fresh list for the target nodes */
2818 	if (targets != NULL)
2819 		Lst_Free(targets);
2820 	targets = Lst_New();
2821 
2822 	ParseDependency(expanded_line);
2823 	free(expanded_line);
2824 
2825 	if (shellcmd != NULL)
2826 		ParseLine_ShellCommand(shellcmd);
2827 }
2828 
2829 static void
2830 ParseLine(char *line)
2831 {
2832 	/*
2833 	 * Lines that begin with '.' can be pretty much anything:
2834 	 *	- directives like '.include' or '.if',
2835 	 *	- suffix rules like '.c.o:',
2836 	 *	- dependencies for filenames that start with '.',
2837 	 *	- variable assignments like '.tmp=value'.
2838 	 */
2839 	if (line[0] == '.' && ParseDirective(line))
2840 		return;
2841 
2842 	if (line[0] == '\t') {
2843 		ParseLine_ShellCommand(line + 1);
2844 		return;
2845 	}
2846 
2847 #ifdef SYSVINCLUDE
2848 	if (IsSysVInclude(line)) {
2849 		/*
2850 		 * It's an S3/S5-style "include".
2851 		 */
2852 		ParseTraditionalInclude(line);
2853 		return;
2854 	}
2855 #endif
2856 
2857 #ifdef GMAKEEXPORT
2858 	if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2859 	    strchr(line, ':') == NULL) {
2860 		/*
2861 		 * It's a Gmake "export".
2862 		 */
2863 		ParseGmakeExport(line);
2864 		return;
2865 	}
2866 #endif
2867 
2868 	if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
2869 		return;
2870 
2871 	FinishDependencyGroup();
2872 
2873 	ParseDependencyLine(line);
2874 }
2875 
2876 /*
2877  * Parse a top-level makefile, incorporating its content into the global
2878  * dependency graph.
2879  */
2880 void
2881 Parse_File(const char *name, int fd)
2882 {
2883 	char *line;
2884 	Buffer buf;
2885 
2886 	buf = loadfile(name, fd != -1 ? fd : STDIN_FILENO);
2887 	if (fd != -1)
2888 		(void)close(fd);
2889 
2890 	assert(targets == NULL);
2891 
2892 	Parse_PushInput(name, 1, 0, buf, NULL);
2893 
2894 	do {
2895 		while ((line = ReadHighLevelLine()) != NULL) {
2896 			DEBUG2(PARSE, "Parsing line %u: %s\n",
2897 			    CurFile()->lineno, line);
2898 			ParseLine(line);
2899 		}
2900 		/* Reached EOF, but it may be just EOF of an include file. */
2901 	} while (ParseEOF());
2902 
2903 	FinishDependencyGroup();
2904 
2905 	if (parseErrors != 0) {
2906 		(void)fflush(stdout);
2907 		(void)fprintf(stderr,
2908 		    "%s: Fatal errors encountered -- cannot continue\n",
2909 		    progname);
2910 		PrintOnError(NULL, "");
2911 		exit(1);
2912 	}
2913 }
2914 
2915 /* Initialize the parsing module. */
2916 void
2917 Parse_Init(void)
2918 {
2919 	mainNode = NULL;
2920 	parseIncPath = SearchPath_New();
2921 	sysIncPath = SearchPath_New();
2922 	defSysIncPath = SearchPath_New();
2923 	Vector_Init(&includes, sizeof(IncludedFile));
2924 }
2925 
2926 /* Clean up the parsing module. */
2927 void
2928 Parse_End(void)
2929 {
2930 #ifdef CLEANUP
2931 	Lst_DoneCall(&targCmds, free);
2932 	assert(targets == NULL);
2933 	SearchPath_Free(defSysIncPath);
2934 	SearchPath_Free(sysIncPath);
2935 	SearchPath_Free(parseIncPath);
2936 	assert(includes.len == 0);
2937 	Vector_Done(&includes);
2938 #endif
2939 }
2940 
2941 
2942 /*
2943  * Return a list containing the single main target to create.
2944  * If no such target exists, we Punt with an obnoxious error message.
2945  */
2946 void
2947 Parse_MainName(GNodeList *mainList)
2948 {
2949 	if (mainNode == NULL)
2950 		Punt("no target to make.");
2951 
2952 	Lst_Append(mainList, mainNode);
2953 	if (mainNode->type & OP_DOUBLEDEP)
2954 		Lst_AppendAll(mainList, &mainNode->cohorts);
2955 
2956 	Global_Append(".TARGETS", mainNode->name);
2957 }
2958 
2959 int
2960 Parse_NumErrors(void)
2961 {
2962 	return parseErrors;
2963 }
2964