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