Merge from vendor branch FILE:
[dragonfly.git] / usr.bin / make / parse.c
1 /*
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
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Adam de Boor.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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.
25  *
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
36  * SUCH DAMAGE.
37  *
38  * @(#)parse.c  8.3 (Berkeley) 3/19/94
39  * $FreeBSD: src/usr.bin/make/parse.c,v 1.22.2.2 2004/07/10 08:14:42 eik Exp $
40  * $DragonFly: src/usr.bin/make/parse.c,v 1.28 2004/12/17 21:09:04 okumoto Exp $
41  */
42
43 /*-
44  * parse.c --
45  *      Functions to parse a makefile.
46  *
47  *      One function, Parse_Init, must be called before any functions
48  *      in this module are used. After that, the function Parse_File is the
49  *      main entry point and controls most of the other functions in this
50  *      module.
51  *
52  *      Most important structures are kept in Lsts. Directories for
53  *      the #include "..." function are kept in the 'parseIncPath' Lst, while
54  *      those for the #include <...> are kept in the 'sysIncPath' Lst. The
55  *      targets currently being defined are kept in the 'targets' Lst.
56  *
57  *      The variables 'curFile.fname' and 'curFile.lineno' are used to track
58  *      the name of the current file and the line number in that file so that
59  *      error messages can be more meaningful.
60  *
61  * Interface:
62  *      Parse_Init                  Initialization function which must be
63  *                                  called before anything else in this module
64  *                                  is used.
65  *
66  *      Parse_End                   Cleanup the module
67  *
68  *      Parse_File                  Function used to parse a makefile. It must
69  *                                  be given the name of the file, which should
70  *                                  already have been opened, and a function
71  *                                  to call to read a character from the file.
72  *
73  *      Parse_IsVar                 Returns TRUE if the given line is a
74  *                                  variable assignment. Used by MainParseArgs
75  *                                  to determine if an argument is a target
76  *                                  or a variable assignment. Used internally
77  *                                  for pretty much the same thing...
78  *
79  *      Parse_Error                 Function called when an error occurs in
80  *                                  parsing. Used by the variable and
81  *                                  conditional modules.
82  *      Parse_MainName              Returns a Lst of the main target to create.
83  */
84
85 #include <stdarg.h>
86 #include <ctype.h>
87 #include <err.h>
88 #include <stdio.h>
89 #include "make.h"
90 #include "hash.h"
91 #include "dir.h"
92 #include "job.h"
93 #include "buf.h"
94 #include "pathnames.h"
95
96 /*
97  * These values are returned by ParseEOF to tell Parse_File whether to
98  * CONTINUE parsing, i.e. it had only reached the end of an include file,
99  * or if it's DONE.
100  */
101 #define CONTINUE        1
102 #define DONE            0
103
104 /* targets we're working on */
105 static Lst targets = Lst_Initializer(targets);
106
107 static Boolean      inLine;     /* true if currently in a dependency
108                                  * line or its commands */
109 static int          fatals = 0;
110
111 static GNode        *mainNode;  /* The main target to create. This is the
112                                  * first target on the first dependency
113                                  * line in the first makefile */
114
115 IFile           curFile;        /* current makefile */
116
117 /* stack of IFiles generated by * #includes */
118 static Lst includes = Lst_Initializer(includes);
119
120 /* list of directories for "..." includes */
121 Lst parseIncPath = Lst_Initializer(parseIncPath);
122
123 /* list of directories for <...> includes */
124 Lst sysIncPath = Lst_Initializer(sysIncPath);
125
126 /*-
127  * specType contains the SPECial TYPE of the current target. It is
128  * Not if the target is unspecial. If it *is* special, however, the children
129  * are linked as children of the parent but not vice versa. This variable is
130  * set in ParseDoDependency
131  */
132 typedef enum {
133     Begin,          /* .BEGIN */
134     Default,        /* .DEFAULT */
135     End,            /* .END */
136     Ignore,         /* .IGNORE */
137     Includes,       /* .INCLUDES */
138     Interrupt,      /* .INTERRUPT */
139     Libs,           /* .LIBS */
140     MFlags,         /* .MFLAGS or .MAKEFLAGS */
141     Main,           /* .MAIN and we don't have anything user-specified to
142                      * make */
143     NoExport,       /* .NOEXPORT */
144     Not,            /* Not special */
145     NotParallel,    /* .NOTPARALELL */
146     Null,           /* .NULL */
147     Order,          /* .ORDER */
148     Parallel,       /* .PARALLEL */
149     ExPath,         /* .PATH */
150     Phony,          /* .PHONY */
151     Posix,          /* .POSIX */
152     Precious,       /* .PRECIOUS */
153     ExShell,        /* .SHELL */
154     Silent,         /* .SILENT */
155     SingleShell,    /* .SINGLESHELL */
156     Suffixes,       /* .SUFFIXES */
157     Wait,           /* .WAIT */
158     Attribute       /* Generic attribute */
159 } ParseSpecial;
160
161 static ParseSpecial specType;
162 static int waiting;
163
164 /*
165  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
166  * seen, then set to each successive source on the line.
167  */
168 static GNode    *predecessor;
169
170 /*
171  * The parseKeywords table is searched using binary search when deciding
172  * if a target or source is special. The 'spec' field is the ParseSpecial
173  * type of the keyword ("Not" if the keyword isn't special as a target) while
174  * the 'op' field is the operator to apply to the list of targets if the
175  * keyword is used as a source ("0" if the keyword isn't special as a source)
176  */
177 static struct {
178     char          *name;        /* Name of keyword */
179     ParseSpecial  spec;         /* Type when used as a target */
180     int           op;           /* Operator when used as a source */
181 } parseKeywords[] = {
182 { ".BEGIN",       Begin,        0 },
183 { ".DEFAULT",     Default,      0 },
184 { ".END",         End,          0 },
185 { ".EXEC",        Attribute,    OP_EXEC },
186 { ".IGNORE",      Ignore,       OP_IGNORE },
187 { ".INCLUDES",    Includes,     0 },
188 { ".INTERRUPT",   Interrupt,    0 },
189 { ".INVISIBLE",   Attribute,    OP_INVISIBLE },
190 { ".JOIN",        Attribute,    OP_JOIN },
191 { ".LIBS",        Libs,         0 },
192 { ".MAIN",        Main,         0 },
193 { ".MAKE",        Attribute,    OP_MAKE },
194 { ".MAKEFLAGS",   MFlags,       0 },
195 { ".MFLAGS",      MFlags,       0 },
196 { ".NOTMAIN",     Attribute,    OP_NOTMAIN },
197 { ".NOTPARALLEL", NotParallel,  0 },
198 { ".NO_PARALLEL", NotParallel,  0 },
199 { ".NULL",        Null,         0 },
200 { ".OPTIONAL",    Attribute,    OP_OPTIONAL },
201 { ".ORDER",       Order,        0 },
202 { ".PARALLEL",    Parallel,     0 },
203 { ".PATH",        ExPath,       0 },
204 { ".PHONY",       Phony,        OP_PHONY },
205 { ".POSIX",       Posix,        0 },
206 { ".PRECIOUS",    Precious,     OP_PRECIOUS },
207 { ".RECURSIVE",   Attribute,    OP_MAKE },
208 { ".SHELL",       ExShell,      0 },
209 { ".SILENT",      Silent,       OP_SILENT },
210 { ".SINGLESHELL", SingleShell,  0 },
211 { ".SUFFIXES",    Suffixes,     0 },
212 { ".USE",         Attribute,    OP_USE },
213 { ".WAIT",        Wait,         0 },
214 };
215
216 static int ParseFindKeyword(char *);
217 static int ParseLinkSrc(void *, void *);
218 static int ParseDoOp(void *, void *);
219 static int ParseAddDep(void *, void *);
220 static void ParseDoSrc(int, char *, Lst *);
221 static int ParseFindMain(void *, void *);
222 static int ParseAddDir(void *, void *);
223 static int ParseClearPath(void *, void *);
224 static void ParseDoDependency(char *);
225 static int ParseAddCmd(void *, void *);
226 static int ParseReadc(void);
227 static void ParseUnreadc(int);
228 static void ParseHasCommands(void *);
229 static void ParseDoInclude(char *);
230 static void ParseDoError(char *);
231 static void ParseDoWarning(char *);
232 #ifdef SYSVINCLUDE
233 static void ParseTraditionalInclude(char *);
234 #endif
235 static int ParseEOF(int);
236 static char *ParseReadLine(void);
237 static char *ParseSkipLine(int, int);
238 static void ParseFinishLine(void);
239
240 /*-
241  *----------------------------------------------------------------------
242  * ParseFindKeyword --
243  *      Look in the table of keywords for one matching the given string.
244  *
245  * Results:
246  *      The index of the keyword, or -1 if it isn't there.
247  *
248  * Side Effects:
249  *      None
250  *----------------------------------------------------------------------
251  */
252 static int
253 ParseFindKeyword(char *str)
254 {
255     int             start,
256                     end,
257                     cur;
258     int             diff;
259
260     start = 0;
261     end = (sizeof(parseKeywords) / sizeof(parseKeywords[0])) - 1;
262
263     do {
264         cur = start + ((end - start) / 2);
265         diff = strcmp(str, parseKeywords[cur].name);
266
267         if (diff == 0) {
268             return (cur);
269         } else if (diff < 0) {
270             end = cur - 1;
271         } else {
272             start = cur + 1;
273         }
274     } while (start <= end);
275     return (-1);
276 }
277
278 /*-
279  * Parse_Error  --
280  *      Error message abort function for parsing. Prints out the context
281  *      of the error (line number and file) as well as the message with
282  *      two optional arguments.
283  *
284  * Results:
285  *      None
286  *
287  * Side Effects:
288  *      "fatals" is incremented if the level is PARSE_FATAL.
289  */
290 /* VARARGS */
291 void
292 Parse_Error(int type, const char *fmt, ...)
293 {
294         va_list ap;
295
296         va_start(ap, fmt);
297         fprintf(stderr, "\"%s\", line %d: ",
298             curFile.fname, curFile.lineno);
299         if (type == PARSE_WARNING)
300                 fprintf(stderr, "warning: ");
301         vfprintf(stderr, fmt, ap);
302         va_end(ap);
303         fprintf(stderr, "\n");
304         fflush(stderr);
305         if (type == PARSE_FATAL)
306                 fatals += 1;
307 }
308
309 /*-
310  *---------------------------------------------------------------------
311  * ParseLinkSrc  --
312  *      Link the parent node to its new child. Used in a Lst_ForEach by
313  *      ParseDoDependency. If the specType isn't 'Not', the parent
314  *      isn't linked as a parent of the child.
315  *
316  * Results:
317  *      Always = 0
318  *
319  * Side Effects:
320  *      New elements are added to the parents list of cgn and the
321  *      children list of cgn. the unmade field of pgn is updated
322  *      to reflect the additional child.
323  *---------------------------------------------------------------------
324  */
325 static int
326 ParseLinkSrc(void *pgnp, void *cgnp)
327 {
328     GNode *pgn = pgnp;
329     GNode *cgn = cgnp;
330
331     if (Lst_Member(&pgn->children, cgn) == NULL) {
332         Lst_AtEnd(&pgn->children, cgn);
333         if (specType == Not) {
334             Lst_AtEnd(&cgn->parents, pgn);
335         }
336         pgn->unmade += 1;
337     }
338     return (0);
339 }
340
341 /*-
342  *---------------------------------------------------------------------
343  * ParseDoOp  --
344  *      Apply the parsed operator to the given target node. Used in a
345  *      Lst_ForEach call by ParseDoDependency once all targets have
346  *      been found and their operator parsed. If the previous and new
347  *      operators are incompatible, a major error is taken.
348  *
349  * Results:
350  *      Always 0
351  *
352  * Side Effects:
353  *      The type field of the node is altered to reflect any new bits in
354  *      the op.
355  *---------------------------------------------------------------------
356  */
357 static int
358 ParseDoOp(void *gnp, void *opp)
359 {
360     GNode *gn = gnp;
361     int op = *(int *)opp;
362
363     /*
364      * If the dependency mask of the operator and the node don't match and
365      * the node has actually had an operator applied to it before, and
366      * the operator actually has some dependency information in it, complain.
367      */
368     if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
369         !OP_NOP(gn->type) && !OP_NOP(op))
370     {
371         Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
372         return (1);
373     }
374
375     if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
376         /*
377          * If the node was the object of a :: operator, we need to create a
378          * new instance of it for the children and commands on this dependency
379          * line. The new instance is placed on the 'cohorts' list of the
380          * initial one (note the initial one is not on its own cohorts list)
381          * and the new instance is linked to all parents of the initial
382          * instance.
383          */
384         GNode *cohort;
385         LstNode *ln;
386
387         cohort = Targ_NewGN(gn->name);
388         /*
389          * Duplicate links to parents so graph traversal is simple. Perhaps
390          * some type bits should be duplicated?
391          *
392          * Make the cohort invisible as well to avoid duplicating it into
393          * other variables. True, parents of this target won't tend to do
394          * anything with their local variables, but better safe than
395          * sorry.
396          */
397         Lst_ForEach(&gn->parents, ParseLinkSrc, cohort);
398         cohort->type = OP_DOUBLEDEP|OP_INVISIBLE;
399         Lst_AtEnd(&gn->cohorts, cohort);
400
401         /*
402          * Replace the node in the targets list with the new copy
403          */
404         ln = Lst_Member(&targets, gn);
405         Lst_Replace(ln, cohort);
406         gn = cohort;
407     }
408     /*
409      * We don't want to nuke any previous flags (whatever they were) so we
410      * just OR the new operator into the old
411      */
412     gn->type |= op;
413
414     return (0);
415 }
416
417 /*-
418  *---------------------------------------------------------------------
419  * ParseAddDep  --
420  *      Check if the pair of GNodes given needs to be synchronized.
421  *      This has to be when two nodes are on different sides of a
422  *      .WAIT directive.
423  *
424  * Results:
425  *      Returns 1 if the two targets need to be ordered, 0 otherwise.
426  *      If it returns 1, the search can stop
427  *
428  * Side Effects:
429  *      A dependency can be added between the two nodes.
430  *
431  *---------------------------------------------------------------------
432  */
433 static int
434 ParseAddDep(void *pp, void *sp)
435 {
436     GNode *p = pp;
437     GNode *s = sp;
438
439     if (p->order < s->order) {
440         /*
441          * XXX: This can cause loops, and loops can cause unmade targets,
442          * but checking is tedious, and the debugging output can show the
443          * problem
444          */
445         Lst_AtEnd(&p->successors, s);
446         Lst_AtEnd(&s->preds, p);
447         return (0);
448     }
449     else
450         return (1);
451 }
452
453
454 /*-
455  *---------------------------------------------------------------------
456  * ParseDoSrc  --
457  *      Given the name of a source, figure out if it is an attribute
458  *      and apply it to the targets if it is. Else decide if there is
459  *      some attribute which should be applied *to* the source because
460  *      of some special target and apply it if so. Otherwise, make the
461  *      source be a child of the targets in the list 'targets'
462  *
463  * Results:
464  *      None
465  *
466  * Side Effects:
467  *      Operator bits may be added to the list of targets or to the source.
468  *      The targets may have a new source added to their lists of children.
469  *---------------------------------------------------------------------
470  */
471 static void
472 ParseDoSrc(int tOp, char *src, Lst *allsrc)
473 {
474     GNode       *gn = NULL;
475
476     if (*src == '.' && isupper ((unsigned char) src[1])) {
477         int keywd = ParseFindKeyword(src);
478         if (keywd != -1) {
479             int op = parseKeywords[keywd].op;
480             if (op != 0) {
481                 Lst_ForEach(&targets, ParseDoOp, &op);
482                 return;
483             }
484             if (parseKeywords[keywd].spec == Wait) {
485                 waiting++;
486                 return;
487             }
488         }
489     }
490
491     switch (specType) {
492     case Main:
493         /*
494          * If we have noted the existence of a .MAIN, it means we need
495          * to add the sources of said target to the list of things
496          * to create. The string 'src' is likely to be free, so we
497          * must make a new copy of it. Note that this will only be
498          * invoked if the user didn't specify a target on the command
499          * line. This is to allow #ifmake's to succeed, or something...
500          */
501         Lst_AtEnd(&create, estrdup(src));
502         /*
503          * Add the name to the .TARGETS variable as well, so the user cna
504          * employ that, if desired.
505          */
506         Var_Append(".TARGETS", src, VAR_GLOBAL);
507         return;
508
509     case Order:
510         /*
511          * Create proper predecessor/successor links between the previous
512          * source and the current one.
513          */
514         gn = Targ_FindNode(src, TARG_CREATE);
515         if (predecessor != NULL) {
516             Lst_AtEnd(&predecessor->successors, gn);
517             Lst_AtEnd(&gn->preds, predecessor);
518         }
519         /*
520          * The current source now becomes the predecessor for the next one.
521          */
522         predecessor = gn;
523         break;
524
525     default:
526         /*
527          * If the source is not an attribute, we need to find/create
528          * a node for it. After that we can apply any operator to it
529          * from a special target or link it to its parents, as
530          * appropriate.
531          *
532          * In the case of a source that was the object of a :: operator,
533          * the attribute is applied to all of its instances (as kept in
534          * the 'cohorts' list of the node) or all the cohorts are linked
535          * to all the targets.
536          */
537         gn = Targ_FindNode(src, TARG_CREATE);
538         if (tOp) {
539             gn->type |= tOp;
540         } else {
541             Lst_ForEach(&targets, ParseLinkSrc, gn);
542         }
543         if ((gn->type & OP_OPMASK) == OP_DOUBLEDEP) {
544             GNode       *cohort;
545             LstNode     *ln;
546
547             for (ln = Lst_First(&gn->cohorts); ln != NULL; ln = Lst_Succ(ln)) {
548                 cohort = Lst_Datum(ln);
549                 if (tOp) {
550                     cohort->type |= tOp;
551                 } else {
552                     Lst_ForEach(&targets, ParseLinkSrc, cohort);
553                 }
554             }
555         }
556         break;
557     }
558
559     gn->order = waiting;
560     Lst_AtEnd(allsrc, gn);
561     if (waiting) {
562         Lst_ForEach(allsrc, ParseAddDep, gn);
563     }
564 }
565
566 /*-
567  *-----------------------------------------------------------------------
568  * ParseFindMain --
569  *      Find a real target in the list and set it to be the main one.
570  *      Called by ParseDoDependency when a main target hasn't been found
571  *      yet.
572  *
573  * Results:
574  *      0 if main not found yet, 1 if it is.
575  *
576  * Side Effects:
577  *      mainNode is changed and Targ_SetMain is called.
578  *
579  *-----------------------------------------------------------------------
580  */
581 static int
582 ParseFindMain(void *gnp, void *dummy __unused)
583 {
584     GNode *gn = gnp;
585
586     if ((gn->type & (OP_NOTMAIN | OP_USE | OP_EXEC | OP_TRANSFORM)) == 0) {
587         mainNode = gn;
588         Targ_SetMain(gn);
589         return (1);
590     } else {
591         return (0);
592     }
593 }
594
595 /*-
596  *-----------------------------------------------------------------------
597  * ParseAddDir --
598  *      Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
599  *
600  * Results:
601  *      === 0
602  *
603  * Side Effects:
604  *      See Dir_AddDir.
605  *
606  *-----------------------------------------------------------------------
607  */
608 static int
609 ParseAddDir(void *path, void *name)
610 {
611
612     Dir_AddDir(path, name);
613     return(0);
614 }
615
616 /*-
617  *-----------------------------------------------------------------------
618  * ParseClearPath --
619  *      Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
620  *
621  * Results:
622  *      === 0
623  *
624  * Side Effects:
625  *      See Dir_ClearPath
626  *
627  *-----------------------------------------------------------------------
628  */
629 static int
630 ParseClearPath(void *path, void *dummy __unused)
631 {
632
633     Dir_ClearPath(path);
634     return (0);
635 }
636
637 /*-
638  *---------------------------------------------------------------------
639  * ParseDoDependency  --
640  *      Parse the dependency line in line.
641  *
642  * Results:
643  *      None
644  *
645  * Side Effects:
646  *      The nodes of the sources are linked as children to the nodes of the
647  *      targets. Some nodes may be created.
648  *
649  *      We parse a dependency line by first extracting words from the line and
650  * finding nodes in the list of all targets with that name. This is done
651  * until a character is encountered which is an operator character. Currently
652  * these are only ! and :. At this point the operator is parsed and the
653  * pointer into the line advanced until the first source is encountered.
654  *      The parsed operator is applied to each node in the 'targets' list,
655  * which is where the nodes found for the targets are kept, by means of
656  * the ParseDoOp function.
657  *      The sources are read in much the same way as the targets were except
658  * that now they are expanded using the wildcarding scheme of the C-Shell
659  * and all instances of the resulting words in the list of all targets
660  * are found. Each of the resulting nodes is then linked to each of the
661  * targets as one of its children.
662  *      Certain targets are handled specially. These are the ones detailed
663  * by the specType variable.
664  *      The storing of transformation rules is also taken care of here.
665  * A target is recognized as a transformation rule by calling
666  * Suff_IsTransform. If it is a transformation rule, its node is gotten
667  * from the suffix module via Suff_AddTransform rather than the standard
668  * Targ_FindNode in the target module.
669  *---------------------------------------------------------------------
670  */
671 static void
672 ParseDoDependency (char *line)
673 {
674     char           *cp;         /* our current position */
675     GNode          *gn;         /* a general purpose temporary node */
676     int             op;         /* the operator on the line */
677     char            savec;      /* a place to save a character */
678     Lst paths;  /* Search paths to alter when parsing a list of .PATH targets */
679     int             tOp;        /* operator from special target */
680
681     tOp = 0;
682
683     specType = Not;
684     waiting = 0;
685     Lst_Init(&paths);
686
687     do {
688         for (cp = line;
689             *cp && !isspace((unsigned char)*cp) && *cp != '(';
690             cp++)
691         {
692             if (*cp == '$') {
693                 /*
694                  * Must be a dynamic source (would have been expanded
695                  * otherwise), so call the Var module to parse the puppy
696                  * so we can safely advance beyond it...There should be
697                  * no errors in this, as they would have been discovered
698                  * in the initial Var_Subst and we wouldn't be here.
699                  */
700                 size_t length;
701                 Boolean freeIt;
702                 char    *result;
703
704                 result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
705
706                 if (freeIt) {
707                     free(result);
708                 }
709                 cp += length - 1;
710             } else if (*cp == '!' || *cp == ':') {
711                 /*
712                  * We don't want to end a word on ':' or '!' if there is a
713                  * better match later on in the string (greedy matching).
714                  * This allows the user to have targets like:
715                  *    fie::fi:fo: fum
716                  *    foo::bar:
717                  * where "fie::fi:fo" and "foo::bar" are the targets.  In
718                  * real life this is used for perl5 library man pages where
719                  * "::" separates an object from its class.
720                  * Ie: "File::Spec::Unix".  This behaviour is also consistent
721                  * with other versions of make.
722                  */
723                 char *p = cp + 1;
724
725                 if (*cp == ':' && *p == ':')
726                     p++;
727
728                 /* Found the best match already. */
729                 if (*p == '\0' || isspace(*p))
730                     break;
731
732                 p += strcspn(p, "!:");
733
734                 /* No better match later on... */
735                 if (*p == '\0')
736                     break;
737             }
738             continue;
739         }
740         if (*cp == '(') {
741             /*
742              * Archives must be handled specially to make sure the OP_ARCHV
743              * flag is set in their 'type' field, for one thing, and because
744              * things like "archive(file1.o file2.o file3.o)" are permissible.
745              * Arch_ParseArchive will set 'line' to be the first non-blank
746              * after the archive-spec. It creates/finds nodes for the members
747              * and places them on the given list, returning SUCCESS if all
748              * went well and FAILURE if there was an error in the
749              * specification. On error, line should remain untouched.
750              */
751             if (Arch_ParseArchive(&line, &targets, VAR_CMD) != SUCCESS) {
752                 Parse_Error(PARSE_FATAL,
753                              "Error in archive specification: \"%s\"", line);
754                 return;
755             } else {
756                 continue;
757             }
758         }
759         savec = *cp;
760
761         if (!*cp) {
762             /*
763              * Ending a dependency line without an operator is a Bozo
764              * no-no.  As a heuristic, this is also often triggered by
765              * undetected conflicts from cvs/rcs merges.
766              */
767             if ((strncmp(line, "<<<<<<", 6) == 0) ||
768                 (strncmp(line, "======", 6) == 0) ||
769                 (strncmp(line, ">>>>>>", 6) == 0))
770                 Parse_Error(PARSE_FATAL,
771                     "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
772             else
773                 Parse_Error(PARSE_FATAL, "Need an operator");
774             return;
775         }
776         *cp = '\0';
777         /*
778          * Have a word in line. See if it's a special target and set
779          * specType to match it.
780          */
781         if (*line == '.' && isupper((unsigned char)line[1])) {
782             /*
783              * See if the target is a special target that must have it
784              * or its sources handled specially.
785              */
786             int keywd = ParseFindKeyword(line);
787             if (keywd != -1) {
788                 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
789                     Parse_Error(PARSE_FATAL, "Mismatched special targets");
790                     return;
791                 }
792
793                 specType = parseKeywords[keywd].spec;
794                 tOp = parseKeywords[keywd].op;
795
796                 /*
797                  * Certain special targets have special semantics:
798                  *      .PATH           Have to set the dirSearchPath
799                  *                      variable too
800                  *      .MAIN           Its sources are only used if
801                  *                      nothing has been specified to
802                  *                      create.
803                  *      .DEFAULT        Need to create a node to hang
804                  *                      commands on, but we don't want
805                  *                      it in the graph, nor do we want
806                  *                      it to be the Main Target, so we
807                  *                      create it, set OP_NOTMAIN and
808                  *                      add it to the list, setting
809                  *                      DEFAULT to the new node for
810                  *                      later use. We claim the node is
811                  *                      A transformation rule to make
812                  *                      life easier later, when we'll
813                  *                      use Make_HandleUse to actually
814                  *                      apply the .DEFAULT commands.
815                  *      .PHONY          The list of targets
816                  *      .BEGIN
817                  *      .END
818                  *      .INTERRUPT      Are not to be considered the
819                  *                      main target.
820                  *      .NOTPARALLEL    Make only one target at a time.
821                  *      .SINGLESHELL    Create a shell for each command.
822                  *      .ORDER          Must set initial predecessor to NULL
823                  */
824                 switch (specType) {
825                     case ExPath:
826                         Lst_AtEnd(&paths, &dirSearchPath);
827                         break;
828                     case Main:
829                         if (!Lst_IsEmpty(&create)) {
830                             specType = Not;
831                         }
832                         break;
833                     case Begin:
834                     case End:
835                     case Interrupt:
836                         gn = Targ_FindNode(line, TARG_CREATE);
837                         gn->type |= OP_NOTMAIN;
838                         Lst_AtEnd(&targets, gn);
839                         break;
840                     case Default:
841                         gn = Targ_NewGN(".DEFAULT");
842                         gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
843                         Lst_AtEnd(&targets, gn);
844                         DEFAULT = gn;
845                         break;
846                     case NotParallel:
847                     {
848                         maxJobs = 1;
849                         break;
850                     }
851                     case SingleShell:
852                         compatMake = 1;
853                         break;
854                     case Order:
855                         predecessor = NULL;
856                         break;
857                     default:
858                         break;
859                 }
860             } else if (strncmp(line, ".PATH", 5) == 0) {
861                 /*
862                  * .PATH<suffix> has to be handled specially.
863                  * Call on the suffix module to give us a path to
864                  * modify.
865                  */
866                 Lst *path;
867
868                 specType = ExPath;
869                 path = Suff_GetPath(&line[5]);
870                 if (path == NULL) {
871                     Parse_Error(PARSE_FATAL,
872                                  "Suffix '%s' not defined (yet)",
873                                  &line[5]);
874                     return;
875                 } else
876                     Lst_AtEnd(&paths, path);
877             }
878         }
879
880         /*
881          * Have word in line. Get or create its node and stick it at
882          * the end of the targets list
883          */
884         if ((specType == Not) && (*line != '\0')) {
885             /* target names to be found and added to targets list */
886             Lst curTargs = Lst_Initializer(curTargs);
887
888             if (Dir_HasWildcards(line)) {
889                 /*
890                  * Targets are to be sought only in the current directory,
891                  * so create an empty path for the thing. Note we need to
892                  * use Dir_Destroy in the destruction of the path as the
893                  * Dir module could have added a directory to the path...
894                  */
895                 Lst emptyPath = Lst_Initializer(emptyPath);
896
897                 Dir_Expand(line, &emptyPath, &curTargs);
898
899                 Lst_Destroy(&emptyPath, Dir_Destroy);
900             } else {
901                 /*
902                  * No wildcards, but we want to avoid code duplication,
903                  * so create a list with the word on it.
904                  */
905                 Lst_AtEnd(&curTargs, line);
906             }
907
908             while (!Lst_IsEmpty(&curTargs)) {
909                 char    *targName = Lst_DeQueue(&curTargs);
910
911                 if (!Suff_IsTransform (targName)) {
912                     gn = Targ_FindNode(targName, TARG_CREATE);
913                 } else {
914                     gn = Suff_AddTransform(targName);
915                 }
916
917                 Lst_AtEnd(&targets, gn);
918             }
919         } else if (specType == ExPath && *line != '.' && *line != '\0') {
920             Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
921         }
922
923         *cp = savec;
924         /*
925          * If it is a special type and not .PATH, it's the only target we
926          * allow on this line...
927          */
928         if (specType != Not && specType != ExPath) {
929             Boolean warn = FALSE;
930
931             while ((*cp != '!') && (*cp != ':') && *cp) {
932                 if (*cp != ' ' && *cp != '\t') {
933                     warn = TRUE;
934                 }
935                 cp++;
936             }
937             if (warn) {
938                 Parse_Error(PARSE_WARNING, "Extra target ignored");
939             }
940         } else {
941             while (*cp && isspace((unsigned char)*cp)) {
942                 cp++;
943             }
944         }
945         line = cp;
946     } while ((*line != '!') && (*line != ':') && *line);
947
948     if (!Lst_IsEmpty(&targets)) {
949         switch (specType) {
950             default:
951                 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
952                 break;
953             case Default:
954             case Begin:
955             case End:
956             case Interrupt:
957                 /*
958                  * These four create nodes on which to hang commands, so
959                  * targets shouldn't be empty...
960                  */
961             case Not:
962                 /*
963                  * Nothing special here -- targets can be empty if it wants.
964                  */
965                 break;
966         }
967     }
968
969     /*
970      * Have now parsed all the target names. Must parse the operator next. The
971      * result is left in  op .
972      */
973     if (*cp == '!') {
974         op = OP_FORCE;
975     } else if (*cp == ':') {
976         if (cp[1] == ':') {
977             op = OP_DOUBLEDEP;
978             cp++;
979         } else {
980             op = OP_DEPENDS;
981         }
982     } else {
983         Parse_Error(PARSE_FATAL, "Missing dependency operator");
984         return;
985     }
986
987     cp++;                       /* Advance beyond operator */
988
989     Lst_ForEach(&targets, ParseDoOp, &op);
990
991     /*
992      * Get to the first source
993      */
994     while (*cp && isspace((unsigned char)*cp)) {
995         cp++;
996     }
997     line = cp;
998
999     /*
1000      * Several special targets take different actions if present with no
1001      * sources:
1002      *  a .SUFFIXES line with no sources clears out all old suffixes
1003      *  a .PRECIOUS line makes all targets precious
1004      *  a .IGNORE line ignores errors for all targets
1005      *  a .SILENT line creates silence when making all targets
1006      *  a .PATH removes all directories from the search path(s).
1007      */
1008     if (!*line) {
1009         switch (specType) {
1010             case Suffixes:
1011                 Suff_ClearSuffixes();
1012                 break;
1013             case Precious:
1014                 allPrecious = TRUE;
1015                 break;
1016             case Ignore:
1017                 ignoreErrors = TRUE;
1018                 break;
1019             case Silent:
1020                 beSilent = TRUE;
1021                 break;
1022             case ExPath:
1023                 Lst_ForEach(&paths, ParseClearPath, NULL);
1024                 break;
1025             case Posix:
1026                 Var_Set("%POSIX", "1003.2", VAR_GLOBAL);
1027                 break;
1028             default:
1029                 break;
1030         }
1031     } else if (specType == MFlags) {
1032         /*
1033          * Call on functions in main.c to deal with these arguments and
1034          * set the initial character to a null-character so the loop to
1035          * get sources won't get anything
1036          */
1037         Main_ParseArgLine(line);
1038         *line = '\0';
1039     } else if (specType == ExShell) {
1040         if (Job_ParseShell(line) != SUCCESS) {
1041             Parse_Error(PARSE_FATAL, "improper shell specification");
1042             return;
1043         }
1044         *line = '\0';
1045     } else if ((specType == NotParallel) || (specType == SingleShell)) {
1046         *line = '\0';
1047     }
1048
1049     /*
1050      * NOW GO FOR THE SOURCES
1051      */
1052     if ((specType == Suffixes) || (specType == ExPath) ||
1053         (specType == Includes) || (specType == Libs) ||
1054         (specType == Null))
1055     {
1056         while (*line) {
1057             /*
1058              * If the target was one that doesn't take files as its sources
1059              * but takes something like suffixes, we take each
1060              * space-separated word on the line as a something and deal
1061              * with it accordingly.
1062              *
1063              * If the target was .SUFFIXES, we take each source as a
1064              * suffix and add it to the list of suffixes maintained by the
1065              * Suff module.
1066              *
1067              * If the target was a .PATH, we add the source as a directory
1068              * to search on the search path.
1069              *
1070              * If it was .INCLUDES, the source is taken to be the suffix of
1071              * files which will be #included and whose search path should
1072              * be present in the .INCLUDES variable.
1073              *
1074              * If it was .LIBS, the source is taken to be the suffix of
1075              * files which are considered libraries and whose search path
1076              * should be present in the .LIBS variable.
1077              *
1078              * If it was .NULL, the source is the suffix to use when a file
1079              * has no valid suffix.
1080              */
1081             char  savech;
1082             while (*cp && !isspace((unsigned char)*cp)) {
1083                 cp++;
1084             }
1085             savech = *cp;
1086             *cp = '\0';
1087             switch (specType) {
1088                 case Suffixes:
1089                     Suff_AddSuffix(line);
1090                     break;
1091                 case ExPath:
1092                     Lst_ForEach(&paths, ParseAddDir, line);
1093                     break;
1094                 case Includes:
1095                     Suff_AddInclude(line);
1096                     break;
1097                 case Libs:
1098                     Suff_AddLib(line);
1099                     break;
1100                 case Null:
1101                     Suff_SetNull(line);
1102                     break;
1103                 default:
1104                     break;
1105             }
1106             *cp = savech;
1107             if (savech != '\0') {
1108                 cp++;
1109             }
1110             while (*cp && isspace((unsigned char)*cp)) {
1111                 cp++;
1112             }
1113             line = cp;
1114         }
1115         Lst_Destroy(&paths, NOFREE);
1116
1117     } else {
1118         Lst curSrcs = Lst_Initializer(curSrc);  /* list of sources in order */
1119  
1120         while (*line) {
1121             /*
1122              * The targets take real sources, so we must beware of archive
1123              * specifications (i.e. things with left parentheses in them)
1124              * and handle them accordingly.
1125              */
1126             while (*cp && !isspace((unsigned char)*cp)) {
1127                 if ((*cp == '(') && (cp > line) && (cp[-1] != '$')) {
1128                     /*
1129                      * Only stop for a left parenthesis if it isn't at the
1130                      * start of a word (that'll be for variable changes
1131                      * later) and isn't preceded by a dollar sign (a dynamic
1132                      * source).
1133                      */
1134                     break;
1135                 } else {
1136                     cp++;
1137                 }
1138             }
1139
1140             if (*cp == '(') {
1141                 GNode     *gnp;
1142                 /* list of archive source names after expansion */
1143                 Lst sources = Lst_Initializer(sources);
1144
1145                 if (Arch_ParseArchive(&line, &sources, VAR_CMD) != SUCCESS) {
1146                     Parse_Error(PARSE_FATAL,
1147                                  "Error in source archive spec \"%s\"", line);
1148                     return;
1149                 }
1150
1151                 while (!Lst_IsEmpty(&sources)) {
1152                     gnp = Lst_DeQueue(&sources);
1153                     ParseDoSrc(tOp, gnp->name, &curSrcs);
1154                 }
1155                 cp = line;
1156             } else {
1157                 if (*cp) {
1158                     *cp = '\0';
1159                     cp += 1;
1160                 }
1161
1162                 ParseDoSrc(tOp, line, &curSrcs);
1163             }
1164             while (*cp && isspace((unsigned char)*cp)) {
1165                 cp++;
1166             }
1167             line = cp;
1168         }
1169         Lst_Destroy(&curSrcs, NOFREE);
1170     }
1171
1172     if (mainNode == NULL) {
1173         /*
1174          * If we have yet to decide on a main target to make, in the
1175          * absence of any user input, we want the first target on
1176          * the first dependency line that is actually a real target
1177          * (i.e. isn't a .USE or .EXEC rule) to be made.
1178          */
1179         Lst_ForEach(&targets, ParseFindMain, NULL);
1180     }
1181 }
1182
1183 /*-
1184  *---------------------------------------------------------------------
1185  * Parse_IsVar  --
1186  *      Return TRUE if the passed line is a variable assignment. A variable
1187  *      assignment consists of a single word followed by optional whitespace
1188  *      followed by either a += or an = operator.
1189  *      This function is used both by the Parse_File function and main when
1190  *      parsing the command-line arguments.
1191  *
1192  * Results:
1193  *      TRUE if it is. FALSE if it ain't
1194  *
1195  * Side Effects:
1196  *      none
1197  *---------------------------------------------------------------------
1198  */
1199 Boolean
1200 Parse_IsVar(char *line)
1201 {
1202     Boolean wasSpace = FALSE;   /* set TRUE if found a space */
1203     Boolean haveName = FALSE;   /* Set TRUE if have a variable name */
1204
1205     int level = 0;
1206 #define ISEQOPERATOR(c) \
1207         (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1208
1209     /*
1210      * Skip to variable name
1211      */
1212     for (; (*line == ' ') || (*line == '\t'); line++)
1213         continue;
1214
1215     for (; *line != '=' || level != 0; line++)
1216         switch (*line) {
1217         case '\0':
1218             /*
1219              * end-of-line -- can't be a variable assignment.
1220              */
1221             return (FALSE);
1222
1223         case ' ':
1224         case '\t':
1225             /*
1226              * there can be as much white space as desired so long as there is
1227              * only one word before the operator
1228              */
1229             wasSpace = TRUE;
1230             break;
1231
1232         case '(':
1233         case '{':
1234             level++;
1235             break;
1236
1237         case '}':
1238         case ')':
1239             level--;
1240             break;
1241
1242         default:
1243             if (wasSpace && haveName) {
1244                     if (ISEQOPERATOR(*line)) {
1245                         /*
1246                          * We must have a finished word
1247                          */
1248                         if (level != 0)
1249                             return (FALSE);
1250
1251                         /*
1252                          * When an = operator [+?!:] is found, the next
1253                          * character must be an = or it ain't a valid
1254                          * assignment.
1255                          */
1256                         if (line[1] == '=')
1257                             return (haveName);
1258 #ifdef SUNSHCMD
1259                         /*
1260                          * This is a shell command
1261                          */
1262                         if (strncmp(line, ":sh", 3) == 0)
1263                             return (haveName);
1264 #endif
1265                     }
1266                     /*
1267                      * This is the start of another word, so not assignment.
1268                      */
1269                     return (FALSE);
1270             }
1271             else {
1272                 haveName = TRUE;
1273                 wasSpace = FALSE;
1274             }
1275             break;
1276         }
1277
1278     return (haveName);
1279 }
1280
1281 /*-
1282  *---------------------------------------------------------------------
1283  * Parse_DoVar  --
1284  *      Take the variable assignment in the passed line and do it in the
1285  *      global context.
1286  *
1287  *      Note: There is a lexical ambiguity with assignment modifier characters
1288  *      in variable names. This routine interprets the character before the =
1289  *      as a modifier. Therefore, an assignment like
1290  *          C++=/usr/bin/CC
1291  *      is interpreted as "C+ +=" instead of "C++ =".
1292  *
1293  * Results:
1294  *      none
1295  *
1296  * Side Effects:
1297  *      the variable structure of the given variable name is altered in the
1298  *      global context.
1299  *---------------------------------------------------------------------
1300  */
1301 void
1302 Parse_DoVar(char *line, GNode *ctxt)
1303 {
1304     char           *cp; /* pointer into line */
1305     enum {
1306         VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1307     }               type;       /* Type of assignment */
1308     char            *opc;       /* ptr to operator character to
1309                                  * null-terminate the variable name */
1310     /*
1311      * Avoid clobbered variable warnings by forcing the compiler
1312      * to ``unregister'' variables
1313      */
1314 #if __GNUC__
1315     (void)&cp;
1316     (void)&line;
1317 #endif
1318
1319     /*
1320      * Skip to variable name
1321      */
1322     while ((*line == ' ') || (*line == '\t')) {
1323         line++;
1324     }
1325
1326     /*
1327      * Skip to operator character, nulling out whitespace as we go
1328      */
1329     for (cp = line + 1; *cp != '='; cp++) {
1330         if (isspace((unsigned char)*cp)) {
1331             *cp = '\0';
1332         }
1333     }
1334     opc = cp - 1;       /* operator is the previous character */
1335     *cp++ = '\0';       /* nuke the = */
1336
1337     /*
1338      * Check operator type
1339      */
1340     switch (*opc) {
1341         case '+':
1342             type = VAR_APPEND;
1343             *opc = '\0';
1344             break;
1345
1346         case '?':
1347             /*
1348              * If the variable already has a value, we don't do anything.
1349              */
1350             *opc = '\0';
1351             if (Var_Exists(line, ctxt)) {
1352                 return;
1353             } else {
1354                 type = VAR_NORMAL;
1355             }
1356             break;
1357
1358         case ':':
1359             type = VAR_SUBST;
1360             *opc = '\0';
1361             break;
1362
1363         case '!':
1364             type = VAR_SHELL;
1365             *opc = '\0';
1366             break;
1367
1368         default:
1369 #ifdef SUNSHCMD
1370             while (*opc != ':')
1371                 if (opc == line)
1372                     break;
1373                 else
1374                     --opc;
1375
1376             if (strncmp(opc, ":sh", 3) == 0) {
1377                 type = VAR_SHELL;
1378                 *opc = '\0';
1379                 break;
1380             }
1381 #endif
1382             type = VAR_NORMAL;
1383             break;
1384     }
1385
1386     while (isspace((unsigned char)*cp)) {
1387         cp++;
1388     }
1389
1390     if (type == VAR_APPEND) {
1391         Var_Append(line, cp, ctxt);
1392     } else if (type == VAR_SUBST) {
1393         /*
1394          * Allow variables in the old value to be undefined, but leave their
1395          * invocation alone -- this is done by forcing oldVars to be false.
1396          * XXX: This can cause recursive variables, but that's not hard to do,
1397          * and this allows someone to do something like
1398          *
1399          *  CFLAGS = $(.INCLUDES)
1400          *  CFLAGS := -I.. $(CFLAGS)
1401          *
1402          * And not get an error.
1403          */
1404         Boolean   oldOldVars = oldVars;
1405
1406         oldVars = FALSE;
1407
1408         /*
1409          * make sure that we set the variable the first time to nothing
1410          * so that it gets substituted!
1411          */
1412         if (!Var_Exists(line, ctxt))
1413             Var_Set(line, "", ctxt);
1414
1415         cp = Var_Subst(NULL, cp, ctxt, FALSE);
1416         oldVars = oldOldVars;
1417
1418         Var_Set(line, cp, ctxt);
1419         free(cp);
1420     } else if (type == VAR_SHELL) {
1421         Boolean freeCmd = FALSE; /* TRUE if the command needs to be freed, i.e.
1422                                   * if any variable expansion was performed */
1423         char *res, *error;
1424
1425         if (strchr(cp, '$') != NULL) {
1426             /*
1427              * There's a dollar sign in the command, so perform variable
1428              * expansion on the whole thing. The resulting string will need
1429              * freeing when we're done, so set freeCmd to TRUE.
1430              */
1431             cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1432             freeCmd = TRUE;
1433         }
1434
1435         res = Cmd_Exec(cp, &error);
1436         Var_Set(line, res, ctxt);
1437         free(res);
1438
1439         if (error)
1440             Parse_Error(PARSE_WARNING, error, cp);
1441
1442         if (freeCmd)
1443             free(cp);
1444     } else {
1445         /*
1446          * Normal assignment -- just do it.
1447          */
1448         Var_Set(line, cp, ctxt);
1449     }
1450 }
1451
1452 /*-
1453  * ParseAddCmd  --
1454  *      Lst_ForEach function to add a command line to all targets
1455  *
1456  * Results:
1457  *      Always 0
1458  *
1459  * Side Effects:
1460  *      A new element is added to the commands list of the node.
1461  */
1462 static int
1463 ParseAddCmd(void *gnp, void *cmd)
1464 {
1465     GNode *gn = gnp;
1466
1467     /* if target already supplied, ignore commands */
1468     if (!(gn->type & OP_HAS_COMMANDS))
1469         Lst_AtEnd(&gn->commands, cmd);
1470     else
1471         Parse_Error(PARSE_WARNING,
1472                     "duplicate script for target \"%s\" ignored",
1473                     gn->name);
1474     return (0);
1475 }
1476
1477 /*-
1478  *-----------------------------------------------------------------------
1479  * ParseHasCommands --
1480  *      Callback procedure for Parse_File when destroying the list of
1481  *      targets on the last dependency line. Marks a target as already
1482  *      having commands if it does, to keep from having shell commands
1483  *      on multiple dependency lines.
1484  *
1485  * Results:
1486  *      None
1487  *
1488  * Side Effects:
1489  *      OP_HAS_COMMANDS may be set for the target.
1490  *
1491  *-----------------------------------------------------------------------
1492  */
1493 static void
1494 ParseHasCommands(void *gnp)
1495 {
1496     GNode *gn = gnp;
1497
1498     if (!Lst_IsEmpty(&gn->commands)) {
1499         gn->type |= OP_HAS_COMMANDS;
1500     }
1501 }
1502
1503 /*-
1504  *-----------------------------------------------------------------------
1505  * Parse_AddIncludeDir --
1506  *      Add a directory to the path searched for included makefiles
1507  *      bracketed by double-quotes. Used by functions in main.c
1508  *
1509  * Results:
1510  *      None.
1511  *
1512  * Side Effects:
1513  *      The directory is appended to the list.
1514  *
1515  *-----------------------------------------------------------------------
1516  */
1517 void
1518 Parse_AddIncludeDir(char *dir)
1519 {
1520
1521     Dir_AddDir(&parseIncPath, dir);
1522 }
1523
1524 /*---------------------------------------------------------------------
1525  * ParseDoError  --
1526  *      Handle error directive
1527  *
1528  *      The input is the line minus the ".error".  We substitute variables,
1529  *      print the message and exit(1) or just print a warning if the ".error"
1530  *      directive is malformed.
1531  *
1532  *---------------------------------------------------------------------
1533  */
1534 static void
1535 ParseDoError(char *errmsg)
1536 {
1537
1538         if (!isspace((unsigned char)*errmsg)) {
1539                 Parse_Error(PARSE_WARNING, "invalid syntax: .error%s", errmsg);
1540                 return;
1541         }
1542
1543         while (isspace((unsigned char)*errmsg))
1544                 errmsg++;
1545
1546         errmsg = Var_Subst(NULL, errmsg, VAR_GLOBAL, FALSE);
1547
1548         Parse_Error(PARSE_FATAL, "%s", errmsg);
1549         /* Terminate immediately. */
1550         exit(1);
1551 }
1552
1553 /*---------------------------------------------------------------------
1554  * ParseDoWarning  --
1555  *      Handle warning directive
1556  *
1557  *      The input is the line minus the ".warning".  We substitute variables
1558  *      and print the message or just print a warning if the ".warning"
1559  *      directive is malformed.
1560  *
1561  *---------------------------------------------------------------------
1562  */
1563 static void
1564 ParseDoWarning(char *warnmsg)
1565 {
1566
1567         if (!isspace((unsigned char)*warnmsg)) {
1568                 Parse_Error(PARSE_WARNING, "invalid syntax: .warning%s",
1569                     warnmsg);
1570                 return;
1571         }
1572
1573         while (isspace((unsigned char)*warnmsg))
1574                 warnmsg++;
1575
1576         warnmsg = Var_Subst(NULL, warnmsg, VAR_GLOBAL, FALSE);
1577
1578         Parse_Error(PARSE_WARNING, "%s", warnmsg);
1579 }
1580
1581 /*-
1582  *---------------------------------------------------------------------
1583  * ParseDoInclude  --
1584  *      Push to another file.
1585  *
1586  *      The input is the line minus the #include. A file spec is a string
1587  *      enclosed in <> or "". The former is looked for only in sysIncPath.
1588  *      The latter in . and the directories specified by -I command line
1589  *      options
1590  *
1591  * Results:
1592  *      None
1593  *
1594  * Side Effects:
1595  *      A structure is added to the includes Lst and readProc, curFile.lineno,
1596  *      curFile.fname and curFile.F are altered for the new file
1597  *---------------------------------------------------------------------
1598  */
1599 static void
1600 ParseDoInclude (char *file)
1601 {
1602     char          *fullname;    /* full pathname of file */
1603     IFile         *oldFile;     /* state associated with current file */
1604     char          endc;         /* the character which ends the file spec */
1605     char          *cp;          /* current position in file spec */
1606     Boolean       isSystem;     /* TRUE if makefile is a system makefile */
1607
1608     /*
1609      * Skip to delimiter character so we know where to look
1610      */
1611     while ((*file == ' ') || (*file == '\t')) {
1612         file++;
1613     }
1614
1615     if ((*file != '"') && (*file != '<')) {
1616         Parse_Error(PARSE_FATAL,
1617             ".include filename must be delimited by '\"' or '<'");
1618         return;
1619     }
1620
1621     /*
1622      * Set the search path on which to find the include file based on the
1623      * characters which bracket its name. Angle-brackets imply it's
1624      * a system Makefile while double-quotes imply it's a user makefile
1625      */
1626     if (*file == '<') {
1627         isSystem = TRUE;
1628         endc = '>';
1629     } else {
1630         isSystem = FALSE;
1631         endc = '"';
1632     }
1633
1634     /*
1635      * Skip to matching delimiter
1636      */
1637     for (cp = ++file; *cp && *cp != endc; cp++) {
1638         continue;
1639     }
1640
1641     if (*cp != endc) {
1642         Parse_Error(PARSE_FATAL,
1643                      "Unclosed %cinclude filename. '%c' expected",
1644                      '.', endc);
1645         return;
1646     }
1647     *cp = '\0';
1648
1649     /*
1650      * Substitute for any variables in the file name before trying to
1651      * find the thing.
1652      */
1653     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1654
1655     /*
1656      * Now we know the file's name and its search path, we attempt to
1657      * find the durn thing. A return of NULL indicates the file don't
1658      * exist.
1659      */
1660     if (!isSystem) {
1661         /*
1662          * Include files contained in double-quotes are first searched for
1663          * relative to the including file's location. We don't want to
1664          * cd there, of course, so we just tack on the old file's
1665          * leading path components and call Dir_FindFile to see if
1666          * we can locate the beast.
1667          */
1668         char      *prefEnd, *Fname;
1669
1670         /* Make a temporary copy of this, to be safe. */
1671         Fname = estrdup(curFile.fname);
1672
1673         prefEnd = strrchr(Fname, '/');
1674         if (prefEnd != (char *)NULL) {
1675             char        *newName;
1676
1677             *prefEnd = '\0';
1678             if (file[0] == '/')
1679                 newName = estrdup(file);
1680             else
1681                 newName = str_concat(Fname, file, STR_ADDSLASH);
1682             fullname = Dir_FindFile(newName, &parseIncPath);
1683             if (fullname == NULL) {
1684                 fullname = Dir_FindFile(newName, &dirSearchPath);
1685             }
1686             free(newName);
1687             *prefEnd = '/';
1688         } else {
1689             fullname = NULL;
1690         }
1691         free(Fname);
1692     } else {
1693         fullname = NULL;
1694     }
1695
1696     if (fullname == NULL) {
1697         /*
1698          * System makefile or makefile wasn't found in same directory as
1699          * included makefile. Search for it first on the -I search path,
1700          * then on the .PATH search path, if not found in a -I directory.
1701          * XXX: Suffix specific?
1702          */
1703         fullname = Dir_FindFile(file, &parseIncPath);
1704         if (fullname == NULL) {
1705             fullname = Dir_FindFile(file, &dirSearchPath);
1706         }
1707     }
1708
1709     if (fullname == NULL) {
1710         /*
1711          * Still haven't found the makefile. Look for it on the system
1712          * path as a last resort.
1713          */
1714         fullname = Dir_FindFile(file, &sysIncPath);
1715     }
1716
1717     if (fullname == NULL) {
1718         *cp = endc;
1719         Parse_Error(PARSE_FATAL, "Could not find %s", file);
1720         return;
1721     }
1722
1723     free(file);
1724
1725     /*
1726      * Once we find the absolute path to the file, we get to save all the
1727      * state from the current file before we can start reading this
1728      * include file. The state is stored in an IFile structure which
1729      * is placed on a list with other IFile structures. The list makes
1730      * a very nice stack to track how we got here...
1731      */
1732     oldFile = emalloc(sizeof (IFile));
1733     memcpy(oldFile, &curFile, sizeof(IFile));
1734
1735     Lst_AtFront(&includes, oldFile);
1736
1737     /*
1738      * Once the previous state has been saved, we can get down to reading
1739      * the new file. We set up the name of the file to be the absolute
1740      * name of the include file so error messages refer to the right
1741      * place. Naturally enough, we start reading at line number 0.
1742      */
1743     curFile.fname = fullname;
1744     curFile.lineno = 0;
1745
1746     curFile.F = fopen(fullname, "r");
1747     curFile.p = NULL;
1748     if (curFile.F == NULL) {
1749         Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1750         /*
1751          * Pop to previous file
1752          */
1753         ParseEOF(0);
1754     } else {
1755         Var_Append(".MAKEFILE_LIST", fullname, VAR_GLOBAL);
1756     }
1757 }
1758
1759 /*-
1760  *---------------------------------------------------------------------
1761  * Parse_FromString  --
1762  *      Start Parsing from the given string
1763  *
1764  * Results:
1765  *      None
1766  *
1767  * Side Effects:
1768  *      A structure is added to the includes Lst and readProc, curFile.lineno,
1769  *      curFile.fname and curFile.F are altered for the new file
1770  *---------------------------------------------------------------------
1771  */
1772 void
1773 Parse_FromString(char *str, int lineno)
1774 {
1775     IFile         *oldFile;     /* state associated with this file */
1776
1777     DEBUGF(FOR, ("%s\n---- at line %d\n", str, lineno));
1778
1779     oldFile = emalloc(sizeof(IFile));
1780     memcpy(oldFile, &curFile, sizeof(IFile));
1781
1782     Lst_AtFront(&includes, oldFile);
1783
1784     curFile.F = NULL;
1785     curFile.p = emalloc(sizeof (PTR));
1786     curFile.p->str = curFile.p->ptr = str;
1787     curFile.lineno = lineno;
1788     curFile.fname = estrdup(curFile.fname);
1789 }
1790
1791 #ifdef SYSVINCLUDE
1792 /*-
1793  *---------------------------------------------------------------------
1794  * ParseTraditionalInclude  --
1795  *      Push to another file.
1796  *
1797  *      The input is the line minus the "include".  The file name is
1798  *      the string following the "include".
1799  *
1800  * Results:
1801  *      None
1802  *
1803  * Side Effects:
1804  *      A structure is added to the includes Lst and readProc, curFile.lineno,
1805  *      curFile.fname and curFile.F are altered for the new file
1806  *---------------------------------------------------------------------
1807  */
1808 static void
1809 ParseTraditionalInclude (char *file)
1810 {
1811     char          *fullname;    /* full pathname of file */
1812     IFile         *oldFile;     /* state associated with current file */
1813     char          *cp;          /* current position in file spec */
1814
1815     /*
1816      * Skip over whitespace
1817      */
1818     while ((*file == ' ') || (*file == '\t')) {
1819         file++;
1820     }
1821
1822     if (*file == '\0') {
1823         Parse_Error(PARSE_FATAL,
1824                      "Filename missing from \"include\"");
1825         return;
1826     }
1827
1828     /*
1829      * Skip to end of line or next whitespace
1830      */
1831     for (cp = file; *cp && *cp != '\n' && *cp != '\t' && *cp != ' '; cp++) {
1832         continue;
1833     }
1834
1835     *cp = '\0';
1836
1837     /*
1838      * Substitute for any variables in the file name before trying to
1839      * find the thing.
1840      */
1841     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
1842
1843     /*
1844      * Now we know the file's name, we attempt to find the durn thing.
1845      * Search for it first on the -I search path, then on the .PATH
1846      * search path, if not found in a -I directory.
1847      */
1848     fullname = Dir_FindFile(file, &parseIncPath);
1849     if (fullname == NULL) {
1850         fullname = Dir_FindFile(file, &dirSearchPath);
1851     }
1852
1853     if (fullname == NULL) {
1854         /*
1855          * Still haven't found the makefile. Look for it on the system
1856          * path as a last resort.
1857          */
1858         fullname = Dir_FindFile(file, &sysIncPath);
1859     }
1860
1861     if (fullname == NULL) {
1862         Parse_Error(PARSE_FATAL, "Could not find %s", file);
1863         return;
1864     }
1865
1866     /*
1867      * Once we find the absolute path to the file, we get to save all the
1868      * state from the current file before we can start reading this
1869      * include file. The state is stored in an IFile structure which
1870      * is placed on a list with other IFile structures. The list makes
1871      * a very nice stack to track how we got here...
1872      */
1873     oldFile = emalloc(sizeof(IFile));
1874     memcpy(oldFile, &curFile, sizeof(IFile));
1875
1876     Lst_AtFront(&includes, oldFile);
1877
1878     /*
1879      * Once the previous state has been saved, we can get down to reading
1880      * the new file. We set up the name of the file to be the absolute
1881      * name of the include file so error messages refer to the right
1882      * place. Naturally enough, we start reading at line number 0.
1883      */
1884     curFile.fname = fullname;
1885     curFile.lineno = 0;
1886
1887     curFile.F = fopen(fullname, "r");
1888     curFile.p = NULL;
1889     if (curFile.F == NULL) {
1890         Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
1891         /*
1892          * Pop to previous file
1893          */
1894         ParseEOF(1);
1895     } else {
1896         Var_Append(".MAKEFILE_LIST", fullname, VAR_GLOBAL);
1897     }
1898 }
1899 #endif
1900
1901 /*-
1902  *---------------------------------------------------------------------
1903  * ParseEOF  --
1904  *      Called when EOF is reached in the current file. If we were reading
1905  *      an include file, the includes stack is popped and things set up
1906  *      to go back to reading the previous file at the previous location.
1907  *
1908  * Results:
1909  *      CONTINUE if there's more to do. DONE if not.
1910  *
1911  * Side Effects:
1912  *      The old curFile.F is closed. The includes list is shortened.
1913  *      curFile.lineno, curFile.F, and curFile.fname are changed if
1914  *      CONTINUE is returned.
1915  *---------------------------------------------------------------------
1916  */
1917 static int
1918 ParseEOF(int opened)
1919 {
1920     IFile     *ifile;   /* the state on the top of the includes stack */
1921
1922     if (Lst_IsEmpty(&includes)) {
1923         Var_Append(".MAKEFILE_LIST", "..", VAR_GLOBAL);
1924         return (DONE);
1925     }
1926
1927     ifile = Lst_DeQueue(&includes);
1928     free(curFile.fname);
1929     if (opened && curFile.F) {
1930         fclose(curFile.F);
1931         Var_Append(".MAKEFILE_LIST", "..", VAR_GLOBAL);
1932     }
1933     if (curFile.p) {
1934         free(curFile.p->str);
1935         free(curFile.p);
1936     }
1937     memcpy(&curFile, ifile, sizeof(IFile));
1938     free(ifile);
1939     return (CONTINUE);
1940 }
1941
1942 /*-
1943  *---------------------------------------------------------------------
1944  * ParseReadc  --
1945  *      Read a character from the current file
1946  *
1947  * Results:
1948  *      The character that was read
1949  *
1950  * Side Effects:
1951  *---------------------------------------------------------------------
1952  */
1953 static int
1954 ParseReadc(void)
1955 {
1956
1957     if (curFile.F)
1958         return (fgetc(curFile.F));
1959
1960     if (curFile.p && *curFile.p->ptr)
1961         return (*curFile.p->ptr++);
1962     return (EOF);
1963 }
1964
1965
1966 /*-
1967  *---------------------------------------------------------------------
1968  * ParseUnreadc  --
1969  *      Put back a character to the current file
1970  *
1971  * Results:
1972  *      None.
1973  *
1974  * Side Effects:
1975  *---------------------------------------------------------------------
1976  */
1977 static void
1978 ParseUnreadc(int c)
1979 {
1980
1981     if (curFile.F) {
1982         ungetc(c, curFile.F);
1983         return;
1984     }
1985     if (curFile.p) {
1986         *--(curFile.p->ptr) = c;
1987         return;
1988     }
1989 }
1990
1991
1992 /* ParseSkipLine():
1993  *      Grab the next line unless it begins with a dot (`.') and we're told to
1994  *      ignore such lines.
1995  */
1996 static char *
1997 ParseSkipLine(int skip, int keep_newline)
1998 {
1999     char *line;
2000     int c, lastc;
2001     size_t lineLength = 0;
2002     Buffer buf;
2003
2004     buf = Buf_Init(MAKE_BSIZE);
2005
2006     do {
2007         Buf_Discard(buf, lineLength);
2008         lastc = '\0';
2009
2010         while (((c = ParseReadc()) != '\n' || lastc == '\\')
2011                && c != EOF) {
2012             if (skip && c == '#' && lastc != '\\') {
2013                 /* let a comment be terminated even by an escaped \n.
2014                  * This is consistent to comment handling in ParseReadLine */
2015                 while ((c = ParseReadc()) != '\n' && c != EOF)
2016                     ;
2017                 break;
2018             }
2019             if (c == '\n') {
2020                 if (keep_newline)
2021                     Buf_AddByte(buf, (Byte)c);
2022                 else
2023                     Buf_ReplaceLastByte(buf, (Byte)' ');
2024                 curFile.lineno++;
2025
2026                 while ((c = ParseReadc()) == ' ' || c == '\t')
2027                     continue;
2028
2029                 if (c == EOF)
2030                     break;
2031             }
2032
2033             Buf_AddByte(buf, (Byte)c);
2034             lastc = c;
2035         }
2036
2037         if (c == EOF) {
2038             Parse_Error(PARSE_FATAL, "Unclosed conditional/for loop");
2039             Buf_Destroy(buf, TRUE);
2040             return (NULL);
2041         }
2042
2043         curFile.lineno++;
2044         Buf_AddByte(buf, (Byte)'\0');
2045         line = (char *)Buf_GetAll(buf, &lineLength);
2046     } while (skip == 1 && line[0] != '.');
2047
2048     Buf_Destroy(buf, FALSE);
2049     return (line);
2050 }
2051
2052
2053 /*-
2054  *---------------------------------------------------------------------
2055  * ParseReadLine --
2056  *      Read an entire line from the input file. Called only by Parse_File.
2057  *      To facilitate escaped newlines and what have you, a character is
2058  *      buffered in 'lastc', which is '\0' when no characters have been
2059  *      read. When we break out of the loop, c holds the terminating
2060  *      character and lastc holds a character that should be added to
2061  *      the line (unless we don't read anything but a terminator).
2062  *
2063  * Results:
2064  *      A line w/o its newline
2065  *
2066  * Side Effects:
2067  *      Only those associated with reading a character
2068  *---------------------------------------------------------------------
2069  */
2070 static char *
2071 ParseReadLine(void)
2072 {
2073     Buffer        buf;          /* Buffer for current line */
2074     int           c;            /* the current character */
2075     int           lastc;        /* The most-recent character */
2076     Boolean       semiNL;       /* treat semi-colons as newlines */
2077     Boolean       ignDepOp;     /* TRUE if should ignore dependency operators
2078                                  * for the purposes of setting semiNL */
2079     Boolean       ignComment;   /* TRUE if should ignore comments (in a
2080                                  * shell command */
2081     char          *line;        /* Result */
2082     char          *ep;          /* to strip trailing blanks */
2083     size_t lineLength;          /* Length of result */
2084     int           lineno;       /* Saved line # */
2085
2086     semiNL = FALSE;
2087     ignDepOp = FALSE;
2088     ignComment = FALSE;
2089
2090     /*
2091      * Handle special-characters at the beginning of the line. Either a
2092      * leading tab (shell command) or pound-sign (possible conditional)
2093      * forces us to ignore comments and dependency operators and treat
2094      * semi-colons as semi-colons (by leaving semiNL FALSE). This also
2095      * discards completely blank lines.
2096      */
2097     for (;;) {
2098         c = ParseReadc();
2099
2100         if (c == '\t') {
2101             ignComment = ignDepOp = TRUE;
2102             break;
2103         } else if (c == '\n') {
2104             curFile.lineno++;
2105         } else if (c == '#') {
2106             ParseUnreadc(c);
2107             break;
2108         } else {
2109             /*
2110              * Anything else breaks out without doing anything
2111              */
2112             break;
2113         }
2114     }
2115
2116     if (c != EOF) {
2117         lastc = c;
2118         buf = Buf_Init(MAKE_BSIZE);
2119
2120         while (((c = ParseReadc()) != '\n' || (lastc == '\\')) &&
2121                (c != EOF))
2122         {
2123 test_char:
2124             switch (c) {
2125             case '\n':
2126                 /*
2127                  * Escaped newline: read characters until a non-space or an
2128                  * unescaped newline and replace them all by a single space.
2129                  * This is done by storing the space over the backslash and
2130                  * dropping through with the next nonspace. If it is a
2131                  * semi-colon and semiNL is TRUE, it will be recognized as a
2132                  * newline in the code below this...
2133                  */
2134                 curFile.lineno++;
2135                 lastc = ' ';
2136                 while ((c = ParseReadc()) == ' ' || c == '\t') {
2137                     continue;
2138                 }
2139                 if (c == EOF || c == '\n') {
2140                     goto line_read;
2141                 } else {
2142                     /*
2143                      * Check for comments, semiNL's, etc. -- easier than
2144                      * ParseUnreadc(c); continue;
2145                      */
2146                     goto test_char;
2147                 }
2148                 /*NOTREACHED*/
2149                 break;
2150
2151             case ';':
2152                 /*
2153                  * Semi-colon: Need to see if it should be interpreted as a
2154                  * newline
2155                  */
2156                 if (semiNL) {
2157                     /*
2158                      * To make sure the command that may be following this
2159                      * semi-colon begins with a tab, we push one back into the
2160                      * input stream. This will overwrite the semi-colon in the
2161                      * buffer. If there is no command following, this does no
2162                      * harm, since the newline remains in the buffer and the
2163                      * whole line is ignored.
2164                      */
2165                     ParseUnreadc('\t');
2166                     goto line_read;
2167                 }
2168                 break;
2169             case '=':
2170                 if (!semiNL) {
2171                     /*
2172                      * Haven't seen a dependency operator before this, so this
2173                      * must be a variable assignment -- don't pay attention to
2174                      * dependency operators after this.
2175                      */
2176                     ignDepOp = TRUE;
2177                 } else if (lastc == ':' || lastc == '!') {
2178                     /*
2179                      * Well, we've seen a dependency operator already, but it
2180                      * was the previous character, so this is really just an
2181                      * expanded variable assignment. Revert semi-colons to
2182                      * being just semi-colons again and ignore any more
2183                      * dependency operators.
2184                      *
2185                      * XXX: Note that a line like "foo : a:=b" will blow up,
2186                      * but who'd write a line like that anyway?
2187                      */
2188                     ignDepOp = TRUE;
2189                     semiNL = FALSE;
2190                 }
2191                 break;
2192             case '#':
2193                 if (!ignComment) {
2194                     if (lastc != '\\') {
2195                         /*
2196                          * If the character is a hash mark and it isn't escaped
2197                          * (or we're being compatible), the thing is a comment.
2198                          * Skip to the end of the line.
2199                          */
2200                         do {
2201                             c = ParseReadc();
2202                         } while ((c != '\n') && (c != EOF));
2203                         goto line_read;
2204                     } else {
2205                         /*
2206                          * Don't add the backslash. Just let the # get copied
2207                          * over.
2208                          */
2209                         lastc = c;
2210                         continue;
2211                     }
2212                 }
2213                 break;
2214             case ':':
2215             case '!':
2216                 if (!ignDepOp && (c == ':' || c == '!')) {
2217                     /*
2218                      * A semi-colon is recognized as a newline only on
2219                      * dependency lines. Dependency lines are lines with a
2220                      * colon or an exclamation point. Ergo...
2221                      */
2222                     semiNL = TRUE;
2223                 }
2224                 break;
2225             default:
2226                 break;
2227             }
2228             /*
2229              * Copy in the previous character and save this one in lastc.
2230              */
2231             Buf_AddByte(buf, (Byte)lastc);
2232             lastc = c;
2233
2234         }
2235     line_read:
2236         curFile.lineno++;
2237
2238         if (lastc != '\0') {
2239             Buf_AddByte(buf, (Byte)lastc);
2240         }
2241         Buf_AddByte(buf, (Byte)'\0');
2242         line = (char *)Buf_GetAll(buf, &lineLength);
2243         Buf_Destroy(buf, FALSE);
2244
2245         /*
2246          * Strip trailing blanks and tabs from the line.
2247          * Do not strip a blank or tab that is preceded by
2248          * a '\'
2249          */
2250         ep = line;
2251         while (*ep)
2252             ++ep;
2253         while (ep > line + 1 && (ep[-1] == ' ' || ep[-1] == '\t')) {
2254             if (ep > line + 1 && ep[-2] == '\\')
2255                 break;
2256             --ep;
2257         }
2258         *ep = 0;
2259
2260         if (line[0] == '.') {
2261             /*
2262              * The line might be a conditional. Ask the conditional module
2263              * about it and act accordingly
2264              */
2265             switch (Cond_Eval(line)) {
2266             case COND_SKIP:
2267                 /*
2268                  * Skip to next conditional that evaluates to COND_PARSE.
2269                  */
2270                 do {
2271                     free(line);
2272                     line = ParseSkipLine(1, 0);
2273                 } while (line && Cond_Eval(line) != COND_PARSE);
2274                 if (line == NULL)
2275                     break;
2276                 /*FALLTHRU*/
2277             case COND_PARSE:
2278                 free(line);
2279                 line = ParseReadLine();
2280                 break;
2281             case COND_INVALID:
2282                 if (For_Eval(line)) {
2283                     int ok;
2284                     free(line);
2285                     lineno = curFile.lineno;
2286                     do {
2287                         /*
2288                          * Skip after the matching end
2289                          */
2290                         line = ParseSkipLine(0, 1);
2291                         if (line == NULL) {
2292                             Parse_Error(PARSE_FATAL,
2293                                      "Unexpected end of file in for loop.\n");
2294                             break;
2295                         }
2296                         ok = For_Eval(line);
2297                         free(line);
2298                     }
2299                     while (ok);
2300                     if (line != NULL)
2301                         For_Run(lineno);
2302                     line = ParseReadLine();
2303                 }
2304                 break;
2305             default:
2306                 break;
2307             }
2308         }
2309         return (line);
2310
2311     } else {
2312         /*
2313          * Hit end-of-file, so return a NULL line to indicate this.
2314          */
2315         return (NULL);
2316     }
2317 }
2318
2319 /*-
2320  *-----------------------------------------------------------------------
2321  * ParseFinishLine --
2322  *      Handle the end of a dependency group.
2323  *
2324  * Results:
2325  *      Nothing.
2326  *
2327  * Side Effects:
2328  *      inLine set FALSE. 'targets' list destroyed.
2329  *
2330  *-----------------------------------------------------------------------
2331  */
2332 static void
2333 ParseFinishLine(void)
2334 {
2335
2336     if (inLine) {
2337         Lst_ForEach(&targets, Suff_EndTransform, NULL);
2338         Lst_Destroy(&targets, ParseHasCommands);
2339         inLine = FALSE;
2340     }
2341 }
2342
2343 static char *
2344 stripvarname(char *cp)
2345 {
2346     char *cp2;
2347
2348     while (isspace((unsigned char)*cp))
2349         ++cp;
2350     cp2 = cp;
2351     while (*cp2 && !isspace((unsigned char)*cp2))
2352         ++cp2;
2353     *cp2 = 0;
2354     return(cp);
2355 }
2356
2357
2358 /*-
2359  *---------------------------------------------------------------------
2360  * Parse_File --
2361  *      Parse a file into its component parts, incorporating it into the
2362  *      current dependency graph. This is the main function and controls
2363  *      almost every other function in this module
2364  *
2365  * Results:
2366  *      None
2367  *
2368  * Side Effects:
2369  *      Loads. Nodes are added to the list of all targets, nodes and links
2370  *      are added to the dependency graph. etc. etc. etc.
2371  *---------------------------------------------------------------------
2372  */
2373 void
2374 Parse_File(char *name, FILE *stream)
2375 {
2376     char          *cp,          /* pointer into the line */
2377                   *line;        /* the line we're working on */
2378
2379     inLine = FALSE;
2380     curFile.fname = name;
2381     curFile.F = stream;
2382     curFile.lineno = 0;
2383     fatals = 0;
2384
2385     Var_Append(".MAKEFILE_LIST", name, VAR_GLOBAL);
2386
2387     do {
2388         while ((line = ParseReadLine()) != NULL) {
2389             if (*line == '.') {
2390                 /*
2391                  * Lines that begin with the special character are either
2392                  * include or undef directives.
2393                  */
2394                 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2395                     continue;
2396                 }
2397                 if (strncmp(cp, "include", 7) == 0) {
2398                     ParseDoInclude (cp + 7);
2399                     goto nextLine;
2400                 } else if (strncmp(cp, "error", 5) == 0) {
2401                     ParseDoError(cp + 5);
2402                     goto nextLine;
2403                 } else if (strncmp(cp, "warning", 7) == 0) {
2404                     ParseDoWarning(cp + 7);
2405                     goto nextLine;
2406                 } else if (strncmp(cp, "undef", 5) == 0) {
2407                     cp = stripvarname(cp + 5);
2408                     cp = Var_Subst(NULL, cp, VAR_CMD, FALSE);
2409                     Var_Delete(cp, VAR_GLOBAL);
2410                     goto nextLine;
2411                 } else if (strncmp(cp, "makeenv", 7) == 0) {
2412                     cp = stripvarname(cp + 7);
2413                     Var_SetEnv(cp, VAR_GLOBAL);
2414                     goto nextLine;
2415                 }
2416             }
2417             if (*line == '#') {
2418                 /* If we're this far, the line must be a comment. */
2419                 goto nextLine;
2420             }
2421
2422             if (*line == '\t') {
2423                 /*
2424                  * If a line starts with a tab, it can only hope to be
2425                  * a creation command.
2426                  */
2427                 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2428                     continue;
2429                 }
2430                 if (*cp) {
2431                     if (inLine) {
2432                         /*
2433                          * So long as it's not a blank line and we're actually
2434                          * in a dependency spec, add the command to the list of
2435                          * commands of all targets in the dependency spec
2436                          */
2437                         Lst_ForEach(&targets, ParseAddCmd, cp);
2438                         continue;
2439                     } else {
2440                         Parse_Error(PARSE_FATAL,
2441                                      "Unassociated shell command \"%s\"",
2442                                      cp);
2443                     }
2444                 }
2445 #ifdef SYSVINCLUDE
2446             } else if (strncmp(line, "include", 7) == 0 &&
2447                        isspace((unsigned char)line[7]) &&
2448                        strchr(line, ':') == NULL) {
2449                 /*
2450                  * It's an S3/S5-style "include".
2451                  */
2452                 ParseTraditionalInclude(line + 7);
2453                 goto nextLine;
2454 #endif
2455             } else if (Parse_IsVar(line)) {
2456                 ParseFinishLine();
2457                 Parse_DoVar(line, VAR_GLOBAL);
2458             } else {
2459                 /*
2460                  * We now know it's a dependency line so it needs to have all
2461                  * variables expanded before being parsed. Tell the variable
2462                  * module to complain if some variable is undefined...
2463                  * To make life easier on novices, if the line is indented we
2464                  * first make sure the line has a dependency operator in it.
2465                  * If it doesn't have an operator and we're in a dependency
2466                  * line's script, we assume it's actually a shell command
2467                  * and add it to the current list of targets.
2468                  */
2469                 cp = line;
2470                 if (isspace((unsigned char)line[0])) {
2471                     while ((*cp != '\0') && isspace((unsigned char)*cp)) {
2472                         cp++;
2473                     }
2474                     if (*cp == '\0') {
2475                         goto nextLine;
2476                     }
2477                 }
2478
2479                 ParseFinishLine();
2480
2481                 cp = Var_Subst(NULL, line, VAR_CMD, TRUE);
2482                 free(line);
2483                 line = cp;
2484
2485                 /*
2486                  * Need a non-circular list for the target nodes
2487                  */
2488                 Lst_Destroy(&targets, NOFREE);
2489                 inLine = TRUE;
2490
2491                 ParseDoDependency (line);
2492             }
2493
2494             nextLine:
2495
2496             free(line);
2497         }
2498         /*
2499          * Reached EOF, but it may be just EOF of an include file...
2500          */
2501     } while (ParseEOF(1) == CONTINUE);
2502
2503     /*
2504      * Make sure conditionals are clean
2505      */
2506     Cond_End();
2507
2508     if (fatals)
2509         errx(1, "fatal errors encountered -- cannot continue");
2510 }
2511
2512 /*-
2513  *---------------------------------------------------------------------
2514  * Parse_Init --
2515  *      initialize the parsing module
2516  *
2517  * Results:
2518  *      none
2519  *
2520  * Side Effects:
2521  *      the parseIncPath list is initialized...
2522  *---------------------------------------------------------------------
2523  */
2524 void
2525 Parse_Init(void)
2526 {
2527
2528     mainNode = NULL;
2529 }
2530
2531 void
2532 Parse_End(void)
2533 {
2534
2535     Lst_Destroy(&targets, NOFREE);
2536     Lst_Destroy(&sysIncPath, Dir_Destroy);
2537     Lst_Destroy(&parseIncPath, Dir_Destroy);
2538     Lst_Destroy(&includes, NOFREE);     /* Should be empty now */
2539 }
2540
2541
2542 /*-
2543  *-----------------------------------------------------------------------
2544  * Parse_MainName --
2545  *      Return a Lst of the main target to create for main()'s sake. If
2546  *      no such target exists, we Punt with an obnoxious error message.
2547  *
2548  * Results:
2549  *      A Lst of the single node to create.
2550  *
2551  * Side Effects:
2552  *      None.
2553  *
2554  *-----------------------------------------------------------------------
2555  */
2556 void
2557 Parse_MainName(Lst *listmain)
2558 {
2559
2560     if (mainNode == NULL) {
2561         Punt("no target to make.");
2562         /*NOTREACHED*/
2563     } else if (mainNode->type & OP_DOUBLEDEP) {
2564         Lst_AtEnd(listmain, mainNode);
2565         Lst_Concat(listmain, &mainNode->cohorts, LST_CONCNEW);
2566     }
2567     else
2568         Lst_AtEnd(listmain, mainNode);
2569 }