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