1 /* $NetBSD: parse.c,v 1.164 2010/05/24 21:04:49 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 static char rcsid[] = "$NetBSD: parse.c,v 1.164 2010/05/24 21:04:49 sjg Exp $";
74 #include <sys/cdefs.h>
77 static char sccsid[] = "@(#)parse.c 8.3 (Berkeley) 3/19/94";
79 __RCSID("$NetBSD: parse.c,v 1.164 2010/05/24 21:04:49 sjg Exp $");
86 * Functions to parse a makefile.
88 * One function, Parse_Init, must be called before any functions
89 * in this module are used. After that, the function Parse_File is the
90 * main entry point and controls most of the other functions in this
93 * Most important structures are kept in Lsts. Directories for
94 * the .include "..." function are kept in the 'parseIncPath' Lst, while
95 * those for the .include <...> are kept in the 'sysIncPath' Lst. The
96 * targets currently being defined are kept in the 'targets' Lst.
98 * The variables 'fname' and 'lineno' are used to track the name
99 * of the current file and the line number in that file so that error
100 * messages can be more meaningful.
103 * Parse_Init Initialization function which must be
104 * called before anything else in this module
107 * Parse_End Cleanup the module
109 * Parse_File Function used to parse a makefile. It must
110 * be given the name of the file, which should
111 * already have been opened, and a function
112 * to call to read a character from the file.
114 * Parse_IsVar Returns TRUE if the given line is a
115 * variable assignment. Used by MainParseArgs
116 * to determine if an argument is a target
117 * or a variable assignment. Used internally
118 * for pretty much the same thing...
120 * Parse_Error Function called when an error occurs in
121 * parsing. Used by the variable and
122 * conditional modules.
123 * Parse_MainName Returns a Lst of the main target to create.
137 #include "pathnames.h"
140 * These values are returned by ParseEOF to tell Parse_File whether to
141 * CONTINUE parsing, i.e. it had only reached the end of an include file,
146 static Lst targets; /* targets we're working on */
148 static Lst targCmds; /* command lines for targets */
150 static Boolean inLine; /* true if currently in a dependency
151 * line or its commands */
152 static int fatals = 0;
154 static GNode *mainNode; /* The main target to create. This is the
155 * first target on the first dependency
156 * line in the first makefile */
157 typedef struct IFile {
158 const char *fname; /* name of file */
159 int lineno; /* current line number in file */
160 int first_lineno; /* line number of start of text */
161 int fd; /* the open file */
162 int cond_depth; /* 'if' nesting when file opened */
163 char *P_str; /* point to base of string buffer */
164 char *P_ptr; /* point to next char of string buffer */
165 char *P_end; /* point to the end of string buffer */
166 int P_buflen; /* current size of file buffer */
167 char *(*nextbuf)(void *); /* Function to get more data */
168 void *nextbuf_arg; /* Opaque arg for nextbuf() */
171 #define IFILE_BUFLEN 0x8000
172 static IFile *curFile;
176 * Definitions for handling #include specifications
179 static Lst includes; /* stack of IFiles generated by .includes */
180 Lst parseIncPath; /* list of directories for "..." includes */
181 Lst sysIncPath; /* list of directories for <...> includes */
182 Lst defIncPath; /* default directories for <...> includes */
185 * specType contains the SPECial TYPE of the current target. It is
186 * Not if the target is unspecial. If it *is* special, however, the children
187 * are linked as children of the parent but not vice versa. This variable is
188 * set in ParseDoDependency
192 Default, /* .DEFAULT */
194 dotError, /* .ERROR */
195 Ignore, /* .IGNORE */
196 Includes, /* .INCLUDES */
197 Interrupt, /* .INTERRUPT */
199 MFlags, /* .MFLAGS or .MAKEFLAGS */
200 Main, /* .MAIN and we don't have anything user-specified to
202 NoExport, /* .NOEXPORT */
203 NoPath, /* .NOPATH */
204 Not, /* Not special */
205 NotParallel, /* .NOTPARALLEL */
207 ExObjdir, /* .OBJDIR */
209 Parallel, /* .PARALLEL */
215 Precious, /* .PRECIOUS */
216 ExShell, /* .SHELL */
217 Silent, /* .SILENT */
218 SingleShell, /* .SINGLESHELL */
219 Suffixes, /* .SUFFIXES */
221 Attribute /* Generic attribute */
224 static ParseSpecial specType;
229 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
230 * seen, then set to each successive source on the line.
232 static GNode *predecessor;
235 * The parseKeywords table is searched using binary search when deciding
236 * if a target or source is special. The 'spec' field is the ParseSpecial
237 * type of the keyword ("Not" if the keyword isn't special as a target) while
238 * the 'op' field is the operator to apply to the list of targets if the
239 * keyword is used as a source ("0" if the keyword isn't special as a source)
242 const char *name; /* Name of keyword */
243 ParseSpecial spec; /* Type when used as a target */
244 int op; /* Operator when used as a source */
245 } parseKeywords[] = {
246 { ".BEGIN", Begin, 0 },
247 { ".DEFAULT", Default, 0 },
249 { ".ERROR", dotError, 0 },
250 { ".EXEC", Attribute, OP_EXEC },
251 { ".IGNORE", Ignore, OP_IGNORE },
252 { ".INCLUDES", Includes, 0 },
253 { ".INTERRUPT", Interrupt, 0 },
254 { ".INVISIBLE", Attribute, OP_INVISIBLE },
255 { ".JOIN", Attribute, OP_JOIN },
256 { ".LIBS", Libs, 0 },
257 { ".MADE", Attribute, OP_MADE },
258 { ".MAIN", Main, 0 },
259 { ".MAKE", Attribute, OP_MAKE },
260 { ".MAKEFLAGS", MFlags, 0 },
261 { ".MFLAGS", MFlags, 0 },
262 { ".NOPATH", NoPath, OP_NOPATH },
263 { ".NOTMAIN", Attribute, OP_NOTMAIN },
264 { ".NOTPARALLEL", NotParallel, 0 },
265 { ".NO_PARALLEL", NotParallel, 0 },
266 { ".NULL", Null, 0 },
267 { ".OBJDIR", ExObjdir, 0 },
268 { ".OPTIONAL", Attribute, OP_OPTIONAL },
269 { ".ORDER", Order, 0 },
270 { ".PARALLEL", Parallel, 0 },
271 { ".PATH", ExPath, 0 },
272 { ".PHONY", Phony, OP_PHONY },
274 { ".POSIX", Posix, 0 },
276 { ".PRECIOUS", Precious, OP_PRECIOUS },
277 { ".RECURSIVE", Attribute, OP_MAKE },
278 { ".SHELL", ExShell, 0 },
279 { ".SILENT", Silent, OP_SILENT },
280 { ".SINGLESHELL", SingleShell, 0 },
281 { ".SUFFIXES", Suffixes, 0 },
282 { ".USE", Attribute, OP_USE },
283 { ".USEBEFORE", Attribute, OP_USEBEFORE },
284 { ".WAIT", Wait, 0 },
287 static int ParseIsEscaped(const char *, const char *);
288 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
289 __attribute__((__format__(__printf__, 4, 5)));
290 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
291 __attribute__((__format__(__printf__, 5, 0)));
292 static int ParseFindKeyword(const char *);
293 static int ParseLinkSrc(void *, void *);
294 static int ParseDoOp(void *, void *);
295 static void ParseDoSrc(int, const char *);
296 static int ParseFindMain(void *, void *);
297 static int ParseAddDir(void *, void *);
298 static int ParseClearPath(void *, void *);
299 static void ParseDoDependency(char *);
300 static int ParseAddCmd(void *, void *);
301 static void ParseHasCommands(void *);
302 static void ParseDoInclude(char *);
303 static void ParseSetParseFile(const char *);
305 static void ParseTraditionalInclude(char *);
307 static int ParseEOF(void);
308 static char *ParseReadLine(void);
309 static void ParseFinishLine(void);
310 static void ParseMark(GNode *);
316 *----------------------------------------------------------------------
318 * Check if the current character is escaped on the current line
321 * 0 if the character is not backslash escaped, 1 otherwise
325 *----------------------------------------------------------------------
328 ParseIsEscaped(const char *line, const char *c)
341 *----------------------------------------------------------------------
342 * ParseFindKeyword --
343 * Look in the table of keywords for one matching the given string.
349 * The index of the keyword, or -1 if it isn't there.
353 *----------------------------------------------------------------------
356 ParseFindKeyword(const char *str)
362 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
365 cur = start + ((end - start) / 2);
366 diff = strcmp(str, parseKeywords[cur].name);
370 } else if (diff < 0) {
375 } while (start <= end);
380 * ParseVErrorInternal --
381 * Error message abort function for parsing. Prints out the context
382 * of the error (line number and file) as well as the message with
383 * two optional arguments.
389 * "fatals" is incremented if the level is PARSE_FATAL.
393 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
394 const char *fmt, va_list ap)
396 static Boolean fatal_warning_error_printed = FALSE;
398 (void)fprintf(f, "%s: ", progname);
400 if (cfname != NULL) {
401 (void)fprintf(f, "\"");
402 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
407 * Nothing is more anoying than not knowing
408 * which Makefile is the culprit.
410 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
411 if (dir == NULL || *dir == '\0' ||
412 (*dir == '.' && dir[1] == '\0'))
413 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
417 (void)fprintf(f, "%s/%s", dir, cfname);
419 (void)fprintf(f, "%s", cfname);
421 (void)fprintf(f, "\" line %d: ", (int)clineno);
423 if (type == PARSE_WARNING)
424 (void)fprintf(f, "warning: ");
425 (void)vfprintf(f, fmt, ap);
426 (void)fprintf(f, "\n");
428 if (type == PARSE_FATAL || parseWarnFatal)
430 if (parseWarnFatal && !fatal_warning_error_printed) {
431 Error("parsing warnings being treated as errors");
432 fatal_warning_error_printed = TRUE;
437 * ParseErrorInternal --
448 ParseErrorInternal(const char *cfname, size_t clineno, int type,
449 const char *fmt, ...)
454 (void)fflush(stdout);
455 ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
458 if (debug_file != stderr && debug_file != stdout) {
460 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
467 * External interface to ParseErrorInternal; uses the default filename
478 Parse_Error(int type, const char *fmt, ...)
484 if (curFile == NULL) {
488 fname = curFile->fname;
489 lineno = curFile->lineno;
493 (void)fflush(stdout);
494 ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
497 if (debug_file != stderr && debug_file != stdout) {
499 ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
507 * Parse a .info .warning or .error directive
509 * The input is the line minus the ".". We substitute
510 * variables, print the message and exit(1) (for .error) or just print
511 * a warning if the directive is malformed.
514 ParseMessage(char *line)
523 mtype = PARSE_WARNING;
529 Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line);
533 while (isalpha((u_char)*line))
535 if (!isspace((u_char)*line))
536 return FALSE; /* not for us */
537 while (isspace((u_char)*line))
540 line = Var_Subst(NULL, line, VAR_CMD, 0);
541 Parse_Error(mtype, "%s", line);
544 if (mtype == PARSE_FATAL) {
545 /* Terminate immediately. */
552 *---------------------------------------------------------------------
554 * Link the parent node to its new child. Used in a Lst_ForEach by
555 * ParseDoDependency. If the specType isn't 'Not', the parent
556 * isn't linked as a parent of the child.
559 * pgnp The parent node
560 * cgpn The child node
566 * New elements are added to the parents list of cgn and the
567 * children list of cgn. the unmade field of pgn is updated
568 * to reflect the additional child.
569 *---------------------------------------------------------------------
572 ParseLinkSrc(void *pgnp, void *cgnp)
574 GNode *pgn = (GNode *)pgnp;
575 GNode *cgn = (GNode *)cgnp;
577 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
578 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
579 (void)Lst_AtEnd(pgn->children, cgn);
581 (void)Lst_AtEnd(cgn->parents, pgn);
584 fprintf(debug_file, "# ParseLinkSrc: added child %s - %s\n", pgn->name, cgn->name);
585 Targ_PrintNode(pgn, 0);
586 Targ_PrintNode(cgn, 0);
592 *---------------------------------------------------------------------
594 * Apply the parsed operator to the given target node. Used in a
595 * Lst_ForEach call by ParseDoDependency once all targets have
596 * been found and their operator parsed. If the previous and new
597 * operators are incompatible, a major error is taken.
600 * gnp The node to which the operator is to be applied
601 * opp The operator to apply
607 * The type field of the node is altered to reflect any new bits in
609 *---------------------------------------------------------------------
612 ParseDoOp(void *gnp, void *opp)
614 GNode *gn = (GNode *)gnp;
615 int op = *(int *)opp;
617 * If the dependency mask of the operator and the node don't match and
618 * the node has actually had an operator applied to it before, and
619 * the operator actually has some dependency information in it, complain.
621 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
622 !OP_NOP(gn->type) && !OP_NOP(op))
624 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
628 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
630 * If the node was the object of a :: operator, we need to create a
631 * new instance of it for the children and commands on this dependency
632 * line. The new instance is placed on the 'cohorts' list of the
633 * initial one (note the initial one is not on its own cohorts list)
634 * and the new instance is linked to all parents of the initial
640 * Propagate copied bits to the initial node. They'll be propagated
641 * back to the rest of the cohorts later.
643 gn->type |= op & ~OP_OPMASK;
645 cohort = Targ_FindNode(gn->name, TARG_NOHASH);
647 * Make the cohort invisible as well to avoid duplicating it into
648 * other variables. True, parents of this target won't tend to do
649 * anything with their local variables, but better safe than
650 * sorry. (I think this is pointless now, since the relevant list
651 * traversals will no longer see this node anyway. -mycroft)
653 cohort->type = op | OP_INVISIBLE;
654 (void)Lst_AtEnd(gn->cohorts, cohort);
655 cohort->centurion = gn;
656 gn->unmade_cohorts += 1;
657 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
661 * We don't want to nuke any previous flags (whatever they were) so we
662 * just OR the new operator into the old
671 *---------------------------------------------------------------------
673 * Given the name of a source, figure out if it is an attribute
674 * and apply it to the targets if it is. Else decide if there is
675 * some attribute which should be applied *to* the source because
676 * of some special target and apply it if so. Otherwise, make the
677 * source be a child of the targets in the list 'targets'
680 * tOp operator (if any) from special targets
681 * src name of the source to handle
687 * Operator bits may be added to the list of targets or to the source.
688 * The targets may have a new source added to their lists of children.
689 *---------------------------------------------------------------------
692 ParseDoSrc(int tOp, const char *src)
695 static int wait_number = 0;
698 if (*src == '.' && isupper ((unsigned char)src[1])) {
699 int keywd = ParseFindKeyword(src);
701 int op = parseKeywords[keywd].op;
703 Lst_ForEach(targets, ParseDoOp, &op);
706 if (parseKeywords[keywd].spec == Wait) {
708 * We add a .WAIT node in the dependency list.
709 * After any dynamic dependencies (and filename globbing)
710 * have happened, it is given a dependency on the each
711 * previous child back to and previous .WAIT node.
712 * The next child won't be scheduled until the .WAIT node
714 * We give each .WAIT node a unique name (mainly for diag).
716 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
717 gn = Targ_FindNode(wait_src, TARG_NOHASH);
718 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
719 Lst_ForEach(targets, ParseLinkSrc, gn);
728 * If we have noted the existence of a .MAIN, it means we need
729 * to add the sources of said target to the list of things
730 * to create. The string 'src' is likely to be free, so we
731 * must make a new copy of it. Note that this will only be
732 * invoked if the user didn't specify a target on the command
733 * line. This is to allow #ifmake's to succeed, or something...
735 (void)Lst_AtEnd(create, bmake_strdup(src));
737 * Add the name to the .TARGETS variable as well, so the user can
738 * employ that, if desired.
740 Var_Append(".TARGETS", src, VAR_GLOBAL);
745 * Create proper predecessor/successor links between the previous
746 * source and the current one.
748 gn = Targ_FindNode(src, TARG_CREATE);
749 if (predecessor != NULL) {
750 (void)Lst_AtEnd(predecessor->order_succ, gn);
751 (void)Lst_AtEnd(gn->order_pred, predecessor);
753 fprintf(debug_file, "# ParseDoSrc: added Order dependency %s - %s\n",
754 predecessor->name, gn->name);
755 Targ_PrintNode(predecessor, 0);
756 Targ_PrintNode(gn, 0);
760 * The current source now becomes the predecessor for the next one.
767 * If the source is not an attribute, we need to find/create
768 * a node for it. After that we can apply any operator to it
769 * from a special target or link it to its parents, as
772 * In the case of a source that was the object of a :: operator,
773 * the attribute is applied to all of its instances (as kept in
774 * the 'cohorts' list of the node) or all the cohorts are linked
775 * to all the targets.
778 /* Find/create the 'src' node and attach to all targets */
779 gn = Targ_FindNode(src, TARG_CREATE);
783 Lst_ForEach(targets, ParseLinkSrc, gn);
790 *-----------------------------------------------------------------------
792 * Find a real target in the list and set it to be the main one.
793 * Called by ParseDoDependency when a main target hasn't been found
797 * gnp Node to examine
800 * 0 if main not found yet, 1 if it is.
803 * mainNode is changed and Targ_SetMain is called.
805 *-----------------------------------------------------------------------
808 ParseFindMain(void *gnp, void *dummy)
810 GNode *gn = (GNode *)gnp;
811 if ((gn->type & OP_NOTARGET) == 0) {
814 return (dummy ? 1 : 1);
816 return (dummy ? 0 : 0);
821 *-----------------------------------------------------------------------
823 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
831 *-----------------------------------------------------------------------
834 ParseAddDir(void *path, void *name)
836 (void)Dir_AddDir((Lst) path, (char *)name);
841 *-----------------------------------------------------------------------
843 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
851 *-----------------------------------------------------------------------
854 ParseClearPath(void *path, void *dummy)
856 Dir_ClearPath((Lst) path);
857 return(dummy ? 0 : 0);
861 *---------------------------------------------------------------------
862 * ParseDoDependency --
863 * Parse the dependency line in line.
866 * line the line to parse
872 * The nodes of the sources are linked as children to the nodes of the
873 * targets. Some nodes may be created.
875 * We parse a dependency line by first extracting words from the line and
876 * finding nodes in the list of all targets with that name. This is done
877 * until a character is encountered which is an operator character. Currently
878 * these are only ! and :. At this point the operator is parsed and the
879 * pointer into the line advanced until the first source is encountered.
880 * The parsed operator is applied to each node in the 'targets' list,
881 * which is where the nodes found for the targets are kept, by means of
882 * the ParseDoOp function.
883 * The sources are read in much the same way as the targets were except
884 * that now they are expanded using the wildcarding scheme of the C-Shell
885 * and all instances of the resulting words in the list of all targets
886 * are found. Each of the resulting nodes is then linked to each of the
887 * targets as one of its children.
888 * Certain targets are handled specially. These are the ones detailed
889 * by the specType variable.
890 * The storing of transformation rules is also taken care of here.
891 * A target is recognized as a transformation rule by calling
892 * Suff_IsTransform. If it is a transformation rule, its node is gotten
893 * from the suffix module via Suff_AddTransform rather than the standard
894 * Targ_FindNode in the target module.
895 *---------------------------------------------------------------------
898 ParseDoDependency(char *line)
900 char *cp; /* our current position */
901 GNode *gn = NULL; /* a general purpose temporary node */
902 int op; /* the operator on the line */
903 char savec; /* a place to save a character */
904 Lst paths; /* List of search paths to alter when parsing
905 * a list of .PATH targets */
906 int tOp; /* operator from special target */
907 Lst sources; /* list of archive source names after
909 Lst curTargs; /* list of target names to be found and added
910 * to the targets list */
914 fprintf(debug_file, "ParseDoDependency(%s)\n", line);
920 curTargs = Lst_Init(FALSE);
923 for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
924 !(isspace((unsigned char)*cp) ||
925 *cp == '!' || *cp == ':' || *cp == LPAREN));
929 * Must be a dynamic source (would have been expanded
930 * otherwise), so call the Var module to parse the puppy
931 * so we can safely advance beyond it...There should be
932 * no errors in this, as they would have been discovered
933 * in the initial Var_Subst and we wouldn't be here.
939 result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
946 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
948 * Archives must be handled specially to make sure the OP_ARCHV
949 * flag is set in their 'type' field, for one thing, and because
950 * things like "archive(file1.o file2.o file3.o)" are permissible.
951 * Arch_ParseArchive will set 'line' to be the first non-blank
952 * after the archive-spec. It creates/finds nodes for the members
953 * and places them on the given list, returning SUCCESS if all
954 * went well and FAILURE if there was an error in the
955 * specification. On error, line should remain untouched.
957 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
958 Parse_Error(PARSE_FATAL,
959 "Error in archive specification: \"%s\"", line);
969 * Ending a dependency line without an operator is a Bozo
970 * no-no. As a heuristic, this is also often triggered by
971 * undetected conflicts from cvs/rcs merges.
973 if ((strncmp(line, "<<<<<<", 6) == 0) ||
974 (strncmp(line, "======", 6) == 0) ||
975 (strncmp(line, ">>>>>>", 6) == 0))
976 Parse_Error(PARSE_FATAL,
977 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
979 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
980 : "Need an operator");
986 * Have a word in line. See if it's a special target and set
987 * specType to match it.
989 if (*line == '.' && isupper ((unsigned char)line[1])) {
991 * See if the target is a special target that must have it
992 * or its sources handled specially.
994 int keywd = ParseFindKeyword(line);
996 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
997 Parse_Error(PARSE_FATAL, "Mismatched special targets");
1001 specType = parseKeywords[keywd].spec;
1002 tOp = parseKeywords[keywd].op;
1005 * Certain special targets have special semantics:
1006 * .PATH Have to set the dirSearchPath
1008 * .MAIN Its sources are only used if
1009 * nothing has been specified to
1011 * .DEFAULT Need to create a node to hang
1012 * commands on, but we don't want
1013 * it in the graph, nor do we want
1014 * it to be the Main Target, so we
1015 * create it, set OP_NOTMAIN and
1016 * add it to the list, setting
1017 * DEFAULT to the new node for
1018 * later use. We claim the node is
1019 * A transformation rule to make
1020 * life easier later, when we'll
1021 * use Make_HandleUse to actually
1022 * apply the .DEFAULT commands.
1023 * .PHONY The list of targets
1024 * .NOPATH Don't search for file in the path
1028 * .INTERRUPT Are not to be considered the
1030 * .NOTPARALLEL Make only one target at a time.
1031 * .SINGLESHELL Create a shell for each command.
1032 * .ORDER Must set initial predecessor to NULL
1036 if (paths == NULL) {
1037 paths = Lst_Init(FALSE);
1039 (void)Lst_AtEnd(paths, dirSearchPath);
1042 if (!Lst_IsEmpty(create)) {
1050 gn = Targ_FindNode(line, TARG_CREATE);
1051 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1052 (void)Lst_AtEnd(targets, gn);
1055 gn = Targ_NewGN(".DEFAULT");
1056 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1057 (void)Lst_AtEnd(targets, gn);
1072 } else if (strncmp(line, ".PATH", 5) == 0) {
1074 * .PATH<suffix> has to be handled specially.
1075 * Call on the suffix module to give us a path to
1081 path = Suff_GetPath(&line[5]);
1083 Parse_Error(PARSE_FATAL,
1084 "Suffix '%s' not defined (yet)",
1088 if (paths == (Lst)NULL) {
1089 paths = Lst_Init(FALSE);
1091 (void)Lst_AtEnd(paths, path);
1097 * Have word in line. Get or create its node and stick it at
1098 * the end of the targets list
1100 if ((specType == Not) && (*line != '\0')) {
1101 if (Dir_HasWildcards(line)) {
1103 * Targets are to be sought only in the current directory,
1104 * so create an empty path for the thing. Note we need to
1105 * use Dir_Destroy in the destruction of the path as the
1106 * Dir module could have added a directory to the path...
1108 Lst emptyPath = Lst_Init(FALSE);
1110 Dir_Expand(line, emptyPath, curTargs);
1112 Lst_Destroy(emptyPath, Dir_Destroy);
1115 * No wildcards, but we want to avoid code duplication,
1116 * so create a list with the word on it.
1118 (void)Lst_AtEnd(curTargs, line);
1121 while(!Lst_IsEmpty(curTargs)) {
1122 char *targName = (char *)Lst_DeQueue(curTargs);
1124 if (!Suff_IsTransform (targName)) {
1125 gn = Targ_FindNode(targName, TARG_CREATE);
1127 gn = Suff_AddTransform(targName);
1130 (void)Lst_AtEnd(targets, gn);
1132 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1133 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1138 * If it is a special type and not .PATH, it's the only target we
1139 * allow on this line...
1141 if (specType != Not && specType != ExPath) {
1142 Boolean warning = FALSE;
1144 while (*cp && (ParseIsEscaped(lstart, cp) ||
1145 ((*cp != '!') && (*cp != ':')))) {
1146 if (ParseIsEscaped(lstart, cp) ||
1147 (*cp != ' ' && *cp != '\t')) {
1153 Parse_Error(PARSE_WARNING, "Extra target ignored");
1156 while (*cp && isspace ((unsigned char)*cp)) {
1161 } while (*line && (ParseIsEscaped(lstart, line) ||
1162 ((*line != '!') && (*line != ':'))));
1165 * Don't need the list of target names anymore...
1167 Lst_Destroy(curTargs, NULL);
1170 if (!Lst_IsEmpty(targets)) {
1173 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1181 * These four create nodes on which to hang commands, so
1182 * targets shouldn't be empty...
1186 * Nothing special here -- targets can be empty if it wants.
1193 * Have now parsed all the target names. Must parse the operator next. The
1194 * result is left in op .
1198 } else if (*cp == ':') {
1206 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1207 : "Missing dependency operator");
1211 cp++; /* Advance beyond operator */
1213 Lst_ForEach(targets, ParseDoOp, &op);
1216 * Get to the first source
1218 while (*cp && isspace ((unsigned char)*cp)) {
1224 * Several special targets take different actions if present with no
1226 * a .SUFFIXES line with no sources clears out all old suffixes
1227 * a .PRECIOUS line makes all targets precious
1228 * a .IGNORE line ignores errors for all targets
1229 * a .SILENT line creates silence when making all targets
1230 * a .PATH removes all directories from the search path(s).
1235 Suff_ClearSuffixes();
1241 ignoreErrors = TRUE;
1247 Lst_ForEach(paths, ParseClearPath, NULL);
1252 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1258 } else if (specType == MFlags) {
1260 * Call on functions in main.c to deal with these arguments and
1261 * set the initial character to a null-character so the loop to
1262 * get sources won't get anything
1264 Main_ParseArgLine(line);
1266 } else if (specType == ExShell) {
1267 if (Job_ParseShell(line) != SUCCESS) {
1268 Parse_Error(PARSE_FATAL, "improper shell specification");
1272 } else if ((specType == NotParallel) || (specType == SingleShell)) {
1277 * NOW GO FOR THE SOURCES
1279 if ((specType == Suffixes) || (specType == ExPath) ||
1280 (specType == Includes) || (specType == Libs) ||
1281 (specType == Null) || (specType == ExObjdir))
1285 * If the target was one that doesn't take files as its sources
1286 * but takes something like suffixes, we take each
1287 * space-separated word on the line as a something and deal
1288 * with it accordingly.
1290 * If the target was .SUFFIXES, we take each source as a
1291 * suffix and add it to the list of suffixes maintained by the
1294 * If the target was a .PATH, we add the source as a directory
1295 * to search on the search path.
1297 * If it was .INCLUDES, the source is taken to be the suffix of
1298 * files which will be #included and whose search path should
1299 * be present in the .INCLUDES variable.
1301 * If it was .LIBS, the source is taken to be the suffix of
1302 * files which are considered libraries and whose search path
1303 * should be present in the .LIBS variable.
1305 * If it was .NULL, the source is the suffix to use when a file
1306 * has no valid suffix.
1308 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1309 * and will cause make to do a new chdir to that path.
1311 while (*cp && !isspace ((unsigned char)*cp)) {
1318 Suff_AddSuffix(line, &mainNode);
1321 Lst_ForEach(paths, ParseAddDir, line);
1324 Suff_AddInclude(line);
1333 Main_SetObjdir(line);
1339 if (savec != '\0') {
1342 while (*cp && isspace ((unsigned char)*cp)) {
1348 Lst_Destroy(paths, NULL);
1350 if (specType == ExPath)
1355 * The targets take real sources, so we must beware of archive
1356 * specifications (i.e. things with left parentheses in them)
1357 * and handle them accordingly.
1359 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1360 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1362 * Only stop for a left parenthesis if it isn't at the
1363 * start of a word (that'll be for variable changes
1364 * later) and isn't preceded by a dollar sign (a dynamic
1371 if (*cp == LPAREN) {
1372 sources = Lst_Init(FALSE);
1373 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1374 Parse_Error(PARSE_FATAL,
1375 "Error in source archive spec \"%s\"", line);
1379 while (!Lst_IsEmpty (sources)) {
1380 gn = (GNode *)Lst_DeQueue(sources);
1381 ParseDoSrc(tOp, gn->name);
1383 Lst_Destroy(sources, NULL);
1391 ParseDoSrc(tOp, line);
1393 while (*cp && isspace ((unsigned char)*cp)) {
1400 if (mainNode == NULL) {
1402 * If we have yet to decide on a main target to make, in the
1403 * absence of any user input, we want the first target on
1404 * the first dependency line that is actually a real target
1405 * (i.e. isn't a .USE or .EXEC rule) to be made.
1407 Lst_ForEach(targets, ParseFindMain, NULL);
1412 Lst_Destroy(curTargs, NULL);
1416 *---------------------------------------------------------------------
1418 * Return TRUE if the passed line is a variable assignment. A variable
1419 * assignment consists of a single word followed by optional whitespace
1420 * followed by either a += or an = operator.
1421 * This function is used both by the Parse_File function and main when
1422 * parsing the command-line arguments.
1425 * line the line to check
1428 * TRUE if it is. FALSE if it ain't
1432 *---------------------------------------------------------------------
1435 Parse_IsVar(char *line)
1437 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1440 #define ISEQOPERATOR(c) \
1441 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1444 * Skip to variable name
1446 for (;(*line == ' ') || (*line == '\t'); line++)
1449 /* Scan for one of the assignment operators outside a variable expansion */
1450 while ((ch = *line++) != 0) {
1451 if (ch == '(' || ch == '{') {
1455 if (ch == ')' || ch == '}') {
1461 while (ch == ' ' || ch == '\t') {
1467 if (*line == '=' && ISEQOPERATOR(ch))
1477 *---------------------------------------------------------------------
1479 * Take the variable assignment in the passed line and do it in the
1482 * Note: There is a lexical ambiguity with assignment modifier characters
1483 * in variable names. This routine interprets the character before the =
1484 * as a modifier. Therefore, an assignment like
1486 * is interpreted as "C+ +=" instead of "C++ =".
1489 * line a line guaranteed to be a variable assignment.
1490 * This reduces error checks
1491 * ctxt Context in which to do the assignment
1497 * the variable structure of the given variable name is altered in the
1499 *---------------------------------------------------------------------
1502 Parse_DoVar(char *line, GNode *ctxt)
1504 char *cp; /* pointer into line */
1506 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1507 } type; /* Type of assignment */
1508 char *opc; /* ptr to operator character to
1509 * null-terminate the variable name */
1510 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1511 * i.e. if any variable expansion was
1516 * Skip to variable name
1518 while ((*line == ' ') || (*line == '\t')) {
1523 * Skip to operator character, nulling out whitespace as we go
1524 * XXX Rather than counting () and {} we should look for $ and
1525 * then expand the variable.
1527 for (depth = 0, cp = line + 1; depth != 0 || *cp != '='; cp++) {
1528 if (*cp == '(' || *cp == '{') {
1532 if (*cp == ')' || *cp == '}') {
1536 if (depth == 0 && isspace ((unsigned char)*cp)) {
1540 opc = cp-1; /* operator is the previous character */
1541 *cp++ = '\0'; /* nuke the = */
1544 * Check operator type
1554 * If the variable already has a value, we don't do anything.
1557 if (Var_Exists(line, ctxt)) {
1576 while (opc > line && *opc != ':')
1579 if (strncmp(opc, ":sh", 3) == 0) {
1589 while (isspace ((unsigned char)*cp)) {
1593 if (type == VAR_APPEND) {
1594 Var_Append(line, cp, ctxt);
1595 } else if (type == VAR_SUBST) {
1597 * Allow variables in the old value to be undefined, but leave their
1598 * invocation alone -- this is done by forcing oldVars to be false.
1599 * XXX: This can cause recursive variables, but that's not hard to do,
1600 * and this allows someone to do something like
1602 * CFLAGS = $(.INCLUDES)
1603 * CFLAGS := -I.. $(CFLAGS)
1605 * And not get an error.
1607 Boolean oldOldVars = oldVars;
1612 * make sure that we set the variable the first time to nothing
1613 * so that it gets substituted!
1615 if (!Var_Exists(line, ctxt))
1616 Var_Set(line, "", ctxt, 0);
1618 cp = Var_Subst(NULL, cp, ctxt, FALSE);
1619 oldVars = oldOldVars;
1622 Var_Set(line, cp, ctxt, 0);
1623 } else if (type == VAR_SHELL) {
1627 if (strchr(cp, '$') != NULL) {
1629 * There's a dollar sign in the command, so perform variable
1630 * expansion on the whole thing. The resulting string will need
1631 * freeing when we're done, so set freeCmd to TRUE.
1633 cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1637 res = Cmd_Exec(cp, &error);
1638 Var_Set(line, res, ctxt, 0);
1642 Parse_Error(PARSE_WARNING, error, cp);
1645 * Normal assignment -- just do it.
1647 Var_Set(line, cp, ctxt, 0);
1649 if (strcmp(line, MAKEOVERRIDES) == 0)
1650 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1651 else if (strcmp(line, ".CURDIR") == 0) {
1653 * Somone is being (too?) clever...
1654 * Let's pretend they know what they are doing and
1655 * re-initialize the 'cur' Path.
1659 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1661 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1671 * Lst_ForEach function to add a command line to all targets
1674 * gnp the node to which the command is to be added
1675 * cmd the command to add
1681 * A new element is added to the commands list of the node.
1684 ParseAddCmd(void *gnp, void *cmd)
1686 GNode *gn = (GNode *)gnp;
1688 /* Add to last (ie current) cohort for :: targets */
1689 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1690 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1692 /* if target already supplied, ignore commands */
1693 if (!(gn->type & OP_HAS_COMMANDS)) {
1694 (void)Lst_AtEnd(gn->commands, cmd);
1698 /* XXX: We cannot do this until we fix the tree */
1699 (void)Lst_AtEnd(gn->commands, cmd);
1700 Parse_Error(PARSE_WARNING,
1701 "overriding commands for target \"%s\"; "
1702 "previous commands defined at %s: %d ignored",
1703 gn->name, gn->fname, gn->lineno);
1705 Parse_Error(PARSE_WARNING,
1706 "duplicate script for target \"%s\" ignored",
1708 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1709 "using previous script for \"%s\" defined here",
1717 *-----------------------------------------------------------------------
1718 * ParseHasCommands --
1719 * Callback procedure for Parse_File when destroying the list of
1720 * targets on the last dependency line. Marks a target as already
1721 * having commands if it does, to keep from having shell commands
1722 * on multiple dependency lines.
1725 * gnp Node to examine
1731 * OP_HAS_COMMANDS may be set for the target.
1733 *-----------------------------------------------------------------------
1736 ParseHasCommands(void *gnp)
1738 GNode *gn = (GNode *)gnp;
1739 if (!Lst_IsEmpty(gn->commands)) {
1740 gn->type |= OP_HAS_COMMANDS;
1745 *-----------------------------------------------------------------------
1746 * Parse_AddIncludeDir --
1747 * Add a directory to the path searched for included makefiles
1748 * bracketed by double-quotes. Used by functions in main.c
1751 * dir The name of the directory to add
1757 * The directory is appended to the list.
1759 *-----------------------------------------------------------------------
1762 Parse_AddIncludeDir(char *dir)
1764 (void)Dir_AddDir(parseIncPath, dir);
1768 *---------------------------------------------------------------------
1770 * Push to another file.
1772 * The input is the line minus the `.'. A file spec is a string
1773 * enclosed in <> or "". The former is looked for only in sysIncPath.
1774 * The latter in . and the directories specified by -I command line
1781 * A structure is added to the includes Lst and readProc, lineno,
1782 * fname and curFILE are altered for the new file
1783 *---------------------------------------------------------------------
1787 Parse_include_file(char *file, Boolean isSystem, int silent)
1789 char *fullname; /* full pathname of file */
1791 char *prefEnd, *incdir;
1796 * Now we know the file's name and its search path, we attempt to
1797 * find the durn thing. A return of NULL indicates the file don't
1800 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1802 if (fullname == NULL && !isSystem) {
1804 * Include files contained in double-quotes are first searched for
1805 * relative to the including file's location. We don't want to
1806 * cd there, of course, so we just tack on the old file's
1807 * leading path components and call Dir_FindFile to see if
1808 * we can locate the beast.
1811 incdir = bmake_strdup(curFile->fname);
1812 prefEnd = strrchr(incdir, '/');
1813 if (prefEnd != NULL) {
1815 /* Now do lexical processing of leading "../" on the filename */
1816 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1817 prefEnd = strrchr(incdir + 1, '/');
1818 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
1822 newName = str_concat(incdir, file + i, STR_ADDSLASH);
1823 fullname = Dir_FindFile(newName, parseIncPath);
1824 if (fullname == NULL)
1825 fullname = Dir_FindFile(newName, dirSearchPath);
1830 if (fullname == NULL) {
1832 * Makefile wasn't found in same directory as included makefile.
1833 * Search for it first on the -I search path,
1834 * then on the .PATH search path, if not found in a -I directory.
1835 * If we have a suffix specific path we should use that.
1838 Lst suffPath = NULL;
1840 if ((suff = strrchr(file, '.'))) {
1841 suffPath = Suff_GetPath(suff);
1842 if (suffPath != NULL) {
1843 fullname = Dir_FindFile(file, suffPath);
1846 if (fullname == NULL) {
1847 fullname = Dir_FindFile(file, parseIncPath);
1848 if (fullname == NULL) {
1849 fullname = Dir_FindFile(file, dirSearchPath);
1855 /* Looking for a system file or file still not found */
1856 if (fullname == NULL) {
1858 * Look for it on the system path
1860 fullname = Dir_FindFile(file,
1861 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1864 if (fullname == NULL) {
1866 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1870 /* Actually open the file... */
1871 fd = open(fullname, O_RDONLY);
1874 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1879 /* Start reading from this file next */
1880 Parse_SetInput(fullname, 0, fd, NULL, NULL);
1884 ParseDoInclude(char *line)
1886 char endc; /* the character which ends the file spec */
1887 char *cp; /* current position in file spec */
1888 int silent = (*line != 'i') ? 1 : 0;
1889 char *file = &line[7 + silent];
1891 /* Skip to delimiter character so we know where to look */
1892 while (*file == ' ' || *file == '\t')
1895 if (*file != '"' && *file != '<') {
1896 Parse_Error(PARSE_FATAL,
1897 ".include filename must be delimited by '\"' or '<'");
1902 * Set the search path on which to find the include file based on the
1903 * characters which bracket its name. Angle-brackets imply it's
1904 * a system Makefile while double-quotes imply it's a user makefile
1912 /* Skip to matching delimiter */
1913 for (cp = ++file; *cp && *cp != endc; cp++)
1917 Parse_Error(PARSE_FATAL,
1918 "Unclosed %cinclude filename. '%c' expected",
1925 * Substitute for any variables in the file name before trying to
1928 file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1930 Parse_include_file(file, endc == '>', silent);
1936 *---------------------------------------------------------------------
1937 * ParseSetParseFile --
1938 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
1939 * basename of the given filename
1945 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
1946 * dirname and basename of the given filename.
1947 *---------------------------------------------------------------------
1950 ParseSetParseFile(const char *filename)
1956 slash = strrchr(filename, '/');
1957 if (slash == NULL) {
1958 Var_Set(".PARSEDIR", ".", VAR_GLOBAL, 0);
1959 Var_Set(".PARSEFILE", filename, VAR_GLOBAL, 0);
1961 len = slash - filename;
1962 dirname = bmake_malloc(len + 1);
1963 memcpy(dirname, filename, len);
1965 Var_Set(".PARSEDIR", dirname, VAR_GLOBAL, 0);
1966 Var_Set(".PARSEFILE", slash+1, VAR_GLOBAL, 0);
1972 * Track the makefiles we read - so makefiles can
1973 * set dependencies on them.
1974 * Avoid adding anything more than once.
1978 ParseTrackInput(const char *name)
1982 size_t name_len = strlen(name);
1984 old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
1986 /* does it contain name? */
1987 for (; old != NULL; old = strchr(old, ' ')) {
1990 if (memcmp(old, name, name_len) == 0
1991 && (old[name_len] == 0 || old[name_len] == ' '))
1995 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2004 *---------------------------------------------------------------------
2006 * Start Parsing from the given source
2012 * A structure is added to the includes Lst and readProc, lineno,
2013 * fname and curFile are altered for the new file
2014 *---------------------------------------------------------------------
2017 Parse_SetInput(const char *name, int line, int fd, char *(*nextbuf)(void *), void *arg)
2022 name = curFile->fname;
2024 ParseTrackInput(name);
2027 fprintf(debug_file, "Parse_SetInput: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2028 name, line, fd, nextbuf, arg);
2030 if (fd == -1 && nextbuf == NULL)
2034 if (curFile != NULL)
2035 /* Save exiting file info */
2036 Lst_AtFront(includes, curFile);
2038 /* Allocate and fill in new structure */
2039 curFile = bmake_malloc(sizeof *curFile);
2042 * Once the previous state has been saved, we can get down to reading
2043 * the new file. We set up the name of the file to be the absolute
2044 * name of the include file so error messages refer to the right
2047 curFile->fname = name;
2048 curFile->lineno = line;
2049 curFile->first_lineno = line;
2051 curFile->nextbuf = nextbuf;
2052 curFile->nextbuf_arg = arg;
2054 if (nextbuf == NULL) {
2056 * Allocate a 32k data buffer (as stdio seems to).
2057 * Set pointers so that first ParseReadc has to do a file read.
2059 buf = bmake_malloc(IFILE_BUFLEN);
2061 curFile->P_str = buf;
2062 curFile->P_ptr = buf;
2063 curFile->P_end = buf;
2064 curFile->P_buflen = IFILE_BUFLEN;
2066 /* Get first block of input data */
2067 buf = curFile->nextbuf(curFile->nextbuf_arg);
2069 /* Was all a waste of time ... */
2073 curFile->P_str = buf;
2074 curFile->P_ptr = buf;
2075 curFile->P_end = NULL;
2078 curFile->cond_depth = Cond_save_depth();
2079 ParseSetParseFile(name);
2084 *---------------------------------------------------------------------
2085 * ParseTraditionalInclude --
2086 * Push to another file.
2088 * The input is the current line. The file name(s) are
2089 * following the "include".
2095 * A structure is added to the includes Lst and readProc, lineno,
2096 * fname and curFILE are altered for the new file
2097 *---------------------------------------------------------------------
2100 ParseTraditionalInclude(char *line)
2102 char *cp; /* current position in file spec */
2104 int silent = (line[0] != 'i') ? 1 : 0;
2105 char *file = &line[silent + 7];
2109 fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2113 * Skip over whitespace
2115 while (isspace((unsigned char)*file))
2119 * Substitute for any variables in the file name before trying to
2122 all_files = Var_Subst(NULL, file, VAR_CMD, FALSE);
2124 if (*file == '\0') {
2125 Parse_Error(PARSE_FATAL,
2126 "Filename missing from \"include\"");
2130 for (file = all_files; !done; file = cp + 1) {
2131 /* Skip to end of line or next whitespace */
2132 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2140 Parse_include_file(file, FALSE, silent);
2147 *---------------------------------------------------------------------
2149 * Called when EOF is reached in the current file. If we were reading
2150 * an include file, the includes stack is popped and things set up
2151 * to go back to reading the previous file at the previous location.
2154 * CONTINUE if there's more to do. DONE if not.
2157 * The old curFILE, is closed. The includes list is shortened.
2158 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2159 *---------------------------------------------------------------------
2166 if (curFile->nextbuf != NULL) {
2167 /* eg .for loop data, get next iteration */
2168 ptr = curFile->nextbuf(curFile->nextbuf_arg);
2169 curFile->P_ptr = ptr;
2170 curFile->P_str = ptr;
2171 curFile->lineno = curFile->first_lineno;
2178 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2179 Cond_restore_depth(curFile->cond_depth);
2181 /* Dispose of curFile info */
2182 /* Leak curFile->fname because all the gnodes have pointers to it */
2183 if (curFile->fd != -1)
2185 free(curFile->P_str);
2188 curFile = Lst_DeQueue(includes);
2190 if (curFile == NULL) {
2191 /* We've run out of input */
2192 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2193 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2198 fprintf(debug_file, "ParseEOF: returning to file %s, line %d, fd %d\n",
2199 curFile->fname, curFile->lineno, curFile->fd);
2201 /* Restore the PARSEDIR/PARSEFILE variables */
2202 ParseSetParseFile(curFile->fname);
2207 #define PARSE_SKIP 2
2210 ParseGetLine(int flags, int *length)
2212 IFile *cf = curFile;
2222 /* Loop through blank lines and comment lines */
2232 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2233 if (cf->P_end == NULL)
2234 /* End of string (aka for loop) data */
2236 /* End of data read from file, read more data */
2237 if (ptr != cf->P_end && (ch != '\\' || ptr + 1 != cf->P_end)) {
2238 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2241 /* Move existing data to (near) start of file buffer */
2242 len = cf->P_end - cf->P_ptr;
2243 tp = cf->P_str + 32;
2244 memmove(tp, cf->P_ptr, len);
2245 dist = cf->P_ptr - tp;
2246 /* Update all pointers to reflect moved data */
2257 /* Try to read more data from file into buffer space */
2258 len = cf->P_str + cf->P_buflen - tp - 32;
2260 /* We need a bigger buffer to hold this line */
2261 tp = bmake_realloc(cf->P_str, cf->P_buflen + IFILE_BUFLEN);
2262 cf->P_ptr = cf->P_ptr - cf->P_str + tp;
2263 cf->P_end = cf->P_end - cf->P_str + tp;
2264 ptr = ptr - cf->P_str + tp;
2265 line = line - cf->P_str + tp;
2266 line_end = line_end - cf->P_str + tp;
2268 escaped = escaped - cf->P_str + tp;
2270 comment = comment - cf->P_str + tp;
2273 len += IFILE_BUFLEN;
2274 cf->P_buflen += IFILE_BUFLEN;
2276 len = read(cf->fd, tp, len);
2279 Parse_Error(PARSE_FATAL, "Makefile read error: %s",
2286 /* 0 terminate the data, and update end pointer */
2290 /* Process newly read characters */
2295 /* Don't treat next character as special, remember first one */
2296 if (escaped == NULL)
2304 if (ch == '#' && comment == NULL) {
2305 /* Remember first '#' for comment stripping */
2311 if (!isspace((unsigned char)ch))
2312 /* We are not interested in trailing whitespace */
2316 /* Save next 'to be processed' location */
2319 /* Check we have a non-comment, non-blank line */
2320 if (line_end == line || comment == line) {
2322 /* At end of file */
2324 /* Parse another line */
2328 /* We now have a line of data */
2331 if (flags & PARSE_RAW) {
2332 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2333 *length = line_end - line;
2337 if (flags & PARSE_SKIP) {
2338 /* Completely ignore non-directives */
2341 /* We could do more of the .else/.elif/.endif checks here */
2346 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2347 if (comment != NULL && line[0] != '\t') {
2352 /* If we didn't see a '\\' then the in-situ data is fine */
2353 if (escaped == NULL) {
2354 *length = line_end - line;
2358 /* Remove escapes from '\n' and '#' */
2361 for (; ; *tp++ = ch) {
2371 /* Delete '\\' at end of buffer */
2376 if (ch == '#' && line[0] != '\t')
2377 /* Delete '\\' from before '#' on non-command lines */
2381 /* Leave '\\' in buffer for later */
2383 /* Make sure we don't delete an escaped ' ' from the line end */
2388 /* Escaped '\n' replace following whitespace with a single ' ' */
2389 while (ptr[0] == ' ' || ptr[0] == '\t')
2394 /* Delete any trailing spaces - eg from empty continuations */
2395 while (tp > escaped && isspace((unsigned char)tp[-1]))
2399 *length = tp - line;
2404 *---------------------------------------------------------------------
2406 * Read an entire line from the input file. Called only by Parse_File.
2409 * A line w/o its newline
2412 * Only those associated with reading a character
2413 *---------------------------------------------------------------------
2418 char *line; /* Result */
2419 int lineLength; /* Length of result */
2420 int lineno; /* Saved line # */
2424 line = ParseGetLine(0, &lineLength);
2432 * The line might be a conditional. Ask the conditional module
2433 * about it and act accordingly
2435 switch (Cond_Eval(line)) {
2437 /* Skip to next conditional that evaluates to COND_PARSE. */
2439 line = ParseGetLine(PARSE_SKIP, &lineLength);
2440 } while (line && Cond_Eval(line) != COND_PARSE);
2446 case COND_INVALID: /* Not a conditional line */
2447 /* Check for .for loops */
2448 rval = For_Eval(line);
2450 /* Not a .for line */
2453 /* Syntax error - error printed, ignore line */
2455 /* Start of a .for loop */
2456 lineno = curFile->lineno;
2457 /* Accumulate loop lines until matching .endfor */
2459 line = ParseGetLine(PARSE_RAW, &lineLength);
2461 Parse_Error(PARSE_FATAL,
2462 "Unexpected end of file in for loop.\n");
2465 } while (For_Accum(line));
2466 /* Stash each iteration as a new 'input file' */
2468 /* Read next line from for-loop buffer */
2476 *-----------------------------------------------------------------------
2477 * ParseFinishLine --
2478 * Handle the end of a dependency group.
2484 * inLine set FALSE. 'targets' list destroyed.
2486 *-----------------------------------------------------------------------
2489 ParseFinishLine(void)
2492 Lst_ForEach(targets, Suff_EndTransform, NULL);
2493 Lst_Destroy(targets, ParseHasCommands);
2501 *---------------------------------------------------------------------
2503 * Parse a file into its component parts, incorporating it into the
2504 * current dependency graph. This is the main function and controls
2505 * almost every other function in this module
2508 * name the name of the file being read
2509 * fd Open file to makefile to parse
2516 * Loads. Nodes are added to the list of all targets, nodes and links
2517 * are added to the dependency graph. etc. etc. etc.
2518 *---------------------------------------------------------------------
2521 Parse_File(const char *name, int fd)
2523 char *cp; /* pointer into the line */
2524 char *line; /* the line we're working on */
2529 Parse_SetInput(name, 0, fd, NULL, NULL);
2532 for (; (line = ParseReadLine()) != NULL; ) {
2534 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2535 curFile->lineno, line);
2538 * Lines that begin with the special character may be
2539 * include or undef directives.
2540 * On the other hand they can be suffix rules (.c.o: ...)
2541 * or just dependencies for filenames that start '.'.
2543 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2546 if (strncmp(cp, "include", 7) == 0 ||
2547 ((cp[0] == 's' || cp[0] == '-') &&
2548 strncmp(&cp[1], "include", 7) == 0)) {
2552 if (strncmp(cp, "undef", 5) == 0) {
2554 for (cp += 5; isspace((unsigned char) *cp); cp++)
2556 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2557 (*cp2 != '\0'); cp2++)
2560 Var_Delete(cp, VAR_GLOBAL);
2562 } else if (strncmp(cp, "export", 6) == 0) {
2563 for (cp += 6; isspace((unsigned char) *cp); cp++)
2567 } else if (strncmp(cp, "unexport", 8) == 0) {
2570 } else if (strncmp(cp, "info", 4) == 0 ||
2571 strncmp(cp, "error", 5) == 0 ||
2572 strncmp(cp, "warning", 7) == 0) {
2573 if (ParseMessage(cp))
2578 if (*line == '\t') {
2580 * If a line starts with a tab, it can only hope to be
2581 * a creation command.
2585 for (; isspace ((unsigned char)*cp); cp++) {
2590 Parse_Error(PARSE_FATAL,
2591 "Unassociated shell command \"%s\"",
2594 * So long as it's not a blank line and we're actually
2595 * in a dependency spec, add the command to the list of
2596 * commands of all targets in the dependency spec
2599 cp = bmake_strdup(cp);
2600 Lst_ForEach(targets, ParseAddCmd, cp);
2602 Lst_AtEnd(targCmds, cp);
2610 if (((strncmp(line, "include", 7) == 0 &&
2611 isspace((unsigned char) line[7])) ||
2612 ((line[0] == 's' || line[0] == '-') &&
2613 strncmp(&line[1], "include", 7) == 0 &&
2614 isspace((unsigned char) line[8]))) &&
2615 strchr(line, ':') == NULL) {
2617 * It's an S3/S5-style "include".
2619 ParseTraditionalInclude(line);
2623 if (Parse_IsVar(line)) {
2625 Parse_DoVar(line, VAR_GLOBAL);
2631 * To make life easier on novices, if the line is indented we
2632 * first make sure the line has a dependency operator in it.
2633 * If it doesn't have an operator and we're in a dependency
2634 * line's script, we assume it's actually a shell command
2635 * and add it to the current list of targets.
2638 if (isspace((unsigned char) line[0])) {
2639 while ((*cp != '\0') && isspace((unsigned char) *cp))
2641 while (*cp && (ParseIsEscaped(line, cp) ||
2642 (*cp != ':') && (*cp != '!'))) {
2647 Parse_Error(PARSE_WARNING,
2648 "Shell command needs a leading tab");
2657 * For some reason - probably to make the parser impossible -
2658 * a ';' can be used to separate commands from dependencies.
2659 * Attempt to avoid ';' inside substitution patterns.
2664 for (cp = line; *cp != 0; cp++) {
2665 if (*cp == '\\' && cp[1] != 0) {
2670 (cp[1] == '(' || cp[1] == '{')) {
2675 if (*cp == ')' || *cp == '}') {
2679 } else if (*cp == ';') {
2685 /* Terminate the dependency list at the ';' */
2691 * We now know it's a dependency line so it needs to have all
2692 * variables expanded before being parsed. Tell the variable
2693 * module to complain if some variable is undefined...
2695 line = Var_Subst(NULL, line, VAR_CMD, TRUE);
2698 * Need a non-circular list for the target nodes
2701 Lst_Destroy(targets, NULL);
2703 targets = Lst_Init(FALSE);
2706 ParseDoDependency(line);
2709 /* If there were commands after a ';', add them now */
2715 * Reached EOF, but it may be just EOF of an include file...
2717 } while (ParseEOF() == CONTINUE);
2720 (void)fflush(stdout);
2721 (void)fprintf(stderr,
2722 "%s: Fatal errors encountered -- cannot continue\n",
2724 PrintOnError(NULL, NULL);
2730 *---------------------------------------------------------------------
2732 * initialize the parsing module
2738 * the parseIncPath list is initialized...
2739 *---------------------------------------------------------------------
2745 parseIncPath = Lst_Init(FALSE);
2746 sysIncPath = Lst_Init(FALSE);
2747 defIncPath = Lst_Init(FALSE);
2748 includes = Lst_Init(FALSE);
2750 targCmds = Lst_Init(FALSE);
2758 Lst_Destroy(targCmds, (FreeProc *)free);
2760 Lst_Destroy(targets, NULL);
2761 Lst_Destroy(defIncPath, Dir_Destroy);
2762 Lst_Destroy(sysIncPath, Dir_Destroy);
2763 Lst_Destroy(parseIncPath, Dir_Destroy);
2764 Lst_Destroy(includes, NULL); /* Should be empty now */
2770 *-----------------------------------------------------------------------
2772 * Return a Lst of the main target to create for main()'s sake. If
2773 * no such target exists, we Punt with an obnoxious error message.
2776 * A Lst of the single node to create.
2781 *-----------------------------------------------------------------------
2784 Parse_MainName(void)
2786 Lst mainList; /* result list */
2788 mainList = Lst_Init(FALSE);
2790 if (mainNode == NULL) {
2791 Punt("no target to make.");
2793 } else if (mainNode->type & OP_DOUBLEDEP) {
2794 (void)Lst_AtEnd(mainList, mainNode);
2795 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
2798 (void)Lst_AtEnd(mainList, mainNode);
2799 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
2804 *-----------------------------------------------------------------------
2806 * Add the filename and lineno to the GNode so that we remember
2807 * where it was first defined.
2812 *-----------------------------------------------------------------------
2815 ParseMark(GNode *gn)
2817 gn->fname = curFile->fname;
2818 gn->lineno = curFile->lineno;