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