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