2 * Copyright (c) 1988, 1989, 1990, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 1989 by Berkeley Softworks
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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)parse.c 8.3 (Berkeley) 3/19/94
39 * $FreeBSD: src/usr.bin/make/parse.c,v 1.75 2005/02/07 11:27:47 harti Exp $
40 * $DragonFly: src/usr.bin/make/parse.c,v 1.70 2005/04/15 21:05:52 okumoto Exp $
45 * Functions to parse a makefile.
47 * Most important structures are kept in Lsts. Directories for
48 * the #include "..." function are kept in the 'parseIncPath' Lst, while
49 * those for the #include <...> are kept in the 'sysIncPath' Lst. The
50 * targets currently being defined are kept in the 'targets' Lst.
54 * Parse_File Function used to parse a makefile. It must
55 * be given the name of the file, which should
56 * already have been opened, and a function
57 * to call to read a character from the file.
59 * Parse_IsVar Returns TRUE if the given line is a
60 * variable assignment. Used by MainParseArgs
61 * to determine if an argument is a target
62 * or a variable assignment. Used internally
63 * for pretty much the same thing...
65 * Parse_Error Function called when an error occurs in
66 * parsing. Used by the variable and
67 * conditional modules.
69 * Parse_MainName Returns a Lst of the main target to create.
91 #include "pathnames.h"
99 * These values are returned by ParsePopInput to tell Parse_File whether to
100 * CONTINUE parsing, i.e. it had only reached the end of an include file,
106 /* targets we're working on */
107 static Lst targets = Lst_Initializer(targets);
109 /* true if currently in a dependency line or its commands */
110 static Boolean inLine;
112 static int fatals = 0;
115 * The main target to create. This is the first target on the
116 * first dependency line in the first makefile.
118 static GNode *mainNode;
121 * Definitions for handling #include specifications
124 char *fname; /* name of previous file */
125 int lineno; /* saved line number */
126 FILE *F; /* the open stream */
127 char *str; /* the string when parsing a string */
128 char *ptr; /* the current pointer when parsing a string */
129 TAILQ_ENTRY(IFile) link;/* stack the files */
132 /* stack of IFiles generated by * #includes */
133 static TAILQ_HEAD(, IFile) includes = TAILQ_HEAD_INITIALIZER(includes);
135 /* access current file */
136 #define CURFILE (TAILQ_FIRST(&includes))
138 /* list of directories for "..." includes */
139 struct Path parseIncPath = TAILQ_HEAD_INITIALIZER(parseIncPath);
141 /* list of directories for <...> includes */
142 struct Path sysIncPath = TAILQ_HEAD_INITIALIZER(sysIncPath);
145 * specType contains the SPECial TYPE of the current target. It is
146 * Not if the target is unspecial. If it *is* special, however, the children
147 * are linked as children of the parent but not vice versa. This variable is
148 * set in ParseDoDependency
152 Default, /* .DEFAULT */
154 Export, /* .EXPORT */
155 Ignore, /* .IGNORE */
156 Includes, /* .INCLUDES */
157 Interrupt, /* .INTERRUPT */
159 MFlags, /* .MFLAGS or .MAKEFLAGS */
160 Main, /* .MAIN and we don't have anyth. user-spec. to make */
161 Not, /* Not special */
162 NotParallel, /* .NOTPARALELL */
165 Parallel, /* .PARALLEL */
169 Precious, /* .PRECIOUS */
170 ExShell, /* .SHELL */
171 Silent, /* .SILENT */
172 SingleShell, /* .SINGLESHELL */
173 Suffixes, /* .SUFFIXES */
175 Attribute /* Generic attribute */
178 static ParseSpecial specType;
182 * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
183 * seen, then set to each successive source on the line.
185 static GNode *predecessor;
188 * The parseKeywords table is searched using binary search when deciding
189 * if a target or source is special. The 'spec' field is the ParseSpecial
190 * type of the keyword ("Not" if the keyword isn't special as a target) while
191 * the 'op' field is the operator to apply to the list of targets if the
192 * keyword is used as a source ("0" if the keyword isn't special as a source)
195 const char *name; /* Name of keyword */
196 ParseSpecial spec; /* Type when used as a target */
197 int op; /* Operator when used as a source */
198 } parseKeywords[] = {
199 { ".BEGIN", Begin, 0 },
200 { ".DEFAULT", Default, 0 },
202 { ".EXEC", Attribute, OP_EXEC },
203 { ".EXPORT", Export, 0 },
204 { ".IGNORE", Ignore, OP_IGNORE },
205 { ".INCLUDES", Includes, 0 },
206 { ".INTERRUPT", Interrupt, 0 },
207 { ".INVISIBLE", Attribute, OP_INVISIBLE },
208 { ".JOIN", Attribute, OP_JOIN },
209 { ".LIBS", Libs, 0 },
210 { ".MAIN", Main, 0 },
211 { ".MAKE", Attribute, OP_MAKE },
212 { ".MAKEFLAGS", MFlags, 0 },
213 { ".MFLAGS", MFlags, 0 },
214 { ".NOTMAIN", Attribute, OP_NOTMAIN },
215 { ".NOTPARALLEL", NotParallel, 0 },
216 { ".NO_PARALLEL", NotParallel, 0 },
217 { ".NULL", Null, 0 },
218 { ".OPTIONAL", Attribute, OP_OPTIONAL },
219 { ".ORDER", Order, 0 },
220 { ".PARALLEL", Parallel, 0 },
221 { ".PATH", ExPath, 0 },
222 { ".PHONY", Phony, OP_PHONY },
223 { ".POSIX", Posix, 0 },
224 { ".PRECIOUS", Precious, OP_PRECIOUS },
225 { ".RECURSIVE", Attribute, OP_MAKE },
226 { ".SHELL", ExShell, 0 },
227 { ".SILENT", Silent, OP_SILENT },
228 { ".SINGLESHELL", SingleShell, 0 },
229 { ".SUFFIXES", Suffixes, 0 },
230 { ".USE", Attribute, OP_USE },
231 { ".WAIT", Wait, 0 },
235 * Directive table. We use a hash table. This hash table has been generated
236 * with mph which can be found on the usual GNU mirrors. If you change the
237 * directives (adding, deleting, reordering) you need to create a new table
238 * and hash function (directive_hash). The command line to generate the
241 * mph -d2 -m1 <tab | emitc -l -s
243 * Where tab is a file containing just the directive strings, one per line.
245 * While inporting the result of this the following changes have been made
246 * to the generated code:
248 * prefix the names of the g, T0 and T1 arrays with 'directive_'.
250 * make the type of the tables 'const [un]signed char'.
252 * make the hash function use the length for termination,
253 * not the trailing '\0'.
255 static void parse_include(char *, int, int);
256 static void parse_message(char *, int, int);
257 static void parse_undef(char *, int, int);
258 static void parse_for(char *, int, int);
259 static void parse_endfor(char *, int, int);
261 static const signed char directive_g[] = {
262 16, 0, -1, 14, 5, 2, 2, -1, 0, 0,
263 -1, -1, 16, 11, -1, 15, -1, 14, 7, -1,
264 8, 6, 1, -1, -1, 0, 4, 6, -1, 0,
265 0, 2, 0, 13, -1, 14, -1, 0,
268 static const unsigned char directive_T0[] = {
269 11, 25, 14, 30, 14, 26, 23, 15, 9, 37,
270 27, 32, 27, 1, 17, 27, 35, 13, 8, 22,
274 static const unsigned char directive_T1[] = {
275 19, 20, 31, 17, 29, 2, 7, 12, 1, 31,
276 11, 18, 11, 20, 10, 2, 15, 19, 4, 10,
280 static const struct directive {
283 Boolean skip_flag; /* execute even when skipped */
284 void (*func)(char *, int, int);
286 { "elif", COND_ELIF, TRUE, Cond_If },
287 { "elifdef", COND_ELIFDEF, TRUE, Cond_If },
288 { "elifmake", COND_ELIFMAKE, TRUE, Cond_If },
289 { "elifndef", COND_ELIFNDEF, TRUE, Cond_If },
290 { "elifnmake", COND_ELIFNMAKE, TRUE, Cond_If },
291 { "else", COND_ELSE, TRUE, Cond_Else },
292 { "endfor", 0, FALSE, parse_endfor },
293 { "endif", COND_ENDIF, TRUE, Cond_Endif },
294 { "error", 1, FALSE, parse_message },
295 { "for", 0, FALSE, parse_for },
296 { "if", COND_IF, TRUE, Cond_If },
297 { "ifdef", COND_IFDEF, TRUE, Cond_If },
298 { "ifmake", COND_IFMAKE, TRUE, Cond_If },
299 { "ifndef", COND_IFNDEF, TRUE, Cond_If },
300 { "ifnmake", COND_IFNMAKE, TRUE, Cond_If },
301 { "include", 0, FALSE, parse_include },
302 { "undef", 0, FALSE, parse_undef },
303 { "warning", 0, FALSE, parse_message },
305 #define NDIRECTS (sizeof(directives) / sizeof(directives[0]))
308 *----------------------------------------------------------------------
309 * ParseFindKeyword --
310 * Look in the table of keywords for one matching the given string.
313 * The index of the keyword, or -1 if it isn't there.
317 *----------------------------------------------------------------------
320 ParseFindKeyword(char *str)
328 end = (sizeof(parseKeywords) / sizeof(parseKeywords[0])) - 1;
331 cur = start + (end - start) / 2;
332 diff = strcmp(str, parseKeywords[cur].name);
335 } else if (diff < 0) {
340 } while (start <= end);
347 * Error message abort function for parsing. Prints out the context
348 * of the error (line number and file) as well as the message with
349 * two optional arguments.
355 * "fatals" is incremented if the level is PARSE_FATAL.
359 Parse_Error(int type, const char *fmt, ...)
365 fprintf(stderr, "\"%s\", line %d: ",
366 CURFILE->fname, CURFILE->lineno);
367 if (type == PARSE_WARNING)
368 fprintf(stderr, "warning: ");
369 vfprintf(stderr, fmt, ap);
371 fprintf(stderr, "\n");
373 if (type == PARSE_FATAL)
380 * Push a new input source onto the input stack. If ptr is NULL
381 * the fullname is used to fopen the file. If it is not NULL,
382 * ptr is assumed to point to the string to be parsed. If opening the
383 * file fails, the fullname is freed.
386 ParsePushInput(char *fullname, FILE *fp, char *ptr, int lineno)
390 nf = emalloc(sizeof(*nf));
391 nf->fname = fullname;
395 /* the input source is a file */
396 if ((nf->F = fp) == NULL) {
397 nf->F = fopen(fullname, "r");
399 Parse_Error(PARSE_FATAL, "Cannot open %s",
406 nf->str = nf->ptr = NULL;
407 Var_Append(".MAKEFILE_LIST", fullname, VAR_GLOBAL);
409 nf->str = nf->ptr = ptr;
412 TAILQ_INSERT_HEAD(&includes, nf, link);
417 * Called when EOF is reached in the current file. If we were reading
418 * an include file, the includes stack is popped and things set up
419 * to go back to reading the previous file at the previous location.
422 * CONTINUE if there's more to do. DONE if not.
425 * The old curFile.F is closed. The includes list is shortened.
426 * curFile.lineno, curFile.F, and curFile.fname are changed if
427 * CONTINUE is returned.
432 struct IFile *ifile; /* the state on the top of the includes stack */
434 assert(!TAILQ_EMPTY(&includes));
436 ifile = TAILQ_FIRST(&includes);
437 TAILQ_REMOVE(&includes, ifile, link);
440 if (ifile->F != NULL) {
442 Var_Append(".MAKEFILE_LIST", "..", VAR_GLOBAL);
444 if (ifile->str != NULL) {
449 return (TAILQ_EMPTY(&includes) ? DONE : CONTINUE);
453 *---------------------------------------------------------------------
455 * Link the parent nodes to their new child. Used by
456 * ParseDoDependency. If the specType isn't 'Not', the parent
457 * isn't linked as a parent of the child.
460 * New elements are added to the parents lists of cgn and the
461 * children list of cgn. the unmade field of pgn is updated
462 * to reflect the additional child.
463 *---------------------------------------------------------------------
466 ParseLinkSrc(Lst *parents, GNode *cgn)
471 LST_FOREACH(ln, parents) {
473 if (Lst_Member(&pgn->children, cgn) == NULL) {
474 Lst_AtEnd(&pgn->children, cgn);
475 if (specType == Not) {
476 Lst_AtEnd(&cgn->parents, pgn);
484 *---------------------------------------------------------------------
486 * Apply the parsed operator to all target nodes. Used in
487 * ParseDoDependency once all targets have been found and their
488 * operator parsed. If the previous and new operators are incompatible,
489 * a major error is taken.
492 * The type field of the node is altered to reflect any new bits in
494 *---------------------------------------------------------------------
503 LST_FOREACH(ln, &targets) {
507 * If the dependency mask of the operator and the node don't
508 * match and the node has actually had an operator applied to
509 * it before, and the operator actually has some dependency
510 * information in it, complain.
512 if ((op & OP_OPMASK) != (gn->type & OP_OPMASK) &&
513 !OP_NOP(gn->type) && !OP_NOP(op)) {
514 Parse_Error(PARSE_FATAL, "Inconsistent operator for %s",
519 if (op == OP_DOUBLEDEP &&
520 (gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
522 * If the node was the object of a :: operator, we need
523 * to create a new instance of it for the children and
524 * commands on this dependency line. The new instance
525 * is placed on the 'cohorts' list of the initial one
526 * (note the initial one is not on its own cohorts list)
527 * and the new instance is linked to all parents of the
530 cohort = Targ_NewGN(gn->name);
533 * Duplicate links to parents so graph traversal is
534 * simple. Perhaps some type bits should be duplicated?
536 * Make the cohort invisible as well to avoid
537 * duplicating it into other variables. True, parents
538 * of this target won't tend to do anything with their
539 * local variables, but better safe than sorry.
541 ParseLinkSrc(&gn->parents, cohort);
542 cohort->type = OP_DOUBLEDEP|OP_INVISIBLE;
543 Lst_AtEnd(&gn->cohorts, cohort);
546 * Replace the node in the targets list with the
549 Lst_Replace(ln, cohort);
553 * We don't want to nuke any previous flags (whatever they were)
554 * so we just OR the new operator into the old
561 *---------------------------------------------------------------------
563 * Given the name of a source, figure out if it is an attribute
564 * and apply it to the targets if it is. Else decide if there is
565 * some attribute which should be applied *to* the source because
566 * of some special target and apply it if so. Otherwise, make the
567 * source be a child of the targets in the list 'targets'
573 * Operator bits may be added to the list of targets or to the source.
574 * The targets may have a new source added to their lists of children.
575 *---------------------------------------------------------------------
578 ParseDoSrc(int tOp, char *src, Lst *allsrc)
582 if (*src == '.' && isupper ((unsigned char) src[1])) {
583 int keywd = ParseFindKeyword(src);
585 if(parseKeywords[keywd].op != 0) {
586 ParseDoOp(parseKeywords[keywd].op);
589 if (parseKeywords[keywd].spec == Wait) {
599 * If we have noted the existence of a .MAIN, it means we need
600 * to add the sources of said target to the list of things
601 * to create. The string 'src' is likely to be free, so we
602 * must make a new copy of it. Note that this will only be
603 * invoked if the user didn't specify a target on the command
604 * line. This is to allow #ifmake's to succeed, or something...
606 Lst_AtEnd(&create, estrdup(src));
608 * Add the name to the .TARGETS variable as well, so the user
609 * can employ that, if desired.
611 Var_Append(".TARGETS", src, VAR_GLOBAL);
616 * Create proper predecessor/successor links between the
617 * previous source and the current one.
619 gn = Targ_FindNode(src, TARG_CREATE);
620 if (predecessor != NULL) {
621 Lst_AtEnd(&predecessor->successors, gn);
622 Lst_AtEnd(&gn->preds, predecessor);
625 * The current source now becomes the predecessor for the next
633 * If the source is not an attribute, we need to find/create
634 * a node for it. After that we can apply any operator to it
635 * from a special target or link it to its parents, as
638 * In the case of a source that was the object of a :: operator,
639 * the attribute is applied to all of its instances (as kept in
640 * the 'cohorts' list of the node) or all the cohorts are linked
641 * to all the targets.
643 gn = Targ_FindNode(src, TARG_CREATE);
647 ParseLinkSrc(&targets, gn);
649 if ((gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
653 for (ln = Lst_First(&gn->cohorts); ln != NULL;
655 cohort = Lst_Datum(ln);
659 ParseLinkSrc(&targets, cohort);
667 Lst_AtEnd(allsrc, gn);
673 * Check if GNodes needs to be synchronized.
674 * This has to be when two nodes are on different sides of a
677 LST_FOREACH(ln, allsrc) {
680 if (p->order >= gn->order)
683 * XXX: This can cause loops, and loops can cause
684 * unmade targets, but checking is tedious, and the
685 * debugging output can show the problem
687 Lst_AtEnd(&p->successors, gn);
688 Lst_AtEnd(&gn->preds, p);
695 *---------------------------------------------------------------------
696 * ParseDoDependency --
697 * Parse the dependency line in line.
703 * The nodes of the sources are linked as children to the nodes of the
704 * targets. Some nodes may be created.
706 * We parse a dependency line by first extracting words from the line and
707 * finding nodes in the list of all targets with that name. This is done
708 * until a character is encountered which is an operator character. Currently
709 * these are only ! and :. At this point the operator is parsed and the
710 * pointer into the line advanced until the first source is encountered.
711 * The parsed operator is applied to each node in the 'targets' list,
712 * which is where the nodes found for the targets are kept, by means of
713 * the ParseDoOp function.
714 * The sources are read in much the same way as the targets were except
715 * that now they are expanded using the wildcarding scheme of the C-Shell
716 * and all instances of the resulting words in the list of all targets
717 * are found. Each of the resulting nodes is then linked to each of the
718 * targets as one of its children.
719 * Certain targets are handled specially. These are the ones detailed
720 * by the specType variable.
721 * The storing of transformation rules is also taken care of here.
722 * A target is recognized as a transformation rule by calling
723 * Suff_IsTransform. If it is a transformation rule, its node is gotten
724 * from the suffix module via Suff_AddTransform rather than the standard
725 * Targ_FindNode in the target module.
726 *---------------------------------------------------------------------
729 ParseDoDependency(char *line)
731 char *cp; /* our current position */
732 GNode *gn; /* a general purpose temporary node */
733 int op; /* the operator on the line */
734 char savec; /* a place to save a character */
735 Lst paths; /* Search paths to alter when parsing .PATH targets */
736 int tOp; /* operator from special target */
747 *cp && !isspace((unsigned char)*cp) && *cp != '(';
751 * Must be a dynamic source (would have been
752 * expanded otherwise), so call the Var module
753 * to parse the puppy so we can safely advance
754 * beyond it...There should be no errors in this
755 * as they would have been discovered in the
756 * initial Var_Subst and we wouldn't be here.
762 result = Var_Parse(cp, VAR_CMD, TRUE,
770 } else if (*cp == '!' || *cp == ':') {
772 * We don't want to end a word on ':' or '!' if
773 * there is a better match later on in the
774 * string (greedy matching).
775 * This allows the user to have targets like:
778 * where "fie::fi:fo" and "foo::bar" are the
779 * targets. In real life this is used for perl5
780 * library man pages where "::" separates an
781 * object from its class. Ie:
782 * "File::Spec::Unix". This behaviour is also
783 * consistent with other versions of make.
787 if (*cp == ':' && *p == ':')
790 /* Found the best match already. */
791 if (*p == '\0' || isspace(*p))
794 p += strcspn(p, "!:");
796 /* No better match later on... */
804 * Archives must be handled specially to make sure the
805 * OP_ARCHV flag is set in their 'type' field, for one
806 * thing, and because things like "archive(file1.o
807 * file2.o file3.o)" are permissible. Arch_ParseArchive
808 * will set 'line' to be the first non-blank after the
809 * archive-spec. It creates/finds nodes for the members
810 * and places them on the given list, returning SUCCESS
811 * if all went well and FAILURE if there was an error in
812 * the specification. On error, line should remain
815 if (Arch_ParseArchive(&line, &targets, VAR_CMD) !=
817 Parse_Error(PARSE_FATAL,
818 "Error in archive specification: \"%s\"",
830 * Ending a dependency line without an operator is a * Bozo no-no. As a heuristic, this is also often
831 * triggered by undetected conflicts from cvs/rcs
834 if (strncmp(line, "<<<<<<", 6) == 0 ||
835 strncmp(line, "======", 6) == 0 ||
836 strncmp(line, ">>>>>>", 6) == 0) {
837 Parse_Error(PARSE_FATAL, "Makefile appears to "
838 "contain unresolved cvs/rcs/??? merge "
841 Parse_Error(PARSE_FATAL, "Need an operator");
846 * Have a word in line. See if it's a special target and set
847 * specType to match it.
849 if (*line == '.' && isupper((unsigned char)line[1])) {
851 * See if the target is a special target that must have
852 * it or its sources handled specially.
854 int keywd = ParseFindKeyword(line);
857 if (specType == ExPath &&
858 parseKeywords[keywd].spec != ExPath) {
859 Parse_Error(PARSE_FATAL,
860 "Mismatched special targets");
864 specType = parseKeywords[keywd].spec;
865 tOp = parseKeywords[keywd].op;
868 * Certain special targets have special
870 * .PATH Have to set the dirSearchPath
872 * .MAIN Its sources are only used if
873 * nothing has been specified to
875 * .DEFAULT Need to create a node to hang
876 * commands on, but we don't want
877 * it in the graph, nor do we want
878 * it to be the Main Target, so we
879 * create it, set OP_NOTMAIN and
880 * add it to the list, setting
881 * DEFAULT to the new node for
882 * later use. We claim the node is
883 * A transformation rule to make
884 * life easier later, when we'll
885 * use Make_HandleUse to actually
886 * apply the .DEFAULT commands.
887 * .PHONY The list of targets
890 * .INTERRUPT Are not to be considered the
892 * .NOTPARALLEL Make only one target at a time.
893 * .SINGLESHELL Create a shell for each
895 * .ORDER Must set initial predecessor
900 Lst_AtEnd(&paths, &dirSearchPath);
903 if (!Lst_IsEmpty(&create)) {
910 gn = Targ_FindNode(line, TARG_CREATE);
911 gn->type |= OP_NOTMAIN;
912 Lst_AtEnd(&targets, gn);
915 gn = Targ_NewGN(".DEFAULT");
916 gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
917 Lst_AtEnd(&targets, gn);
933 } else if (strncmp(line, ".PATH", 5) == 0) {
935 * .PATH<suffix> has to be handled specially.
936 * Call on the suffix module to give us a path
942 path = Suff_GetPath(&line[5]);
944 Parse_Error(PARSE_FATAL, "Suffix '%s' "
945 "not defined (yet)", &line[5]);
948 Lst_AtEnd(&paths, path);
953 * Have word in line. Get or create its node and stick it at
954 * the end of the targets list
956 if (specType == Not && *line != '\0') {
958 /* target names to be found and added to targets list */
959 Lst curTargs = Lst_Initializer(curTargs);
961 if (Dir_HasWildcards(line)) {
963 * Targets are to be sought only in the current
964 * directory, so create an empty path for the
965 * thing. Note we need to use Path_Clear in the
966 * destruction of the path as the Dir module
967 * could have added a directory to the path...
969 struct Path emptyPath =
970 TAILQ_HEAD_INITIALIZER(emptyPath);
972 Path_Expand(line, &emptyPath, &curTargs);
973 Path_Clear(&emptyPath);
977 * No wildcards, but we want to avoid code
978 * duplication, so create a list with the word
981 Lst_AtEnd(&curTargs, line);
984 while (!Lst_IsEmpty(&curTargs)) {
985 char *targName = Lst_DeQueue(&curTargs);
987 if (!Suff_IsTransform (targName)) {
988 gn = Targ_FindNode(targName,
991 gn = Suff_AddTransform(targName);
994 Lst_AtEnd(&targets, gn);
996 } else if (specType == ExPath && *line != '.' && *line != '\0'){
997 Parse_Error(PARSE_WARNING, "Extra target (%s) ignored",
1003 * If it is a special type and not .PATH, it's the only
1004 * target we allow on this line...
1006 if (specType != Not && specType != ExPath) {
1007 Boolean warnFlag = FALSE;
1009 while (*cp != '!' && *cp != ':' && *cp) {
1010 if (*cp != ' ' && *cp != '\t') {
1016 Parse_Error(PARSE_WARNING,
1017 "Extra target ignored");
1020 while (*cp && isspace((unsigned char)*cp)) {
1025 } while (*line != '!' && *line != ':' && *line);
1027 if (!Lst_IsEmpty(&targets)) {
1030 Parse_Error(PARSE_WARNING, "Special and mundane "
1031 "targets don't mix. Mundane ones ignored");
1038 * These four create nodes on which to hang commands, so
1039 * targets shouldn't be empty...
1043 * Nothing special here -- targets can be empty if it
1051 * Have now parsed all the target names. Must parse the operator next.
1052 * The result is left in op.
1056 } else if (*cp == ':') {
1064 Parse_Error(PARSE_FATAL, "Missing dependency operator");
1068 cp++; /* Advance beyond operator */
1073 * Get to the first source
1075 while (*cp && isspace((unsigned char)*cp)) {
1081 * Several special targets take different actions if present with no
1083 * a .SUFFIXES line with no sources clears out all old suffixes
1084 * a .PRECIOUS line makes all targets precious
1085 * a .IGNORE line ignores errors for all targets
1086 * a .SILENT line creates silence when making all targets
1087 * a .PATH removes all directories from the search path(s).
1092 Suff_ClearSuffixes();
1098 ignoreErrors = TRUE;
1104 LST_FOREACH(ln, &paths)
1105 Path_Clear(Lst_Datum(ln));
1108 Var_Set("%POSIX", "1003.2", VAR_GLOBAL);
1114 } else if (specType == MFlags) {
1116 * Call on functions in main.c to deal with these arguments and
1117 * set the initial character to a null-character so the loop to
1118 * get sources won't get anything
1120 Main_ParseArgLine(line, 0);
1123 } else if (specType == ExShell) {
1124 if (Job_ParseShell(line) != SUCCESS) {
1125 Parse_Error(PARSE_FATAL,
1126 "improper shell specification");
1131 } else if (specType == NotParallel || specType == SingleShell) {
1136 * NOW GO FOR THE SOURCES
1138 if (specType == Suffixes || specType == ExPath ||
1139 specType == Includes || specType == Libs ||
1143 * If the target was one that doesn't take files as its
1144 * sources but takes something like suffixes, we take
1145 * each space-separated word on the line as a something
1146 * and deal with it accordingly.
1148 * If the target was .SUFFIXES, we take each source as
1149 * a suffix and add it to the list of suffixes
1150 * maintained by the Suff module.
1152 * If the target was a .PATH, we add the source as a
1153 * directory to search on the search path.
1155 * If it was .INCLUDES, the source is taken to be the
1156 * suffix of files which will be #included and whose
1157 * search path should be present in the .INCLUDES
1160 * If it was .LIBS, the source is taken to be the
1161 * suffix of files which are considered libraries and
1162 * whose search path should be present in the .LIBS
1165 * If it was .NULL, the source is the suffix to use
1166 * when a file has no valid suffix.
1169 while (*cp && !isspace((unsigned char)*cp)) {
1176 Suff_AddSuffix(line);
1179 LST_FOREACH(ln, &paths)
1180 Path_AddDir(Lst_Datum(ln), line);
1183 Suff_AddInclude(line);
1195 if (savech != '\0') {
1198 while (*cp && isspace((unsigned char)*cp)) {
1203 Lst_Destroy(&paths, NOFREE);
1205 } else if (specType == Export) {
1206 Var_SetEnv(line, VAR_GLOBAL);
1209 /* list of sources in order */
1210 Lst curSrcs = Lst_Initializer(curSrc);
1214 * The targets take real sources, so we must beware of
1215 * archive specifications (i.e. things with left
1216 * parentheses in them) and handle them accordingly.
1218 while (*cp && !isspace((unsigned char)*cp)) {
1219 if (*cp == '(' && cp > line && cp[-1] != '$') {
1221 * Only stop for a left parenthesis if
1222 * it isn't at the start of a word
1223 * (that'll be for variable changes
1224 * later) and isn't preceded by a dollar
1225 * sign (a dynamic source).
1236 /* list of archive source names after exp. */
1237 Lst sources = Lst_Initializer(sources);
1239 if (Arch_ParseArchive(&line, &sources,
1240 VAR_CMD) != SUCCESS) {
1241 Parse_Error(PARSE_FATAL, "Error in "
1242 "source archive spec \"%s\"", line);
1246 while (!Lst_IsEmpty(&sources)) {
1247 gnp = Lst_DeQueue(&sources);
1248 ParseDoSrc(tOp, gnp->name, &curSrcs);
1257 ParseDoSrc(tOp, line, &curSrcs);
1259 while (*cp && isspace((unsigned char)*cp)) {
1264 Lst_Destroy(&curSrcs, NOFREE);
1267 if (mainNode == NULL) {
1269 * If we have yet to decide on a main target to make, in the
1270 * absence of any user input, we want the first target on
1271 * the first dependency line that is actually a real target
1272 * (i.e. isn't a .USE or .EXEC rule) to be made.
1274 LST_FOREACH(ln, &targets) {
1276 if ((gn->type & (OP_NOTMAIN | OP_USE |
1277 OP_EXEC | OP_TRANSFORM)) == 0) {
1287 *---------------------------------------------------------------------
1289 * Return TRUE if the passed line is a variable assignment. A variable
1290 * assignment consists of a single word followed by optional whitespace
1291 * followed by either a += or an = operator.
1292 * This function is used both by the Parse_File function and main when
1293 * parsing the command-line arguments.
1296 * TRUE if it is. FALSE if it ain't
1300 *---------------------------------------------------------------------
1303 Parse_IsVar(char *line)
1305 Boolean wasSpace = FALSE; /* set TRUE if found a space */
1306 Boolean haveName = FALSE; /* Set TRUE if have a variable name */
1309 #define ISEQOPERATOR(c) \
1310 ((c) == '+' || (c) == ':' || (c) == '?' || (c) == '!')
1313 * Skip to variable name
1315 for (; *line == ' ' || *line == '\t'; line++)
1318 for (; *line != '=' || level != 0; line++) {
1322 * end-of-line -- can't be a variable assignment.
1329 * there can be as much white space as desired so long
1330 * as there is only one word before the operator
1346 if (wasSpace && haveName) {
1347 if (ISEQOPERATOR(*line)) {
1349 * We must have a finished word
1355 * When an = operator [+?!:] is found,
1356 * the next character must be an = or
1357 * it ain't a valid assignment.
1363 * This is a shell command
1365 if (strncmp(line, ":sh", 3) == 0)
1370 * This is the start of another word, so not
1387 *---------------------------------------------------------------------
1389 * Take the variable assignment in the passed line and do it in the
1392 * Note: There is a lexical ambiguity with assignment modifier characters
1393 * in variable names. This routine interprets the character before the =
1394 * as a modifier. Therefore, an assignment like
1396 * is interpreted as "C+ +=" instead of "C++ =".
1402 * the variable structure of the given variable name is altered in the
1404 *---------------------------------------------------------------------
1407 Parse_DoVar(char *line, GNode *ctxt)
1409 char *cp; /* pointer into line */
1415 } type; /* Type of assignment */
1416 char *opc; /* ptr to operator character to
1417 * null-terminate the variable name */
1420 * Avoid clobbered variable warnings by forcing the compiler
1421 * to ``unregister'' variables
1429 * Skip to variable name
1431 while (*line == ' ' || *line == '\t') {
1436 * Skip to operator character, nulling out whitespace as we go
1438 for (cp = line + 1; *cp != '='; cp++) {
1439 if (isspace((unsigned char)*cp)) {
1443 opc = cp - 1; /* operator is the previous character */
1444 *cp++ = '\0'; /* nuke the = */
1447 * Check operator type
1457 * If the variable already has a value, we don't do anything.
1460 if (Var_Exists(line, ctxt)) {
1479 while (*opc != ':') {
1486 if (strncmp(opc, ":sh", 3) == 0) {
1496 while (isspace((unsigned char)*cp)) {
1500 if (type == VAR_APPEND) {
1501 Var_Append(line, cp, ctxt);
1503 } else if (type == VAR_SUBST) {
1505 * Allow variables in the old value to be undefined, but leave
1506 * their invocation alone -- this is done by forcing oldVars
1508 * XXX: This can cause recursive variables, but that's not
1509 * hard to do, and this allows someone to do something like
1511 * CFLAGS = $(.INCLUDES)
1512 * CFLAGS := -I.. $(CFLAGS)
1514 * And not get an error.
1516 Boolean oldOldVars = oldVars;
1521 * make sure that we set the variable the first time to nothing
1522 * so that it gets substituted!
1524 if (!Var_Exists(line, ctxt))
1525 Var_Set(line, "", ctxt);
1527 cp = Buf_Peel(Var_Subst(NULL, cp, ctxt, FALSE));
1529 oldVars = oldOldVars;
1531 Var_Set(line, cp, ctxt);
1534 } else if (type == VAR_SHELL) {
1536 * TRUE if the command needs to be freed, i.e.
1537 * if any variable expansion was performed
1539 Boolean freeCmd = FALSE;
1543 if (strchr(cp, '$') != NULL) {
1545 * There's a dollar sign in the command, so perform
1546 * variable expansion on the whole thing. The
1547 * resulting string will need freeing when we're done,
1548 * so set freeCmd to TRUE.
1550 cp = Buf_Peel(Var_Subst(NULL, cp, VAR_CMD, TRUE));
1554 buf = Cmd_Exec(cp, &error);
1555 Var_Set(line, Buf_Data(buf), ctxt);
1556 Buf_Destroy(buf, TRUE);
1559 Parse_Error(PARSE_WARNING, error, cp);
1566 * Normal assignment -- just do it.
1568 Var_Set(line, cp, ctxt);
1573 *-----------------------------------------------------------------------
1574 * ParseHasCommands --
1575 * Callback procedure for Parse_File when destroying the list of
1576 * targets on the last dependency line. Marks a target as already
1577 * having commands if it does, to keep from having shell commands
1578 * on multiple dependency lines.
1584 * OP_HAS_COMMANDS may be set for the target.
1586 *-----------------------------------------------------------------------
1589 ParseHasCommands(void *gnp)
1593 if (!Lst_IsEmpty(&gn->commands)) {
1594 gn->type |= OP_HAS_COMMANDS;
1599 *-----------------------------------------------------------------------
1600 * Parse_AddIncludeDir --
1601 * Add a directory to the path searched for included makefiles
1602 * bracketed by double-quotes. Used by functions in main.c
1608 * The directory is appended to the list.
1610 *-----------------------------------------------------------------------
1613 Parse_AddIncludeDir(char *dir)
1616 Path_AddDir(&parseIncPath, dir);
1620 *---------------------------------------------------------------------
1621 * Parse_FromString --
1622 * Start Parsing from the given string
1628 * A structure is added to the includes Lst and readProc, curFile.lineno,
1629 * curFile.fname and curFile.F are altered for the new file
1630 *---------------------------------------------------------------------
1633 Parse_FromString(char *str, int lineno)
1636 DEBUGF(FOR, ("%s\n---- at line %d\n", str, lineno));
1638 ParsePushInput(estrdup(CURFILE->fname), NULL, str, lineno);
1643 *---------------------------------------------------------------------
1644 * ParseTraditionalInclude --
1645 * Push to another file.
1647 * The input is the line minus the "include". The file name is
1648 * the string following the "include".
1654 * A structure is added to the includes Lst and readProc, curFile.lineno,
1655 * curFile.fname and curFile.F are altered for the new file
1656 *---------------------------------------------------------------------
1659 ParseTraditionalInclude(char *file)
1661 char *fullname; /* full pathname of file */
1662 char *cp; /* current position in file spec */
1665 * Skip over whitespace
1667 while (*file == ' ' || *file == '\t') {
1671 if (*file == '\0') {
1672 Parse_Error(PARSE_FATAL, "Filename missing from \"include\"");
1677 * Skip to end of line or next whitespace
1679 for (cp = file; *cp && *cp != '\n' && *cp != '\t' && *cp != ' '; cp++) {
1686 * Substitute for any variables in the file name before trying to
1689 file = Buf_Peel(Var_Subst(NULL, file, VAR_CMD, FALSE));
1692 * Now we know the file's name, we attempt to find the durn thing.
1693 * Search for it first on the -I search path, then on the .PATH
1694 * search path, if not found in a -I directory.
1696 fullname = Path_FindFile(file, &parseIncPath);
1697 if (fullname == NULL) {
1698 fullname = Path_FindFile(file, &dirSearchPath);
1701 if (fullname == NULL) {
1703 * Still haven't found the makefile. Look for it on the system
1704 * path as a last resort.
1706 fullname = Path_FindFile(file, &sysIncPath);
1709 if (fullname == NULL) {
1710 Parse_Error(PARSE_FATAL, "Could not find %s", file);
1711 /* XXXHB free(file) */
1715 /* XXXHB free(file) */
1718 * We set up the name of the file to be the absolute
1719 * name of the include file so error messages refer to the right
1722 ParsePushInput(fullname, NULL, NULL, 0);
1727 *---------------------------------------------------------------------
1729 * Read a character from the current file
1732 * The character that was read
1735 *---------------------------------------------------------------------
1741 if (CURFILE->F != NULL)
1742 return (fgetc(CURFILE->F));
1744 if (CURFILE->str != NULL && *CURFILE->ptr != '\0')
1745 return (*CURFILE->ptr++);
1752 *---------------------------------------------------------------------
1754 * Put back a character to the current file
1760 *---------------------------------------------------------------------
1766 if (CURFILE->F != NULL) {
1767 ungetc(c, CURFILE->F);
1770 if (CURFILE->str != NULL) {
1771 *--(CURFILE->ptr) = c;
1777 * Grab the next line unless it begins with a dot (`.') and we're told to
1778 * ignore such lines.
1781 ParseSkipLine(int skip, int keep_newline)
1787 buf = Buf_Init(MAKE_BSIZE);
1793 while (((c = ParseReadc()) != '\n' || lastc == '\\')
1795 if (skip && c == '#' && lastc != '\\') {
1797 * let a comment be terminated even by an
1798 * escaped \n. This is consistent to comment
1799 * handling in ParseReadLine
1801 while ((c = ParseReadc()) != '\n' && c != EOF)
1807 Buf_AddByte(buf, (Byte)c);
1809 Buf_ReplaceLastByte(buf, (Byte)' ');
1812 while ((c = ParseReadc()) == ' ' || c == '\t')
1819 Buf_AddByte(buf, (Byte)c);
1824 Parse_Error(PARSE_FATAL,
1825 "Unclosed conditional/for loop");
1826 Buf_Destroy(buf, TRUE);
1831 Buf_AddByte(buf, (Byte)'\0');
1832 line = Buf_Data(buf);
1833 } while (skip == 1 && line[0] != '.');
1835 Buf_Destroy(buf, FALSE);
1840 *---------------------------------------------------------------------
1842 * Read an entire line from the input file. Called only by Parse_File.
1843 * To facilitate escaped newlines and what have you, a character is
1844 * buffered in 'lastc', which is '\0' when no characters have been
1845 * read. When we break out of the loop, c holds the terminating
1846 * character and lastc holds a character that should be added to
1847 * the line (unless we don't read anything but a terminator).
1850 * A line w/o its newline
1853 * Only those associated with reading a character
1854 *---------------------------------------------------------------------
1859 Buffer *buf; /* Buffer for current line */
1860 int c; /* the current character */
1861 int lastc; /* The most-recent character */
1862 Boolean semiNL; /* treat semi-colons as newlines */
1863 Boolean ignDepOp; /* TRUE if should ignore dependency operators
1864 * for the purposes of setting semiNL */
1865 Boolean ignComment; /* TRUE if should ignore comments (in a
1867 char *line; /* Result */
1868 char *ep; /* to strip trailing blanks */
1878 * Handle tab at the beginning of the line. A leading tab (shell
1879 * command) forces us to ignore comments and dependency operators and
1880 * treat semi-colons as semi-colons (by leaving semiNL FALSE).
1881 * This also discards completely blank lines.
1886 if (ParsePopInput() == DONE) {
1887 /* End of all inputs - return NULL */
1894 ignComment = ignDepOp = TRUE;
1905 buf = Buf_Init(MAKE_BSIZE);
1907 while (((c = ParseReadc()) != '\n' || lastc == '\\') && c != EOF) {
1912 * Escaped newline: read characters until a
1913 * non-space or an unescaped newline and
1914 * replace them all by a single space. This is
1915 * done by storing the space over the backslash
1916 * and dropping through with the next nonspace.
1917 * If it is a semi-colon and semiNL is TRUE,
1918 * it will be recognized as a newline in the
1919 * code below this...
1923 while ((c = ParseReadc()) == ' ' || c == '\t') {
1926 if (c == EOF || c == '\n') {
1930 * Check for comments, semiNL's, etc. --
1931 * easier than ParseUnreadc(c);
1941 * Semi-colon: Need to see if it should be
1942 * interpreted as a newline
1946 * To make sure the command that may
1947 * be following this semi-colon begins
1948 * with a tab, we push one back into the
1949 * input stream. This will overwrite the
1950 * semi-colon in the buffer. If there is
1951 * no command following, this does no
1952 * harm, since the newline remains in
1953 * the buffer and the
1954 * whole line is ignored.
1963 * Haven't seen a dependency operator
1964 * before this, so this must be a
1965 * variable assignment -- don't pay
1966 * attention to dependency operators
1970 } else if (lastc == ':' || lastc == '!') {
1972 * Well, we've seen a dependency
1973 * operator already, but it was the
1974 * previous character, so this is really
1975 * just an expanded variable assignment.
1976 * Revert semi-colons to being just
1977 * semi-colons again and ignore any more
1978 * dependency operators.
1980 * XXX: Note that a line like
1981 * "foo : a:=b" will blow up, but who'd
1982 * write a line like that anyway?
1990 if (lastc != '\\') {
1992 * If the character is a hash
1993 * mark and it isn't escaped
1994 * (or we're being compatible),
1995 * the thing is a comment.
1996 * Skip to the end of the line.
2000 } while (c != '\n' && c != EOF);
2004 * Don't add the backslash.
2005 * Just let the # get copied
2018 * A semi-colon is recognized as a
2019 * newline only on dependency lines.
2020 * Dependency lines are lines with a
2021 * colon or an exclamation point.
2032 * Copy in the previous character (there may be none if this
2033 * was the first character) and save this one in
2037 Buf_AddByte(buf, (Byte)lastc);
2043 if (lastc != '\0') {
2044 Buf_AddByte(buf, (Byte)lastc);
2046 Buf_AddByte(buf, (Byte)'\0');
2047 line = Buf_Peel(buf);
2050 * Strip trailing blanks and tabs from the line.
2051 * Do not strip a blank or tab that is preceded by
2057 while (ep > line + 1 && (ep[-1] == ' ' || ep[-1] == '\t')) {
2058 if (ep > line + 1 && ep[-2] == '\\')
2064 if (line[0] == '\0') {
2065 /* empty line - just ignore */
2074 *-----------------------------------------------------------------------
2075 * ParseFinishLine --
2076 * Handle the end of a dependency group.
2082 * inLine set FALSE. 'targets' list destroyed.
2084 *-----------------------------------------------------------------------
2087 ParseFinishLine(void)
2092 LST_FOREACH(ln, &targets) {
2093 if (((const GNode *)Lst_Datum(ln))->type & OP_TRANSFORM)
2094 Suff_EndTransform(Lst_Datum(ln));
2096 Lst_Destroy(&targets, ParseHasCommands);
2103 * Parse an .include directive and push the file onto the input stack.
2104 * The input is the line minus the .include. A file spec is a string
2105 * enclosed in <> or "". The former is looked for only in sysIncPath.
2106 * The latter in . and the directories specified by -I command line
2110 parse_include(char *file, int code __unused, int lineno __unused)
2112 char *fullname; /* full pathname of file */
2113 char endc; /* the character which ends the file spec */
2114 char *cp; /* current position in file spec */
2115 Boolean isSystem; /* TRUE if makefile is a system makefile */
2116 char *prefEnd, *Fname;
2120 * Skip to delimiter character so we know where to look
2122 while (*file == ' ' || *file == '\t') {
2126 if (*file != '"' && *file != '<') {
2127 Parse_Error(PARSE_FATAL,
2128 ".include filename must be delimited by '\"' or '<'");
2133 * Set the search path on which to find the include file based on the
2134 * characters which bracket its name. Angle-brackets imply it's
2135 * a system Makefile while double-quotes imply it's a user makefile
2146 * Skip to matching delimiter
2148 for (cp = ++file; *cp != endc; cp++) {
2150 Parse_Error(PARSE_FATAL,
2151 "Unclosed .include filename. '%c' expected", endc);
2158 * Substitute for any variables in the file name before trying to
2161 file = Buf_Peel(Var_Subst(NULL, file, VAR_CMD, FALSE));
2164 * Now we know the file's name and its search path, we attempt to
2165 * find the durn thing. A return of NULL indicates the file don't
2170 * Include files contained in double-quotes are first searched
2171 * for relative to the including file's location. We don't want
2172 * to cd there, of course, so we just tack on the old file's
2173 * leading path components and call Dir_FindFile to see if
2174 * we can locate the beast.
2177 /* Make a temporary copy of this, to be safe. */
2178 Fname = estrdup(CURFILE->fname);
2180 prefEnd = strrchr(Fname, '/');
2181 if (prefEnd != NULL) {
2184 newName = estrdup(file);
2186 newName = str_concat(Fname, file, STR_ADDSLASH);
2187 fullname = Path_FindFile(newName, &parseIncPath);
2188 if (fullname == NULL) {
2189 fullname = Path_FindFile(newName,
2202 if (fullname == NULL) {
2204 * System makefile or makefile wasn't found in same directory as
2205 * included makefile. Search for it first on the -I search path,
2206 * then on the .PATH search path, if not found in a -I
2208 * XXX: Suffix specific?
2210 fullname = Path_FindFile(file, &parseIncPath);
2211 if (fullname == NULL) {
2212 fullname = Path_FindFile(file, &dirSearchPath);
2216 if (fullname == NULL) {
2218 * Still haven't found the makefile. Look for it on the system
2219 * path as a last resort.
2221 fullname = Path_FindFile(file, &sysIncPath);
2224 if (fullname == NULL) {
2226 Parse_Error(PARSE_FATAL, "Could not find %s", file);
2233 * We set up the name of the file to be the absolute
2234 * name of the include file so error messages refer to the right
2237 ParsePushInput(fullname, NULL, NULL, 0);
2242 * Parse a .warning or .error directive
2244 * The input is the line minus the ".error"/".warning". We substitute
2245 * variables, print the message and exit(1) (for .error) or just print
2246 * a warning if the directive is malformed.
2249 parse_message(char *line, int iserror, int lineno __unused)
2252 if (!isspace((u_char)*line)) {
2253 Parse_Error(PARSE_WARNING, "invalid syntax: .%s%s",
2254 iserror ? "error" : "warning", line);
2258 while (isspace((u_char)*line))
2261 line = Buf_Peel(Var_Subst(NULL, line, VAR_GLOBAL, FALSE));
2262 Parse_Error(iserror ? PARSE_FATAL : PARSE_WARNING, "%s", line);
2266 /* Terminate immediately. */
2273 * Parse an .undef directive.
2276 parse_undef(char *line, int code __unused, int lineno __unused)
2280 while (isspace((u_char)*line))
2283 for (cp = line; !isspace((u_char)*cp) && *cp != '\0'; cp++) {
2288 cp = Buf_Peel(Var_Subst(NULL, line, VAR_CMD, FALSE));
2289 Var_Delete(cp, VAR_GLOBAL);
2295 * Parse a .for directive.
2298 parse_for(char *line, int code __unused, int lineno)
2301 if (!For_For(line)) {
2308 * Skip after the matching endfor.
2312 line = ParseSkipLine(0, 1);
2314 Parse_Error(PARSE_FATAL,
2315 "Unexpected end of file in for loop.\n");
2318 } while (For_Eval(line));
2327 * Parse endfor. This may only happen if there was no matching .for.
2330 parse_endfor(char *line __unused, int code __unused, int lineno __unused)
2333 Parse_Error(PARSE_FATAL, "for-less endfor");
2340 directive_hash(const u_char *key, size_t len)
2343 const u_char *kp = key;
2345 if (len < 2 || len > 9)
2348 for (f0 = f1 = 0; kp < key + len; ++kp) {
2349 if (*kp < 97 || *kp > 119)
2351 f0 += directive_T0[-97 + *kp];
2352 f1 += directive_T1[-97 + *kp];
2358 return (directive_g[f0] + directive_g[f1]) % 18;
2363 * Got a line starting with a '.'. Check if this is a directive
2367 * TRUE if line was a directive, FALSE otherwise.
2370 parse_directive(char *line)
2378 * .[[:space:]]*\([[:alpha:]][[:alnum:]_]*\).*
2379 * \1 is the keyword.
2381 for (start = line; isspace((u_char)*start); start++) {
2385 if (!isalpha((u_char)*start)) {
2390 while (isalnum((u_char)*cp) || *cp == '_') {
2394 dir = directive_hash(start, cp - start);
2395 if (dir < 0 || dir >= (int)NDIRECTS ||
2396 (size_t)(cp - start) != strlen(directives[dir].name) ||
2397 strncmp(start, directives[dir].name, cp - start) != 0) {
2398 /* not actually matched */
2402 if (!skipLine || directives[dir].skip_flag)
2403 (*directives[dir].func)(cp, directives[dir].code,
2409 *---------------------------------------------------------------------
2411 * Parse a file into its component parts, incorporating it into the
2412 * current dependency graph. This is the main function and controls
2413 * almost every other function in this module
2419 * Loads. Nodes are added to the list of all targets, nodes and links
2420 * are added to the dependency graph. etc. etc. etc.
2421 *---------------------------------------------------------------------
2424 Parse_File(const char *name, FILE *stream)
2426 char *cp; /* pointer into the line */
2427 char *line; /* the line we're working on */
2432 ParsePushInput(estrdup(name), stream, NULL, 0);
2434 while ((line = ParseReadLine()) != NULL) {
2435 if (*line == '.' && parse_directive(line + 1)) {
2436 /* directive consumed */
2439 if (skipLine || *line == '#') {
2440 /* Skipping .if block or comment. */
2444 if (*line == '\t') {
2446 * If a line starts with a tab, it can only
2447 * hope to be a creation command.
2449 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2458 * So long as it's not a blank
2459 * line and we're actually in a
2460 * dependency spec, add the
2461 * command to the list of
2462 * commands of all targets in
2463 * the dependency spec.
2465 LST_FOREACH(ln, &targets) {
2473 if (!(gn->type & OP_HAS_COMMANDS))
2474 Lst_AtEnd(&gn->commands, cp);
2476 Parse_Error(PARSE_WARNING, "duplicate script "
2477 "for target \"%s\" ignored", gn->name);
2481 Parse_Error(PARSE_FATAL,
2482 "Unassociated shell command \"%s\"",
2487 } else if (strncmp(line, "include", 7) == 0 &&
2488 isspace((unsigned char)line[7]) &&
2489 strchr(line, ':') == NULL) {
2491 * It's an S3/S5-style "include".
2493 ParseTraditionalInclude(line + 7);
2496 } else if (Parse_IsVar(line)) {
2498 Parse_DoVar(line, VAR_GLOBAL);
2502 * We now know it's a dependency line so it
2503 * needs to have all variables expanded before
2504 * being parsed. Tell the variable module to
2505 * complain if some variable is undefined...
2506 * To make life easier on novices, if the line
2507 * is indented we first make sure the line has
2508 * a dependency operator in it. If it doesn't
2509 * have an operator and we're in a dependency
2510 * line's script, we assume it's actually a
2511 * shell command and add it to the current
2512 * list of targets. XXX this comment seems wrong.
2515 if (isspace((unsigned char)line[0])) {
2516 while (*cp != '\0' &&
2517 isspace((unsigned char)*cp)) {
2527 cp = Buf_Peel(Var_Subst(NULL, line, VAR_CMD, TRUE));
2533 * Need a non-circular list for the target nodes
2535 Lst_Destroy(&targets, NOFREE);
2538 ParseDoDependency(line);
2548 * Make sure conditionals are clean
2553 errx(1, "fatal errors encountered -- cannot continue");
2557 *-----------------------------------------------------------------------
2559 * Return a Lst of the main target to create for main()'s sake. If
2560 * no such target exists, we Punt with an obnoxious error message.
2563 * A Lst of the single node to create.
2568 *-----------------------------------------------------------------------
2571 Parse_MainName(Lst *listmain)
2574 if (mainNode == NULL) {
2575 Punt("no target to make.");
2577 } else if (mainNode->type & OP_DOUBLEDEP) {
2578 Lst_AtEnd(listmain, mainNode);
2579 Lst_Concat(listmain, &mainNode->cohorts, LST_CONCNEW);
2581 Lst_AtEnd(listmain, mainNode);