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