]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/bmake/suff.c
MFV r366990: less v563.
[FreeBSD/FreeBSD.git] / contrib / bmake / suff.c
1 /*      $NetBSD: suff.c,v 1.142 2020/08/31 16:44:25 rillig Exp $        */
2
3 /*
4  * Copyright (c) 1988, 1989, 1990, 1993
5  *      The Regents of the University of California.  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. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34
35 /*
36  * Copyright (c) 1989 by Berkeley Softworks
37  * All rights reserved.
38  *
39  * This code is derived from software contributed to Berkeley by
40  * Adam de Boor.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. All advertising materials mentioning features or use of this software
51  *    must display the following acknowledgement:
52  *      This product includes software developed by the University of
53  *      California, Berkeley and its contributors.
54  * 4. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70
71 #ifndef MAKE_NATIVE
72 static char rcsid[] = "$NetBSD: suff.c,v 1.142 2020/08/31 16:44:25 rillig Exp $";
73 #else
74 #include <sys/cdefs.h>
75 #ifndef lint
76 #if 0
77 static char sccsid[] = "@(#)suff.c      8.4 (Berkeley) 3/21/94";
78 #else
79 __RCSID("$NetBSD: suff.c,v 1.142 2020/08/31 16:44:25 rillig Exp $");
80 #endif
81 #endif /* not lint */
82 #endif
83
84 /*-
85  * suff.c --
86  *      Functions to maintain suffix lists and find implicit dependents
87  *      using suffix transformation rules
88  *
89  * Interface:
90  *      Suff_Init               Initialize all things to do with suffixes.
91  *
92  *      Suff_End                Cleanup the module
93  *
94  *      Suff_DoPaths            This function is used to make life easier
95  *                              when searching for a file according to its
96  *                              suffix. It takes the global search path,
97  *                              as defined using the .PATH: target, and appends
98  *                              its directories to the path of each of the
99  *                              defined suffixes, as specified using
100  *                              .PATH<suffix>: targets. In addition, all
101  *                              directories given for suffixes labeled as
102  *                              include files or libraries, using the .INCLUDES
103  *                              or .LIBS targets, are played with using
104  *                              Dir_MakeFlags to create the .INCLUDES and
105  *                              .LIBS global variables.
106  *
107  *      Suff_ClearSuffixes      Clear out all the suffixes and defined
108  *                              transformations.
109  *
110  *      Suff_IsTransform        Return TRUE if the passed string is the lhs
111  *                              of a transformation rule.
112  *
113  *      Suff_AddSuffix          Add the passed string as another known suffix.
114  *
115  *      Suff_GetPath            Return the search path for the given suffix.
116  *
117  *      Suff_AddInclude         Mark the given suffix as denoting an include
118  *                              file.
119  *
120  *      Suff_AddLib             Mark the given suffix as denoting a library.
121  *
122  *      Suff_AddTransform       Add another transformation to the suffix
123  *                              graph. Returns  GNode suitable for framing, I
124  *                              mean, tacking commands, attributes, etc. on.
125  *
126  *      Suff_SetNull            Define the suffix to consider the suffix of
127  *                              any file that doesn't have a known one.
128  *
129  *      Suff_FindDeps           Find implicit sources for and the location of
130  *                              a target based on its suffix. Returns the
131  *                              bottom-most node added to the graph or NULL
132  *                              if the target had no implicit sources.
133  *
134  *      Suff_FindPath           Return the appropriate path to search in
135  *                              order to find the node.
136  */
137
138 #include          "make.h"
139 #include          "dir.h"
140
141 #define SUFF_DEBUG0(fmt) \
142     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt)
143
144 #define SUFF_DEBUG1(fmt, arg1) \
145     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1)
146
147 #define SUFF_DEBUG2(fmt, arg1, arg2) \
148     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1, arg2)
149
150 #define SUFF_DEBUG3(fmt, arg1, arg2, arg3) \
151     if (!DEBUG(SUFF)) (void) 0; else fprintf(debug_file, fmt, arg1, arg2, arg3)
152
153 static Lst       sufflist;      /* Lst of suffixes */
154 #ifdef CLEANUP
155 static Lst       suffClean;     /* Lst of suffixes to be cleaned */
156 #endif
157 static Lst       srclist;       /* Lst of sources */
158 static Lst       transforms;    /* Lst of transformation rules */
159
160 static int        sNum = 0;     /* Counter for assigning suffix numbers */
161
162 typedef enum {
163     SUFF_INCLUDE        = 0x01, /* One which is #include'd */
164     SUFF_LIBRARY        = 0x02, /* One which contains a library */
165     SUFF_NULL           = 0x04  /* The empty suffix */
166     /* XXX: Why is SUFF_NULL needed? Wouldn't nameLen == 0 mean the same? */
167 } SuffFlags;
168
169 ENUM_FLAGS_RTTI_3(SuffFlags,
170                   SUFF_INCLUDE, SUFF_LIBRARY, SUFF_NULL);
171
172 /*
173  * Structure describing an individual suffix.
174  */
175 typedef struct Suff {
176     char         *name;         /* The suffix itself, such as ".c" */
177     int          nameLen;       /* Length of the name, to avoid strlen calls */
178     SuffFlags    flags;         /* Type of suffix */
179     Lst          searchPath;    /* The path along which files of this suffix
180                                  * may be found */
181     int          sNum;          /* The suffix number */
182     int          refCount;      /* Reference count of list membership */
183     Lst          parents;       /* Suffixes we have a transformation to */
184     Lst          children;      /* Suffixes we have a transformation from */
185     Lst          ref;           /* List of lists this suffix is referenced */
186 } Suff;
187
188 /*
189  * Structure used in the search for implied sources.
190  */
191 typedef struct _Src {
192     char            *file;      /* The file to look for */
193     char            *pref;      /* Prefix from which file was formed */
194     Suff            *suff;      /* The suffix on the file */
195     struct _Src     *parent;    /* The Src for which this is a source */
196     GNode           *node;      /* The node describing the file */
197     int             children;   /* Count of existing children (so we don't free
198                                  * this thing too early or never nuke it) */
199 #ifdef DEBUG_SRC
200     Lst             cp;         /* Debug; children list */
201 #endif
202 } Src;
203
204 /*
205  * A structure for passing more than one argument to the Lst-library-invoked
206  * function...
207  */
208 typedef struct {
209     Lst            l;
210     Src            *s;
211 } LstSrc;
212
213 typedef struct {
214     GNode         **gn;
215     Suff           *s;
216     Boolean         r;
217 } GNodeSuff;
218
219 static Suff         *suffNull;  /* The NULL suffix for this run */
220 static Suff         *emptySuff; /* The empty suffix required for POSIX
221                                  * single-suffix transformation rules */
222
223
224 static void SuffUnRef(void *, void *);
225 static void SuffFree(void *);
226 static void SuffInsert(Lst, Suff *);
227 static void SuffRemove(Lst, Suff *);
228 static Boolean SuffParseTransform(char *, Suff **, Suff **);
229 static int SuffRebuildGraph(void *, void *);
230 static int SuffScanTargets(void *, void *);
231 static int SuffAddSrc(void *, void *);
232 static void SuffAddLevel(Lst, Src *);
233 static void SuffExpandChildren(LstNode, GNode *);
234 static void SuffExpandWildcards(LstNode, GNode *);
235 static Boolean SuffApplyTransform(GNode *, GNode *, Suff *, Suff *);
236 static void SuffFindDeps(GNode *, Lst);
237 static void SuffFindArchiveDeps(GNode *, Lst);
238 static void SuffFindNormalDeps(GNode *, Lst);
239 static int SuffPrintName(void *, void *);
240 static int SuffPrintSuff(void *, void *);
241 static int SuffPrintTrans(void *, void *);
242
243         /*************** Lst Predicates ****************/
244 /*-
245  *-----------------------------------------------------------------------
246  * SuffStrIsPrefix  --
247  *      See if pref is a prefix of str.
248  *
249  * Input:
250  *      pref            possible prefix
251  *      str             string to check
252  *
253  * Results:
254  *      NULL if it ain't, pointer to character in str after prefix if so
255  *
256  * Side Effects:
257  *      None
258  *-----------------------------------------------------------------------
259  */
260 static const char *
261 SuffStrIsPrefix(const char *pref, const char *str)
262 {
263     while (*str && *pref == *str) {
264         pref++;
265         str++;
266     }
267
268     return *pref ? NULL : str;
269 }
270
271 typedef struct {
272     char        *ename;         /* The end of the name */
273     int          len;           /* Length of the name */
274 } SuffSuffGetSuffixArgs;
275
276 /* See if suff is a suffix of str. str->ename should point to THE END
277  * of the string to check. (THE END == the null byte)
278  *
279  * Input:
280  *      s               possible suffix
281  *      str             string to examine
282  *
283  * Results:
284  *      NULL if it ain't, pointer to character in str before suffix if
285  *      it is.
286  */
287 static char *
288 SuffSuffGetSuffix(const Suff *s, const SuffSuffGetSuffixArgs *str)
289 {
290     char  *p1;          /* Pointer into suffix name */
291     char  *p2;          /* Pointer into string being examined */
292
293     if (str->len < s->nameLen)
294         return NULL;            /* this string is shorter than the suffix */
295
296     p1 = s->name + s->nameLen;
297     p2 = str->ename;
298
299     while (p1 >= s->name && *p1 == *p2) {
300         p1--;
301         p2--;
302     }
303
304     return p1 == s->name - 1 ? p2 : NULL;
305 }
306
307 /* Predicate form of SuffSuffGetSuffix, for Lst_Find. */
308 static Boolean
309 SuffSuffIsSuffix(const void *s, const void *sd)
310 {
311     return SuffSuffGetSuffix(s, sd) != NULL;
312 }
313
314 /* See if the suffix has the desired name. */
315 static Boolean
316 SuffSuffHasName(const void *s, const void *desiredName)
317 {
318     return strcmp(((const Suff *)s)->name, desiredName) == 0;
319 }
320
321 /* See if the suffix name is a prefix of the string. Care must be taken when
322  * using this to search for transformations and what-not, since there could
323  * well be two suffixes, one of which is a prefix of the other... */
324 static Boolean
325 SuffSuffIsPrefix(const void *s, const void *str)
326 {
327     return SuffStrIsPrefix(((const Suff *)s)->name, str) != NULL;
328 }
329
330 /* See if the graph node has the desired name. */
331 static Boolean
332 SuffGNHasName(const void *gn, const void *desiredName)
333 {
334     return strcmp(((const GNode *)gn)->name, desiredName) == 0;
335 }
336
337             /*********** Maintenance Functions ************/
338
339 static void
340 SuffUnRef(void *lp, void *sp)
341 {
342     Lst l = (Lst) lp;
343
344     LstNode ln = Lst_FindDatum(l, sp);
345     if (ln != NULL) {
346         Lst_Remove(l, ln);
347         ((Suff *)sp)->refCount--;
348     }
349 }
350
351 /* Free up all memory associated with the given suffix structure. */
352 static void
353 SuffFree(void *sp)
354 {
355     Suff *s = (Suff *)sp;
356
357     if (s == suffNull)
358         suffNull = NULL;
359
360     if (s == emptySuff)
361         emptySuff = NULL;
362
363 #ifdef notdef
364     /* We don't delete suffixes in order, so we cannot use this */
365     if (s->refCount)
366         Punt("Internal error deleting suffix `%s' with refcount = %d", s->name,
367             s->refCount);
368 #endif
369
370     Lst_Free(s->ref);
371     Lst_Free(s->children);
372     Lst_Free(s->parents);
373     Lst_Destroy(s->searchPath, Dir_Destroy);
374
375     free(s->name);
376     free(s);
377 }
378
379 /* Remove the suffix from the list, and free if it is otherwise unused. */
380 static void
381 SuffRemove(Lst l, Suff *s)
382 {
383     SuffUnRef(l, s);
384     if (s->refCount == 0) {
385         SuffUnRef(sufflist, s);
386         SuffFree(s);
387     }
388 }
389
390 /* Insert the suffix into the list keeping the list ordered by suffix numbers.
391  *
392  * Input:
393  *      l               the list where in s should be inserted
394  *      s               the suffix to insert
395  */
396 static void
397 SuffInsert(Lst l, Suff *s)
398 {
399     LstNode       ln;           /* current element in l we're examining */
400     Suff          *s2 = NULL;   /* the suffix descriptor in this element */
401
402     Lst_Open(l);
403     while ((ln = Lst_Next(l)) != NULL) {
404         s2 = LstNode_Datum(ln);
405         if (s2->sNum >= s->sNum) {
406             break;
407         }
408     }
409     Lst_Close(l);
410
411     SUFF_DEBUG2("inserting %s(%d)...", s->name, s->sNum);
412
413     if (ln == NULL) {
414         SUFF_DEBUG0("at end of list\n");
415         Lst_Append(l, s);
416         s->refCount++;
417         Lst_Append(s->ref, l);
418     } else if (s2->sNum != s->sNum) {
419         SUFF_DEBUG2("before %s(%d)\n", s2->name, s2->sNum);
420         Lst_InsertBefore(l, ln, s);
421         s->refCount++;
422         Lst_Append(s->ref, l);
423     } else {
424         SUFF_DEBUG0("already there\n");
425     }
426 }
427
428 static Suff *
429 SuffNew(const char *name)
430 {
431     Suff *s = bmake_malloc(sizeof(Suff));
432
433     s->name =           bmake_strdup(name);
434     s->nameLen =        strlen(s->name);
435     s->searchPath = Lst_Init();
436     s->children =       Lst_Init();
437     s->parents =        Lst_Init();
438     s->ref =    Lst_Init();
439     s->sNum =           sNum++;
440     s->flags =          0;
441     s->refCount =       1;
442
443     return s;
444 }
445
446 /* This is gross. Nuke the list of suffixes but keep all transformation
447  * rules around. The transformation graph is destroyed in this process, but
448  * we leave the list of rules so when a new graph is formed the rules will
449  * remain. This function is called from the parse module when a .SUFFIXES:\n
450  * line is encountered. */
451 void
452 Suff_ClearSuffixes(void)
453 {
454 #ifdef CLEANUP
455     Lst_MoveAll(suffClean, sufflist);
456 #endif
457     sufflist = Lst_Init();
458     sNum = 0;
459     if (suffNull)
460         SuffFree(suffNull);
461     emptySuff = suffNull = SuffNew("");
462
463     Dir_Concat(suffNull->searchPath, dirSearchPath);
464     suffNull->flags =       SUFF_NULL;
465 }
466
467 /* Parse a transformation string to find its two component suffixes.
468  *
469  * Input:
470  *      str             String being parsed
471  *      out_src         Place to store source of trans.
472  *      out_targ        Place to store target of trans.
473  *
474  * Results:
475  *      TRUE if the string is a valid transformation, FALSE otherwise.
476  */
477 static Boolean
478 SuffParseTransform(char *str, Suff **out_src, Suff **out_targ)
479 {
480     LstNode             srcLn;      /* element in suffix list of trans source*/
481     Suff                *src;       /* Source of transformation */
482     LstNode             targLn;     /* element in suffix list of trans target*/
483     char                *str2;      /* Extra pointer (maybe target suffix) */
484     LstNode             singleLn;   /* element in suffix list of any suffix
485                                      * that exactly matches str */
486     Suff                *single = NULL;/* Source of possible transformation to
487                                      * null suffix */
488
489     srcLn = NULL;
490     singleLn = NULL;
491
492     /*
493      * Loop looking first for a suffix that matches the start of the
494      * string and then for one that exactly matches the rest of it. If
495      * we can find two that meet these criteria, we've successfully
496      * parsed the string.
497      */
498     for (;;) {
499         if (srcLn == NULL) {
500             srcLn = Lst_Find(sufflist, SuffSuffIsPrefix, str);
501         } else {
502             srcLn = Lst_FindFrom(sufflist, LstNode_Next(srcLn),
503                                   SuffSuffIsPrefix, str);
504         }
505         if (srcLn == NULL) {
506             /*
507              * Ran out of source suffixes -- no such rule
508              */
509             if (singleLn != NULL) {
510                 /*
511                  * Not so fast Mr. Smith! There was a suffix that encompassed
512                  * the entire string, so we assume it was a transformation
513                  * to the null suffix (thank you POSIX). We still prefer to
514                  * find a double rule over a singleton, hence we leave this
515                  * check until the end.
516                  *
517                  * XXX: Use emptySuff over suffNull?
518                  */
519                 *out_src = single;
520                 *out_targ = suffNull;
521                 return TRUE;
522             }
523             return FALSE;
524         }
525         src = LstNode_Datum(srcLn);
526         str2 = str + src->nameLen;
527         if (*str2 == '\0') {
528             single = src;
529             singleLn = srcLn;
530         } else {
531             targLn = Lst_Find(sufflist, SuffSuffHasName, str2);
532             if (targLn != NULL) {
533                 *out_src = src;
534                 *out_targ = LstNode_Datum(targLn);
535                 return TRUE;
536             }
537         }
538     }
539 }
540
541 /* Return TRUE if the given string is a transformation rule, that is, a
542  * concatenation of two known suffixes. */
543 Boolean
544 Suff_IsTransform(char *str)
545 {
546     Suff          *src, *targ;
547
548     return SuffParseTransform(str, &src, &targ);
549 }
550
551 /* Add the transformation rule described by the line to the list of rules
552  * and place the transformation itself in the graph.
553  *
554  * The node is placed on the end of the transforms Lst and links are made
555  * between the two suffixes mentioned in the target name.
556
557  * Input:
558  *      line            name of transformation to add
559  *
560  * Results:
561  *      The node created for the transformation in the transforms list
562  */
563 GNode *
564 Suff_AddTransform(char *line)
565 {
566     GNode         *gn;          /* GNode of transformation rule */
567     Suff          *s,           /* source suffix */
568                   *t;           /* target suffix */
569     LstNode       ln;           /* Node for existing transformation */
570     Boolean ok;
571
572     ln = Lst_Find(transforms, SuffGNHasName, line);
573     if (ln == NULL) {
574         /*
575          * Make a new graph node for the transformation. It will be filled in
576          * by the Parse module.
577          */
578         gn = Targ_NewGN(line);
579         Lst_Append(transforms, gn);
580     } else {
581         /*
582          * New specification for transformation rule. Just nuke the old list
583          * of commands so they can be filled in again... We don't actually
584          * free the commands themselves, because a given command can be
585          * attached to several different transformations.
586          */
587         gn = LstNode_Datum(ln);
588         Lst_Free(gn->commands);
589         Lst_Free(gn->children);
590         gn->commands = Lst_Init();
591         gn->children = Lst_Init();
592     }
593
594     gn->type = OP_TRANSFORM;
595
596     ok = SuffParseTransform(line, &s, &t);
597     assert(ok);
598     (void)ok;
599
600     /*
601      * link the two together in the proper relationship and order
602      */
603     SUFF_DEBUG2("defining transformation from `%s' to `%s'\n",
604                 s->name, t->name);
605     SuffInsert(t->children, s);
606     SuffInsert(s->parents, t);
607
608     return gn;
609 }
610
611 /* Handle the finish of a transformation definition, removing the
612  * transformation from the graph if it has neither commands nor sources.
613  * This is a callback procedure for the Parse module via Lst_ForEach.
614  *
615  * If the node has no commands or children, the children and parents lists
616  * of the affected suffixes are altered.
617  *
618  * Input:
619  *      gnp             Node for transformation
620  *
621  * Results:
622  *      0, so that Lst_ForEach continues
623  */
624 int
625 Suff_EndTransform(void *gnp, void *dummy MAKE_ATTR_UNUSED)
626 {
627     GNode *gn = (GNode *)gnp;
628
629     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(gn->cohorts))
630         gn = LstNode_Datum(Lst_Last(gn->cohorts));
631     if ((gn->type & OP_TRANSFORM) && Lst_IsEmpty(gn->commands) &&
632         Lst_IsEmpty(gn->children))
633     {
634         Suff    *s, *t;
635
636         /*
637          * SuffParseTransform() may fail for special rules which are not
638          * actual transformation rules. (e.g. .DEFAULT)
639          */
640         if (SuffParseTransform(gn->name, &s, &t)) {
641             Lst  p;
642
643             SUFF_DEBUG2("deleting transformation from `%s' to `%s'\n",
644                         s->name, t->name);
645
646             /*
647              * Store s->parents because s could be deleted in SuffRemove
648              */
649             p = s->parents;
650
651             /*
652              * Remove the source from the target's children list. We check for a
653              * nil return to handle a beanhead saying something like
654              *  .c.o .c.o:
655              *
656              * We'll be called twice when the next target is seen, but .c and .o
657              * are only linked once...
658              */
659             SuffRemove(t->children, s);
660
661             /*
662              * Remove the target from the source's parents list
663              */
664             SuffRemove(p, t);
665         }
666     } else if (gn->type & OP_TRANSFORM) {
667         SUFF_DEBUG1("transformation %s complete\n", gn->name);
668     }
669
670     return 0;
671 }
672
673 /* Called from Suff_AddSuffix via Lst_ForEach to search through the list of
674  * existing transformation rules and rebuild the transformation graph when
675  * it has been destroyed by Suff_ClearSuffixes. If the given rule is a
676  * transformation involving this suffix and another, existing suffix, the
677  * proper relationship is established between the two.
678  *
679  * The appropriate links will be made between this suffix and others if
680  * transformation rules exist for it.
681  *
682  * Input:
683  *      transformp      Transformation to test
684  *      sp              Suffix to rebuild
685  *
686  * Results:
687  *      0, so that Lst_ForEach continues
688  */
689 static int
690 SuffRebuildGraph(void *transformp, void *sp)
691 {
692     GNode       *transform = (GNode *)transformp;
693     Suff        *s = (Suff *)sp;
694     char        *cp;
695     LstNode     ln;
696     Suff        *s2;
697     SuffSuffGetSuffixArgs sd;
698
699     /*
700      * First see if it is a transformation from this suffix.
701      */
702     cp = UNCONST(SuffStrIsPrefix(s->name, transform->name));
703     if (cp != NULL) {
704         ln = Lst_Find(sufflist, SuffSuffHasName, cp);
705         if (ln != NULL) {
706             /*
707              * Found target. Link in and return, since it can't be anything
708              * else.
709              */
710             s2 = LstNode_Datum(ln);
711             SuffInsert(s2->children, s);
712             SuffInsert(s->parents, s2);
713             return 0;
714         }
715     }
716
717     /*
718      * Not from, maybe to?
719      */
720     sd.len = strlen(transform->name);
721     sd.ename = transform->name + sd.len;
722     cp = SuffSuffGetSuffix(s, &sd);
723     if (cp != NULL) {
724         /*
725          * Null-terminate the source suffix in order to find it.
726          */
727         cp[1] = '\0';
728         ln = Lst_Find(sufflist, SuffSuffHasName, transform->name);
729         /*
730          * Replace the start of the target suffix
731          */
732         cp[1] = s->name[0];
733         if (ln != NULL) {
734             /*
735              * Found it -- establish the proper relationship
736              */
737             s2 = LstNode_Datum(ln);
738             SuffInsert(s->children, s2);
739             SuffInsert(s2->parents, s);
740         }
741     }
742     return 0;
743 }
744
745 /* Called from Suff_AddSuffix via Lst_ForEach to search through the list of
746  * existing targets and find if any of the existing targets can be turned
747  * into a transformation rule.
748  *
749  * If such a target is found and the target is the current main target, the
750  * main target is set to NULL and the next target examined (if that exists)
751  * becomes the main target.
752  *
753  * Results:
754  *      1 if a new main target has been selected, 0 otherwise.
755  */
756 static int
757 SuffScanTargets(void *targetp, void *gsp)
758 {
759     GNode       *target = (GNode *)targetp;
760     GNodeSuff   *gs = (GNodeSuff *)gsp;
761     Suff        *s, *t;
762     char        *ptr;
763
764     if (*gs->gn == NULL && gs->r && (target->type & OP_NOTARGET) == 0) {
765         *gs->gn = target;
766         Targ_SetMain(target);
767         return 1;
768     }
769
770     if (target->type == OP_TRANSFORM)
771         return 0;
772
773     if ((ptr = strstr(target->name, gs->s->name)) == NULL ||
774         ptr == target->name)
775         return 0;
776
777     if (SuffParseTransform(target->name, &s, &t)) {
778         if (*gs->gn == target) {
779             gs->r = TRUE;
780             *gs->gn = NULL;
781             Targ_SetMain(NULL);
782         }
783         Lst_Free(target->children);
784         target->children = Lst_Init();
785         target->type = OP_TRANSFORM;
786         /*
787          * link the two together in the proper relationship and order
788          */
789         SUFF_DEBUG2("defining transformation from `%s' to `%s'\n",
790                     s->name, t->name);
791         SuffInsert(t->children, s);
792         SuffInsert(s->parents, t);
793     }
794     return 0;
795 }
796
797 /* Add the suffix to the end of the list of known suffixes.
798  * Should we restructure the suffix graph? Make doesn't...
799  *
800  * A GNode is created for the suffix and a Suff structure is created and
801  * added to the suffixes list unless the suffix was already known.
802  * The mainNode passed can be modified if a target mutated into a
803  * transform and that target happened to be the main target.
804  *
805  * Input:
806  *      name            the name of the suffix to add
807  */
808 void
809 Suff_AddSuffix(const char *name, GNode **gn)
810 {
811     Suff          *s;       /* new suffix descriptor */
812     LstNode       ln;
813     GNodeSuff     gs;
814
815     ln = Lst_Find(sufflist, SuffSuffHasName, name);
816     if (ln == NULL) {
817         s = SuffNew(name);
818
819         Lst_Append(sufflist, s);
820         /*
821          * We also look at our existing targets list to see if adding
822          * this suffix will make one of our current targets mutate into
823          * a suffix rule. This is ugly, but other makes treat all targets
824          * that start with a . as suffix rules.
825          */
826         gs.gn = gn;
827         gs.s  = s;
828         gs.r  = FALSE;
829         Lst_ForEach(Targ_List(), SuffScanTargets, &gs);
830         /*
831          * Look for any existing transformations from or to this suffix.
832          * XXX: Only do this after a Suff_ClearSuffixes?
833          */
834         Lst_ForEach(transforms, SuffRebuildGraph, s);
835     }
836 }
837
838 /* Return the search path for the given suffix, or NULL. */
839 Lst
840 Suff_GetPath(char *sname)
841 {
842     LstNode       ln;
843     Suff          *s;
844
845     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
846     if (ln == NULL) {
847         return NULL;
848     } else {
849         s = LstNode_Datum(ln);
850         return s->searchPath;
851     }
852 }
853
854 /* Extend the search paths for all suffixes to include the default search
855  * path.
856  *
857  * The searchPath field of all the suffixes is extended by the directories
858  * in dirSearchPath. If paths were specified for the ".h" suffix, the
859  * directories are stuffed into a global variable called ".INCLUDES" with
860  * each directory preceded by a -I. The same is done for the ".a" suffix,
861  * except the variable is called ".LIBS" and the flag is -L.
862  */
863 void
864 Suff_DoPaths(void)
865 {
866     Suff                *s;
867     LstNode             ln;
868     char                *ptr;
869     Lst                 inIncludes; /* Cumulative .INCLUDES path */
870     Lst                 inLibs;     /* Cumulative .LIBS path */
871
872
873     inIncludes = Lst_Init();
874     inLibs = Lst_Init();
875
876     Lst_Open(sufflist);
877     while ((ln = Lst_Next(sufflist)) != NULL) {
878         s = LstNode_Datum(ln);
879         if (!Lst_IsEmpty(s->searchPath)) {
880 #ifdef INCLUDES
881             if (s->flags & SUFF_INCLUDE) {
882                 Dir_Concat(inIncludes, s->searchPath);
883             }
884 #endif /* INCLUDES */
885 #ifdef LIBRARIES
886             if (s->flags & SUFF_LIBRARY) {
887                 Dir_Concat(inLibs, s->searchPath);
888             }
889 #endif /* LIBRARIES */
890             Dir_Concat(s->searchPath, dirSearchPath);
891         } else {
892             Lst_Destroy(s->searchPath, Dir_Destroy);
893             s->searchPath = Lst_Copy(dirSearchPath, Dir_CopyDir);
894         }
895     }
896     Lst_Close(sufflist);
897
898     Var_Set(".INCLUDES", ptr = Dir_MakeFlags("-I", inIncludes), VAR_GLOBAL);
899     free(ptr);
900     Var_Set(".LIBS", ptr = Dir_MakeFlags("-L", inLibs), VAR_GLOBAL);
901     free(ptr);
902
903     Lst_Destroy(inIncludes, Dir_Destroy);
904     Lst_Destroy(inLibs, Dir_Destroy);
905 }
906
907 /* Add the given suffix as a type of file which gets included.
908  * Called from the parse module when a .INCLUDES line is parsed.
909  * The suffix must have already been defined.
910  * The SUFF_INCLUDE bit is set in the suffix's flags field.
911  *
912  * Input:
913  *      sname           Name of the suffix to mark
914  */
915 void
916 Suff_AddInclude(char *sname)
917 {
918     LstNode       ln;
919     Suff          *s;
920
921     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
922     if (ln != NULL) {
923         s = LstNode_Datum(ln);
924         s->flags |= SUFF_INCLUDE;
925     }
926 }
927
928 /* Add the given suffix as a type of file which is a library.
929  * Called from the parse module when parsing a .LIBS line.
930  * The suffix must have been defined via .SUFFIXES before this is called.
931  * The SUFF_LIBRARY bit is set in the suffix's flags field.
932  *
933  * Input:
934  *      sname           Name of the suffix to mark
935  */
936 void
937 Suff_AddLib(const char *sname)
938 {
939     LstNode       ln;
940     Suff          *s;
941
942     ln = Lst_Find(sufflist, SuffSuffHasName, sname);
943     if (ln != NULL) {
944         s = LstNode_Datum(ln);
945         s->flags |= SUFF_LIBRARY;
946     }
947 }
948
949           /********** Implicit Source Search Functions *********/
950
951 /* Add a suffix as a Src structure to the given list with its parent
952  * being the given Src structure. If the suffix is the null suffix,
953  * the prefix is used unaltered as the file name in the Src structure.
954  *
955  * Input:
956  *      sp              suffix for which to create a Src structure
957  *      lsp             list and parent for the new Src
958  *
959  * Results:
960  *      0, so that Lst_ForEach continues
961  */
962 static int
963 SuffAddSrc(void *sp, void *lsp)
964 {
965     Suff        *s = (Suff *)sp;
966     LstSrc      *ls = (LstSrc *)lsp;
967     Src         *s2;        /* new Src structure */
968     Src         *targ;      /* Target structure */
969
970     targ = ls->s;
971
972     if ((s->flags & SUFF_NULL) && (*s->name != '\0')) {
973         /*
974          * If the suffix has been marked as the NULL suffix, also create a Src
975          * structure for a file with no suffix attached. Two birds, and all
976          * that...
977          */
978         s2 = bmake_malloc(sizeof(Src));
979         s2->file =      bmake_strdup(targ->pref);
980         s2->pref =      targ->pref;
981         s2->parent =    targ;
982         s2->node =      NULL;
983         s2->suff =      s;
984         s->refCount++;
985         s2->children =  0;
986         targ->children += 1;
987         Lst_Append(ls->l, s2);
988 #ifdef DEBUG_SRC
989         s2->cp = Lst_Init();
990         Lst_Append(targ->cp, s2);
991         fprintf(debug_file, "1 add %p %p to %p:", targ, s2, ls->l);
992         Lst_ForEach(ls->l, PrintAddr, NULL);
993         fprintf(debug_file, "\n");
994 #endif
995     }
996     s2 = bmake_malloc(sizeof(Src));
997     s2->file =      str_concat2(targ->pref, s->name);
998     s2->pref =      targ->pref;
999     s2->parent =    targ;
1000     s2->node =      NULL;
1001     s2->suff =      s;
1002     s->refCount++;
1003     s2->children =  0;
1004     targ->children += 1;
1005     Lst_Append(ls->l, s2);
1006 #ifdef DEBUG_SRC
1007     s2->cp = Lst_Init();
1008     Lst_Append(targ->cp, s2);
1009     fprintf(debug_file, "2 add %p %p to %p:", targ, s2, ls->l);
1010     Lst_ForEach(ls->l, PrintAddr, NULL);
1011     fprintf(debug_file, "\n");
1012 #endif
1013
1014     return 0;
1015 }
1016
1017 /* Add all the children of targ as Src structures to the given list.
1018  *
1019  * Input:
1020  *      l               list to which to add the new level
1021  *      targ            Src structure to use as the parent
1022  */
1023 static void
1024 SuffAddLevel(Lst l, Src *targ)
1025 {
1026     LstSrc         ls;
1027
1028     ls.s = targ;
1029     ls.l = l;
1030
1031     Lst_ForEach(targ->suff->children, SuffAddSrc, &ls);
1032 }
1033
1034 /* Free the first Src in the list that doesn't have a reference count.
1035  * Return whether a Src was removed. */
1036 static Boolean
1037 SuffRemoveSrc(Lst l)
1038 {
1039     LstNode ln;
1040     Src *s;
1041
1042     Lst_Open(l);
1043
1044 #ifdef DEBUG_SRC
1045     fprintf(debug_file, "cleaning %lx: ", (unsigned long) l);
1046     Lst_ForEach(l, PrintAddr, NULL);
1047     fprintf(debug_file, "\n");
1048 #endif
1049
1050     while ((ln = Lst_Next(l)) != NULL) {
1051         s = LstNode_Datum(ln);
1052         if (s->children == 0) {
1053             free(s->file);
1054             if (!s->parent)
1055                 free(s->pref);
1056             else {
1057 #ifdef DEBUG_SRC
1058                 LstNode ln2 = Lst_FindDatum(s->parent->cp, s);
1059                 if (ln2 != NULL)
1060                     Lst_Remove(s->parent->cp, ln2);
1061 #endif
1062                 --s->parent->children;
1063             }
1064 #ifdef DEBUG_SRC
1065             fprintf(debug_file, "free: [l=%p] p=%p %d\n", l, s, s->children);
1066             Lst_Free(s->cp);
1067 #endif
1068             Lst_Remove(l, ln);
1069             free(s);
1070             Lst_Close(l);
1071             return TRUE;
1072         }
1073 #ifdef DEBUG_SRC
1074         else {
1075             fprintf(debug_file, "keep: [l=%p] p=%p %d: ", l, s, s->children);
1076             Lst_ForEach(s->cp, PrintAddr, NULL);
1077             fprintf(debug_file, "\n");
1078         }
1079 #endif
1080     }
1081
1082     Lst_Close(l);
1083
1084     return FALSE;
1085 }
1086
1087 /* Find the first existing file/target in the list srcs.
1088  *
1089  * Input:
1090  *      srcs            list of Src structures to search through
1091  *
1092  * Results:
1093  *      The lowest structure in the chain of transformations, or NULL.
1094  */
1095 static Src *
1096 SuffFindThem(Lst srcs, Lst slst)
1097 {
1098     Src            *s;          /* current Src */
1099     Src            *rs;         /* returned Src */
1100     char           *ptr;
1101
1102     rs = NULL;
1103
1104     while (!Lst_IsEmpty(srcs)) {
1105         s = Lst_Dequeue(srcs);
1106
1107         SUFF_DEBUG1("\ttrying %s...", s->file);
1108
1109         /*
1110          * A file is considered to exist if either a node exists in the
1111          * graph for it or the file actually exists.
1112          */
1113         if (Targ_FindNode(s->file, TARG_NOCREATE) != NULL) {
1114 #ifdef DEBUG_SRC
1115             fprintf(debug_file, "remove %p from %p\n", s, srcs);
1116 #endif
1117             rs = s;
1118             break;
1119         }
1120
1121         if ((ptr = Dir_FindFile(s->file, s->suff->searchPath)) != NULL) {
1122             rs = s;
1123 #ifdef DEBUG_SRC
1124             fprintf(debug_file, "remove %p from %p\n", s, srcs);
1125 #endif
1126             free(ptr);
1127             break;
1128         }
1129
1130         SUFF_DEBUG0("not there\n");
1131
1132         SuffAddLevel(srcs, s);
1133         Lst_Append(slst, s);
1134     }
1135
1136     if (rs) {
1137         SUFF_DEBUG0("got it\n");
1138     }
1139     return rs;
1140 }
1141
1142 /* See if any of the children of the target in the Src structure is one from
1143  * which the target can be transformed. If there is one, a Src structure is
1144  * put together for it and returned.
1145  *
1146  * Input:
1147  *      targ            Src to play with
1148  *
1149  * Results:
1150  *      The Src of the "winning" child, or NULL.
1151  */
1152 static Src *
1153 SuffFindCmds(Src *targ, Lst slst)
1154 {
1155     LstNode             ln;     /* General-purpose list node */
1156     GNode               *t,     /* Target GNode */
1157                         *s;     /* Source GNode */
1158     int                 prefLen;/* The length of the defined prefix */
1159     Suff                *suff;  /* Suffix on matching beastie */
1160     Src                 *ret;   /* Return value */
1161     char                *cp;
1162
1163     t = targ->node;
1164     Lst_Open(t->children);
1165     prefLen = strlen(targ->pref);
1166
1167     for (;;) {
1168         ln = Lst_Next(t->children);
1169         if (ln == NULL) {
1170             Lst_Close(t->children);
1171             return NULL;
1172         }
1173         s = LstNode_Datum(ln);
1174
1175         if (s->type & OP_OPTIONAL && Lst_IsEmpty(t->commands)) {
1176             /*
1177              * We haven't looked to see if .OPTIONAL files exist yet, so
1178              * don't use one as the implicit source.
1179              * This allows us to use .OPTIONAL in .depend files so make won't
1180              * complain "don't know how to make xxx.h' when a dependent file
1181              * has been moved/deleted.
1182              */
1183             continue;
1184         }
1185
1186         cp = strrchr(s->name, '/');
1187         if (cp == NULL) {
1188             cp = s->name;
1189         } else {
1190             cp++;
1191         }
1192         if (strncmp(cp, targ->pref, prefLen) != 0)
1193             continue;
1194         /*
1195          * The node matches the prefix ok, see if it has a known
1196          * suffix.
1197          */
1198         ln = Lst_Find(sufflist, SuffSuffHasName, &cp[prefLen]);
1199         if (ln == NULL)
1200             continue;
1201         /*
1202          * It even has a known suffix, see if there's a transformation
1203          * defined between the node's suffix and the target's suffix.
1204          *
1205          * XXX: Handle multi-stage transformations here, too.
1206          */
1207         suff = LstNode_Datum(ln);
1208
1209         /* XXX: Can targ->suff be NULL here? */
1210         if (targ->suff != NULL &&
1211             Lst_FindDatum(suff->parents, targ->suff) != NULL)
1212             break;
1213     }
1214
1215     /*
1216      * Hot Damn! Create a new Src structure to describe
1217      * this transformation (making sure to duplicate the
1218      * source node's name so Suff_FindDeps can free it
1219      * again (ick)), and return the new structure.
1220      */
1221     ret = bmake_malloc(sizeof(Src));
1222     ret->file = bmake_strdup(s->name);
1223     ret->pref = targ->pref;
1224     ret->suff = suff;
1225     suff->refCount++;
1226     ret->parent = targ;
1227     ret->node = s;
1228     ret->children = 0;
1229     targ->children += 1;
1230 #ifdef DEBUG_SRC
1231     ret->cp = Lst_Init();
1232     fprintf(debug_file, "3 add %p %p\n", targ, ret);
1233     Lst_Append(targ->cp, ret);
1234 #endif
1235     Lst_Append(slst, ret);
1236     SUFF_DEBUG1("\tusing existing source %s\n", s->name);
1237     Lst_Close(t->children);
1238     return ret;
1239 }
1240
1241 /* Expand the names of any children of a given node that contain variable
1242  * invocations or file wildcards into actual targets.
1243  *
1244  * The expanded node is removed from the parent's list of children, and the
1245  * parent's unmade counter is decremented, but other nodes may be added.
1246  *
1247  * Input:
1248  *      cln             Child to examine
1249  *      pgn             Parent node being processed
1250  */
1251 static void
1252 SuffExpandChildren(LstNode cln, GNode *pgn)
1253 {
1254     GNode       *cgn = LstNode_Datum(cln);
1255     GNode       *gn;        /* New source 8) */
1256     char        *cp;        /* Expanded value */
1257
1258     if (!Lst_IsEmpty(cgn->order_pred) || !Lst_IsEmpty(cgn->order_succ))
1259         /* It is all too hard to process the result of .ORDER */
1260         return;
1261
1262     if (cgn->type & OP_WAIT)
1263         /* Ignore these (& OP_PHONY ?) */
1264         return;
1265
1266     /*
1267      * First do variable expansion -- this takes precedence over
1268      * wildcard expansion. If the result contains wildcards, they'll be gotten
1269      * to later since the resulting words are tacked on to the end of
1270      * the children list.
1271      */
1272     if (strchr(cgn->name, '$') == NULL) {
1273         SuffExpandWildcards(cln, pgn);
1274         return;
1275     }
1276
1277     SUFF_DEBUG1("Expanding \"%s\"...", cgn->name);
1278     cp = Var_Subst(cgn->name, pgn, VARE_UNDEFERR|VARE_WANTRES);
1279
1280     {
1281         Lst         members = Lst_Init();
1282
1283         if (cgn->type & OP_ARCHV) {
1284             /*
1285              * Node was an archive(member) target, so we want to call
1286              * on the Arch module to find the nodes for us, expanding
1287              * variables in the parent's context.
1288              */
1289             char        *sacrifice = cp;
1290
1291             (void)Arch_ParseArchive(&sacrifice, members, pgn);
1292         } else {
1293             /*
1294              * Break the result into a vector of strings whose nodes
1295              * we can find, then add those nodes to the members list.
1296              * Unfortunately, we can't use brk_string b/c it
1297              * doesn't understand about variable specifications with
1298              * spaces in them...
1299              */
1300             char            *start;
1301             char            *initcp = cp;   /* For freeing... */
1302
1303             for (start = cp; *start == ' ' || *start == '\t'; start++)
1304                 continue;
1305             for (cp = start; *cp != '\0'; cp++) {
1306                 if (*cp == ' ' || *cp == '\t') {
1307                     /*
1308                      * White-space -- terminate element, find the node,
1309                      * add it, skip any further spaces.
1310                      */
1311                     *cp++ = '\0';
1312                     gn = Targ_FindNode(start, TARG_CREATE);
1313                     Lst_Append(members, gn);
1314                     while (*cp == ' ' || *cp == '\t') {
1315                         cp++;
1316                     }
1317                     /*
1318                      * Adjust cp for increment at start of loop, but
1319                      * set start to first non-space.
1320                      */
1321                     start = cp--;
1322                 } else if (*cp == '$') {
1323                     /*
1324                      * Start of a variable spec -- contact variable module
1325                      * to find the end so we can skip over it.
1326                      */
1327                     const char  *junk;
1328                     int         len;
1329                     void        *freeIt;
1330
1331                     junk = Var_Parse(cp, pgn, VARE_UNDEFERR|VARE_WANTRES,
1332                                      &len, &freeIt);
1333                     if (junk != var_Error) {
1334                         cp += len - 1;
1335                     }
1336
1337                     free(freeIt);
1338                 } else if (*cp == '\\' && cp[1] != '\0') {
1339                     /*
1340                      * Escaped something -- skip over it
1341                      */
1342                     cp++;
1343                 }
1344             }
1345
1346             if (cp != start) {
1347                 /*
1348                  * Stuff left over -- add it to the list too
1349                  */
1350                 gn = Targ_FindNode(start, TARG_CREATE);
1351                 Lst_Append(members, gn);
1352             }
1353             /*
1354              * Point cp back at the beginning again so the variable value
1355              * can be freed.
1356              */
1357             cp = initcp;
1358         }
1359
1360         /*
1361          * Add all elements of the members list to the parent node.
1362          */
1363         while(!Lst_IsEmpty(members)) {
1364             gn = Lst_Dequeue(members);
1365
1366             SUFF_DEBUG1("%s...", gn->name);
1367             /* Add gn to the parents child list before the original child */
1368             Lst_InsertBefore(pgn->children, cln, gn);
1369             Lst_Append(gn->parents, pgn);
1370             pgn->unmade++;
1371             /* Expand wildcards on new node */
1372             SuffExpandWildcards(LstNode_Prev(cln), pgn);
1373         }
1374         Lst_Free(members);
1375
1376         /*
1377          * Free the result
1378          */
1379         free(cp);
1380     }
1381
1382     SUFF_DEBUG0("\n");
1383
1384     /*
1385      * Now the source is expanded, remove it from the list of children to
1386      * keep it from being processed.
1387      */
1388     pgn->unmade--;
1389     Lst_Remove(pgn->children, cln);
1390     Lst_Remove(cgn->parents, Lst_FindDatum(cgn->parents, pgn));
1391 }
1392
1393 static void
1394 SuffExpandWildcards(LstNode cln, GNode *pgn)
1395 {
1396     GNode       *cgn = LstNode_Datum(cln);
1397     GNode       *gn;        /* New source 8) */
1398     char        *cp;        /* Expanded value */
1399     Lst         explist;    /* List of expansions */
1400
1401     if (!Dir_HasWildcards(cgn->name))
1402         return;
1403
1404     /*
1405      * Expand the word along the chosen path
1406      */
1407     explist = Lst_Init();
1408     Dir_Expand(cgn->name, Suff_FindPath(cgn), explist);
1409
1410     while (!Lst_IsEmpty(explist)) {
1411         /*
1412          * Fetch next expansion off the list and find its GNode
1413          */
1414         cp = Lst_Dequeue(explist);
1415
1416         SUFF_DEBUG1("%s...", cp);
1417         gn = Targ_FindNode(cp, TARG_CREATE);
1418
1419         /* Add gn to the parents child list before the original child */
1420         Lst_InsertBefore(pgn->children, cln, gn);
1421         Lst_Append(gn->parents, pgn);
1422         pgn->unmade++;
1423     }
1424
1425     Lst_Free(explist);
1426
1427     SUFF_DEBUG0("\n");
1428
1429     /*
1430      * Now the source is expanded, remove it from the list of children to
1431      * keep it from being processed.
1432      */
1433     pgn->unmade--;
1434     Lst_Remove(pgn->children, cln);
1435     Lst_Remove(cgn->parents, Lst_FindDatum(cgn->parents, pgn));
1436 }
1437
1438 /* Find a path along which to expand the node.
1439  *
1440  * If the word has a known suffix, use that path.
1441  * If it has no known suffix, use the default system search path.
1442  *
1443  * Input:
1444  *      gn              Node being examined
1445  *
1446  * Results:
1447  *      The appropriate path to search for the GNode.
1448  */
1449 Lst
1450 Suff_FindPath(GNode* gn)
1451 {
1452     Suff *suff = gn->suffix;
1453
1454     if (suff == NULL) {
1455         SuffSuffGetSuffixArgs sd;   /* Search string data */
1456         LstNode ln;
1457         sd.len = strlen(gn->name);
1458         sd.ename = gn->name + sd.len;
1459         ln = Lst_Find(sufflist, SuffSuffIsSuffix, &sd);
1460
1461         SUFF_DEBUG1("Wildcard expanding \"%s\"...", gn->name);
1462         if (ln != NULL)
1463             suff = LstNode_Datum(ln);
1464         /* XXX: Here we can save the suffix so we don't have to do this again */
1465     }
1466
1467     if (suff != NULL) {
1468         SUFF_DEBUG1("suffix is \"%s\"...", suff->name);
1469         return suff->searchPath;
1470     } else {
1471         /*
1472          * Use default search path
1473          */
1474         return dirSearchPath;
1475     }
1476 }
1477
1478 /* Apply a transformation rule, given the source and target nodes and
1479  * suffixes.
1480  *
1481  * Input:
1482  *      tGn             Target node
1483  *      sGn             Source node
1484  *      t               Target suffix
1485  *      s               Source suffix
1486  *
1487  * Results:
1488  *      TRUE if successful, FALSE if not.
1489  *
1490  * Side Effects:
1491  *      The source and target are linked and the commands from the
1492  *      transformation are added to the target node's commands list.
1493  *      All attributes but OP_DEPMASK and OP_TRANSFORM are applied
1494  *      to the target. The target also inherits all the sources for
1495  *      the transformation rule.
1496  */
1497 static Boolean
1498 SuffApplyTransform(GNode *tGn, GNode *sGn, Suff *t, Suff *s)
1499 {
1500     LstNode     ln, nln;    /* General node */
1501     char        *tname;     /* Name of transformation rule */
1502     GNode       *gn;        /* Node for same */
1503
1504     /*
1505      * Form the proper links between the target and source.
1506      */
1507     Lst_Append(tGn->children, sGn);
1508     Lst_Append(sGn->parents, tGn);
1509     tGn->unmade += 1;
1510
1511     /*
1512      * Locate the transformation rule itself
1513      */
1514     tname = str_concat2(s->name, t->name);
1515     ln = Lst_Find(transforms, SuffGNHasName, tname);
1516     free(tname);
1517
1518     if (ln == NULL) {
1519         /*
1520          * Not really such a transformation rule (can happen when we're
1521          * called to link an OP_MEMBER and OP_ARCHV node), so return
1522          * FALSE.
1523          */
1524         return FALSE;
1525     }
1526
1527     gn = LstNode_Datum(ln);
1528
1529     SUFF_DEBUG3("\tapplying %s -> %s to \"%s\"\n", s->name, t->name, tGn->name);
1530
1531     /*
1532      * Record last child for expansion purposes
1533      */
1534     ln = Lst_Last(tGn->children);
1535
1536     /*
1537      * Pass the buck to Make_HandleUse to apply the rule
1538      */
1539     (void)Make_HandleUse(gn, tGn);
1540
1541     /*
1542      * Deal with wildcards and variables in any acquired sources
1543      */
1544     for (ln = ln != NULL ? LstNode_Next(ln) : NULL; ln != NULL; ln = nln) {
1545         nln = LstNode_Next(ln);
1546         SuffExpandChildren(ln, tGn);
1547     }
1548
1549     /*
1550      * Keep track of another parent to which this beast is transformed so
1551      * the .IMPSRC variable can be set correctly for the parent.
1552      */
1553     Lst_Append(sGn->implicitParents, tGn);
1554
1555     return TRUE;
1556 }
1557
1558
1559 /* Locate dependencies for an OP_ARCHV node.
1560  *
1561  * Input:
1562  *      gn              Node for which to locate dependencies
1563  *
1564  * Side Effects:
1565  *      Same as Suff_FindDeps
1566  */
1567 static void
1568 SuffFindArchiveDeps(GNode *gn, Lst slst)
1569 {
1570     char        *eoarch;    /* End of archive portion */
1571     char        *eoname;    /* End of member portion */
1572     GNode       *mem;       /* Node for member */
1573     LstNode     ln, nln;    /* Next suffix node to check */
1574     Suff        *ms;        /* Suffix descriptor for member */
1575     char        *name;      /* Start of member's name */
1576
1577     /*
1578      * The node is an archive(member) pair. so we must find a
1579      * suffix for both of them.
1580      */
1581     eoarch = strchr(gn->name, '(');
1582     eoname = strchr(eoarch, ')');
1583
1584     /*
1585      * Caller guarantees the format `libname(member)', via
1586      * Arch_ParseArchive.
1587      */
1588     assert(eoarch != NULL);
1589     assert(eoname != NULL);
1590
1591     *eoname = '\0';       /* Nuke parentheses during suffix search */
1592     *eoarch = '\0';       /* So a suffix can be found */
1593
1594     name = eoarch + 1;
1595
1596     /*
1597      * To simplify things, call Suff_FindDeps recursively on the member now,
1598      * so we can simply compare the member's .PREFIX and .TARGET variables
1599      * to locate its suffix. This allows us to figure out the suffix to
1600      * use for the archive without having to do a quadratic search over the
1601      * suffix list, backtracking for each one...
1602      */
1603     mem = Targ_FindNode(name, TARG_CREATE);
1604     SuffFindDeps(mem, slst);
1605
1606     /*
1607      * Create the link between the two nodes right off
1608      */
1609     Lst_Append(gn->children, mem);
1610     Lst_Append(mem->parents, gn);
1611     gn->unmade += 1;
1612
1613     /*
1614      * Copy in the variables from the member node to this one.
1615      */
1616     {
1617         char *freeIt;
1618         Var_Set(PREFIX, Var_Value(PREFIX, mem, &freeIt), gn);
1619         bmake_free(freeIt);
1620         Var_Set(TARGET, Var_Value(TARGET, mem, &freeIt), gn);
1621         bmake_free(freeIt);
1622     }
1623
1624     ms = mem->suffix;
1625     if (ms == NULL) {
1626         /*
1627          * Didn't know what it was -- use .NULL suffix if not in make mode
1628          */
1629         SUFF_DEBUG0("using null suffix\n");
1630         ms = suffNull;
1631     }
1632
1633
1634     /*
1635      * Set the other two local variables required for this target.
1636      */
1637     Var_Set(MEMBER, name, gn);
1638     Var_Set(ARCHIVE, gn->name, gn);
1639
1640     /*
1641      * Set $@ for compatibility with other makes
1642      */
1643     Var_Set(TARGET, gn->name, gn);
1644
1645     /*
1646      * Now we've got the important local variables set, expand any sources
1647      * that still contain variables or wildcards in their names.
1648      */
1649     for (ln = Lst_First(gn->children); ln != NULL; ln = nln) {
1650         nln = LstNode_Next(ln);
1651         SuffExpandChildren(ln, gn);
1652     }
1653
1654     if (ms != NULL) {
1655         /*
1656          * Member has a known suffix, so look for a transformation rule from
1657          * it to a possible suffix of the archive. Rather than searching
1658          * through the entire list, we just look at suffixes to which the
1659          * member's suffix may be transformed...
1660          */
1661         SuffSuffGetSuffixArgs sd;       /* Search string data */
1662
1663         /*
1664          * Use first matching suffix...
1665          */
1666         sd.len = eoarch - gn->name;
1667         sd.ename = eoarch;
1668         ln = Lst_Find(ms->parents, SuffSuffIsSuffix, &sd);
1669
1670         if (ln != NULL) {
1671             /*
1672              * Got one -- apply it
1673              */
1674             Suff *suff = LstNode_Datum(ln);
1675             if (!SuffApplyTransform(gn, mem, suff, ms)) {
1676                 SUFF_DEBUG2("\tNo transformation from %s -> %s\n",
1677                             ms->name, suff->name);
1678             }
1679         }
1680     }
1681
1682     /*
1683      * Replace the opening and closing parens now we've no need of the separate
1684      * pieces.
1685      */
1686     *eoarch = '('; *eoname = ')';
1687
1688     /*
1689      * Pretend gn appeared to the left of a dependency operator so
1690      * the user needn't provide a transformation from the member to the
1691      * archive.
1692      */
1693     if (OP_NOP(gn->type)) {
1694         gn->type |= OP_DEPENDS;
1695     }
1696
1697     /*
1698      * Flag the member as such so we remember to look in the archive for
1699      * its modification time. The OP_JOIN | OP_MADE is needed because this
1700      * target should never get made.
1701      */
1702     mem->type |= OP_MEMBER | OP_JOIN | OP_MADE;
1703 }
1704
1705 /* Locate implicit dependencies for regular targets.
1706  *
1707  * Input:
1708  *      gn              Node for which to find sources
1709  *
1710  * Side Effects:
1711  *      Same as Suff_FindDeps
1712  */
1713 static void
1714 SuffFindNormalDeps(GNode *gn, Lst slst)
1715 {
1716     char        *eoname;    /* End of name */
1717     char        *sopref;    /* Start of prefix */
1718     LstNode     ln, nln;    /* Next suffix node to check */
1719     Lst         srcs;       /* List of sources at which to look */
1720     Lst         targs;      /* List of targets to which things can be
1721                              * transformed. They all have the same file,
1722                              * but different suff and pref fields */
1723     Src         *bottom;    /* Start of found transformation path */
1724     Src         *src;       /* General Src pointer */
1725     char        *pref;      /* Prefix to use */
1726     Src         *targ;      /* General Src target pointer */
1727     SuffSuffGetSuffixArgs sd; /* Search string data */
1728
1729
1730     sd.len = strlen(gn->name);
1731     sd.ename = eoname = gn->name + sd.len;
1732
1733     sopref = gn->name;
1734
1735     /*
1736      * Begin at the beginning...
1737      */
1738     ln = Lst_First(sufflist);
1739     srcs = Lst_Init();
1740     targs = Lst_Init();
1741
1742     /*
1743      * We're caught in a catch-22 here. On the one hand, we want to use any
1744      * transformation implied by the target's sources, but we can't examine
1745      * the sources until we've expanded any variables/wildcards they may hold,
1746      * and we can't do that until we've set up the target's local variables
1747      * and we can't do that until we know what the proper suffix for the
1748      * target is (in case there are two suffixes one of which is a suffix of
1749      * the other) and we can't know that until we've found its implied
1750      * source, which we may not want to use if there's an existing source
1751      * that implies a different transformation.
1752      *
1753      * In an attempt to get around this, which may not work all the time,
1754      * but should work most of the time, we look for implied sources first,
1755      * checking transformations to all possible suffixes of the target,
1756      * use what we find to set the target's local variables, expand the
1757      * children, then look for any overriding transformations they imply.
1758      * Should we find one, we discard the one we found before.
1759      */
1760     bottom = NULL;
1761     targ = NULL;
1762
1763     if (!(gn->type & OP_PHONY)) {
1764
1765         while (ln != NULL) {
1766             /*
1767              * Look for next possible suffix...
1768              */
1769             ln = Lst_FindFrom(sufflist, ln, SuffSuffIsSuffix, &sd);
1770
1771             if (ln != NULL) {
1772                 const char *eopref;
1773
1774                 /*
1775                  * Allocate a Src structure to which things can be transformed
1776                  */
1777                 targ = bmake_malloc(sizeof(Src));
1778                 targ->file = bmake_strdup(gn->name);
1779                 targ->suff = LstNode_Datum(ln);
1780                 targ->suff->refCount++;
1781                 targ->node = gn;
1782                 targ->parent = NULL;
1783                 targ->children = 0;
1784 #ifdef DEBUG_SRC
1785                 targ->cp = Lst_Init();
1786 #endif
1787
1788                 eopref = eoname - targ->suff->nameLen;
1789                 targ->pref = bmake_strsedup(sopref, eopref);
1790
1791                 /*
1792                  * Add nodes from which the target can be made
1793                  */
1794                 SuffAddLevel(srcs, targ);
1795
1796                 /*
1797                  * Record the target so we can nuke it
1798                  */
1799                 Lst_Append(targs, targ);
1800
1801                 /*
1802                  * Search from this suffix's successor...
1803                  */
1804                 ln = LstNode_Next(ln);
1805             }
1806         }
1807
1808         /*
1809          * Handle target of unknown suffix...
1810          */
1811         if (Lst_IsEmpty(targs) && suffNull != NULL) {
1812             SUFF_DEBUG1("\tNo known suffix on %s. Using .NULL suffix\n",
1813                         gn->name);
1814
1815             targ = bmake_malloc(sizeof(Src));
1816             targ->file = bmake_strdup(gn->name);
1817             targ->suff = suffNull;
1818             targ->suff->refCount++;
1819             targ->node = gn;
1820             targ->parent = NULL;
1821             targ->children = 0;
1822             targ->pref = bmake_strdup(sopref);
1823 #ifdef DEBUG_SRC
1824             targ->cp = Lst_Init();
1825 #endif
1826
1827             /*
1828              * Only use the default suffix rules if we don't have commands
1829              * defined for this gnode; traditional make programs used to
1830              * not define suffix rules if the gnode had children but we
1831              * don't do this anymore.
1832              */
1833             if (Lst_IsEmpty(gn->commands))
1834                 SuffAddLevel(srcs, targ);
1835             else {
1836                 SUFF_DEBUG0("not ");
1837             }
1838
1839             SUFF_DEBUG0("adding suffix rules\n");
1840
1841             Lst_Append(targs, targ);
1842         }
1843
1844         /*
1845          * Using the list of possible sources built up from the target
1846          * suffix(es), try and find an existing file/target that matches.
1847          */
1848         bottom = SuffFindThem(srcs, slst);
1849
1850         if (bottom == NULL) {
1851             /*
1852              * No known transformations -- use the first suffix found
1853              * for setting the local variables.
1854              */
1855             if (!Lst_IsEmpty(targs)) {
1856                 targ = LstNode_Datum(Lst_First(targs));
1857             } else {
1858                 targ = NULL;
1859             }
1860         } else {
1861             /*
1862              * Work up the transformation path to find the suffix of the
1863              * target to which the transformation was made.
1864              */
1865             for (targ = bottom; targ->parent != NULL; targ = targ->parent)
1866                 continue;
1867         }
1868     }
1869
1870     Var_Set(TARGET, gn->path ? gn->path : gn->name, gn);
1871
1872     pref = (targ != NULL) ? targ->pref : gn->name;
1873     Var_Set(PREFIX, pref, gn);
1874
1875     /*
1876      * Now we've got the important local variables set, expand any sources
1877      * that still contain variables or wildcards in their names.
1878      */
1879     for (ln = Lst_First(gn->children); ln != NULL; ln = nln) {
1880         nln = LstNode_Next(ln);
1881         SuffExpandChildren(ln, gn);
1882     }
1883
1884     if (targ == NULL) {
1885         SUFF_DEBUG1("\tNo valid suffix on %s\n", gn->name);
1886
1887 sfnd_abort:
1888         /*
1889          * Deal with finding the thing on the default search path. We
1890          * always do that, not only if the node is only a source (not
1891          * on the lhs of a dependency operator or [XXX] it has neither
1892          * children or commands) as the old pmake did.
1893          */
1894         if ((gn->type & (OP_PHONY|OP_NOPATH)) == 0) {
1895             free(gn->path);
1896             gn->path = Dir_FindFile(gn->name,
1897                                     (targ == NULL ? dirSearchPath :
1898                                      targ->suff->searchPath));
1899             if (gn->path != NULL) {
1900                 char *ptr;
1901                 Var_Set(TARGET, gn->path, gn);
1902
1903                 if (targ != NULL) {
1904                     /*
1905                      * Suffix known for the thing -- trim the suffix off
1906                      * the path to form the proper .PREFIX variable.
1907                      */
1908                     int     savep = strlen(gn->path) - targ->suff->nameLen;
1909                     char    savec;
1910
1911                     if (gn->suffix)
1912                         gn->suffix->refCount--;
1913                     gn->suffix = targ->suff;
1914                     gn->suffix->refCount++;
1915
1916                     savec = gn->path[savep];
1917                     gn->path[savep] = '\0';
1918
1919                     if ((ptr = strrchr(gn->path, '/')) != NULL)
1920                         ptr++;
1921                     else
1922                         ptr = gn->path;
1923
1924                     Var_Set(PREFIX, ptr, gn);
1925
1926                     gn->path[savep] = savec;
1927                 } else {
1928                     /*
1929                      * The .PREFIX gets the full path if the target has
1930                      * no known suffix.
1931                      */
1932                     if (gn->suffix)
1933                         gn->suffix->refCount--;
1934                     gn->suffix = NULL;
1935
1936                     if ((ptr = strrchr(gn->path, '/')) != NULL)
1937                         ptr++;
1938                     else
1939                         ptr = gn->path;
1940
1941                     Var_Set(PREFIX, ptr, gn);
1942                 }
1943             }
1944         }
1945
1946         goto sfnd_return;
1947     }
1948
1949     /*
1950      * If the suffix indicates that the target is a library, mark that in
1951      * the node's type field.
1952      */
1953     if (targ->suff->flags & SUFF_LIBRARY) {
1954         gn->type |= OP_LIB;
1955     }
1956
1957     /*
1958      * Check for overriding transformation rule implied by sources
1959      */
1960     if (!Lst_IsEmpty(gn->children)) {
1961         src = SuffFindCmds(targ, slst);
1962
1963         if (src != NULL) {
1964             /*
1965              * Free up all the Src structures in the transformation path
1966              * up to, but not including, the parent node.
1967              */
1968             while (bottom && bottom->parent != NULL) {
1969                 if (Lst_FindDatum(slst, bottom) == NULL) {
1970                     Lst_Append(slst, bottom);
1971                 }
1972                 bottom = bottom->parent;
1973             }
1974             bottom = src;
1975         }
1976     }
1977
1978     if (bottom == NULL) {
1979         /*
1980          * No idea from where it can come -- return now.
1981          */
1982         goto sfnd_abort;
1983     }
1984
1985     /*
1986      * We now have a list of Src structures headed by 'bottom' and linked via
1987      * their 'parent' pointers. What we do next is create links between
1988      * source and target nodes (which may or may not have been created)
1989      * and set the necessary local variables in each target. The
1990      * commands for each target are set from the commands of the
1991      * transformation rule used to get from the src suffix to the targ
1992      * suffix. Note that this causes the commands list of the original
1993      * node, gn, to be replaced by the commands of the final
1994      * transformation rule. Also, the unmade field of gn is incremented.
1995      * Etc.
1996      */
1997     if (bottom->node == NULL) {
1998         bottom->node = Targ_FindNode(bottom->file, TARG_CREATE);
1999     }
2000
2001     for (src = bottom; src->parent != NULL; src = src->parent) {
2002         targ = src->parent;
2003
2004         if (src->node->suffix)
2005             src->node->suffix->refCount--;
2006         src->node->suffix = src->suff;
2007         src->node->suffix->refCount++;
2008
2009         if (targ->node == NULL) {
2010             targ->node = Targ_FindNode(targ->file, TARG_CREATE);
2011         }
2012
2013         SuffApplyTransform(targ->node, src->node,
2014                            targ->suff, src->suff);
2015
2016         if (targ->node != gn) {
2017             /*
2018              * Finish off the dependency-search process for any nodes
2019              * between bottom and gn (no point in questing around the
2020              * filesystem for their implicit source when it's already
2021              * known). Note that the node can't have any sources that
2022              * need expanding, since SuffFindThem will stop on an existing
2023              * node, so all we need to do is set the standard and System V
2024              * variables.
2025              */
2026             targ->node->type |= OP_DEPS_FOUND;
2027
2028             Var_Set(PREFIX, targ->pref, targ->node);
2029
2030             Var_Set(TARGET, targ->node->name, targ->node);
2031         }
2032     }
2033
2034     if (gn->suffix)
2035         gn->suffix->refCount--;
2036     gn->suffix = src->suff;
2037     gn->suffix->refCount++;
2038
2039     /*
2040      * Nuke the transformation path and the Src structures left over in the
2041      * two lists.
2042      */
2043 sfnd_return:
2044     if (bottom)
2045         if (Lst_FindDatum(slst, bottom) == NULL)
2046             Lst_Append(slst, bottom);
2047
2048     while (SuffRemoveSrc(srcs) || SuffRemoveSrc(targs))
2049         continue;
2050
2051     Lst_MoveAll(slst, srcs);
2052     Lst_MoveAll(slst, targs);
2053 }
2054
2055
2056 /* Find implicit sources for the target described by the graph node.
2057  *
2058  * Nodes are added to the graph below the passed-in node. The nodes are
2059  * marked to have their IMPSRC variable filled in. The PREFIX variable is set
2060  * for the given node and all its implied children.
2061  *
2062  * The path found by this target is the shortest path in the transformation
2063  * graph, which may pass through non-existent targets, to an existing target.
2064  * The search continues on all paths from the root suffix until a file is
2065  * found. I.e. if there's a path .o -> .c -> .l -> .l,v from the root and the
2066  * .l,v file exists but the .c and .l files don't, the search will branch out
2067  * in all directions from .o and again from all the nodes on the next level
2068  * until the .l,v node is encountered.
2069  */
2070 void
2071 Suff_FindDeps(GNode *gn)
2072 {
2073
2074     SuffFindDeps(gn, srclist);
2075     while (SuffRemoveSrc(srclist))
2076         continue;
2077 }
2078
2079 static void
2080 SuffFindDeps(GNode *gn, Lst slst)
2081 {
2082     if (gn->type & OP_DEPS_FOUND)
2083         return;
2084     gn->type |= OP_DEPS_FOUND;
2085
2086     /*
2087      * Make sure we have these set, may get revised below.
2088      */
2089     Var_Set(TARGET, gn->path ? gn->path : gn->name, gn);
2090     Var_Set(PREFIX, gn->name, gn);
2091
2092     SUFF_DEBUG1("SuffFindDeps (%s)\n", gn->name);
2093
2094     if (gn->type & OP_ARCHV) {
2095         SuffFindArchiveDeps(gn, slst);
2096     } else if (gn->type & OP_LIB) {
2097         /*
2098          * If the node is a library, it is the arch module's job to find it
2099          * and set the TARGET variable accordingly. We merely provide the
2100          * search path, assuming all libraries end in ".a" (if the suffix
2101          * hasn't been defined, there's nothing we can do for it, so we just
2102          * set the TARGET variable to the node's name in order to give it a
2103          * value).
2104          */
2105         LstNode ln;
2106         Suff    *s;
2107
2108         ln = Lst_Find(sufflist, SuffSuffHasName, LIBSUFF);
2109         if (gn->suffix)
2110             gn->suffix->refCount--;
2111         if (ln != NULL) {
2112             gn->suffix = s = LstNode_Datum(ln);
2113             gn->suffix->refCount++;
2114             Arch_FindLib(gn, s->searchPath);
2115         } else {
2116             gn->suffix = NULL;
2117             Var_Set(TARGET, gn->name, gn);
2118         }
2119         /*
2120          * Because a library (-lfoo) target doesn't follow the standard
2121          * filesystem conventions, we don't set the regular variables for
2122          * the thing. .PREFIX is simply made empty...
2123          */
2124         Var_Set(PREFIX, "", gn);
2125     } else {
2126         SuffFindNormalDeps(gn, slst);
2127     }
2128 }
2129
2130 /* Define which suffix is the null suffix.
2131  *
2132  * Need to handle the changing of the null suffix gracefully so the old
2133  * transformation rules don't just go away.
2134  *
2135  * Input:
2136  *      name            Name of null suffix
2137  */
2138 void
2139 Suff_SetNull(char *name)
2140 {
2141     Suff    *s;
2142     LstNode ln;
2143
2144     ln = Lst_Find(sufflist, SuffSuffHasName, name);
2145     if (ln != NULL) {
2146         s = LstNode_Datum(ln);
2147         if (suffNull != NULL) {
2148             suffNull->flags &= ~SUFF_NULL;
2149         }
2150         s->flags |= SUFF_NULL;
2151         /*
2152          * XXX: Here's where the transformation mangling would take place
2153          */
2154         suffNull = s;
2155     } else {
2156         Parse_Error(PARSE_WARNING, "Desired null suffix %s not defined.",
2157                      name);
2158     }
2159 }
2160
2161 /* Initialize the suffixes module. */
2162 void
2163 Suff_Init(void)
2164 {
2165 #ifdef CLEANUP
2166     suffClean = Lst_Init();
2167     sufflist = Lst_Init();
2168 #endif
2169     srclist = Lst_Init();
2170     transforms = Lst_Init();
2171
2172     /*
2173      * Create null suffix for single-suffix rules (POSIX). The thing doesn't
2174      * actually go on the suffix list or everyone will think that's its
2175      * suffix.
2176      */
2177     Suff_ClearSuffixes();
2178 }
2179
2180
2181 /* Clean up the suffixes module. */
2182 void
2183 Suff_End(void)
2184 {
2185 #ifdef CLEANUP
2186     Lst_Destroy(sufflist, SuffFree);
2187     Lst_Destroy(suffClean, SuffFree);
2188     if (suffNull)
2189         SuffFree(suffNull);
2190     Lst_Free(srclist);
2191     Lst_Free(transforms);
2192 #endif
2193 }
2194
2195
2196 /********************* DEBUGGING FUNCTIONS **********************/
2197
2198 static int SuffPrintName(void *s, void *dummy MAKE_ATTR_UNUSED)
2199 {
2200
2201     fprintf(debug_file, "%s ", ((Suff *)s)->name);
2202     return 0;
2203 }
2204
2205 static int
2206 SuffPrintSuff(void *sp, void *dummy MAKE_ATTR_UNUSED)
2207 {
2208     Suff    *s = (Suff *)sp;
2209
2210     fprintf(debug_file, "# `%s' [%d] ", s->name, s->refCount);
2211
2212     if (s->flags != 0) {
2213         char flags_buf[SuffFlags_ToStringSize];
2214
2215         fprintf(debug_file, " (%s)",
2216                 Enum_FlagsToString(flags_buf, sizeof flags_buf,
2217                                    s->flags, SuffFlags_ToStringSpecs));
2218     }
2219     fputc('\n', debug_file);
2220     fprintf(debug_file, "#\tTo: ");
2221     Lst_ForEach(s->parents, SuffPrintName, NULL);
2222     fputc('\n', debug_file);
2223     fprintf(debug_file, "#\tFrom: ");
2224     Lst_ForEach(s->children, SuffPrintName, NULL);
2225     fputc('\n', debug_file);
2226     fprintf(debug_file, "#\tSearch Path: ");
2227     Dir_PrintPath(s->searchPath);
2228     fputc('\n', debug_file);
2229     return 0;
2230 }
2231
2232 static int
2233 SuffPrintTrans(void *tp, void *dummy MAKE_ATTR_UNUSED)
2234 {
2235     GNode   *t = (GNode *)tp;
2236
2237     fprintf(debug_file, "%-16s: ", t->name);
2238     Targ_PrintType(t->type);
2239     fputc('\n', debug_file);
2240     Lst_ForEach(t->commands, Targ_PrintCmd, NULL);
2241     fputc('\n', debug_file);
2242     return 0;
2243 }
2244
2245 void
2246 Suff_PrintAll(void)
2247 {
2248     fprintf(debug_file, "#*** Suffixes:\n");
2249     Lst_ForEach(sufflist, SuffPrintSuff, NULL);
2250
2251     fprintf(debug_file, "#*** Transformations:\n");
2252     Lst_ForEach(transforms, SuffPrintTrans, NULL);
2253 }