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