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