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