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