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