make(1): Remove local mods to parse.c and job.c
[dragonfly.git] / contrib / bmake / parse.c
1 /*      $NetBSD: parse.c,v 1.191 2013/08/28 21:56:49 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.191 2013/08/28 21:56:49 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.191 2013/08/28 21:56:49 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     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 #ifdef SUNSHCMD
1755         if (ch == ':' && strncmp(line, "sh", 2) == 0) {
1756             line += 2;
1757             continue;
1758         }
1759 #endif
1760         if (ch == '=')
1761             return TRUE;
1762         if (*line == '=' && ISEQOPERATOR(ch))
1763             return TRUE;
1764         if (wasSpace)
1765             return FALSE;
1766     }
1767
1768     return FALSE;
1769 }
1770
1771 /*-
1772  *---------------------------------------------------------------------
1773  * Parse_DoVar  --
1774  *      Take the variable assignment in the passed line and do it in the
1775  *      global context.
1776  *
1777  *      Note: There is a lexical ambiguity with assignment modifier characters
1778  *      in variable names. This routine interprets the character before the =
1779  *      as a modifier. Therefore, an assignment like
1780  *          C++=/usr/bin/CC
1781  *      is interpreted as "C+ +=" instead of "C++ =".
1782  *
1783  * Input:
1784  *      line            a line guaranteed to be a variable assignment.
1785  *                      This reduces error checks
1786  *      ctxt            Context in which to do the assignment
1787  *
1788  * Results:
1789  *      none
1790  *
1791  * Side Effects:
1792  *      the variable structure of the given variable name is altered in the
1793  *      global context.
1794  *---------------------------------------------------------------------
1795  */
1796 void
1797 Parse_DoVar(char *line, GNode *ctxt)
1798 {
1799     char           *cp; /* pointer into line */
1800     enum {
1801         VAR_SUBST, VAR_APPEND, VAR_SHELL, VAR_NORMAL
1802     }               type;       /* Type of assignment */
1803     char            *opc;       /* ptr to operator character to
1804                                  * null-terminate the variable name */
1805     Boolean        freeCp = FALSE; /* TRUE if cp needs to be freed,
1806                                     * i.e. if any variable expansion was
1807                                     * performed */
1808     int depth;
1809
1810     /*
1811      * Skip to variable name
1812      */
1813     while ((*line == ' ') || (*line == '\t')) {
1814         line++;
1815     }
1816
1817     /*
1818      * Skip to operator character, nulling out whitespace as we go
1819      * XXX Rather than counting () and {} we should look for $ and
1820      * then expand the variable.
1821      */
1822     for (depth = 0, cp = line + 1; depth != 0 || *cp != '='; cp++) {
1823         if (*cp == '(' || *cp == '{') {
1824             depth++;
1825             continue;
1826         }
1827         if (*cp == ')' || *cp == '}') {
1828             depth--;
1829             continue;
1830         }
1831         if (depth == 0 && isspace ((unsigned char)*cp)) {
1832             *cp = '\0';
1833         }
1834     }
1835     opc = cp-1;         /* operator is the previous character */
1836     *cp++ = '\0';       /* nuke the = */
1837
1838     /*
1839      * Check operator type
1840      */
1841     switch (*opc) {
1842         case '+':
1843             type = VAR_APPEND;
1844             *opc = '\0';
1845             break;
1846
1847         case '?':
1848             /*
1849              * If the variable already has a value, we don't do anything.
1850              */
1851             *opc = '\0';
1852             if (Var_Exists(line, ctxt)) {
1853                 return;
1854             } else {
1855                 type = VAR_NORMAL;
1856             }
1857             break;
1858
1859         case ':':
1860             type = VAR_SUBST;
1861             *opc = '\0';
1862             break;
1863
1864         case '!':
1865             type = VAR_SHELL;
1866             *opc = '\0';
1867             break;
1868
1869         default:
1870 #ifdef SUNSHCMD
1871             while (opc > line && *opc != ':')
1872                 opc--;
1873
1874             if (strncmp(opc, ":sh", 3) == 0) {
1875                 type = VAR_SHELL;
1876                 *opc = '\0';
1877                 break;
1878             }
1879 #endif
1880             type = VAR_NORMAL;
1881             break;
1882     }
1883
1884     while (isspace ((unsigned char)*cp)) {
1885         cp++;
1886     }
1887
1888     if (type == VAR_APPEND) {
1889         Var_Append(line, cp, ctxt);
1890     } else if (type == VAR_SUBST) {
1891         /*
1892          * Allow variables in the old value to be undefined, but leave their
1893          * invocation alone -- this is done by forcing oldVars to be false.
1894          * XXX: This can cause recursive variables, but that's not hard to do,
1895          * and this allows someone to do something like
1896          *
1897          *  CFLAGS = $(.INCLUDES)
1898          *  CFLAGS := -I.. $(CFLAGS)
1899          *
1900          * And not get an error.
1901          */
1902         Boolean   oldOldVars = oldVars;
1903
1904         oldVars = FALSE;
1905
1906         /*
1907          * make sure that we set the variable the first time to nothing
1908          * so that it gets substituted!
1909          */
1910         if (!Var_Exists(line, ctxt))
1911             Var_Set(line, "", ctxt, 0);
1912
1913         cp = Var_Subst(NULL, cp, ctxt, FALSE);
1914         oldVars = oldOldVars;
1915         freeCp = TRUE;
1916
1917         Var_Set(line, cp, ctxt, 0);
1918     } else if (type == VAR_SHELL) {
1919         char *res;
1920         const char *error;
1921
1922         if (strchr(cp, '$') != NULL) {
1923             /*
1924              * There's a dollar sign in the command, so perform variable
1925              * expansion on the whole thing. The resulting string will need
1926              * freeing when we're done, so set freeCmd to TRUE.
1927              */
1928             cp = Var_Subst(NULL, cp, VAR_CMD, TRUE);
1929             freeCp = TRUE;
1930         }
1931
1932         res = Cmd_Exec(cp, &error);
1933         Var_Set(line, res, ctxt, 0);
1934         free(res);
1935
1936         if (error)
1937             Parse_Error(PARSE_WARNING, error, cp);
1938     } else {
1939         /*
1940          * Normal assignment -- just do it.
1941          */
1942         Var_Set(line, cp, ctxt, 0);
1943     }
1944     if (strcmp(line, MAKEOVERRIDES) == 0)
1945         Main_ExportMAKEFLAGS(FALSE);    /* re-export MAKEFLAGS */
1946     else if (strcmp(line, ".CURDIR") == 0) {
1947         /*
1948          * Somone is being (too?) clever...
1949          * Let's pretend they know what they are doing and
1950          * re-initialize the 'cur' Path.
1951          */
1952         Dir_InitCur(cp);
1953         Dir_SetPATH();
1954     } else if (strcmp(line, MAKE_JOB_PREFIX) == 0) {
1955         Job_SetPrefix();
1956     } else if (strcmp(line, MAKE_EXPORTED) == 0) {
1957         Var_Export(cp, 0);
1958     }
1959     if (freeCp)
1960         free(cp);
1961 }
1962
1963
1964 /*-
1965  * ParseAddCmd  --
1966  *      Lst_ForEach function to add a command line to all targets
1967  *
1968  * Input:
1969  *      gnp             the node to which the command is to be added
1970  *      cmd             the command to add
1971  *
1972  * Results:
1973  *      Always 0
1974  *
1975  * Side Effects:
1976  *      A new element is added to the commands list of the node.
1977  */
1978 static int
1979 ParseAddCmd(void *gnp, void *cmd)
1980 {
1981     GNode *gn = (GNode *)gnp;
1982
1983     /* Add to last (ie current) cohort for :: targets */
1984     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
1985         gn = (GNode *)Lst_Datum(Lst_Last(gn->cohorts));
1986
1987     /* if target already supplied, ignore commands */
1988     if (!(gn->type & OP_HAS_COMMANDS)) {
1989         (void)Lst_AtEnd(gn->commands, cmd);
1990         ParseMark(gn);
1991     } else {
1992 #ifdef notyet
1993         /* XXX: We cannot do this until we fix the tree */
1994         (void)Lst_AtEnd(gn->commands, cmd);
1995         Parse_Error(PARSE_WARNING,
1996                      "overriding commands for target \"%s\"; "
1997                      "previous commands defined at %s: %d ignored",
1998                      gn->name, gn->fname, gn->lineno);
1999 #else
2000         Parse_Error(PARSE_WARNING,
2001                      "duplicate script for target \"%s\" ignored",
2002                      gn->name);
2003         ParseErrorInternal(gn->fname, gn->lineno, PARSE_WARNING,
2004                             "using previous script for \"%s\" defined here",
2005                             gn->name);
2006 #endif
2007     }
2008     return(0);
2009 }
2010
2011 /*-
2012  *-----------------------------------------------------------------------
2013  * ParseHasCommands --
2014  *      Callback procedure for Parse_File when destroying the list of
2015  *      targets on the last dependency line. Marks a target as already
2016  *      having commands if it does, to keep from having shell commands
2017  *      on multiple dependency lines.
2018  *
2019  * Input:
2020  *      gnp             Node to examine
2021  *
2022  * Results:
2023  *      None
2024  *
2025  * Side Effects:
2026  *      OP_HAS_COMMANDS may be set for the target.
2027  *
2028  *-----------------------------------------------------------------------
2029  */
2030 static void
2031 ParseHasCommands(void *gnp)
2032 {
2033     GNode *gn = (GNode *)gnp;
2034     if (!Lst_IsEmpty(gn->commands)) {
2035         gn->type |= OP_HAS_COMMANDS;
2036     }
2037 }
2038
2039 /*-
2040  *-----------------------------------------------------------------------
2041  * Parse_AddIncludeDir --
2042  *      Add a directory to the path searched for included makefiles
2043  *      bracketed by double-quotes. Used by functions in main.c
2044  *
2045  * Input:
2046  *      dir             The name of the directory to add
2047  *
2048  * Results:
2049  *      None.
2050  *
2051  * Side Effects:
2052  *      The directory is appended to the list.
2053  *
2054  *-----------------------------------------------------------------------
2055  */
2056 void
2057 Parse_AddIncludeDir(char *dir)
2058 {
2059     (void)Dir_AddDir(parseIncPath, dir);
2060 }
2061
2062 /*-
2063  *---------------------------------------------------------------------
2064  * ParseDoInclude  --
2065  *      Push to another file.
2066  *
2067  *      The input is the line minus the `.'. A file spec is a string
2068  *      enclosed in <> or "". The former is looked for only in sysIncPath.
2069  *      The latter in . and the directories specified by -I command line
2070  *      options
2071  *
2072  * Results:
2073  *      None
2074  *
2075  * Side Effects:
2076  *      A structure is added to the includes Lst and readProc, lineno,
2077  *      fname and curFILE are altered for the new file
2078  *---------------------------------------------------------------------
2079  */
2080
2081 static void
2082 Parse_include_file(char *file, Boolean isSystem, int silent)
2083 {
2084     struct loadedfile *lf;
2085     char          *fullname;    /* full pathname of file */
2086     char          *newName;
2087     char          *prefEnd, *incdir;
2088     int           fd;
2089     int           i;
2090
2091     /*
2092      * Now we know the file's name and its search path, we attempt to
2093      * find the durn thing. A return of NULL indicates the file don't
2094      * exist.
2095      */
2096     fullname = file[0] == '/' ? bmake_strdup(file) : NULL;
2097
2098     if (fullname == NULL && !isSystem) {
2099         /*
2100          * Include files contained in double-quotes are first searched for
2101          * relative to the including file's location. We don't want to
2102          * cd there, of course, so we just tack on the old file's
2103          * leading path components and call Dir_FindFile to see if
2104          * we can locate the beast.
2105          */
2106
2107         incdir = bmake_strdup(curFile->fname);
2108         prefEnd = strrchr(incdir, '/');
2109         if (prefEnd != NULL) {
2110             *prefEnd = '\0';
2111             /* Now do lexical processing of leading "../" on the filename */
2112             for (i = 0; strncmp(file + i, "../", 3) == 0; i += 3) {
2113                 prefEnd = strrchr(incdir + 1, '/');
2114                 if (prefEnd == NULL || strcmp(prefEnd, "/..") == 0)
2115                     break;
2116                 *prefEnd = '\0';
2117             }
2118             newName = str_concat(incdir, file + i, STR_ADDSLASH);
2119             fullname = Dir_FindFile(newName, parseIncPath);
2120             if (fullname == NULL)
2121                 fullname = Dir_FindFile(newName, dirSearchPath);
2122             free(newName);
2123         }
2124         free(incdir);
2125
2126         if (fullname == NULL) {
2127             /*
2128              * Makefile wasn't found in same directory as included makefile.
2129              * Search for it first on the -I search path,
2130              * then on the .PATH search path, if not found in a -I directory.
2131              * If we have a suffix specific path we should use that.
2132              */
2133             char *suff;
2134             Lst suffPath = NULL;
2135
2136             if ((suff = strrchr(file, '.'))) {
2137                 suffPath = Suff_GetPath(suff);
2138                 if (suffPath != NULL) {
2139                     fullname = Dir_FindFile(file, suffPath);
2140                 }
2141             }
2142             if (fullname == NULL) {
2143                 fullname = Dir_FindFile(file, parseIncPath);
2144                 if (fullname == NULL) {
2145                     fullname = Dir_FindFile(file, dirSearchPath);
2146                 }
2147             }
2148         }
2149     }
2150
2151     /* Looking for a system file or file still not found */
2152     if (fullname == NULL) {
2153         /*
2154          * Look for it on the system path
2155          */
2156         fullname = Dir_FindFile(file,
2157                     Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath);
2158     }
2159
2160     if (fullname == NULL) {
2161         if (!silent)
2162             Parse_Error(PARSE_FATAL, "Could not find %s", file);
2163         return;
2164     }
2165
2166     /* Actually open the file... */
2167     fd = open(fullname, O_RDONLY);
2168     if (fd == -1) {
2169         if (!silent)
2170             Parse_Error(PARSE_FATAL, "Cannot open %s", fullname);
2171         free(fullname);
2172         return;
2173     }
2174
2175     /* load it */
2176     lf = loadfile(fullname, fd);
2177
2178     /* Start reading from this file next */
2179     Parse_SetInput(fullname, 0, -1, loadedfile_nextbuf, lf);
2180     curFile->lf = lf;
2181 }
2182
2183 static void
2184 ParseDoInclude(char *line)
2185 {
2186     char          endc;         /* the character which ends the file spec */
2187     char          *cp;          /* current position in file spec */
2188     int           silent = (*line != 'i') ? 1 : 0;
2189     char          *file = &line[7 + silent];
2190
2191     /* Skip to delimiter character so we know where to look */
2192     while (*file == ' ' || *file == '\t')
2193         file++;
2194
2195     if (*file != '"' && *file != '<') {
2196         Parse_Error(PARSE_FATAL,
2197             ".include filename must be delimited by '\"' or '<'");
2198         return;
2199     }
2200
2201     /*
2202      * Set the search path on which to find the include file based on the
2203      * characters which bracket its name. Angle-brackets imply it's
2204      * a system Makefile while double-quotes imply it's a user makefile
2205      */
2206     if (*file == '<') {
2207         endc = '>';
2208     } else {
2209         endc = '"';
2210     }
2211
2212     /* Skip to matching delimiter */
2213     for (cp = ++file; *cp && *cp != endc; cp++)
2214         continue;
2215
2216     if (*cp != endc) {
2217         Parse_Error(PARSE_FATAL,
2218                      "Unclosed %cinclude filename. '%c' expected",
2219                      '.', endc);
2220         return;
2221     }
2222     *cp = '\0';
2223
2224     /*
2225      * Substitute for any variables in the file name before trying to
2226      * find the thing.
2227      */
2228     file = Var_Subst(NULL, file, VAR_CMD, FALSE);
2229
2230     Parse_include_file(file, endc == '>', silent);
2231     free(file);
2232 }
2233
2234
2235 /*-
2236  *---------------------------------------------------------------------
2237  * ParseSetParseFile  --
2238  *      Set the .PARSEDIR and .PARSEFILE variables to the dirname and
2239  *      basename of the given filename
2240  *
2241  * Results:
2242  *      None
2243  *
2244  * Side Effects:
2245  *      The .PARSEDIR and .PARSEFILE variables are overwritten by the
2246  *      dirname and basename of the given filename.
2247  *---------------------------------------------------------------------
2248  */
2249 static void
2250 ParseSetParseFile(const char *filename)
2251 {
2252     char *slash, *dirname;
2253     const char *pd, *pf;
2254     int len;
2255
2256     slash = strrchr(filename, '/');
2257     if (slash == NULL) {
2258         Var_Set(".PARSEDIR", pd = curdir, VAR_GLOBAL, 0);
2259         Var_Set(".PARSEFILE", pf = filename, VAR_GLOBAL, 0);
2260         dirname= NULL;
2261     } else {
2262         len = slash - filename;
2263         dirname = bmake_malloc(len + 1);
2264         memcpy(dirname, filename, len);
2265         dirname[len] = '\0';
2266         Var_Set(".PARSEDIR", pd = dirname, VAR_GLOBAL, 0);
2267         Var_Set(".PARSEFILE", pf = slash + 1, VAR_GLOBAL, 0);
2268     }
2269     if (DEBUG(PARSE))
2270         fprintf(debug_file, "ParseSetParseFile: ${.PARSEDIR} = `%s' "
2271             "${.PARSEFILE} = `%s'\n", pd, pf);
2272     free(dirname);
2273 }
2274
2275 /*
2276  * Track the makefiles we read - so makefiles can
2277  * set dependencies on them.
2278  * Avoid adding anything more than once.
2279  */
2280
2281 static void
2282 ParseTrackInput(const char *name)
2283 {
2284     char *old;
2285     char *fp = NULL;
2286     size_t name_len = strlen(name);
2287     
2288     old = Var_Value(MAKE_MAKEFILES, VAR_GLOBAL, &fp);
2289     if (old) {
2290         /* does it contain name? */
2291         for (; old != NULL; old = strchr(old, ' ')) {
2292             if (*old == ' ')
2293                 old++;
2294             if (memcmp(old, name, name_len) == 0
2295                     && (old[name_len] == 0 || old[name_len] == ' '))
2296                 goto cleanup;
2297         }
2298     }
2299     Var_Append (MAKE_MAKEFILES, name, VAR_GLOBAL);
2300  cleanup:
2301     if (fp) {
2302         free(fp);
2303     }
2304 }
2305
2306
2307 /*-
2308  *---------------------------------------------------------------------
2309  * Parse_setInput  --
2310  *      Start Parsing from the given source
2311  *
2312  * Results:
2313  *      None
2314  *
2315  * Side Effects:
2316  *      A structure is added to the includes Lst and readProc, lineno,
2317  *      fname and curFile are altered for the new file
2318  *---------------------------------------------------------------------
2319  */
2320 void
2321 Parse_SetInput(const char *name, int line, int fd,
2322         char *(*nextbuf)(void *, size_t *), void *arg)
2323 {
2324     char *buf;
2325     size_t len;
2326
2327     if (name == NULL)
2328         name = curFile->fname;
2329     else
2330         ParseTrackInput(name);
2331
2332     if (DEBUG(PARSE))
2333         fprintf(debug_file, "Parse_SetInput: file %s, line %d, fd %d, nextbuf %p, arg %p\n",
2334                 name, line, fd, nextbuf, arg);
2335
2336     if (fd == -1 && nextbuf == NULL)
2337         /* sanity */
2338         return;
2339
2340     if (curFile != NULL)
2341         /* Save exiting file info */
2342         Lst_AtFront(includes, curFile);
2343
2344     /* Allocate and fill in new structure */
2345     curFile = bmake_malloc(sizeof *curFile);
2346
2347     /*
2348      * Once the previous state has been saved, we can get down to reading
2349      * the new file. We set up the name of the file to be the absolute
2350      * name of the include file so error messages refer to the right
2351      * place.
2352      */
2353     curFile->fname = bmake_strdup(name);
2354     curFile->lineno = line;
2355     curFile->first_lineno = line;
2356     curFile->nextbuf = nextbuf;
2357     curFile->nextbuf_arg = arg;
2358     curFile->lf = NULL;
2359
2360     assert(nextbuf != NULL);
2361
2362     /* Get first block of input data */
2363     buf = curFile->nextbuf(curFile->nextbuf_arg, &len);
2364     if (buf == NULL) {
2365         /* Was all a waste of time ... */
2366         if (curFile->fname)
2367             free(curFile->fname);
2368         free(curFile);
2369         return;
2370     }
2371     curFile->P_str = buf;
2372     curFile->P_ptr = buf;
2373     curFile->P_end = buf+len;
2374
2375     curFile->cond_depth = Cond_save_depth();
2376     ParseSetParseFile(name);
2377 }
2378
2379 #ifdef SYSVINCLUDE
2380 /*-
2381  *---------------------------------------------------------------------
2382  * ParseTraditionalInclude  --
2383  *      Push to another file.
2384  *
2385  *      The input is the current line. The file name(s) are
2386  *      following the "include".
2387  *
2388  * Results:
2389  *      None
2390  *
2391  * Side Effects:
2392  *      A structure is added to the includes Lst and readProc, lineno,
2393  *      fname and curFILE are altered for the new file
2394  *---------------------------------------------------------------------
2395  */
2396 static void
2397 ParseTraditionalInclude(char *line)
2398 {
2399     char          *cp;          /* current position in file spec */
2400     int            done = 0;
2401     int            silent = (line[0] != 'i') ? 1 : 0;
2402     char          *file = &line[silent + 7];
2403     char          *all_files;
2404
2405     if (DEBUG(PARSE)) {
2406             fprintf(debug_file, "ParseTraditionalInclude: %s\n", file);
2407     }
2408
2409     /*
2410      * Skip over whitespace
2411      */
2412     while (isspace((unsigned char)*file))
2413         file++;
2414
2415     /*
2416      * Substitute for any variables in the file name before trying to
2417      * find the thing.
2418      */
2419     all_files = Var_Subst(NULL, file, VAR_CMD, FALSE);
2420
2421     if (*file == '\0') {
2422         Parse_Error(PARSE_FATAL,
2423                      "Filename missing from \"include\"");
2424         return;
2425     }
2426
2427     for (file = all_files; !done; file = cp + 1) {
2428         /* Skip to end of line or next whitespace */
2429         for (cp = file; *cp && !isspace((unsigned char) *cp); cp++)
2430             continue;
2431
2432         if (*cp)
2433             *cp = '\0';
2434         else
2435             done = 1;
2436
2437         Parse_include_file(file, FALSE, silent);
2438     }
2439     free(all_files);
2440 }
2441 #endif
2442
2443 #ifdef GMAKEEXPORT
2444 /*-
2445  *---------------------------------------------------------------------
2446  * ParseGmakeExport  --
2447  *      Parse export <variable>=<value>
2448  *
2449  *      And set the environment with it.
2450  *
2451  * Results:
2452  *      None
2453  *
2454  * Side Effects:
2455  *      None
2456  *---------------------------------------------------------------------
2457  */
2458 static void
2459 ParseGmakeExport(char *line)
2460 {
2461     char          *variable = &line[6];
2462     char          *value;
2463
2464     if (DEBUG(PARSE)) {
2465             fprintf(debug_file, "ParseGmakeExport: %s\n", variable);
2466     }
2467
2468     /*
2469      * Skip over whitespace
2470      */
2471     while (isspace((unsigned char)*variable))
2472         variable++;
2473
2474     for (value = variable; *value && *value != '='; value++)
2475         continue;
2476
2477     if (*value != '=') {
2478         Parse_Error(PARSE_FATAL,
2479                      "Variable/Value missing from \"export\"");
2480         return;
2481     }
2482     *value++ = '\0';                    /* terminate variable */
2483
2484     /*
2485      * Expand the value before putting it in the environment.
2486      */
2487     value = Var_Subst(NULL, value, VAR_CMD, FALSE);
2488     setenv(variable, value, 1);
2489 }
2490 #endif
2491
2492 /*-
2493  *---------------------------------------------------------------------
2494  * ParseEOF  --
2495  *      Called when EOF is reached in the current file. If we were reading
2496  *      an include file, the includes stack is popped and things set up
2497  *      to go back to reading the previous file at the previous location.
2498  *
2499  * Results:
2500  *      CONTINUE if there's more to do. DONE if not.
2501  *
2502  * Side Effects:
2503  *      The old curFILE, is closed. The includes list is shortened.
2504  *      lineno, curFILE, and fname are changed if CONTINUE is returned.
2505  *---------------------------------------------------------------------
2506  */
2507 static int
2508 ParseEOF(void)
2509 {
2510     char *ptr;
2511     size_t len;
2512
2513     assert(curFile->nextbuf != NULL);
2514
2515     /* get next input buffer, if any */
2516     ptr = curFile->nextbuf(curFile->nextbuf_arg, &len);
2517     curFile->P_ptr = ptr;
2518     curFile->P_str = ptr;
2519     curFile->P_end = ptr + len;
2520     curFile->lineno = curFile->first_lineno;
2521     if (ptr != NULL) {
2522         /* Iterate again */
2523         return CONTINUE;
2524     }
2525
2526     /* Ensure the makefile (or loop) didn't have mismatched conditionals */
2527     Cond_restore_depth(curFile->cond_depth);
2528
2529     if (curFile->lf != NULL) {
2530             loadedfile_destroy(curFile->lf);
2531             curFile->lf = NULL;
2532     }
2533
2534     /* Dispose of curFile info */
2535     /* Leak curFile->fname because all the gnodes have pointers to it */
2536     free(curFile->P_str);
2537     free(curFile);
2538
2539     curFile = Lst_DeQueue(includes);
2540
2541     if (curFile == NULL) {
2542         /* We've run out of input */
2543         Var_Delete(".PARSEDIR", VAR_GLOBAL);
2544         Var_Delete(".PARSEFILE", VAR_GLOBAL);
2545         return DONE;
2546     }
2547
2548     if (DEBUG(PARSE))
2549         fprintf(debug_file, "ParseEOF: returning to file %s, line %d\n",
2550             curFile->fname, curFile->lineno);
2551
2552     /* Restore the PARSEDIR/PARSEFILE variables */
2553     ParseSetParseFile(curFile->fname);
2554     return (CONTINUE);
2555 }
2556
2557 #define PARSE_RAW 1
2558 #define PARSE_SKIP 2
2559
2560 static char *
2561 ParseGetLine(int flags, int *length)
2562 {
2563     IFile *cf = curFile;
2564     char *ptr;
2565     char ch;
2566     char *line;
2567     char *line_end;
2568     char *escaped;
2569     char *comment;
2570     char *tp;
2571
2572     /* Loop through blank lines and comment lines */
2573     for (;;) {
2574         cf->lineno++;
2575         line = cf->P_ptr;
2576         ptr = line;
2577         line_end = line;
2578         escaped = NULL;
2579         comment = NULL;
2580         for (;;) {
2581             if (cf->P_end != NULL && ptr == cf->P_end) {
2582                 /* end of buffer */
2583                 ch = 0;
2584                 break;
2585             }
2586             ch = *ptr;
2587             if (ch == 0 || (ch == '\\' && ptr[1] == 0)) {
2588                 if (cf->P_end == NULL)
2589                     /* End of string (aka for loop) data */
2590                     break;
2591                 /* see if there is more we can parse */
2592                 while (ptr++ < cf->P_end) {
2593                     if ((ch = *ptr) == '\n') {
2594                         if (ptr > line && ptr[-1] == '\\')
2595                             continue;
2596                         Parse_Error(PARSE_WARNING,
2597                             "Zero byte read from file, skipping rest of line.");
2598                         break;
2599                     }
2600                 }
2601                 if (cf->nextbuf != NULL) {
2602                     /*
2603                      * End of this buffer; return EOF and outer logic
2604                      * will get the next one. (eww)
2605                      */
2606                     break;
2607                 }
2608                 Parse_Error(PARSE_FATAL, "Zero byte read from file");
2609                 return NULL;
2610             }
2611
2612             if (ch == '\\') {
2613                 /* Don't treat next character as special, remember first one */
2614                 if (escaped == NULL)
2615                     escaped = ptr;
2616                 if (ptr[1] == '\n')
2617                     cf->lineno++;
2618                 ptr += 2;
2619                 line_end = ptr;
2620                 continue;
2621             }
2622             if (ch == '#' && comment == NULL) {
2623                 /* Remember first '#' for comment stripping */
2624                 /* Unless previous char was '[', as in modifier :[#] */
2625                 if (!(ptr > line && ptr[-1] == '['))
2626                     comment = line_end;
2627             }
2628             ptr++;
2629             if (ch == '\n')
2630                 break;
2631             if (!isspace((unsigned char)ch))
2632                 /* We are not interested in trailing whitespace */
2633                 line_end = ptr;
2634         }
2635
2636         /* Save next 'to be processed' location */
2637         cf->P_ptr = ptr;
2638
2639         /* Check we have a non-comment, non-blank line */
2640         if (line_end == line || comment == line) {
2641             if (ch == 0)
2642                 /* At end of file */
2643                 return NULL;
2644             /* Parse another line */
2645             continue;
2646         }
2647
2648         /* We now have a line of data */
2649         *line_end = 0;
2650
2651         if (flags & PARSE_RAW) {
2652             /* Leave '\' (etc) in line buffer (eg 'for' lines) */
2653             *length = line_end - line;
2654             return line;
2655         }
2656
2657         if (flags & PARSE_SKIP) {
2658             /* Completely ignore non-directives */
2659             if (line[0] != '.')
2660                 continue;
2661             /* We could do more of the .else/.elif/.endif checks here */
2662         }
2663         break;
2664     }
2665
2666     /* Brutally ignore anything after a non-escaped '#' in non-commands */
2667     if (comment != NULL && line[0] != '\t') {
2668         line_end = comment;
2669         *line_end = 0;
2670     }
2671
2672     /* If we didn't see a '\\' then the in-situ data is fine */
2673     if (escaped == NULL) {
2674         *length = line_end - line;
2675         return line;
2676     }
2677
2678     /* Remove escapes from '\n' and '#' */
2679     tp = ptr = escaped;
2680     escaped = line;
2681     for (; ; *tp++ = ch) {
2682         ch = *ptr++;
2683         if (ch != '\\') {
2684             if (ch == 0)
2685                 break;
2686             continue;
2687         }
2688
2689         ch = *ptr++;
2690         if (ch == 0) {
2691             /* Delete '\\' at end of buffer */
2692             tp--;
2693             break;
2694         }
2695
2696         if (ch == '#' && line[0] != '\t')
2697             /* Delete '\\' from before '#' on non-command lines */
2698             continue;
2699
2700         if (ch != '\n') {
2701             /* Leave '\\' in buffer for later */
2702             *tp++ = '\\';
2703             /* Make sure we don't delete an escaped ' ' from the line end */
2704             escaped = tp + 1;
2705             continue;
2706         }
2707
2708         /* Escaped '\n' replace following whitespace with a single ' ' */
2709         while (ptr[0] == ' ' || ptr[0] == '\t')
2710             ptr++;
2711         ch = ' ';
2712     }
2713
2714     /* Delete any trailing spaces - eg from empty continuations */
2715     while (tp > escaped && isspace((unsigned char)tp[-1]))
2716         tp--;
2717
2718     *tp = 0;
2719     *length = tp - line;
2720     return line;
2721 }
2722
2723 /*-
2724  *---------------------------------------------------------------------
2725  * ParseReadLine --
2726  *      Read an entire line from the input file. Called only by Parse_File.
2727  *
2728  * Results:
2729  *      A line w/o its newline
2730  *
2731  * Side Effects:
2732  *      Only those associated with reading a character
2733  *---------------------------------------------------------------------
2734  */
2735 static char *
2736 ParseReadLine(void)
2737 {
2738     char          *line;        /* Result */
2739     int           lineLength;   /* Length of result */
2740     int           lineno;       /* Saved line # */
2741     int           rval;
2742
2743     for (;;) {
2744         line = ParseGetLine(0, &lineLength);
2745         if (line == NULL)
2746             return NULL;
2747
2748         if (line[0] != '.')
2749             return line;
2750
2751         /*
2752          * The line might be a conditional. Ask the conditional module
2753          * about it and act accordingly
2754          */
2755         switch (Cond_Eval(line)) {
2756         case COND_SKIP:
2757             /* Skip to next conditional that evaluates to COND_PARSE.  */
2758             do {
2759                 line = ParseGetLine(PARSE_SKIP, &lineLength);
2760             } while (line && Cond_Eval(line) != COND_PARSE);
2761             if (line == NULL)
2762                 break;
2763             continue;
2764         case COND_PARSE:
2765             continue;
2766         case COND_INVALID:    /* Not a conditional line */
2767             /* Check for .for loops */
2768             rval = For_Eval(line);
2769             if (rval == 0)
2770                 /* Not a .for line */
2771                 break;
2772             if (rval < 0)
2773                 /* Syntax error - error printed, ignore line */
2774                 continue;
2775             /* Start of a .for loop */
2776             lineno = curFile->lineno;
2777             /* Accumulate loop lines until matching .endfor */
2778             do {
2779                 line = ParseGetLine(PARSE_RAW, &lineLength);
2780                 if (line == NULL) {
2781                     Parse_Error(PARSE_FATAL,
2782                              "Unexpected end of file in for loop.");
2783                     break;
2784                 }
2785             } while (For_Accum(line));
2786             /* Stash each iteration as a new 'input file' */
2787             For_Run(lineno);
2788             /* Read next line from for-loop buffer */
2789             continue;
2790         }
2791         return (line);
2792     }
2793 }
2794
2795 /*-
2796  *-----------------------------------------------------------------------
2797  * ParseFinishLine --
2798  *      Handle the end of a dependency group.
2799  *
2800  * Results:
2801  *      Nothing.
2802  *
2803  * Side Effects:
2804  *      inLine set FALSE. 'targets' list destroyed.
2805  *
2806  *-----------------------------------------------------------------------
2807  */
2808 static void
2809 ParseFinishLine(void)
2810 {
2811     if (inLine) {
2812         Lst_ForEach(targets, Suff_EndTransform, NULL);
2813         Lst_Destroy(targets, ParseHasCommands);
2814         targets = NULL;
2815         inLine = FALSE;
2816     }
2817 }
2818
2819
2820 /*-
2821  *---------------------------------------------------------------------
2822  * Parse_File --
2823  *      Parse a file into its component parts, incorporating it into the
2824  *      current dependency graph. This is the main function and controls
2825  *      almost every other function in this module
2826  *
2827  * Input:
2828  *      name            the name of the file being read
2829  *      fd              Open file to makefile to parse
2830  *
2831  * Results:
2832  *      None
2833  *
2834  * Side Effects:
2835  *      closes fd.
2836  *      Loads. Nodes are added to the list of all targets, nodes and links
2837  *      are added to the dependency graph. etc. etc. etc.
2838  *---------------------------------------------------------------------
2839  */
2840 void
2841 Parse_File(const char *name, int fd)
2842 {
2843     char          *cp;          /* pointer into the line */
2844     char          *line;        /* the line we're working on */
2845     struct loadedfile *lf;
2846
2847     lf = loadfile(name, fd);
2848
2849     inLine = FALSE;
2850     fatals = 0;
2851
2852     if (name == NULL) {
2853             name = "(stdin)";
2854     }
2855
2856     Parse_SetInput(name, 0, -1, loadedfile_nextbuf, lf);
2857     curFile->lf = lf;
2858
2859     do {
2860         for (; (line = ParseReadLine()) != NULL; ) {
2861             if (DEBUG(PARSE))
2862                 fprintf(debug_file, "ParseReadLine (%d): '%s'\n",
2863                         curFile->lineno, line);
2864             if (*line == '.') {
2865                 /*
2866                  * Lines that begin with the special character may be
2867                  * include or undef directives.
2868                  * On the other hand they can be suffix rules (.c.o: ...)
2869                  * or just dependencies for filenames that start '.'.
2870                  */
2871                 for (cp = line + 1; isspace((unsigned char)*cp); cp++) {
2872                     continue;
2873                 }
2874                 if (strncmp(cp, "include", 7) == 0 ||
2875                         ((cp[0] == 's' || cp[0] == '-') &&
2876                             strncmp(&cp[1], "include", 7) == 0)) {
2877                     ParseDoInclude(cp);
2878                     continue;
2879                 }
2880                 if (strncmp(cp, "undef", 5) == 0) {
2881                     char *cp2;
2882                     for (cp += 5; isspace((unsigned char) *cp); cp++)
2883                         continue;
2884                     for (cp2 = cp; !isspace((unsigned char) *cp2) &&
2885                                    (*cp2 != '\0'); cp2++)
2886                         continue;
2887                     *cp2 = '\0';
2888                     Var_Delete(cp, VAR_GLOBAL);
2889                     continue;
2890                 } else if (strncmp(cp, "export", 6) == 0) {
2891                     for (cp += 6; isspace((unsigned char) *cp); cp++)
2892                         continue;
2893                     Var_Export(cp, 1);
2894                     continue;
2895                 } else if (strncmp(cp, "unexport", 8) == 0) {
2896                     Var_UnExport(cp);
2897                     continue;
2898                 } else if (strncmp(cp, "info", 4) == 0 ||
2899                            strncmp(cp, "error", 5) == 0 ||
2900                            strncmp(cp, "warning", 7) == 0) {
2901                     if (ParseMessage(cp))
2902                         continue;
2903                 }                   
2904             }
2905
2906             if (*line == '\t') {
2907                 /*
2908                  * If a line starts with a tab, it can only hope to be
2909                  * a creation command.
2910                  */
2911                 cp = line + 1;
2912               shellCommand:
2913                 for (; isspace ((unsigned char)*cp); cp++) {
2914                     continue;
2915                 }
2916                 if (*cp) {
2917                     if (!inLine)
2918                         Parse_Error(PARSE_FATAL,
2919                                      "Unassociated shell command \"%s\"",
2920                                      cp);
2921                     /*
2922                      * So long as it's not a blank line and we're actually
2923                      * in a dependency spec, add the command to the list of
2924                      * commands of all targets in the dependency spec
2925                      */
2926                     if (targets) {
2927                         cp = bmake_strdup(cp);
2928                         Lst_ForEach(targets, ParseAddCmd, cp);
2929 #ifdef CLEANUP
2930                         Lst_AtEnd(targCmds, cp);
2931 #endif
2932                     }
2933                 }
2934                 continue;
2935             }
2936
2937 #ifdef SYSVINCLUDE
2938             if (((strncmp(line, "include", 7) == 0 &&
2939                     isspace((unsigned char) line[7])) ||
2940                         ((line[0] == 's' || line[0] == '-') &&
2941                             strncmp(&line[1], "include", 7) == 0 &&
2942                             isspace((unsigned char) line[8]))) &&
2943                     strchr(line, ':') == NULL) {
2944                 /*
2945                  * It's an S3/S5-style "include".
2946                  */
2947                 ParseTraditionalInclude(line);
2948                 continue;
2949             }
2950 #endif
2951 #ifdef GMAKEEXPORT
2952             if (strncmp(line, "export", 6) == 0 &&
2953                 isspace((unsigned char) line[6]) &&
2954                 strchr(line, ':') == NULL) {
2955                 /*
2956                  * It's a Gmake "export".
2957                  */
2958                 ParseGmakeExport(line);
2959                 continue;
2960             }
2961 #endif
2962             if (Parse_IsVar(line)) {
2963                 ParseFinishLine();
2964                 Parse_DoVar(line, VAR_GLOBAL);
2965                 continue;
2966             }
2967
2968 #ifndef POSIX
2969             /*
2970              * To make life easier on novices, if the line is indented we
2971              * first make sure the line has a dependency operator in it.
2972              * If it doesn't have an operator and we're in a dependency
2973              * line's script, we assume it's actually a shell command
2974              * and add it to the current list of targets.
2975              */
2976             cp = line;
2977             if (isspace((unsigned char) line[0])) {
2978                 while ((*cp != '\0') && isspace((unsigned char) *cp))
2979                     cp++;
2980                 while (*cp && (ParseIsEscaped(line, cp) ||
2981                         (*cp != ':') && (*cp != '!'))) {
2982                     cp++;
2983                 }
2984                 if (*cp == '\0') {
2985                     if (inLine) {
2986                         Parse_Error(PARSE_WARNING,
2987                                      "Shell command needs a leading tab");
2988                         goto shellCommand;
2989                     }
2990                 }
2991             }
2992 #endif
2993             ParseFinishLine();
2994
2995             /*
2996              * For some reason - probably to make the parser impossible -
2997              * a ';' can be used to separate commands from dependencies.
2998              * Attempt to avoid ';' inside substitution patterns.
2999              */
3000             {
3001                 int level = 0;
3002
3003                 for (cp = line; *cp != 0; cp++) {
3004                     if (*cp == '\\' && cp[1] != 0) {
3005                         cp++;
3006                         continue;
3007                     }
3008                     if (*cp == '$' &&
3009                         (cp[1] == '(' || cp[1] == '{')) {
3010                         level++;
3011                         continue;
3012                     }
3013                     if (level > 0) {
3014                         if (*cp == ')' || *cp == '}') {
3015                             level--;
3016                             continue;
3017                         }
3018                     } else if (*cp == ';') {
3019                         break;
3020                     }
3021                 }
3022             }
3023             if (*cp != 0)
3024                 /* Terminate the dependency list at the ';' */
3025                 *cp++ = 0;
3026             else
3027                 cp = NULL;
3028
3029             /*
3030              * We now know it's a dependency line so it needs to have all
3031              * variables expanded before being parsed. Tell the variable
3032              * module to complain if some variable is undefined...
3033              */
3034             line = Var_Subst(NULL, line, VAR_CMD, TRUE);
3035
3036             /*
3037              * Need a non-circular list for the target nodes
3038              */
3039             if (targets)
3040                 Lst_Destroy(targets, NULL);
3041
3042             targets = Lst_Init(FALSE);
3043             inLine = TRUE;
3044
3045             ParseDoDependency(line);
3046             free(line);
3047
3048             /* If there were commands after a ';', add them now */
3049             if (cp != NULL) {
3050                 goto shellCommand;
3051             }
3052         }
3053         /*
3054          * Reached EOF, but it may be just EOF of an include file...
3055          */
3056     } while (ParseEOF() == CONTINUE);
3057
3058     if (fatals) {
3059         (void)fflush(stdout);
3060         (void)fprintf(stderr,
3061             "%s: Fatal errors encountered -- cannot continue",
3062             progname);
3063         PrintOnError(NULL, NULL);
3064         exit(1);
3065     }
3066 }
3067
3068 /*-
3069  *---------------------------------------------------------------------
3070  * Parse_Init --
3071  *      initialize the parsing module
3072  *
3073  * Results:
3074  *      none
3075  *
3076  * Side Effects:
3077  *      the parseIncPath list is initialized...
3078  *---------------------------------------------------------------------
3079  */
3080 void
3081 Parse_Init(void)
3082 {
3083     mainNode = NULL;
3084     parseIncPath = Lst_Init(FALSE);
3085     sysIncPath = Lst_Init(FALSE);
3086     defIncPath = Lst_Init(FALSE);
3087     includes = Lst_Init(FALSE);
3088 #ifdef CLEANUP
3089     targCmds = Lst_Init(FALSE);
3090 #endif
3091 }
3092
3093 void
3094 Parse_End(void)
3095 {
3096 #ifdef CLEANUP
3097     Lst_Destroy(targCmds, (FreeProc *)free);
3098     if (targets)
3099         Lst_Destroy(targets, NULL);
3100     Lst_Destroy(defIncPath, Dir_Destroy);
3101     Lst_Destroy(sysIncPath, Dir_Destroy);
3102     Lst_Destroy(parseIncPath, Dir_Destroy);
3103     Lst_Destroy(includes, NULL);        /* Should be empty now */
3104 #endif
3105 }
3106
3107
3108 /*-
3109  *-----------------------------------------------------------------------
3110  * Parse_MainName --
3111  *      Return a Lst of the main target to create for main()'s sake. If
3112  *      no such target exists, we Punt with an obnoxious error message.
3113  *
3114  * Results:
3115  *      A Lst of the single node to create.
3116  *
3117  * Side Effects:
3118  *      None.
3119  *
3120  *-----------------------------------------------------------------------
3121  */
3122 Lst
3123 Parse_MainName(void)
3124 {
3125     Lst           mainList;     /* result list */
3126
3127     mainList = Lst_Init(FALSE);
3128
3129     if (mainNode == NULL) {
3130         Punt("no target to make.");
3131         /*NOTREACHED*/
3132     } else if (mainNode->type & OP_DOUBLEDEP) {
3133         (void)Lst_AtEnd(mainList, mainNode);
3134         Lst_Concat(mainList, mainNode->cohorts, LST_CONCNEW);
3135     }
3136     else
3137         (void)Lst_AtEnd(mainList, mainNode);
3138     Var_Append(".TARGETS", mainNode->name, VAR_GLOBAL);
3139     return (mainList);
3140 }
3141
3142 /*-
3143  *-----------------------------------------------------------------------
3144  * ParseMark --
3145  *      Add the filename and lineno to the GNode so that we remember
3146  *      where it was first defined.
3147  *
3148  * Side Effects:
3149  *      None.
3150  *
3151  *-----------------------------------------------------------------------
3152  */
3153 static void
3154 ParseMark(GNode *gn)
3155 {
3156     gn->fname = curFile->fname;
3157     gn->lineno = curFile->lineno;
3158 }