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