1 /* $NetBSD: parse.c,v 1.159 2009/11/06 20:20:56 dsl 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.159 2009/11/06 20:20:56 dsl 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.159 2009/11/06 20:20:56 dsl 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 Ignore
, /* .IGNORE */
195 Includes
, /* .INCLUDES */
196 Interrupt
, /* .INTERRUPT */
198 MFlags
, /* .MFLAGS or .MAKEFLAGS */
199 Main
, /* .MAIN and we don't have anything user-specified to
201 NoExport
, /* .NOEXPORT */
202 NoPath
, /* .NOPATH */
203 Not
, /* Not special */
204 NotParallel
, /* .NOTPARALLEL */
206 ExObjdir
, /* .OBJDIR */
208 Parallel
, /* .PARALLEL */
214 Precious
, /* .PRECIOUS */
215 ExShell
, /* .SHELL */
216 Silent
, /* .SILENT */
217 SingleShell
, /* .SINGLESHELL */
218 Suffixes
, /* .SUFFIXES */
220 Attribute
/* Generic attribute */
223 static ParseSpecial specType
;
228 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
229 * seen, then set to each successive source on the line.
231 static GNode
*predecessor
;
234 * The parseKeywords table is searched using binary search when deciding
235 * if a target or source is special. The 'spec' field is the ParseSpecial
236 * type of the keyword ("Not" if the keyword isn't special as a target) while
237 * the 'op' field is the operator to apply to the list of targets if the
238 * keyword is used as a source ("0" if the keyword isn't special as a source)
241 const char *name
; /* Name of keyword */
242 ParseSpecial spec
; /* Type when used as a target */
243 int op
; /* Operator when used as a source */
244 } parseKeywords
[] = {
245 { ".BEGIN", Begin
, 0 },
246 { ".DEFAULT", Default
, 0 },
248 { ".EXEC", Attribute
, OP_EXEC
},
249 { ".IGNORE", Ignore
, OP_IGNORE
},
250 { ".INCLUDES", Includes
, 0 },
251 { ".INTERRUPT", Interrupt
, 0 },
252 { ".INVISIBLE", Attribute
, OP_INVISIBLE
},
253 { ".JOIN", Attribute
, OP_JOIN
},
254 { ".LIBS", Libs
, 0 },
255 { ".MADE", Attribute
, OP_MADE
},
256 { ".MAIN", Main
, 0 },
257 { ".MAKE", Attribute
, OP_MAKE
},
258 { ".MAKEFLAGS", MFlags
, 0 },
259 { ".MFLAGS", MFlags
, 0 },
260 { ".NOPATH", NoPath
, OP_NOPATH
},
261 { ".NOTMAIN", Attribute
, OP_NOTMAIN
},
262 { ".NOTPARALLEL", NotParallel
, 0 },
263 { ".NO_PARALLEL", NotParallel
, 0 },
264 { ".NULL", Null
, 0 },
265 { ".OBJDIR", ExObjdir
, 0 },
266 { ".OPTIONAL", Attribute
, OP_OPTIONAL
},
267 { ".ORDER", Order
, 0 },
268 { ".PARALLEL", Parallel
, 0 },
269 { ".PATH", ExPath
, 0 },
270 { ".PHONY", Phony
, OP_PHONY
},
272 { ".POSIX", Posix
, 0 },
274 { ".PRECIOUS", Precious
, OP_PRECIOUS
},
275 { ".RECURSIVE", Attribute
, OP_MAKE
},
276 { ".SHELL", ExShell
, 0 },
277 { ".SILENT", Silent
, OP_SILENT
},
278 { ".SINGLESHELL", SingleShell
, 0 },
279 { ".SUFFIXES", Suffixes
, 0 },
280 { ".USE", Attribute
, OP_USE
},
281 { ".USEBEFORE", Attribute
, OP_USEBEFORE
},
282 { ".WAIT", Wait
, 0 },
285 static int ParseIsEscaped(const char *, const char *);
286 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
287 __attribute__((__format__(__printf__
, 4, 5)));
288 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
289 __attribute__((__format__(__printf__
, 5, 0)));
290 static int ParseFindKeyword(const char *);
291 static int ParseLinkSrc(void *, void *);
292 static int ParseDoOp(void *, void *);
293 static void ParseDoSrc(int, const char *);
294 static int ParseFindMain(void *, void *);
295 static int ParseAddDir(void *, void *);
296 static int ParseClearPath(void *, void *);
297 static void ParseDoDependency(char *);
298 static int ParseAddCmd(void *, void *);
299 static void ParseHasCommands(void *);
300 static void ParseDoInclude(char *);
301 static void ParseSetParseFile(const char *);
303 static void ParseTraditionalInclude(char *);
305 static int ParseEOF(void);
306 static char *ParseReadLine(void);
307 static void ParseFinishLine(void);
308 static void ParseMark(GNode
*);
314 *----------------------------------------------------------------------
316 * Check if the current character is escaped on the current line
319 * 0 if the character is not backslash escaped, 1 otherwise
323 *----------------------------------------------------------------------
326 ParseIsEscaped(const char *line
, const char *c
)
339 *----------------------------------------------------------------------
340 * ParseFindKeyword --
341 * Look in the table of keywords for one matching the given string.
347 * The index of the keyword, or -1 if it isn't there.
351 *----------------------------------------------------------------------
354 ParseFindKeyword(const char *str
)
360 end
= (sizeof(parseKeywords
)/sizeof(parseKeywords
[0])) - 1;
363 cur
= start
+ ((end
- start
) / 2);
364 diff
= strcmp(str
, parseKeywords
[cur
].name
);
368 } else if (diff
< 0) {
373 } while (start
<= end
);
378 * ParseVErrorInternal --
379 * Error message abort function for parsing. Prints out the context
380 * of the error (line number and file) as well as the message with
381 * two optional arguments.
387 * "fatals" is incremented if the level is PARSE_FATAL.
391 ParseVErrorInternal(FILE *f
, const char *cfname
, size_t clineno
, int type
,
392 const char *fmt
, va_list ap
)
394 static Boolean fatal_warning_error_printed
= FALSE
;
396 (void)fprintf(f
, "%s: ", progname
);
398 if (cfname
!= NULL
) {
399 (void)fprintf(f
, "\"");
400 if (*cfname
!= '/' && strcmp(cfname
, "(stdin)") != 0) {
405 * Nothing is more anoying than not knowing
406 * which Makefile is the culprit.
408 dir
= Var_Value(".PARSEDIR", VAR_GLOBAL
, &cp
);
409 if (dir
== NULL
|| *dir
== '\0' ||
410 (*dir
== '.' && dir
[1] == '\0'))
411 dir
= Var_Value(".CURDIR", VAR_GLOBAL
, &cp
);
415 (void)fprintf(f
, "%s/%s", dir
, cfname
);
417 (void)fprintf(f
, "%s", cfname
);
419 (void)fprintf(f
, "\" line %d: ", (int)clineno
);
421 if (type
== PARSE_WARNING
)
422 (void)fprintf(f
, "warning: ");
423 (void)vfprintf(f
, fmt
, ap
);
424 (void)fprintf(f
, "\n");
426 if (type
== PARSE_FATAL
|| parseWarnFatal
)
428 if (parseWarnFatal
&& !fatal_warning_error_printed
) {
429 Error("parsing warnings being treated as errors");
430 fatal_warning_error_printed
= TRUE
;
435 * ParseErrorInternal --
446 ParseErrorInternal(const char *cfname
, size_t clineno
, int type
,
447 const char *fmt
, ...)
452 ParseVErrorInternal(stderr
, cfname
, clineno
, type
, fmt
, ap
);
455 if (debug_file
!= stderr
&& debug_file
!= stdout
) {
457 ParseVErrorInternal(debug_file
, cfname
, clineno
, type
, fmt
, ap
);
464 * External interface to ParseErrorInternal; uses the default filename
475 Parse_Error(int type
, const char *fmt
, ...)
481 if (curFile
== NULL
) {
485 fname
= curFile
->fname
;
486 lineno
= curFile
->lineno
;
490 ParseVErrorInternal(stderr
, fname
, lineno
, type
, fmt
, ap
);
493 if (debug_file
!= stderr
&& debug_file
!= stdout
) {
495 ParseVErrorInternal(debug_file
, fname
, lineno
, type
, fmt
, ap
);
501 *---------------------------------------------------------------------
503 * Link the parent node to its new child. Used in a Lst_ForEach by
504 * ParseDoDependency. If the specType isn't 'Not', the parent
505 * isn't linked as a parent of the child.
508 * pgnp The parent node
509 * cgpn The child node
515 * New elements are added to the parents list of cgn and the
516 * children list of cgn. the unmade field of pgn is updated
517 * to reflect the additional child.
518 *---------------------------------------------------------------------
521 ParseLinkSrc(void *pgnp
, void *cgnp
)
523 GNode
*pgn
= (GNode
*)pgnp
;
524 GNode
*cgn
= (GNode
*)cgnp
;
526 if ((pgn
->type
& OP_DOUBLEDEP
) && !Lst_IsEmpty (pgn
->cohorts
))
527 pgn
= (GNode
*)Lst_Datum(Lst_Last(pgn
->cohorts
));
528 (void)Lst_AtEnd(pgn
->children
, cgn
);
530 (void)Lst_AtEnd(cgn
->parents
, pgn
);
533 fprintf(debug_file
, "# ParseLinkSrc: added child %s - %s\n", pgn
->name
, cgn
->name
);
534 Targ_PrintNode(pgn
, 0);
535 Targ_PrintNode(cgn
, 0);
541 *---------------------------------------------------------------------
543 * Apply the parsed operator to the given target node. Used in a
544 * Lst_ForEach call by ParseDoDependency once all targets have
545 * been found and their operator parsed. If the previous and new
546 * operators are incompatible, a major error is taken.
549 * gnp The node to which the operator is to be applied
550 * opp The operator to apply
556 * The type field of the node is altered to reflect any new bits in
558 *---------------------------------------------------------------------
561 ParseDoOp(void *gnp
, void *opp
)
563 GNode
*gn
= (GNode
*)gnp
;
564 int op
= *(int *)opp
;
566 * If the dependency mask of the operator and the node don't match and
567 * the node has actually had an operator applied to it before, and
568 * the operator actually has some dependency information in it, complain.
570 if (((op
& OP_OPMASK
) != (gn
->type
& OP_OPMASK
)) &&
571 !OP_NOP(gn
->type
) && !OP_NOP(op
))
573 Parse_Error(PARSE_FATAL
, "Inconsistent operator for %s", gn
->name
);
577 if ((op
== OP_DOUBLEDEP
) && ((gn
->type
& OP_OPMASK
) == OP_DOUBLEDEP
)) {
579 * If the node was the object of a :: operator, we need to create a
580 * new instance of it for the children and commands on this dependency
581 * line. The new instance is placed on the 'cohorts' list of the
582 * initial one (note the initial one is not on its own cohorts list)
583 * and the new instance is linked to all parents of the initial
589 * Propagate copied bits to the initial node. They'll be propagated
590 * back to the rest of the cohorts later.
592 gn
->type
|= op
& ~OP_OPMASK
;
594 cohort
= Targ_FindNode(gn
->name
, TARG_NOHASH
);
596 * Make the cohort invisible as well to avoid duplicating it into
597 * other variables. True, parents of this target won't tend to do
598 * anything with their local variables, but better safe than
599 * sorry. (I think this is pointless now, since the relevant list
600 * traversals will no longer see this node anyway. -mycroft)
602 cohort
->type
= op
| OP_INVISIBLE
;
603 (void)Lst_AtEnd(gn
->cohorts
, cohort
);
604 cohort
->centurion
= gn
;
605 gn
->unmade_cohorts
+= 1;
606 snprintf(cohort
->cohort_num
, sizeof cohort
->cohort_num
, "#%d",
610 * We don't want to nuke any previous flags (whatever they were) so we
611 * just OR the new operator into the old
620 *---------------------------------------------------------------------
622 * Given the name of a source, figure out if it is an attribute
623 * and apply it to the targets if it is. Else decide if there is
624 * some attribute which should be applied *to* the source because
625 * of some special target and apply it if so. Otherwise, make the
626 * source be a child of the targets in the list 'targets'
629 * tOp operator (if any) from special targets
630 * src name of the source to handle
636 * Operator bits may be added to the list of targets or to the source.
637 * The targets may have a new source added to their lists of children.
638 *---------------------------------------------------------------------
641 ParseDoSrc(int tOp
, const char *src
)
644 static int wait_number
= 0;
647 if (*src
== '.' && isupper ((unsigned char)src
[1])) {
648 int keywd
= ParseFindKeyword(src
);
650 int op
= parseKeywords
[keywd
].op
;
652 Lst_ForEach(targets
, ParseDoOp
, &op
);
655 if (parseKeywords
[keywd
].spec
== Wait
) {
657 * We add a .WAIT node in the dependency list.
658 * After any dynamic dependencies (and filename globbing)
659 * have happened, it is given a dependency on the each
660 * previous child back to and previous .WAIT node.
661 * The next child won't be scheduled until the .WAIT node
663 * We give each .WAIT node a unique name (mainly for diag).
665 snprintf(wait_src
, sizeof wait_src
, ".WAIT_%u", ++wait_number
);
666 gn
= Targ_FindNode(wait_src
, TARG_NOHASH
);
667 gn
->type
= OP_WAIT
| OP_PHONY
| OP_DEPENDS
| OP_NOTMAIN
;
668 Lst_ForEach(targets
, ParseLinkSrc
, gn
);
677 * If we have noted the existence of a .MAIN, it means we need
678 * to add the sources of said target to the list of things
679 * to create. The string 'src' is likely to be free, so we
680 * must make a new copy of it. Note that this will only be
681 * invoked if the user didn't specify a target on the command
682 * line. This is to allow #ifmake's to succeed, or something...
684 (void)Lst_AtEnd(create
, bmake_strdup(src
));
686 * Add the name to the .TARGETS variable as well, so the user can
687 * employ that, if desired.
689 Var_Append(".TARGETS", src
, VAR_GLOBAL
);
694 * Create proper predecessor/successor links between the previous
695 * source and the current one.
697 gn
= Targ_FindNode(src
, TARG_CREATE
);
698 if (predecessor
!= NULL
) {
699 (void)Lst_AtEnd(predecessor
->order_succ
, gn
);
700 (void)Lst_AtEnd(gn
->order_pred
, predecessor
);
702 fprintf(debug_file
, "# ParseDoSrc: added Order dependency %s - %s\n",
703 predecessor
->name
, gn
->name
);
704 Targ_PrintNode(predecessor
, 0);
705 Targ_PrintNode(gn
, 0);
709 * The current source now becomes the predecessor for the next one.
716 * If the source is not an attribute, we need to find/create
717 * a node for it. After that we can apply any operator to it
718 * from a special target or link it to its parents, as
721 * In the case of a source that was the object of a :: operator,
722 * the attribute is applied to all of its instances (as kept in
723 * the 'cohorts' list of the node) or all the cohorts are linked
724 * to all the targets.
727 /* Find/create the 'src' node and attach to all targets */
728 gn
= Targ_FindNode(src
, TARG_CREATE
);
732 Lst_ForEach(targets
, ParseLinkSrc
, gn
);
739 *-----------------------------------------------------------------------
741 * Find a real target in the list and set it to be the main one.
742 * Called by ParseDoDependency when a main target hasn't been found
746 * gnp Node to examine
749 * 0 if main not found yet, 1 if it is.
752 * mainNode is changed and Targ_SetMain is called.
754 *-----------------------------------------------------------------------
757 ParseFindMain(void *gnp
, void *dummy
)
759 GNode
*gn
= (GNode
*)gnp
;
760 if ((gn
->type
& OP_NOTARGET
) == 0) {
763 return (dummy
? 1 : 1);
765 return (dummy
? 0 : 0);
770 *-----------------------------------------------------------------------
772 * Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
780 *-----------------------------------------------------------------------
783 ParseAddDir(void *path
, void *name
)
785 (void)Dir_AddDir((Lst
) path
, (char *)name
);
790 *-----------------------------------------------------------------------
792 * Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
800 *-----------------------------------------------------------------------
803 ParseClearPath(void *path
, void *dummy
)
805 Dir_ClearPath((Lst
) path
);
806 return(dummy
? 0 : 0);
810 *---------------------------------------------------------------------
811 * ParseDoDependency --
812 * Parse the dependency line in line.
815 * line the line to parse
821 * The nodes of the sources are linked as children to the nodes of the
822 * targets. Some nodes may be created.
824 * We parse a dependency line by first extracting words from the line and
825 * finding nodes in the list of all targets with that name. This is done
826 * until a character is encountered which is an operator character. Currently
827 * these are only ! and :. At this point the operator is parsed and the
828 * pointer into the line advanced until the first source is encountered.
829 * The parsed operator is applied to each node in the 'targets' list,
830 * which is where the nodes found for the targets are kept, by means of
831 * the ParseDoOp function.
832 * The sources are read in much the same way as the targets were except
833 * that now they are expanded using the wildcarding scheme of the C-Shell
834 * and all instances of the resulting words in the list of all targets
835 * are found. Each of the resulting nodes is then linked to each of the
836 * targets as one of its children.
837 * Certain targets are handled specially. These are the ones detailed
838 * by the specType variable.
839 * The storing of transformation rules is also taken care of here.
840 * A target is recognized as a transformation rule by calling
841 * Suff_IsTransform. If it is a transformation rule, its node is gotten
842 * from the suffix module via Suff_AddTransform rather than the standard
843 * Targ_FindNode in the target module.
844 *---------------------------------------------------------------------
847 ParseDoDependency(char *line
)
849 char *cp
; /* our current position */
850 GNode
*gn
= NULL
; /* a general purpose temporary node */
851 int op
; /* the operator on the line */
852 char savec
; /* a place to save a character */
853 Lst paths
; /* List of search paths to alter when parsing
854 * a list of .PATH targets */
855 int tOp
; /* operator from special target */
856 Lst sources
; /* list of archive source names after
858 Lst curTargs
; /* list of target names to be found and added
859 * to the targets list */
863 fprintf(debug_file
, "ParseDoDependency(%s)\n", line
);
869 curTargs
= Lst_Init(FALSE
);
872 for (cp
= line
; *cp
&& (ParseIsEscaped(lstart
, cp
) ||
873 !(isspace((unsigned char)*cp
) ||
874 *cp
== '!' || *cp
== ':' || *cp
== LPAREN
));
878 * Must be a dynamic source (would have been expanded
879 * otherwise), so call the Var module to parse the puppy
880 * so we can safely advance beyond it...There should be
881 * no errors in this, as they would have been discovered
882 * in the initial Var_Subst and we wouldn't be here.
888 result
= Var_Parse(cp
, VAR_CMD
, TRUE
, &length
, &freeIt
);
895 if (!ParseIsEscaped(lstart
, cp
) && *cp
== LPAREN
) {
897 * Archives must be handled specially to make sure the OP_ARCHV
898 * flag is set in their 'type' field, for one thing, and because
899 * things like "archive(file1.o file2.o file3.o)" are permissible.
900 * Arch_ParseArchive will set 'line' to be the first non-blank
901 * after the archive-spec. It creates/finds nodes for the members
902 * and places them on the given list, returning SUCCESS if all
903 * went well and FAILURE if there was an error in the
904 * specification. On error, line should remain untouched.
906 if (Arch_ParseArchive(&line
, targets
, VAR_CMD
) != SUCCESS
) {
907 Parse_Error(PARSE_FATAL
,
908 "Error in archive specification: \"%s\"", line
);
918 * Ending a dependency line without an operator is a Bozo
919 * no-no. As a heuristic, this is also often triggered by
920 * undetected conflicts from cvs/rcs merges.
922 if ((strncmp(line
, "<<<<<<", 6) == 0) ||
923 (strncmp(line
, "======", 6) == 0) ||
924 (strncmp(line
, ">>>>>>", 6) == 0))
925 Parse_Error(PARSE_FATAL
,
926 "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
928 Parse_Error(PARSE_FATAL
, lstart
[0] == '.' ? "Unknown directive"
929 : "Need an operator");
935 * Have a word in line. See if it's a special target and set
936 * specType to match it.
938 if (*line
== '.' && isupper ((unsigned char)line
[1])) {
940 * See if the target is a special target that must have it
941 * or its sources handled specially.
943 int keywd
= ParseFindKeyword(line
);
945 if (specType
== ExPath
&& parseKeywords
[keywd
].spec
!= ExPath
) {
946 Parse_Error(PARSE_FATAL
, "Mismatched special targets");
950 specType
= parseKeywords
[keywd
].spec
;
951 tOp
= parseKeywords
[keywd
].op
;
954 * Certain special targets have special semantics:
955 * .PATH Have to set the dirSearchPath
957 * .MAIN Its sources are only used if
958 * nothing has been specified to
960 * .DEFAULT Need to create a node to hang
961 * commands on, but we don't want
962 * it in the graph, nor do we want
963 * it to be the Main Target, so we
964 * create it, set OP_NOTMAIN and
965 * add it to the list, setting
966 * DEFAULT to the new node for
967 * later use. We claim the node is
968 * A transformation rule to make
969 * life easier later, when we'll
970 * use Make_HandleUse to actually
971 * apply the .DEFAULT commands.
972 * .PHONY The list of targets
973 * .NOPATH Don't search for file in the path
976 * .INTERRUPT Are not to be considered the
978 * .NOTPARALLEL Make only one target at a time.
979 * .SINGLESHELL Create a shell for each command.
980 * .ORDER Must set initial predecessor to NULL
985 paths
= Lst_Init(FALSE
);
987 (void)Lst_AtEnd(paths
, dirSearchPath
);
990 if (!Lst_IsEmpty(create
)) {
997 gn
= Targ_FindNode(line
, TARG_CREATE
);
998 gn
->type
|= OP_NOTMAIN
|OP_SPECIAL
;
999 (void)Lst_AtEnd(targets
, gn
);
1002 gn
= Targ_NewGN(".DEFAULT");
1003 gn
->type
|= (OP_NOTMAIN
|OP_TRANSFORM
);
1004 (void)Lst_AtEnd(targets
, gn
);
1019 } else if (strncmp(line
, ".PATH", 5) == 0) {
1021 * .PATH<suffix> has to be handled specially.
1022 * Call on the suffix module to give us a path to
1028 path
= Suff_GetPath(&line
[5]);
1030 Parse_Error(PARSE_FATAL
,
1031 "Suffix '%s' not defined (yet)",
1035 if (paths
== (Lst
)NULL
) {
1036 paths
= Lst_Init(FALSE
);
1038 (void)Lst_AtEnd(paths
, path
);
1044 * Have word in line. Get or create its node and stick it at
1045 * the end of the targets list
1047 if ((specType
== Not
) && (*line
!= '\0')) {
1048 if (Dir_HasWildcards(line
)) {
1050 * Targets are to be sought only in the current directory,
1051 * so create an empty path for the thing. Note we need to
1052 * use Dir_Destroy in the destruction of the path as the
1053 * Dir module could have added a directory to the path...
1055 Lst emptyPath
= Lst_Init(FALSE
);
1057 Dir_Expand(line
, emptyPath
, curTargs
);
1059 Lst_Destroy(emptyPath
, Dir_Destroy
);
1062 * No wildcards, but we want to avoid code duplication,
1063 * so create a list with the word on it.
1065 (void)Lst_AtEnd(curTargs
, line
);
1068 while(!Lst_IsEmpty(curTargs
)) {
1069 char *targName
= (char *)Lst_DeQueue(curTargs
);
1071 if (!Suff_IsTransform (targName
)) {
1072 gn
= Targ_FindNode(targName
, TARG_CREATE
);
1074 gn
= Suff_AddTransform(targName
);
1077 (void)Lst_AtEnd(targets
, gn
);
1079 } else if (specType
== ExPath
&& *line
!= '.' && *line
!= '\0') {
1080 Parse_Error(PARSE_WARNING
, "Extra target (%s) ignored", line
);
1085 * If it is a special type and not .PATH, it's the only target we
1086 * allow on this line...
1088 if (specType
!= Not
&& specType
!= ExPath
) {
1089 Boolean warning
= FALSE
;
1091 while (*cp
&& (ParseIsEscaped(lstart
, cp
) ||
1092 ((*cp
!= '!') && (*cp
!= ':')))) {
1093 if (ParseIsEscaped(lstart
, cp
) ||
1094 (*cp
!= ' ' && *cp
!= '\t')) {
1100 Parse_Error(PARSE_WARNING
, "Extra target ignored");
1103 while (*cp
&& isspace ((unsigned char)*cp
)) {
1108 } while (*line
&& (ParseIsEscaped(lstart
, line
) ||
1109 ((*line
!= '!') && (*line
!= ':'))));
1112 * Don't need the list of target names anymore...
1114 Lst_Destroy(curTargs
, NULL
);
1117 if (!Lst_IsEmpty(targets
)) {
1120 Parse_Error(PARSE_WARNING
, "Special and mundane targets don't mix. Mundane ones ignored");
1127 * These four create nodes on which to hang commands, so
1128 * targets shouldn't be empty...
1132 * Nothing special here -- targets can be empty if it wants.
1139 * Have now parsed all the target names. Must parse the operator next. The
1140 * result is left in op .
1144 } else if (*cp
== ':') {
1152 Parse_Error(PARSE_FATAL
, lstart
[0] == '.' ? "Unknown directive"
1153 : "Missing dependency operator");
1157 cp
++; /* Advance beyond operator */
1159 Lst_ForEach(targets
, ParseDoOp
, &op
);
1162 * Get to the first source
1164 while (*cp
&& isspace ((unsigned char)*cp
)) {
1170 * Several special targets take different actions if present with no
1172 * a .SUFFIXES line with no sources clears out all old suffixes
1173 * a .PRECIOUS line makes all targets precious
1174 * a .IGNORE line ignores errors for all targets
1175 * a .SILENT line creates silence when making all targets
1176 * a .PATH removes all directories from the search path(s).
1181 Suff_ClearSuffixes();
1187 ignoreErrors
= TRUE
;
1193 Lst_ForEach(paths
, ParseClearPath
, NULL
);
1198 Var_Set("%POSIX", "1003.2", VAR_GLOBAL
, 0);
1204 } else if (specType
== MFlags
) {
1206 * Call on functions in main.c to deal with these arguments and
1207 * set the initial character to a null-character so the loop to
1208 * get sources won't get anything
1210 Main_ParseArgLine(line
);
1212 } else if (specType
== ExShell
) {
1213 if (Job_ParseShell(line
) != SUCCESS
) {
1214 Parse_Error(PARSE_FATAL
, "improper shell specification");
1218 } else if ((specType
== NotParallel
) || (specType
== SingleShell
)) {
1223 * NOW GO FOR THE SOURCES
1225 if ((specType
== Suffixes
) || (specType
== ExPath
) ||
1226 (specType
== Includes
) || (specType
== Libs
) ||
1227 (specType
== Null
) || (specType
== ExObjdir
))
1231 * If the target was one that doesn't take files as its sources
1232 * but takes something like suffixes, we take each
1233 * space-separated word on the line as a something and deal
1234 * with it accordingly.
1236 * If the target was .SUFFIXES, we take each source as a
1237 * suffix and add it to the list of suffixes maintained by the
1240 * If the target was a .PATH, we add the source as a directory
1241 * to search on the search path.
1243 * If it was .INCLUDES, the source is taken to be the suffix of
1244 * files which will be #included and whose search path should
1245 * be present in the .INCLUDES variable.
1247 * If it was .LIBS, the source is taken to be the suffix of
1248 * files which are considered libraries and whose search path
1249 * should be present in the .LIBS variable.
1251 * If it was .NULL, the source is the suffix to use when a file
1252 * has no valid suffix.
1254 * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1255 * and will cause make to do a new chdir to that path.
1257 while (*cp
&& !isspace ((unsigned char)*cp
)) {
1264 Suff_AddSuffix(line
, &mainNode
);
1267 Lst_ForEach(paths
, ParseAddDir
, line
);
1270 Suff_AddInclude(line
);
1279 Main_SetObjdir(line
);
1285 if (savec
!= '\0') {
1288 while (*cp
&& isspace ((unsigned char)*cp
)) {
1294 Lst_Destroy(paths
, NULL
);
1296 if (specType
== ExPath
)
1301 * The targets take real sources, so we must beware of archive
1302 * specifications (i.e. things with left parentheses in them)
1303 * and handle them accordingly.
1305 for (; *cp
&& !isspace ((unsigned char)*cp
); cp
++) {
1306 if ((*cp
== LPAREN
) && (cp
> line
) && (cp
[-1] != '$')) {
1308 * Only stop for a left parenthesis if it isn't at the
1309 * start of a word (that'll be for variable changes
1310 * later) and isn't preceded by a dollar sign (a dynamic
1317 if (*cp
== LPAREN
) {
1318 sources
= Lst_Init(FALSE
);
1319 if (Arch_ParseArchive(&line
, sources
, VAR_CMD
) != SUCCESS
) {
1320 Parse_Error(PARSE_FATAL
,
1321 "Error in source archive spec \"%s\"", line
);
1325 while (!Lst_IsEmpty (sources
)) {
1326 gn
= (GNode
*)Lst_DeQueue(sources
);
1327 ParseDoSrc(tOp
, gn
->name
);
1329 Lst_Destroy(sources
, NULL
);
1337 ParseDoSrc(tOp
, line
);
1339 while (*cp
&& isspace ((unsigned char)*cp
)) {
1346 if (mainNode
== NULL
) {
1348 * If we have yet to decide on a main target to make, in the
1349 * absence of any user input, we want the first target on
1350 * the first dependency line that is actually a real target
1351 * (i.e. isn't a .USE or .EXEC rule) to be made.
1353 Lst_ForEach(targets
, ParseFindMain
, NULL
);
1358 Lst_Destroy(curTargs
, NULL
);
1362 *---------------------------------------------------------------------
1364 * Return TRUE if the passed line is a variable assignment. A variable
1365 * assignment consists of a single word followed by optional whitespace
1366 * followed by either a += or an = operator.
1367 * This function is used both by the Parse_File function and main when
1368 * parsing the command-line arguments.
1371 * line the line to check
1374 * TRUE if it is. FALSE if it ain't
1378 *---------------------------------------------------------------------
1381 Parse_IsVar(char *line
)
1383 Boolean wasSpace
= FALSE
; /* set TRUE if found a space */
1386 #define ISEQOPERATOR(c) \
1387 (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1390 * Skip to variable name
1392 for (;(*line
== ' ') || (*line
== '\t'); line
++)
1395 /* Scan for one of the assignment operators outside a variable expansion */
1396 while ((ch
= *line
++) != 0) {
1397 if (ch
== '(' || ch
== '{') {
1401 if (ch
== ')' || ch
== '}') {
1407 while (ch
== ' ' || ch
== '\t') {
1413 if (*line
== '=' && ISEQOPERATOR(ch
))
1423 *---------------------------------------------------------------------
1425 * Take the variable assignment in the passed line and do it in the
1428 * Note: There is a lexical ambiguity with assignment modifier characters
1429 * in variable names. This routine interprets the character before the =
1430 * as a modifier. Therefore, an assignment like
1432 * is interpreted as "C+ +=" instead of "C++ =".
1435 * line a line guaranteed to be a variable assignment.
1436 * This reduces error checks
1437 * ctxt Context in which to do the assignment
1443 * the variable structure of the given variable name is altered in the
1445 *---------------------------------------------------------------------
1448 Parse_DoVar(char *line
, GNode
*ctxt
)
1450 char *cp
; /* pointer into line */
1452 VAR_SUBST
, VAR_APPEND
, VAR_SHELL
, VAR_NORMAL
1453 } type
; /* Type of assignment */
1454 char *opc
; /* ptr to operator character to
1455 * null-terminate the variable name */
1456 Boolean freeCp
= FALSE
; /* TRUE if cp needs to be freed,
1457 * i.e. if any variable expansion was
1462 * Skip to variable name
1464 while ((*line
== ' ') || (*line
== '\t')) {
1469 * Skip to operator character, nulling out whitespace as we go
1470 * XXX Rather than counting () and {} we should look for $ and
1471 * then expand the variable.
1473 for (depth
= 0, cp
= line
+ 1; depth
!= 0 || *cp
!= '='; cp
++) {
1474 if (*cp
== '(' || *cp
== '{') {
1478 if (*cp
== ')' || *cp
== '}') {
1482 if (depth
== 0 && isspace ((unsigned char)*cp
)) {
1486 opc
= cp
-1; /* operator is the previous character */
1487 *cp
++ = '\0'; /* nuke the = */
1490 * Check operator type
1500 * If the variable already has a value, we don't do anything.
1503 if (Var_Exists(line
, ctxt
)) {
1522 while (opc
> line
&& *opc
!= ':')
1525 if (strncmp(opc
, ":sh", 3) == 0) {
1535 while (isspace ((unsigned char)*cp
)) {
1539 if (type
== VAR_APPEND
) {
1540 Var_Append(line
, cp
, ctxt
);
1541 } else if (type
== VAR_SUBST
) {
1543 * Allow variables in the old value to be undefined, but leave their
1544 * invocation alone -- this is done by forcing oldVars to be false.
1545 * XXX: This can cause recursive variables, but that's not hard to do,
1546 * and this allows someone to do something like
1548 * CFLAGS = $(.INCLUDES)
1549 * CFLAGS := -I.. $(CFLAGS)
1551 * And not get an error.
1553 Boolean oldOldVars
= oldVars
;
1558 * make sure that we set the variable the first time to nothing
1559 * so that it gets substituted!
1561 if (!Var_Exists(line
, ctxt
))
1562 Var_Set(line
, "", ctxt
, 0);
1564 cp
= Var_Subst(NULL
, cp
, ctxt
, FALSE
);
1565 oldVars
= oldOldVars
;
1568 Var_Set(line
, cp
, ctxt
, 0);
1569 } else if (type
== VAR_SHELL
) {
1573 if (strchr(cp
, '$') != NULL
) {
1575 * There's a dollar sign in the command, so perform variable
1576 * expansion on the whole thing. The resulting string will need
1577 * freeing when we're done, so set freeCmd to TRUE.
1579 cp
= Var_Subst(NULL
, cp
, VAR_CMD
, TRUE
);
1583 res
= Cmd_Exec(cp
, &error
);
1584 Var_Set(line
, res
, ctxt
, 0);
1588 Parse_Error(PARSE_WARNING
, error
, cp
);
1591 * Normal assignment -- just do it.
1593 Var_Set(line
, cp
, ctxt
, 0);
1595 if (strcmp(line
, MAKEOVERRIDES
) == 0)
1596 Main_ExportMAKEFLAGS(FALSE
); /* re-export MAKEFLAGS */
1597 else if (strcmp(line
, ".CURDIR") == 0) {
1599 * Somone is being (too?) clever...
1600 * Let's pretend they know what they are doing and
1601 * re-initialize the 'cur' Path.
1605 } else if (strcmp(line
, MAKE_JOB_PREFIX
) == 0) {
1607 } else if (strcmp(line
, MAKE_EXPORTED
) == 0) {
1617 * Lst_ForEach function to add a command line to all targets
1620 * gnp the node to which the command is to be added
1621 * cmd the command to add
1627 * A new element is added to the commands list of the node.
1630 ParseAddCmd(void *gnp
, void *cmd
)
1632 GNode
*gn
= (GNode
*)gnp
;
1634 /* Add to last (ie current) cohort for :: targets */
1635 if ((gn
->type
& OP_DOUBLEDEP
) && !Lst_IsEmpty (gn
->cohorts
))
1636 gn
= (GNode
*)Lst_Datum(Lst_Last(gn
->cohorts
));
1638 /* if target already supplied, ignore commands */
1639 if (!(gn
->type
& OP_HAS_COMMANDS
)) {
1640 (void)Lst_AtEnd(gn
->commands
, cmd
);
1644 /* XXX: We cannot do this until we fix the tree */
1645 (void)Lst_AtEnd(gn
->commands
, cmd
);
1646 Parse_Error(PARSE_WARNING
,
1647 "overriding commands for target \"%s\"; "
1648 "previous commands defined at %s: %d ignored",
1649 gn
->name
, gn
->fname
, gn
->lineno
);
1651 Parse_Error(PARSE_WARNING
,
1652 "duplicate script for target \"%s\" ignored",
1654 ParseErrorInternal(gn
->fname
, gn
->lineno
, PARSE_WARNING
,
1655 "using previous script for \"%s\" defined here",
1663 *-----------------------------------------------------------------------
1664 * ParseHasCommands --
1665 * Callback procedure for Parse_File when destroying the list of
1666 * targets on the last dependency line. Marks a target as already
1667 * having commands if it does, to keep from having shell commands
1668 * on multiple dependency lines.
1671 * gnp Node to examine
1677 * OP_HAS_COMMANDS may be set for the target.
1679 *-----------------------------------------------------------------------
1682 ParseHasCommands(void *gnp
)
1684 GNode
*gn
= (GNode
*)gnp
;
1685 if (!Lst_IsEmpty(gn
->commands
)) {
1686 gn
->type
|= OP_HAS_COMMANDS
;
1691 *-----------------------------------------------------------------------
1692 * Parse_AddIncludeDir --
1693 * Add a directory to the path searched for included makefiles
1694 * bracketed by double-quotes. Used by functions in main.c
1697 * dir The name of the directory to add
1703 * The directory is appended to the list.
1705 *-----------------------------------------------------------------------
1708 Parse_AddIncludeDir(char *dir
)
1710 (void)Dir_AddDir(parseIncPath
, dir
);
1714 *---------------------------------------------------------------------
1716 * Push to another file.
1718 * The input is the line minus the `.'. A file spec is a string
1719 * enclosed in <> or "". The former is looked for only in sysIncPath.
1720 * The latter in . and the directories specified by -I command line
1727 * A structure is added to the includes Lst and readProc, lineno,
1728 * fname and curFILE are altered for the new file
1729 *---------------------------------------------------------------------
1733 Parse_include_file(char *file
, Boolean isSystem
, int silent
)
1735 char *fullname
; /* full pathname of file */
1737 char *prefEnd
, *incdir
;
1742 * Now we know the file's name and its search path, we attempt to
1743 * find the durn thing. A return of NULL indicates the file don't
1746 fullname
= file
[0] == '/' ? bmake_strdup(file
) : NULL
;
1748 if (fullname
== NULL
&& !isSystem
) {
1750 * Include files contained in double-quotes are first searched for
1751 * relative to the including file's location. We don't want to
1752 * cd there, of course, so we just tack on the old file's
1753 * leading path components and call Dir_FindFile to see if
1754 * we can locate the beast.
1757 incdir
= bmake_strdup(curFile
->fname
);
1758 prefEnd
= strrchr(incdir
, '/');
1759 if (prefEnd
!= NULL
) {
1761 /* Now do lexical processing of leading "../" on the filename */
1762 for (i
= 0; strncmp(file
+ i
, "../", 3) == 0; i
+= 3) {
1763 prefEnd
= strrchr(incdir
+ 1, '/');
1764 if (prefEnd
== NULL
|| strcmp(prefEnd
, "/..") == 0)
1768 newName
= str_concat(incdir
, file
+ i
, STR_ADDSLASH
);
1769 fullname
= Dir_FindFile(newName
, parseIncPath
);
1770 if (fullname
== NULL
)
1771 fullname
= Dir_FindFile(newName
, dirSearchPath
);
1776 if (fullname
== NULL
) {
1778 * Makefile wasn't found in same directory as included makefile.
1779 * Search for it first on the -I search path,
1780 * then on the .PATH search path, if not found in a -I directory.
1781 * If we have a suffix specific path we should use that.
1784 Lst suffPath
= NULL
;
1786 if ((suff
= strrchr(file
, '.'))) {
1787 suffPath
= Suff_GetPath(suff
);
1788 if (suffPath
!= NULL
) {
1789 fullname
= Dir_FindFile(file
, suffPath
);
1792 if (fullname
== NULL
) {
1793 fullname
= Dir_FindFile(file
, parseIncPath
);
1794 if (fullname
== NULL
) {
1795 fullname
= Dir_FindFile(file
, dirSearchPath
);
1801 /* Looking for a system file or file still not found */
1802 if (fullname
== NULL
) {
1804 * Look for it on the system path
1806 fullname
= Dir_FindFile(file
,
1807 Lst_IsEmpty(sysIncPath
) ? defIncPath
: sysIncPath
);
1810 if (fullname
== NULL
) {
1812 Parse_Error(PARSE_FATAL
, "Could not find %s", file
);
1816 /* Actually open the file... */
1817 fd
= open(fullname
, O_RDONLY
);
1820 Parse_Error(PARSE_FATAL
, "Cannot open %s", fullname
);
1825 /* Start reading from this file next */
1826 Parse_SetInput(fullname
, 0, fd
, NULL
, NULL
);
1830 ParseDoInclude(char *line
)
1832 char endc
; /* the character which ends the file spec */
1833 char *cp
; /* current position in file spec */
1834 int silent
= (*line
!= 'i') ? 1 : 0;
1835 char *file
= &line
[7 + silent
];
1837 /* Skip to delimiter character so we know where to look */
1838 while (*file
== ' ' || *file
== '\t')
1841 if (*file
!= '"' && *file
!= '<') {
1842 Parse_Error(PARSE_FATAL
,
1843 ".include filename must be delimited by '\"' or '<'");
1848 * Set the search path on which to find the include file based on the
1849 * characters which bracket its name. Angle-brackets imply it's
1850 * a system Makefile while double-quotes imply it's a user makefile
1858 /* Skip to matching delimiter */
1859 for (cp
= ++file
; *cp
&& *cp
!= endc
; cp
++)
1863 Parse_Error(PARSE_FATAL
,
1864 "Unclosed %cinclude filename. '%c' expected",
1871 * Substitute for any variables in the file name before trying to
1874 file
= Var_Subst(NULL
, file
, VAR_CMD
, FALSE
);
1876 Parse_include_file(file
, endc
== '>', silent
);
1882 *---------------------------------------------------------------------
1883 * ParseSetParseFile --
1884 * Set the .PARSEDIR and .PARSEFILE variables to the dirname and
1885 * basename of the given filename
1891 * The .PARSEDIR and .PARSEFILE variables are overwritten by the
1892 * dirname and basename of the given filename.
1893 *---------------------------------------------------------------------
1896 ParseSetParseFile(const char *filename
)
1902 slash
= strrchr(filename
, '/');
1903 if (slash
== NULL
) {
1904 Var_Set(".PARSEDIR", ".", VAR_GLOBAL
, 0);
1905 Var_Set(".PARSEFILE", filename
, VAR_GLOBAL
, 0);
1907 len
= slash
- filename
;
1908 dirname
= bmake_malloc(len
+ 1);
1909 memcpy(dirname
, filename
, len
);
1911 Var_Set(".PARSEDIR", dirname
, VAR_GLOBAL
, 0);
1912 Var_Set(".PARSEFILE", slash
+1, VAR_GLOBAL
, 0);
1918 * Track the makefiles we read - so makefiles can
1919 * set dependencies on them.
1920 * Avoid adding anything more than once.
1924 ParseTrackInput(const char *name
)
1928 size_t name_len
= strlen(name
);
1930 old
= Var_Value(MAKE_MAKEFILES
, VAR_GLOBAL
, &fp
);
1932 /* does it contain name? */
1933 for (; old
!= NULL
; old
= strchr(old
, ' ')) {
1936 if (memcmp(old
, name
, name_len
) == 0
1937 && (old
[name_len
] == 0 || old
[name_len
] == ' '))
1941 Var_Append (MAKE_MAKEFILES
, name
, VAR_GLOBAL
);
1950 *---------------------------------------------------------------------
1952 * Start Parsing from the given source
1958 * A structure is added to the includes Lst and readProc, lineno,
1959 * fname and curFile are altered for the new file
1960 *---------------------------------------------------------------------
1963 Parse_SetInput(const char *name
, int line
, int fd
, char *(*nextbuf
)(void *), void *arg
)
1968 name
= curFile
->fname
;
1970 ParseTrackInput(name
);
1973 fprintf(debug_file
, "Parse_SetInput: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
1974 name
, line
, fd
, nextbuf
, arg
);
1976 if (fd
== -1 && nextbuf
== NULL
)
1980 if (curFile
!= NULL
)
1981 /* Save exiting file info */
1982 Lst_AtFront(includes
, curFile
);
1984 /* Allocate and fill in new structure */
1985 curFile
= bmake_malloc(sizeof *curFile
);
1988 * Once the previous state has been saved, we can get down to reading
1989 * the new file. We set up the name of the file to be the absolute
1990 * name of the include file so error messages refer to the right
1993 curFile
->fname
= name
;
1994 curFile
->lineno
= line
;
1995 curFile
->first_lineno
= line
;
1997 curFile
->nextbuf
= nextbuf
;
1998 curFile
->nextbuf_arg
= arg
;
2000 if (nextbuf
== NULL
) {
2002 * Allocate a 32k data buffer (as stdio seems to).
2003 * Set pointers so that first ParseReadc has to do a file read.
2005 buf
= bmake_malloc(IFILE_BUFLEN
);
2007 curFile
->P_str
= buf
;
2008 curFile
->P_ptr
= buf
;
2009 curFile
->P_end
= buf
;
2010 curFile
->P_buflen
= IFILE_BUFLEN
;
2012 /* Get first block of input data */
2013 buf
= curFile
->nextbuf(curFile
->nextbuf_arg
);
2015 /* Was all a waste of time ... */
2019 curFile
->P_str
= buf
;
2020 curFile
->P_ptr
= buf
;
2021 curFile
->P_end
= NULL
;
2024 curFile
->cond_depth
= Cond_save_depth();
2025 ParseSetParseFile(name
);
2030 *---------------------------------------------------------------------
2031 * ParseTraditionalInclude --
2032 * Push to another file.
2034 * The input is the current line. The file name(s) are
2035 * following the "include".
2041 * A structure is added to the includes Lst and readProc, lineno,
2042 * fname and curFILE are altered for the new file
2043 *---------------------------------------------------------------------
2046 ParseTraditionalInclude(char *line
)
2048 char *cp
; /* current position in file spec */
2050 int silent
= (line
[0] != 'i') ? 1 : 0;
2051 char *file
= &line
[silent
+ 7];
2055 fprintf(debug_file
, "ParseTraditionalInclude: %s\n", file
);
2059 * Skip over whitespace
2061 while (isspace((unsigned char)*file
))
2065 * Substitute for any variables in the file name before trying to
2068 all_files
= Var_Subst(NULL
, file
, VAR_CMD
, FALSE
);
2070 if (*file
== '\0') {
2071 Parse_Error(PARSE_FATAL
,
2072 "Filename missing from \"include\"");
2076 for (file
= all_files
; !done
; file
= cp
+ 1) {
2077 /* Skip to end of line or next whitespace */
2078 for (cp
= file
; *cp
&& !isspace((unsigned char) *cp
); cp
++)
2086 Parse_include_file(file
, FALSE
, silent
);
2093 *---------------------------------------------------------------------
2095 * Called when EOF is reached in the current file. If we were reading
2096 * an include file, the includes stack is popped and things set up
2097 * to go back to reading the previous file at the previous location.
2100 * CONTINUE if there's more to do. DONE if not.
2103 * The old curFILE, is closed. The includes list is shortened.
2104 * lineno, curFILE, and fname are changed if CONTINUE is returned.
2105 *---------------------------------------------------------------------
2112 if (curFile
->nextbuf
!= NULL
) {
2113 /* eg .for loop data, get next iteration */
2114 ptr
= curFile
->nextbuf(curFile
->nextbuf_arg
);
2115 curFile
->P_ptr
= ptr
;
2116 curFile
->P_str
= ptr
;
2117 curFile
->lineno
= curFile
->first_lineno
;
2124 /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2125 Cond_restore_depth(curFile
->cond_depth
);
2127 /* Dispose of curFile info */
2128 /* Leak curFile->fname because all the gnodes have pointers to it */
2129 if (curFile
->fd
!= -1)
2131 free(curFile
->P_str
);
2134 curFile
= Lst_DeQueue(includes
);
2136 if (curFile
== NULL
) {
2137 /* We've run out of input */
2138 Var_Delete(".PARSEDIR", VAR_GLOBAL
);
2139 Var_Delete(".PARSEFILE", VAR_GLOBAL
);
2144 fprintf(debug_file
, "ParseEOF: returning to file %s, line %d, fd %d\n",
2145 curFile
->fname
, curFile
->lineno
, curFile
->fd
);
2147 /* Restore the PARSEDIR/PARSEFILE variables */
2148 ParseSetParseFile(curFile
->fname
);
2153 #define PARSE_SKIP 2
2156 ParseGetLine(int flags
, int *length
)
2158 IFile
*cf
= curFile
;
2168 /* Loop through blank lines and comment lines */
2178 if (ch
== 0 || (ch
== '\\' && ptr
[1] == 0)) {
2179 if (cf
->P_end
== NULL
)
2180 /* End of string (aka for loop) data */
2182 /* End of data read from file, read more data */
2183 if (ptr
!= cf
->P_end
&& (ch
!= '\\' || ptr
+ 1 != cf
->P_end
)) {
2184 Parse_Error(PARSE_FATAL
, "Zero byte read from file");
2187 /* Move existing data to (near) start of file buffer */
2188 len
= cf
->P_end
- cf
->P_ptr
;
2189 tp
= cf
->P_str
+ 32;
2190 memmove(tp
, cf
->P_ptr
, len
);
2191 dist
= cf
->P_ptr
- tp
;
2192 /* Update all pointers to reflect moved data */
2203 /* Try to read more data from file into buffer space */
2204 len
= cf
->P_str
+ cf
->P_buflen
- tp
- 32;
2206 /* We need a bigger buffer to hold this line */
2207 tp
= bmake_realloc(cf
->P_str
, cf
->P_buflen
+ IFILE_BUFLEN
);
2208 cf
->P_ptr
= cf
->P_ptr
- cf
->P_str
+ tp
;
2209 cf
->P_end
= cf
->P_end
- cf
->P_str
+ tp
;
2210 ptr
= ptr
- cf
->P_str
+ tp
;
2211 line
= line
- cf
->P_str
+ tp
;
2212 line_end
= line_end
- cf
->P_str
+ tp
;
2214 escaped
= escaped
- cf
->P_str
+ tp
;
2216 comment
= comment
- cf
->P_str
+ tp
;
2219 len
+= IFILE_BUFLEN
;
2220 cf
->P_buflen
+= IFILE_BUFLEN
;
2222 len
= read(cf
->fd
, tp
, len
);
2225 Parse_Error(PARSE_FATAL
, "Makefile read error: %s",
2232 /* 0 terminate the data, and update end pointer */
2236 /* Process newly read characters */
2241 /* Don't treat next character as special, remember first one */
2242 if (escaped
== NULL
)
2250 if (ch
== '#' && comment
== NULL
) {
2251 /* Remember first '#' for comment stripping */
2257 if (!isspace((unsigned char)ch
))
2258 /* We are not interested in trailing whitespace */
2262 /* Save next 'to be processed' location */
2265 /* Check we have a non-comment, non-blank line */
2266 if (line_end
== line
|| comment
== line
) {
2268 /* At end of file */
2270 /* Parse another line */
2274 /* We now have a line of data */
2277 if (flags
& PARSE_RAW
) {
2278 /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2279 *length
= line_end
- line
;
2283 if (flags
& PARSE_SKIP
) {
2284 /* Completely ignore non-directives */
2287 /* We could do more of the .else/.elif/.endif checks here */
2292 /* Brutally ignore anything after a non-escaped '#' in non-commands */
2293 if (comment
!= NULL
&& line
[0] != '\t') {
2298 /* If we didn't see a '\\' then the in-situ data is fine */
2299 if (escaped
== NULL
) {
2300 *length
= line_end
- line
;
2304 /* Remove escapes from '\n' and '#' */
2307 for (; ; *tp
++ = ch
) {
2317 /* Delete '\\' at end of buffer */
2322 if (ch
== '#' && line
[0] != '\t')
2323 /* Delete '\\' from before '#' on non-command lines */
2327 /* Leave '\\' in buffer for later */
2329 /* Make sure we don't delete an escaped ' ' from the line end */
2334 /* Escaped '\n' replace following whitespace with a single ' ' */
2335 while (ptr
[0] == ' ' || ptr
[0] == '\t')
2340 /* Delete any trailing spaces - eg from empty continuations */
2341 while (tp
> escaped
&& isspace((unsigned char)tp
[-1]))
2345 *length
= tp
- line
;
2350 *---------------------------------------------------------------------
2352 * Read an entire line from the input file. Called only by Parse_File.
2355 * A line w/o its newline
2358 * Only those associated with reading a character
2359 *---------------------------------------------------------------------
2364 char *line
; /* Result */
2365 int lineLength
; /* Length of result */
2366 int lineno
; /* Saved line # */
2370 line
= ParseGetLine(0, &lineLength
);
2378 * The line might be a conditional. Ask the conditional module
2379 * about it and act accordingly
2381 switch (Cond_Eval(line
)) {
2383 /* Skip to next conditional that evaluates to COND_PARSE. */
2385 line
= ParseGetLine(PARSE_SKIP
, &lineLength
);
2386 } while (line
&& Cond_Eval(line
) != COND_PARSE
);
2392 case COND_INVALID
: /* Not a conditional line */
2393 /* Check for .for loops */
2394 rval
= For_Eval(line
);
2396 /* Not a .for line */
2399 /* Syntax error - error printed, ignore line */
2401 /* Start of a .for loop */
2402 lineno
= curFile
->lineno
;
2403 /* Accumulate loop lines until matching .endfor */
2405 line
= ParseGetLine(PARSE_RAW
, &lineLength
);
2407 Parse_Error(PARSE_FATAL
,
2408 "Unexpected end of file in for loop.\n");
2411 } while (For_Accum(line
));
2412 /* Stash each iteration as a new 'input file' */
2414 /* Read next line from for-loop buffer */
2422 *-----------------------------------------------------------------------
2423 * ParseFinishLine --
2424 * Handle the end of a dependency group.
2430 * inLine set FALSE. 'targets' list destroyed.
2432 *-----------------------------------------------------------------------
2435 ParseFinishLine(void)
2438 Lst_ForEach(targets
, Suff_EndTransform
, NULL
);
2439 Lst_Destroy(targets
, ParseHasCommands
);
2447 *---------------------------------------------------------------------
2449 * Parse a file into its component parts, incorporating it into the
2450 * current dependency graph. This is the main function and controls
2451 * almost every other function in this module
2454 * name the name of the file being read
2455 * fd Open file to makefile to parse
2462 * Loads. Nodes are added to the list of all targets, nodes and links
2463 * are added to the dependency graph. etc. etc. etc.
2464 *---------------------------------------------------------------------
2467 Parse_File(const char *name
, int fd
)
2469 char *cp
; /* pointer into the line */
2470 char *line
; /* the line we're working on */
2475 Parse_SetInput(name
, 0, fd
, NULL
, NULL
);
2478 for (; (line
= ParseReadLine()) != NULL
; ) {
2480 fprintf(debug_file
, "ParseReadLine (%d): '%s'\n",
2481 curFile
->lineno
, line
);
2484 * Lines that begin with the special character may be
2485 * include or undef directives.
2486 * On the other hand they can be suffix rules (.c.o: ...)
2487 * or just dependencies for filenames that start '.'.
2489 for (cp
= line
+ 1; isspace((unsigned char)*cp
); cp
++) {
2492 if (strncmp(cp
, "include", 7) == 0 ||
2493 ((cp
[0] == 's' || cp
[0] == '-') &&
2494 strncmp(&cp
[1], "include", 7) == 0)) {
2498 if (strncmp(cp
, "undef", 5) == 0) {
2500 for (cp
+= 5; isspace((unsigned char) *cp
); cp
++)
2502 for (cp2
= cp
; !isspace((unsigned char) *cp2
) &&
2503 (*cp2
!= '\0'); cp2
++)
2506 Var_Delete(cp
, VAR_GLOBAL
);
2508 } else if (strncmp(cp
, "export", 6) == 0) {
2509 for (cp
+= 6; isspace((unsigned char) *cp
); cp
++)
2513 } else if (strncmp(cp
, "unexport", 8) == 0) {
2519 if (*line
== '\t') {
2521 * If a line starts with a tab, it can only hope to be
2522 * a creation command.
2526 for (; isspace ((unsigned char)*cp
); cp
++) {
2531 Parse_Error(PARSE_FATAL
,
2532 "Unassociated shell command \"%s\"",
2535 * So long as it's not a blank line and we're actually
2536 * in a dependency spec, add the command to the list of
2537 * commands of all targets in the dependency spec
2540 cp
= bmake_strdup(cp
);
2541 Lst_ForEach(targets
, ParseAddCmd
, cp
);
2543 Lst_AtEnd(targCmds
, cp
);
2551 if (((strncmp(line
, "include", 7) == 0 &&
2552 isspace((unsigned char) line
[7])) ||
2553 ((line
[0] == 's' || line
[0] == '-') &&
2554 strncmp(&line
[1], "include", 7) == 0 &&
2555 isspace((unsigned char) line
[8]))) &&
2556 strchr(line
, ':') == NULL
) {
2558 * It's an S3/S5-style "include".
2560 ParseTraditionalInclude(line
);
2564 if (Parse_IsVar(line
)) {
2566 Parse_DoVar(line
, VAR_GLOBAL
);
2572 * To make life easier on novices, if the line is indented we
2573 * first make sure the line has a dependency operator in it.
2574 * If it doesn't have an operator and we're in a dependency
2575 * line's script, we assume it's actually a shell command
2576 * and add it to the current list of targets.
2579 if (isspace((unsigned char) line
[0])) {
2580 while ((*cp
!= '\0') && isspace((unsigned char) *cp
))
2582 while (*cp
&& (ParseIsEscaped(line
, cp
) ||
2583 (*cp
!= ':') && (*cp
!= '!'))) {
2588 Parse_Error(PARSE_WARNING
,
2589 "Shell command needs a leading tab");
2598 * For some reason - probably to make the parser impossible -
2599 * a ';' can be used to separate commands from dependencies.
2600 * Attempt to avoid ';' inside substitution patterns.
2605 for (cp
= line
; *cp
!= 0; cp
++) {
2606 if (*cp
== '\\' && cp
[1] != 0) {
2611 (cp
[1] == '(' || cp
[1] == '{')) {
2616 if (*cp
== ')' || *cp
== '}') {
2620 } else if (*cp
== ';') {
2626 /* Terminate the dependency list at the ';' */
2632 * We now know it's a dependency line so it needs to have all
2633 * variables expanded before being parsed. Tell the variable
2634 * module to complain if some variable is undefined...
2636 line
= Var_Subst(NULL
, line
, VAR_CMD
, TRUE
);
2639 * Need a non-circular list for the target nodes
2642 Lst_Destroy(targets
, NULL
);
2644 targets
= Lst_Init(FALSE
);
2647 ParseDoDependency(line
);
2650 /* If there were commands after a ';', add them now */
2656 * Reached EOF, but it may be just EOF of an include file...
2658 } while (ParseEOF() == CONTINUE
);
2661 (void)fprintf(stderr
,
2662 "%s: Fatal errors encountered -- cannot continue\n",
2670 *---------------------------------------------------------------------
2672 * initialize the parsing module
2678 * the parseIncPath list is initialized...
2679 *---------------------------------------------------------------------
2685 parseIncPath
= Lst_Init(FALSE
);
2686 sysIncPath
= Lst_Init(FALSE
);
2687 defIncPath
= Lst_Init(FALSE
);
2688 includes
= Lst_Init(FALSE
);
2690 targCmds
= Lst_Init(FALSE
);
2698 Lst_Destroy(targCmds
, (FreeProc
*)free
);
2700 Lst_Destroy(targets
, NULL
);
2701 Lst_Destroy(defIncPath
, Dir_Destroy
);
2702 Lst_Destroy(sysIncPath
, Dir_Destroy
);
2703 Lst_Destroy(parseIncPath
, Dir_Destroy
);
2704 Lst_Destroy(includes
, NULL
); /* Should be empty now */
2710 *-----------------------------------------------------------------------
2712 * Return a Lst of the main target to create for main()'s sake. If
2713 * no such target exists, we Punt with an obnoxious error message.
2716 * A Lst of the single node to create.
2721 *-----------------------------------------------------------------------
2724 Parse_MainName(void)
2726 Lst mainList
; /* result list */
2728 mainList
= Lst_Init(FALSE
);
2730 if (mainNode
== NULL
) {
2731 Punt("no target to make.");
2733 } else if (mainNode
->type
& OP_DOUBLEDEP
) {
2734 (void)Lst_AtEnd(mainList
, mainNode
);
2735 Lst_Concat(mainList
, mainNode
->cohorts
, LST_CONCNEW
);
2738 (void)Lst_AtEnd(mainList
, mainNode
);
2739 Var_Append(".TARGETS", mainNode
->name
, VAR_GLOBAL
);
2744 *-----------------------------------------------------------------------
2746 * Add the filename and lineno to the GNode so that we remember
2747 * where it was first defined.
2752 *-----------------------------------------------------------------------
2755 ParseMark(GNode
*gn
)
2757 gn
->fname
= curFile
->fname
;
2758 gn
->lineno
= curFile
->lineno
;