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