1 /* $NetBSD: parse.c,v 1.692 2023/01/24 00:24:02 sjg Exp $ */
4 * Copyright (c) 1988, 1989, 1990, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
36 * Copyright (c) 1989 by Berkeley Softworks
37 * All rights reserved.
39 * This code is derived from software contributed to Berkeley by
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
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.
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
72 * Parsing of makefiles.
74 * Parse_File is the main entry point and controls most of the other
75 * functions in this module.
78 * Parse_Init Initialize the module
80 * Parse_End Clean up the module
82 * Parse_File Parse a top-level makefile. Included files are
83 * handled by IncludeFile instead.
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.
91 * Parse_Error Report a parse error, a warning or an informational
94 * Parse_MainName Returns a list of the single main target to create.
97 #include <sys/types.h>
109 #include <sys/mman.h>
112 #define MAP_COPY MAP_PRIVATE
121 #include "pathnames.h"
123 /* "@(#)parse.c 8.3 (Berkeley) 3/19/94" */
124 MAKE_RCSID("$NetBSD: parse.c,v 1.692 2023/01/24 00:24:02 sjg Exp $");
129 typedef struct IncludedFile {
130 FStr name; /* absolute or relative to the cwd */
131 unsigned lineno; /* 1-based */
132 unsigned readLines; /* the number of physical lines that have
133 * been read from the file */
134 unsigned forHeadLineno; /* 1-based */
135 unsigned forBodyReadLines; /* the number of physical lines that have
136 * been read from the file above the body of
138 unsigned int condMinDepth; /* depth of nested 'if' directives, at the
139 * beginning of the file */
140 bool depending; /* state of doing_depend on EOF */
142 Buffer buf; /* the file's content or the body of the .for
143 * loop; either empty or ends with '\n' */
144 char *buf_ptr; /* next char to be read */
145 char *buf_end; /* buf_end[-1] == '\n' */
147 struct ForLoop *forLoop;
150 /* Special attributes for target nodes. */
151 typedef enum ParseSpecial {
152 SP_ATTRIBUTE, /* Generic attribute */
153 SP_BEGIN, /* .BEGIN */
154 SP_DEFAULT, /* .DEFAULT */
155 SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
157 SP_ERROR, /* .ERROR */
158 SP_IGNORE, /* .IGNORE */
159 SP_INCLUDES, /* .INCLUDES; not mentioned in the manual page */
160 SP_INTERRUPT, /* .INTERRUPT */
161 SP_LIBS, /* .LIBS; not mentioned in the manual page */
162 SP_MAIN, /* .MAIN and no user-specified targets to make */
164 SP_MFLAGS, /* .MFLAGS or .MAKEFLAGS */
165 SP_NOMETA, /* .NOMETA */
166 SP_NOMETA_CMP, /* .NOMETA_CMP */
167 SP_NOPATH, /* .NOPATH */
168 SP_NOREADONLY, /* .NOREADONLY */
169 SP_NOT, /* Not special */
170 SP_NOTPARALLEL, /* .NOTPARALLEL or .NO_PARALLEL */
171 SP_NULL, /* .NULL; not mentioned in the manual page */
172 SP_OBJDIR, /* .OBJDIR */
173 SP_ORDER, /* .ORDER */
174 SP_PARALLEL, /* .PARALLEL; not mentioned in the manual page */
175 SP_PATH, /* .PATH or .PATH.suffix */
176 SP_PHONY, /* .PHONY */
178 SP_POSIX, /* .POSIX; not mentioned in the manual page */
180 SP_PRECIOUS, /* .PRECIOUS */
181 SP_READONLY, /* .READONLY */
182 SP_SHELL, /* .SHELL */
183 SP_SILENT, /* .SILENT */
184 SP_SINGLESHELL, /* .SINGLESHELL; not mentioned in the manual page */
185 SP_STALE, /* .STALE */
186 SP_SUFFIXES, /* .SUFFIXES */
187 SP_SYSPATH, /* .SYSPATH */
191 typedef List SearchPathList;
192 typedef ListNode SearchPathListNode;
195 typedef enum VarAssignOp {
198 VAR_DEFAULT, /* ?= */
200 VAR_SHELL /* != or :sh= */
203 typedef struct VarAssign {
204 char *varname; /* unexpanded */
206 const char *value; /* unexpanded */
209 static bool Parse_IsVar(const char *, VarAssign *);
210 static void Parse_Var(VarAssign *, GNode *);
213 * The target to be made if no targets are specified in the command line.
214 * This is the first target defined in any of the makefiles.
219 * During parsing, the targets from the left-hand side of the currently
220 * active dependency line, or NULL if the current line does not belong to a
221 * dependency line, for example because it is a variable assignment.
223 * See unit-tests/deptgt.mk, keyword "parse.c:targets".
225 static GNodeList *targets;
229 * All shell commands for all targets, in no particular order and possibly
230 * with duplicates. Kept in a separate list since the commands from .USE or
231 * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
232 * easily understandable ownership over the allocated strings.
234 static StringList targCmds = LST_INIT;
238 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
239 * is seen, then set to each successive source on the line.
241 static GNode *order_pred;
243 static int parseErrors = 0;
246 * The include chain of makefiles. At index 0 is the top-level makefile from
247 * the command line, followed by the included files or .for loops, up to and
248 * including the current file.
250 * See PrintStackTrace for how to interpret the data.
252 static Vector /* of IncludedFile */ includes;
254 SearchPath *parseIncPath; /* directories for "..." includes */
255 SearchPath *sysIncPath; /* directories for <...> includes */
256 SearchPath *defSysIncPath; /* default for sysIncPath */
259 * The parseKeywords table is searched using binary search when deciding
260 * if a target or source is special. The 'spec' field is the ParseSpecial
261 * type of the keyword (SP_NOT if the keyword isn't special as a target) while
262 * the 'op' field is the operator to apply to the list of targets if the
263 * keyword is used as a source ("0" if the keyword isn't special as a source)
265 static const struct {
267 ParseSpecial special; /* when used as a target */
268 GNodeType targetAttr; /* when used as a source */
269 } parseKeywords[] = {
270 { ".BEGIN", SP_BEGIN, OP_NONE },
271 { ".DEFAULT", SP_DEFAULT, OP_NONE },
272 { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
273 { ".END", SP_END, OP_NONE },
274 { ".ERROR", SP_ERROR, OP_NONE },
275 { ".EXEC", SP_ATTRIBUTE, OP_EXEC },
276 { ".IGNORE", SP_IGNORE, OP_IGNORE },
277 { ".INCLUDES", SP_INCLUDES, OP_NONE },
278 { ".INTERRUPT", SP_INTERRUPT, OP_NONE },
279 { ".INVISIBLE", SP_ATTRIBUTE, OP_INVISIBLE },
280 { ".JOIN", SP_ATTRIBUTE, OP_JOIN },
281 { ".LIBS", SP_LIBS, OP_NONE },
282 { ".MADE", SP_ATTRIBUTE, OP_MADE },
283 { ".MAIN", SP_MAIN, OP_NONE },
284 { ".MAKE", SP_ATTRIBUTE, OP_MAKE },
285 { ".MAKEFLAGS", SP_MFLAGS, OP_NONE },
286 { ".META", SP_META, OP_META },
287 { ".MFLAGS", SP_MFLAGS, OP_NONE },
288 { ".NOMETA", SP_NOMETA, OP_NOMETA },
289 { ".NOMETA_CMP", SP_NOMETA_CMP, OP_NOMETA_CMP },
290 { ".NOPATH", SP_NOPATH, OP_NOPATH },
291 { ".NOREADONLY", SP_NOREADONLY, OP_NONE },
292 { ".NOTMAIN", SP_ATTRIBUTE, OP_NOTMAIN },
293 { ".NOTPARALLEL", SP_NOTPARALLEL, OP_NONE },
294 { ".NO_PARALLEL", SP_NOTPARALLEL, OP_NONE },
295 { ".NULL", SP_NULL, OP_NONE },
296 { ".OBJDIR", SP_OBJDIR, OP_NONE },
297 { ".OPTIONAL", SP_ATTRIBUTE, OP_OPTIONAL },
298 { ".ORDER", SP_ORDER, OP_NONE },
299 { ".PARALLEL", SP_PARALLEL, OP_NONE },
300 { ".PATH", SP_PATH, OP_NONE },
301 { ".PHONY", SP_PHONY, OP_PHONY },
303 { ".POSIX", SP_POSIX, OP_NONE },
305 { ".PRECIOUS", SP_PRECIOUS, OP_PRECIOUS },
306 { ".READONLY", SP_READONLY, OP_NONE },
307 { ".RECURSIVE", SP_ATTRIBUTE, OP_MAKE },
308 { ".SHELL", SP_SHELL, OP_NONE },
309 { ".SILENT", SP_SILENT, OP_SILENT },
310 { ".SINGLESHELL", SP_SINGLESHELL, OP_NONE },
311 { ".STALE", SP_STALE, OP_NONE },
312 { ".SUFFIXES", SP_SUFFIXES, OP_NONE },
313 { ".SYSPATH", SP_SYSPATH, OP_NONE },
314 { ".USE", SP_ATTRIBUTE, OP_USE },
315 { ".USEBEFORE", SP_ATTRIBUTE, OP_USEBEFORE },
316 { ".WAIT", SP_WAIT, OP_NONE },
319 enum PosixState posix_state = PS_NOT_YET;
321 static IncludedFile *
324 assert(i < includes.len);
325 return Vector_Get(&includes, i);
328 /* The file that is currently being read. */
329 static IncludedFile *
332 return GetInclude(includes.len - 1);
336 CurFile_CondMinDepth(void)
338 return CurFile()->condMinDepth;
342 LoadFile(const char *path, int fd)
349 bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
350 st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
351 ? (size_t)st.st_size : 1024;
352 Buf_InitSize(&buf, bufSize);
355 if (buf.len == buf.cap) {
356 if (buf.cap >= 512 * 1024 * 1024) {
357 Error("%s: file too large", path);
358 exit(2); /* Not 1 so -q can distinguish error */
362 assert(buf.len < buf.cap);
363 n = read(fd, buf.data + buf.len, buf.cap - buf.len);
365 Error("%s: read error: %s", path, strerror(errno));
366 exit(2); /* Not 1 so -q can distinguish error */
371 buf.len += (size_t)n;
373 assert(buf.len <= buf.cap);
375 if (!Buf_EndsWith(&buf, '\n'))
376 Buf_AddByte(&buf, '\n');
378 return buf; /* may not be null-terminated */
382 * Print the current chain of .include and .for directives. In Parse_Fatal
383 * or other functions that already print the location, includingInnermost
384 * would be redundant, but in other cases like Error or Fatal it needs to be
388 PrintStackTrace(bool includingInnermost)
390 const IncludedFile *entries;
397 entries = GetInclude(0);
398 if (!includingInnermost && entries[n - 1].forLoop == NULL)
399 n--; /* already in the diagnostic */
401 for (i = n; i-- > 0;) {
402 const IncludedFile *entry = entries + i;
403 const char *fname = entry->name.str;
404 char dirbuf[MAXPATHLEN + 1];
406 if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0)
407 fname = realpath(fname, dirbuf);
409 if (entry->forLoop != NULL) {
410 char *details = ForLoop_Details(entry->forLoop);
411 debug_printf("\tin .for loop from %s:%u with %s\n",
412 fname, entry->forHeadLineno, details);
414 } else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
415 /* entry->lineno is not a useful line number */
417 debug_printf("\tin %s:%u\n", fname, entry->lineno);
421 /* Check if the current character is escaped on the current line. */
423 IsEscaped(const char *line, const char *p)
425 bool escaped = false;
426 while (p > line && *--p == '\\')
432 * Add the filename and lineno to the GNode so that we remember where it
436 RememberLocation(GNode *gn)
438 IncludedFile *curFile = CurFile();
439 gn->fname = Str_Intern(curFile->name.str);
440 gn->lineno = curFile->lineno;
444 * Look in the table of keywords for one matching the given string.
445 * Return the index of the keyword, or -1 if it isn't there.
448 FindKeyword(const char *str)
451 int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
453 while (start <= end) {
454 int curr = start + (end - start) / 2;
455 int diff = strcmp(str, parseKeywords[curr].name);
469 PrintLocation(FILE *f, bool useVars, const GNode *gn)
471 char dirbuf[MAXPATHLEN + 1];
479 } else if (includes.len > 0) {
480 IncludedFile *curFile = CurFile();
481 fname = curFile->name.str;
482 lineno = curFile->lineno;
486 if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
487 (void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
491 dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
494 if (dir.str[0] != '/')
495 dir.str = realpath(dir.str, dirbuf);
497 base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
498 if (base.str == NULL)
499 base.str = str_basename(fname);
501 (void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
507 static void MAKE_ATTR_PRINTFLIKE(5, 0)
508 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
509 ParseErrorLevel level, const char *fmt, va_list ap)
511 static bool fatal_warning_error_printed = false;
513 (void)fprintf(f, "%s: ", progname);
515 PrintLocation(f, useVars, gn);
516 if (level == PARSE_WARNING)
517 (void)fprintf(f, "warning: ");
518 (void)vfprintf(f, fmt, ap);
519 (void)fprintf(f, "\n");
522 if (level == PARSE_FATAL)
524 if (level == PARSE_WARNING && opts.parseWarnFatal) {
525 if (!fatal_warning_error_printed) {
526 Error("parsing warnings being treated as errors");
527 fatal_warning_error_printed = true;
533 PrintStackTrace(false);
536 static void MAKE_ATTR_PRINTFLIKE(3, 4)
537 ParseErrorInternal(const GNode *gn,
538 ParseErrorLevel level, const char *fmt, ...)
542 (void)fflush(stdout);
544 ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
547 if (opts.debug_file != stdout && opts.debug_file != stderr) {
549 ParseVErrorInternal(opts.debug_file, false, gn,
556 * Print a parse error message, including location information.
558 * If the level is PARSE_FATAL, continue parsing until the end of the
559 * current top-level makefile, then exit (see Parse_File).
561 * Fmt is given without a trailing newline.
564 Parse_Error(ParseErrorLevel level, const char *fmt, ...)
568 (void)fflush(stdout);
570 ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
573 if (opts.debug_file != stdout && opts.debug_file != stderr) {
575 ParseVErrorInternal(opts.debug_file, true, NULL,
583 * Handle an .info, .warning or .error directive. For an .error directive,
587 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
591 if (umsg[0] == '\0') {
592 Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
597 (void)Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES, &xmsg);
598 /* TODO: handle errors */
600 Parse_Error(level, "%s", xmsg);
603 if (level == PARSE_FATAL) {
604 PrintOnError(NULL, "\n");
610 * Add the child to the parent's children, and for non-special targets, vice
611 * versa. Special targets such as .END do not need to be informed once the
612 * child target has been made.
615 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
617 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
618 pgn = pgn->cohorts.last->datum;
620 Lst_Append(&pgn->children, cgn);
623 /* Special targets like .END don't need any children. */
625 Lst_Append(&cgn->parents, pgn);
628 debug_printf("# LinkSource: added child %s - %s\n",
629 pgn->name, cgn->name);
630 Targ_PrintNode(pgn, 0);
631 Targ_PrintNode(cgn, 0);
635 /* Add the node to each target from the current dependency group. */
637 LinkToTargets(GNode *gn, bool isSpecial)
641 for (ln = targets->first; ln != NULL; ln = ln->next)
642 LinkSource(ln->datum, gn, isSpecial);
646 TryApplyDependencyOperator(GNode *gn, GNodeType op)
649 * If the node occurred on the left-hand side of a dependency and the
650 * operator also defines a dependency, they must match.
652 if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
653 ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
654 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
659 if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
661 * If the node was of the left-hand side of a '::' operator,
662 * we need to create a new instance of it for the children
663 * and commands on this dependency line since each of these
664 * dependency groups has its own attributes and commands,
665 * separate from the others.
667 * The new instance is placed on the 'cohorts' list of the
668 * initial one (note the initial one is not on its own
669 * cohorts list) and the new instance is linked to all
670 * parents of the initial instance.
675 * Propagate copied bits to the initial node. They'll be
676 * propagated back to the rest of the cohorts later.
678 gn->type |= op & (unsigned)~OP_OPMASK;
680 cohort = Targ_NewInternalNode(gn->name);
682 RememberLocation(cohort);
684 * Make the cohort invisible as well to avoid duplicating it
685 * into other variables. True, parents of this target won't
686 * tend to do anything with their local variables, but better
689 * (I think this is pointless now, since the relevant list
690 * traversals will no longer see this node anyway. -mycroft)
692 cohort->type = op | OP_INVISIBLE;
693 Lst_Append(&gn->cohorts, cohort);
694 cohort->centurion = gn;
695 gn->unmade_cohorts++;
696 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
697 (unsigned int)gn->unmade_cohorts % 1000000);
700 * We don't want to nuke any previous flags (whatever they
701 * were) so we just OR the new operator into the old.
710 ApplyDependencyOperator(GNodeType op)
714 for (ln = targets->first; ln != NULL; ln = ln->next)
715 if (!TryApplyDependencyOperator(ln->datum, op))
720 * We add a .WAIT node in the dependency list. After any dynamic dependencies
721 * (and filename globbing) have happened, it is given a dependency on each
722 * previous child, back until the previous .WAIT node. The next child won't
723 * be scheduled until the .WAIT node is built.
725 * We give each .WAIT node a unique name (mainly for diagnostics).
728 ApplyDependencySourceWait(bool isSpecial)
730 static unsigned wait_number = 0;
731 char name[6 + 10 + 1];
734 snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
735 gn = Targ_NewInternalNode(name);
737 RememberLocation(gn);
738 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
739 LinkToTargets(gn, isSpecial);
743 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
746 GNodeType targetAttr;
748 if (*src != '.' || !ch_isupper(src[1]))
751 keywd = FindKeyword(src);
755 targetAttr = parseKeywords[keywd].targetAttr;
756 if (targetAttr != OP_NONE) {
757 ApplyDependencyOperator(targetAttr);
760 if (parseKeywords[keywd].special == SP_WAIT) {
761 ApplyDependencySourceWait(special != SP_NOT);
768 * In a line like ".MAIN: source1 source2", add all sources to the list of
769 * things to create, but only if the user didn't specify a target on the
770 * command line and .MAIN occurs for the first time.
772 * See HandleDependencyTargetSpecial, branch SP_MAIN.
773 * See unit-tests/cond-func-make-main.mk.
776 ApplyDependencySourceMain(const char *src)
778 Lst_Append(&opts.create, bmake_strdup(src));
780 * Add the name to the .TARGETS variable as well, so the user can
781 * employ that, if desired.
783 Global_Append(".TARGETS", src);
787 * For the sources of a .ORDER target, create predecessor/successor links
788 * between the previous source and the current one.
791 ApplyDependencySourceOrder(const char *src)
795 gn = Targ_GetNode(src);
797 RememberLocation(gn);
798 if (order_pred != NULL) {
799 Lst_Append(&order_pred->order_succ, gn);
800 Lst_Append(&gn->order_pred, order_pred);
803 "# .ORDER forces '%s' to be made before '%s'\n",
804 order_pred->name, gn->name);
805 Targ_PrintNode(order_pred, 0);
806 Targ_PrintNode(gn, 0);
810 * The current source now becomes the predecessor for the next one.
815 /* The source is not an attribute, so find/create a node for it. */
817 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
818 ParseSpecial special)
822 gn = Targ_GetNode(src);
824 RememberLocation(gn);
825 if (targetAttr != OP_NONE)
826 gn->type |= targetAttr;
828 LinkToTargets(gn, special != SP_NOT);
832 * Given the name of a source in a dependency line, figure out if it is an
833 * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
834 * decide if there is some attribute which should be applied *to* the source
835 * because of some special target (such as .PHONY) and apply it if so.
836 * Otherwise, make the source a child of the targets.
839 ApplyDependencySource(GNodeType targetAttr, const char *src,
840 ParseSpecial special)
842 if (ApplyDependencySourceKeyword(src, special))
845 if (special == SP_MAIN)
846 ApplyDependencySourceMain(src);
847 else if (special == SP_ORDER)
848 ApplyDependencySourceOrder(src);
850 ApplyDependencySourceOther(src, targetAttr, special);
854 * If we have yet to decide on a main target to make, in the absence of any
855 * user input, we want the first target on the first dependency line that is
856 * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
859 MaybeUpdateMainTarget(void)
863 if (mainNode != NULL)
866 for (ln = targets->first; ln != NULL; ln = ln->next) {
867 GNode *gn = ln->datum;
868 if (GNode_IsMainCandidate(gn)) {
869 DEBUG1(MAKE, "Setting main node to \"%s\"\n", gn->name);
877 InvalidLineType(const char *line)
879 if (strncmp(line, "<<<<<<", 6) == 0 ||
880 strncmp(line, ">>>>>>", 6) == 0)
881 Parse_Error(PARSE_FATAL,
882 "Makefile appears to contain unresolved CVS/RCS/??? merge conflicts");
883 else if (line[0] == '.') {
884 const char *dirstart = line + 1;
886 cpp_skip_whitespace(&dirstart);
888 while (ch_isalnum(*dirend) || *dirend == '-')
890 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
891 (int)(dirend - dirstart), dirstart);
893 Parse_Error(PARSE_FATAL, "Invalid line type");
897 ParseDependencyTargetWord(char **pp, const char *lstart)
899 const char *cp = *pp;
901 while (*cp != '\0') {
902 if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' ||
904 !IsEscaped(lstart, cp))
909 * Must be a dynamic source (would have been expanded
912 * There should be no errors in this, as they would
913 * have been discovered in the initial Var_Subst and
914 * we wouldn't be here.
918 (void)Var_Parse(&cp, SCOPE_CMDLINE,
919 VARE_PARSE_ONLY, &val);
929 * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
931 * See the tests deptgt-*.mk.
934 HandleDependencyTargetSpecial(const char *targetName,
935 ParseSpecial *inout_special,
936 SearchPathList **inout_paths)
938 switch (*inout_special) {
940 if (*inout_paths == NULL)
941 *inout_paths = Lst_New();
942 Lst_Append(*inout_paths, &dirSearchPath);
945 if (*inout_paths == NULL)
946 *inout_paths = Lst_New();
947 Lst_Append(*inout_paths, sysIncPath);
951 * Allow targets from the command line to override the
954 if (!Lst_IsEmpty(&opts.create))
955 *inout_special = SP_NOT;
962 GNode *gn = Targ_GetNode(targetName);
964 RememberLocation(gn);
965 gn->type |= OP_NOTMAIN | OP_SPECIAL;
966 Lst_Append(targets, gn);
971 * Need to create a node to hang commands on, but we don't
972 * want it in the graph, nor do we want it to be the Main
973 * Target. We claim the node is a transformation rule to make
974 * life easier later, when we'll use Make_HandleUse to
975 * actually apply the .DEFAULT commands.
977 GNode *gn = GNode_New(".DEFAULT");
978 gn->type |= OP_NOTMAIN | OP_TRANSFORM;
979 Lst_Append(targets, gn);
983 case SP_DELETE_ON_ERROR:
984 deleteOnError = true;
990 opts.compatMake = true;
1001 HandleDependencyTargetPath(const char *suffixName,
1002 SearchPathList **inout_paths)
1006 path = Suff_GetPath(suffixName);
1008 Parse_Error(PARSE_FATAL,
1009 "Suffix '%s' not defined (yet)", suffixName);
1013 if (*inout_paths == NULL)
1014 *inout_paths = Lst_New();
1015 Lst_Append(*inout_paths, path);
1020 /* See if it's a special target and if so set inout_special to match it. */
1022 HandleDependencyTarget(const char *targetName,
1023 ParseSpecial *inout_special,
1024 GNodeType *inout_targetAttr,
1025 SearchPathList **inout_paths)
1029 if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
1033 * See if the target is a special target that must have it
1034 * or its sources handled specially.
1036 keywd = FindKeyword(targetName);
1038 if (*inout_special == SP_PATH &&
1039 parseKeywords[keywd].special != SP_PATH) {
1040 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1044 *inout_special = parseKeywords[keywd].special;
1045 *inout_targetAttr = parseKeywords[keywd].targetAttr;
1047 HandleDependencyTargetSpecial(targetName, inout_special,
1050 } else if (strncmp(targetName, ".PATH", 5) == 0) {
1051 *inout_special = SP_PATH;
1052 if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
1059 HandleSingleDependencyTargetMundane(const char *name)
1061 GNode *gn = Suff_IsTransform(name)
1062 ? Suff_AddTransform(name)
1063 : Targ_GetNode(name);
1065 RememberLocation(gn);
1067 Lst_Append(targets, gn);
1071 HandleDependencyTargetMundane(const char *targetName)
1073 if (Dir_HasWildcards(targetName)) {
1074 StringList targetNames = LST_INIT;
1076 SearchPath *emptyPath = SearchPath_New();
1077 SearchPath_Expand(emptyPath, targetName, &targetNames);
1078 SearchPath_Free(emptyPath);
1080 while (!Lst_IsEmpty(&targetNames)) {
1081 char *targName = Lst_Dequeue(&targetNames);
1082 HandleSingleDependencyTargetMundane(targName);
1086 HandleSingleDependencyTargetMundane(targetName);
1090 SkipExtraTargets(char **pp, const char *lstart)
1092 bool warning = false;
1093 const char *p = *pp;
1095 while (*p != '\0') {
1096 if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
1098 if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
1103 const char *start = *pp;
1104 cpp_skip_whitespace(&start);
1105 Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
1106 (int)(p - start), start);
1113 CheckSpecialMundaneMixture(ParseSpecial special)
1123 * These create nodes on which to hang commands, so targets
1124 * shouldn't be empty.
1127 /* Nothing special here -- targets may be empty. */
1130 Parse_Error(PARSE_WARNING,
1131 "Special and mundane targets don't mix. "
1132 "Mundane ones ignored");
1138 * In a dependency line like 'targets: sources' or 'targets! sources', parse
1139 * the operator ':', '::' or '!' from between the targets and the sources.
1142 ParseDependencyOp(char **pp)
1145 return (*pp)++, OP_FORCE;
1146 if (**pp == ':' && (*pp)[1] == ':')
1147 return *pp += 2, OP_DOUBLEDEP;
1148 else if (**pp == ':')
1149 return (*pp)++, OP_DEPENDS;
1155 ClearPaths(ParseSpecial special, SearchPathList *paths)
1157 if (paths != NULL) {
1158 SearchPathListNode *ln;
1159 for (ln = paths->first; ln != NULL; ln = ln->next)
1160 SearchPath_Clear(ln->datum);
1162 if (special == SP_SYSPATH)
1169 FindInDirOfIncludingFile(const char *file)
1171 char *fullname, *incdir, *slash, *newName;
1175 incdir = bmake_strdup(CurFile()->name.str);
1176 slash = strrchr(incdir, '/');
1177 if (slash != NULL) {
1180 * Now do lexical processing of leading "../" on the
1183 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1184 slash = strrchr(incdir + 1, '/');
1185 if (slash == NULL || strcmp(slash, "/..") == 0)
1189 newName = str_concat3(incdir, "/", file + i);
1190 fullname = Dir_FindFile(newName, parseIncPath);
1191 if (fullname == NULL)
1192 fullname = Dir_FindFile(newName, &dirSearchPath);
1200 FindInQuotPath(const char *file)
1203 SearchPath *suffPath;
1206 fullname = FindInDirOfIncludingFile(file);
1207 if (fullname == NULL &&
1208 (suff = strrchr(file, '.')) != NULL &&
1209 (suffPath = Suff_GetPath(suff)) != NULL)
1210 fullname = Dir_FindFile(file, suffPath);
1211 if (fullname == NULL)
1212 fullname = Dir_FindFile(file, parseIncPath);
1213 if (fullname == NULL)
1214 fullname = Dir_FindFile(file, &dirSearchPath);
1219 * Handle one of the .[-ds]include directives by remembering the current file
1220 * and pushing the included file on the stack. After the included file has
1221 * finished, parsing continues with the including file; see Parse_PushInput
1224 * System includes are looked up in sysIncPath, any other includes are looked
1225 * up in the parsedir and then in the directories specified by the -I command
1229 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
1232 char *fullname; /* full pathname of file */
1235 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1237 if (fullname == NULL && !isSystem)
1238 fullname = FindInQuotPath(file);
1240 if (fullname == NULL) {
1241 SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
1242 ? defSysIncPath : sysIncPath;
1243 fullname = Dir_FindFile(file, path);
1246 if (fullname == NULL) {
1248 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1252 if ((fd = open(fullname, O_RDONLY)) == -1) {
1254 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1259 buf = LoadFile(fullname, fd);
1262 Parse_PushInput(fullname, 1, 0, buf, NULL);
1264 doing_depend = depinc; /* only turn it on */
1268 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
1270 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
1274 Suff_ClearSuffixes();
1280 opts.ignoreErrors = true;
1287 ClearPaths(special, paths);
1291 if (posix_state == PS_NOW_OR_NEVER) {
1293 * With '-r', 'posix.mk' (if it exists)
1294 * can effectively substitute for 'sys.mk',
1295 * otherwise it is an extension.
1297 Global_Set("%POSIX", "1003.2");
1298 IncludeFile("posix.mk", true, false, true);
1308 AddToPaths(const char *dir, SearchPathList *paths)
1310 if (paths != NULL) {
1311 SearchPathListNode *ln;
1312 for (ln = paths->first; ln != NULL; ln = ln->next)
1313 (void)SearchPath_Add(ln->datum, dir);
1318 * If the target was one that doesn't take files as its sources but takes
1319 * something like suffixes, we take each space-separated word on the line as
1320 * a something and deal with it accordingly.
1323 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
1324 SearchPathList *paths)
1328 Suff_AddSuffix(word);
1331 AddToPaths(word, paths);
1334 Suff_AddInclude(word);
1340 Var_ReadOnly(word, false);
1346 Main_SetObjdir(false, "%s", word);
1349 Var_ReadOnly(word, true);
1352 AddToPaths(word, paths);
1360 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
1361 GNodeType *inout_targetAttr,
1362 SearchPathList **inout_paths)
1364 char savec = *nameEnd;
1367 if (!HandleDependencyTarget(name, inout_special,
1368 inout_targetAttr, inout_paths))
1371 if (*inout_special == SP_NOT && *name != '\0')
1372 HandleDependencyTargetMundane(name);
1373 else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
1374 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
1381 ParseDependencyTargets(char **pp,
1383 ParseSpecial *inout_special,
1384 GNodeType *inout_targetAttr,
1385 SearchPathList **inout_paths)
1392 ParseDependencyTargetWord(&p, lstart);
1395 * If the word is followed by a left parenthesis, it's the
1396 * name of one or more files inside an archive.
1398 if (!IsEscaped(lstart, p) && *p == '(') {
1400 if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
1401 Parse_Error(PARSE_FATAL,
1402 "Error in archive specification: \"%s\"",
1410 InvalidLineType(lstart);
1414 if (!ApplyDependencyTarget(tgt, p, inout_special,
1415 inout_targetAttr, inout_paths))
1418 if (*inout_special != SP_NOT && *inout_special != SP_PATH)
1419 SkipExtraTargets(&p, lstart);
1421 pp_skip_whitespace(&p);
1425 if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
1434 ParseDependencySourcesSpecial(char *start,
1435 ParseSpecial special, SearchPathList *paths)
1439 while (*start != '\0') {
1441 while (*end != '\0' && !ch_isspace(*end))
1445 ParseDependencySourceSpecial(special, start, paths);
1449 pp_skip_whitespace(&end);
1455 LinkVarToTargets(VarAssign *var)
1459 for (ln = targets->first; ln != NULL; ln = ln->next)
1460 Parse_Var(var, ln->datum);
1464 ParseDependencySourcesMundane(char *start,
1465 ParseSpecial special, GNodeType targetAttr)
1467 while (*start != '\0') {
1472 * Check for local variable assignment,
1473 * rest of the line is the value.
1475 if (Parse_IsVar(start, &var)) {
1477 * Check if this makefile has disabled
1478 * setting local variables.
1480 bool target_vars = GetBooleanExpr(
1481 "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
1484 LinkVarToTargets(&var);
1491 * The targets take real sources, so we must beware of archive
1492 * specifications (i.e. things with left parentheses in them)
1493 * and handle them accordingly.
1495 for (; *end != '\0' && !ch_isspace(*end); end++) {
1496 if (*end == '(' && end > start && end[-1] != '$') {
1498 * Only stop for a left parenthesis if it
1499 * isn't at the start of a word (that'll be
1500 * for variable changes later) and isn't
1501 * preceded by a dollar sign (a dynamic
1509 GNodeList sources = LST_INIT;
1510 if (!Arch_ParseArchive(&start, &sources,
1512 Parse_Error(PARSE_FATAL,
1513 "Error in source archive spec \"%s\"",
1518 while (!Lst_IsEmpty(&sources)) {
1519 GNode *gn = Lst_Dequeue(&sources);
1520 ApplyDependencySource(targetAttr, gn->name,
1531 ApplyDependencySource(targetAttr, start, special);
1533 pp_skip_whitespace(&end);
1540 * From a dependency line like 'targets: sources', parse the sources.
1542 * See the tests depsrc-*.mk.
1545 ParseDependencySources(char *p, GNodeType targetAttr,
1546 ParseSpecial special, SearchPathList **inout_paths)
1549 HandleDependencySourcesEmpty(special, *inout_paths);
1550 } else if (special == SP_MFLAGS) {
1551 Main_ParseArgLine(p);
1553 } else if (special == SP_SHELL) {
1554 if (!Job_ParseShell(p)) {
1555 Parse_Error(PARSE_FATAL,
1556 "improper shell specification");
1560 } else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
1561 special == SP_DELETE_ON_ERROR) {
1565 /* Now go for the sources. */
1576 ParseDependencySourcesSpecial(p, special, *inout_paths);
1577 if (*inout_paths != NULL) {
1578 Lst_Free(*inout_paths);
1579 *inout_paths = NULL;
1581 if (special == SP_PATH)
1583 if (special == SP_SYSPATH)
1587 assert(*inout_paths == NULL);
1588 if (!ParseDependencySourcesMundane(p, special, targetAttr))
1593 MaybeUpdateMainTarget();
1597 * Parse a dependency line consisting of targets, followed by a dependency
1598 * operator, optionally followed by sources.
1600 * The nodes of the sources are linked as children to the nodes of the
1601 * targets. Nodes are created as necessary.
1603 * The operator is applied to each node in the global 'targets' list,
1604 * which is where the nodes found for the targets are kept.
1606 * The sources are parsed in much the same way as the targets, except
1607 * that they are expanded using the wildcarding scheme of the C-Shell,
1608 * and a target is created for each expanded word. Each of the resulting
1609 * nodes is then linked to each of the targets as one of its children.
1611 * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1612 * specially, see ParseSpecial.
1614 * Transformation rules such as '.c.o' are also handled here, see
1615 * Suff_AddTransform.
1617 * Upon return, the value of the line is unspecified.
1620 ParseDependency(char *line)
1623 SearchPathList *paths; /* search paths to alter when parsing a list
1624 * of .PATH targets */
1625 GNodeType targetAttr; /* from special sources */
1626 ParseSpecial special; /* in special targets, the children are
1627 * linked as children of the parent but not
1631 DEBUG1(PARSE, "ParseDependency(%s)\n", line);
1634 targetAttr = OP_NONE;
1637 if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths))
1640 if (!Lst_IsEmpty(targets))
1641 CheckSpecialMundaneMixture(special);
1643 op = ParseDependencyOp(&p);
1644 if (op == OP_NONE) {
1645 InvalidLineType(line);
1648 ApplyDependencyOperator(op);
1650 pp_skip_whitespace(&p);
1652 ParseDependencySources(p, targetAttr, special, &paths);
1660 * Determine the assignment operator and adjust the end of the variable
1664 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
1670 if (op > name && op[-1] == '+') {
1674 } else if (op > name && op[-1] == '?') {
1678 } else if (op > name && op[-1] == ':') {
1682 } else if (op > name && op[-1] == '!') {
1689 while (op > name && ch_isspace(op[-1]))
1692 if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
1699 va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
1706 * Parse a variable assignment, consisting of a single-word variable name,
1707 * optional whitespace, an assignment operator, optional whitespace and the
1710 * Note: There is a lexical ambiguity with assignment modifier characters
1711 * in variable names. This routine interprets the character before the =
1712 * as a modifier. Therefore, an assignment like
1714 * is interpreted as "C+ +=" instead of "C++ =".
1716 * Used for both lines in a file and command line arguments.
1719 Parse_IsVar(const char *p, VarAssign *out_var)
1721 const char *nameStart, *nameEnd, *firstSpace, *eq;
1724 cpp_skip_hspace(&p); /* Skip to variable name */
1727 * During parsing, the '+' of the operator '+=' is initially parsed
1728 * as part of the variable name. It is later corrected, as is the
1729 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
1730 * determines the actual end of the variable name.
1737 * Scan for one of the assignment operators outside a variable
1740 while (*p != '\0') {
1742 if (ch == '(' || ch == '{') {
1746 if (ch == ')' || ch == '}') {
1754 if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
1756 while (ch == ' ' || ch == '\t')
1762 if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1769 else if (*p == '=' &&
1770 (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
1772 else if (firstSpace != NULL)
1777 nameEnd = firstSpace != NULL ? firstSpace : eq;
1779 cpp_skip_whitespace(&p);
1780 *out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
1788 * Check for syntax errors such as unclosed expressions or unknown modifiers.
1791 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
1794 if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1795 char *expandedValue;
1797 (void)Var_Subst(uvalue, scope, VARE_PARSE_ONLY,
1799 /* TODO: handle errors */
1800 free(expandedValue);
1805 /* Perform a variable assignment that uses the operator ':='. */
1807 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1813 * make sure that we set the variable the first time to nothing
1814 * so that it gets substituted.
1816 * TODO: Add a test that demonstrates why this code is needed,
1817 * apart from making the debug log longer.
1819 * XXX: The variable name is expanded up to 3 times.
1821 if (!Var_ExistsExpand(scope, name))
1822 Var_SetExpand(scope, name, "");
1824 (void)Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF, &evalue);
1825 /* TODO: handle errors */
1827 Var_SetExpand(scope, name, evalue);
1829 *out_avalue = FStr_InitOwn(evalue);
1832 /* Perform a variable assignment that uses the operator '!='. */
1834 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1838 char *output, *error;
1840 cmd = FStr_InitRefer(uvalue);
1841 Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
1843 output = Cmd_Exec(cmd.str, &error);
1844 Var_SetExpand(scope, name, output);
1845 *out_avalue = FStr_InitOwn(output);
1846 if (error != NULL) {
1847 Parse_Error(PARSE_WARNING, "%s", error);
1855 * Perform a variable assignment.
1857 * The actual value of the variable is returned in *out_true_avalue.
1858 * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1861 * Return whether the assignment was actually performed, which is usually
1862 * the case. It is only skipped if the operator is '?=' and the variable
1866 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1867 GNode *scope, FStr *out_true_avalue)
1869 FStr avalue = FStr_InitRefer(uvalue);
1871 if (op == VAR_APPEND)
1872 Var_AppendExpand(scope, name, uvalue);
1873 else if (op == VAR_SUBST)
1874 VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1875 else if (op == VAR_SHELL)
1876 VarAssign_EvalShell(name, uvalue, scope, &avalue);
1878 /* XXX: The variable name is expanded up to 2 times. */
1879 if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1882 /* Normal assignment -- just do it. */
1883 Var_SetExpand(scope, name, uvalue);
1886 *out_true_avalue = avalue;
1891 VarAssignSpecial(const char *name, const char *avalue)
1893 if (strcmp(name, MAKEOVERRIDES) == 0)
1894 Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */
1895 else if (strcmp(name, ".CURDIR") == 0) {
1897 * Someone is being (too?) clever...
1898 * Let's pretend they know what they are doing and
1899 * re-initialize the 'cur' CachedDir.
1901 Dir_InitCur(avalue);
1903 } else if (strcmp(name, MAKE_JOB_PREFIX) == 0)
1905 else if (strcmp(name, MAKE_EXPORTED) == 0)
1906 Var_ExportVars(avalue);
1909 /* Perform the variable assignment in the given scope. */
1911 Parse_Var(VarAssign *var, GNode *scope)
1913 FStr avalue; /* actual value (maybe expanded) */
1915 VarCheckSyntax(var->op, var->value, scope);
1916 if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1917 VarAssignSpecial(var->varname, avalue.str);
1924 * See if the command possibly calls a sub-make by using the variable
1925 * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1928 MaybeSubMake(const char *cmd)
1932 for (start = cmd; *start != '\0'; start++) {
1933 const char *p = start;
1936 /* XXX: What if progname != "make"? */
1937 if (strncmp(p, "make", 4) == 0)
1938 if (start == cmd || !ch_isalnum(p[-1]))
1939 if (!ch_isalnum(p[4]))
1954 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */
1957 if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
1964 * Append the command to the target node.
1966 * The node may be marked as a submake node if the command is determined to
1970 GNode_AddCommand(GNode *gn, char *cmd)
1972 /* Add to last (ie current) cohort for :: targets */
1973 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
1974 gn = gn->cohorts.last->datum;
1976 /* if target already supplied, ignore commands */
1977 if (!(gn->type & OP_HAS_COMMANDS)) {
1978 Lst_Append(&gn->commands, cmd);
1979 if (MaybeSubMake(cmd))
1980 gn->type |= OP_SUBMAKE;
1981 RememberLocation(gn);
1984 /* XXX: We cannot do this until we fix the tree */
1985 Lst_Append(&gn->commands, cmd);
1986 Parse_Error(PARSE_WARNING,
1987 "overriding commands for target \"%s\"; "
1988 "previous commands defined at %s: %u ignored",
1989 gn->name, gn->fname, gn->lineno);
1991 Parse_Error(PARSE_WARNING,
1992 "duplicate script for target \"%s\" ignored",
1994 ParseErrorInternal(gn, PARSE_WARNING,
1995 "using previous script for \"%s\" defined here",
2002 * Add a directory to the path searched for included makefiles bracketed
2006 Parse_AddIncludeDir(const char *dir)
2008 (void)SearchPath_Add(parseIncPath, dir);
2013 * Parse a directive like '.include' or '.-include'.
2015 * .include "user-makefile.mk"
2016 * .include <system-makefile.mk>
2019 ParseInclude(char *directive)
2021 char endc; /* '>' or '"' */
2023 bool silent = directive[0] != 'i';
2026 p = directive + (silent ? 8 : 7);
2029 if (*p != '"' && *p != '<') {
2030 Parse_Error(PARSE_FATAL,
2031 ".include filename must be delimited by '\"' or '<'");
2039 file = FStr_InitRefer(p);
2041 /* Skip to matching delimiter */
2042 while (*p != '\0' && *p != endc)
2046 Parse_Error(PARSE_FATAL,
2047 "Unclosed .include filename. '%c' expected", endc);
2053 Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
2054 IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2059 * Split filename into dirname + basename, then assign these to the
2063 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2065 const char *slash, *basename;
2068 slash = strrchr(filename, '/');
2069 if (slash == NULL) {
2070 dirname = FStr_InitRefer(curdir);
2071 basename = filename;
2073 dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2074 basename = slash + 1;
2077 Global_Set(dirvar, dirname.str);
2078 Global_Set(filevar, basename);
2080 DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2081 dirvar, dirname.str, filevar, basename);
2082 FStr_Done(&dirname);
2086 * Return the immediately including file.
2088 * This is made complicated since the .for loop is implemented as a special
2089 * kind of .include; see For_Run.
2092 GetActuallyIncludingFile(void)
2095 const IncludedFile *incs = GetInclude(0);
2097 for (i = includes.len; i >= 2; i--)
2098 if (incs[i - 1].forLoop == NULL)
2099 return incs[i - 2].name.str;
2103 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2105 SetParseFile(const char *filename)
2107 const char *including;
2109 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2111 including = GetActuallyIncludingFile();
2112 if (including != NULL) {
2113 SetFilenameVars(including,
2114 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2116 Global_Delete(".INCLUDEDFROMDIR");
2117 Global_Delete(".INCLUDEDFROMFILE");
2122 StrContainsWord(const char *str, const char *word)
2124 size_t strLen = strlen(str);
2125 size_t wordLen = strlen(word);
2128 if (strLen < wordLen)
2131 for (p = str; p != NULL; p = strchr(p, ' ')) {
2134 if (p > str + strLen - wordLen)
2137 if (memcmp(p, word, wordLen) == 0 &&
2138 (p[wordLen] == '\0' || p[wordLen] == ' '))
2145 * XXX: Searching through a set of words with this linear search is
2146 * inefficient for variables that contain thousands of words.
2148 * XXX: The paths in this list don't seem to be normalized in any way.
2151 VarContainsWord(const char *varname, const char *word)
2153 FStr val = Var_Value(SCOPE_GLOBAL, varname);
2154 bool found = val.str != NULL && StrContainsWord(val.str, word);
2160 * Track the makefiles we read - so makefiles can set dependencies on them.
2161 * Avoid adding anything more than once.
2163 * Time complexity: O(n) per call, in total O(n^2), where n is the number
2164 * of makefiles that have been loaded.
2167 TrackInput(const char *name)
2169 if (!VarContainsWord(MAKE_MAKEFILES, name))
2170 Global_Append(MAKE_MAKEFILES, name);
2174 /* Parse from the given buffer, later return to the current file. */
2176 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2177 Buffer buf, struct ForLoop *forLoop)
2179 IncludedFile *curFile;
2181 if (forLoop != NULL)
2182 name = CurFile()->name.str;
2186 DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
2187 forLoop != NULL ? ".for loop in": "file", name, lineno);
2189 curFile = Vector_Push(&includes);
2190 curFile->name = FStr_InitOwn(bmake_strdup(name));
2191 curFile->lineno = lineno;
2192 curFile->readLines = readLines;
2193 curFile->forHeadLineno = lineno;
2194 curFile->forBodyReadLines = readLines;
2196 curFile->depending = doing_depend; /* restore this on EOF */
2197 curFile->forLoop = forLoop;
2199 if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2200 abort(); /* see For_Run */
2202 curFile->buf_ptr = curFile->buf.data;
2203 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2204 curFile->condMinDepth = cond_depth;
2208 /* Check if the directive is an include directive. */
2210 IsInclude(const char *dir, bool sysv)
2212 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2215 if (strncmp(dir, "include", 7) != 0)
2218 /* Space is not mandatory for BSD .include */
2219 return !sysv || ch_isspace(dir[7]);
2224 /* Check if the line is a SYSV include directive. */
2226 IsSysVInclude(const char *line)
2230 if (!IsInclude(line, true))
2233 /* Avoid interpreting a dependency line as an include */
2234 for (p = line; (p = strchr(p, ':')) != NULL;) {
2236 /* end of line -> it's a dependency */
2240 /* '::' operator or ': ' -> it's a dependency */
2241 if (*p == ':' || ch_isspace(*p))
2247 /* Push to another file. The line points to the word "include". */
2249 ParseTraditionalInclude(char *line)
2251 char *cp; /* current position in file spec */
2253 bool silent = line[0] != 'i';
2254 char *file = line + (silent ? 8 : 7);
2257 DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2259 pp_skip_whitespace(&file);
2261 (void)Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES, &all_files);
2262 /* TODO: handle errors */
2264 for (file = all_files; !done; file = cp + 1) {
2265 /* Skip to end of line or next whitespace */
2266 for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
2274 IncludeFile(file, false, false, silent);
2282 /* Parse "export <variable>=<value>", and actually export it. */
2284 ParseGmakeExport(char *line)
2286 char *variable = line + 6;
2289 DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2291 pp_skip_whitespace(&variable);
2293 for (value = variable; *value != '\0' && *value != '='; value++)
2296 if (*value != '=') {
2297 Parse_Error(PARSE_FATAL,
2298 "Variable/Value missing from \"export\"");
2301 *value++ = '\0'; /* terminate variable */
2304 * Expand the value before putting it in the environment.
2306 (void)Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES, &value);
2307 /* TODO: handle errors */
2309 setenv(variable, value, 1);
2315 * Called when EOF is reached in the current file. If we were reading an
2316 * include file or a .for loop, the includes stack is popped and things set
2317 * up to go back to reading the previous file at the previous location.
2320 * true to continue parsing, i.e. it had only reached the end of an
2321 * included file, false if the main file has been parsed completely.
2326 IncludedFile *curFile = CurFile();
2328 doing_depend = curFile->depending;
2329 if (curFile->forLoop != NULL &&
2330 For_NextIteration(curFile->forLoop, &curFile->buf)) {
2331 curFile->buf_ptr = curFile->buf.data;
2332 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2333 curFile->readLines = curFile->forBodyReadLines;
2339 FStr_Done(&curFile->name);
2340 Buf_Done(&curFile->buf);
2341 if (curFile->forLoop != NULL)
2342 ForLoop_Free(curFile->forLoop);
2343 Vector_Pop(&includes);
2345 if (includes.len == 0) {
2346 /* We've run out of input */
2347 Global_Delete(".PARSEDIR");
2348 Global_Delete(".PARSEFILE");
2349 Global_Delete(".INCLUDEDFROMDIR");
2350 Global_Delete(".INCLUDEDFROMFILE");
2354 curFile = CurFile();
2355 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
2356 curFile->name.str, curFile->readLines + 1);
2358 SetParseFile(curFile->name.str);
2362 typedef enum ParseRawLineResult {
2366 } ParseRawLineResult;
2369 * Parse until the end of a line, taking into account lines that end with
2370 * backslash-newline. The resulting line goes from out_line to out_line_end;
2371 * the line is not null-terminated.
2373 static ParseRawLineResult
2374 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2375 char **out_firstBackslash, char **out_commentLineEnd)
2377 char *line = curFile->buf_ptr;
2378 char *buf_end = curFile->buf_end;
2380 char *line_end = line;
2381 char *firstBackslash = NULL;
2382 char *commentLineEnd = NULL;
2383 ParseRawLineResult res = PRLR_LINE;
2385 curFile->readLines++;
2396 if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2397 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2401 /* Treat next character after '\' as literal. */
2403 if (firstBackslash == NULL)
2406 curFile->readLines++;
2407 if (p + 2 == buf_end) {
2416 assert(p <= buf_end);
2421 * Remember the first '#' for comment stripping, unless
2422 * the previous char was '[', as in the modifier ':[#]'.
2424 if (ch == '#' && commentLineEnd == NULL &&
2425 !(p > line && p[-1] == '['))
2426 commentLineEnd = line_end;
2432 /* We are not interested in trailing whitespace. */
2433 if (!ch_isspace(ch))
2437 curFile->buf_ptr = p;
2439 *out_line_end = line_end;
2440 *out_firstBackslash = firstBackslash;
2441 *out_commentLineEnd = commentLineEnd;
2446 * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2447 * with a single space.
2450 UnescapeBackslash(char *line, char *start)
2452 const char *src = start;
2454 char *spaceStart = line;
2467 /* Delete '\\' at the end of the buffer. */
2472 /* Delete '\\' from before '#' on non-command lines. */
2473 if (ch == '#' && line[0] != '\t')
2475 else if (ch == '\n') {
2476 cpp_skip_hspace(&src);
2479 /* Leave '\\' in the buffer for later. */
2482 /* Keep an escaped ' ' at the line end. */
2487 /* Delete any trailing spaces - eg from empty continuations */
2488 while (dst > spaceStart && ch_isspace(dst[-1]))
2493 typedef enum LineKind {
2495 * Return the next line that is neither empty nor a comment.
2496 * Backslash line continuations are folded into a single space.
2497 * A trailing comment, if any, is discarded.
2502 * Return the next line, even if it is empty or a comment.
2503 * Preserve backslash-newline to keep the line numbers correct.
2505 * Used in .for loops to collect the body of the loop while waiting
2506 * for the corresponding .endfor.
2511 * Return the next line that starts with a dot.
2512 * Backslash line continuations are folded into a single space.
2513 * A trailing comment, if any, is discarded.
2515 * Used in .if directives to skip over irrelevant branches while
2516 * waiting for the corresponding .endif.
2522 * Return the next "interesting" logical line from the current file. The
2523 * returned string will be freed at the end of including the file.
2526 ReadLowLevelLine(LineKind kind)
2528 IncludedFile *curFile = CurFile();
2529 ParseRawLineResult res;
2532 char *firstBackslash;
2533 char *commentLineEnd;
2536 curFile->lineno = curFile->readLines + 1;
2537 res = ParseRawLine(curFile,
2538 &line, &line_end, &firstBackslash, &commentLineEnd);
2539 if (res == PRLR_ERROR)
2542 if (line == line_end || line == commentLineEnd) {
2543 if (res == PRLR_EOF)
2545 if (kind != LK_FOR_BODY)
2549 /* We now have a line of data */
2550 assert(ch_isspace(*line_end));
2553 if (kind == LK_FOR_BODY)
2554 return line; /* Don't join the physical lines. */
2556 if (kind == LK_DOT && line[0] != '.')
2561 if (commentLineEnd != NULL && line[0] != '\t')
2562 *commentLineEnd = '\0';
2563 if (firstBackslash != NULL)
2564 UnescapeBackslash(line, firstBackslash);
2569 SkipIrrelevantBranches(void)
2573 while ((line = ReadLowLevelLine(LK_DOT)) != NULL) {
2574 if (Cond_EvalLine(line) == CR_TRUE)
2577 * TODO: Check for typos in .elif directives such as .elsif
2580 * This check will probably duplicate some of the code in
2581 * ParseLine. Most of the code there cannot apply, only
2582 * ParseVarassign and ParseDependencyLine can, and to prevent
2583 * code duplication, these would need to be called with a
2584 * flag called onlyCheckSyntax.
2586 * See directive-elif.mk for details.
2594 ParseForLoop(const char *line)
2597 unsigned forHeadLineno;
2598 unsigned bodyReadLines;
2601 rval = For_Eval(line);
2603 return false; /* Not a .for line */
2605 return true; /* Syntax error - error printed, ignore line */
2607 forHeadLineno = CurFile()->lineno;
2608 bodyReadLines = CurFile()->readLines;
2610 /* Accumulate the loop body until the matching '.endfor'. */
2613 line = ReadLowLevelLine(LK_FOR_BODY);
2615 Parse_Error(PARSE_FATAL,
2616 "Unexpected end of file in .for loop");
2619 } while (For_Accum(line, &forLevel));
2621 For_Run(forHeadLineno, bodyReadLines);
2626 * Read an entire line from the input file.
2628 * Empty lines, .if and .for are completely handled by this function,
2629 * leaving only variable assignments, other directives, dependency lines
2630 * and shell commands to the caller.
2632 * Return a line without trailing whitespace, or NULL for EOF. The returned
2633 * string will be freed at the end of including the file.
2636 ReadHighLevelLine(void)
2641 line = ReadLowLevelLine(LK_NONEMPTY);
2642 if (posix_state == PS_MAYBE_NEXT_LINE)
2643 posix_state = PS_NOW_OR_NEVER;
2645 posix_state = PS_TOO_LATE;
2652 switch (Cond_EvalLine(line)) {
2653 case CR_FALSE: /* May also mean a syntax error. */
2654 if (!SkipIrrelevantBranches())
2659 case CR_ERROR: /* Not a conditional line */
2660 if (ParseForLoop(line))
2669 FinishDependencyGroup(void)
2673 if (targets == NULL)
2676 for (ln = targets->first; ln != NULL; ln = ln->next) {
2677 GNode *gn = ln->datum;
2679 Suff_EndTransform(gn);
2682 * Mark the target as already having commands if it does, to
2683 * keep from having shell commands on multiple dependency
2686 if (!Lst_IsEmpty(&gn->commands))
2687 gn->type |= OP_HAS_COMMANDS;
2694 /* Add the command to each target from the current dependency spec. */
2696 ParseLine_ShellCommand(const char *p)
2698 cpp_skip_whitespace(&p);
2700 return; /* skip empty commands */
2702 if (targets == NULL) {
2703 Parse_Error(PARSE_FATAL,
2704 "Unassociated shell command \"%s\"", p);
2709 char *cmd = bmake_strdup(p);
2712 for (ln = targets->first; ln != NULL; ln = ln->next) {
2713 GNode *gn = ln->datum;
2714 GNode_AddCommand(gn, cmd);
2717 Lst_Append(&targCmds, cmd);
2725 IncludedFile *curFile = CurFile();
2727 if (curFile->forLoop != NULL) {
2728 /* pretend we reached EOF */
2729 For_Break(curFile->forLoop);
2730 cond_depth = CurFile_CondMinDepth();
2733 Parse_Error(PARSE_FATAL, "break outside of for loop");
2737 * See if the line starts with one of the known directives, and if so, handle
2741 ParseDirective(char *line)
2743 char *cp = line + 1;
2747 pp_skip_whitespace(&cp);
2748 if (IsInclude(cp, false)) {
2754 while (ch_islower(*cp) || *cp == '-')
2758 if (*cp != '\0' && !ch_isspace(*cp))
2761 pp_skip_whitespace(&cp);
2764 if (Substring_Equals(dir, "break"))
2766 else if (Substring_Equals(dir, "undef"))
2768 else if (Substring_Equals(dir, "export"))
2769 Var_Export(VEM_PLAIN, arg);
2770 else if (Substring_Equals(dir, "export-env"))
2771 Var_Export(VEM_ENV, arg);
2772 else if (Substring_Equals(dir, "export-literal"))
2773 Var_Export(VEM_LITERAL, arg);
2774 else if (Substring_Equals(dir, "unexport"))
2775 Var_UnExport(false, arg);
2776 else if (Substring_Equals(dir, "unexport-env"))
2777 Var_UnExport(true, arg);
2778 else if (Substring_Equals(dir, "info"))
2779 HandleMessage(PARSE_INFO, "info", arg);
2780 else if (Substring_Equals(dir, "warning"))
2781 HandleMessage(PARSE_WARNING, "warning", arg);
2782 else if (Substring_Equals(dir, "error"))
2783 HandleMessage(PARSE_FATAL, "error", arg);
2790 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2794 if (!Parse_IsVar(line, &var))
2796 if (finishDependencyGroup)
2797 FinishDependencyGroup();
2798 Parse_Var(&var, scope);
2804 FindSemicolon(char *p)
2808 for (; *p != '\0'; p++) {
2809 if (*p == '\\' && p[1] != '\0') {
2814 if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2816 else if (level > 0 && (*p == ')' || *p == '}'))
2818 else if (level == 0 && *p == ';')
2825 * dependency -> [target...] op [source...] [';' command]
2826 * op -> ':' | '::' | '!'
2829 ParseDependencyLine(char *line)
2832 char *expanded_line;
2833 const char *shellcmd = NULL;
2836 * For some reason - probably to make the parser impossible -
2837 * a ';' can be used to separate commands from dependencies.
2838 * Attempt to skip over ';' inside substitution patterns.
2841 char *semicolon = FindSemicolon(line);
2842 if (*semicolon != '\0') {
2843 /* Terminate the dependency list at the ';' */
2845 shellcmd = semicolon + 1;
2850 * We now know it's a dependency line so it needs to have all
2851 * variables expanded before being parsed.
2853 * XXX: Ideally the dependency line would first be split into
2854 * its left-hand side, dependency operator and right-hand side,
2855 * and then each side would be expanded on its own. This would
2856 * allow for the left-hand side to allow only defined variables
2857 * and to allow variables on the right-hand side to be undefined
2860 * Parsing the line first would also prevent that targets
2861 * generated from variable expressions are interpreted as the
2862 * dependency operator, such as in "target${:U\:} middle: source",
2863 * in which the middle is interpreted as a source, not a target.
2867 * In lint mode, allow undefined variables to appear in dependency
2870 * Ideally, only the right-hand side would allow undefined variables
2871 * since it is common to have optional dependencies. Having undefined
2872 * variables on the left-hand side is more unusual though. Since
2873 * both sides are expanded in a single pass, there is not much choice
2876 * In normal mode, it does not matter whether undefined variables are
2877 * allowed or not since as of 2020-09-14, Var_Parse does not print
2878 * any parse errors in such a case. It simply returns the special
2879 * empty string var_Error, which cannot be detected in the result of
2882 emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
2883 (void)Var_Subst(line, SCOPE_CMDLINE, emode, &expanded_line);
2884 /* TODO: handle errors */
2886 /* Need a fresh list for the target nodes */
2887 if (targets != NULL)
2889 targets = Lst_New();
2891 ParseDependency(expanded_line);
2892 free(expanded_line);
2894 if (shellcmd != NULL)
2895 ParseLine_ShellCommand(shellcmd);
2899 ParseLine(char *line)
2902 * Lines that begin with '.' can be pretty much anything:
2903 * - directives like '.include' or '.if',
2904 * - suffix rules like '.c.o:',
2905 * - dependencies for filenames that start with '.',
2906 * - variable assignments like '.tmp=value'.
2908 if (line[0] == '.' && ParseDirective(line))
2911 if (line[0] == '\t') {
2912 ParseLine_ShellCommand(line + 1);
2917 if (IsSysVInclude(line)) {
2919 * It's an S3/S5-style "include".
2921 ParseTraditionalInclude(line);
2927 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
2928 strchr(line, ':') == NULL) {
2930 * It's a Gmake "export".
2932 ParseGmakeExport(line);
2937 if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
2940 FinishDependencyGroup();
2942 ParseDependencyLine(line);
2946 * Parse a top-level makefile, incorporating its content into the global
2950 Parse_File(const char *name, int fd)
2955 buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
2959 assert(targets == NULL);
2961 Parse_PushInput(name, 1, 0, buf, NULL);
2964 while ((line = ReadHighLevelLine()) != NULL) {
2965 DEBUG2(PARSE, "Parsing line %u: %s\n",
2966 CurFile()->lineno, line);
2969 /* Reached EOF, but it may be just EOF of an include file. */
2970 } while (ParseEOF());
2972 FinishDependencyGroup();
2974 if (parseErrors != 0) {
2975 (void)fflush(stdout);
2976 (void)fprintf(stderr,
2977 "%s: Fatal errors encountered -- cannot continue\n",
2979 PrintOnError(NULL, "");
2984 /* Initialize the parsing module. */
2989 parseIncPath = SearchPath_New();
2990 sysIncPath = SearchPath_New();
2991 defSysIncPath = SearchPath_New();
2992 Vector_Init(&includes, sizeof(IncludedFile));
2995 /* Clean up the parsing module. */
3000 Lst_DoneCall(&targCmds, free);
3001 assert(targets == NULL);
3002 SearchPath_Free(defSysIncPath);
3003 SearchPath_Free(sysIncPath);
3004 SearchPath_Free(parseIncPath);
3005 assert(includes.len == 0);
3006 Vector_Done(&includes);
3012 * Return a list containing the single main target to create.
3013 * If no such target exists, we Punt with an obnoxious error message.
3016 Parse_MainName(GNodeList *mainList)
3018 if (mainNode == NULL)
3019 Punt("no target to make.");
3021 Lst_Append(mainList, mainNode);
3022 if (mainNode->type & OP_DOUBLEDEP)
3023 Lst_AppendAll(mainList, &mainNode->cohorts);
3025 Global_Append(".TARGETS", mainNode->name);
3029 Parse_NumErrors(void)