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