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