1 /* $NetBSD: parse.c,v 1.704 2023/06/23 06:08:56 rillig 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 Populate the list of targets 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.704 2023/06/23 06:08:56 rillig Exp $");
126 /* Detects a multiple-inclusion guard in a makefile. */
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 */
137 typedef struct IncludedFile {
138 FStr name; /* absolute or relative to the cwd */
139 unsigned lineno; /* 1-based */
140 unsigned readLines; /* the number of physical lines that have
141 * been read from the file */
142 unsigned forHeadLineno; /* 1-based */
143 unsigned forBodyReadLines; /* the number of physical lines that have
144 * been read from the file above the body of
146 unsigned int condMinDepth; /* depth of nested 'if' directives, at the
147 * beginning of the file */
148 bool depending; /* state of doing_depend on EOF */
150 Buffer buf; /* the file's content or the body of the .for
151 * loop; either empty or ends with '\n' */
152 char *buf_ptr; /* next char to be read from buf */
153 char *buf_end; /* buf_end[-1] == '\n' */
155 GuardState guardState;
158 struct ForLoop *forLoop;
161 /* Special attributes for target nodes. */
162 typedef enum ParseSpecial {
163 SP_ATTRIBUTE, /* Generic attribute */
164 SP_BEGIN, /* .BEGIN */
165 SP_DEFAULT, /* .DEFAULT */
166 SP_DELETE_ON_ERROR, /* .DELETE_ON_ERROR */
168 SP_ERROR, /* .ERROR */
169 SP_IGNORE, /* .IGNORE */
170 SP_INCLUDES, /* .INCLUDES; not mentioned in the manual page */
171 SP_INTERRUPT, /* .INTERRUPT */
172 SP_LIBS, /* .LIBS; not mentioned in the manual page */
173 SP_MAIN, /* .MAIN and no user-specified targets to make */
175 SP_MFLAGS, /* .MFLAGS or .MAKEFLAGS */
176 SP_NOMETA, /* .NOMETA */
177 SP_NOMETA_CMP, /* .NOMETA_CMP */
178 SP_NOPATH, /* .NOPATH */
179 SP_NOREADONLY, /* .NOREADONLY */
180 SP_NOT, /* Not special */
181 SP_NOTPARALLEL, /* .NOTPARALLEL or .NO_PARALLEL */
182 SP_NULL, /* .NULL; not mentioned in the manual page */
183 SP_OBJDIR, /* .OBJDIR */
184 SP_ORDER, /* .ORDER */
185 SP_PARALLEL, /* .PARALLEL; not mentioned in the manual page */
186 SP_PATH, /* .PATH or .PATH.suffix */
187 SP_PHONY, /* .PHONY */
189 SP_POSIX, /* .POSIX; not mentioned in the manual page */
191 SP_PRECIOUS, /* .PRECIOUS */
192 SP_READONLY, /* .READONLY */
193 SP_SHELL, /* .SHELL */
194 SP_SILENT, /* .SILENT */
195 SP_SINGLESHELL, /* .SINGLESHELL; not mentioned in the manual page */
196 SP_STALE, /* .STALE */
197 SP_SUFFIXES, /* .SUFFIXES */
198 SP_SYSPATH, /* .SYSPATH */
202 typedef List SearchPathList;
203 typedef ListNode SearchPathListNode;
206 typedef enum VarAssignOp {
209 VAR_DEFAULT, /* ?= */
211 VAR_SHELL /* != or :sh= */
214 typedef struct VarAssign {
215 char *varname; /* unexpanded */
217 const char *value; /* unexpanded */
220 static bool Parse_IsVar(const char *, VarAssign *);
221 static void Parse_Var(VarAssign *, GNode *);
224 * The target to be made if no targets are specified in the command line.
225 * This is the first target defined in any of the makefiles.
230 * During parsing, the targets from the left-hand side of the currently
231 * active dependency line, or NULL if the current line does not belong to a
232 * dependency line, for example because it is a variable assignment.
234 * See unit-tests/deptgt.mk, keyword "parse.c:targets".
236 static GNodeList *targets;
240 * All shell commands for all targets, in no particular order and possibly
241 * with duplicates. Kept in a separate list since the commands from .USE or
242 * .USEBEFORE nodes are shared with other GNodes, thereby giving up the
243 * easily understandable ownership over the allocated strings.
245 static StringList targCmds = LST_INIT;
249 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
250 * is seen, then set to each successive source on the line.
252 static GNode *order_pred;
254 static int parseErrors = 0;
257 * The include chain of makefiles. At index 0 is the top-level makefile from
258 * the command line, followed by the included files or .for loops, up to and
259 * including the current file.
261 * See PrintStackTrace for how to interpret the data.
263 static Vector /* of IncludedFile */ includes;
265 SearchPath *parseIncPath; /* directories for "..." includes */
266 SearchPath *sysIncPath; /* directories for <...> includes */
267 SearchPath *defSysIncPath; /* default for sysIncPath */
270 * The parseKeywords table is searched using binary search when deciding
271 * if a target or source is special.
273 static const struct {
275 ParseSpecial special; /* when used as a target */
276 GNodeType targetAttr; /* when used as a source */
277 } parseKeywords[] = {
278 { ".BEGIN", SP_BEGIN, OP_NONE },
279 { ".DEFAULT", SP_DEFAULT, OP_NONE },
280 { ".DELETE_ON_ERROR", SP_DELETE_ON_ERROR, OP_NONE },
281 { ".END", SP_END, OP_NONE },
282 { ".ERROR", SP_ERROR, OP_NONE },
283 { ".EXEC", SP_ATTRIBUTE, OP_EXEC },
284 { ".IGNORE", SP_IGNORE, OP_IGNORE },
285 { ".INCLUDES", SP_INCLUDES, OP_NONE },
286 { ".INTERRUPT", SP_INTERRUPT, OP_NONE },
287 { ".INVISIBLE", SP_ATTRIBUTE, OP_INVISIBLE },
288 { ".JOIN", SP_ATTRIBUTE, OP_JOIN },
289 { ".LIBS", SP_LIBS, OP_NONE },
290 { ".MADE", SP_ATTRIBUTE, OP_MADE },
291 { ".MAIN", SP_MAIN, OP_NONE },
292 { ".MAKE", SP_ATTRIBUTE, OP_MAKE },
293 { ".MAKEFLAGS", SP_MFLAGS, OP_NONE },
294 { ".META", SP_META, OP_META },
295 { ".MFLAGS", SP_MFLAGS, OP_NONE },
296 { ".NOMETA", SP_NOMETA, OP_NOMETA },
297 { ".NOMETA_CMP", SP_NOMETA_CMP, OP_NOMETA_CMP },
298 { ".NOPATH", SP_NOPATH, OP_NOPATH },
299 { ".NOREADONLY", SP_NOREADONLY, OP_NONE },
300 { ".NOTMAIN", SP_ATTRIBUTE, OP_NOTMAIN },
301 { ".NOTPARALLEL", SP_NOTPARALLEL, OP_NONE },
302 { ".NO_PARALLEL", SP_NOTPARALLEL, OP_NONE },
303 { ".NULL", SP_NULL, OP_NONE },
304 { ".OBJDIR", SP_OBJDIR, OP_NONE },
305 { ".OPTIONAL", SP_ATTRIBUTE, OP_OPTIONAL },
306 { ".ORDER", SP_ORDER, OP_NONE },
307 { ".PARALLEL", SP_PARALLEL, OP_NONE },
308 { ".PATH", SP_PATH, OP_NONE },
309 { ".PHONY", SP_PHONY, OP_PHONY },
311 { ".POSIX", SP_POSIX, OP_NONE },
313 { ".PRECIOUS", SP_PRECIOUS, OP_PRECIOUS },
314 { ".READONLY", SP_READONLY, OP_NONE },
315 { ".RECURSIVE", SP_ATTRIBUTE, OP_MAKE },
316 { ".SHELL", SP_SHELL, OP_NONE },
317 { ".SILENT", SP_SILENT, OP_SILENT },
318 { ".SINGLESHELL", SP_SINGLESHELL, OP_NONE },
319 { ".STALE", SP_STALE, OP_NONE },
320 { ".SUFFIXES", SP_SUFFIXES, OP_NONE },
321 { ".SYSPATH", SP_SYSPATH, OP_NONE },
322 { ".USE", SP_ATTRIBUTE, OP_USE },
323 { ".USEBEFORE", SP_ATTRIBUTE, OP_USEBEFORE },
324 { ".WAIT", SP_WAIT, OP_NONE },
327 enum PosixState posix_state = PS_NOT_YET;
329 static HashTable /* full file name -> Guard */ guards;
331 static IncludedFile *
334 assert(i < includes.len);
335 return Vector_Get(&includes, i);
338 /* The makefile that is currently being read. */
339 static IncludedFile *
342 return GetInclude(includes.len - 1);
346 CurFile_CondMinDepth(void)
348 return CurFile()->condMinDepth;
352 LoadFile(const char *path, int fd)
359 bufSize = fstat(fd, &st) == 0 && S_ISREG(st.st_mode) &&
360 st.st_size > 0 && st.st_size < 1024 * 1024 * 1024
361 ? (size_t)st.st_size : 1024;
362 Buf_InitSize(&buf, bufSize);
365 if (buf.len == buf.cap) {
366 if (buf.cap >= 512 * 1024 * 1024) {
367 Error("%s: file too large", path);
368 exit(2); /* Not 1 so -q can distinguish error */
372 assert(buf.len < buf.cap);
373 n = read(fd, buf.data + buf.len, buf.cap - buf.len);
375 Error("%s: read error: %s", path, strerror(errno));
376 exit(2); /* Not 1 so -q can distinguish error */
381 buf.len += (size_t)n;
383 assert(buf.len <= buf.cap);
385 if (!Buf_EndsWith(&buf, '\n'))
386 Buf_AddByte(&buf, '\n');
388 return buf; /* may not be null-terminated */
392 * Print the current chain of .include and .for directives. In Parse_Fatal
393 * or other functions that already print the location, includingInnermost
394 * would be redundant, but in other cases like Error or Fatal it needs to be
398 PrintStackTrace(bool includingInnermost)
400 const IncludedFile *entries;
407 entries = GetInclude(0);
408 if (!includingInnermost && entries[n - 1].forLoop == NULL)
409 n--; /* already in the diagnostic */
411 for (i = n; i-- > 0;) {
412 const IncludedFile *entry = entries + i;
413 const char *fname = entry->name.str;
414 char dirbuf[MAXPATHLEN + 1];
416 if (fname[0] != '/' && strcmp(fname, "(stdin)") != 0) {
417 const char *realPath = realpath(fname, dirbuf);
418 if (realPath != NULL)
422 if (entry->forLoop != NULL) {
423 char *details = ForLoop_Details(entry->forLoop);
424 debug_printf("\tin .for loop from %s:%u with %s\n",
425 fname, entry->forHeadLineno, details);
427 } else if (i + 1 < n && entries[i + 1].forLoop != NULL) {
428 /* entry->lineno is not a useful line number */
430 debug_printf("\tin %s:%u\n", fname, entry->lineno);
434 /* Check if the current character is escaped on the current line. */
436 IsEscaped(const char *line, const char *p)
438 bool escaped = false;
439 while (p > line && *--p == '\\')
445 * Add the filename and lineno to the GNode so that we remember where its
446 * last command was added or where it was mentioned in a .depend file.
449 RememberLocation(GNode *gn)
451 IncludedFile *curFile = CurFile();
452 gn->fname = Str_Intern(curFile->name.str);
453 gn->lineno = curFile->lineno;
457 * Look in the table of keywords for one matching the given string.
458 * Return the index of the keyword, or -1 if it isn't there.
461 FindKeyword(const char *str)
464 int end = sizeof parseKeywords / sizeof parseKeywords[0] - 1;
466 while (start <= end) {
467 int curr = start + (end - start) / 2;
468 int diff = strcmp(str, parseKeywords[curr].name);
482 PrintLocation(FILE *f, bool useVars, const GNode *gn)
484 char dirbuf[MAXPATHLEN + 1];
492 } else if (includes.len > 0) {
493 IncludedFile *curFile = CurFile();
494 fname = curFile->name.str;
495 lineno = curFile->lineno;
499 if (!useVars || fname[0] == '/' || strcmp(fname, "(stdin)") == 0) {
500 (void)fprintf(f, "\"%s\" line %u: ", fname, lineno);
504 dir = Var_Value(SCOPE_GLOBAL, ".PARSEDIR");
507 if (dir.str[0] != '/')
508 dir.str = realpath(dir.str, dirbuf);
510 base = Var_Value(SCOPE_GLOBAL, ".PARSEFILE");
511 if (base.str == NULL)
512 base.str = str_basename(fname);
514 (void)fprintf(f, "\"%s/%s\" line %u: ", dir.str, base.str, lineno);
520 static void MAKE_ATTR_PRINTFLIKE(5, 0)
521 ParseVErrorInternal(FILE *f, bool useVars, const GNode *gn,
522 ParseErrorLevel level, const char *fmt, va_list ap)
524 static bool fatal_warning_error_printed = false;
526 (void)fprintf(f, "%s: ", progname);
528 PrintLocation(f, useVars, gn);
529 if (level == PARSE_WARNING)
530 (void)fprintf(f, "warning: ");
531 (void)vfprintf(f, fmt, ap);
532 (void)fprintf(f, "\n");
535 if (level == PARSE_FATAL)
537 if (level == PARSE_WARNING && opts.parseWarnFatal) {
538 if (!fatal_warning_error_printed) {
539 Error("parsing warnings being treated as errors");
540 fatal_warning_error_printed = true;
546 PrintStackTrace(false);
549 static void MAKE_ATTR_PRINTFLIKE(3, 4)
550 ParseErrorInternal(const GNode *gn,
551 ParseErrorLevel level, const char *fmt, ...)
555 (void)fflush(stdout);
557 ParseVErrorInternal(stderr, false, gn, level, fmt, ap);
560 if (opts.debug_file != stdout && opts.debug_file != stderr) {
562 ParseVErrorInternal(opts.debug_file, false, gn,
569 * Print a parse error message, including location information.
571 * If the level is PARSE_FATAL, continue parsing until the end of the
572 * current top-level makefile, then exit (see Parse_File).
574 * Fmt is given without a trailing newline.
577 Parse_Error(ParseErrorLevel level, const char *fmt, ...)
581 (void)fflush(stdout);
583 ParseVErrorInternal(stderr, true, NULL, level, fmt, ap);
586 if (opts.debug_file != stdout && opts.debug_file != stderr) {
588 ParseVErrorInternal(opts.debug_file, true, NULL,
596 * Handle an .info, .warning or .error directive. For an .error directive,
600 HandleMessage(ParseErrorLevel level, const char *levelName, const char *umsg)
604 if (umsg[0] == '\0') {
605 Parse_Error(PARSE_FATAL, "Missing argument for \".%s\"",
610 xmsg = Var_Subst(umsg, SCOPE_CMDLINE, VARE_WANTRES);
611 /* TODO: handle errors */
613 Parse_Error(level, "%s", xmsg);
616 if (level == PARSE_FATAL) {
617 PrintOnError(NULL, "\n");
623 * Add the child to the parent's children, and for non-special targets, vice
624 * versa. Special targets such as .END do not need to be informed once the
625 * child target has been made.
628 LinkSource(GNode *pgn, GNode *cgn, bool isSpecial)
630 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&pgn->cohorts))
631 pgn = pgn->cohorts.last->datum;
633 Lst_Append(&pgn->children, cgn);
636 /* Special targets like .END don't need any children. */
638 Lst_Append(&cgn->parents, pgn);
641 debug_printf("# LinkSource: added child %s - %s\n",
642 pgn->name, cgn->name);
643 Targ_PrintNode(pgn, 0);
644 Targ_PrintNode(cgn, 0);
648 /* Add the node to each target from the current dependency group. */
650 LinkToTargets(GNode *gn, bool isSpecial)
654 for (ln = targets->first; ln != NULL; ln = ln->next)
655 LinkSource(ln->datum, gn, isSpecial);
659 TryApplyDependencyOperator(GNode *gn, GNodeType op)
662 * If the node occurred on the left-hand side of a dependency and the
663 * operator also defines a dependency, they must match.
665 if ((op & OP_OPMASK) && (gn->type & OP_OPMASK) &&
666 ((op & OP_OPMASK) != (gn->type & OP_OPMASK))) {
667 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
672 if (op == OP_DOUBLEDEP && (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
674 * If the node was on the left-hand side of a '::' operator,
675 * we need to create a new instance of it for the children
676 * and commands on this dependency line since each of these
677 * dependency groups has its own attributes and commands,
678 * separate from the others.
680 * The new instance is placed on the 'cohorts' list of the
681 * initial one (note the initial one is not on its own
682 * cohorts list) and the new instance is linked to all
683 * parents of the initial instance.
688 * Propagate copied bits to the initial node. They'll be
689 * propagated back to the rest of the cohorts later.
691 gn->type |= op & (unsigned)~OP_OPMASK;
693 cohort = Targ_NewInternalNode(gn->name);
695 RememberLocation(cohort);
697 * Make the cohort invisible as well to avoid duplicating it
698 * into other variables. True, parents of this target won't
699 * tend to do anything with their local variables, but better
702 * (I think this is pointless now, since the relevant list
703 * traversals will no longer see this node anyway. -mycroft)
705 cohort->type = op | OP_INVISIBLE;
706 Lst_Append(&gn->cohorts, cohort);
707 cohort->centurion = gn;
708 gn->unmade_cohorts++;
709 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
710 (unsigned int)gn->unmade_cohorts % 1000000);
713 * We don't want to nuke any previous flags (whatever they
714 * were) so we just OR the new operator into the old.
723 ApplyDependencyOperator(GNodeType op)
727 for (ln = targets->first; ln != NULL; ln = ln->next)
728 if (!TryApplyDependencyOperator(ln->datum, op))
733 * We add a .WAIT node in the dependency list. After any dynamic dependencies
734 * (and filename globbing) have happened, it is given a dependency on each
735 * previous child, back until the previous .WAIT node. The next child won't
736 * be scheduled until the .WAIT node is built.
738 * We give each .WAIT node a unique name (mainly for diagnostics).
741 ApplyDependencySourceWait(bool isSpecial)
743 static unsigned wait_number = 0;
744 char name[6 + 10 + 1];
747 snprintf(name, sizeof name, ".WAIT_%u", ++wait_number);
748 gn = Targ_NewInternalNode(name);
750 RememberLocation(gn);
751 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
752 LinkToTargets(gn, isSpecial);
756 ApplyDependencySourceKeyword(const char *src, ParseSpecial special)
759 GNodeType targetAttr;
761 if (*src != '.' || !ch_isupper(src[1]))
764 keywd = FindKeyword(src);
768 targetAttr = parseKeywords[keywd].targetAttr;
769 if (targetAttr != OP_NONE) {
770 ApplyDependencyOperator(targetAttr);
773 if (parseKeywords[keywd].special == SP_WAIT) {
774 ApplyDependencySourceWait(special != SP_NOT);
781 * In a line like ".MAIN: source1 source2", add all sources to the list of
782 * things to create, but only if the user didn't specify a target on the
783 * command line and .MAIN occurs for the first time.
785 * See HandleDependencyTargetSpecial, branch SP_MAIN.
786 * See unit-tests/cond-func-make-main.mk.
789 ApplyDependencySourceMain(const char *src)
791 Lst_Append(&opts.create, bmake_strdup(src));
793 * Add the name to the .TARGETS variable as well, so the user can
794 * employ that, if desired.
796 Global_Append(".TARGETS", src);
800 * For the sources of a .ORDER target, create predecessor/successor links
801 * between the previous source and the current one.
804 ApplyDependencySourceOrder(const char *src)
808 gn = Targ_GetNode(src);
810 RememberLocation(gn);
811 if (order_pred != NULL) {
812 Lst_Append(&order_pred->order_succ, gn);
813 Lst_Append(&gn->order_pred, order_pred);
816 "# .ORDER forces '%s' to be made before '%s'\n",
817 order_pred->name, gn->name);
818 Targ_PrintNode(order_pred, 0);
819 Targ_PrintNode(gn, 0);
823 * The current source now becomes the predecessor for the next one.
828 /* The source is not an attribute, so find/create a node for it. */
830 ApplyDependencySourceOther(const char *src, GNodeType targetAttr,
831 ParseSpecial special)
835 gn = Targ_GetNode(src);
837 RememberLocation(gn);
838 if (targetAttr != OP_NONE)
839 gn->type |= targetAttr;
841 LinkToTargets(gn, special != SP_NOT);
845 * Given the name of a source in a dependency line, figure out if it is an
846 * attribute (such as .SILENT) and if so, apply it to all targets. Otherwise
847 * decide if there is some attribute which should be applied *to* the source
848 * because of some special target (such as .PHONY) and apply it if so.
849 * Otherwise, make the source a child of the targets.
852 ApplyDependencySource(GNodeType targetAttr, const char *src,
853 ParseSpecial special)
855 if (ApplyDependencySourceKeyword(src, special))
858 if (special == SP_MAIN)
859 ApplyDependencySourceMain(src);
860 else if (special == SP_ORDER)
861 ApplyDependencySourceOrder(src);
863 ApplyDependencySourceOther(src, targetAttr, special);
867 * If we have yet to decide on a main target to make, in the absence of any
868 * user input, we want the first target on the first dependency line that is
869 * actually a real target (i.e. isn't a .USE or .EXEC rule) to be made.
872 MaybeUpdateMainTarget(void)
876 if (mainNode != NULL)
879 for (ln = targets->first; ln != NULL; ln = ln->next) {
880 GNode *gn = ln->datum;
881 if (GNode_IsMainCandidate(gn)) {
882 DEBUG1(MAKE, "Setting main node to \"%s\"\n", gn->name);
890 InvalidLineType(const char *line)
892 if (strncmp(line, "<<<<<<", 6) == 0 ||
893 strncmp(line, ">>>>>>", 6) == 0)
894 Parse_Error(PARSE_FATAL,
895 "Makefile appears to contain unresolved CVS/RCS/??? merge conflicts");
896 else if (line[0] == '.') {
897 const char *dirstart = line + 1;
899 cpp_skip_whitespace(&dirstart);
901 while (ch_isalnum(*dirend) || *dirend == '-')
903 Parse_Error(PARSE_FATAL, "Unknown directive \"%.*s\"",
904 (int)(dirend - dirstart), dirstart);
906 Parse_Error(PARSE_FATAL, "Invalid line type");
910 ParseDependencyTargetWord(char **pp, const char *lstart)
912 const char *cp = *pp;
914 while (*cp != '\0') {
915 if ((ch_isspace(*cp) || *cp == '!' || *cp == ':' ||
917 !IsEscaped(lstart, cp))
922 * Must be a dynamic source (would have been expanded
925 * There should be no errors in this, as they would
926 * have been discovered in the initial Var_Subst and
927 * we wouldn't be here.
929 FStr val = Var_Parse(&cp, SCOPE_CMDLINE,
940 * Handle special targets like .PATH, .DEFAULT, .BEGIN, .ORDER.
942 * See the tests deptgt-*.mk.
945 HandleDependencyTargetSpecial(const char *targetName,
946 ParseSpecial *inout_special,
947 SearchPathList **inout_paths)
949 switch (*inout_special) {
951 if (*inout_paths == NULL)
952 *inout_paths = Lst_New();
953 Lst_Append(*inout_paths, &dirSearchPath);
956 if (*inout_paths == NULL)
957 *inout_paths = Lst_New();
958 Lst_Append(*inout_paths, sysIncPath);
962 * Allow targets from the command line to override the
965 if (!Lst_IsEmpty(&opts.create))
966 *inout_special = SP_NOT;
973 GNode *gn = Targ_GetNode(targetName);
975 RememberLocation(gn);
976 gn->type |= OP_NOTMAIN | OP_SPECIAL;
977 Lst_Append(targets, gn);
982 * Need to create a node to hang commands on, but we don't
983 * want it in the graph, nor do we want it to be the Main
984 * Target. We claim the node is a transformation rule to make
985 * life easier later, when we'll use Make_HandleUse to
986 * actually apply the .DEFAULT commands.
988 GNode *gn = GNode_New(".DEFAULT");
989 gn->type |= OP_NOTMAIN | OP_TRANSFORM;
990 Lst_Append(targets, gn);
994 case SP_DELETE_ON_ERROR:
995 deleteOnError = true;
1000 case SP_SINGLESHELL:
1001 opts.compatMake = true;
1012 HandleDependencyTargetPath(const char *suffixName,
1013 SearchPathList **inout_paths)
1017 path = Suff_GetPath(suffixName);
1019 Parse_Error(PARSE_FATAL,
1020 "Suffix '%s' not defined (yet)", suffixName);
1024 if (*inout_paths == NULL)
1025 *inout_paths = Lst_New();
1026 Lst_Append(*inout_paths, path);
1031 /* See if it's a special target and if so set inout_special to match it. */
1033 HandleDependencyTarget(const char *targetName,
1034 ParseSpecial *inout_special,
1035 GNodeType *inout_targetAttr,
1036 SearchPathList **inout_paths)
1040 if (!(targetName[0] == '.' && ch_isupper(targetName[1])))
1044 * See if the target is a special target that must have it
1045 * or its sources handled specially.
1047 keywd = FindKeyword(targetName);
1049 if (*inout_special == SP_PATH &&
1050 parseKeywords[keywd].special != SP_PATH) {
1051 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1055 *inout_special = parseKeywords[keywd].special;
1056 *inout_targetAttr = parseKeywords[keywd].targetAttr;
1058 HandleDependencyTargetSpecial(targetName, inout_special,
1061 } else if (strncmp(targetName, ".PATH", 5) == 0) {
1062 *inout_special = SP_PATH;
1063 if (!HandleDependencyTargetPath(targetName + 5, inout_paths))
1070 HandleSingleDependencyTargetMundane(const char *name)
1072 GNode *gn = Suff_IsTransform(name)
1073 ? Suff_AddTransform(name)
1074 : Targ_GetNode(name);
1076 RememberLocation(gn);
1078 Lst_Append(targets, gn);
1082 HandleDependencyTargetMundane(const char *targetName)
1084 if (Dir_HasWildcards(targetName)) {
1085 StringList targetNames = LST_INIT;
1087 SearchPath *emptyPath = SearchPath_New();
1088 SearchPath_Expand(emptyPath, targetName, &targetNames);
1089 SearchPath_Free(emptyPath);
1091 while (!Lst_IsEmpty(&targetNames)) {
1092 char *targName = Lst_Dequeue(&targetNames);
1093 HandleSingleDependencyTargetMundane(targName);
1097 HandleSingleDependencyTargetMundane(targetName);
1101 SkipExtraTargets(char **pp, const char *lstart)
1103 bool warning = false;
1104 const char *p = *pp;
1106 while (*p != '\0') {
1107 if (!IsEscaped(lstart, p) && (*p == '!' || *p == ':'))
1109 if (IsEscaped(lstart, p) || (*p != ' ' && *p != '\t'))
1114 const char *start = *pp;
1115 cpp_skip_whitespace(&start);
1116 Parse_Error(PARSE_WARNING, "Extra target '%.*s' ignored",
1117 (int)(p - start), start);
1124 CheckSpecialMundaneMixture(ParseSpecial special)
1134 * These create nodes on which to hang commands, so targets
1135 * shouldn't be empty.
1138 /* Nothing special here -- targets may be empty. */
1141 Parse_Error(PARSE_WARNING,
1142 "Special and mundane targets don't mix. "
1143 "Mundane ones ignored");
1149 * In a dependency line like 'targets: sources' or 'targets! sources', parse
1150 * the operator ':', '::' or '!' from between the targets and the sources.
1153 ParseDependencyOp(char **pp)
1156 return (*pp)++, OP_FORCE;
1157 if (**pp == ':' && (*pp)[1] == ':')
1158 return *pp += 2, OP_DOUBLEDEP;
1159 else if (**pp == ':')
1160 return (*pp)++, OP_DEPENDS;
1166 ClearPaths(ParseSpecial special, SearchPathList *paths)
1168 if (paths != NULL) {
1169 SearchPathListNode *ln;
1170 for (ln = paths->first; ln != NULL; ln = ln->next)
1171 SearchPath_Clear(ln->datum);
1173 if (special == SP_SYSPATH)
1180 FindInDirOfIncludingFile(const char *file)
1182 char *fullname, *incdir, *slash, *newName;
1186 incdir = bmake_strdup(CurFile()->name.str);
1187 slash = strrchr(incdir, '/');
1188 if (slash != NULL) {
1191 * Now do lexical processing of leading "../" on the
1194 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1195 slash = strrchr(incdir + 1, '/');
1196 if (slash == NULL || strcmp(slash, "/..") == 0)
1200 newName = str_concat3(incdir, "/", file + i);
1201 fullname = Dir_FindFile(newName, parseIncPath);
1202 if (fullname == NULL)
1203 fullname = Dir_FindFile(newName, &dirSearchPath);
1211 FindInQuotPath(const char *file)
1214 SearchPath *suffPath;
1217 fullname = FindInDirOfIncludingFile(file);
1218 if (fullname == NULL &&
1219 (suff = strrchr(file, '.')) != NULL &&
1220 (suffPath = Suff_GetPath(suff)) != NULL)
1221 fullname = Dir_FindFile(file, suffPath);
1222 if (fullname == NULL)
1223 fullname = Dir_FindFile(file, parseIncPath);
1224 if (fullname == NULL)
1225 fullname = Dir_FindFile(file, &dirSearchPath);
1230 SkipGuarded(const char *fullname)
1232 Guard *guard = HashTable_FindValue(&guards, fullname);
1233 if (guard != NULL && guard->kind == GK_VARIABLE
1234 && GNode_ValueDirect(SCOPE_GLOBAL, guard->name) != NULL)
1236 if (guard != NULL && guard->kind == GK_TARGET
1237 && Targ_FindNode(guard->name) != NULL)
1242 DEBUG2(PARSE, "Skipping '%s' because '%s' is defined\n",
1243 fullname, guard->name);
1248 * Handle one of the .[-ds]include directives by remembering the current file
1249 * and pushing the included file on the stack. After the included file has
1250 * finished, parsing continues with the including file; see Parse_PushInput
1253 * System includes are looked up in sysIncPath, any other includes are looked
1254 * up in the parsedir and then in the directories specified by the -I command
1258 IncludeFile(const char *file, bool isSystem, bool depinc, bool silent)
1261 char *fullname; /* full pathname of file */
1264 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1266 if (fullname == NULL && !isSystem)
1267 fullname = FindInQuotPath(file);
1269 if (fullname == NULL) {
1270 SearchPath *path = Lst_IsEmpty(&sysIncPath->dirs)
1271 ? defSysIncPath : sysIncPath;
1272 fullname = Dir_FindFile(file, path);
1275 if (fullname == NULL) {
1277 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1281 if (SkipGuarded(fullname))
1284 if ((fd = open(fullname, O_RDONLY)) == -1) {
1286 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1291 buf = LoadFile(fullname, fd);
1294 Parse_PushInput(fullname, 1, 0, buf, NULL);
1296 doing_depend = depinc; /* only turn it on */
1300 /* Handle a "dependency" line like '.SPECIAL:' without any sources. */
1302 HandleDependencySourcesEmpty(ParseSpecial special, SearchPathList *paths)
1306 Suff_ClearSuffixes();
1312 opts.ignoreErrors = true;
1319 ClearPaths(special, paths);
1323 if (posix_state == PS_NOW_OR_NEVER) {
1325 * With '-r', 'posix.mk' (if it exists)
1326 * can effectively substitute for 'sys.mk',
1327 * otherwise it is an extension.
1329 Global_Set("%POSIX", "1003.2");
1330 IncludeFile("posix.mk", true, false, true);
1340 AddToPaths(const char *dir, SearchPathList *paths)
1342 if (paths != NULL) {
1343 SearchPathListNode *ln;
1344 for (ln = paths->first; ln != NULL; ln = ln->next)
1345 (void)SearchPath_Add(ln->datum, dir);
1350 * If the target was one that doesn't take files as its sources but takes
1351 * something like suffixes, we take each space-separated word on the line as
1352 * a something and deal with it accordingly.
1355 ParseDependencySourceSpecial(ParseSpecial special, const char *word,
1356 SearchPathList *paths)
1360 Suff_AddSuffix(word);
1363 AddToPaths(word, paths);
1366 Suff_AddInclude(word);
1372 Var_ReadOnly(word, false);
1378 Main_SetObjdir(false, "%s", word);
1381 Var_ReadOnly(word, true);
1384 AddToPaths(word, paths);
1392 ApplyDependencyTarget(char *name, char *nameEnd, ParseSpecial *inout_special,
1393 GNodeType *inout_targetAttr,
1394 SearchPathList **inout_paths)
1396 char savec = *nameEnd;
1399 if (!HandleDependencyTarget(name, inout_special,
1400 inout_targetAttr, inout_paths))
1403 if (*inout_special == SP_NOT && *name != '\0')
1404 HandleDependencyTargetMundane(name);
1405 else if (*inout_special == SP_PATH && *name != '.' && *name != '\0')
1406 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", name);
1413 ParseDependencyTargets(char **pp,
1415 ParseSpecial *inout_special,
1416 GNodeType *inout_targetAttr,
1417 SearchPathList **inout_paths)
1424 ParseDependencyTargetWord(&p, lstart);
1427 * If the word is followed by a left parenthesis, it's the
1428 * name of one or more files inside an archive.
1430 if (!IsEscaped(lstart, p) && *p == '(') {
1432 if (!Arch_ParseArchive(&p, targets, SCOPE_CMDLINE)) {
1433 Parse_Error(PARSE_FATAL,
1434 "Error in archive specification: \"%s\"",
1442 InvalidLineType(lstart);
1446 if (!ApplyDependencyTarget(tgt, p, inout_special,
1447 inout_targetAttr, inout_paths))
1450 if (*inout_special != SP_NOT && *inout_special != SP_PATH)
1451 SkipExtraTargets(&p, lstart);
1453 pp_skip_whitespace(&p);
1457 if ((*p == '!' || *p == ':') && !IsEscaped(lstart, p))
1466 ParseDependencySourcesSpecial(char *start,
1467 ParseSpecial special, SearchPathList *paths)
1471 while (*start != '\0') {
1473 while (*end != '\0' && !ch_isspace(*end))
1477 ParseDependencySourceSpecial(special, start, paths);
1481 pp_skip_whitespace(&end);
1487 LinkVarToTargets(VarAssign *var)
1491 for (ln = targets->first; ln != NULL; ln = ln->next)
1492 Parse_Var(var, ln->datum);
1496 ParseDependencySourcesMundane(char *start,
1497 ParseSpecial special, GNodeType targetAttr)
1499 while (*start != '\0') {
1504 * Check for local variable assignment,
1505 * rest of the line is the value.
1507 if (Parse_IsVar(start, &var)) {
1509 * Check if this makefile has disabled
1510 * setting local variables.
1512 bool target_vars = GetBooleanExpr(
1513 "${.MAKE.TARGET_LOCAL_VARIABLES}", true);
1516 LinkVarToTargets(&var);
1523 * The targets take real sources, so we must beware of archive
1524 * specifications (i.e. things with left parentheses in them)
1525 * and handle them accordingly.
1527 for (; *end != '\0' && !ch_isspace(*end); end++) {
1528 if (*end == '(' && end > start && end[-1] != '$') {
1530 * Only stop for a left parenthesis if it
1531 * isn't at the start of a word (that'll be
1532 * for variable changes later) and isn't
1533 * preceded by a dollar sign (a dynamic
1541 GNodeList sources = LST_INIT;
1542 if (!Arch_ParseArchive(&start, &sources,
1544 Parse_Error(PARSE_FATAL,
1545 "Error in source archive spec \"%s\"",
1550 while (!Lst_IsEmpty(&sources)) {
1551 GNode *gn = Lst_Dequeue(&sources);
1552 ApplyDependencySource(targetAttr, gn->name,
1563 ApplyDependencySource(targetAttr, start, special);
1565 pp_skip_whitespace(&end);
1572 * From a dependency line like 'targets: sources', parse the sources.
1574 * See the tests depsrc-*.mk.
1577 ParseDependencySources(char *p, GNodeType targetAttr,
1578 ParseSpecial special, SearchPathList **inout_paths)
1581 HandleDependencySourcesEmpty(special, *inout_paths);
1582 } else if (special == SP_MFLAGS) {
1583 Main_ParseArgLine(p);
1585 } else if (special == SP_SHELL) {
1586 if (!Job_ParseShell(p)) {
1587 Parse_Error(PARSE_FATAL,
1588 "improper shell specification");
1592 } else if (special == SP_NOTPARALLEL || special == SP_SINGLESHELL ||
1593 special == SP_DELETE_ON_ERROR) {
1597 /* Now go for the sources. */
1608 ParseDependencySourcesSpecial(p, special, *inout_paths);
1609 if (*inout_paths != NULL) {
1610 Lst_Free(*inout_paths);
1611 *inout_paths = NULL;
1613 if (special == SP_PATH)
1615 if (special == SP_SYSPATH)
1619 assert(*inout_paths == NULL);
1620 if (!ParseDependencySourcesMundane(p, special, targetAttr))
1625 MaybeUpdateMainTarget();
1629 * Parse a dependency line consisting of targets, followed by a dependency
1630 * operator, optionally followed by sources.
1632 * The nodes of the sources are linked as children to the nodes of the
1633 * targets. Nodes are created as necessary.
1635 * The operator is applied to each node in the global 'targets' list,
1636 * which is where the nodes found for the targets are kept.
1638 * The sources are parsed in much the same way as the targets, except
1639 * that they are expanded using the wildcarding scheme of the C-Shell,
1640 * and a target is created for each expanded word. Each of the resulting
1641 * nodes is then linked to each of the targets as one of its children.
1643 * Certain targets and sources such as .PHONY or .PRECIOUS are handled
1644 * specially, see ParseSpecial.
1646 * Transformation rules such as '.c.o' are also handled here, see
1647 * Suff_AddTransform.
1649 * Upon return, the value of the line is unspecified.
1652 ParseDependency(char *line)
1655 SearchPathList *paths; /* search paths to alter when parsing a list
1656 * of .PATH targets */
1657 GNodeType targetAttr; /* from special sources */
1658 ParseSpecial special; /* in special targets, the children are
1659 * linked as children of the parent but not
1663 DEBUG1(PARSE, "ParseDependency(%s)\n", line);
1666 targetAttr = OP_NONE;
1669 if (!ParseDependencyTargets(&p, line, &special, &targetAttr, &paths))
1672 if (!Lst_IsEmpty(targets))
1673 CheckSpecialMundaneMixture(special);
1675 op = ParseDependencyOp(&p);
1676 if (op == OP_NONE) {
1677 InvalidLineType(line);
1680 ApplyDependencyOperator(op);
1682 pp_skip_whitespace(&p);
1684 ParseDependencySources(p, targetAttr, special, &paths);
1692 * Determine the assignment operator and adjust the end of the variable
1696 AdjustVarassignOp(const char *name, const char *nameEnd, const char *op,
1702 if (op > name && op[-1] == '+') {
1706 } else if (op > name && op[-1] == '?') {
1710 } else if (op > name && op[-1] == ':') {
1714 } else if (op > name && op[-1] == '!') {
1721 while (op > name && ch_isspace(op[-1]))
1724 if (op - name >= 3 && memcmp(op - 3, ":sh", 3) == 0) {
1731 va.varname = bmake_strsedup(name, nameEnd < op ? nameEnd : op);
1738 * Parse a variable assignment, consisting of a single-word variable name,
1739 * optional whitespace, an assignment operator, optional whitespace and the
1742 * Note: There is a lexical ambiguity with assignment modifier characters
1743 * in variable names. This routine interprets the character before the =
1744 * as a modifier. Therefore, an assignment like
1746 * is interpreted as "C+ +=" instead of "C++ =".
1748 * Used for both lines in a file and command line arguments.
1751 Parse_IsVar(const char *p, VarAssign *out_var)
1753 const char *nameStart, *nameEnd, *firstSpace, *eq;
1756 cpp_skip_hspace(&p); /* Skip to variable name */
1759 * During parsing, the '+' of the operator '+=' is initially parsed
1760 * as part of the variable name. It is later corrected, as is the
1761 * ':sh' modifier. Of these two (nameEnd and eq), the earlier one
1762 * determines the actual end of the variable name.
1769 * Scan for one of the assignment operators outside a variable
1772 while (*p != '\0') {
1774 if (ch == '(' || ch == '{') {
1778 if (ch == ')' || ch == '}') {
1786 if ((ch == ' ' || ch == '\t') && firstSpace == NULL)
1788 while (ch == ' ' || ch == '\t')
1794 if (ch == ':' && p[0] == 's' && p[1] == 'h') {
1801 else if (*p == '=' &&
1802 (ch == '+' || ch == ':' || ch == '?' || ch == '!'))
1804 else if (firstSpace != NULL)
1809 nameEnd = firstSpace != NULL ? firstSpace : eq;
1811 cpp_skip_whitespace(&p);
1812 *out_var = AdjustVarassignOp(nameStart, nameEnd, eq, p);
1820 * Check for syntax errors such as unclosed expressions or unknown modifiers.
1823 VarCheckSyntax(VarAssignOp type, const char *uvalue, GNode *scope)
1826 if (type != VAR_SUBST && strchr(uvalue, '$') != NULL) {
1827 char *expandedValue = Var_Subst(uvalue,
1828 scope, VARE_PARSE_ONLY);
1829 /* TODO: handle errors */
1830 free(expandedValue);
1835 /* Perform a variable assignment that uses the operator ':='. */
1837 VarAssign_EvalSubst(GNode *scope, const char *name, const char *uvalue,
1843 * make sure that we set the variable the first time to nothing
1844 * so that it gets substituted.
1846 * TODO: Add a test that demonstrates why this code is needed,
1847 * apart from making the debug log longer.
1849 * XXX: The variable name is expanded up to 3 times.
1851 if (!Var_ExistsExpand(scope, name))
1852 Var_SetExpand(scope, name, "");
1854 evalue = Var_Subst(uvalue, scope, VARE_KEEP_DOLLAR_UNDEF);
1855 /* TODO: handle errors */
1857 Var_SetExpand(scope, name, evalue);
1859 *out_avalue = FStr_InitOwn(evalue);
1862 /* Perform a variable assignment that uses the operator '!='. */
1864 VarAssign_EvalShell(const char *name, const char *uvalue, GNode *scope,
1868 char *output, *error;
1870 cmd = FStr_InitRefer(uvalue);
1871 Var_Expand(&cmd, SCOPE_CMDLINE, VARE_UNDEFERR);
1873 output = Cmd_Exec(cmd.str, &error);
1874 Var_SetExpand(scope, name, output);
1875 *out_avalue = FStr_InitOwn(output);
1876 if (error != NULL) {
1877 Parse_Error(PARSE_WARNING, "%s", error);
1885 * Perform a variable assignment.
1887 * The actual value of the variable is returned in *out_true_avalue.
1888 * Especially for VAR_SUBST and VAR_SHELL this can differ from the literal
1891 * Return whether the assignment was actually performed, which is usually
1892 * the case. It is only skipped if the operator is '?=' and the variable
1896 VarAssign_Eval(const char *name, VarAssignOp op, const char *uvalue,
1897 GNode *scope, FStr *out_true_avalue)
1899 FStr avalue = FStr_InitRefer(uvalue);
1901 if (op == VAR_APPEND)
1902 Var_AppendExpand(scope, name, uvalue);
1903 else if (op == VAR_SUBST)
1904 VarAssign_EvalSubst(scope, name, uvalue, &avalue);
1905 else if (op == VAR_SHELL)
1906 VarAssign_EvalShell(name, uvalue, scope, &avalue);
1908 /* XXX: The variable name is expanded up to 2 times. */
1909 if (op == VAR_DEFAULT && Var_ExistsExpand(scope, name))
1912 /* Normal assignment -- just do it. */
1913 Var_SetExpand(scope, name, uvalue);
1916 *out_true_avalue = avalue;
1921 VarAssignSpecial(const char *name, const char *avalue)
1923 if (strcmp(name, ".MAKEOVERRIDES") == 0)
1924 Main_ExportMAKEFLAGS(false); /* re-export MAKEFLAGS */
1925 else if (strcmp(name, ".CURDIR") == 0) {
1927 * Someone is being (too?) clever...
1928 * Let's pretend they know what they are doing and
1929 * re-initialize the 'cur' CachedDir.
1931 Dir_InitCur(avalue);
1933 } else if (strcmp(name, ".MAKE.JOB.PREFIX") == 0)
1935 else if (strcmp(name, ".MAKE.EXPORTED") == 0)
1936 Var_ExportVars(avalue);
1939 /* Perform the variable assignment in the given scope. */
1941 Parse_Var(VarAssign *var, GNode *scope)
1943 FStr avalue; /* actual value (maybe expanded) */
1945 VarCheckSyntax(var->op, var->value, scope);
1946 if (VarAssign_Eval(var->varname, var->op, var->value, scope, &avalue)) {
1947 VarAssignSpecial(var->varname, avalue.str);
1954 * See if the command possibly calls a sub-make by using the variable
1955 * expressions ${.MAKE}, ${MAKE} or the plain word "make".
1958 MaybeSubMake(const char *cmd)
1962 for (start = cmd; *start != '\0'; start++) {
1963 const char *p = start;
1966 /* XXX: What if progname != "make"? */
1967 if (strncmp(p, "make", 4) == 0)
1968 if (start == cmd || !ch_isalnum(p[-1]))
1969 if (!ch_isalnum(p[4]))
1984 if (*p == '.') /* Accept either ${.MAKE} or ${MAKE}. */
1987 if (strncmp(p, "MAKE", 4) == 0 && p[4] == endc)
1994 * Append the command to the target node.
1996 * The node may be marked as a submake node if the command is determined to
2000 GNode_AddCommand(GNode *gn, char *cmd)
2002 /* Add to last (ie current) cohort for :: targets */
2003 if ((gn->type & OP_DOUBLEDEP) && gn->cohorts.last != NULL)
2004 gn = gn->cohorts.last->datum;
2006 /* if target already supplied, ignore commands */
2007 if (!(gn->type & OP_HAS_COMMANDS)) {
2008 Lst_Append(&gn->commands, cmd);
2009 if (MaybeSubMake(cmd))
2010 gn->type |= OP_SUBMAKE;
2011 RememberLocation(gn);
2014 /* XXX: We cannot do this until we fix the tree */
2015 Lst_Append(&gn->commands, cmd);
2016 Parse_Error(PARSE_WARNING,
2017 "overriding commands for target \"%s\"; "
2018 "previous commands defined at %s: %u ignored",
2019 gn->name, gn->fname, gn->lineno);
2021 Parse_Error(PARSE_WARNING,
2022 "duplicate script for target \"%s\" ignored",
2024 ParseErrorInternal(gn, PARSE_WARNING,
2025 "using previous script for \"%s\" defined here",
2032 * Add a directory to the path searched for included makefiles bracketed
2036 Parse_AddIncludeDir(const char *dir)
2038 (void)SearchPath_Add(parseIncPath, dir);
2043 * Parse a directive like '.include' or '.-include'.
2045 * .include "user-makefile.mk"
2046 * .include <system-makefile.mk>
2049 ParseInclude(char *directive)
2051 char endc; /* '>' or '"' */
2053 bool silent = directive[0] != 'i';
2056 p = directive + (silent ? 8 : 7);
2059 if (*p != '"' && *p != '<') {
2060 Parse_Error(PARSE_FATAL,
2061 ".include filename must be delimited by '\"' or '<'");
2069 file = FStr_InitRefer(p);
2071 /* Skip to matching delimiter */
2072 while (*p != '\0' && *p != endc)
2076 Parse_Error(PARSE_FATAL,
2077 "Unclosed .include filename. '%c' expected", endc);
2083 Var_Expand(&file, SCOPE_CMDLINE, VARE_WANTRES);
2084 IncludeFile(file.str, endc == '>', directive[0] == 'd', silent);
2089 * Split filename into dirname + basename, then assign these to the
2093 SetFilenameVars(const char *filename, const char *dirvar, const char *filevar)
2095 const char *slash, *basename;
2098 slash = strrchr(filename, '/');
2099 if (slash == NULL) {
2100 dirname = FStr_InitRefer(curdir);
2101 basename = filename;
2103 dirname = FStr_InitOwn(bmake_strsedup(filename, slash));
2104 basename = slash + 1;
2107 Global_Set(dirvar, dirname.str);
2108 Global_Set(filevar, basename);
2110 DEBUG4(PARSE, "SetFilenameVars: ${%s} = `%s' ${%s} = `%s'\n",
2111 dirvar, dirname.str, filevar, basename);
2112 FStr_Done(&dirname);
2116 * Return the immediately including file.
2118 * This is made complicated since the .for loop is implemented as a special
2119 * kind of .include; see For_Run.
2122 GetActuallyIncludingFile(void)
2125 const IncludedFile *incs = GetInclude(0);
2127 for (i = includes.len; i >= 2; i--)
2128 if (incs[i - 1].forLoop == NULL)
2129 return incs[i - 2].name.str;
2133 /* Set .PARSEDIR, .PARSEFILE, .INCLUDEDFROMDIR and .INCLUDEDFROMFILE. */
2135 SetParseFile(const char *filename)
2137 const char *including;
2139 SetFilenameVars(filename, ".PARSEDIR", ".PARSEFILE");
2141 including = GetActuallyIncludingFile();
2142 if (including != NULL) {
2143 SetFilenameVars(including,
2144 ".INCLUDEDFROMDIR", ".INCLUDEDFROMFILE");
2146 Global_Delete(".INCLUDEDFROMDIR");
2147 Global_Delete(".INCLUDEDFROMFILE");
2152 StrContainsWord(const char *str, const char *word)
2154 size_t strLen = strlen(str);
2155 size_t wordLen = strlen(word);
2158 if (strLen < wordLen)
2161 for (p = str; p != NULL; p = strchr(p, ' ')) {
2164 if (p > str + strLen - wordLen)
2167 if (memcmp(p, word, wordLen) == 0 &&
2168 (p[wordLen] == '\0' || p[wordLen] == ' '))
2175 * XXX: Searching through a set of words with this linear search is
2176 * inefficient for variables that contain thousands of words.
2178 * XXX: The paths in this list don't seem to be normalized in any way.
2181 VarContainsWord(const char *varname, const char *word)
2183 FStr val = Var_Value(SCOPE_GLOBAL, varname);
2184 bool found = val.str != NULL && StrContainsWord(val.str, word);
2190 * Track the makefiles we read - so makefiles can set dependencies on them.
2191 * Avoid adding anything more than once.
2193 * Time complexity: O(n) per call, in total O(n^2), where n is the number
2194 * of makefiles that have been loaded.
2197 TrackInput(const char *name)
2199 if (!VarContainsWord(".MAKE.MAKEFILES", name))
2200 Global_Append(".MAKE.MAKEFILES", name);
2204 /* Parse from the given buffer, later return to the current file. */
2206 Parse_PushInput(const char *name, unsigned lineno, unsigned readLines,
2207 Buffer buf, struct ForLoop *forLoop)
2209 IncludedFile *curFile;
2211 if (forLoop != NULL)
2212 name = CurFile()->name.str;
2216 DEBUG3(PARSE, "Parse_PushInput: %s %s, line %u\n",
2217 forLoop != NULL ? ".for loop in": "file", name, lineno);
2219 curFile = Vector_Push(&includes);
2220 curFile->name = FStr_InitOwn(bmake_strdup(name));
2221 curFile->lineno = lineno;
2222 curFile->readLines = readLines;
2223 curFile->forHeadLineno = lineno;
2224 curFile->forBodyReadLines = readLines;
2226 curFile->depending = doing_depend; /* restore this on EOF */
2227 curFile->guardState = forLoop == NULL ? GS_START : GS_NO;
2228 curFile->guard = NULL;
2229 curFile->forLoop = forLoop;
2231 if (forLoop != NULL && !For_NextIteration(forLoop, &curFile->buf))
2232 abort(); /* see For_Run */
2234 curFile->buf_ptr = curFile->buf.data;
2235 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2236 curFile->condMinDepth = cond_depth;
2240 /* Check if the directive is an include directive. */
2242 IsInclude(const char *dir, bool sysv)
2244 if (dir[0] == 's' || dir[0] == '-' || (dir[0] == 'd' && !sysv))
2247 if (strncmp(dir, "include", 7) != 0)
2250 /* Space is not mandatory for BSD .include */
2251 return !sysv || ch_isspace(dir[7]);
2256 /* Check if the line is a SYSV include directive. */
2258 IsSysVInclude(const char *line)
2262 if (!IsInclude(line, true))
2265 /* Avoid interpreting a dependency line as an include */
2266 for (p = line; (p = strchr(p, ':')) != NULL;) {
2268 /* end of line -> it's a dependency */
2272 /* '::' operator or ': ' -> it's a dependency */
2273 if (*p == ':' || ch_isspace(*p))
2279 /* Push to another file. The line points to the word "include". */
2281 ParseTraditionalInclude(char *line)
2283 char *cp; /* current position in file spec */
2285 bool silent = line[0] != 'i';
2286 char *file = line + (silent ? 8 : 7);
2289 DEBUG1(PARSE, "ParseTraditionalInclude: %s\n", file);
2291 pp_skip_whitespace(&file);
2293 all_files = Var_Subst(file, SCOPE_CMDLINE, VARE_WANTRES);
2294 /* TODO: handle errors */
2296 for (file = all_files; !done; file = cp + 1) {
2297 /* Skip to end of line or next whitespace */
2298 for (cp = file; *cp != '\0' && !ch_isspace(*cp); cp++)
2306 IncludeFile(file, false, false, silent);
2314 /* Parse "export <variable>=<value>", and actually export it. */
2316 ParseGmakeExport(char *line)
2318 char *variable = line + 6;
2321 DEBUG1(PARSE, "ParseGmakeExport: %s\n", variable);
2323 pp_skip_whitespace(&variable);
2325 for (value = variable; *value != '\0' && *value != '='; value++)
2328 if (*value != '=') {
2329 Parse_Error(PARSE_FATAL,
2330 "Variable/Value missing from \"export\"");
2333 *value++ = '\0'; /* terminate variable */
2336 * Expand the value before putting it in the environment.
2338 value = Var_Subst(value, SCOPE_CMDLINE, VARE_WANTRES);
2339 /* TODO: handle errors */
2341 setenv(variable, value, 1);
2347 * Called when EOF is reached in the current file. If we were reading an
2348 * include file or a .for loop, the includes stack is popped and things set
2349 * up to go back to reading the previous file at the previous location.
2352 * true to continue parsing, i.e. it had only reached the end of an
2353 * included file, false if the main file has been parsed completely.
2358 IncludedFile *curFile = CurFile();
2360 doing_depend = curFile->depending;
2361 if (curFile->forLoop != NULL &&
2362 For_NextIteration(curFile->forLoop, &curFile->buf)) {
2363 curFile->buf_ptr = curFile->buf.data;
2364 curFile->buf_end = curFile->buf.data + curFile->buf.len;
2365 curFile->readLines = curFile->forBodyReadLines;
2371 if (curFile->guardState == GS_DONE)
2372 HashTable_Set(&guards, curFile->name.str, curFile->guard);
2373 else if (curFile->guard != NULL) {
2374 free(curFile->guard->name);
2375 free(curFile->guard);
2378 FStr_Done(&curFile->name);
2379 Buf_Done(&curFile->buf);
2380 if (curFile->forLoop != NULL)
2381 ForLoop_Free(curFile->forLoop);
2382 Vector_Pop(&includes);
2384 if (includes.len == 0) {
2385 /* We've run out of input */
2386 Global_Delete(".PARSEDIR");
2387 Global_Delete(".PARSEFILE");
2388 Global_Delete(".INCLUDEDFROMDIR");
2389 Global_Delete(".INCLUDEDFROMFILE");
2393 curFile = CurFile();
2394 DEBUG2(PARSE, "ParseEOF: returning to file %s, line %u\n",
2395 curFile->name.str, curFile->readLines + 1);
2397 SetParseFile(curFile->name.str);
2401 typedef enum ParseRawLineResult {
2405 } ParseRawLineResult;
2408 * Parse until the end of a line, taking into account lines that end with
2409 * backslash-newline. The resulting line goes from out_line to out_line_end;
2410 * the line is not null-terminated.
2412 static ParseRawLineResult
2413 ParseRawLine(IncludedFile *curFile, char **out_line, char **out_line_end,
2414 char **out_firstBackslash, char **out_commentLineEnd)
2416 char *line = curFile->buf_ptr;
2417 char *buf_end = curFile->buf_end;
2419 char *line_end = line;
2420 char *firstBackslash = NULL;
2421 char *commentLineEnd = NULL;
2422 ParseRawLineResult res = PRLR_LINE;
2424 curFile->readLines++;
2435 if (ch == '\0' || (ch == '\\' && p[1] == '\0')) {
2436 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2440 /* Treat next character after '\' as literal. */
2442 if (firstBackslash == NULL)
2445 curFile->readLines++;
2446 if (p + 2 == buf_end) {
2455 assert(p <= buf_end);
2460 * Remember the first '#' for comment stripping, unless
2461 * the previous char was '[', as in the modifier ':[#]'.
2463 if (ch == '#' && commentLineEnd == NULL &&
2464 !(p > line && p[-1] == '['))
2465 commentLineEnd = line_end;
2471 /* We are not interested in trailing whitespace. */
2472 if (!ch_isspace(ch))
2476 curFile->buf_ptr = p;
2478 *out_line_end = line_end;
2479 *out_firstBackslash = firstBackslash;
2480 *out_commentLineEnd = commentLineEnd;
2485 * Beginning at start, unescape '\#' to '#' and replace backslash-newline
2486 * with a single space.
2489 UnescapeBackslash(char *line, char *start)
2491 const char *src = start;
2493 char *spaceStart = line;
2506 /* Delete '\\' at the end of the buffer. */
2511 /* Delete '\\' from before '#' on non-command lines. */
2512 if (ch == '#' && line[0] != '\t')
2514 else if (ch == '\n') {
2515 cpp_skip_hspace(&src);
2518 /* Leave '\\' in the buffer for later. */
2521 /* Keep an escaped ' ' at the line end. */
2526 /* Delete any trailing spaces - eg from empty continuations */
2527 while (dst > spaceStart && ch_isspace(dst[-1]))
2532 typedef enum LineKind {
2534 * Return the next line that is neither empty nor a comment.
2535 * Backslash line continuations are folded into a single space.
2536 * A trailing comment, if any, is discarded.
2541 * Return the next line, even if it is empty or a comment.
2542 * Preserve backslash-newline to keep the line numbers correct.
2544 * Used in .for loops to collect the body of the loop while waiting
2545 * for the corresponding .endfor.
2550 * Return the next line that starts with a dot.
2551 * Backslash line continuations are folded into a single space.
2552 * A trailing comment, if any, is discarded.
2554 * Used in .if directives to skip over irrelevant branches while
2555 * waiting for the corresponding .endif.
2561 * Return the next "interesting" logical line from the current file. The
2562 * returned string will be freed at the end of including the file.
2565 ReadLowLevelLine(LineKind kind)
2567 IncludedFile *curFile = CurFile();
2568 ParseRawLineResult res;
2571 char *firstBackslash;
2572 char *commentLineEnd;
2575 curFile->lineno = curFile->readLines + 1;
2576 res = ParseRawLine(curFile,
2577 &line, &line_end, &firstBackslash, &commentLineEnd);
2578 if (res == PRLR_ERROR)
2581 if (line == line_end || line == commentLineEnd) {
2582 if (res == PRLR_EOF)
2584 if (kind != LK_FOR_BODY)
2588 /* We now have a line of data */
2589 assert(ch_isspace(*line_end));
2592 if (kind == LK_FOR_BODY)
2593 return line; /* Don't join the physical lines. */
2595 if (kind == LK_DOT && line[0] != '.')
2600 if (commentLineEnd != NULL && line[0] != '\t')
2601 *commentLineEnd = '\0';
2602 if (firstBackslash != NULL)
2603 UnescapeBackslash(line, firstBackslash);
2608 SkipIrrelevantBranches(void)
2612 while ((line = ReadLowLevelLine(LK_DOT)) != NULL) {
2613 if (Cond_EvalLine(line) == CR_TRUE)
2616 * TODO: Check for typos in .elif directives such as .elsif
2619 * This check will probably duplicate some of the code in
2620 * ParseLine. Most of the code there cannot apply, only
2621 * ParseVarassign and ParseDependencyLine can, and to prevent
2622 * code duplication, these would need to be called with a
2623 * flag called onlyCheckSyntax.
2625 * See directive-elif.mk for details.
2633 ParseForLoop(const char *line)
2636 unsigned forHeadLineno;
2637 unsigned bodyReadLines;
2640 rval = For_Eval(line);
2642 return false; /* Not a .for line */
2644 return true; /* Syntax error - error printed, ignore line */
2646 forHeadLineno = CurFile()->lineno;
2647 bodyReadLines = CurFile()->readLines;
2649 /* Accumulate the loop body until the matching '.endfor'. */
2652 line = ReadLowLevelLine(LK_FOR_BODY);
2654 Parse_Error(PARSE_FATAL,
2655 "Unexpected end of file in .for loop");
2658 } while (For_Accum(line, &forLevel));
2660 For_Run(forHeadLineno, bodyReadLines);
2665 * Read an entire line from the input file.
2667 * Empty lines, .if and .for are completely handled by this function,
2668 * leaving only variable assignments, other directives, dependency lines
2669 * and shell commands to the caller.
2671 * Return a line without trailing whitespace, or NULL for EOF. The returned
2672 * string will be freed at the end of including the file.
2675 ReadHighLevelLine(void)
2678 CondResult condResult;
2681 IncludedFile *curFile = CurFile();
2682 line = ReadLowLevelLine(LK_NONEMPTY);
2683 if (posix_state == PS_MAYBE_NEXT_LINE)
2684 posix_state = PS_NOW_OR_NEVER;
2686 posix_state = PS_TOO_LATE;
2690 if (curFile->guardState != GS_NO
2691 && ((curFile->guardState == GS_START && line[0] != '.')
2692 || curFile->guardState == GS_DONE))
2693 curFile->guardState = GS_NO;
2697 condResult = Cond_EvalLine(line);
2698 if (curFile->guardState == GS_START) {
2700 if (condResult != CR_ERROR
2701 && (guard = Cond_ExtractGuard(line)) != NULL) {
2702 curFile->guardState = GS_COND;
2703 curFile->guard = guard;
2705 curFile->guardState = GS_NO;
2707 switch (condResult) {
2708 case CR_FALSE: /* May also mean a syntax error. */
2709 if (!SkipIrrelevantBranches())
2714 case CR_ERROR: /* Not a conditional line */
2715 if (ParseForLoop(line))
2724 FinishDependencyGroup(void)
2728 if (targets == NULL)
2731 for (ln = targets->first; ln != NULL; ln = ln->next) {
2732 GNode *gn = ln->datum;
2734 Suff_EndTransform(gn);
2737 * Mark the target as already having commands if it does, to
2738 * keep from having shell commands on multiple dependency
2741 if (!Lst_IsEmpty(&gn->commands))
2742 gn->type |= OP_HAS_COMMANDS;
2749 /* Add the command to each target from the current dependency spec. */
2751 ParseLine_ShellCommand(const char *p)
2753 cpp_skip_whitespace(&p);
2755 return; /* skip empty commands */
2757 if (targets == NULL) {
2758 Parse_Error(PARSE_FATAL,
2759 "Unassociated shell command \"%s\"", p);
2764 char *cmd = bmake_strdup(p);
2767 for (ln = targets->first; ln != NULL; ln = ln->next) {
2768 GNode *gn = ln->datum;
2769 GNode_AddCommand(gn, cmd);
2772 Lst_Append(&targCmds, cmd);
2778 HandleBreak(const char *arg)
2780 IncludedFile *curFile = CurFile();
2783 Parse_Error(PARSE_FATAL,
2784 "The .break directive does not take arguments");
2786 if (curFile->forLoop != NULL) {
2787 /* pretend we reached EOF */
2788 For_Break(curFile->forLoop);
2789 cond_depth = CurFile_CondMinDepth();
2792 Parse_Error(PARSE_FATAL, "break outside of for loop");
2796 * See if the line starts with one of the known directives, and if so, handle
2800 ParseDirective(char *line)
2802 char *cp = line + 1;
2806 pp_skip_whitespace(&cp);
2807 if (IsInclude(cp, false)) {
2813 while (ch_islower(*cp) || *cp == '-')
2817 if (*cp != '\0' && !ch_isspace(*cp))
2820 pp_skip_whitespace(&cp);
2823 if (Substring_Equals(dir, "break"))
2825 else if (Substring_Equals(dir, "undef"))
2827 else if (Substring_Equals(dir, "export"))
2828 Var_Export(VEM_PLAIN, arg);
2829 else if (Substring_Equals(dir, "export-env"))
2830 Var_Export(VEM_ENV, arg);
2831 else if (Substring_Equals(dir, "export-literal"))
2832 Var_Export(VEM_LITERAL, arg);
2833 else if (Substring_Equals(dir, "unexport"))
2834 Var_UnExport(false, arg);
2835 else if (Substring_Equals(dir, "unexport-env"))
2836 Var_UnExport(true, arg);
2837 else if (Substring_Equals(dir, "info"))
2838 HandleMessage(PARSE_INFO, "info", arg);
2839 else if (Substring_Equals(dir, "warning"))
2840 HandleMessage(PARSE_WARNING, "warning", arg);
2841 else if (Substring_Equals(dir, "error"))
2842 HandleMessage(PARSE_FATAL, "error", arg);
2849 Parse_VarAssign(const char *line, bool finishDependencyGroup, GNode *scope)
2853 if (!Parse_IsVar(line, &var))
2855 if (finishDependencyGroup)
2856 FinishDependencyGroup();
2857 Parse_Var(&var, scope);
2863 Parse_GuardElse(void)
2865 IncludedFile *curFile = CurFile();
2866 if (cond_depth == curFile->condMinDepth + 1)
2867 curFile->guardState = GS_NO;
2871 Parse_GuardEndif(void)
2873 IncludedFile *curFile = CurFile();
2874 if (cond_depth == curFile->condMinDepth
2875 && curFile->guardState == GS_COND)
2876 curFile->guardState = GS_DONE;
2880 FindSemicolon(char *p)
2884 for (; *p != '\0'; p++) {
2885 if (*p == '\\' && p[1] != '\0') {
2890 if (*p == '$' && (p[1] == '(' || p[1] == '{'))
2892 else if (level > 0 && (*p == ')' || *p == '}'))
2894 else if (level == 0 && *p == ';')
2901 * dependency -> [target...] op [source...] [';' command]
2902 * op -> ':' | '::' | '!'
2905 ParseDependencyLine(char *line)
2908 char *expanded_line;
2909 const char *shellcmd = NULL;
2912 * For some reason - probably to make the parser impossible -
2913 * a ';' can be used to separate commands from dependencies.
2914 * Attempt to skip over ';' inside substitution patterns.
2917 char *semicolon = FindSemicolon(line);
2918 if (*semicolon != '\0') {
2919 /* Terminate the dependency list at the ';' */
2921 shellcmd = semicolon + 1;
2926 * We now know it's a dependency line so it needs to have all
2927 * variables expanded before being parsed.
2929 * XXX: Ideally the dependency line would first be split into
2930 * its left-hand side, dependency operator and right-hand side,
2931 * and then each side would be expanded on its own. This would
2932 * allow for the left-hand side to allow only defined variables
2933 * and to allow variables on the right-hand side to be undefined
2936 * Parsing the line first would also prevent that targets
2937 * generated from variable expressions are interpreted as the
2938 * dependency operator, such as in "target${:U\:} middle: source",
2939 * in which the middle is interpreted as a source, not a target.
2943 * In lint mode, allow undefined variables to appear in dependency
2946 * Ideally, only the right-hand side would allow undefined variables
2947 * since it is common to have optional dependencies. Having undefined
2948 * variables on the left-hand side is more unusual though. Since
2949 * both sides are expanded in a single pass, there is not much choice
2952 * In normal mode, it does not matter whether undefined variables are
2953 * allowed or not since as of 2020-09-14, Var_Parse does not print
2954 * any parse errors in such a case. It simply returns the special
2955 * empty string var_Error, which cannot be detected in the result of
2958 emode = opts.strict ? VARE_WANTRES : VARE_UNDEFERR;
2959 expanded_line = Var_Subst(line, SCOPE_CMDLINE, emode);
2960 /* TODO: handle errors */
2962 /* Need a fresh list for the target nodes */
2963 if (targets != NULL)
2965 targets = Lst_New();
2967 ParseDependency(expanded_line);
2968 free(expanded_line);
2970 if (shellcmd != NULL)
2971 ParseLine_ShellCommand(shellcmd);
2975 ParseLine(char *line)
2978 * Lines that begin with '.' can be pretty much anything:
2979 * - directives like '.include' or '.if',
2980 * - suffix rules like '.c.o:',
2981 * - dependencies for filenames that start with '.',
2982 * - variable assignments like '.tmp=value'.
2984 if (line[0] == '.' && ParseDirective(line))
2987 if (line[0] == '\t') {
2988 ParseLine_ShellCommand(line + 1);
2993 if (IsSysVInclude(line)) {
2995 * It's an S3/S5-style "include".
2997 ParseTraditionalInclude(line);
3003 if (strncmp(line, "export", 6) == 0 && ch_isspace(line[6]) &&
3004 strchr(line, ':') == NULL) {
3006 * It's a Gmake "export".
3008 ParseGmakeExport(line);
3013 if (Parse_VarAssign(line, true, SCOPE_GLOBAL))
3016 FinishDependencyGroup();
3018 ParseDependencyLine(line);
3022 * Parse a top-level makefile, incorporating its content into the global
3026 Parse_File(const char *name, int fd)
3031 buf = LoadFile(name, fd != -1 ? fd : STDIN_FILENO);
3035 assert(targets == NULL);
3037 Parse_PushInput(name, 1, 0, buf, NULL);
3040 while ((line = ReadHighLevelLine()) != NULL) {
3041 DEBUG2(PARSE, "Parsing line %u: %s\n",
3042 CurFile()->lineno, line);
3045 /* Reached EOF, but it may be just EOF of an include file. */
3046 } while (ParseEOF());
3048 FinishDependencyGroup();
3050 if (parseErrors != 0) {
3051 (void)fflush(stdout);
3052 (void)fprintf(stderr,
3053 "%s: Fatal errors encountered -- cannot continue\n",
3055 PrintOnError(NULL, "");
3060 /* Initialize the parsing module. */
3065 parseIncPath = SearchPath_New();
3066 sysIncPath = SearchPath_New();
3067 defSysIncPath = SearchPath_New();
3068 Vector_Init(&includes, sizeof(IncludedFile));
3069 HashTable_Init(&guards);
3072 /* Clean up the parsing module. */
3079 Lst_DoneCall(&targCmds, free);
3080 assert(targets == NULL);
3081 SearchPath_Free(defSysIncPath);
3082 SearchPath_Free(sysIncPath);
3083 SearchPath_Free(parseIncPath);
3084 assert(includes.len == 0);
3085 Vector_Done(&includes);
3086 HashIter_Init(&hi, &guards);
3087 while (HashIter_Next(&hi) != NULL) {
3088 Guard *guard = hi.entry->value;
3092 HashTable_Done(&guards);
3097 /* Populate the list with the single main target to create, or error out. */
3099 Parse_MainName(GNodeList *mainList)
3101 if (mainNode == NULL)
3102 Punt("no target to make.");
3104 Lst_Append(mainList, mainNode);
3105 if (mainNode->type & OP_DOUBLEDEP)
3106 Lst_AppendAll(mainList, &mainNode->cohorts);
3108 Global_Append(".TARGETS", mainNode->name);
3112 Parse_NumErrors(void)