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