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