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