1 /* $NetBSD: parse.c,v 1.148 2008/10/29 15:37:08 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.148 2008/10/29 15:37:08 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.148 2008/10/29 15:37:08 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; /* line number in file */
160 int fd; /* the open file */
161 int cond_depth; /* 'if' nesting when file opened */
162 char *P_str; /* point to base of string buffer */
163 char *P_ptr; /* point to next char of string buffer */
164 char *P_end; /* point to the end of string buffer */
165 int P_buflen; /* current size of file buffer */
168 #define IFILE_BUFLEN 0x8000
169 static IFile *curFile;
173 * Definitions for handling #include specifications
176 static Lst includes; /* stack of IFiles generated by .includes */
177 Lst parseIncPath; /* list of directories for "..." includes */
178 Lst sysIncPath; /* list of directories for <...> includes */
179 Lst defIncPath; /* default directories for <...> includes */
182 * specType contains the SPECial TYPE of the current target. It is
183 * Not if the target is unspecial. If it *is* special, however, the children
184 * are linked as children of the parent but not vice versa. This variable is
185 * set in ParseDoDependency
189 Default, /* .DEFAULT */
191 Ignore, /* .IGNORE */
192 Includes, /* .INCLUDES */
193 Interrupt, /* .INTERRUPT */
195 MFlags, /* .MFLAGS or .MAKEFLAGS */
196 Main, /* .MAIN and we don't have anything user-specified to
198 NoExport, /* .NOEXPORT */
199 NoPath, /* .NOPATH */
200 Not, /* Not special */
201 NotParallel, /* .NOTPARALLEL */
203 ExObjdir, /* .OBJDIR */
205 Parallel, /* .PARALLEL */
211 Precious, /* .PRECIOUS */
212 ExShell, /* .SHELL */
213 Silent, /* .SILENT */
214 SingleShell, /* .SINGLESHELL */
215 Suffixes, /* .SUFFIXES */
217 Attribute /* Generic attribute */
220 static ParseSpecial specType;
225 * Predecessor node for handling .ORDER. Initialized to NILGNODE when .ORDER
226 * seen, then set to each successive source on the line.
228 static GNode *predecessor;
231 * The parseKeywords table is searched using binary search when deciding
232 * if a target or source is special. The 'spec' field is the ParseSpecial
233 * type of the keyword ("Not" if the keyword isn't special as a target) while
234 * the 'op' field is the operator to apply to the list of targets if the
235 * keyword is used as a source ("0" if the keyword isn't special as a source)
238 const char *name; /* Name of keyword */
239 ParseSpecial spec; /* Type when used as a target */
240 int op; /* Operator when used as a source */
241 } parseKeywords[] = {
242 { ".BEGIN", Begin, 0 },
243 { ".DEFAULT", Default, 0 },
245 { ".EXEC", Attribute, OP_EXEC },
246 { ".IGNORE", Ignore, OP_IGNORE },
247 { ".INCLUDES", Includes, 0 },
248 { ".INTERRUPT", Interrupt, 0 },
249 { ".INVISIBLE", Attribute, OP_INVISIBLE },
250 { ".JOIN", Attribute, OP_JOIN },
251 { ".LIBS", Libs, 0 },
252 { ".MADE", Attribute, OP_MADE },
253 { ".MAIN", Main, 0 },
254 { ".MAKE", Attribute, OP_MAKE },
255 { ".MAKEFLAGS", MFlags, 0 },
256 { ".MFLAGS", MFlags, 0 },
257 { ".NOPATH", NoPath, OP_NOPATH },
258 { ".NOTMAIN", Attribute, OP_NOTMAIN },
259 { ".NOTPARALLEL", NotParallel, 0 },
260 { ".NO_PARALLEL", NotParallel, 0 },
261 { ".NULL", Null, 0 },
262 { ".OBJDIR", ExObjdir, 0 },
263 { ".OPTIONAL", Attribute, OP_OPTIONAL },
264 { ".ORDER", Order, 0 },
265 { ".PARALLEL", Parallel, 0 },
266 { ".PATH", ExPath, 0 },
267 { ".PHONY", Phony, OP_PHONY },
269 { ".POSIX", Posix, 0 },
271 { ".PRECIOUS", Precious, OP_PRECIOUS },
272 { ".RECURSIVE", Attribute, OP_MAKE },
273 { ".SHELL", ExShell, 0 },
274 { ".SILENT", Silent, OP_SILENT },
275 { ".SINGLESHELL", SingleShell, 0 },
276 { ".SUFFIXES", Suffixes, 0 },
277 { ".USE", Attribute, OP_USE },
278 { ".USEBEFORE", Attribute, OP_USEBEFORE },
279 { ".WAIT", Wait, 0 },
282 static int ParseIsEscaped(const char *, const char *);
283 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
284 __attribute__((__format__(__printf__, 4, 5)));
285 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
286 __attribute__((__format__(__printf__, 5, 0)));
287 static int ParseFindKeyword(const char *);
288 static int ParseLinkSrc(ClientData, ClientData);
289 static int ParseDoOp(ClientData, ClientData);
290 static void ParseDoSrc(int, const char *);
291 static int ParseFindMain(ClientData, ClientData);
292 static int ParseAddDir(ClientData, ClientData);
293 static int ParseClearPath(ClientData, ClientData);
294 static void ParseDoDependency(char *);
295 static int ParseAddCmd(ClientData, ClientData);
296 static void ParseHasCommands(ClientData);
297 static void ParseDoInclude(char *);
298 static void ParseSetParseFile(const char *);
300 static void ParseTraditionalInclude(char *);
302 static int ParseEOF(void);
303 static char *ParseReadLine(void);
304 static void ParseFinishLine(void);
305 static void ParseMark(GNode *);
311 *----------------------------------------------------------------------
313 * Check if the current character is escaped on the current line
316 * 0 if the character is not backslash escaped, 1 otherwise
320 *----------------------------------------------------------------------
323 ParseIsEscaped(const char *line, const char *c)
336 *----------------------------------------------------------------------
337 * ParseFindKeyword --
338 * Look in the table of keywords for one matching the given string.
344 * The index of the keyword, or -1 if it isn't there.
348 *----------------------------------------------------------------------
351 ParseFindKeyword(const char *str)
357 end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
360 cur = start + ((end - start) / 2);
361 diff = strcmp(str, parseKeywords[cur].name);
365 } else if (diff < 0) {
370 } while (start <= end);
375 * ParseVErrorInternal --
376 * Error message abort function for parsing. Prints out the context
377 * of the error (line number and file) as well as the message with
378 * two optional arguments.
384 * "fatals" is incremented if the level is PARSE_FATAL.
388 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
389 const char *fmt, va_list ap)
391 static Boolean fatal_warning_error_printed = FALSE;
393 (void)fprintf(f, "%s: ", progname);
395 if (cfname != NULL) {
396 (void)fprintf(f, "\"");
397 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
402 * Nothing is more anoying than not knowing
403 * which Makefile is the culprit.
405 dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
406 if (dir == NULL || *dir == '\0' ||
407 (*dir == '.' && dir[1] == '\0'))
408 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
412 (void)fprintf(f, "%s/%s", dir, cfname);
414 (void)fprintf(f, "%s", cfname);
416 (void)fprintf(f, "\" line %d: ", (int)clineno);
418 if (type == PARSE_WARNING)
419 (void)fprintf(f, "warning: ");
420 (void)vfprintf(f, fmt, ap);
421 (void)fprintf(f, "\n");
423 if (type == PARSE_FATAL || parseWarnFatal)
425 if (parseWarnFatal && !fatal_warning_error_printed) {
426 Error("parsing warnings being treated as errors");
427 fatal_warning_error_printed = TRUE;
432 * ParseErrorInternal --
443 ParseErrorInternal(const char *cfname, size_t clineno, int type,
444 const char *fmt, ...)
449 ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
452 if (debug_file != stderr && debug_file != stdout) {
454 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
461 * External interface to ParseErrorInternal; uses the default filename
472 Parse_Error(int type, const char *fmt, ...)
477 if (curFile == (IFile *)NIL) {
479 static IFile intFile = {
486 ParseVErrorInternal(stderr, curFile->fname, curFile->lineno,
490 if (debug_file != stderr && debug_file != stdout) {
492 ParseVErrorInternal(debug_file, curFile->fname, curFile->lineno,
497 * if we get this far, make sure we don't leave curFile
498 * pointing to our dummy one.
500 if (curFile->fname == NULL) {
501 curFile = (IFile *)NIL;
506 *---------------------------------------------------------------------
508 * Link the parent node to its new child. Used in a Lst_ForEach by
509 * ParseDoDependency. If the specType isn't 'Not', the parent
510 * isn't linked as a parent of the child.
513 * pgnp The parent node
514 * cgpn The child node
520 * New elements are added to the parents list of cgn and the
521 * children list of cgn. the unmade field of pgn is updated
522 * to reflect the additional child.
523 *---------------------------------------------------------------------
526 ParseLinkSrc(ClientData pgnp, ClientData cgnp)
528 GNode *pgn = (GNode *)pgnp;
529 GNode *cgn = (GNode *)cgnp;
531 if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
532 pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
533 (void)Lst_AtEnd(pgn->children, cgn);
535 (void)Lst_AtEnd(cgn->parents, pgn);
538 fprintf(debug_file, "# ParseLinkSrc: added child %s - %s\n", pgn->name, cgn->name);
539 Targ_PrintNode(pgn, 0);
540 Targ_PrintNode(cgn, 0);
546 *---------------------------------------------------------------------
548 * Apply the parsed operator to the given target node. Used in a
549 * Lst_ForEach call by ParseDoDependency once all targets have
550 * been found and their operator parsed. If the previous and new
551 * operators are incompatible, a major error is taken.
554 * gnp The node to which the operator is to be applied
555 * opp The operator to apply
561 * The type field of the node is altered to reflect any new bits in
563 *---------------------------------------------------------------------
566 ParseDoOp(ClientData gnp, ClientData opp)
568 GNode *gn = (GNode *)gnp;
569 int op = *(int *)opp;
571 * If the dependency mask of the operator and the node don't match and
572 * the node has actually had an operator applied to it before, and
573 * the operator actually has some dependency information in it, complain.
575 if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
576 !OP_NOP(gn->type) && !OP_NOP(op))
578 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
582 if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
584 * If the node was the object of a :: operator, we need to create a
585 * new instance of it for the children and commands on this dependency
586 * line. The new instance is placed on the 'cohorts' list of the
587 * initial one (note the initial one is not on its own cohorts list)
588 * and the new instance is linked to all parents of the initial
594 * Propagate copied bits to the initial node. They'll be propagated
595 * back to the rest of the cohorts later.
597 gn->type |= op & ~OP_OPMASK;
599 cohort = Targ_FindNode(gn->name, TARG_NOHASH);
601 * Make the cohort invisible as well to avoid duplicating it into
602 * other variables. True, parents of this target won't tend to do
603 * anything with their local variables, but better safe than
604 * sorry. (I think this is pointless now, since the relevant list
605 * traversals will no longer see this node anyway. -mycroft)
607 cohort->type = op | OP_INVISIBLE;
608 (void)Lst_AtEnd(gn->cohorts, cohort);
609 cohort->centurion = gn;
610 gn->unmade_cohorts += 1;
611 snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
615 * We don't want to nuke any previous flags (whatever they were) so we
616 * just OR the new operator into the old
625 *---------------------------------------------------------------------
627 * Given the name of a source, figure out if it is an attribute
628 * and apply it to the targets if it is. Else decide if there is
629 * some attribute which should be applied *to* the source because
630 * of some special target and apply it if so. Otherwise, make the
631 * source be a child of the targets in the list 'targets'
634 * tOp operator (if any) from special targets
635 * src name of the source to handle
641 * Operator bits may be added to the list of targets or to the source.
642 * The targets may have a new source added to their lists of children.
643 *---------------------------------------------------------------------
646 ParseDoSrc(int tOp, const char *src)
649 static int wait_number = 0;
652 if (*src == '.' && isupper ((unsigned char)src[1])) {
653 int keywd = ParseFindKeyword(src);
655 int op = parseKeywords[keywd].op;
657 Lst_ForEach(targets, ParseDoOp, &op);
660 if (parseKeywords[keywd].spec == Wait) {
662 * We add a .WAIT node in the dependency list.
663 * After any dynamic dependencies (and filename globbing)
664 * have happened, it is given a dependency on the each
665 * previous child back to and previous .WAIT node.
666 * The next child won't be scheduled until the .WAIT node
668 * We give each .WAIT node a unique name (mainly for diag).
670 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
671 gn = Targ_FindNode(wait_src, TARG_NOHASH);
672 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
673 Lst_ForEach(targets, ParseLinkSrc, gn);
682 * If we have noted the existence of a .MAIN, it means we need
683 * to add the sources of said target to the list of things
684 * to create. The string 'src' is likely to be free, so we
685 * must make a new copy of it. Note that this will only be
686 * invoked if the user didn't specify a target on the command
687 * line. This is to allow #ifmake's to succeed, or something...
689 (void)Lst_AtEnd(create, bmake_strdup(src));
691 * Add the name to the .TARGETS variable as well, so the user can
692 * employ that, if desired.
694 Var_Append(".TARGETS", src, VAR_GLOBAL);
699 * Create proper predecessor/successor links between the previous
700 * source and the current one.
702 gn = Targ_FindNode(src, TARG_CREATE);
703 if (predecessor != NILGNODE) {
704 (void)Lst_AtEnd(predecessor->order_succ, gn);
705 (void)Lst_AtEnd(gn->order_pred, predecessor);
707 fprintf(debug_file, "# ParseDoSrc: added Order dependency %s - %s\n",
708 predecessor->name, gn->name);
709 Targ_PrintNode(predecessor, 0);
710 Targ_PrintNode(gn, 0);
714 * The current source now becomes the predecessor for the next one.
721 * If the source is not an attribute, we need to find/create
722 * a node for it. After that we can apply any operator to it
723 * from a special target or link it to its parents, as
726 * In the case of a source that was the object of a :: operator,
727 * the attribute is applied to all of its instances (as kept in
728 * the 'cohorts' list of the node) or all the cohorts are linked
729 * to all the targets.
732 /* Find/create the 'src' node and attach to all targets */
733 gn = Targ_FindNode(src, TARG_CREATE);
737 Lst_ForEach(targets, ParseLinkSrc, gn);
744 *-----------------------------------------------------------------------
746 * Find a real target in the list and set it to be the main one.
747 * Called by ParseDoDependency when a main target hasn't been found
751 * gnp Node to examine
754 * 0 if main not found yet, 1 if it is.
757 * mainNode is changed and Targ_SetMain is called.
759 *-----------------------------------------------------------------------
762 ParseFindMain(ClientData gnp, ClientData dummy)
764 GNode *gn = (GNode *)gnp;
765 if ((gn->type & OP_NOTARGET) == 0) {
768 return (dummy ? 1 : 1);
770 return (dummy ? 0 : 0);
775 *-----------------------------------------------------------------------
777 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
785 *-----------------------------------------------------------------------
788 ParseAddDir(ClientData path, ClientData name)
790 (void)Dir_AddDir((Lst) path, (char *)name);
795 *-----------------------------------------------------------------------
797 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
805 *-----------------------------------------------------------------------
808 ParseClearPath(ClientData path, ClientData dummy)
810 Dir_ClearPath((Lst) path);
811 return(dummy ? 0 : 0);
815 *---------------------------------------------------------------------
816 * ParseDoDependency --
817 * Parse the dependency line in line.
820 * line the line to parse
826 * The nodes of the sources are linked as children to the nodes of the
827 * targets. Some nodes may be created.
829 * We parse a dependency line by first extracting words from the line and
830 * finding nodes in the list of all targets with that name. This is done
831 * until a character is encountered which is an operator character. Currently
832 * these are only ! and :. At this point the operator is parsed and the
833 * pointer into the line advanced until the first source is encountered.
834 * The parsed operator is applied to each node in the 'targets' list,
835 * which is where the nodes found for the targets are kept, by means of
836 * the ParseDoOp function.
837 * The sources are read in much the same way as the targets were except
838 * that now they are expanded using the wildcarding scheme of the C-Shell
839 * and all instances of the resulting words in the list of all targets
840 * are found. Each of the resulting nodes is then linked to each of the
841 * targets as one of its children.
842 * Certain targets are handled specially. These are the ones detailed
843 * by the specType variable.
844 * The storing of transformation rules is also taken care of here.
845 * A target is recognized as a transformation rule by calling
846 * Suff_IsTransform. If it is a transformation rule, its node is gotten
847 * from the suffix module via Suff_AddTransform rather than the standard
848 * Targ_FindNode in the target module.
849 *---------------------------------------------------------------------
852 ParseDoDependency(char *line)
854 char *cp; /* our current position */
855 GNode *gn = NULL; /* a general purpose temporary node */
856 int op; /* the operator on the line */
857 char savec; /* a place to save a character */
858 Lst paths; /* List of search paths to alter when parsing
859 * a list of .PATH targets */
860 int tOp; /* operator from special target */
861 Lst sources; /* list of archive source names after
863 Lst curTargs; /* list of target names to be found and added
864 * to the targets list */
868 fprintf(debug_file, "ParseDoDependency(%s)\n", line);
874 curTargs = Lst_Init(FALSE);
877 for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
878 !(isspace((unsigned char)*cp) ||
879 *cp == '!' || *cp == ':' || *cp == LPAREN));
883 * Must be a dynamic source (would have been expanded
884 * otherwise), so call the Var module to parse the puppy
885 * so we can safely advance beyond it...There should be
886 * no errors in this, as they would have been discovered
887 * in the initial Var_Subst and we wouldn't be here.
893 result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
900 if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
902 * Archives must be handled specially to make sure the OP_ARCHV
903 * flag is set in their 'type' field, for one thing, and because
904 * things like "archive(file1.o file2.o file3.o)" are permissible.
905 * Arch_ParseArchive will set 'line' to be the first non-blank
906 * after the archive-spec. It creates/finds nodes for the members
907 * and places them on the given list, returning SUCCESS if all
908 * went well and FAILURE if there was an error in the
909 * specification. On error, line should remain untouched.
911 if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
912 Parse_Error(PARSE_FATAL,
913 "Error in archive specification: \"%s\"", line);
923 * Ending a dependency line without an operator is a Bozo
924 * no-no. As a heuristic, this is also often triggered by
925 * undetected conflicts from cvs/rcs merges.
927 if ((strncmp(line, "<<<<<<", 6) == 0) ||
928 (strncmp(line, "======", 6) == 0) ||
929 (strncmp(line, ">>>>>>", 6) == 0))
930 Parse_Error(PARSE_FATAL,
931 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
933 Parse_Error(PARSE_FATAL, "Need an operator");
939 * Have a word in line. See if it's a special target and set
940 * specType to match it.
942 if (*line == '.' && isupper ((unsigned char)line[1])) {
944 * See if the target is a special target that must have it
945 * or its sources handled specially.
947 int keywd = ParseFindKeyword(line);
949 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
950 Parse_Error(PARSE_FATAL, "Mismatched special targets");
954 specType = parseKeywords[keywd].spec;
955 tOp = parseKeywords[keywd].op;
958 * Certain special targets have special semantics:
959 * .PATH Have to set the dirSearchPath
961 * .MAIN Its sources are only used if
962 * nothing has been specified to
964 * .DEFAULT Need to create a node to hang
965 * commands on, but we don't want
966 * it in the graph, nor do we want
967 * it to be the Main Target, so we
968 * create it, set OP_NOTMAIN and
969 * add it to the list, setting
970 * DEFAULT to the new node for
971 * later use. We claim the node is
972 * A transformation rule to make
973 * life easier later, when we'll
974 * use Make_HandleUse to actually
975 * apply the .DEFAULT commands.
976 * .PHONY The list of targets
977 * .NOPATH Don't search for file in the path
980 * .INTERRUPT Are not to be considered the
982 * .NOTPARALLEL Make only one target at a time.
983 * .SINGLESHELL Create a shell for each command.
984 * .ORDER Must set initial predecessor to NIL
989 paths = Lst_Init(FALSE);
991 (void)Lst_AtEnd(paths, dirSearchPath);
994 if (!Lst_IsEmpty(create)) {
1001 gn = Targ_FindNode(line, TARG_CREATE);
1002 gn->type |= OP_NOTMAIN|OP_SPECIAL;
1003 (void)Lst_AtEnd(targets, gn);
1006 gn = Targ_NewGN(".DEFAULT");
1007 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1008 (void)Lst_AtEnd(targets, gn);
1018 predecessor = NILGNODE;
1023 } else if (strncmp(line, ".PATH", 5) == 0) {
1025 * .PATH<suffix> has to be handled specially.
1026 * Call on the suffix module to give us a path to
1032 path = Suff_GetPath(&line[5]);
1033 if (path == NILLST) {
1034 Parse_Error(PARSE_FATAL,
1035 "Suffix '%s' not defined (yet)",
1039 if (paths == (Lst)NULL) {
1040 paths = Lst_Init(FALSE);
1042 (void)Lst_AtEnd(paths, path);
1048 * Have word in line. Get or create its node and stick it at
1049 * the end of the targets list
1051 if ((specType == Not) && (*line != '\0')) {
1052 if (Dir_HasWildcards(line)) {
1054 * Targets are to be sought only in the current directory,
1055 * so create an empty path for the thing. Note we need to
1056 * use Dir_Destroy in the destruction of the path as the
1057 * Dir module could have added a directory to the path...
1059 Lst emptyPath = Lst_Init(FALSE);
1061 Dir_Expand(line, emptyPath, curTargs);
1063 Lst_Destroy(emptyPath, Dir_Destroy);
1066 * No wildcards, but we want to avoid code duplication,
1067 * so create a list with the word on it.
1069 (void)Lst_AtEnd(curTargs, line);
1072 while(!Lst_IsEmpty(curTargs)) {
1073 char *targName = (char *)Lst_DeQueue(curTargs);
1075 if (!Suff_IsTransform (targName)) {
1076 gn = Targ_FindNode(targName, TARG_CREATE);
1078 gn = Suff_AddTransform(targName);
1081 (void)Lst_AtEnd(targets, gn);
1083 } else if (specType == ExPath && *line != '.' && *line != '\0') {
1084 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1089 * If it is a special type and not .PATH, it's the only target we
1090 * allow on this line...
1092 if (specType != Not && specType != ExPath) {
1093 Boolean warning = FALSE;
1095 while (*cp && (ParseIsEscaped(lstart, cp) ||
1096 ((*cp != '!') && (*cp != ':')))) {
1097 if (ParseIsEscaped(lstart, cp) ||
1098 (*cp != ' ' && *cp != '\t')) {
1104 Parse_Error(PARSE_WARNING, "Extra target ignored");
1107 while (*cp && isspace ((unsigned char)*cp)) {
1112 } while (*line && (ParseIsEscaped(lstart, line) ||
1113 ((*line != '!') && (*line != ':'))));
1116 * Don't need the list of target names anymore...
1118 Lst_Destroy(curTargs, NOFREE);
1121 if (!Lst_IsEmpty(targets)) {
1124 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1131 * These four create nodes on which to hang commands, so
1132 * targets shouldn't be empty...
1136 * Nothing special here -- targets can be empty if it wants.
1143 * Have now parsed all the target names. Must parse the operator next. The
1144 * result is left in op .
1148 } else if (*cp == ':') {
1156 Parse_Error(PARSE_FATAL, "Missing dependency operator");
1160 cp++; /* Advance beyond operator */
1162 Lst_ForEach(targets, ParseDoOp, &op);
1165 * Get to the first source
1167 while (*cp && isspace ((unsigned char)*cp)) {
1173 * Several special targets take different actions if present with no
1175 * a .SUFFIXES line with no sources clears out all old suffixes
1176 * a .PRECIOUS line makes all targets precious
1177 * a .IGNORE line ignores errors for all targets
1178 * a .SILENT line creates silence when making all targets
1179 * a .PATH removes all directories from the search path(s).
1184 Suff_ClearSuffixes();
1190 ignoreErrors = TRUE;
1196 Lst_ForEach(paths, ParseClearPath, NULL);
1201 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1207 } else if (specType == MFlags) {
1209 * Call on functions in main.c to deal with these arguments and
1210 * set the initial character to a null-character so the loop to
1211 * get sources won't get anything
1213 Main_ParseArgLine(line);
1215 } else if (specType == ExShell) {
1216 if (Job_ParseShell(line) != SUCCESS) {
1217 Parse_Error(PARSE_FATAL, "improper shell specification");
1221 } else if ((specType == NotParallel) || (specType == SingleShell)) {
1226 * NOW GO FOR THE SOURCES
1228 if ((specType == Suffixes) || (specType == ExPath) ||
1229 (specType == Includes) || (specType == Libs) ||
1230 (specType == Null) || (specType == ExObjdir))
1234 * If the target was one that doesn't take files as its sources
1235 * but takes something like suffixes, we take each
1236 * space-separated word on the line as a something and deal
1237 * with it accordingly.
1239 * If the target was .SUFFIXES, we take each source as a
1240 * suffix and add it to the list of suffixes maintained by the
1243 * If the target was a .PATH, we add the source as a directory
1244 * to search on the search path.
1246 * If it was .INCLUDES, the source is taken to be the suffix of
1247 * files which will be #included and whose search path should
1248 * be present in the .INCLUDES variable.
1250 * If it was .LIBS, the source is taken to be the suffix of
1251 * files which are considered libraries and whose search path
1252 * should be present in the .LIBS variable.
1254 * If it was .NULL, the source is the suffix to use when a file
1255 * has no valid suffix.
1257 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1258 * and will cause make to do a new chdir to that path.
1260 while (*cp && !isspace ((unsigned char)*cp)) {
1267 Suff_AddSuffix(line, &mainNode);
1270 Lst_ForEach(paths, ParseAddDir, line);
1273 Suff_AddInclude(line);
1282 Main_SetObjdir(line);
1288 if (savec != '\0') {
1291 while (*cp && isspace ((unsigned char)*cp)) {
1297 Lst_Destroy(paths, NOFREE);
1299 if (specType == ExPath)
1304 * The targets take real sources, so we must beware of archive
1305 * specifications (i.e. things with left parentheses in them)
1306 * and handle them accordingly.
1308 for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1309 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1311 * Only stop for a left parenthesis if it isn't at the
1312 * start of a word (that'll be for variable changes
1313 * later) and isn't preceded by a dollar sign (a dynamic
1320 if (*cp == LPAREN) {
1321 sources = Lst_Init(FALSE);
1322 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1323 Parse_Error(PARSE_FATAL,
1324 "Error in source archive spec \"%s\"", line);
1328 while (!Lst_IsEmpty (sources)) {
1329 gn = (GNode *)Lst_DeQueue(sources);
1330 ParseDoSrc(tOp, gn->name);
1332 Lst_Destroy(sources, NOFREE);
1340 ParseDoSrc(tOp, line);
1342 while (*cp && isspace ((unsigned char)*cp)) {
1349 if (mainNode == NILGNODE) {
1351 * If we have yet to decide on a main target to make, in the
1352 * absence of any user input, we want the first target on
1353 * the first dependency line that is actually a real target
1354 * (i.e. isn't a .USE or .EXEC rule) to be made.
1356 Lst_ForEach(targets, ParseFindMain, NULL);
1361 Lst_Destroy(curTargs, NOFREE);
1365 *---------------------------------------------------------------------
1367 * Return TRUE if the passed line is a variable assignment. A variable
1368 * assignment consists of a single word followed by optional whitespace
1369 * followed by either a += or an = operator.
1370 * This function is used both by the Parse_File function and main when
1371 * parsing the command-line arguments.
1374 * line the line to check
1377 * TRUE if it is. FALSE if it ain't
1381 *---------------------------------------------------------------------
1384 Parse_IsVar(char *line)
1386 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1387 Boolean haveName = FALSE; /* Set TRUE if have a variable name */
1389 #define ISEQOPERATOR(c) \
1390 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1393 * Skip to variable name
1395 for (;(*line == ' ') || (*line == '\t'); line++)
1398 for (; *line != '=' || level != 0; line++)
1402 * end-of-line -- can't be a variable assignment.
1409 * there can be as much white space as desired so long as there is
1410 * only one word before the operator
1426 if (wasSpace && haveName) {
1427 if (ISEQOPERATOR(*line)) {
1429 * We must have a finished word
1435 * When an = operator [+?!:] is found, the next
1436 * character must be an = or it ain't a valid
1443 * This is a shell command
1445 if (strncmp(line, ":sh", 3) == 0)
1450 * This is the start of another word, so not assignment.
1465 *---------------------------------------------------------------------
1467 * Take the variable assignment in the passed line and do it in the
1470 * Note: There is a lexical ambiguity with assignment modifier characters
1471 * in variable names. This routine interprets the character before the =
1472 * as a modifier. Therefore, an assignment like
1474 * is interpreted as "C+ +=" instead of "C++ =".
1477 * line a line guaranteed to be a variable assignment.
1478 * This reduces error checks
1479 * ctxt Context in which to do the assignment
1485 * the variable structure of the given variable name is altered in the
1487 *---------------------------------------------------------------------
1490 Parse_DoVar(char *line, GNode *ctxt)
1492 char *cp; /* pointer into line */
1494 VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1495 } type; /* Type of assignment */
1496 char *opc; /* ptr to operator character to
1497 * null-terminate the variable name */
1498 Boolean freeCp = FALSE; /* TRUE if cp needs to be freed,
1499 * i.e. if any variable expansion was
1503 * Skip to variable name
1505 while ((*line == ' ') || (*line == '\t')) {
1510 * Skip to operator character, nulling out whitespace as we go
1512 for (cp = line + 1; *cp != '='; cp++) {
1513 if (isspace ((unsigned char)*cp)) {
1517 opc = cp-1; /* operator is the previous character */
1518 *cp++ = '\0'; /* nuke the = */
1521 * Check operator type
1531 * If the variable already has a value, we don't do anything.
1534 if (Var_Exists(line, ctxt)) {
1553 while (opc > line && *opc != ':')
1556 if (strncmp(opc, ":sh", 3) == 0) {
1566 while (isspace ((unsigned char)*cp)) {
1570 if (type == VAR_APPEND) {
1571 Var_Append(line, cp, ctxt);
1572 } else if (type == VAR_SUBST) {
1574 * Allow variables in the old value to be undefined, but leave their
1575 * invocation alone -- this is done by forcing oldVars to be false.
1576 * XXX: This can cause recursive variables, but that's not hard to do,
1577 * and this allows someone to do something like
1579 * CFLAGS = $(.INCLUDES)
1580 * CFLAGS := -I.. $(CFLAGS)
1582 * And not get an error.
1584 Boolean oldOldVars = oldVars;
1589 * make sure that we set the variable the first time to nothing
1590 * so that it gets substituted!
1592 if (!Var_Exists(line, ctxt))
1593 Var_Set(line, "", ctxt, 0);
1595 cp = Var_Subst(NULL, cp, ctxt, FALSE);
1596 oldVars = oldOldVars;
1599 Var_Set(line, cp, ctxt, 0);
1600 } else if (type == VAR_SHELL) {
1604 if (strchr(cp, '$') != NULL) {
1606 * There's a dollar sign in the command, so perform variable
1607 * expansion on the whole thing. The resulting string will need
1608 * freeing when we're done, so set freeCmd to TRUE.
1610 cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1614 res = Cmd_Exec(cp, &error);
1615 Var_Set(line, res, ctxt, 0);
1619 Parse_Error(PARSE_WARNING, error, cp);
1622 * Normal assignment -- just do it.
1624 Var_Set(line, cp, ctxt, 0);
1626 if (strcmp(line, MAKEOVERRIDES) == 0)
1627 Main_ExportMAKEFLAGS(FALSE); /* re-export MAKEFLAGS */
1628 else if (strcmp(line, ".CURDIR") == 0) {
1630 * Somone is being (too?) clever...
1631 * Let's pretend they know what they are doing and
1632 * re-initialize the 'cur' Path.
1636 } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1638 } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1648 * Lst_ForEach function to add a command line to all targets
1651 * gnp the node to which the command is to be added
1652 * cmd the command to add
1658 * A new element is added to the commands list of the node.
1661 ParseAddCmd(ClientData gnp, ClientData cmd)
1663 GNode *gn = (GNode *)gnp;
1665 /* Add to last (ie current) cohort for :: targets */
1666 if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1667 gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1669 /* if target already supplied, ignore commands */
1670 if (!(gn->type & OP_HAS_COMMANDS)) {
1671 (void)Lst_AtEnd(gn->commands, cmd);
1675 /* XXX: We cannot do this until we fix the tree */
1676 (void)Lst_AtEnd(gn->commands, cmd);
1677 Parse_Error(PARSE_WARNING,
1678 "overriding commands for target \"%s\"; "
1679 "previous commands defined at %s: %d ignored",
1680 gn->name, gn->fname, gn->lineno);
1682 Parse_Error(PARSE_WARNING,
1683 "duplicate script for target \"%s\" ignored",
1685 ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1686 "using previous script for \"%s\" defined here",
1694 *-----------------------------------------------------------------------
1695 * ParseHasCommands --
1696 * Callback procedure for Parse_File when destroying the list of
1697 * targets on the last dependency line. Marks a target as already
1698 * having commands if it does, to keep from having shell commands
1699 * on multiple dependency lines.
1702 * gnp Node to examine
1708 * OP_HAS_COMMANDS may be set for the target.
1710 *-----------------------------------------------------------------------
1713 ParseHasCommands(ClientData gnp)
1715 GNode *gn = (GNode *)gnp;
1716 if (!Lst_IsEmpty(gn->commands)) {
1717 gn->type |= OP_HAS_COMMANDS;
1722 *-----------------------------------------------------------------------
1723 * Parse_AddIncludeDir --
1724 * Add a directory to the path searched for included makefiles
1725 * bracketed by double-quotes. Used by functions in main.c
1728 * dir The name of the directory to add
1734 * The directory is appended to the list.
1736 *-----------------------------------------------------------------------
1739 Parse_AddIncludeDir(char *dir)
1741 (void)Dir_AddDir(parseIncPath, dir);
1745 *---------------------------------------------------------------------
1747 * Push to another file.
1749 * The input is the line minus the `.'. A file spec is a string
1750 * enclosed in <> or "". The former is looked for only in sysIncPath.
1751 * The latter in . and the directories specified by -I command line
1758 * A structure is added to the includes Lst and readProc, lineno,
1759 * fname and curFILE are altered for the new file
1760 *---------------------------------------------------------------------
1764 Parse_include_file(char *file, Boolean isSystem, int silent)
1766 char *fullname; /* full pathname of file */
1768 char *prefEnd, *incdir;
1773 * Now we know the file's name and its search path, we attempt to
1774 * find the durn thing. A return of NULL indicates the file don't
1777 fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
1779 if (fullname == NULL && !isSystem) {
1781 * Include files contained in double-quotes are first searched for
1782 * relative to the including file's location. We don't want to
1783 * cd there, of course, so we just tack on the old file's
1784 * leading path components and call Dir_FindFile to see if
1785 * we can locate the beast.
1788 incdir = bmake_strdup(curFile->fname);
1789 prefEnd = strrchr(incdir, '/');
1790 if (prefEnd != NULL) {
1792 /* Now do lexical processing of leading "../" on the filename */
1793 for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
1794 prefEnd = strrchr(incdir + 1, '/');
1795 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
1799 newName = str_concat(incdir, file + i, STR_ADDSLASH);
1800 fullname = Dir_FindFile(newName, parseIncPath);
1801 if (fullname == NULL)
1802 fullname = Dir_FindFile(newName, dirSearchPath);
1807 if (fullname == NULL) {
1809 * Makefile wasn't found in same directory as included makefile.
1810 * Search for it first on the -I search path,
1811 * then on the .PATH search path, if not found in a -I directory.
1812 * If we have a suffix specific path we should use that.
1815 Lst suffPath = NILLST;
1817 if ((suff = strrchr(file, '.'))) {
1818 suffPath = Suff_GetPath(suff);
1819 if (suffPath != NILLST) {
1820 fullname = Dir_FindFile(file, suffPath);
1823 if (fullname == NULL) {
1824 fullname = Dir_FindFile(file, parseIncPath);
1825 if (fullname == NULL) {
1826 fullname = Dir_FindFile(file, dirSearchPath);
1832 /* Looking for a system file or file still not found */
1833 if (fullname == NULL) {
1835 * Look for it on the system path
1837 fullname = Dir_FindFile(file,
1838 Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
1841 if (fullname == NULL) {
1843 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1847 /* Actually open the file... */
1848 fd = open(fullname, O_RDONLY);
1851 Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1856 /* Start reading from this file next */
1857 Parse_SetInput(fullname, 0, fd, NULL);
1861 ParseDoInclude(char *line)
1863 char endc; /* the character which ends the file spec */
1864 char *cp; /* current position in file spec */
1865 int silent = (*line != 'i') ? 1 : 0;
1866 char *file = &line[7 + silent];
1868 /* Skip to delimiter character so we know where to look */
1869 while (*file == ' ' || *file == '\t')
1872 if (*file != '"' && *file != '<') {
1873 Parse_Error(PARSE_FATAL,
1874 ".include filename must be delimited by '\"' or '<'");
1879 * Set the search path on which to find the include file based on the
1880 * characters which bracket its name. Angle-brackets imply it's
1881 * a system Makefile while double-quotes imply it's a user makefile
1889 /* Skip to matching delimiter */
1890 for (cp = ++file; *cp && *cp != endc; cp++)
1894 Parse_Error(PARSE_FATAL,
1895 "Unclosed %cinclude filename. '%c' expected",
1902 * Substitute for any variables in the file name before trying to
1905 file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1907 Parse_include_file(file, endc == '>', silent);
1913 *---------------------------------------------------------------------
1914 * ParseSetParseFile --
1915 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
1916 * basename of the given filename
1922 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
1923 * dirname and basename of the given filename.
1924 *---------------------------------------------------------------------
1927 ParseSetParseFile(const char *filename)
1933 slash = strrchr(filename, '/');
1934 if (slash == NULL) {
1935 Var_Set(".PARSEDIR", ".", VAR_GLOBAL, 0);
1936 Var_Set(".PARSEFILE", filename, VAR_GLOBAL, 0);
1938 len = slash - filename;
1939 dirname = bmake_malloc(len + 1);
1940 memcpy(dirname, filename, len);
1942 Var_Set(".PARSEDIR", dirname, VAR_GLOBAL, 0);
1943 Var_Set(".PARSEFILE", slash+1, VAR_GLOBAL, 0);
1949 * Track the makefiles we read - so makefiles can
1950 * set dependencies on them.
1951 * Avoid adding anything more than once.
1955 ParseTrackInput(const char *name)
1959 size_t name_len = strlen(name);
1961 old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
1963 /* does it contain name? */
1964 for (; old != NULL; old = strchr(old, ' ')) {
1967 if (memcmp(old, name, name_len) == 0
1968 && (old[name_len] == 0 || old[name_len] == ' '))
1972 Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
1981 *---------------------------------------------------------------------
1983 * Start Parsing from the given source
1989 * A structure is added to the includes Lst and readProc, lineno,
1990 * fname and curFile are altered for the new file
1991 *---------------------------------------------------------------------
1994 Parse_SetInput(const char *name, int line, int fd, char *buf)
1997 name = curFile->fname;
1999 ParseTrackInput(name);
2002 fprintf(debug_file, "Parse_SetInput: file %s, line %d, fd %d, buf %p\n",
2003 name, line, fd, buf);
2005 if (fd == -1 && buf == NULL)
2009 if (curFile != NULL)
2010 /* Save exiting file info */
2011 Lst_AtFront(includes, curFile);
2013 /* Allocate and fill in new structure */
2014 curFile = bmake_malloc(sizeof *curFile);
2017 * Once the previous state has been saved, we can get down to reading
2018 * the new file. We set up the name of the file to be the absolute
2019 * name of the include file so error messages refer to the right
2022 curFile->fname = name;
2023 curFile->lineno = line;
2025 curFile->cond_depth = Cond_save_depth();
2027 ParseSetParseFile(name);
2031 * Allocate a 32k data buffer (as stdio seems to).
2032 * Set pointers so that first ParseReadc has to do a file read.
2034 buf = bmake_malloc(IFILE_BUFLEN);
2036 curFile->P_str = buf;
2037 curFile->P_ptr = buf;
2038 curFile->P_end = buf;
2039 curFile->P_buflen = IFILE_BUFLEN;
2041 /* Start reading from the start of the buffer */
2042 curFile->P_str = buf;
2043 curFile->P_ptr = buf;
2044 curFile->P_end = NULL;
2051 *---------------------------------------------------------------------
2052 * ParseTraditionalInclude --
2053 * Push to another file.
2055 * The input is the current line. The file name(s) are
2056 * following the "include".
2062 * A structure is added to the includes Lst and readProc, lineno,
2063 * fname and curFILE are altered for the new file
2064 *---------------------------------------------------------------------
2067 ParseTraditionalInclude(char *line)
2069 char *cp; /* current position in file spec */
2071 int silent = (line[0] != 'i') ? 1 : 0;
2072 char *file = &line[silent + 7];
2076 fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2080 * Skip over whitespace
2082 while (isspace((unsigned char)*file))
2086 * Substitute for any variables in the file name before trying to
2089 all_files = Var_Subst(NULL, file, VAR_CMD, FALSE);
2091 if (*file == '\0') {
2092 Parse_Error(PARSE_FATAL,
2093 "Filename missing from \"include\"");
2097 for (file = all_files; !done; file = cp + 1) {
2098 /* Skip to end of line or next whitespace */
2099 for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2107 Parse_include_file(file, FALSE, silent);
2114 *---------------------------------------------------------------------
2116 * Called when EOF is reached in the current file. If we were reading
2117 * an include file, the includes stack is popped and things set up
2118 * to go back to reading the previous file at the previous location.
2121 * CONTINUE if there's more to do. DONE if not.
2124 * The old curFILE, is closed. The includes list is shortened.
2125 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2126 *---------------------------------------------------------------------
2131 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2132 Cond_restore_depth(curFile->cond_depth);
2134 /* Dispose of curFile info */
2135 /* Leak curFile->fname because all the gnodes have pointers to it */
2136 if (curFile->fd != -1)
2138 free(curFile->P_str);
2141 curFile = Lst_DeQueue(includes);
2143 if (curFile == (IFile *)NIL) {
2144 /* We've run out of input */
2145 Var_Delete(".PARSEDIR", VAR_GLOBAL);
2146 Var_Delete(".PARSEFILE", VAR_GLOBAL);
2151 fprintf(debug_file, "ParseEOF: returning to file %s, line %d, fd %d\n",
2152 curFile->fname, curFile->lineno, curFile->fd);
2154 /* Restore the PARSEDIR/PARSEFILE variables */
2155 ParseSetParseFile(curFile->fname);
2160 #define PARSE_SKIP 2
2163 ParseGetLine(int flags, int *length)
2165 IFile *cf = curFile;
2175 /* Loop through blank lines and comment lines */
2185 if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2186 if (cf->P_end == NULL)
2187 /* End of string (aka for loop) data */
2189 /* End of data read from file, read more data */
2190 if (ptr != cf->P_end && (ch != '\\' || ptr + 1 != cf->P_end)) {
2191 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2194 /* Move existing data to (near) start of file buffer */
2195 len = cf->P_end - cf->P_ptr;
2196 tp = cf->P_str + 32;
2197 memmove(tp, cf->P_ptr, len);
2198 dist = cf->P_ptr - tp;
2199 /* Update all pointers to reflect moved data */
2210 /* Try to read more data from file into buffer space */
2211 len = cf->P_str + cf->P_buflen - tp - 32;
2213 /* We need a bigger buffer to hold this line */
2214 tp = bmake_realloc(cf->P_str, cf->P_buflen + IFILE_BUFLEN);
2215 cf->P_ptr = cf->P_ptr - cf->P_str + tp;
2216 cf->P_end = cf->P_end - cf->P_str + tp;
2217 ptr = ptr - cf->P_str + tp;
2218 line = line - cf->P_str + tp;
2219 line_end = line_end - cf->P_str + tp;
2221 escaped = escaped - cf->P_str + tp;
2223 comment = comment - cf->P_str + tp;
2226 len += IFILE_BUFLEN;
2227 cf->P_buflen += IFILE_BUFLEN;
2229 len = read(cf->fd, tp, len);
2232 Parse_Error(PARSE_FATAL, "Makefile read error: %s",
2239 /* 0 terminate the data, and update end pointer */
2243 /* Process newly read characters */
2248 /* Don't treat next character as special, remember first one */
2249 if (escaped == NULL)
2257 if (ch == '#' && comment == NULL) {
2258 /* Remember first '#' for comment stripping */
2264 if (!isspace((unsigned char)ch))
2265 /* We are not interested in trailing whitespace */
2269 /* Save next 'to be processed' location */
2272 /* Check we have a non-comment, non-blank line */
2273 if (line_end == line || comment == line) {
2275 /* At end of file */
2277 /* Parse another line */
2281 /* We now have a line of data */
2284 if (flags & PARSE_RAW) {
2285 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2286 *length = line_end - line;
2290 if (flags & PARSE_SKIP) {
2291 /* Completely ignore non-directives */
2294 /* We could do more of the .else/.elif/.endif checks here */
2299 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2300 if (comment != NULL && line[0] != '\t') {
2305 /* If we didn't see a '\\' then the in-situ data is fine */
2306 if (escaped == NULL) {
2307 *length = line_end - line;
2311 /* Remove escapes from '\n' and '#' */
2314 for (; ; *tp++ = ch) {
2324 /* Delete '\\' at end of buffer */
2329 if (ch == '#' && line[0] != '\t')
2330 /* Delete '\\' from before '#' on non-command lines */
2334 /* Leave '\\' in buffer for later */
2336 /* Make sure we don't delete an escaped ' ' from the line end */
2341 /* Escaped '\n' replace following whitespace with a single ' ' */
2342 while (ptr[0] == ' ' || ptr[0] == '\t')
2347 /* Delete any trailing spaces - eg from empty continuations */
2348 while (tp > escaped && isspace((unsigned char)tp[-1]))
2352 *length = tp - line;
2357 *---------------------------------------------------------------------
2359 * Read an entire line from the input file. Called only by Parse_File.
2362 * A line w/o its newline
2365 * Only those associated with reading a character
2366 *---------------------------------------------------------------------
2371 char *line; /* Result */
2372 int lineLength; /* Length of result */
2373 int lineno; /* Saved line # */
2376 line = ParseGetLine(0, &lineLength);
2384 * The line might be a conditional. Ask the conditional module
2385 * about it and act accordingly
2387 switch (Cond_Eval(line)) {
2389 /* Skip to next conditional that evaluates to COND_PARSE. */
2391 line = ParseGetLine(PARSE_SKIP, &lineLength);
2392 } while (line && Cond_Eval(line) != COND_PARSE);
2398 case COND_INVALID: /* Not a conditional line */
2399 if (!For_Eval(line))
2401 lineno = curFile->lineno;
2402 /* Skip after the matching end */
2404 line = ParseGetLine(PARSE_RAW, &lineLength);
2406 Parse_Error(PARSE_FATAL,
2407 "Unexpected end of file in for loop.\n");
2410 } while (For_Eval(line));
2411 /* Stash each iteration as a new 'input file' */
2413 /* Read next line from for-loop buffer */
2421 *-----------------------------------------------------------------------
2422 * ParseFinishLine --
2423 * Handle the end of a dependency group.
2429 * inLine set FALSE. 'targets' list destroyed.
2431 *-----------------------------------------------------------------------
2434 ParseFinishLine(void)
2437 Lst_ForEach(targets, Suff_EndTransform, NULL);
2438 Lst_Destroy(targets, ParseHasCommands);
2446 *---------------------------------------------------------------------
2448 * Parse a file into its component parts, incorporating it into the
2449 * current dependency graph. This is the main function and controls
2450 * almost every other function in this module
2453 * name the name of the file being read
2454 * fd Open file to makefile to parse
2461 * Loads. Nodes are added to the list of all targets, nodes and links
2462 * are added to the dependency graph. etc. etc. etc.
2463 *---------------------------------------------------------------------
2466 Parse_File(const char *name, int fd)
2468 char *cp; /* pointer into the line */
2469 char *line; /* the line we're working on */
2474 Parse_SetInput(name, 0, fd, NULL);
2477 for (; (line = ParseReadLine()) != NULL; ) {
2479 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2480 curFile->lineno, line);
2483 * Lines that begin with the special character are either
2484 * include or undef directives.
2486 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2489 if (strncmp(cp, "include", 7) == 0 ||
2490 ((cp[0] == 's' || cp[0] == '-') &&
2491 strncmp(&cp[1], "include", 7) == 0)) {
2495 if (strncmp(cp, "undef", 5) == 0) {
2497 for (cp += 5; isspace((unsigned char) *cp); cp++)
2499 for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2500 (*cp2 != '\0'); cp2++)
2503 Var_Delete(cp, VAR_GLOBAL);
2505 } else if (strncmp(cp, "export", 6) == 0) {
2506 for (cp += 6; isspace((unsigned char) *cp); cp++)
2513 if (*line == '\t') {
2515 * If a line starts with a tab, it can only hope to be
2516 * a creation command.
2520 for (; isspace ((unsigned char)*cp); cp++) {
2525 Parse_Error(PARSE_FATAL,
2526 "Unassociated shell command \"%s\"",
2529 * So long as it's not a blank line and we're actually
2530 * in a dependency spec, add the command to the list of
2531 * commands of all targets in the dependency spec
2534 cp = bmake_strdup(cp);
2535 Lst_ForEach(targets, ParseAddCmd, cp);
2537 Lst_AtEnd(targCmds, cp);
2545 if (((strncmp(line, "include", 7) == 0 &&
2546 isspace((unsigned char) line[7])) ||
2547 ((line[0] == 's' || line[0] == '-') &&
2548 strncmp(&line[1], "include", 7) == 0 &&
2549 isspace((unsigned char) line[8]))) &&
2550 strchr(line, ':') == NULL) {
2552 * It's an S3/S5-style "include".
2554 ParseTraditionalInclude(line);
2558 if (Parse_IsVar(line)) {
2560 Parse_DoVar(line, VAR_GLOBAL);
2566 * To make life easier on novices, if the line is indented we
2567 * first make sure the line has a dependency operator in it.
2568 * If it doesn't have an operator and we're in a dependency
2569 * line's script, we assume it's actually a shell command
2570 * and add it to the current list of targets.
2573 if (isspace((unsigned char) line[0])) {
2574 while ((*cp != '\0') && isspace((unsigned char) *cp))
2576 while (*cp && (ParseIsEscaped(line, cp) ||
2577 (*cp != ':') && (*cp != '!'))) {
2582 Parse_Error(PARSE_WARNING,
2583 "Shell command needs a leading tab");
2592 * For some reason - probably to make the parser impossible -
2593 * a ';' can be used to separate commands from dependencies.
2594 * No attempt is made to avoid ';' inside substitution patterns.
2596 for (cp = line; *cp != 0; cp++) {
2597 if (*cp == '\\' && cp[1] != 0) {
2605 /* Terminate the dependency list at the ';' */
2611 * We now know it's a dependency line so it needs to have all
2612 * variables expanded before being parsed. Tell the variable
2613 * module to complain if some variable is undefined...
2615 line = Var_Subst(NULL, line, VAR_CMD, TRUE);
2618 * Need a non-circular list for the target nodes
2621 Lst_Destroy(targets, NOFREE);
2623 targets = Lst_Init(FALSE);
2626 ParseDoDependency(line);
2629 /* If there were commands after a ';', add them now */
2635 * Reached EOF, but it may be just EOF of an include file...
2637 } while (ParseEOF() == CONTINUE);
2640 (void)fprintf(stderr,
2641 "%s: Fatal errors encountered -- cannot continue\n",
2649 *---------------------------------------------------------------------
2651 * initialize the parsing module
2657 * the parseIncPath list is initialized...
2658 *---------------------------------------------------------------------
2663 mainNode = NILGNODE;
2664 parseIncPath = Lst_Init(FALSE);
2665 sysIncPath = Lst_Init(FALSE);
2666 defIncPath = Lst_Init(FALSE);
2667 includes = Lst_Init(FALSE);
2669 targCmds = Lst_Init(FALSE);
2677 Lst_Destroy(targCmds, (FreeProc *)free);
2679 Lst_Destroy(targets, NOFREE);
2680 Lst_Destroy(defIncPath, Dir_Destroy);
2681 Lst_Destroy(sysIncPath, Dir_Destroy);
2682 Lst_Destroy(parseIncPath, Dir_Destroy);
2683 Lst_Destroy(includes, NOFREE); /* Should be empty now */
2689 *-----------------------------------------------------------------------
2691 * Return a Lst of the main target to create for main()'s sake. If
2692 * no such target exists, we Punt with an obnoxious error message.
2695 * A Lst of the single node to create.
2700 *-----------------------------------------------------------------------
2703 Parse_MainName(void)
2705 Lst mainList; /* result list */
2707 mainList = Lst_Init(FALSE);
2709 if (mainNode == NILGNODE) {
2710 Punt("no target to make.");
2712 } else if (mainNode->type & OP_DOUBLEDEP) {
2713 (void)Lst_AtEnd(mainList, mainNode);
2714 Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
2717 (void)Lst_AtEnd(mainList, mainNode);
2718 Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
2723 *-----------------------------------------------------------------------
2725 * Add the filename and lineno to the GNode so that we remember
2726 * where it was first defined.
2731 *-----------------------------------------------------------------------
2734 ParseMark(GNode *gn)
2736 gn->fname = curFile->fname;
2737 gn->lineno = curFile->lineno;