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