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