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