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