]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bmake/parse.c
Merge ACPICA 20130418.
[FreeBSD/FreeBSD.git] / contrib / bmake / parse.c
1 /*      $NetBSD: parse.c,v 1.188 2013/03/22 16:07:59 sjg Exp $  */
2
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *      The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *      This product includes software developed by the University of
53  *      California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: parse.c,v 1.188 2013/03/22 16:07:59 sjg Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)parse.c     8.3 (Berkeley) 3/19/94";
78 #else
79 __RCSID("$NetBSD: parse.c,v 1.188 2013/03/22 16:07:59 sjg Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85  * parse.c --
86  *      Functions to parse a makefile.
87  *
88  *      One function, Parse_Init, must be called before any functions
89  *      in this module are used. After that, the function Parse_File is the
90  *      main entry point and controls most of the other functions in this
91  *      module.
92  *
93  *      Most important structures are kept in Lsts. Directories for
94  *      the .include "..." function are kept in the 'parseIncPath' Lst, while
95  *      those for the .include <...> are kept in the 'sysIncPath' Lst. The
96  *      targets currently being defined are kept in the 'targets' Lst.
97  *
98  *      The variables 'fname' and 'lineno' are used to track the name
99  *      of the current file and the line number in that file so that error
100  *      messages can be more meaningful.
101  *
102  * Interface:
103  *      Parse_Init                  Initialization function which must be
104  *                                  called before anything else in this module
105  *                                  is used.
106  *
107  *      Parse_End                   Cleanup the module
108  *
109  *      Parse_File                  Function used to parse a makefile. It must
110  *                                  be given the name of the file, which should
111  *                                  already have been opened, and a function
112  *                                  to call to read a character from the file.
113  *
114  *      Parse_IsVar                 Returns TRUE if the given line is a
115  *                                  variable assignment. Used by MainParseArgs
116  *                                  to determine if an argument is a target
117  *                                  or a variable assignment. Used internally
118  *                                  for pretty much the same thing...
119  *
120  *      Parse_Error                 Function called when an error occurs in
121  *                                  parsing. Used by the variable and
122  *                                  conditional modules.
123  *      Parse_MainName              Returns a Lst of the main target to create.
124  */
125
126 #include <sys/types.h>
127 #include <sys/stat.h>
128 #include <assert.h>
129 #include <ctype.h>
130 #include <errno.h>
131 #include <fcntl.h>
132 #include <stdarg.h>
133 #include <stdio.h>
134
135 #include "make.h"
136 #include "hash.h"
137 #include "dir.h"
138 #include "job.h"
139 #include "buf.h"
140 #include "pathnames.h"
141
142 #ifdef HAVE_MMAP
143 #include <sys/mman.h>
144
145 #ifndef MAP_COPY
146 #define MAP_COPY MAP_PRIVATE
147 #endif
148 #ifndef MAP_FILE
149 #define MAP_FILE 0
150 #endif
151 #endif
152
153 ////////////////////////////////////////////////////////////
154 // types and constants
155
156 /*
157  * Structure for a file being read ("included file")
158  */
159 typedef struct IFile {
160     const char      *fname;         /* name of file */
161     int             lineno;         /* current line number in file */
162     int             first_lineno;   /* line number of start of text */
163     int             cond_depth;     /* 'if' nesting when file opened */
164     char            *P_str;         /* point to base of string buffer */
165     char            *P_ptr;         /* point to next char of string buffer */
166     char            *P_end;         /* point to the end of string buffer */
167     char            *(*nextbuf)(void *, size_t *); /* Function to get more data */
168     void            *nextbuf_arg;   /* Opaque arg for nextbuf() */
169     struct loadedfile *lf;          /* loadedfile object, if any */
170 } IFile;
171
172
173 /*
174  * These values are returned by ParseEOF to tell Parse_File whether to
175  * CONTINUE parsing, i.e. it had only reached the end of an include file,
176  * or if it's DONE.
177  */
178 #define CONTINUE        1
179 #define DONE            0
180
181 /*
182  * Tokens for target attributes
183  */
184 typedef enum {
185     Begin,          /* .BEGIN */
186     Default,        /* .DEFAULT */
187     End,            /* .END */
188     dotError,       /* .ERROR */
189     Ignore,         /* .IGNORE */
190     Includes,       /* .INCLUDES */
191     Interrupt,      /* .INTERRUPT */
192     Libs,           /* .LIBS */
193     Meta,           /* .META */
194     MFlags,         /* .MFLAGS or .MAKEFLAGS */
195     Main,           /* .MAIN and we don't have anything user-specified to
196                      * make */
197     NoExport,       /* .NOEXPORT */
198     NoMeta,         /* .NOMETA */
199     NoMetaCmp,      /* .NOMETA_CMP */
200     NoPath,         /* .NOPATH */
201     Not,            /* Not special */
202     NotParallel,    /* .NOTPARALLEL */
203     Null,           /* .NULL */
204     ExObjdir,       /* .OBJDIR */
205     Order,          /* .ORDER */
206     Parallel,       /* .PARALLEL */
207     ExPath,         /* .PATH */
208     Phony,          /* .PHONY */
209 #ifdef POSIX
210     Posix,          /* .POSIX */
211 #endif
212     Precious,       /* .PRECIOUS */
213     ExShell,        /* .SHELL */
214     Silent,         /* .SILENT */
215     SingleShell,    /* .SINGLESHELL */
216     Stale,          /* .STALE */
217     Suffixes,       /* .SUFFIXES */
218     Wait,           /* .WAIT */
219     Attribute       /* Generic attribute */
220 } ParseSpecial;
221
222 /*
223  * Other tokens
224  */
225 #define LPAREN  '('
226 #define RPAREN  ')'
227
228
229 ////////////////////////////////////////////////////////////
230 // result data
231
232 /*
233  * The main target to create. This is the first target on the first
234  * dependency line in the first makefile.
235  */
236 static GNode *mainNode;
237
238 ////////////////////////////////////////////////////////////
239 // eval state
240
241 /* targets we're working on */
242 static Lst targets;
243
244 #ifdef CLEANUP
245 /* command lines for targets */
246 static Lst targCmds;
247 #endif
248
249 /*
250  * specType contains the SPECial TYPE of the current target. It is
251  * Not if the target is unspecial. If it *is* special, however, the children
252  * are linked as children of the parent but not vice versa. This variable is
253  * set in ParseDoDependency
254  */
255 static ParseSpecial specType;
256
257 /*
258  * Predecessor node for handling .ORDER. Initialized to NULL when .ORDER
259  * seen, then set to each successive source on the line.
260  */
261 static GNode    *predecessor;
262
263 ////////////////////////////////////////////////////////////
264 // parser state
265
266 /* true if currently in a dependency line or its commands */
267 static Boolean inLine;
268
269 /* number of fatal errors */
270 static int fatals = 0;
271
272 /*
273  * Variables for doing includes
274  */
275
276 /* current file being read */
277 static IFile *curFile;
278
279 /* stack of IFiles generated by .includes */
280 static Lst includes;
281
282 /* include paths (lists of directories) */
283 Lst parseIncPath;       /* dirs for "..." includes */
284 Lst sysIncPath;         /* dirs for <...> includes */
285 Lst defIncPath;         /* default for sysIncPath */
286
287 ////////////////////////////////////////////////////////////
288 // parser tables
289
290 /*
291  * The parseKeywords table is searched using binary search when deciding
292  * if a target or source is special. The 'spec' field is the ParseSpecial
293  * type of the keyword ("Not" if the keyword isn't special as a target) while
294  * the 'op' field is the operator to apply to the list of targets if the
295  * keyword is used as a source ("0" if the keyword isn't special as a source)
296  */
297 static const struct {
298     const char   *name;         /* Name of keyword */
299     ParseSpecial  spec;         /* Type when used as a target */
300     int           op;           /* Operator when used as a source */
301 } parseKeywords[] = {
302 { ".BEGIN",       Begin,        0 },
303 { ".DEFAULT",     Default,      0 },
304 { ".END",         End,          0 },
305 { ".ERROR",       dotError,     0 },
306 { ".EXEC",        Attribute,    OP_EXEC },
307 { ".IGNORE",      Ignore,       OP_IGNORE },
308 { ".INCLUDES",    Includes,     0 },
309 { ".INTERRUPT",   Interrupt,    0 },
310 { ".INVISIBLE",   Attribute,    OP_INVISIBLE },
311 { ".JOIN",        Attribute,    OP_JOIN },
312 { ".LIBS",        Libs,         0 },
313 { ".MADE",        Attribute,    OP_MADE },
314 { ".MAIN",        Main,         0 },
315 { ".MAKE",        Attribute,    OP_MAKE },
316 { ".MAKEFLAGS",   MFlags,       0 },
317 { ".META",        Meta,         OP_META },
318 { ".MFLAGS",      MFlags,       0 },
319 { ".NOMETA",      NoMeta,       OP_NOMETA },
320 { ".NOMETA_CMP",  NoMetaCmp,    OP_NOMETA_CMP },
321 { ".NOPATH",      NoPath,       OP_NOPATH },
322 { ".NOTMAIN",     Attribute,    OP_NOTMAIN },
323 { ".NOTPARALLEL", NotParallel,  0 },
324 { ".NO_PARALLEL", NotParallel,  0 },
325 { ".NULL",        Null,         0 },
326 { ".OBJDIR",      ExObjdir,     0 },
327 { ".OPTIONAL",    Attribute,    OP_OPTIONAL },
328 { ".ORDER",       Order,        0 },
329 { ".PARALLEL",    Parallel,     0 },
330 { ".PATH",        ExPath,       0 },
331 { ".PHONY",       Phony,        OP_PHONY },
332 #ifdef POSIX
333 { ".POSIX",       Posix,        0 },
334 #endif
335 { ".PRECIOUS",    Precious,     OP_PRECIOUS },
336 { ".RECURSIVE",   Attribute,    OP_MAKE },
337 { ".SHELL",       ExShell,      0 },
338 { ".SILENT",      Silent,       OP_SILENT },
339 { ".SINGLESHELL", SingleShell,  0 },
340 { ".STALE",       Stale,        0 },
341 { ".SUFFIXES",    Suffixes,     0 },
342 { ".USE",         Attribute,    OP_USE },
343 { ".USEBEFORE",   Attribute,    OP_USEBEFORE },
344 { ".WAIT",        Wait,         0 },
345 };
346
347 ////////////////////////////////////////////////////////////
348 // local functions
349
350 static int ParseIsEscaped(const char *, const char *);
351 static void ParseErrorInternal(const char *, size_t, int, const char *, ...)
352     MAKE_ATTR_PRINTFLIKE(4,5);
353 static void ParseVErrorInternal(FILE *, const char *, size_t, int, const char *, va_list)
354     MAKE_ATTR_PRINTFLIKE(5, 0);
355 static int ParseFindKeyword(const char *);
356 static int ParseLinkSrc(void *, void *);
357 static int ParseDoOp(void *, void *);
358 static void ParseDoSrc(int, const char *);
359 static int ParseFindMain(void *, void *);
360 static int ParseAddDir(void *, void *);
361 static int ParseClearPath(void *, void *);
362 static void ParseDoDependency(char *);
363 static int ParseAddCmd(void *, void *);
364 static void ParseHasCommands(void *);
365 static void ParseDoInclude(char *);
366 static void ParseSetParseFile(const char *);
367 #ifdef SYSVINCLUDE
368 static void ParseTraditionalInclude(char *);
369 #endif
370 #ifdef GMAKEEXPORT
371 static void ParseGmakeExport(char *);
372 #endif
373 static int ParseEOF(void);
374 static char *ParseReadLine(void);
375 static void ParseFinishLine(void);
376 static void ParseMark(GNode *);
377
378 ////////////////////////////////////////////////////////////
379 // file loader
380
381 struct loadedfile {
382         const char *path;               /* name, for error reports */
383         char *buf;                      /* contents buffer */
384         size_t len;                     /* length of contents */
385         size_t maplen;                  /* length of mmap area, or 0 */
386         Boolean used;                   /* XXX: have we used the data yet */
387 };
388
389 /*
390  * Constructor/destructor for loadedfile
391  */
392 static struct loadedfile *
393 loadedfile_create(const char *path)
394 {
395         struct loadedfile *lf;
396
397         lf = bmake_malloc(sizeof(*lf));
398         lf->path = (path == NULL ? "(stdin)" : path);
399         lf->buf = NULL;
400         lf->len = 0;
401         lf->maplen = 0;
402         lf->used = FALSE;
403         return lf;
404 }
405
406 static void
407 loadedfile_destroy(struct loadedfile *lf)
408 {
409         if (lf->buf != NULL) {
410                 if (lf->maplen > 0) {
411 #ifdef HAVE_MMAP
412                         munmap(lf->buf, lf->maplen);
413 #endif
414                 } else {
415                         free(lf->buf);
416                 }
417         }
418         free(lf);
419 }
420
421 /*
422  * nextbuf() operation for loadedfile, as needed by the weird and twisted
423  * logic below. Once that's cleaned up, we can get rid of lf->used...
424  */
425 static char *
426 loadedfile_nextbuf(void *x, size_t *len)
427 {
428         struct loadedfile *lf = x;
429
430         if (lf->used) {
431                 return NULL;
432         }
433         lf->used = TRUE;
434         *len = lf->len;
435         return lf->buf;
436 }
437
438 /*
439  * Try to get the size of a file.
440  */
441 static ReturnStatus
442 load_getsize(int fd, size_t *ret)
443 {
444         struct stat st;
445
446         if (fstat(fd, &st) < 0) {
447                 return FAILURE;
448         }
449
450         if (!S_ISREG(st.st_mode)) {
451                 return FAILURE;
452         }
453
454         /*
455          * st_size is an off_t, which is 64 bits signed; *ret is
456          * size_t, which might be 32 bits unsigned or 64 bits
457          * unsigned. Rather than being elaborate, just punt on
458          * files that are more than 2^31 bytes. We should never
459          * see a makefile that size in practice...
460          *
461          * While we're at it reject negative sizes too, just in case.
462          */
463         if (st.st_size < 0 || st.st_size > 0x7fffffff) {
464                 return FAILURE;
465         }
466
467         *ret = (size_t) st.st_size;
468         return SUCCESS;
469 }
470
471 /*
472  * Read in a file.
473  *
474  * Until the path search logic can be moved under here instead of
475  * being in the caller in another source file, we need to have the fd
476  * passed in already open. Bleh.
477  *
478  * If the path is NULL use stdin and (to insure against fd leaks)
479  * assert that the caller passed in -1.
480  */
481 static struct loadedfile *
482 loadfile(const char *path, int fd)
483 {
484         struct loadedfile *lf;
485 #ifdef HAVE_MMAP
486         long pagesize;
487 #endif
488         ssize_t result;
489         size_t bufpos;
490
491         lf = loadedfile_create(path);
492
493         if (path == NULL) {
494                 assert(fd == -1);
495                 fd = STDIN_FILENO;
496         } else {
497 #if 0 /* notyet */
498                 fd = open(path, O_RDONLY);
499                 if (fd < 0) {
500                         ...
501                         Error("%s: %s", path, strerror(errno));
502                         exit(1);
503                 }
504 #endif
505         }
506
507 #ifdef HAVE_MMAP
508         if (load_getsize(fd, &lf->len) == SUCCESS) {
509                 /* found a size, try mmap */
510                 pagesize = sysconf(_SC_PAGESIZE);
511                 if (pagesize <= 0) {
512                         pagesize = 0x1000;
513                 }
514                 /* round size up to a page */
515                 lf->maplen = pagesize * ((lf->len + pagesize - 1)/pagesize);
516
517                 /*
518                  * XXX hack for dealing with empty files; remove when
519                  * we're no longer limited by interfacing to the old
520                  * logic elsewhere in this file.
521                  */
522                 if (lf->maplen == 0) {
523                         lf->maplen = pagesize;
524                 }
525
526                 /*
527                  * FUTURE: remove PROT_WRITE when the parser no longer
528                  * needs to scribble on the input.
529                  */
530                 lf->buf = mmap(NULL, lf->maplen, PROT_READ|PROT_WRITE,
531                                MAP_FILE|MAP_COPY, fd, 0);
532                 if (lf->buf != MAP_FAILED) {
533                         /* succeeded */
534                         if (lf->len == lf->maplen && lf->buf[lf->len - 1] != '\n') {
535                                 char *b = malloc(lf->len + 1);
536                                 b[lf->len] = '\n';
537                                 memcpy(b, lf->buf, lf->len++);
538                                 munmap(lf->buf, lf->maplen);
539                                 lf->maplen = 0;
540                                 lf->buf = b;
541                         }
542                         goto done;
543                 }
544         }
545 #endif
546         /* cannot mmap; load the traditional way */
547
548         lf->maplen = 0;
549         lf->len = 1024;
550         lf->buf = bmake_malloc(lf->len);
551
552         bufpos = 0;
553         while (1) {
554                 assert(bufpos <= lf->len);
555                 if (bufpos == lf->len) {
556                         lf->len *= 2;
557                         lf->buf = bmake_realloc(lf->buf, lf->len);
558                 }
559                 result = read(fd, lf->buf + bufpos, lf->len - bufpos);
560                 if (result < 0) {
561                         Error("%s: read error: %s", path, strerror(errno));
562                         exit(1);
563                 }
564                 if (result == 0) {
565                         break;
566                 }
567                 bufpos += result;
568         }
569         assert(bufpos <= lf->len);
570         lf->len = bufpos;
571
572         /* truncate malloc region to actual length (maybe not useful) */
573         if (lf->len > 0) {
574                 lf->buf = bmake_realloc(lf->buf, lf->len);
575         }
576
577 #ifdef HAVE_MMAP
578 done:
579 #endif
580         if (path != NULL) {
581                 close(fd);
582         }
583         return lf;
584 }
585
586 ////////////////////////////////////////////////////////////
587 // old code
588
589 /*-
590  *----------------------------------------------------------------------
591  * ParseIsEscaped --
592  *      Check if the current character is escaped on the current line
593  *
594  * Results:
595  *      0 if the character is not backslash escaped, 1 otherwise
596  *
597  * Side Effects:
598  *      None
599  *----------------------------------------------------------------------
600  */
601 static int
602 ParseIsEscaped(const char *line, const char *c)
603 {
604     int active = 0;
605     for (;;) {
606         if (line == c)
607             return active;
608         if (*--c != '\\')
609             return active;
610         active = !active;
611     }
612 }
613
614 /*-
615  *----------------------------------------------------------------------
616  * ParseFindKeyword --
617  *      Look in the table of keywords for one matching the given string.
618  *
619  * Input:
620  *      str             String to find
621  *
622  * Results:
623  *      The index of the keyword, or -1 if it isn't there.
624  *
625  * Side Effects:
626  *      None
627  *----------------------------------------------------------------------
628  */
629 static int
630 ParseFindKeyword(const char *str)
631 {
632     int    start, end, cur;
633     int    diff;
634
635     start = 0;
636     end = (sizeof(parseKeywords)/sizeof(parseKeywords[0])) - 1;
637
638     do {
639         cur = start + ((end - start) / 2);
640         diff = strcmp(str, parseKeywords[cur].name);
641
642         if (diff == 0) {
643             return (cur);
644         } else if (diff < 0) {
645             end = cur - 1;
646         } else {
647             start = cur + 1;
648         }
649     } while (start <= end);
650     return (-1);
651 }
652
653 /*-
654  * ParseVErrorInternal  --
655  *      Error message abort function for parsing. Prints out the context
656  *      of the error (line number and file) as well as the message with
657  *      two optional arguments.
658  *
659  * Results:
660  *      None
661  *
662  * Side Effects:
663  *      "fatals" is incremented if the level is PARSE_FATAL.
664  */
665 /* VARARGS */
666 static void
667 ParseVErrorInternal(FILE *f, const char *cfname, size_t clineno, int type,
668     const char *fmt, va_list ap)
669 {
670         static Boolean fatal_warning_error_printed = FALSE;
671
672         (void)fprintf(f, "%s: ", progname);
673
674         if (cfname != NULL) {
675                 (void)fprintf(f, "\"");
676                 if (*cfname != '/' && strcmp(cfname, "(stdin)") != 0) {
677                         char *cp;
678                         const char *dir;
679
680                         /*
681                          * Nothing is more annoying than not knowing
682                          * which Makefile is the culprit.
683                          */
684                         dir = Var_Value(".PARSEDIR", VAR_GLOBAL, &cp);
685                         if (dir == NULL || *dir == '\0' ||
686                             (*dir == '.' && dir[1] == '\0'))
687                                 dir = Var_Value(".CURDIR", VAR_GLOBAL, &cp);
688                         if (dir == NULL)
689                                 dir = ".";
690
691                         (void)fprintf(f, "%s/%s", dir, cfname);
692                 } else
693                         (void)fprintf(f, "%s", cfname);
694
695                 (void)fprintf(f, "\" line %d: ", (int)clineno);
696         }
697         if (type == PARSE_WARNING)
698                 (void)fprintf(f, "warning: ");
699         (void)vfprintf(f, fmt, ap);
700         (void)fprintf(f, "\n");
701         (void)fflush(f);
702         if (type == PARSE_FATAL || parseWarnFatal)
703                 fatals += 1;
704         if (parseWarnFatal && !fatal_warning_error_printed) {
705                 Error("parsing warnings being treated as errors");
706                 fatal_warning_error_printed = TRUE;
707         }
708 }
709
710 /*-
711  * ParseErrorInternal  --
712  *      Error function
713  *
714  * Results:
715  *      None
716  *
717  * Side Effects:
718  *      None
719  */
720 /* VARARGS */
721 static void
722 ParseErrorInternal(const char *cfname, size_t clineno, int type,
723     const char *fmt, ...)
724 {
725         va_list ap;
726
727         va_start(ap, fmt);
728         (void)fflush(stdout);
729         ParseVErrorInternal(stderr, cfname, clineno, type, fmt, ap);
730         va_end(ap);
731
732         if (debug_file != stderr && debug_file != stdout) {
733                 va_start(ap, fmt);
734                 ParseVErrorInternal(debug_file, cfname, clineno, type, fmt, ap);
735                 va_end(ap);
736         }
737 }
738
739 /*-
740  * Parse_Error  --
741  *      External interface to ParseErrorInternal; uses the default filename
742  *      Line number.
743  *
744  * Results:
745  *      None
746  *
747  * Side Effects:
748  *      None
749  */
750 /* VARARGS */
751 void
752 Parse_Error(int type, const char *fmt, ...)
753 {
754         va_list ap;
755         const char *fname;
756         size_t lineno;
757
758         if (curFile == NULL) {
759                 fname = NULL;
760                 lineno = 0;
761         } else {
762                 fname = curFile->fname;
763                 lineno = curFile->lineno;
764         }
765
766         va_start(ap, fmt);
767         (void)fflush(stdout);
768         ParseVErrorInternal(stderr, fname, lineno, type, fmt, ap);
769         va_end(ap);
770
771         if (debug_file != stderr && debug_file != stdout) {
772                 va_start(ap, fmt);
773                 ParseVErrorInternal(debug_file, fname, lineno, type, fmt, ap);
774                 va_end(ap);
775         }
776 }
777
778
779 /*
780  * ParseMessage
781  *      Parse a .info .warning or .error directive
782  *
783  *      The input is the line minus the ".".  We substitute
784  *      variables, print the message and exit(1) (for .error) or just print
785  *      a warning if the directive is malformed.
786  */
787 static Boolean
788 ParseMessage(char *line)
789 {
790     int mtype;
791
792     switch(*line) {
793     case 'i':
794         mtype = 0;
795         break;
796     case 'w':
797         mtype = PARSE_WARNING;
798         break;
799     case 'e':
800         mtype = PARSE_FATAL;
801         break;
802     default:
803         Parse_Error(PARSE_WARNING, "invalid syntax: \".%s\"", line);
804         return FALSE;
805     }
806
807     while (isalpha((u_char)*line))
808         line++;
809     if (!isspace((u_char)*line))
810         return FALSE;                   /* not for us */
811     while (isspace((u_char)*line))
812         line++;
813
814     line = Var_Subst(NULL, line, VAR_CMD, 0);
815     Parse_Error(mtype, "%s", line);
816     free(line);
817
818     if (mtype == PARSE_FATAL) {
819         /* Terminate immediately. */
820         exit(1);
821     }
822     return TRUE;
823 }
824
825 /*-
826  *---------------------------------------------------------------------
827  * ParseLinkSrc  --
828  *      Link the parent node to its new child. Used in a Lst_ForEach by
829  *      ParseDoDependency. If the specType isn't 'Not', the parent
830  *      isn't linked as a parent of the child.
831  *
832  * Input:
833  *      pgnp            The parent node
834  *      cgpn            The child node
835  *
836  * Results:
837  *      Always = 0
838  *
839  * Side Effects:
840  *      New elements are added to the parents list of cgn and the
841  *      children list of cgn. the unmade field of pgn is updated
842  *      to reflect the additional child.
843  *---------------------------------------------------------------------
844  */
845 static int
846 ParseLinkSrc(void *pgnp, void *cgnp)
847 {
848     GNode          *pgn = (GNode *)pgnp;
849     GNode          *cgn = (GNode *)cgnp;
850
851     if ((pgn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (pgn->cohorts))
852         pgn = (GNode *)Lst_Datum(Lst_Last(pgn->cohorts));
853     (void)Lst_AtEnd(pgn->children, cgn);
854     if (specType == Not)
855             (void)Lst_AtEnd(cgn->parents, pgn);
856     pgn->unmade += 1;
857     if (DEBUG(PARSE)) {
858         fprintf(debug_file, "# ParseLinkSrc: added child %s - %s\n", pgn->name, cgn->name);
859         Targ_PrintNode(pgn, 0);
860         Targ_PrintNode(cgn, 0);
861     }
862     return (0);
863 }
864
865 /*-
866  *---------------------------------------------------------------------
867  * ParseDoOp  --
868  *      Apply the parsed operator to the given target node. Used in a
869  *      Lst_ForEach call by ParseDoDependency once all targets have
870  *      been found and their operator parsed. If the previous and new
871  *      operators are incompatible, a major error is taken.
872  *
873  * Input:
874  *      gnp             The node to which the operator is to be applied
875  *      opp             The operator to apply
876  *
877  * Results:
878  *      Always 0
879  *
880  * Side Effects:
881  *      The type field of the node is altered to reflect any new bits in
882  *      the op.
883  *---------------------------------------------------------------------
884  */
885 static int
886 ParseDoOp(void *gnp, void *opp)
887 {
888     GNode          *gn = (GNode *)gnp;
889     int             op = *(int *)opp;
890     /*
891      * If the dependency mask of the operator and the node don't match and
892      * the node has actually had an operator applied to it before, and
893      * the operator actually has some dependency information in it, complain.
894      */
895     if (((op & OP_OPMASK) != (gn->type & OP_OPMASK)) &&
896         !OP_NOP(gn->type) && !OP_NOP(op))
897     {
898         Parse_Error(PARSE_FATAL, "Inconsistent operator for %s", gn->name);
899         return (1);
900     }
901
902     if ((op == OP_DOUBLEDEP) && ((gn->type & OP_OPMASK) == OP_DOUBLEDEP)) {
903         /*
904          * If the node was the object of a :: operator, we need to create a
905          * new instance of it for the children and commands on this dependency
906          * line. The new instance is placed on the 'cohorts' list of the
907          * initial one (note the initial one is not on its own cohorts list)
908          * and the new instance is linked to all parents of the initial
909          * instance.
910          */
911         GNode   *cohort;
912
913         /*
914          * Propagate copied bits to the initial node.  They'll be propagated
915          * back to the rest of the cohorts later.
916          */
917         gn->type |= op & ~OP_OPMASK;
918
919         cohort = Targ_FindNode(gn->name, TARG_NOHASH);
920         if (doing_depend)
921             ParseMark(cohort);
922         /*
923          * Make the cohort invisible as well to avoid duplicating it into
924          * other variables. True, parents of this target won't tend to do
925          * anything with their local variables, but better safe than
926          * sorry. (I think this is pointless now, since the relevant list
927          * traversals will no longer see this node anyway. -mycroft)
928          */
929         cohort->type = op | OP_INVISIBLE;
930         (void)Lst_AtEnd(gn->cohorts, cohort);
931         cohort->centurion = gn;
932         gn->unmade_cohorts += 1;
933         snprintf(cohort->cohort_num, sizeof cohort->cohort_num, "#%d",
934                 gn->unmade_cohorts);
935     } else {
936         /*
937          * We don't want to nuke any previous flags (whatever they were) so we
938          * just OR the new operator into the old
939          */
940         gn->type |= op;
941     }
942
943     return (0);
944 }
945
946 /*-
947  *---------------------------------------------------------------------
948  * ParseDoSrc  --
949  *      Given the name of a source, figure out if it is an attribute
950  *      and apply it to the targets if it is. Else decide if there is
951  *      some attribute which should be applied *to* the source because
952  *      of some special target and apply it if so. Otherwise, make the
953  *      source be a child of the targets in the list 'targets'
954  *
955  * Input:
956  *      tOp             operator (if any) from special targets
957  *      src             name of the source to handle
958  *
959  * Results:
960  *      None
961  *
962  * Side Effects:
963  *      Operator bits may be added to the list of targets or to the source.
964  *      The targets may have a new source added to their lists of children.
965  *---------------------------------------------------------------------
966  */
967 static void
968 ParseDoSrc(int tOp, const char *src)
969 {
970     GNode       *gn = NULL;
971     static int wait_number = 0;
972     char wait_src[16];
973
974     if (*src == '.' && isupper ((unsigned char)src[1])) {
975         int keywd = ParseFindKeyword(src);
976         if (keywd != -1) {
977             int op = parseKeywords[keywd].op;
978             if (op != 0) {
979                 Lst_ForEach(targets, ParseDoOp, &op);
980                 return;
981             }
982             if (parseKeywords[keywd].spec == Wait) {
983                 /*
984                  * We add a .WAIT node in the dependency list.
985                  * After any dynamic dependencies (and filename globbing)
986                  * have happened, it is given a dependency on the each
987                  * previous child back to and previous .WAIT node.
988                  * The next child won't be scheduled until the .WAIT node
989                  * is built.
990                  * We give each .WAIT node a unique name (mainly for diag).
991                  */
992                 snprintf(wait_src, sizeof wait_src, ".WAIT_%u", ++wait_number);
993                 gn = Targ_FindNode(wait_src, TARG_NOHASH);
994                 if (doing_depend)
995                     ParseMark(gn);
996                 gn->type = OP_WAIT | OP_PHONY | OP_DEPENDS | OP_NOTMAIN;
997                 Lst_ForEach(targets, ParseLinkSrc, gn);
998                 return;
999             }
1000         }
1001     }
1002
1003     switch (specType) {
1004     case Main:
1005         /*
1006          * If we have noted the existence of a .MAIN, it means we need
1007          * to add the sources of said target to the list of things
1008          * to create. The string 'src' is likely to be free, so we
1009          * must make a new copy of it. Note that this will only be
1010          * invoked if the user didn't specify a target on the command
1011          * line. This is to allow #ifmake's to succeed, or something...
1012          */
1013         (void)Lst_AtEnd(create, bmake_strdup(src));
1014         /*
1015          * Add the name to the .TARGETS variable as well, so the user can
1016          * employ that, if desired.
1017          */
1018         Var_Append(".TARGETS", src, VAR_GLOBAL);
1019         return;
1020
1021     case Order:
1022         /*
1023          * Create proper predecessor/successor links between the previous
1024          * source and the current one.
1025          */
1026         gn = Targ_FindNode(src, TARG_CREATE);
1027         if (doing_depend)
1028             ParseMark(gn);
1029         if (predecessor != NULL) {
1030             (void)Lst_AtEnd(predecessor->order_succ, gn);
1031             (void)Lst_AtEnd(gn->order_pred, predecessor);
1032             if (DEBUG(PARSE)) {
1033                 fprintf(debug_file, "# ParseDoSrc: added Order dependency %s - %s\n",
1034                         predecessor->name, gn->name);
1035                 Targ_PrintNode(predecessor, 0);
1036                 Targ_PrintNode(gn, 0);
1037             }
1038         }
1039         /*
1040          * The current source now becomes the predecessor for the next one.
1041          */
1042         predecessor = gn;
1043         break;
1044
1045     default:
1046         /*
1047          * If the source is not an attribute, we need to find/create
1048          * a node for it. After that we can apply any operator to it
1049          * from a special target or link it to its parents, as
1050          * appropriate.
1051          *
1052          * In the case of a source that was the object of a :: operator,
1053          * the attribute is applied to all of its instances (as kept in
1054          * the 'cohorts' list of the node) or all the cohorts are linked
1055          * to all the targets.
1056          */
1057
1058         /* Find/create the 'src' node and attach to all targets */
1059         gn = Targ_FindNode(src, TARG_CREATE);
1060         if (doing_depend)
1061             ParseMark(gn);
1062         if (tOp) {
1063             gn->type |= tOp;
1064         } else {
1065             Lst_ForEach(targets, ParseLinkSrc, gn);
1066         }
1067         break;
1068     }
1069 }
1070
1071 /*-
1072  *-----------------------------------------------------------------------
1073  * ParseFindMain --
1074  *      Find a real target in the list and set it to be the main one.
1075  *      Called by ParseDoDependency when a main target hasn't been found
1076  *      yet.
1077  *
1078  * Input:
1079  *      gnp             Node to examine
1080  *
1081  * Results:
1082  *      0 if main not found yet, 1 if it is.
1083  *
1084  * Side Effects:
1085  *      mainNode is changed and Targ_SetMain is called.
1086  *
1087  *-----------------------------------------------------------------------
1088  */
1089 static int
1090 ParseFindMain(void *gnp, void *dummy)
1091 {
1092     GNode         *gn = (GNode *)gnp;
1093     if ((gn->type & OP_NOTARGET) == 0) {
1094         mainNode = gn;
1095         Targ_SetMain(gn);
1096         return (dummy ? 1 : 1);
1097     } else {
1098         return (dummy ? 0 : 0);
1099     }
1100 }
1101
1102 /*-
1103  *-----------------------------------------------------------------------
1104  * ParseAddDir --
1105  *      Front-end for Dir_AddDir to make sure Lst_ForEach keeps going
1106  *
1107  * Results:
1108  *      === 0
1109  *
1110  * Side Effects:
1111  *      See Dir_AddDir.
1112  *
1113  *-----------------------------------------------------------------------
1114  */
1115 static int
1116 ParseAddDir(void *path, void *name)
1117 {
1118     (void)Dir_AddDir((Lst) path, (char *)name);
1119     return(0);
1120 }
1121
1122 /*-
1123  *-----------------------------------------------------------------------
1124  * ParseClearPath --
1125  *      Front-end for Dir_ClearPath to make sure Lst_ForEach keeps going
1126  *
1127  * Results:
1128  *      === 0
1129  *
1130  * Side Effects:
1131  *      See Dir_ClearPath
1132  *
1133  *-----------------------------------------------------------------------
1134  */
1135 static int
1136 ParseClearPath(void *path, void *dummy)
1137 {
1138     Dir_ClearPath((Lst) path);
1139     return(dummy ? 0 : 0);
1140 }
1141
1142 /*-
1143  *---------------------------------------------------------------------
1144  * ParseDoDependency  --
1145  *      Parse the dependency line in line.
1146  *
1147  * Input:
1148  *      line            the line to parse
1149  *
1150  * Results:
1151  *      None
1152  *
1153  * Side Effects:
1154  *      The nodes of the sources are linked as children to the nodes of the
1155  *      targets. Some nodes may be created.
1156  *
1157  *      We parse a dependency line by first extracting words from the line and
1158  * finding nodes in the list of all targets with that name. This is done
1159  * until a character is encountered which is an operator character. Currently
1160  * these are only ! and :. At this point the operator is parsed and the
1161  * pointer into the line advanced until the first source is encountered.
1162  *      The parsed operator is applied to each node in the 'targets' list,
1163  * which is where the nodes found for the targets are kept, by means of
1164  * the ParseDoOp function.
1165  *      The sources are read in much the same way as the targets were except
1166  * that now they are expanded using the wildcarding scheme of the C-Shell
1167  * and all instances of the resulting words in the list of all targets
1168  * are found. Each of the resulting nodes is then linked to each of the
1169  * targets as one of its children.
1170  *      Certain targets are handled specially. These are the ones detailed
1171  * by the specType variable.
1172  *      The storing of transformation rules is also taken care of here.
1173  * A target is recognized as a transformation rule by calling
1174  * Suff_IsTransform. If it is a transformation rule, its node is gotten
1175  * from the suffix module via Suff_AddTransform rather than the standard
1176  * Targ_FindNode in the target module.
1177  *---------------------------------------------------------------------
1178  */
1179 static void
1180 ParseDoDependency(char *line)
1181 {
1182     char           *cp;         /* our current position */
1183     GNode          *gn = NULL;  /* a general purpose temporary node */
1184     int             op;         /* the operator on the line */
1185     char            savec;      /* a place to save a character */
1186     Lst             paths;      /* List of search paths to alter when parsing
1187                                  * a list of .PATH targets */
1188     int             tOp;        /* operator from special target */
1189     Lst             sources;    /* list of archive source names after
1190                                  * expansion */
1191     Lst             curTargs;   /* list of target names to be found and added
1192                                  * to the targets list */
1193     char           *lstart = line;
1194
1195     if (DEBUG(PARSE))
1196         fprintf(debug_file, "ParseDoDependency(%s)\n", line);
1197     tOp = 0;
1198
1199     specType = Not;
1200     paths = NULL;
1201
1202     curTargs = Lst_Init(FALSE);
1203
1204     do {
1205         for (cp = line; *cp && (ParseIsEscaped(lstart, cp) ||
1206                      !(isspace((unsigned char)*cp) ||
1207                          *cp == '!' || *cp == ':' || *cp == LPAREN));
1208                  cp++) {
1209             if (*cp == '$') {
1210                 /*
1211                  * Must be a dynamic source (would have been expanded
1212                  * otherwise), so call the Var module to parse the puppy
1213                  * so we can safely advance beyond it...There should be
1214                  * no errors in this, as they would have been discovered
1215                  * in the initial Var_Subst and we wouldn't be here.
1216                  */
1217                 int     length;
1218                 void    *freeIt;
1219                 char    *result;
1220
1221                 result = Var_Parse(cp, VAR_CMD, TRUE, &length, &freeIt);
1222                 if (freeIt)
1223                     free(freeIt);
1224                 cp += length-1;
1225             }
1226         }
1227
1228         if (!ParseIsEscaped(lstart, cp) && *cp == LPAREN) {
1229             /*
1230              * Archives must be handled specially to make sure the OP_ARCHV
1231              * flag is set in their 'type' field, for one thing, and because
1232              * things like "archive(file1.o file2.o file3.o)" are permissible.
1233              * Arch_ParseArchive will set 'line' to be the first non-blank
1234              * after the archive-spec. It creates/finds nodes for the members
1235              * and places them on the given list, returning SUCCESS if all
1236              * went well and FAILURE if there was an error in the
1237              * specification. On error, line should remain untouched.
1238              */
1239             if (Arch_ParseArchive(&line, targets, VAR_CMD) != SUCCESS) {
1240                 Parse_Error(PARSE_FATAL,
1241                              "Error in archive specification: \"%s\"", line);
1242                 goto out;
1243             } else {
1244                 continue;
1245             }
1246         }
1247         savec = *cp;
1248
1249         if (!*cp) {
1250             /*
1251              * Ending a dependency line without an operator is a Bozo
1252              * no-no.  As a heuristic, this is also often triggered by
1253              * undetected conflicts from cvs/rcs merges.
1254              */
1255             if ((strncmp(line, "<<<<<<", 6) == 0) ||
1256                 (strncmp(line, "======", 6) == 0) ||
1257                 (strncmp(line, ">>>>>>", 6) == 0))
1258                 Parse_Error(PARSE_FATAL,
1259                     "Makefile appears to contain unresolved cvs/rcs/??? merge conflicts");
1260             else
1261                 Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1262                                      : "Need an operator");
1263             goto out;
1264         }
1265         *cp = '\0';
1266
1267         /*
1268          * Have a word in line. See if it's a special target and set
1269          * specType to match it.
1270          */
1271         if (*line == '.' && isupper ((unsigned char)line[1])) {
1272             /*
1273              * See if the target is a special target that must have it
1274              * or its sources handled specially.
1275              */
1276             int keywd = ParseFindKeyword(line);
1277             if (keywd != -1) {
1278                 if (specType == ExPath && parseKeywords[keywd].spec != ExPath) {
1279                     Parse_Error(PARSE_FATAL, "Mismatched special targets");
1280                     goto out;
1281                 }
1282
1283                 specType = parseKeywords[keywd].spec;
1284                 tOp = parseKeywords[keywd].op;
1285
1286                 /*
1287                  * Certain special targets have special semantics:
1288                  *      .PATH           Have to set the dirSearchPath
1289                  *                      variable too
1290                  *      .MAIN           Its sources are only used if
1291                  *                      nothing has been specified to
1292                  *                      create.
1293                  *      .DEFAULT        Need to create a node to hang
1294                  *                      commands on, but we don't want
1295                  *                      it in the graph, nor do we want
1296                  *                      it to be the Main Target, so we
1297                  *                      create it, set OP_NOTMAIN and
1298                  *                      add it to the list, setting
1299                  *                      DEFAULT to the new node for
1300                  *                      later use. We claim the node is
1301                  *                      A transformation rule to make
1302                  *                      life easier later, when we'll
1303                  *                      use Make_HandleUse to actually
1304                  *                      apply the .DEFAULT commands.
1305                  *      .PHONY          The list of targets
1306                  *      .NOPATH         Don't search for file in the path
1307                  *      .STALE
1308                  *      .BEGIN
1309                  *      .END
1310                  *      .ERROR
1311                  *      .INTERRUPT      Are not to be considered the
1312                  *                      main target.
1313                  *      .NOTPARALLEL    Make only one target at a time.
1314                  *      .SINGLESHELL    Create a shell for each command.
1315                  *      .ORDER          Must set initial predecessor to NULL
1316                  */
1317                 switch (specType) {
1318                 case ExPath:
1319                     if (paths == NULL) {
1320                         paths = Lst_Init(FALSE);
1321                     }
1322                     (void)Lst_AtEnd(paths, dirSearchPath);
1323                     break;
1324                 case Main:
1325                     if (!Lst_IsEmpty(create)) {
1326                         specType = Not;
1327                     }
1328                     break;
1329                 case Begin:
1330                 case End:
1331                 case Stale:
1332                 case dotError:
1333                 case Interrupt:
1334                     gn = Targ_FindNode(line, TARG_CREATE);
1335                     if (doing_depend)
1336                         ParseMark(gn);
1337                     gn->type |= OP_NOTMAIN|OP_SPECIAL;
1338                     (void)Lst_AtEnd(targets, gn);
1339                     break;
1340                 case Default:
1341                     gn = Targ_NewGN(".DEFAULT");
1342                     gn->type |= (OP_NOTMAIN|OP_TRANSFORM);
1343                     (void)Lst_AtEnd(targets, gn);
1344                     DEFAULT = gn;
1345                     break;
1346                 case NotParallel:
1347                     maxJobs = 1;
1348                     break;
1349                 case SingleShell:
1350                     compatMake = TRUE;
1351                     break;
1352                 case Order:
1353                     predecessor = NULL;
1354                     break;
1355                 default:
1356                     break;
1357                 }
1358             } else if (strncmp(line, ".PATH", 5) == 0) {
1359                 /*
1360                  * .PATH<suffix> has to be handled specially.
1361                  * Call on the suffix module to give us a path to
1362                  * modify.
1363                  */
1364                 Lst     path;
1365
1366                 specType = ExPath;
1367                 path = Suff_GetPath(&line[5]);
1368                 if (path == NULL) {
1369                     Parse_Error(PARSE_FATAL,
1370                                  "Suffix '%s' not defined (yet)",
1371                                  &line[5]);
1372                     goto out;
1373                 } else {
1374                     if (paths == NULL) {
1375                         paths = Lst_Init(FALSE);
1376                     }
1377                     (void)Lst_AtEnd(paths, path);
1378                 }
1379             }
1380         }
1381
1382         /*
1383          * Have word in line. Get or create its node and stick it at
1384          * the end of the targets list
1385          */
1386         if ((specType == Not) && (*line != '\0')) {
1387             if (Dir_HasWildcards(line)) {
1388                 /*
1389                  * Targets are to be sought only in the current directory,
1390                  * so create an empty path for the thing. Note we need to
1391                  * use Dir_Destroy in the destruction of the path as the
1392                  * Dir module could have added a directory to the path...
1393                  */
1394                 Lst         emptyPath = Lst_Init(FALSE);
1395
1396                 Dir_Expand(line, emptyPath, curTargs);
1397
1398                 Lst_Destroy(emptyPath, Dir_Destroy);
1399             } else {
1400                 /*
1401                  * No wildcards, but we want to avoid code duplication,
1402                  * so create a list with the word on it.
1403                  */
1404                 (void)Lst_AtEnd(curTargs, line);
1405             }
1406
1407             while(!Lst_IsEmpty(curTargs)) {
1408                 char    *targName = (char *)Lst_DeQueue(curTargs);
1409
1410                 if (!Suff_IsTransform (targName)) {
1411                     gn = Targ_FindNode(targName, TARG_CREATE);
1412                 } else {
1413                     gn = Suff_AddTransform(targName);
1414                 }
1415                 if (doing_depend)
1416                     ParseMark(gn);
1417
1418                 (void)Lst_AtEnd(targets, gn);
1419             }
1420         } else if (specType == ExPath && *line != '.' && *line != '\0') {
1421             Parse_Error(PARSE_WARNING, "Extra target (%s) ignored", line);
1422         }
1423
1424         *cp = savec;
1425         /*
1426          * If it is a special type and not .PATH, it's the only target we
1427          * allow on this line...
1428          */
1429         if (specType != Not && specType != ExPath) {
1430             Boolean warning = FALSE;
1431
1432             while (*cp && (ParseIsEscaped(lstart, cp) ||
1433                 ((*cp != '!') && (*cp != ':')))) {
1434                 if (ParseIsEscaped(lstart, cp) ||
1435                     (*cp != ' ' && *cp != '\t')) {
1436                     warning = TRUE;
1437                 }
1438                 cp++;
1439             }
1440             if (warning) {
1441                 Parse_Error(PARSE_WARNING, "Extra target ignored");
1442             }
1443         } else {
1444             while (*cp && isspace ((unsigned char)*cp)) {
1445                 cp++;
1446             }
1447         }
1448         line = cp;
1449     } while (*line && (ParseIsEscaped(lstart, line) ||
1450         ((*line != '!') && (*line != ':'))));
1451
1452     /*
1453      * Don't need the list of target names anymore...
1454      */
1455     Lst_Destroy(curTargs, NULL);
1456     curTargs = NULL;
1457
1458     if (!Lst_IsEmpty(targets)) {
1459         switch(specType) {
1460             default:
1461                 Parse_Error(PARSE_WARNING, "Special and mundane targets don't mix. Mundane ones ignored");
1462                 break;
1463             case Default:
1464             case Stale:
1465             case Begin:
1466             case End:
1467             case dotError:
1468             case Interrupt:
1469                 /*
1470                  * These four create nodes on which to hang commands, so
1471                  * targets shouldn't be empty...
1472                  */
1473             case Not:
1474                 /*
1475                  * Nothing special here -- targets can be empty if it wants.
1476                  */
1477                 break;
1478         }
1479     }
1480
1481     /*
1482      * Have now parsed all the target names. Must parse the operator next. The
1483      * result is left in  op .
1484      */
1485     if (*cp == '!') {
1486         op = OP_FORCE;
1487     } else if (*cp == ':') {
1488         if (cp[1] == ':') {
1489             op = OP_DOUBLEDEP;
1490             cp++;
1491         } else {
1492             op = OP_DEPENDS;
1493         }
1494     } else {
1495         Parse_Error(PARSE_FATAL, lstart[0] == '.' ? "Unknown directive"
1496                     : "Missing dependency operator");
1497         goto out;
1498     }
1499
1500     cp++;                       /* Advance beyond operator */
1501
1502     Lst_ForEach(targets, ParseDoOp, &op);
1503
1504     /*
1505      * Get to the first source
1506      */
1507     while (*cp && isspace ((unsigned char)*cp)) {
1508         cp++;
1509     }
1510     line = cp;
1511
1512     /*
1513      * Several special targets take different actions if present with no
1514      * sources:
1515      *  a .SUFFIXES line with no sources clears out all old suffixes
1516      *  a .PRECIOUS line makes all targets precious
1517      *  a .IGNORE line ignores errors for all targets
1518      *  a .SILENT line creates silence when making all targets
1519      *  a .PATH removes all directories from the search path(s).
1520      */
1521     if (!*line) {
1522         switch (specType) {
1523             case Suffixes:
1524                 Suff_ClearSuffixes();
1525                 break;
1526             case Precious:
1527                 allPrecious = TRUE;
1528                 break;
1529             case Ignore:
1530                 ignoreErrors = TRUE;
1531                 break;
1532             case Silent:
1533                 beSilent = TRUE;
1534                 break;
1535             case ExPath:
1536                 Lst_ForEach(paths, ParseClearPath, NULL);
1537                 Dir_SetPATH();
1538                 break;
1539 #ifdef POSIX
1540             case Posix:
1541                 Var_Set("%POSIX", "1003.2", VAR_GLOBAL, 0);
1542                 break;
1543 #endif
1544             default:
1545                 break;
1546         }
1547     } else if (specType == MFlags) {
1548         /*
1549          * Call on functions in main.c to deal with these arguments and
1550          * set the initial character to a null-character so the loop to
1551          * get sources won't get anything
1552          */
1553         Main_ParseArgLine(line);
1554         *line = '\0';
1555     } else if (specType == ExShell) {
1556         if (Job_ParseShell(line) != SUCCESS) {
1557             Parse_Error(PARSE_FATAL, "improper shell specification");
1558             goto out;
1559         }
1560         *line = '\0';
1561     } else if ((specType == NotParallel) || (specType == SingleShell)) {
1562         *line = '\0';
1563     }
1564
1565     /*
1566      * NOW GO FOR THE SOURCES
1567      */
1568     if ((specType == Suffixes) || (specType == ExPath) ||
1569         (specType == Includes) || (specType == Libs) ||
1570         (specType == Null) || (specType == ExObjdir))
1571     {
1572         while (*line) {
1573             /*
1574              * If the target was one that doesn't take files as its sources
1575              * but takes something like suffixes, we take each
1576              * space-separated word on the line as a something and deal
1577              * with it accordingly.
1578              *
1579              * If the target was .SUFFIXES, we take each source as a
1580              * suffix and add it to the list of suffixes maintained by the
1581              * Suff module.
1582              *
1583              * If the target was a .PATH, we add the source as a directory
1584              * to search on the search path.
1585              *
1586              * If it was .INCLUDES, the source is taken to be the suffix of
1587              * files which will be #included and whose search path should
1588              * be present in the .INCLUDES variable.
1589              *
1590              * If it was .LIBS, the source is taken to be the suffix of
1591              * files which are considered libraries and whose search path
1592              * should be present in the .LIBS variable.
1593              *
1594              * If it was .NULL, the source is the suffix to use when a file
1595              * has no valid suffix.
1596              *
1597              * If it was .OBJDIR, the source is a new definition for .OBJDIR,
1598              * and will cause make to do a new chdir to that path.
1599              */
1600             while (*cp && !isspace ((unsigned char)*cp)) {
1601                 cp++;
1602             }
1603             savec = *cp;
1604             *cp = '\0';
1605             switch (specType) {
1606                 case Suffixes:
1607                     Suff_AddSuffix(line, &mainNode);
1608                     break;
1609                 case ExPath:
1610                     Lst_ForEach(paths, ParseAddDir, line);
1611                     break;
1612                 case Includes:
1613                     Suff_AddInclude(line);
1614                     break;
1615                 case Libs:
1616                     Suff_AddLib(line);
1617                     break;
1618                 case Null:
1619                     Suff_SetNull(line);
1620                     break;
1621                 case ExObjdir:
1622                     Main_SetObjdir(line);
1623                     break;
1624                 default:
1625                     break;
1626             }
1627             *cp = savec;
1628             if (savec != '\0') {
1629                 cp++;
1630             }
1631             while (*cp && isspace ((unsigned char)*cp)) {
1632                 cp++;
1633             }
1634             line = cp;
1635         }
1636         if (paths) {
1637             Lst_Destroy(paths, NULL);
1638         }
1639         if (specType == ExPath)
1640             Dir_SetPATH();
1641     } else {
1642         while (*line) {
1643             /*
1644              * The targets take real sources, so we must beware of archive
1645              * specifications (i.e. things with left parentheses in them)
1646              * and handle them accordingly.
1647              */
1648             for (; *cp && !isspace ((unsigned char)*cp); cp++) {
1649                 if ((*cp == LPAREN) && (cp > line) && (cp[-1] != '$')) {
1650                     /*
1651                      * Only stop for a left parenthesis if it isn't at the
1652                      * start of a word (that'll be for variable changes
1653                      * later) and isn't preceded by a dollar sign (a dynamic
1654                      * source).
1655                      */
1656                     break;
1657                 }
1658             }
1659
1660             if (*cp == LPAREN) {
1661                 sources = Lst_Init(FALSE);
1662                 if (Arch_ParseArchive(&line, sources, VAR_CMD) != SUCCESS) {
1663                     Parse_Error(PARSE_FATAL,
1664                                  "Error in source archive spec \"%s\"", line);
1665                     goto out;
1666                 }
1667
1668                 while (!Lst_IsEmpty (sources)) {
1669                     gn = (GNode *)Lst_DeQueue(sources);
1670                     ParseDoSrc(tOp, gn->name);
1671                 }
1672                 Lst_Destroy(sources, NULL);
1673                 cp = line;
1674             } else {
1675                 if (*cp) {
1676                     *cp = '\0';
1677                     cp += 1;
1678                 }
1679
1680                 ParseDoSrc(tOp, line);
1681             }
1682             while (*cp && isspace ((unsigned char)*cp)) {
1683                 cp++;
1684             }
1685             line = cp;
1686         }
1687     }
1688
1689     if (mainNode == NULL) {
1690         /*
1691          * If we have yet to decide on a main target to make, in the
1692          * absence of any user input, we want the first target on
1693          * the first dependency line that is actually a real target
1694          * (i.e. isn't a .USE or .EXEC rule) to be made.
1695          */
1696         Lst_ForEach(targets, ParseFindMain, NULL);
1697     }
1698
1699 out:
1700     if (curTargs)
1701             Lst_Destroy(curTargs, NULL);
1702 }
1703
1704 /*-
1705  *---------------------------------------------------------------------
1706  * Parse_IsVar  --
1707  *      Return TRUE if the passed line is a variable assignment. A variable
1708  *      assignment consists of a single word followed by optional whitespace
1709  *      followed by either a += or an = operator.
1710  *      This function is used both by the Parse_File function and main when
1711  *      parsing the command-line arguments.
1712  *
1713  * Input:
1714  *      line            the line to check
1715  *
1716  * Results:
1717  *      TRUE if it is. FALSE if it ain't
1718  *
1719  * Side Effects:
1720  *      none
1721  *---------------------------------------------------------------------
1722  */
1723 Boolean
1724 Parse_IsVar(char *line)
1725 {
1726     Boolean wasSpace = FALSE;   /* set TRUE if found a space */
1727     char ch;
1728     int level = 0;
1729 #define ISEQOPERATOR(c) \
1730         (((c) == '+') || ((c) == ':') || ((c) == '?') || ((c) == '!'))
1731
1732     /*
1733      * Skip to variable name
1734      */
1735     for (;(*line == ' ') || (*line == '\t'); line++)
1736         continue;
1737
1738     /* Scan for one of the assignment operators outside a variable expansion */
1739     while ((ch = *line++) != 0) {
1740         if (ch == '(' || ch == '{') {
1741             level++;
1742             continue;
1743         }
1744         if (ch == ')' || ch == '}') {
1745             level--;
1746             continue;
1747         }
1748         if (level != 0)
1749             continue;
1750         while (ch == ' ' || ch == '\t') {
1751             ch = *line++;
1752             wasSpace = TRUE;
1753         }
1754         if (ch == '=')
1755             return TRUE;
1756         if (*line == '=' && ISEQOPERATOR(ch))
1757             return TRUE;
1758         if (wasSpace)
1759             return FALSE;
1760     }
1761
1762     return FALSE;
1763 }
1764
1765 /*-
1766  *---------------------------------------------------------------------
1767  * Parse_DoVar  --
1768  *      Take the variable assignment in the passed line and do it in the
1769  *      global context.
1770  *
1771  *      Note: There is a lexical ambiguity with assignment modifier characters
1772  *      in variable names. This routine interprets the character before the =
1773  *      as a modifier. Therefore, an assignment like
1774  *          C++=/usr/bin/CC
1775  *      is interpreted as "C+ +=" instead of "C++ =".
1776  *
1777  * Input:
1778  *      line            a line guaranteed to be a variable assignment.
1779  *                      This reduces error checks
1780  *      ctxt            Context in which to do the assignment
1781  *
1782  * Results:
1783  *      none
1784  *
1785  * Side Effects:
1786  *      the variable structure of the given variable name is altered in the
1787  *      global context.
1788  *---------------------------------------------------------------------
1789  */
1790 void
1791 Parse_DoVar(char *line, GNode *ctxt)
1792 {
1793     char           *cp; /* pointer into line */
1794     enum {
1795         VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1796     }               type;       /* Type of assignment */
1797     char            *opc;       /* ptr to operator character to
1798                                  * null-terminate the variable name */
1799     Boolean        freeCp = FALSE; /* TRUE if cp needs to be freed,
1800                                     * i.e. if any variable expansion was
1801                                     * performed */
1802     int depth;
1803
1804     /*
1805      * Skip to variable name
1806      */
1807     while ((*line == ' ') || (*line == '\t')) {
1808         line++;
1809     }
1810
1811     /*
1812      * Skip to operator character, nulling out whitespace as we go
1813      * XXX Rather than counting () and {} we should look for $ and
1814      * then expand the variable.
1815      */
1816     for (depth = 0, cp = line + 1; depth != 0 || *cp != '='; cp++) {
1817         if (*cp == '(' || *cp == '{') {
1818             depth++;
1819             continue;
1820         }
1821         if (*cp == ')' || *cp == '}') {
1822             depth--;
1823             continue;
1824         }
1825         if (depth == 0 && isspace ((unsigned char)*cp)) {
1826             *cp = '\0';
1827         }
1828     }
1829     opc = cp-1;         /* operator is the previous character */
1830     *cp++ = '\0';       /* nuke the = */
1831
1832     /*
1833      * Check operator type
1834      */
1835     switch (*opc) {
1836         case '+':
1837             type = VAR_APPEND;
1838             *opc = '\0';
1839             break;
1840
1841         case '?':
1842             /*
1843              * If the variable already has a value, we don't do anything.
1844              */
1845             *opc = '\0';
1846             if (Var_Exists(line, ctxt)) {
1847                 return;
1848             } else {
1849                 type = VAR_NORMAL;
1850             }
1851             break;
1852
1853         case ':':
1854             type = VAR_SUBST;
1855             *opc = '\0';
1856             break;
1857
1858         case '!':
1859             type = VAR_SHELL;
1860             *opc = '\0';
1861             break;
1862
1863         default:
1864 #ifdef SUNSHCMD
1865             while (opc > line && *opc != ':')
1866                 opc--;
1867
1868             if (strncmp(opc, ":sh", 3) == 0) {
1869                 type = VAR_SHELL;
1870                 *opc = '\0';
1871                 break;
1872             }
1873 #endif
1874             type = VAR_NORMAL;
1875             break;
1876     }
1877
1878     while (isspace ((unsigned char)*cp)) {
1879         cp++;
1880     }
1881
1882     if (type == VAR_APPEND) {
1883         Var_Append(line, cp, ctxt);
1884     } else if (type == VAR_SUBST) {
1885         /*
1886          * Allow variables in the old value to be undefined, but leave their
1887          * invocation alone -- this is done by forcing oldVars to be false.
1888          * XXX: This can cause recursive variables, but that's not hard to do,
1889          * and this allows someone to do something like
1890          *
1891          *  CFLAGS = $(.INCLUDES)
1892          *  CFLAGS := -I.. $(CFLAGS)
1893          *
1894          * And not get an error.
1895          */
1896         Boolean   oldOldVars = oldVars;
1897
1898         oldVars = FALSE;
1899
1900         /*
1901          * make sure that we set the variable the first time to nothing
1902          * so that it gets substituted!
1903          */
1904         if (!Var_Exists(line, ctxt))
1905             Var_Set(line, "", ctxt, 0);
1906
1907         cp = Var_Subst(NULL, cp, ctxt, FALSE);
1908         oldVars = oldOldVars;
1909         freeCp = TRUE;
1910
1911         Var_Set(line, cp, ctxt, 0);
1912     } else if (type == VAR_SHELL) {
1913         char *res;
1914         const char *error;
1915
1916         if (strchr(cp, '$') != NULL) {
1917             /*
1918              * There's a dollar sign in the command, so perform variable
1919              * expansion on the whole thing. The resulting string will need
1920              * freeing when we're done, so set freeCmd to TRUE.
1921              */
1922             cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1923             freeCp = TRUE;
1924         }
1925
1926         res = Cmd_Exec(cp, &error);
1927         Var_Set(line, res, ctxt, 0);
1928         free(res);
1929
1930         if (error)
1931             Parse_Error(PARSE_WARNING, error, cp);
1932     } else {
1933         /*
1934          * Normal assignment -- just do it.
1935          */
1936         Var_Set(line, cp, ctxt, 0);
1937     }
1938     if (strcmp(line, MAKEOVERRIDES) == 0)
1939         Main_ExportMAKEFLAGS(FALSE);    /* re-export MAKEFLAGS */
1940     else if (strcmp(line, ".CURDIR") == 0) {
1941         /*
1942          * Somone is being (too?) clever...
1943          * Let's pretend they know what they are doing and
1944          * re-initialize the 'cur' Path.
1945          */
1946         Dir_InitCur(cp);
1947         Dir_SetPATH();
1948     } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1949         Job_SetPrefix();
1950     } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1951         Var_Export(cp, 0);
1952     }
1953     if (freeCp)
1954         free(cp);
1955 }
1956
1957
1958 /*-
1959  * ParseAddCmd  --
1960  *      Lst_ForEach function to add a command line to all targets
1961  *
1962  * Input:
1963  *      gnp             the node to which the command is to be added
1964  *      cmd             the command to add
1965  *
1966  * Results:
1967  *      Always 0
1968  *
1969  * Side Effects:
1970  *      A new element is added to the commands list of the node.
1971  */
1972 static int
1973 ParseAddCmd(void *gnp, void *cmd)
1974 {
1975     GNode *gn = (GNode *)gnp;
1976
1977     /* Add to last (ie current) cohort for :: targets */
1978     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1979         gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1980
1981     /* if target already supplied, ignore commands */
1982     if (!(gn->type & OP_HAS_COMMANDS)) {
1983         (void)Lst_AtEnd(gn->commands, cmd);
1984         ParseMark(gn);
1985     } else {
1986 #ifdef notyet
1987         /* XXX: We cannot do this until we fix the tree */
1988         (void)Lst_AtEnd(gn->commands, cmd);
1989         Parse_Error(PARSE_WARNING,
1990                      "overriding commands for target \"%s\"; "
1991                      "previous commands defined at %s: %d ignored",
1992                      gn->name, gn->fname, gn->lineno);
1993 #else
1994         Parse_Error(PARSE_WARNING,
1995                      "duplicate script for target \"%s\" ignored",
1996                      gn->name);
1997         ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
1998                             "using previous script for \"%s\" defined here",
1999                             gn->name);
2000 #endif
2001     }
2002     return(0);
2003 }
2004
2005 /*-
2006  *-----------------------------------------------------------------------
2007  * ParseHasCommands --
2008  *      Callback procedure for Parse_File when destroying the list of
2009  *      targets on the last dependency line. Marks a target as already
2010  *      having commands if it does, to keep from having shell commands
2011  *      on multiple dependency lines.
2012  *
2013  * Input:
2014  *      gnp             Node to examine
2015  *
2016  * Results:
2017  *      None
2018  *
2019  * Side Effects:
2020  *      OP_HAS_COMMANDS may be set for the target.
2021  *
2022  *-----------------------------------------------------------------------
2023  */
2024 static void
2025 ParseHasCommands(void *gnp)
2026 {
2027     GNode *gn = (GNode *)gnp;
2028     if (!Lst_IsEmpty(gn->commands)) {
2029         gn->type |= OP_HAS_COMMANDS;
2030     }
2031 }
2032
2033 /*-
2034  *-----------------------------------------------------------------------
2035  * Parse_AddIncludeDir --
2036  *      Add a directory to the path searched for included makefiles
2037  *      bracketed by double-quotes. Used by functions in main.c
2038  *
2039  * Input:
2040  *      dir             The name of the directory to add
2041  *
2042  * Results:
2043  *      None.
2044  *
2045  * Side Effects:
2046  *      The directory is appended to the list.
2047  *
2048  *-----------------------------------------------------------------------
2049  */
2050 void
2051 Parse_AddIncludeDir(char *dir)
2052 {
2053     (void)Dir_AddDir(parseIncPath, dir);
2054 }
2055
2056 /*-
2057  *---------------------------------------------------------------------
2058  * ParseDoInclude  --
2059  *      Push to another file.
2060  *
2061  *      The input is the line minus the `.'. A file spec is a string
2062  *      enclosed in <> or "". The former is looked for only in sysIncPath.
2063  *      The latter in . and the directories specified by -I command line
2064  *      options
2065  *
2066  * Results:
2067  *      None
2068  *
2069  * Side Effects:
2070  *      A structure is added to the includes Lst and readProc, lineno,
2071  *      fname and curFILE are altered for the new file
2072  *---------------------------------------------------------------------
2073  */
2074
2075 static void
2076 Parse_include_file(char *file, Boolean isSystem, int silent)
2077 {
2078     struct loadedfile *lf;
2079     char          *fullname;    /* full pathname of file */
2080     char          *newName;
2081     char          *prefEnd, *incdir;
2082     int           fd;
2083     int           i;
2084
2085     /*
2086      * Now we know the file's name and its search path, we attempt to
2087      * find the durn thing. A return of NULL indicates the file don't
2088      * exist.
2089      */
2090     fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2091
2092     if (fullname == NULL && !isSystem) {
2093         /*
2094          * Include files contained in double-quotes are first searched for
2095          * relative to the including file's location. We don't want to
2096          * cd there, of course, so we just tack on the old file's
2097          * leading path components and call Dir_FindFile to see if
2098          * we can locate the beast.
2099          */
2100
2101         incdir = bmake_strdup(curFile->fname);
2102         prefEnd = strrchr(incdir, '/');
2103         if (prefEnd != NULL) {
2104             *prefEnd = '\0';
2105             /* Now do lexical processing of leading "../" on the filename */
2106             for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2107                 prefEnd = strrchr(incdir + 1, '/');
2108                 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2109                     break;
2110                 *prefEnd = '\0';
2111             }
2112             newName = str_concat(incdir, file + i, STR_ADDSLASH);
2113             fullname = Dir_FindFile(newName, parseIncPath);
2114             if (fullname == NULL)
2115                 fullname = Dir_FindFile(newName, dirSearchPath);
2116             free(newName);
2117         }
2118         free(incdir);
2119
2120         if (fullname == NULL) {
2121             /*
2122              * Makefile wasn't found in same directory as included makefile.
2123              * Search for it first on the -I search path,
2124              * then on the .PATH search path, if not found in a -I directory.
2125              * If we have a suffix specific path we should use that.
2126              */
2127             char *suff;
2128             Lst suffPath = NULL;
2129
2130             if ((suff = strrchr(file, '.'))) {
2131                 suffPath = Suff_GetPath(suff);
2132                 if (suffPath != NULL) {
2133                     fullname = Dir_FindFile(file, suffPath);
2134                 }
2135             }
2136             if (fullname == NULL) {
2137                 fullname = Dir_FindFile(file, parseIncPath);
2138                 if (fullname == NULL) {
2139                     fullname = Dir_FindFile(file, dirSearchPath);
2140                 }
2141             }
2142         }
2143     }
2144
2145     /* Looking for a system file or file still not found */
2146     if (fullname == NULL) {
2147         /*
2148          * Look for it on the system path
2149          */
2150         fullname = Dir_FindFile(file,
2151                     Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2152     }
2153
2154     if (fullname == NULL) {
2155         if (!silent)
2156             Parse_Error(PARSE_FATAL, "Could not find %s", file);
2157         return;
2158     }
2159
2160     /* Actually open the file... */
2161     fd = open(fullname, O_RDONLY);
2162     if (fd == -1) {
2163         if (!silent)
2164             Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2165         free(fullname);
2166         return;
2167     }
2168
2169     /* load it */
2170     lf = loadfile(fullname, fd);
2171
2172     /* Start reading from this file next */
2173     Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2174     curFile->lf = lf;
2175 }
2176
2177 static void
2178 ParseDoInclude(char *line)
2179 {
2180     char          endc;         /* the character which ends the file spec */
2181     char          *cp;          /* current position in file spec */
2182     int           silent = (*line != 'i') ? 1 : 0;
2183     char          *file = &line[7 + silent];
2184
2185     /* Skip to delimiter character so we know where to look */
2186     while (*file == ' ' || *file == '\t')
2187         file++;
2188
2189     if (*file != '"' && *file != '<') {
2190         Parse_Error(PARSE_FATAL,
2191             ".include filename must be delimited by '\"' or '<'");
2192         return;
2193     }
2194
2195     /*
2196      * Set the search path on which to find the include file based on the
2197      * characters which bracket its name. Angle-brackets imply it's
2198      * a system Makefile while double-quotes imply it's a user makefile
2199      */
2200     if (*file == '<') {
2201         endc = '>';
2202     } else {
2203         endc = '"';
2204     }
2205
2206     /* Skip to matching delimiter */
2207     for (cp = ++file; *cp && *cp != endc; cp++)
2208         continue;
2209
2210     if (*cp != endc) {
2211         Parse_Error(PARSE_FATAL,
2212                      "Unclosed %cinclude filename. '%c' expected",
2213                      '.', endc);
2214         return;
2215     }
2216     *cp = '\0';
2217
2218     /*
2219      * Substitute for any variables in the file name before trying to
2220      * find the thing.
2221      */
2222     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
2223
2224     Parse_include_file(file, endc == '>', silent);
2225     free(file);
2226 }
2227
2228
2229 /*-
2230  *---------------------------------------------------------------------
2231  * ParseSetParseFile  --
2232  *      Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2233  *      basename of the given filename
2234  *
2235  * Results:
2236  *      None
2237  *
2238  * Side Effects:
2239  *      The .PARSEDIR and .PARSEFILE variables are overwritten by the
2240  *      dirname and basename of the given filename.
2241  *---------------------------------------------------------------------
2242  */
2243 static void
2244 ParseSetParseFile(const char *filename)
2245 {
2246     char *slash, *dirname;
2247     const char *pd, *pf;
2248     int len;
2249
2250     slash = strrchr(filename, '/');
2251     if (slash == NULL) {
2252         Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0);
2253         Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0);
2254         dirname= NULL;
2255     } else {
2256         len = slash - filename;
2257         dirname = bmake_malloc(len + 1);
2258         memcpy(dirname, filename, len);
2259         dirname[len] = '\0';
2260         Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0);
2261         Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0);
2262     }
2263     if (DEBUG(PARSE))
2264         fprintf(debug_file, "ParseSetParseFile: ${.PARSEDIR} = `%s' "
2265             "${.PARSEFILE} = `%s'\n", pd, pf);
2266     free(dirname);
2267 }
2268
2269 /*
2270  * Track the makefiles we read - so makefiles can
2271  * set dependencies on them.
2272  * Avoid adding anything more than once.
2273  */
2274
2275 static void
2276 ParseTrackInput(const char *name)
2277 {
2278     char *old;
2279     char *fp = NULL;
2280     size_t name_len = strlen(name);
2281     
2282     old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2283     if (old) {
2284         /* does it contain name? */
2285         for (; old != NULL; old = strchr(old, ' ')) {
2286             if (*old == ' ')
2287                 old++;
2288             if (memcmp(old, name, name_len) == 0
2289                     && (old[name_len] == 0 || old[name_len] == ' '))
2290                 goto cleanup;
2291         }
2292     }
2293     Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2294  cleanup:
2295     if (fp) {
2296         free(fp);
2297     }
2298 }
2299
2300
2301 /*-
2302  *---------------------------------------------------------------------
2303  * Parse_setInput  --
2304  *      Start Parsing from the given source
2305  *
2306  * Results:
2307  *      None
2308  *
2309  * Side Effects:
2310  *      A structure is added to the includes Lst and readProc, lineno,
2311  *      fname and curFile are altered for the new file
2312  *---------------------------------------------------------------------
2313  */
2314 void
2315 Parse_SetInput(const char *name, int line, int fd,
2316         char *(*nextbuf)(void *, size_t *), void *arg)
2317 {
2318     char *buf;
2319     size_t len;
2320
2321     if (name == NULL)
2322         name = curFile->fname;
2323     else
2324         ParseTrackInput(name);
2325
2326     if (DEBUG(PARSE))
2327         fprintf(debug_file, "Parse_SetInput: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2328                 name, line, fd, nextbuf, arg);
2329
2330     if (fd == -1 && nextbuf == NULL)
2331         /* sanity */
2332         return;
2333
2334     if (curFile != NULL)
2335         /* Save exiting file info */
2336         Lst_AtFront(includes, curFile);
2337
2338     /* Allocate and fill in new structure */
2339     curFile = bmake_malloc(sizeof *curFile);
2340
2341     /*
2342      * Once the previous state has been saved, we can get down to reading
2343      * the new file. We set up the name of the file to be the absolute
2344      * name of the include file so error messages refer to the right
2345      * place.
2346      */
2347     curFile->fname = name;
2348     curFile->lineno = line;
2349     curFile->first_lineno = line;
2350     curFile->nextbuf = nextbuf;
2351     curFile->nextbuf_arg = arg;
2352     curFile->lf = NULL;
2353
2354     assert(nextbuf != NULL);
2355
2356     /* Get first block of input data */
2357     buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2358     if (buf == NULL) {
2359         /* Was all a waste of time ... */
2360         free(curFile);
2361         return;
2362     }
2363     curFile->P_str = buf;
2364     curFile->P_ptr = buf;
2365     curFile->P_end = buf+len;
2366
2367     curFile->cond_depth = Cond_save_depth();
2368     ParseSetParseFile(name);
2369 }
2370
2371 #ifdef SYSVINCLUDE
2372 /*-
2373  *---------------------------------------------------------------------
2374  * ParseTraditionalInclude  --
2375  *      Push to another file.
2376  *
2377  *      The input is the current line. The file name(s) are
2378  *      following the "include".
2379  *
2380  * Results:
2381  *      None
2382  *
2383  * Side Effects:
2384  *      A structure is added to the includes Lst and readProc, lineno,
2385  *      fname and curFILE are altered for the new file
2386  *---------------------------------------------------------------------
2387  */
2388 static void
2389 ParseTraditionalInclude(char *line)
2390 {
2391     char          *cp;          /* current position in file spec */
2392     int            done = 0;
2393     int            silent = (line[0] != 'i') ? 1 : 0;
2394     char          *file = &line[silent + 7];
2395     char          *all_files;
2396
2397     if (DEBUG(PARSE)) {
2398             fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2399     }
2400
2401     /*
2402      * Skip over whitespace
2403      */
2404     while (isspace((unsigned char)*file))
2405         file++;
2406
2407     /*
2408      * Substitute for any variables in the file name before trying to
2409      * find the thing.
2410      */
2411     all_files = Var_Subst(NULL, file, VAR_CMD, FALSE);
2412
2413     if (*file == '\0') {
2414         Parse_Error(PARSE_FATAL,
2415                      "Filename missing from \"include\"");
2416         return;
2417     }
2418
2419     for (file = all_files; !done; file = cp + 1) {
2420         /* Skip to end of line or next whitespace */
2421         for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2422             continue;
2423
2424         if (*cp)
2425             *cp = '\0';
2426         else
2427             done = 1;
2428
2429         Parse_include_file(file, FALSE, silent);
2430     }
2431     free(all_files);
2432 }
2433 #endif
2434
2435 #ifdef GMAKEEXPORT
2436 /*-
2437  *---------------------------------------------------------------------
2438  * ParseGmakeExport  --
2439  *      Parse export <variable>=<value>
2440  *
2441  *      And set the environment with it.
2442  *
2443  * Results:
2444  *      None
2445  *
2446  * Side Effects:
2447  *      None
2448  *---------------------------------------------------------------------
2449  */
2450 static void
2451 ParseGmakeExport(char *line)
2452 {
2453     char          *variable = &line[6];
2454     char          *value;
2455
2456     if (DEBUG(PARSE)) {
2457             fprintf(debug_file, "ParseGmakeExport: %s\n", variable);
2458     }
2459
2460     /*
2461      * Skip over whitespace
2462      */
2463     while (isspace((unsigned char)*variable))
2464         variable++;
2465
2466     for (value = variable; *value && *value != '='; value++)
2467         continue;
2468
2469     if (*value != '=') {
2470         Parse_Error(PARSE_FATAL,
2471                      "Variable/Value missing from \"export\"");
2472         return;
2473     }
2474     *value++ = '\0';                    /* terminate variable */
2475
2476     /*
2477      * Expand the value before putting it in the environment.
2478      */
2479     value = Var_Subst(NULL, value, VAR_CMD, FALSE);
2480     setenv(variable, value, 1);
2481 }
2482 #endif
2483
2484 /*-
2485  *---------------------------------------------------------------------
2486  * ParseEOF  --
2487  *      Called when EOF is reached in the current file. If we were reading
2488  *      an include file, the includes stack is popped and things set up
2489  *      to go back to reading the previous file at the previous location.
2490  *
2491  * Results:
2492  *      CONTINUE if there's more to do. DONE if not.
2493  *
2494  * Side Effects:
2495  *      The old curFILE, is closed. The includes list is shortened.
2496  *      lineno, curFILE, and fname are changed if CONTINUE is returned.
2497  *---------------------------------------------------------------------
2498  */
2499 static int
2500 ParseEOF(void)
2501 {
2502     char *ptr;
2503     size_t len;
2504
2505     assert(curFile->nextbuf != NULL);
2506
2507     /* get next input buffer, if any */
2508     ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2509     curFile->P_ptr = ptr;
2510     curFile->P_str = ptr;
2511     curFile->P_end = ptr + len;
2512     curFile->lineno = curFile->first_lineno;
2513     if (ptr != NULL) {
2514         /* Iterate again */
2515         return CONTINUE;
2516     }
2517
2518     /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2519     Cond_restore_depth(curFile->cond_depth);
2520
2521     if (curFile->lf != NULL) {
2522             loadedfile_destroy(curFile->lf);
2523             curFile->lf = NULL;
2524     }
2525
2526     /* Dispose of curFile info */
2527     /* Leak curFile->fname because all the gnodes have pointers to it */
2528     free(curFile->P_str);
2529     free(curFile);
2530
2531     curFile = Lst_DeQueue(includes);
2532
2533     if (curFile == NULL) {
2534         /* We've run out of input */
2535         Var_Delete(".PARSEDIR", VAR_GLOBAL);
2536         Var_Delete(".PARSEFILE", VAR_GLOBAL);
2537         return DONE;
2538     }
2539
2540     if (DEBUG(PARSE))
2541         fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2542             curFile->fname, curFile->lineno);
2543
2544     /* Restore the PARSEDIR/PARSEFILE variables */
2545     ParseSetParseFile(curFile->fname);
2546     return (CONTINUE);
2547 }
2548
2549 #define PARSE_RAW 1
2550 #define PARSE_SKIP 2
2551
2552 static char *
2553 ParseGetLine(int flags, int *length)
2554 {
2555     IFile *cf = curFile;
2556     char *ptr;
2557     char ch;
2558     char *line;
2559     char *line_end;
2560     char *escaped;
2561     char *comment;
2562     char *tp;
2563
2564     /* Loop through blank lines and comment lines */
2565     for (;;) {
2566         cf->lineno++;
2567         line = cf->P_ptr;
2568         ptr = line;
2569         line_end = line;
2570         escaped = NULL;
2571         comment = NULL;
2572         for (;;) {
2573             if (cf->P_end != NULL && ptr == cf->P_end) {
2574                 /* end of buffer */
2575                 ch = 0;
2576                 break;
2577             }
2578             ch = *ptr;
2579             if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2580                 if (cf->P_end == NULL)
2581                     /* End of string (aka for loop) data */
2582                     break;
2583                 if (cf->nextbuf != NULL) {
2584                     /*
2585                      * End of this buffer; return EOF and outer logic
2586                      * will get the next one. (eww)
2587                      */
2588                     break;
2589                 }
2590                 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2591                 return NULL;
2592             }
2593
2594             if (ch == '\\') {
2595                 /* Don't treat next character as special, remember first one */
2596                 if (escaped == NULL)
2597                     escaped = ptr;
2598                 if (ptr[1] == '\n')
2599                     cf->lineno++;
2600                 ptr += 2;
2601                 line_end = ptr;
2602                 continue;
2603             }
2604             if (ch == '#' && comment == NULL) {
2605                 /* Remember first '#' for comment stripping */
2606                 /* Unless previous char was '[', as in modifier :[#] */
2607                 if (!(ptr > line && ptr[-1] == '['))
2608                     comment = line_end;
2609             }
2610             ptr++;
2611             if (ch == '\n')
2612                 break;
2613             if (!isspace((unsigned char)ch))
2614                 /* We are not interested in trailing whitespace */
2615                 line_end = ptr;
2616         }
2617
2618         /* Save next 'to be processed' location */
2619         cf->P_ptr = ptr;
2620
2621         /* Check we have a non-comment, non-blank line */
2622         if (line_end == line || comment == line) {
2623             if (ch == 0)
2624                 /* At end of file */
2625                 return NULL;
2626             /* Parse another line */
2627             continue;
2628         }
2629
2630         /* We now have a line of data */
2631         *line_end = 0;
2632
2633         if (flags & PARSE_RAW) {
2634             /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2635             *length = line_end - line;
2636             return line;
2637         }
2638
2639         if (flags & PARSE_SKIP) {
2640             /* Completely ignore non-directives */
2641             if (line[0] != '.')
2642                 continue;
2643             /* We could do more of the .else/.elif/.endif checks here */
2644         }
2645         break;
2646     }
2647
2648     /* Brutally ignore anything after a non-escaped '#' in non-commands */
2649     if (comment != NULL && line[0] != '\t') {
2650         line_end = comment;
2651         *line_end = 0;
2652     }
2653
2654     /* If we didn't see a '\\' then the in-situ data is fine */
2655     if (escaped == NULL) {
2656         *length = line_end - line;
2657         return line;
2658     }
2659
2660     /* Remove escapes from '\n' and '#' */
2661     tp = ptr = escaped;
2662     escaped = line;
2663     for (; ; *tp++ = ch) {
2664         ch = *ptr++;
2665         if (ch != '\\') {
2666             if (ch == 0)
2667                 break;
2668             continue;
2669         }
2670
2671         ch = *ptr++;
2672         if (ch == 0) {
2673             /* Delete '\\' at end of buffer */
2674             tp--;
2675             break;
2676         }
2677
2678         if (ch == '#' && line[0] != '\t')
2679             /* Delete '\\' from before '#' on non-command lines */
2680             continue;
2681
2682         if (ch != '\n') {
2683             /* Leave '\\' in buffer for later */
2684             *tp++ = '\\';
2685             /* Make sure we don't delete an escaped ' ' from the line end */
2686             escaped = tp + 1;
2687             continue;
2688         }
2689
2690         /* Escaped '\n' replace following whitespace with a single ' ' */
2691         while (ptr[0] == ' ' || ptr[0] == '\t')
2692             ptr++;
2693         ch = ' ';
2694     }
2695
2696     /* Delete any trailing spaces - eg from empty continuations */
2697     while (tp > escaped && isspace((unsigned char)tp[-1]))
2698         tp--;
2699
2700     *tp = 0;
2701     *length = tp - line;
2702     return line;
2703 }
2704
2705 /*-
2706  *---------------------------------------------------------------------
2707  * ParseReadLine --
2708  *      Read an entire line from the input file. Called only by Parse_File.
2709  *
2710  * Results:
2711  *      A line w/o its newline
2712  *
2713  * Side Effects:
2714  *      Only those associated with reading a character
2715  *---------------------------------------------------------------------
2716  */
2717 static char *
2718 ParseReadLine(void)
2719 {
2720     char          *line;        /* Result */
2721     int           lineLength;   /* Length of result */
2722     int           lineno;       /* Saved line # */
2723     int           rval;
2724
2725     for (;;) {
2726         line = ParseGetLine(0, &lineLength);
2727         if (line == NULL)
2728             return NULL;
2729
2730         if (line[0] != '.')
2731             return line;
2732
2733         /*
2734          * The line might be a conditional. Ask the conditional module
2735          * about it and act accordingly
2736          */
2737         switch (Cond_Eval(line)) {
2738         case COND_SKIP:
2739             /* Skip to next conditional that evaluates to COND_PARSE.  */
2740             do {
2741                 line = ParseGetLine(PARSE_SKIP, &lineLength);
2742             } while (line && Cond_Eval(line) != COND_PARSE);
2743             if (line == NULL)
2744                 break;
2745             continue;
2746         case COND_PARSE:
2747             continue;
2748         case COND_INVALID:    /* Not a conditional line */
2749             /* Check for .for loops */
2750             rval = For_Eval(line);
2751             if (rval == 0)
2752                 /* Not a .for line */
2753                 break;
2754             if (rval < 0)
2755                 /* Syntax error - error printed, ignore line */
2756                 continue;
2757             /* Start of a .for loop */
2758             lineno = curFile->lineno;
2759             /* Accumulate loop lines until matching .endfor */
2760             do {
2761                 line = ParseGetLine(PARSE_RAW, &lineLength);
2762                 if (line == NULL) {
2763                     Parse_Error(PARSE_FATAL,
2764                              "Unexpected end of file in for loop.");
2765                     break;
2766                 }
2767             } while (For_Accum(line));
2768             /* Stash each iteration as a new 'input file' */
2769             For_Run(lineno);
2770             /* Read next line from for-loop buffer */
2771             continue;
2772         }
2773         return (line);
2774     }
2775 }
2776
2777 /*-
2778  *-----------------------------------------------------------------------
2779  * ParseFinishLine --
2780  *      Handle the end of a dependency group.
2781  *
2782  * Results:
2783  *      Nothing.
2784  *
2785  * Side Effects:
2786  *      inLine set FALSE. 'targets' list destroyed.
2787  *
2788  *-----------------------------------------------------------------------
2789  */
2790 static void
2791 ParseFinishLine(void)
2792 {
2793     if (inLine) {
2794         Lst_ForEach(targets, Suff_EndTransform, NULL);
2795         Lst_Destroy(targets, ParseHasCommands);
2796         targets = NULL;
2797         inLine = FALSE;
2798     }
2799 }
2800
2801
2802 /*-
2803  *---------------------------------------------------------------------
2804  * Parse_File --
2805  *      Parse a file into its component parts, incorporating it into the
2806  *      current dependency graph. This is the main function and controls
2807  *      almost every other function in this module
2808  *
2809  * Input:
2810  *      name            the name of the file being read
2811  *      fd              Open file to makefile to parse
2812  *
2813  * Results:
2814  *      None
2815  *
2816  * Side Effects:
2817  *      closes fd.
2818  *      Loads. Nodes are added to the list of all targets, nodes and links
2819  *      are added to the dependency graph. etc. etc. etc.
2820  *---------------------------------------------------------------------
2821  */
2822 void
2823 Parse_File(const char *name, int fd)
2824 {
2825     char          *cp;          /* pointer into the line */
2826     char          *line;        /* the line we're working on */
2827     struct loadedfile *lf;
2828
2829     lf = loadfile(name, fd);
2830
2831     inLine = FALSE;
2832     fatals = 0;
2833
2834     if (name == NULL) {
2835             name = "(stdin)";
2836     }
2837
2838     Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2839     curFile->lf = lf;
2840
2841     do {
2842         for (; (line = ParseReadLine()) != NULL; ) {
2843             if (DEBUG(PARSE))
2844                 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2845                         curFile->lineno, line);
2846             if (*line == '.') {
2847                 /*
2848                  * Lines that begin with the special character may be
2849                  * include or undef directives.
2850                  * On the other hand they can be suffix rules (.c.o: ...)
2851                  * or just dependencies for filenames that start '.'.
2852                  */
2853                 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2854                     continue;
2855                 }
2856                 if (strncmp(cp, "include", 7) == 0 ||
2857                         ((cp[0] == 's' || cp[0] == '-') &&
2858                             strncmp(&cp[1], "include", 7) == 0)) {
2859                     ParseDoInclude(cp);
2860                     continue;
2861                 }
2862                 if (strncmp(cp, "undef", 5) == 0) {
2863                     char *cp2;
2864                     for (cp += 5; isspace((unsigned char) *cp); cp++)
2865                         continue;
2866                     for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2867                                    (*cp2 != '\0'); cp2++)
2868                         continue;
2869                     *cp2 = '\0';
2870                     Var_Delete(cp, VAR_GLOBAL);
2871                     continue;
2872                 } else if (strncmp(cp, "export", 6) == 0) {
2873                     for (cp += 6; isspace((unsigned char) *cp); cp++)
2874                         continue;
2875                     Var_Export(cp, 1);
2876                     continue;
2877                 } else if (strncmp(cp, "unexport", 8) == 0) {
2878                     Var_UnExport(cp);
2879                     continue;
2880                 } else if (strncmp(cp, "info", 4) == 0 ||
2881                            strncmp(cp, "error", 5) == 0 ||
2882                            strncmp(cp, "warning", 7) == 0) {
2883                     if (ParseMessage(cp))
2884                         continue;
2885                 }                   
2886             }
2887
2888             if (*line == '\t') {
2889                 /*
2890                  * If a line starts with a tab, it can only hope to be
2891                  * a creation command.
2892                  */
2893                 cp = line + 1;
2894               shellCommand:
2895                 for (; isspace ((unsigned char)*cp); cp++) {
2896                     continue;
2897                 }
2898                 if (*cp) {
2899                     if (!inLine)
2900                         Parse_Error(PARSE_FATAL,
2901                                      "Unassociated shell command \"%s\"",
2902                                      cp);
2903                     /*
2904                      * So long as it's not a blank line and we're actually
2905                      * in a dependency spec, add the command to the list of
2906                      * commands of all targets in the dependency spec
2907                      */
2908                     if (targets) {
2909                         cp = bmake_strdup(cp);
2910                         Lst_ForEach(targets, ParseAddCmd, cp);
2911 #ifdef CLEANUP
2912                         Lst_AtEnd(targCmds, cp);
2913 #endif
2914                     }
2915                 }
2916                 continue;
2917             }
2918
2919 #ifdef SYSVINCLUDE
2920             if (((strncmp(line, "include", 7) == 0 &&
2921                     isspace((unsigned char) line[7])) ||
2922                         ((line[0] == 's' || line[0] == '-') &&
2923                             strncmp(&line[1], "include", 7) == 0 &&
2924                             isspace((unsigned char) line[8]))) &&
2925                     strchr(line, ':') == NULL) {
2926                 /*
2927                  * It's an S3/S5-style "include".
2928                  */
2929                 ParseTraditionalInclude(line);
2930                 continue;
2931             }
2932 #endif
2933 #ifdef GMAKEEXPORT
2934             if (strncmp(line, "export", 6) == 0 &&
2935                 isspace((unsigned char) line[6]) &&
2936                 strchr(line, ':') == NULL) {
2937                 /*
2938                  * It's a Gmake "export".
2939                  */
2940                 ParseGmakeExport(line);
2941                 continue;
2942             }
2943 #endif
2944             if (Parse_IsVar(line)) {
2945                 ParseFinishLine();
2946                 Parse_DoVar(line, VAR_GLOBAL);
2947                 continue;
2948             }
2949
2950 #ifndef POSIX
2951             /*
2952              * To make life easier on novices, if the line is indented we
2953              * first make sure the line has a dependency operator in it.
2954              * If it doesn't have an operator and we're in a dependency
2955              * line's script, we assume it's actually a shell command
2956              * and add it to the current list of targets.
2957              */
2958             cp = line;
2959             if (isspace((unsigned char) line[0])) {
2960                 while ((*cp != '\0') && isspace((unsigned char) *cp))
2961                     cp++;
2962                 while (*cp && (ParseIsEscaped(line, cp) ||
2963                         (*cp != ':') && (*cp != '!'))) {
2964                     cp++;
2965                 }
2966                 if (*cp == '\0') {
2967                     if (inLine) {
2968                         Parse_Error(PARSE_WARNING,
2969                                      "Shell command needs a leading tab");
2970                         goto shellCommand;
2971                     }
2972                 }
2973             }
2974 #endif
2975             ParseFinishLine();
2976
2977             /*
2978              * For some reason - probably to make the parser impossible -
2979              * a ';' can be used to separate commands from dependencies.
2980              * Attempt to avoid ';' inside substitution patterns.
2981              */
2982             {
2983                 int level = 0;
2984
2985                 for (cp = line; *cp != 0; cp++) {
2986                     if (*cp == '\\' && cp[1] != 0) {
2987                         cp++;
2988                         continue;
2989                     }
2990                     if (*cp == '$' &&
2991                         (cp[1] == '(' || cp[1] == '{')) {
2992                         level++;
2993                         continue;
2994                     }
2995                     if (level > 0) {
2996                         if (*cp == ')' || *cp == '}') {
2997                             level--;
2998                             continue;
2999                         }
3000                     } else if (*cp == ';') {
3001                         break;
3002                     }
3003                 }
3004             }
3005             if (*cp != 0)
3006                 /* Terminate the dependency list at the ';' */
3007                 *cp++ = 0;
3008             else
3009                 cp = NULL;
3010
3011             /*
3012              * We now know it's a dependency line so it needs to have all
3013              * variables expanded before being parsed. Tell the variable
3014              * module to complain if some variable is undefined...
3015              */
3016             line = Var_Subst(NULL, line, VAR_CMD, TRUE);
3017
3018             /*
3019              * Need a non-circular list for the target nodes
3020              */
3021             if (targets)
3022                 Lst_Destroy(targets, NULL);
3023
3024             targets = Lst_Init(FALSE);
3025             inLine = TRUE;
3026
3027             ParseDoDependency(line);
3028             free(line);
3029
3030             /* If there were commands after a ';', add them now */
3031             if (cp != NULL) {
3032                 goto shellCommand;
3033             }
3034         }
3035         /*
3036          * Reached EOF, but it may be just EOF of an include file...
3037          */
3038     } while (ParseEOF() == CONTINUE);
3039
3040     if (fatals) {
3041         (void)fflush(stdout);
3042         (void)fprintf(stderr,
3043             "%s: Fatal errors encountered -- cannot continue",
3044             progname);
3045         PrintOnError(NULL, NULL);
3046         exit(1);
3047     }
3048 }
3049
3050 /*-
3051  *---------------------------------------------------------------------
3052  * Parse_Init --
3053  *      initialize the parsing module
3054  *
3055  * Results:
3056  *      none
3057  *
3058  * Side Effects:
3059  *      the parseIncPath list is initialized...
3060  *---------------------------------------------------------------------
3061  */
3062 void
3063 Parse_Init(void)
3064 {
3065     mainNode = NULL;
3066     parseIncPath = Lst_Init(FALSE);
3067     sysIncPath = Lst_Init(FALSE);
3068     defIncPath = Lst_Init(FALSE);
3069     includes = Lst_Init(FALSE);
3070 #ifdef CLEANUP
3071     targCmds = Lst_Init(FALSE);
3072 #endif
3073 }
3074
3075 void
3076 Parse_End(void)
3077 {
3078 #ifdef CLEANUP
3079     Lst_Destroy(targCmds, (FreeProc *)free);
3080     if (targets)
3081         Lst_Destroy(targets, NULL);
3082     Lst_Destroy(defIncPath, Dir_Destroy);
3083     Lst_Destroy(sysIncPath, Dir_Destroy);
3084     Lst_Destroy(parseIncPath, Dir_Destroy);
3085     Lst_Destroy(includes, NULL);        /* Should be empty now */
3086 #endif
3087 }
3088
3089
3090 /*-
3091  *-----------------------------------------------------------------------
3092  * Parse_MainName --
3093  *      Return a Lst of the main target to create for main()'s sake. If
3094  *      no such target exists, we Punt with an obnoxious error message.
3095  *
3096  * Results:
3097  *      A Lst of the single node to create.
3098  *
3099  * Side Effects:
3100  *      None.
3101  *
3102  *-----------------------------------------------------------------------
3103  */
3104 Lst
3105 Parse_MainName(void)
3106 {
3107     Lst           mainList;     /* result list */
3108
3109     mainList = Lst_Init(FALSE);
3110
3111     if (mainNode == NULL) {
3112         Punt("no target to make.");
3113         /*NOTREACHED*/
3114     } else if (mainNode->type & OP_DOUBLEDEP) {
3115         (void)Lst_AtEnd(mainList, mainNode);
3116         Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3117     }
3118     else
3119         (void)Lst_AtEnd(mainList, mainNode);
3120     Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3121     return (mainList);
3122 }
3123
3124 /*-
3125  *-----------------------------------------------------------------------
3126  * ParseMark --
3127  *      Add the filename and lineno to the GNode so that we remember
3128  *      where it was first defined.
3129  *
3130  * Side Effects:
3131  *      None.
3132  *
3133  *-----------------------------------------------------------------------
3134  */
3135 static void
3136 ParseMark(GNode *gn)
3137 {
3138     gn->fname = curFile->fname;
3139     gn->lineno = curFile->lineno;
3140 }