xref: /netbsd-src/usr.bin/make/suff.c (revision da5f4674a3fc214be3572d358b66af40ab9401e7)
1 /*	$NetBSD: suff.c,v 1.42 2003/08/07 11:14:57 agc 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 #ifdef MAKE_BOOTSTRAP
72 static char rcsid[] = "$NetBSD: suff.c,v 1.42 2003/08/07 11:14:57 agc 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.42 2003/08/07 11:14:57 agc 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 NILGNODE
132  *	    	  	    	if the target had no implicit sources.
133  */
134 
135 #include    	  <stdio.h>
136 #include	  "make.h"
137 #include	  "hash.h"
138 #include	  "dir.h"
139 
140 static Lst       sufflist;	/* Lst of suffixes */
141 #ifdef CLEANUP
142 static Lst	 suffClean;	/* Lst of suffixes to be cleaned */
143 #endif
144 static Lst	 srclist;	/* Lst of sources */
145 static Lst       transforms;	/* Lst of transformation rules */
146 
147 static int        sNum = 0;	/* Counter for assigning suffix numbers */
148 
149 /*
150  * Structure describing an individual suffix.
151  */
152 typedef struct _Suff {
153     char         *name;	    	/* The suffix itself */
154     int		 nameLen;	/* Length of the suffix */
155     short	 flags;      	/* Type of suffix */
156 #define SUFF_INCLUDE	  0x01	    /* One which is #include'd */
157 #define SUFF_LIBRARY	  0x02	    /* One which contains a library */
158 #define SUFF_NULL 	  0x04	    /* The empty suffix */
159     Lst    	 searchPath;	/* The path along which files of this suffix
160 				 * may be found */
161     int          sNum;	      	/* The suffix number */
162     int		 refCount;	/* Reference count of list membership */
163     Lst          parents;	/* Suffixes we have a transformation to */
164     Lst          children;	/* Suffixes we have a transformation from */
165     Lst		 ref;		/* List of lists this suffix is referenced */
166 } Suff;
167 
168 /*
169  * for SuffSuffIsSuffix
170  */
171 typedef struct {
172     char	*ename;		/* The end of the name */
173     int		 len;		/* Length of the name */
174 } SuffixCmpData;
175 
176 /*
177  * Structure used in the search for implied sources.
178  */
179 typedef struct _Src {
180     char            *file;	/* The file to look for */
181     char    	    *pref;  	/* Prefix from which file was formed */
182     Suff            *suff;	/* The suffix on the file */
183     struct _Src     *parent;	/* The Src for which this is a source */
184     GNode           *node;	/* The node describing the file */
185     int	    	    children;	/* Count of existing children (so we don't free
186 				 * this thing too early or never nuke it) */
187 #ifdef DEBUG_SRC
188     Lst		    cp;		/* Debug; children list */
189 #endif
190 } Src;
191 
192 /*
193  * A structure for passing more than one argument to the Lst-library-invoked
194  * function...
195  */
196 typedef struct {
197     Lst            l;
198     Src            *s;
199 } LstSrc;
200 
201 typedef struct {
202     GNode	  **gn;
203     Suff	   *s;
204     Boolean	    r;
205 } GNodeSuff;
206 
207 static Suff 	    *suffNull;	/* The NULL suffix for this run */
208 static Suff 	    *emptySuff;	/* The empty suffix required for POSIX
209 				 * single-suffix transformation rules */
210 
211 
212 static char *SuffStrIsPrefix(char *, char *);
213 static char *SuffSuffIsSuffix(Suff *, SuffixCmpData *);
214 static int SuffSuffIsSuffixP(ClientData, ClientData);
215 static int SuffSuffHasNameP(ClientData, ClientData);
216 static int SuffSuffIsPrefix(ClientData, ClientData);
217 static int SuffGNHasNameP(ClientData, ClientData);
218 static void SuffUnRef(ClientData, ClientData);
219 static void SuffFree(ClientData);
220 static void SuffInsert(Lst, Suff *);
221 static void SuffRemove(Lst, Suff *);
222 static Boolean SuffParseTransform(char *, Suff **, Suff **);
223 static int SuffRebuildGraph(ClientData, ClientData);
224 static int SuffScanTargets(ClientData, ClientData);
225 static int SuffAddSrc(ClientData, ClientData);
226 static int SuffRemoveSrc(Lst);
227 static void SuffAddLevel(Lst, Src *);
228 static Src *SuffFindThem(Lst, Lst);
229 static Src *SuffFindCmds(Src *, Lst);
230 static int SuffExpandChildren(LstNode, GNode *);
231 static Boolean SuffApplyTransform(GNode *, GNode *, Suff *, Suff *);
232 static void SuffFindDeps(GNode *, Lst);
233 static void SuffFindArchiveDeps(GNode *, Lst);
234 static void SuffFindNormalDeps(GNode *, Lst);
235 static int SuffPrintName(ClientData, ClientData);
236 static int SuffPrintSuff(ClientData, ClientData);
237 static int SuffPrintTrans(ClientData, ClientData);
238 
239 	/*************** Lst Predicates ****************/
240 /*-
241  *-----------------------------------------------------------------------
242  * SuffStrIsPrefix  --
243  *	See if pref is a prefix of str.
244  *
245  * Input:
246  *	pref		possible prefix
247  *	str		string to check
248  *
249  * Results:
250  *	NULL if it ain't, pointer to character in str after prefix if so
251  *
252  * Side Effects:
253  *	None
254  *-----------------------------------------------------------------------
255  */
256 static char    *
257 SuffStrIsPrefix(char *pref, char *str)
258 {
259     while (*str && *pref == *str) {
260 	pref++;
261 	str++;
262     }
263 
264     return (*pref ? NULL : str);
265 }
266 
267 /*-
268  *-----------------------------------------------------------------------
269  * SuffSuffIsSuffix  --
270  *	See if suff is a suffix of str. sd->ename should point to THE END
271  *	of the string to check. (THE END == the null byte)
272  *
273  * Input:
274  *	s		possible suffix
275  *	sd		string to examine
276  *
277  * Results:
278  *	NULL if it ain't, pointer to character in str before suffix if
279  *	it is.
280  *
281  * Side Effects:
282  *	None
283  *-----------------------------------------------------------------------
284  */
285 static char *
286 SuffSuffIsSuffix(Suff *s, SuffixCmpData *sd)
287 {
288     char  *p1;	    	/* Pointer into suffix name */
289     char  *p2;	    	/* Pointer into string being examined */
290 
291     if (sd->len < s->nameLen)
292 	return NULL;		/* this string is shorter than the suffix */
293 
294     p1 = s->name + s->nameLen;
295     p2 = sd->ename;
296 
297     while (p1 >= s->name && *p1 == *p2) {
298 	p1--;
299 	p2--;
300     }
301 
302     return (p1 == s->name - 1 ? p2 : NULL);
303 }
304 
305 /*-
306  *-----------------------------------------------------------------------
307  * SuffSuffIsSuffixP --
308  *	Predicate form of SuffSuffIsSuffix. Passed as the callback function
309  *	to Lst_Find.
310  *
311  * Results:
312  *	0 if the suffix is the one desired, non-zero if not.
313  *
314  * Side Effects:
315  *	None.
316  *
317  *-----------------------------------------------------------------------
318  */
319 static int
320 SuffSuffIsSuffixP(ClientData s, ClientData sd)
321 {
322     return(!SuffSuffIsSuffix((Suff *) s, (SuffixCmpData *) sd));
323 }
324 
325 /*-
326  *-----------------------------------------------------------------------
327  * SuffSuffHasNameP --
328  *	Callback procedure for finding a suffix based on its name. Used by
329  *	Suff_GetPath.
330  *
331  * Input:
332  *	s		Suffix to check
333  *	sd		Desired name
334  *
335  * Results:
336  *	0 if the suffix is of the given name. non-zero otherwise.
337  *
338  * Side Effects:
339  *	None
340  *-----------------------------------------------------------------------
341  */
342 static int
343 SuffSuffHasNameP(ClientData s, ClientData sname)
344 {
345     return (strcmp ((char *) sname, ((Suff *) s)->name));
346 }
347 
348 /*-
349  *-----------------------------------------------------------------------
350  * SuffSuffIsPrefix  --
351  *	See if the suffix described by s is a prefix of the string. Care
352  *	must be taken when using this to search for transformations and
353  *	what-not, since there could well be two suffixes, one of which
354  *	is a prefix of the other...
355  *
356  * Input:
357  *	s		suffix to compare
358  *	str		string to examine
359  *
360  * Results:
361  *	0 if s is a prefix of str. non-zero otherwise
362  *
363  * Side Effects:
364  *	None
365  *-----------------------------------------------------------------------
366  */
367 static int
368 SuffSuffIsPrefix(ClientData s, ClientData str)
369 {
370     return (SuffStrIsPrefix (((Suff *) s)->name, (char *) str) == NULL ? 1 : 0);
371 }
372 
373 /*-
374  *-----------------------------------------------------------------------
375  * SuffGNHasNameP  --
376  *	See if the graph node has the desired name
377  *
378  * Input:
379  *	gn		current node we're looking at
380  *	name		name we're looking for
381  *
382  * Results:
383  *	0 if it does. non-zero if it doesn't
384  *
385  * Side Effects:
386  *	None
387  *-----------------------------------------------------------------------
388  */
389 static int
390 SuffGNHasNameP(ClientData gn, ClientData name)
391 {
392     return (strcmp ((char *) name, ((GNode *) gn)->name));
393 }
394 
395  	    /*********** Maintenance Functions ************/
396 
397 static void
398 SuffUnRef(ClientData lp, ClientData sp)
399 {
400     Lst l = (Lst) lp;
401 
402     LstNode ln = Lst_Member(l, sp);
403     if (ln != NILLNODE) {
404 	Lst_Remove(l, ln);
405 	((Suff *) sp)->refCount--;
406     }
407 }
408 
409 /*-
410  *-----------------------------------------------------------------------
411  * SuffFree  --
412  *	Free up all memory associated with the given suffix structure.
413  *
414  * Results:
415  *	none
416  *
417  * Side Effects:
418  *	the suffix entry is detroyed
419  *-----------------------------------------------------------------------
420  */
421 static void
422 SuffFree(ClientData sp)
423 {
424     Suff           *s = (Suff *) sp;
425 
426     if (s == suffNull)
427 	suffNull = NULL;
428 
429     if (s == emptySuff)
430 	emptySuff = NULL;
431 
432 #ifdef notdef
433     /* We don't delete suffixes in order, so we cannot use this */
434     if (s->refCount)
435 	Punt("Internal error deleting suffix `%s' with refcount = %d", s->name,
436 	    s->refCount);
437 #endif
438 
439     Lst_Destroy (s->ref, NOFREE);
440     Lst_Destroy (s->children, NOFREE);
441     Lst_Destroy (s->parents, NOFREE);
442     Lst_Destroy (s->searchPath, Dir_Destroy);
443 
444     free ((Address)s->name);
445     free ((Address)s);
446 }
447 
448 /*-
449  *-----------------------------------------------------------------------
450  * SuffRemove  --
451  *	Remove the suffix into the list
452  *
453  * Results:
454  *	None
455  *
456  * Side Effects:
457  *	The reference count for the suffix is decremented and the
458  *	suffix is possibly freed
459  *-----------------------------------------------------------------------
460  */
461 static void
462 SuffRemove(Lst l, Suff *s)
463 {
464     SuffUnRef((ClientData) l, (ClientData) s);
465     if (s->refCount == 0) {
466 	SuffUnRef ((ClientData) sufflist, (ClientData) s);
467 	SuffFree((ClientData) s);
468     }
469 }
470 
471 /*-
472  *-----------------------------------------------------------------------
473  * SuffInsert  --
474  *	Insert the suffix into the list keeping the list ordered by suffix
475  *	numbers.
476  *
477  * Input:
478  *	l		the list where in s should be inserted
479  *	s		the suffix to insert
480  *
481  * Results:
482  *	None
483  *
484  * Side Effects:
485  *	The reference count of the suffix is incremented
486  *-----------------------------------------------------------------------
487  */
488 static void
489 SuffInsert(Lst l, Suff *s)
490 {
491     LstNode 	  ln;		/* current element in l we're examining */
492     Suff          *s2 = NULL;	/* the suffix descriptor in this element */
493 
494     if (Lst_Open (l) == FAILURE) {
495 	return;
496     }
497     while ((ln = Lst_Next (l)) != NILLNODE) {
498 	s2 = (Suff *) Lst_Datum (ln);
499 	if (s2->sNum >= s->sNum) {
500 	    break;
501 	}
502     }
503 
504     Lst_Close (l);
505     if (DEBUG(SUFF)) {
506 	printf("inserting %s(%d)...", s->name, s->sNum);
507     }
508     if (ln == NILLNODE) {
509 	if (DEBUG(SUFF)) {
510 	    printf("at end of list\n");
511 	}
512 	(void)Lst_AtEnd (l, (ClientData)s);
513 	s->refCount++;
514 	(void)Lst_AtEnd(s->ref, (ClientData) l);
515     } else if (s2->sNum != s->sNum) {
516 	if (DEBUG(SUFF)) {
517 	    printf("before %s(%d)\n", s2->name, s2->sNum);
518 	}
519 	(void)Lst_Insert (l, ln, (ClientData)s);
520 	s->refCount++;
521 	(void)Lst_AtEnd(s->ref, (ClientData) l);
522     } else if (DEBUG(SUFF)) {
523 	printf("already there\n");
524     }
525 }
526 
527 /*-
528  *-----------------------------------------------------------------------
529  * Suff_ClearSuffixes --
530  *	This is gross. Nuke the list of suffixes but keep all transformation
531  *	rules around. The transformation graph is destroyed in this process,
532  *	but we leave the list of rules so when a new graph is formed the rules
533  *	will remain.
534  *	This function is called from the parse module when a
535  *	.SUFFIXES:\n line is encountered.
536  *
537  * Results:
538  *	none
539  *
540  * Side Effects:
541  *	the sufflist and its graph nodes are destroyed
542  *-----------------------------------------------------------------------
543  */
544 void
545 Suff_ClearSuffixes(void)
546 {
547 #ifdef CLEANUP
548     Lst_Concat (suffClean, sufflist, LST_CONCLINK);
549 #endif
550     sufflist = Lst_Init(FALSE);
551     sNum = 0;
552     suffNull = emptySuff;
553 }
554 
555 /*-
556  *-----------------------------------------------------------------------
557  * SuffParseTransform --
558  *	Parse a transformation string to find its two component suffixes.
559  *
560  * Input:
561  *	str		String being parsed
562  *	srcPtr		Place to store source of trans.
563  *	targPtr		Place to store target of trans.
564  *
565  * Results:
566  *	TRUE if the string is a valid transformation and FALSE otherwise.
567  *
568  * Side Effects:
569  *	The passed pointers are overwritten.
570  *
571  *-----------------------------------------------------------------------
572  */
573 static Boolean
574 SuffParseTransform(char *str, Suff **srcPtr, Suff **targPtr)
575 {
576     LstNode		srcLn;	    /* element in suffix list of trans source*/
577     Suff		*src;	    /* Source of transformation */
578     LstNode		targLn;	    /* element in suffix list of trans target*/
579     char		*str2;	    /* Extra pointer (maybe target suffix) */
580     LstNode 	    	singleLn;   /* element in suffix list of any suffix
581 				     * that exactly matches str */
582     Suff    	    	*single = NULL;/* Source of possible transformation to
583 				     * null suffix */
584 
585     srcLn = NILLNODE;
586     singleLn = NILLNODE;
587 
588     /*
589      * Loop looking first for a suffix that matches the start of the
590      * string and then for one that exactly matches the rest of it. If
591      * we can find two that meet these criteria, we've successfully
592      * parsed the string.
593      */
594     for (;;) {
595 	if (srcLn == NILLNODE) {
596 	    srcLn = Lst_Find(sufflist, (ClientData)str, SuffSuffIsPrefix);
597 	} else {
598 	    srcLn = Lst_FindFrom (sufflist, Lst_Succ(srcLn), (ClientData)str,
599 				  SuffSuffIsPrefix);
600 	}
601 	if (srcLn == NILLNODE) {
602 	    /*
603 	     * Ran out of source suffixes -- no such rule
604 	     */
605 	    if (singleLn != NILLNODE) {
606 		/*
607 		 * Not so fast Mr. Smith! There was a suffix that encompassed
608 		 * the entire string, so we assume it was a transformation
609 		 * to the null suffix (thank you POSIX). We still prefer to
610 		 * find a double rule over a singleton, hence we leave this
611 		 * check until the end.
612 		 *
613 		 * XXX: Use emptySuff over suffNull?
614 		 */
615 		*srcPtr = single;
616 		*targPtr = suffNull;
617 		return(TRUE);
618 	    }
619 	    return (FALSE);
620 	}
621 	src = (Suff *) Lst_Datum (srcLn);
622 	str2 = str + src->nameLen;
623 	if (*str2 == '\0') {
624 	    single = src;
625 	    singleLn = srcLn;
626 	} else {
627 	    targLn = Lst_Find(sufflist, (ClientData)str2, SuffSuffHasNameP);
628 	    if (targLn != NILLNODE) {
629 		*srcPtr = src;
630 		*targPtr = (Suff *)Lst_Datum(targLn);
631 		return (TRUE);
632 	    }
633 	}
634     }
635 }
636 
637 /*-
638  *-----------------------------------------------------------------------
639  * Suff_IsTransform  --
640  *	Return TRUE if the given string is a transformation rule
641  *
642  *
643  * Input:
644  *	str		string to check
645  *
646  * Results:
647  *	TRUE if the string is a concatenation of two known suffixes.
648  *	FALSE otherwise
649  *
650  * Side Effects:
651  *	None
652  *-----------------------------------------------------------------------
653  */
654 Boolean
655 Suff_IsTransform(char *str)
656 {
657     Suff    	  *src, *targ;
658 
659     return (SuffParseTransform(str, &src, &targ));
660 }
661 
662 /*-
663  *-----------------------------------------------------------------------
664  * Suff_AddTransform --
665  *	Add the transformation rule described by the line to the
666  *	list of rules and place the transformation itself in the graph
667  *
668  * Input:
669  *	line		name of transformation to add
670  *
671  * Results:
672  *	The node created for the transformation in the transforms list
673  *
674  * Side Effects:
675  *	The node is placed on the end of the transforms Lst and links are
676  *	made between the two suffixes mentioned in the target name
677  *-----------------------------------------------------------------------
678  */
679 GNode *
680 Suff_AddTransform(char *line)
681 {
682     GNode         *gn;		/* GNode of transformation rule */
683     Suff          *s,		/* source suffix */
684                   *t;		/* target suffix */
685     LstNode 	  ln;	    	/* Node for existing transformation */
686 
687     ln = Lst_Find (transforms, (ClientData)line, SuffGNHasNameP);
688     if (ln == NILLNODE) {
689 	/*
690 	 * Make a new graph node for the transformation. It will be filled in
691 	 * by the Parse module.
692 	 */
693 	gn = Targ_NewGN (line);
694 	(void)Lst_AtEnd (transforms, (ClientData)gn);
695     } else {
696 	/*
697 	 * New specification for transformation rule. Just nuke the old list
698 	 * of commands so they can be filled in again... We don't actually
699 	 * free the commands themselves, because a given command can be
700 	 * attached to several different transformations.
701 	 */
702 	gn = (GNode *) Lst_Datum (ln);
703 	Lst_Destroy (gn->commands, NOFREE);
704 	Lst_Destroy (gn->children, NOFREE);
705 	gn->commands = Lst_Init (FALSE);
706 	gn->children = Lst_Init (FALSE);
707     }
708 
709     gn->type = OP_TRANSFORM;
710 
711     (void)SuffParseTransform(line, &s, &t);
712 
713     /*
714      * link the two together in the proper relationship and order
715      */
716     if (DEBUG(SUFF)) {
717 	printf("defining transformation from `%s' to `%s'\n",
718 		s->name, t->name);
719     }
720     SuffInsert (t->children, s);
721     SuffInsert (s->parents, t);
722 
723     return (gn);
724 }
725 
726 /*-
727  *-----------------------------------------------------------------------
728  * Suff_EndTransform --
729  *	Handle the finish of a transformation definition, removing the
730  *	transformation from the graph if it has neither commands nor
731  *	sources. This is a callback procedure for the Parse module via
732  *	Lst_ForEach
733  *
734  * Input:
735  *	gnp		Node for transformation
736  *	dummy		Node for transformation
737  *
738  * Results:
739  *	=== 0
740  *
741  * Side Effects:
742  *	If the node has no commands or children, the children and parents
743  *	lists of the affected suffices are altered.
744  *
745  *-----------------------------------------------------------------------
746  */
747 int
748 Suff_EndTransform(ClientData gnp, ClientData dummy)
749 {
750     GNode *gn = (GNode *) gnp;
751 
752     if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty (gn->cohorts))
753 	gn = (GNode *) Lst_Datum (Lst_Last (gn->cohorts));
754     if ((gn->type & OP_TRANSFORM) && Lst_IsEmpty(gn->commands) &&
755 	Lst_IsEmpty(gn->children))
756     {
757 	Suff	*s, *t;
758 
759 	/*
760 	 * SuffParseTransform() may fail for special rules which are not
761 	 * actual transformation rules. (e.g. .DEFAULT)
762 	 */
763 	if (SuffParseTransform(gn->name, &s, &t)) {
764 	    Lst	 p;
765 
766 	    if (DEBUG(SUFF)) {
767 		printf("deleting transformation from `%s' to `%s'\n",
768 		s->name, t->name);
769 	    }
770 
771 	    /*
772 	     * Store s->parents because s could be deleted in SuffRemove
773 	     */
774 	    p = s->parents;
775 
776 	    /*
777 	     * Remove the source from the target's children list. We check for a
778 	     * nil return to handle a beanhead saying something like
779 	     *  .c.o .c.o:
780 	     *
781 	     * We'll be called twice when the next target is seen, but .c and .o
782 	     * are only linked once...
783 	     */
784 	    SuffRemove(t->children, s);
785 
786 	    /*
787 	     * Remove the target from the source's parents list
788 	     */
789 	    SuffRemove(p, t);
790 	}
791     } else if ((gn->type & OP_TRANSFORM) && DEBUG(SUFF)) {
792 	printf("transformation %s complete\n", gn->name);
793     }
794 
795     return(dummy ? 0 : 0);
796 }
797 
798 /*-
799  *-----------------------------------------------------------------------
800  * SuffRebuildGraph --
801  *	Called from Suff_AddSuffix via Lst_ForEach to search through the
802  *	list of existing transformation rules and rebuild the transformation
803  *	graph when it has been destroyed by Suff_ClearSuffixes. If the
804  *	given rule is a transformation involving this suffix and another,
805  *	existing suffix, the proper relationship is established between
806  *	the two.
807  *
808  * Input:
809  *	transformp	Transformation to test
810  *	sp		Suffix to rebuild
811  *
812  * Results:
813  *	Always 0.
814  *
815  * Side Effects:
816  *	The appropriate links will be made between this suffix and
817  *	others if transformation rules exist for it.
818  *
819  *-----------------------------------------------------------------------
820  */
821 static int
822 SuffRebuildGraph(ClientData transformp, ClientData sp)
823 {
824     GNode   	*transform = (GNode *) transformp;
825     Suff    	*s = (Suff *) sp;
826     char 	*cp;
827     LstNode	ln;
828     Suff  	*s2;
829     SuffixCmpData sd;
830 
831     /*
832      * First see if it is a transformation from this suffix.
833      */
834     cp = SuffStrIsPrefix(s->name, transform->name);
835     if (cp != (char *)NULL) {
836 	ln = Lst_Find(sufflist, (ClientData)cp, SuffSuffHasNameP);
837 	if (ln != NILLNODE) {
838 	    /*
839 	     * Found target. Link in and return, since it can't be anything
840 	     * else.
841 	     */
842 	    s2 = (Suff *)Lst_Datum(ln);
843 	    SuffInsert(s2->children, s);
844 	    SuffInsert(s->parents, s2);
845 	    return(0);
846 	}
847     }
848 
849     /*
850      * Not from, maybe to?
851      */
852     sd.len = strlen(transform->name);
853     sd.ename = transform->name + sd.len;
854     cp = SuffSuffIsSuffix(s, &sd);
855     if (cp != (char *)NULL) {
856 	/*
857 	 * Null-terminate the source suffix in order to find it.
858 	 */
859 	cp[1] = '\0';
860 	ln = Lst_Find(sufflist, (ClientData)transform->name, SuffSuffHasNameP);
861 	/*
862 	 * Replace the start of the target suffix
863 	 */
864 	cp[1] = s->name[0];
865 	if (ln != NILLNODE) {
866 	    /*
867 	     * Found it -- establish the proper relationship
868 	     */
869 	    s2 = (Suff *)Lst_Datum(ln);
870 	    SuffInsert(s->children, s2);
871 	    SuffInsert(s2->parents, s);
872 	}
873     }
874     return(0);
875 }
876 
877 /*-
878  *-----------------------------------------------------------------------
879  * SuffScanTargets --
880  *	Called from Suff_AddSuffix via Lst_ForEach to search through the
881  *	list of existing targets and find if any of the existing targets
882  *	can be turned into a transformation rule.
883  *
884  * Results:
885  *	1 if a new main target has been selected, 0 otherwise.
886  *
887  * Side Effects:
888  *	If such a target is found and the target is the current main
889  *	target, the main target is set to NULL and the next target
890  *	examined (if that exists) becomes the main target.
891  *
892  *-----------------------------------------------------------------------
893  */
894 static int
895 SuffScanTargets(ClientData targetp, ClientData gsp)
896 {
897     GNode   	*target = (GNode *) targetp;
898     GNodeSuff	*gs = (GNodeSuff *) gsp;
899     Suff	*s, *t;
900     char 	*ptr;
901 
902     if (*gs->gn == NILGNODE && gs->r && (target->type & OP_NOTARGET) == 0) {
903 	*gs->gn = target;
904 	Targ_SetMain(target);
905 	return 1;
906     }
907 
908     if (target->type == OP_TRANSFORM)
909 	return 0;
910 
911     if ((ptr = strstr(target->name, gs->s->name)) == NULL ||
912 	ptr == target->name)
913 	return 0;
914 
915     if (SuffParseTransform(target->name, &s, &t)) {
916 	if (*gs->gn == target) {
917 	    gs->r = TRUE;
918 	    *gs->gn = NILGNODE;
919 	    Targ_SetMain(NILGNODE);
920 	}
921 	Lst_Destroy (target->children, NOFREE);
922 	target->children = Lst_Init (FALSE);
923 	target->type = OP_TRANSFORM;
924 	/*
925 	 * link the two together in the proper relationship and order
926 	 */
927 	if (DEBUG(SUFF)) {
928 	    printf("defining transformation from `%s' to `%s'\n",
929 		s->name, t->name);
930 	}
931 	SuffInsert (t->children, s);
932 	SuffInsert (s->parents, t);
933     }
934     return 0;
935 }
936 
937 /*-
938  *-----------------------------------------------------------------------
939  * Suff_AddSuffix --
940  *	Add the suffix in string to the end of the list of known suffixes.
941  *	Should we restructure the suffix graph? Make doesn't...
942  *
943  * Input:
944  *	str		the name of the suffix to add
945  *
946  * Results:
947  *	None
948  *
949  * Side Effects:
950  *	A GNode is created for the suffix and a Suff structure is created and
951  *	added to the suffixes list unless the suffix was already known.
952  *	The mainNode passed can be modified if a target mutated into a
953  *	transform and that target happened to be the main target.
954  *-----------------------------------------------------------------------
955  */
956 void
957 Suff_AddSuffix(char *str, GNode **gn)
958 {
959     Suff          *s;	    /* new suffix descriptor */
960     LstNode 	  ln;
961     GNodeSuff	  gs;
962 
963     ln = Lst_Find (sufflist, (ClientData)str, SuffSuffHasNameP);
964     if (ln == NILLNODE) {
965 	s = (Suff *) emalloc (sizeof (Suff));
966 
967 	s->name =   	estrdup (str);
968 	s->nameLen = 	strlen (s->name);
969 	s->searchPath = Lst_Init (FALSE);
970 	s->children = 	Lst_Init (FALSE);
971 	s->parents = 	Lst_Init (FALSE);
972 	s->ref = 	Lst_Init (FALSE);
973 	s->sNum =   	sNum++;
974 	s->flags =  	0;
975 	s->refCount =	1;
976 
977 	(void)Lst_AtEnd (sufflist, (ClientData)s);
978 	/*
979 	 * We also look at our existing targets list to see if adding
980 	 * this suffix will make one of our current targets mutate into
981 	 * a suffix rule. This is ugly, but other makes treat all targets
982 	 * that start with a . as suffix rules.
983 	 */
984 	gs.gn = gn;
985 	gs.s  = s;
986 	gs.r  = FALSE;
987 	Lst_ForEach (Targ_List(), SuffScanTargets, (ClientData) &gs);
988 	/*
989 	 * Look for any existing transformations from or to this suffix.
990 	 * XXX: Only do this after a Suff_ClearSuffixes?
991 	 */
992 	Lst_ForEach (transforms, SuffRebuildGraph, (ClientData) s);
993     }
994 }
995 
996 /*-
997  *-----------------------------------------------------------------------
998  * Suff_GetPath --
999  *	Return the search path for the given suffix, if it's defined.
1000  *
1001  * Results:
1002  *	The searchPath for the desired suffix or NILLST if the suffix isn't
1003  *	defined.
1004  *
1005  * Side Effects:
1006  *	None
1007  *-----------------------------------------------------------------------
1008  */
1009 Lst
1010 Suff_GetPath(char *sname)
1011 {
1012     LstNode   	  ln;
1013     Suff    	  *s;
1014 
1015     ln = Lst_Find (sufflist, (ClientData)sname, SuffSuffHasNameP);
1016     if (ln == NILLNODE) {
1017 	return (NILLST);
1018     } else {
1019 	s = (Suff *) Lst_Datum (ln);
1020 	return (s->searchPath);
1021     }
1022 }
1023 
1024 /*-
1025  *-----------------------------------------------------------------------
1026  * Suff_DoPaths --
1027  *	Extend the search paths for all suffixes to include the default
1028  *	search path.
1029  *
1030  * Results:
1031  *	None.
1032  *
1033  * Side Effects:
1034  *	The searchPath field of all the suffixes is extended by the
1035  *	directories in dirSearchPath. If paths were specified for the
1036  *	".h" suffix, the directories are stuffed into a global variable
1037  *	called ".INCLUDES" with each directory preceded by a -I. The same
1038  *	is done for the ".a" suffix, except the variable is called
1039  *	".LIBS" and the flag is -L.
1040  *-----------------------------------------------------------------------
1041  */
1042 void
1043 Suff_DoPaths(void)
1044 {
1045     Suff	   	*s;
1046     LstNode  		ln;
1047     char		*ptr;
1048     Lst	    	    	inIncludes; /* Cumulative .INCLUDES path */
1049     Lst	    	    	inLibs;	    /* Cumulative .LIBS path */
1050 
1051     if (Lst_Open (sufflist) == FAILURE) {
1052 	return;
1053     }
1054 
1055     inIncludes = Lst_Init(FALSE);
1056     inLibs = Lst_Init(FALSE);
1057 
1058     while ((ln = Lst_Next (sufflist)) != NILLNODE) {
1059 	s = (Suff *) Lst_Datum (ln);
1060 	if (!Lst_IsEmpty (s->searchPath)) {
1061 #ifdef INCLUDES
1062 	    if (s->flags & SUFF_INCLUDE) {
1063 		Dir_Concat(inIncludes, s->searchPath);
1064 	    }
1065 #endif /* INCLUDES */
1066 #ifdef LIBRARIES
1067 	    if (s->flags & SUFF_LIBRARY) {
1068 		Dir_Concat(inLibs, s->searchPath);
1069 	    }
1070 #endif /* LIBRARIES */
1071 	    Dir_Concat(s->searchPath, dirSearchPath);
1072 	} else {
1073 	    Lst_Destroy (s->searchPath, Dir_Destroy);
1074 	    s->searchPath = Lst_Duplicate(dirSearchPath, Dir_CopyDir);
1075 	}
1076     }
1077 
1078     Var_Set(".INCLUDES", ptr = Dir_MakeFlags("-I", inIncludes), VAR_GLOBAL, 0);
1079     free(ptr);
1080     Var_Set(".LIBS", ptr = Dir_MakeFlags("-L", inLibs), VAR_GLOBAL, 0);
1081     free(ptr);
1082 
1083     Lst_Destroy(inIncludes, Dir_Destroy);
1084     Lst_Destroy(inLibs, Dir_Destroy);
1085 
1086     Lst_Close (sufflist);
1087 }
1088 
1089 /*-
1090  *-----------------------------------------------------------------------
1091  * Suff_AddInclude --
1092  *	Add the given suffix as a type of file which gets included.
1093  *	Called from the parse module when a .INCLUDES line is parsed.
1094  *	The suffix must have already been defined.
1095  *
1096  * Input:
1097  *	sname		Name of the suffix to mark
1098  *
1099  * Results:
1100  *	None.
1101  *
1102  * Side Effects:
1103  *	The SUFF_INCLUDE bit is set in the suffix's flags field
1104  *
1105  *-----------------------------------------------------------------------
1106  */
1107 void
1108 Suff_AddInclude(char *sname)
1109 {
1110     LstNode	  ln;
1111     Suff	  *s;
1112 
1113     ln = Lst_Find (sufflist, (ClientData)sname, SuffSuffHasNameP);
1114     if (ln != NILLNODE) {
1115 	s = (Suff *) Lst_Datum (ln);
1116 	s->flags |= SUFF_INCLUDE;
1117     }
1118 }
1119 
1120 /*-
1121  *-----------------------------------------------------------------------
1122  * Suff_AddLib --
1123  *	Add the given suffix as a type of file which is a library.
1124  *	Called from the parse module when parsing a .LIBS line. The
1125  *	suffix must have been defined via .SUFFIXES before this is
1126  *	called.
1127  *
1128  * Input:
1129  *	sname		Name of the suffix to mark
1130  *
1131  * Results:
1132  *	None.
1133  *
1134  * Side Effects:
1135  *	The SUFF_LIBRARY bit is set in the suffix's flags field
1136  *
1137  *-----------------------------------------------------------------------
1138  */
1139 void
1140 Suff_AddLib(char *sname)
1141 {
1142     LstNode	  ln;
1143     Suff	  *s;
1144 
1145     ln = Lst_Find (sufflist, (ClientData)sname, SuffSuffHasNameP);
1146     if (ln != NILLNODE) {
1147 	s = (Suff *) Lst_Datum (ln);
1148 	s->flags |= SUFF_LIBRARY;
1149     }
1150 }
1151 
1152  	  /********** Implicit Source Search Functions *********/
1153 
1154 /*-
1155  *-----------------------------------------------------------------------
1156  * SuffAddSrc  --
1157  *	Add a suffix as a Src structure to the given list with its parent
1158  *	being the given Src structure. If the suffix is the null suffix,
1159  *	the prefix is used unaltered as the file name in the Src structure.
1160  *
1161  * Input:
1162  *	sp		suffix for which to create a Src structure
1163  *	lsp		list and parent for the new Src
1164  *
1165  * Results:
1166  *	always returns 0
1167  *
1168  * Side Effects:
1169  *	A Src structure is created and tacked onto the end of the list
1170  *-----------------------------------------------------------------------
1171  */
1172 static int
1173 SuffAddSrc(ClientData sp, ClientData lsp)
1174 {
1175     Suff	*s = (Suff *) sp;
1176     LstSrc      *ls = (LstSrc *) lsp;
1177     Src         *s2;	    /* new Src structure */
1178     Src    	*targ; 	    /* Target structure */
1179 
1180     targ = ls->s;
1181 
1182     if ((s->flags & SUFF_NULL) && (*s->name != '\0')) {
1183 	/*
1184 	 * If the suffix has been marked as the NULL suffix, also create a Src
1185 	 * structure for a file with no suffix attached. Two birds, and all
1186 	 * that...
1187 	 */
1188 	s2 = (Src *) emalloc (sizeof (Src));
1189 	s2->file =  	estrdup(targ->pref);
1190 	s2->pref =  	targ->pref;
1191 	s2->parent = 	targ;
1192 	s2->node =  	NILGNODE;
1193 	s2->suff =  	s;
1194 	s->refCount++;
1195 	s2->children =	0;
1196 	targ->children += 1;
1197 	(void)Lst_AtEnd (ls->l, (ClientData)s2);
1198 #ifdef DEBUG_SRC
1199 	s2->cp = Lst_Init(FALSE);
1200 	Lst_AtEnd(targ->cp, (ClientData) s2);
1201 	printf("1 add %x %x to %x:", targ, s2, ls->l);
1202 	Lst_ForEach(ls->l, PrintAddr, (ClientData) 0);
1203 	printf("\n");
1204 #endif
1205     }
1206     s2 = (Src *) emalloc (sizeof (Src));
1207     s2->file = 	    str_concat (targ->pref, s->name, 0);
1208     s2->pref =	    targ->pref;
1209     s2->parent =    targ;
1210     s2->node = 	    NILGNODE;
1211     s2->suff = 	    s;
1212     s->refCount++;
1213     s2->children =  0;
1214     targ->children += 1;
1215     (void)Lst_AtEnd (ls->l, (ClientData)s2);
1216 #ifdef DEBUG_SRC
1217     s2->cp = Lst_Init(FALSE);
1218     Lst_AtEnd(targ->cp, (ClientData) s2);
1219     printf("2 add %x %x to %x:", targ, s2, ls->l);
1220     Lst_ForEach(ls->l, PrintAddr, (ClientData) 0);
1221     printf("\n");
1222 #endif
1223 
1224     return(0);
1225 }
1226 
1227 /*-
1228  *-----------------------------------------------------------------------
1229  * SuffAddLevel  --
1230  *	Add all the children of targ as Src structures to the given list
1231  *
1232  * Input:
1233  *	l		list to which to add the new level
1234  *	targ		Src structure to use as the parent
1235  *
1236  * Results:
1237  *	None
1238  *
1239  * Side Effects:
1240  * 	Lots of structures are created and added to the list
1241  *-----------------------------------------------------------------------
1242  */
1243 static void
1244 SuffAddLevel(Lst l, Src *targ)
1245 {
1246     LstSrc         ls;
1247 
1248     ls.s = targ;
1249     ls.l = l;
1250 
1251     Lst_ForEach (targ->suff->children, SuffAddSrc, (ClientData)&ls);
1252 }
1253 
1254 /*-
1255  *----------------------------------------------------------------------
1256  * SuffRemoveSrc --
1257  *	Free all src structures in list that don't have a reference count
1258  *
1259  * Results:
1260  *	Ture if an src was removed
1261  *
1262  * Side Effects:
1263  *	The memory is free'd.
1264  *----------------------------------------------------------------------
1265  */
1266 static int
1267 SuffRemoveSrc(Lst l)
1268 {
1269     LstNode ln;
1270     Src *s;
1271     int t = 0;
1272 
1273     if (Lst_Open (l) == FAILURE) {
1274 	return 0;
1275     }
1276 #ifdef DEBUG_SRC
1277     printf("cleaning %lx: ", (unsigned long) l);
1278     Lst_ForEach(l, PrintAddr, (ClientData) 0);
1279     printf("\n");
1280 #endif
1281 
1282 
1283     while ((ln = Lst_Next (l)) != NILLNODE) {
1284 	s = (Src *) Lst_Datum (ln);
1285 	if (s->children == 0) {
1286 	    free ((Address)s->file);
1287 	    if (!s->parent)
1288 		free((Address)s->pref);
1289 	    else {
1290 #ifdef DEBUG_SRC
1291 		LstNode ln = Lst_Member(s->parent->cp, (ClientData)s);
1292 		if (ln != NILLNODE)
1293 		    Lst_Remove(s->parent->cp, ln);
1294 #endif
1295 		--s->parent->children;
1296 	    }
1297 #ifdef DEBUG_SRC
1298 	    printf("free: [l=%x] p=%x %d\n", l, s, s->children);
1299 	    Lst_Destroy(s->cp, NOFREE);
1300 #endif
1301 	    Lst_Remove(l, ln);
1302 	    free ((Address)s);
1303 	    t |= 1;
1304 	    Lst_Close(l);
1305 	    return TRUE;
1306 	}
1307 #ifdef DEBUG_SRC
1308 	else {
1309 	    printf("keep: [l=%x] p=%x %d: ", l, s, s->children);
1310 	    Lst_ForEach(s->cp, PrintAddr, (ClientData) 0);
1311 	    printf("\n");
1312 	}
1313 #endif
1314     }
1315 
1316     Lst_Close(l);
1317 
1318     return t;
1319 }
1320 
1321 /*-
1322  *-----------------------------------------------------------------------
1323  * SuffFindThem --
1324  *	Find the first existing file/target in the list srcs
1325  *
1326  * Input:
1327  *	srcs		list of Src structures to search through
1328  *
1329  * Results:
1330  *	The lowest structure in the chain of transformations
1331  *
1332  * Side Effects:
1333  *	None
1334  *-----------------------------------------------------------------------
1335  */
1336 static Src *
1337 SuffFindThem(Lst srcs, Lst slst)
1338 {
1339     Src            *s;		/* current Src */
1340     Src		   *rs;		/* returned Src */
1341     char	   *ptr;
1342 
1343     rs = (Src *) NULL;
1344 
1345     while (!Lst_IsEmpty (srcs)) {
1346 	s = (Src *) Lst_DeQueue (srcs);
1347 
1348 	if (DEBUG(SUFF)) {
1349 	    printf ("\ttrying %s...", s->file);
1350 	}
1351 
1352 	/*
1353 	 * A file is considered to exist if either a node exists in the
1354 	 * graph for it or the file actually exists.
1355 	 */
1356 	if (Targ_FindNode(s->file, TARG_NOCREATE) != NILGNODE) {
1357 #ifdef DEBUG_SRC
1358 	    printf("remove %x from %x\n", s, srcs);
1359 #endif
1360 	    rs = s;
1361 	    break;
1362 	}
1363 
1364 	if ((ptr = Dir_FindFile (s->file, s->suff->searchPath)) != NULL) {
1365 	    rs = s;
1366 #ifdef DEBUG_SRC
1367 	    printf("remove %x from %x\n", s, srcs);
1368 #endif
1369 	    free(ptr);
1370 	    break;
1371 	}
1372 
1373 	if (DEBUG(SUFF)) {
1374 	    printf ("not there\n");
1375 	}
1376 
1377 	SuffAddLevel (srcs, s);
1378 	Lst_AtEnd(slst, (ClientData) s);
1379     }
1380 
1381     if (DEBUG(SUFF) && rs) {
1382 	printf ("got it\n");
1383     }
1384     return (rs);
1385 }
1386 
1387 /*-
1388  *-----------------------------------------------------------------------
1389  * SuffFindCmds --
1390  *	See if any of the children of the target in the Src structure is
1391  *	one from which the target can be transformed. If there is one,
1392  *	a Src structure is put together for it and returned.
1393  *
1394  * Input:
1395  *	targ		Src structure to play with
1396  *
1397  * Results:
1398  *	The Src structure of the "winning" child, or NIL if no such beast.
1399  *
1400  * Side Effects:
1401  *	A Src structure may be allocated.
1402  *
1403  *-----------------------------------------------------------------------
1404  */
1405 static Src *
1406 SuffFindCmds(Src *targ, Lst slst)
1407 {
1408     LstNode 	  	ln; 	/* General-purpose list node */
1409     GNode		*t, 	/* Target GNode */
1410 	    	  	*s; 	/* Source GNode */
1411     int	    	  	prefLen;/* The length of the defined prefix */
1412     Suff    	  	*suff;	/* Suffix on matching beastie */
1413     Src	    	  	*ret;	/* Return value */
1414     char    	  	*cp;
1415 
1416     t = targ->node;
1417     (void) Lst_Open (t->children);
1418     prefLen = strlen (targ->pref);
1419 
1420     while ((ln = Lst_Next (t->children)) != NILLNODE) {
1421 	s = (GNode *)Lst_Datum (ln);
1422 
1423 	cp = strrchr (s->name, '/');
1424 	if (cp == (char *)NULL) {
1425 	    cp = s->name;
1426 	} else {
1427 	    cp++;
1428 	}
1429 	if (strncmp (cp, targ->pref, prefLen) == 0) {
1430 	    /*
1431 	     * The node matches the prefix ok, see if it has a known
1432 	     * suffix.
1433 	     */
1434 	    ln = Lst_Find (sufflist, (ClientData)&cp[prefLen],
1435 			   SuffSuffHasNameP);
1436 	    if (ln != NILLNODE) {
1437 		/*
1438 		 * It even has a known suffix, see if there's a transformation
1439 		 * defined between the node's suffix and the target's suffix.
1440 		 *
1441 		 * XXX: Handle multi-stage transformations here, too.
1442 		 */
1443 		suff = (Suff *)Lst_Datum (ln);
1444 
1445 		if (Lst_Member (suff->parents,
1446 				(ClientData)targ->suff) != NILLNODE)
1447 		{
1448 		    /*
1449 		     * Hot Damn! Create a new Src structure to describe
1450 		     * this transformation (making sure to duplicate the
1451 		     * source node's name so Suff_FindDeps can free it
1452 		     * again (ick)), and return the new structure.
1453 		     */
1454 		    ret = (Src *)emalloc (sizeof (Src));
1455 		    ret->file = estrdup(s->name);
1456 		    ret->pref = targ->pref;
1457 		    ret->suff = suff;
1458 		    suff->refCount++;
1459 		    ret->parent = targ;
1460 		    ret->node = s;
1461 		    ret->children = 0;
1462 		    targ->children += 1;
1463 #ifdef DEBUG_SRC
1464 		    ret->cp = Lst_Init(FALSE);
1465 		    printf("3 add %x %x\n", targ, ret);
1466 		    Lst_AtEnd(targ->cp, (ClientData) ret);
1467 #endif
1468 		    Lst_AtEnd(slst, (ClientData) ret);
1469 		    if (DEBUG(SUFF)) {
1470 			printf ("\tusing existing source %s\n", s->name);
1471 		    }
1472 		    return (ret);
1473 		}
1474 	    }
1475 	}
1476     }
1477     Lst_Close (t->children);
1478     return ((Src *)NULL);
1479 }
1480 
1481 /*-
1482  *-----------------------------------------------------------------------
1483  * SuffExpandChildren --
1484  *	Expand the names of any children of a given node that contain
1485  *	variable invocations or file wildcards into actual targets.
1486  *
1487  * Input:
1488  *	prevLN		Child to examine
1489  *	pgn		Parent node being processed
1490  *
1491  * Results:
1492  *	=== 0 (continue)
1493  *
1494  * Side Effects:
1495  *	The expanded node is removed from the parent's list of children,
1496  *	and the parent's unmade counter is decremented, but other nodes
1497  * 	may be added.
1498  *
1499  *-----------------------------------------------------------------------
1500  */
1501 static int
1502 SuffExpandChildren(LstNode prevLN, GNode *pgn)
1503 {
1504     GNode   	*cgn = (GNode *) Lst_Datum(prevLN);
1505     GNode	*gn;	    /* New source 8) */
1506     LstNode	ln;	    /* List element for old source */
1507     char	*cp;	    /* Expanded value */
1508 
1509     /*
1510      * First do variable expansion -- this takes precedence over
1511      * wildcard expansion. If the result contains wildcards, they'll be gotten
1512      * to later since the resulting words are tacked on to the end of
1513      * the children list.
1514      */
1515     if (strchr(cgn->name, '$') != (char *)NULL) {
1516 	if (DEBUG(SUFF)) {
1517 	    printf("Expanding \"%s\"...", cgn->name);
1518 	}
1519 	cp = Var_Subst(NULL, cgn->name, pgn, TRUE);
1520 
1521 	if (cp != (char *)NULL) {
1522 	    Lst	    members = Lst_Init(FALSE);
1523 
1524 	    if (cgn->type & OP_ARCHV) {
1525 		/*
1526 		 * Node was an archive(member) target, so we want to call
1527 		 * on the Arch module to find the nodes for us, expanding
1528 		 * variables in the parent's context.
1529 		 */
1530 		char	*sacrifice = cp;
1531 
1532 		(void)Arch_ParseArchive(&sacrifice, members, pgn);
1533 	    } else {
1534 		/*
1535 		 * Break the result into a vector of strings whose nodes
1536 		 * we can find, then add those nodes to the members list.
1537 		 * Unfortunately, we can't use brk_string b/c it
1538 		 * doesn't understand about variable specifications with
1539 		 * spaces in them...
1540 		 */
1541 		char	    *start;
1542 		char	    *initcp = cp;   /* For freeing... */
1543 
1544 		for (start = cp; *start == ' ' || *start == '\t'; start++)
1545 		    continue;
1546 		for (cp = start; *cp != '\0'; cp++) {
1547 		    if (*cp == ' ' || *cp == '\t') {
1548 			/*
1549 			 * White-space -- terminate element, find the node,
1550 			 * add it, skip any further spaces.
1551 			 */
1552 			*cp++ = '\0';
1553 			gn = Targ_FindNode(start, TARG_CREATE);
1554 			(void)Lst_AtEnd(members, (ClientData)gn);
1555 			while (*cp == ' ' || *cp == '\t') {
1556 			    cp++;
1557 			}
1558 			/*
1559 			 * Adjust cp for increment at start of loop, but
1560 			 * set start to first non-space.
1561 			 */
1562 			start = cp--;
1563 		    } else if (*cp == '$') {
1564 			/*
1565 			 * Start of a variable spec -- contact variable module
1566 			 * to find the end so we can skip over it.
1567 			 */
1568 			char	*junk;
1569 			int 	len;
1570 			Boolean	doFree;
1571 
1572 			junk = Var_Parse(cp, pgn, TRUE, &len, &doFree);
1573 			if (junk != var_Error) {
1574 			    cp += len - 1;
1575 			}
1576 
1577 			if (doFree) {
1578 			    free(junk);
1579 			}
1580 		    } else if (*cp == '\\' && *cp != '\0') {
1581 			/*
1582 			 * Escaped something -- skip over it
1583 			 */
1584 			cp++;
1585 		    }
1586 		}
1587 
1588 		if (cp != start) {
1589 		    /*
1590 		     * Stuff left over -- add it to the list too
1591 		     */
1592 		    gn = Targ_FindNode(start, TARG_CREATE);
1593 		    (void)Lst_AtEnd(members, (ClientData)gn);
1594 		}
1595 		/*
1596 		 * Point cp back at the beginning again so the variable value
1597 		 * can be freed.
1598 		 */
1599 		cp = initcp;
1600 	    }
1601 	    /*
1602 	     * Add all elements of the members list to the parent node.
1603 	     */
1604 	    while(!Lst_IsEmpty(members)) {
1605 		gn = (GNode *)Lst_DeQueue(members);
1606 
1607 		if (DEBUG(SUFF)) {
1608 		    printf("%s...", gn->name);
1609 		}
1610 		if (Lst_Member(pgn->children, (ClientData)gn) == NILLNODE) {
1611 		    (void)Lst_Append(pgn->children, prevLN, (ClientData)gn);
1612 		    prevLN = Lst_Succ(prevLN);
1613 		    (void)Lst_AtEnd(gn->parents, (ClientData)pgn);
1614 		    pgn->unmade++;
1615 		}
1616 	    }
1617 	    Lst_Destroy(members, NOFREE);
1618 	    /*
1619 	     * Free the result
1620 	     */
1621 	    free((char *)cp);
1622 	}
1623 	/*
1624 	 * Now the source is expanded, remove it from the list of children to
1625 	 * keep it from being processed.
1626 	 */
1627 	if (DEBUG(SUFF)) {
1628 	    printf("\n");
1629 	}
1630 	return(1);
1631     } else if (Dir_HasWildcards(cgn->name)) {
1632 	Lst 	explist;    /* List of expansions */
1633 	Lst 	path;	    /* Search path along which to expand */
1634 	SuffixCmpData sd;   /* Search string data */
1635 
1636 	/*
1637 	 * Find a path along which to expand the word.
1638 	 *
1639 	 * If the word has a known suffix, use that path.
1640 	 * If it has no known suffix and we're allowed to use the null
1641 	 *   suffix, use its path.
1642 	 * Else use the default system search path.
1643 	 */
1644 	sd.len = strlen(cgn->name);
1645 	sd.ename = cgn->name + sd.len;
1646 	ln = Lst_Find(sufflist, (ClientData)&sd, SuffSuffIsSuffixP);
1647 
1648 	if (DEBUG(SUFF)) {
1649 	    printf("Wildcard expanding \"%s\"...", cgn->name);
1650 	}
1651 
1652 	if (ln != NILLNODE) {
1653 	    Suff    *s = (Suff *)Lst_Datum(ln);
1654 
1655 	    if (DEBUG(SUFF)) {
1656 		printf("suffix is \"%s\"...", s->name);
1657 	    }
1658 	    path = s->searchPath;
1659 	} else {
1660 	    /*
1661 	     * Use default search path
1662 	     */
1663 	    path = dirSearchPath;
1664 	}
1665 
1666 	/*
1667 	 * Expand the word along the chosen path
1668 	 */
1669 	explist = Lst_Init(FALSE);
1670 	Dir_Expand(cgn->name, path, explist);
1671 
1672 	while (!Lst_IsEmpty(explist)) {
1673 	    /*
1674 	     * Fetch next expansion off the list and find its GNode
1675 	     */
1676 	    cp = (char *)Lst_DeQueue(explist);
1677 
1678 	    if (DEBUG(SUFF)) {
1679 		printf("%s...", cp);
1680 	    }
1681 	    gn = Targ_FindNode(cp, TARG_CREATE);
1682 
1683 	    /*
1684 	     * If gn isn't already a child of the parent, make it so and
1685 	     * up the parent's count of unmade children.
1686 	     */
1687 	    if (Lst_Member(pgn->children, (ClientData)gn) == NILLNODE) {
1688 		(void)Lst_Append(pgn->children, prevLN, (ClientData)gn);
1689 		prevLN = Lst_Succ(prevLN);
1690 		(void)Lst_AtEnd(gn->parents, (ClientData)pgn);
1691 		pgn->unmade++;
1692 	    }
1693 	}
1694 
1695 	/*
1696 	 * Nuke what's left of the list
1697 	 */
1698 	Lst_Destroy(explist, NOFREE);
1699 
1700 	/*
1701 	 * Now the source is expanded, remove it from the list of children to
1702 	 * keep it from being processed.
1703 	 */
1704 	if (DEBUG(SUFF)) {
1705 	    printf("\n");
1706 	}
1707 	return(1);
1708     }
1709 
1710     return(0);
1711 }
1712 
1713 /*-
1714  *-----------------------------------------------------------------------
1715  * SuffApplyTransform --
1716  *	Apply a transformation rule, given the source and target nodes
1717  *	and suffixes.
1718  *
1719  * Input:
1720  *	tGn		Target node
1721  *	sGn		Source node
1722  *	t		Target suffix
1723  *	s		Source suffix
1724  *
1725  * Results:
1726  *	TRUE if successful, FALSE if not.
1727  *
1728  * Side Effects:
1729  *	The source and target are linked and the commands from the
1730  *	transformation are added to the target node's commands list.
1731  *	All attributes but OP_DEPMASK and OP_TRANSFORM are applied
1732  *	to the target. The target also inherits all the sources for
1733  *	the transformation rule.
1734  *
1735  *-----------------------------------------------------------------------
1736  */
1737 static Boolean
1738 SuffApplyTransform(GNode *tGn, GNode *sGn, Suff *t, Suff *s)
1739 {
1740     LstNode 	ln, nln;    /* General node */
1741     char    	*tname;	    /* Name of transformation rule */
1742     GNode   	*gn;	    /* Node for same */
1743 
1744     /*
1745      * Form the proper links between the target and source.
1746      */
1747     (void)Lst_AtEnd(tGn->children, (ClientData)sGn);
1748     (void)Lst_AtEnd(sGn->parents, (ClientData)tGn);
1749     tGn->unmade += 1;
1750 
1751     /*
1752      * Locate the transformation rule itself
1753      */
1754     tname = str_concat(s->name, t->name, 0);
1755     ln = Lst_Find(transforms, (ClientData)tname, SuffGNHasNameP);
1756     free(tname);
1757 
1758     if (ln == NILLNODE) {
1759 	/*
1760 	 * Not really such a transformation rule (can happen when we're
1761 	 * called to link an OP_MEMBER and OP_ARCHV node), so return
1762 	 * FALSE.
1763 	 */
1764 	return(FALSE);
1765     }
1766 
1767     gn = (GNode *)Lst_Datum(ln);
1768 
1769     if (DEBUG(SUFF)) {
1770 	printf("\tapplying %s -> %s to \"%s\"\n", s->name, t->name, tGn->name);
1771     }
1772 
1773     /*
1774      * Record last child for expansion purposes
1775      */
1776     ln = Lst_Last(tGn->children);
1777 
1778     /*
1779      * Pass the buck to Make_HandleUse to apply the rule
1780      */
1781     (void)Make_HandleUse(gn, tGn);
1782 
1783     /*
1784      * Deal with wildcards and variables in any acquired sources
1785      */
1786     ln = Lst_Succ(ln);
1787     while (ln != NILLNODE) {
1788 	if (SuffExpandChildren(ln, tGn)) {
1789 	    nln = Lst_Succ(ln);
1790 	    tGn->unmade--;
1791 	    Lst_Remove(tGn->children, ln);
1792 	    ln = nln;
1793 	} else
1794 	    ln = Lst_Succ(ln);
1795     }
1796 
1797     /*
1798      * Keep track of another parent to which this beast is transformed so
1799      * the .IMPSRC variable can be set correctly for the parent.
1800      */
1801     (void)Lst_AtEnd(sGn->iParents, (ClientData)tGn);
1802 
1803     return(TRUE);
1804 }
1805 
1806 
1807 /*-
1808  *-----------------------------------------------------------------------
1809  * SuffFindArchiveDeps --
1810  *	Locate dependencies for an OP_ARCHV node.
1811  *
1812  * Input:
1813  *	gn		Node for which to locate dependencies
1814  *
1815  * Results:
1816  *	None
1817  *
1818  * Side Effects:
1819  *	Same as Suff_FindDeps
1820  *
1821  *-----------------------------------------------------------------------
1822  */
1823 static void
1824 SuffFindArchiveDeps(GNode *gn, Lst slst)
1825 {
1826     char    	*eoarch;    /* End of archive portion */
1827     char    	*eoname;    /* End of member portion */
1828     GNode   	*mem;	    /* Node for member */
1829     static const char	*copy[] = {
1830 	/* Variables to be copied from the member node */
1831 	TARGET,	    	    /* Must be first */
1832 	PREFIX,	    	    /* Must be second */
1833     };
1834     int	    	i;  	    /* Index into copy and vals */
1835     Suff    	*ms;	    /* Suffix descriptor for member */
1836     char    	*name;	    /* Start of member's name */
1837 
1838     /*
1839      * The node is an archive(member) pair. so we must find a
1840      * suffix for both of them.
1841      */
1842     eoarch = strchr (gn->name, '(');
1843     eoname = strchr (eoarch, ')');
1844 
1845     *eoname = '\0';	  /* Nuke parentheses during suffix search */
1846     *eoarch = '\0';	  /* So a suffix can be found */
1847 
1848     name = eoarch + 1;
1849 
1850     /*
1851      * To simplify things, call Suff_FindDeps recursively on the member now,
1852      * so we can simply compare the member's .PREFIX and .TARGET variables
1853      * to locate its suffix. This allows us to figure out the suffix to
1854      * use for the archive without having to do a quadratic search over the
1855      * suffix list, backtracking for each one...
1856      */
1857     mem = Targ_FindNode(name, TARG_CREATE);
1858     SuffFindDeps(mem, slst);
1859 
1860     /*
1861      * Create the link between the two nodes right off
1862      */
1863     (void)Lst_AtEnd(gn->children, (ClientData)mem);
1864     (void)Lst_AtEnd(mem->parents, (ClientData)gn);
1865     gn->unmade += 1;
1866 
1867     /*
1868      * Copy in the variables from the member node to this one.
1869      */
1870     for (i = (sizeof(copy)/sizeof(copy[0]))-1; i >= 0; i--) {
1871 	char *p1;
1872 	Var_Set(copy[i], Var_Value(copy[i], mem, &p1), gn, 0);
1873 	if (p1)
1874 	    free(p1);
1875 
1876     }
1877 
1878     ms = mem->suffix;
1879     if (ms == NULL) {
1880 	/*
1881 	 * Didn't know what it was -- use .NULL suffix if not in make mode
1882 	 */
1883 	if (DEBUG(SUFF)) {
1884 	    printf("using null suffix\n");
1885 	}
1886 	ms = suffNull;
1887     }
1888 
1889 
1890     /*
1891      * Set the other two local variables required for this target.
1892      */
1893     Var_Set (MEMBER, name, gn, 0);
1894     Var_Set (ARCHIVE, gn->name, gn, 0);
1895 
1896     if (ms != NULL) {
1897 	/*
1898 	 * Member has a known suffix, so look for a transformation rule from
1899 	 * it to a possible suffix of the archive. Rather than searching
1900 	 * through the entire list, we just look at suffixes to which the
1901 	 * member's suffix may be transformed...
1902 	 */
1903 	LstNode		ln;
1904 	SuffixCmpData	sd;		/* Search string data */
1905 
1906 	/*
1907 	 * Use first matching suffix...
1908 	 */
1909 	sd.len = eoarch - gn->name;
1910 	sd.ename = eoarch;
1911 	ln = Lst_Find(ms->parents, &sd, SuffSuffIsSuffixP);
1912 
1913 	if (ln != NILLNODE) {
1914 	    /*
1915 	     * Got one -- apply it
1916 	     */
1917 	    if (!SuffApplyTransform(gn, mem, (Suff *)Lst_Datum(ln), ms) &&
1918 		DEBUG(SUFF))
1919 	    {
1920 		printf("\tNo transformation from %s -> %s\n",
1921 		       ms->name, ((Suff *)Lst_Datum(ln))->name);
1922 	    }
1923 	}
1924     }
1925 
1926     /*
1927      * Replace the opening and closing parens now we've no need of the separate
1928      * pieces.
1929      */
1930     *eoarch = '('; *eoname = ')';
1931 
1932     /*
1933      * Pretend gn appeared to the left of a dependency operator so
1934      * the user needn't provide a transformation from the member to the
1935      * archive.
1936      */
1937     if (OP_NOP(gn->type)) {
1938 	gn->type |= OP_DEPENDS;
1939     }
1940 
1941     /*
1942      * Flag the member as such so we remember to look in the archive for
1943      * its modification time.
1944      */
1945     mem->type |= OP_MEMBER;
1946 }
1947 
1948 /*-
1949  *-----------------------------------------------------------------------
1950  * SuffFindNormalDeps --
1951  *	Locate implicit dependencies for regular targets.
1952  *
1953  * Input:
1954  *	gn		Node for which to find sources
1955  *
1956  * Results:
1957  *	None.
1958  *
1959  * Side Effects:
1960  *	Same as Suff_FindDeps...
1961  *
1962  *-----------------------------------------------------------------------
1963  */
1964 static void
1965 SuffFindNormalDeps(GNode *gn, Lst slst)
1966 {
1967     char    	*eoname;    /* End of name */
1968     char    	*sopref;    /* Start of prefix */
1969     LstNode 	ln, nln;    /* Next suffix node to check */
1970     Lst	    	srcs;	    /* List of sources at which to look */
1971     Lst	    	targs;	    /* List of targets to which things can be
1972 			     * transformed. They all have the same file,
1973 			     * but different suff and pref fields */
1974     Src	    	*bottom;    /* Start of found transformation path */
1975     Src 	*src;	    /* General Src pointer */
1976     char    	*pref;	    /* Prefix to use */
1977     Src	    	*targ;	    /* General Src target pointer */
1978     SuffixCmpData sd;	    /* Search string data */
1979 
1980 
1981     sd.len = strlen(gn->name);
1982     sd.ename = eoname = gn->name + sd.len;
1983 
1984     sopref = gn->name;
1985 
1986     /*
1987      * Begin at the beginning...
1988      */
1989     ln = Lst_First(sufflist);
1990     srcs = Lst_Init(FALSE);
1991     targs = Lst_Init(FALSE);
1992 
1993     /*
1994      * We're caught in a catch-22 here. On the one hand, we want to use any
1995      * transformation implied by the target's sources, but we can't examine
1996      * the sources until we've expanded any variables/wildcards they may hold,
1997      * and we can't do that until we've set up the target's local variables
1998      * and we can't do that until we know what the proper suffix for the
1999      * target is (in case there are two suffixes one of which is a suffix of
2000      * the other) and we can't know that until we've found its implied
2001      * source, which we may not want to use if there's an existing source
2002      * that implies a different transformation.
2003      *
2004      * In an attempt to get around this, which may not work all the time,
2005      * but should work most of the time, we look for implied sources first,
2006      * checking transformations to all possible suffixes of the target,
2007      * use what we find to set the target's local variables, expand the
2008      * children, then look for any overriding transformations they imply.
2009      * Should we find one, we discard the one we found before.
2010      */
2011 
2012     while (ln != NILLNODE) {
2013 	/*
2014 	 * Look for next possible suffix...
2015 	 */
2016 	ln = Lst_FindFrom(sufflist, ln, &sd, SuffSuffIsSuffixP);
2017 
2018 	if (ln != NILLNODE) {
2019 	    int	    prefLen;	    /* Length of the prefix */
2020 
2021 	    /*
2022 	     * Allocate a Src structure to which things can be transformed
2023 	     */
2024 	    targ = (Src *)emalloc(sizeof (Src));
2025 	    targ->file = estrdup(gn->name);
2026 	    targ->suff = (Suff *)Lst_Datum(ln);
2027 	    targ->suff->refCount++;
2028 	    targ->node = gn;
2029 	    targ->parent = (Src *)NULL;
2030 	    targ->children = 0;
2031 #ifdef DEBUG_SRC
2032 	    targ->cp = Lst_Init(FALSE);
2033 #endif
2034 
2035 	    /*
2036 	     * Allocate room for the prefix, whose end is found by subtracting
2037 	     * the length of the suffix from the end of the name.
2038 	     */
2039 	    prefLen = (eoname - targ->suff->nameLen) - sopref;
2040 	    targ->pref = emalloc(prefLen + 1);
2041 	    memcpy(targ->pref, sopref, prefLen);
2042 	    targ->pref[prefLen] = '\0';
2043 
2044 	    /*
2045 	     * Add nodes from which the target can be made
2046 	     */
2047 	    SuffAddLevel(srcs, targ);
2048 
2049 	    /*
2050 	     * Record the target so we can nuke it
2051 	     */
2052 	    (void)Lst_AtEnd(targs, (ClientData)targ);
2053 
2054 	    /*
2055 	     * Search from this suffix's successor...
2056 	     */
2057 	    ln = Lst_Succ(ln);
2058 	}
2059     }
2060 
2061     /*
2062      * Handle target of unknown suffix...
2063      */
2064     if (Lst_IsEmpty(targs) && suffNull != NULL) {
2065 	if (DEBUG(SUFF)) {
2066 	    printf("\tNo known suffix on %s. Using .NULL suffix\n", gn->name);
2067 	}
2068 
2069 	targ = (Src *)emalloc(sizeof (Src));
2070 	targ->file = estrdup(gn->name);
2071 	targ->suff = suffNull;
2072 	targ->suff->refCount++;
2073 	targ->node = gn;
2074 	targ->parent = (Src *)NULL;
2075 	targ->children = 0;
2076 	targ->pref = estrdup(sopref);
2077 #ifdef DEBUG_SRC
2078 	targ->cp = Lst_Init(FALSE);
2079 #endif
2080 
2081 	/*
2082 	 * Only use the default suffix rules if we don't have commands
2083 	 * defined for this gnode; traditional make programs used to
2084 	 * not define suffix rules if the gnode had children but we
2085 	 * don't do this anymore.
2086 	 */
2087 	if (Lst_IsEmpty(gn->commands))
2088 	    SuffAddLevel(srcs, targ);
2089 	else {
2090 	    if (DEBUG(SUFF))
2091 		printf("not ");
2092 	}
2093 
2094 	if (DEBUG(SUFF))
2095 	    printf("adding suffix rules\n");
2096 
2097 	(void)Lst_AtEnd(targs, (ClientData)targ);
2098     }
2099 
2100     /*
2101      * Using the list of possible sources built up from the target suffix(es),
2102      * try and find an existing file/target that matches.
2103      */
2104     bottom = SuffFindThem(srcs, slst);
2105 
2106     if (bottom == (Src *)NULL) {
2107 	/*
2108 	 * No known transformations -- use the first suffix found for setting
2109 	 * the local variables.
2110 	 */
2111 	if (!Lst_IsEmpty(targs)) {
2112 	    targ = (Src *)Lst_Datum(Lst_First(targs));
2113 	} else {
2114 	    targ = (Src *)NULL;
2115 	}
2116     } else {
2117 	/*
2118 	 * Work up the transformation path to find the suffix of the
2119 	 * target to which the transformation was made.
2120 	 */
2121 	for (targ = bottom; targ->parent != NULL; targ = targ->parent)
2122 	    continue;
2123     }
2124 
2125     Var_Set(TARGET, gn->path ? gn->path : gn->name, gn, 0);
2126 
2127     pref = (targ != NULL) ? targ->pref : gn->name;
2128     Var_Set(PREFIX, pref, gn, 0);
2129 
2130     /*
2131      * Now we've got the important local variables set, expand any sources
2132      * that still contain variables or wildcards in their names.
2133      */
2134     ln = Lst_First(gn->children);
2135     while (ln != NILLNODE) {
2136 	if (SuffExpandChildren(ln, gn)) {
2137 	    nln = Lst_Succ(ln);
2138 	    gn->unmade--;
2139 	    Lst_Remove(gn->children, ln);
2140 	    ln = nln;
2141 	} else
2142 	    ln = Lst_Succ(ln);
2143     }
2144 
2145     if (targ == NULL) {
2146 	if (DEBUG(SUFF)) {
2147 	    printf("\tNo valid suffix on %s\n", gn->name);
2148 	}
2149 
2150 sfnd_abort:
2151 	/*
2152 	 * Deal with finding the thing on the default search path. We
2153 	 * always do that, not only if the node is only a source (not
2154 	 * on the lhs of a dependency operator or [XXX] it has neither
2155 	 * children or commands) as the old pmake did.
2156 	 */
2157 	if ((gn->type & (OP_PHONY|OP_NOPATH)) == 0) {
2158 	    free(gn->path);
2159 	    gn->path = Dir_FindFile(gn->name,
2160 				    (targ == NULL ? dirSearchPath :
2161 				     targ->suff->searchPath));
2162 	    if (gn->path != NULL) {
2163 		char *ptr;
2164 		Var_Set(TARGET, gn->path, gn, 0);
2165 
2166 		if (targ != NULL) {
2167 		    /*
2168 		     * Suffix known for the thing -- trim the suffix off
2169 		     * the path to form the proper .PREFIX variable.
2170 		     */
2171 		    int     savep = strlen(gn->path) - targ->suff->nameLen;
2172 		    char    savec;
2173 
2174 		    if (gn->suffix)
2175 			gn->suffix->refCount--;
2176 		    gn->suffix = targ->suff;
2177 		    gn->suffix->refCount++;
2178 
2179 		    savec = gn->path[savep];
2180 		    gn->path[savep] = '\0';
2181 
2182 		    if ((ptr = strrchr(gn->path, '/')) != NULL)
2183 			ptr++;
2184 		    else
2185 			ptr = gn->path;
2186 
2187 		    Var_Set(PREFIX, ptr, gn, 0);
2188 
2189 		    gn->path[savep] = savec;
2190 		} else {
2191 		    /*
2192 		     * The .PREFIX gets the full path if the target has
2193 		     * no known suffix.
2194 		     */
2195 		    if (gn->suffix)
2196 			gn->suffix->refCount--;
2197 		    gn->suffix = NULL;
2198 
2199 		    if ((ptr = strrchr(gn->path, '/')) != NULL)
2200 			ptr++;
2201 		    else
2202 			ptr = gn->path;
2203 
2204 		    Var_Set(PREFIX, ptr, gn, 0);
2205 		}
2206 	    }
2207 	}
2208 
2209 	goto sfnd_return;
2210     }
2211 
2212     /*
2213      * If the suffix indicates that the target is a library, mark that in
2214      * the node's type field.
2215      */
2216     if (targ->suff->flags & SUFF_LIBRARY) {
2217 	gn->type |= OP_LIB;
2218     }
2219 
2220     /*
2221      * Check for overriding transformation rule implied by sources
2222      */
2223     if (!Lst_IsEmpty(gn->children)) {
2224 	src = SuffFindCmds(targ, slst);
2225 
2226 	if (src != (Src *)NULL) {
2227 	    /*
2228 	     * Free up all the Src structures in the transformation path
2229 	     * up to, but not including, the parent node.
2230 	     */
2231 	    while (bottom && bottom->parent != NULL) {
2232 		if (Lst_Member(slst, (ClientData) bottom) == NILLNODE) {
2233 		    Lst_AtEnd(slst, (ClientData) bottom);
2234 		}
2235 		bottom = bottom->parent;
2236 	    }
2237 	    bottom = src;
2238 	}
2239     }
2240 
2241     if (bottom == NULL) {
2242 	/*
2243 	 * No idea from where it can come -- return now.
2244 	 */
2245 	goto sfnd_abort;
2246     }
2247 
2248     /*
2249      * We now have a list of Src structures headed by 'bottom' and linked via
2250      * their 'parent' pointers. What we do next is create links between
2251      * source and target nodes (which may or may not have been created)
2252      * and set the necessary local variables in each target. The
2253      * commands for each target are set from the commands of the
2254      * transformation rule used to get from the src suffix to the targ
2255      * suffix. Note that this causes the commands list of the original
2256      * node, gn, to be replaced by the commands of the final
2257      * transformation rule. Also, the unmade field of gn is incremented.
2258      * Etc.
2259      */
2260     if (bottom->node == NILGNODE) {
2261 	bottom->node = Targ_FindNode(bottom->file, TARG_CREATE);
2262     }
2263 
2264     for (src = bottom; src->parent != (Src *)NULL; src = src->parent) {
2265 	targ = src->parent;
2266 
2267 	if (src->node->suffix)
2268 	    src->node->suffix->refCount--;
2269 	src->node->suffix = src->suff;
2270 	src->node->suffix->refCount++;
2271 
2272 	if (targ->node == NILGNODE) {
2273 	    targ->node = Targ_FindNode(targ->file, TARG_CREATE);
2274 	}
2275 
2276 	SuffApplyTransform(targ->node, src->node,
2277 			   targ->suff, src->suff);
2278 
2279 	if (targ->node != gn) {
2280 	    /*
2281 	     * Finish off the dependency-search process for any nodes
2282 	     * between bottom and gn (no point in questing around the
2283 	     * filesystem for their implicit source when it's already
2284 	     * known). Note that the node can't have any sources that
2285 	     * need expanding, since SuffFindThem will stop on an existing
2286 	     * node, so all we need to do is set the standard and System V
2287 	     * variables.
2288 	     */
2289 	    targ->node->type |= OP_DEPS_FOUND;
2290 
2291 	    Var_Set(PREFIX, targ->pref, targ->node, 0);
2292 
2293 	    Var_Set(TARGET, targ->node->name, targ->node, 0);
2294 	}
2295     }
2296 
2297     if (gn->suffix)
2298 	gn->suffix->refCount--;
2299     gn->suffix = src->suff;
2300     gn->suffix->refCount++;
2301 
2302     /*
2303      * Nuke the transformation path and the Src structures left over in the
2304      * two lists.
2305      */
2306 sfnd_return:
2307     if (bottom)
2308 	if (Lst_Member(slst, (ClientData) bottom) == NILLNODE)
2309 	    Lst_AtEnd(slst, (ClientData) bottom);
2310 
2311     while (SuffRemoveSrc(srcs) || SuffRemoveSrc(targs))
2312 	continue;
2313 
2314     Lst_Concat(slst, srcs, LST_CONCLINK);
2315     Lst_Concat(slst, targs, LST_CONCLINK);
2316 }
2317 
2318 
2319 /*-
2320  *-----------------------------------------------------------------------
2321  * Suff_FindDeps  --
2322  *	Find implicit sources for the target described by the graph node
2323  *	gn
2324  *
2325  * Results:
2326  *	Nothing.
2327  *
2328  * Side Effects:
2329  *	Nodes are added to the graph below the passed-in node. The nodes
2330  *	are marked to have their IMPSRC variable filled in. The
2331  *	PREFIX variable is set for the given node and all its
2332  *	implied children.
2333  *
2334  * Notes:
2335  *	The path found by this target is the shortest path in the
2336  *	transformation graph, which may pass through non-existent targets,
2337  *	to an existing target. The search continues on all paths from the
2338  *	root suffix until a file is found. I.e. if there's a path
2339  *	.o -> .c -> .l -> .l,v from the root and the .l,v file exists but
2340  *	the .c and .l files don't, the search will branch out in
2341  *	all directions from .o and again from all the nodes on the
2342  *	next level until the .l,v node is encountered.
2343  *
2344  *-----------------------------------------------------------------------
2345  */
2346 
2347 void
2348 Suff_FindDeps(GNode *gn)
2349 {
2350 
2351     SuffFindDeps(gn, srclist);
2352     while (SuffRemoveSrc(srclist))
2353 	continue;
2354 }
2355 
2356 
2357 /*
2358  * Input:
2359  *	gn		node we're dealing with
2360  *
2361  */
2362 static void
2363 SuffFindDeps(GNode *gn, Lst slst)
2364 {
2365     if (gn->type & (OP_DEPS_FOUND|OP_PHONY)) {
2366 	/*
2367 	 * If dependencies already found, no need to do it again...
2368 	 * If this is a .PHONY target, we do not apply suffix rules.
2369 	 */
2370 	return;
2371     } else {
2372 	gn->type |= OP_DEPS_FOUND;
2373     }
2374 
2375     if (DEBUG(SUFF)) {
2376 	printf ("SuffFindDeps (%s)\n", gn->name);
2377     }
2378 
2379     if (gn->type & OP_ARCHV) {
2380 	SuffFindArchiveDeps(gn, slst);
2381     } else if (gn->type & OP_LIB) {
2382 	/*
2383 	 * If the node is a library, it is the arch module's job to find it
2384 	 * and set the TARGET variable accordingly. We merely provide the
2385 	 * search path, assuming all libraries end in ".a" (if the suffix
2386 	 * hasn't been defined, there's nothing we can do for it, so we just
2387 	 * set the TARGET variable to the node's name in order to give it a
2388 	 * value).
2389 	 */
2390 	LstNode	ln;
2391 	Suff	*s;
2392 
2393 	ln = Lst_Find (sufflist, (ClientData)UNCONST(LIBSUFF),
2394 	    SuffSuffHasNameP);
2395 	if (gn->suffix)
2396 	    gn->suffix->refCount--;
2397 	if (ln != NILLNODE) {
2398 	    gn->suffix = s = (Suff *) Lst_Datum (ln);
2399 	    gn->suffix->refCount++;
2400 	    Arch_FindLib (gn, s->searchPath);
2401 	} else {
2402 	    gn->suffix = NULL;
2403 	    Var_Set (TARGET, gn->name, gn, 0);
2404 	}
2405 	/*
2406 	 * Because a library (-lfoo) target doesn't follow the standard
2407 	 * filesystem conventions, we don't set the regular variables for
2408 	 * the thing. .PREFIX is simply made empty...
2409 	 */
2410 	Var_Set(PREFIX, "", gn, 0);
2411     } else {
2412 	SuffFindNormalDeps(gn, slst);
2413     }
2414 }
2415 
2416 /*-
2417  *-----------------------------------------------------------------------
2418  * Suff_SetNull --
2419  *	Define which suffix is the null suffix.
2420  *
2421  * Input:
2422  *	name		Name of null suffix
2423  *
2424  * Results:
2425  *	None.
2426  *
2427  * Side Effects:
2428  *	'suffNull' is altered.
2429  *
2430  * Notes:
2431  *	Need to handle the changing of the null suffix gracefully so the
2432  *	old transformation rules don't just go away.
2433  *
2434  *-----------------------------------------------------------------------
2435  */
2436 void
2437 Suff_SetNull(char *name)
2438 {
2439     Suff    *s;
2440     LstNode ln;
2441 
2442     ln = Lst_Find(sufflist, (ClientData)name, SuffSuffHasNameP);
2443     if (ln != NILLNODE) {
2444 	s = (Suff *)Lst_Datum(ln);
2445 	if (suffNull != (Suff *)NULL) {
2446 	    suffNull->flags &= ~SUFF_NULL;
2447 	}
2448 	s->flags |= SUFF_NULL;
2449 	/*
2450 	 * XXX: Here's where the transformation mangling would take place
2451 	 */
2452 	suffNull = s;
2453     } else {
2454 	Parse_Error (PARSE_WARNING, "Desired null suffix %s not defined.",
2455 		     name);
2456     }
2457 }
2458 
2459 /*-
2460  *-----------------------------------------------------------------------
2461  * Suff_Init --
2462  *	Initialize suffixes module
2463  *
2464  * Results:
2465  *	None
2466  *
2467  * Side Effects:
2468  *	Many
2469  *-----------------------------------------------------------------------
2470  */
2471 void
2472 Suff_Init(void)
2473 {
2474     sufflist = Lst_Init (FALSE);
2475 #ifdef CLEANUP
2476     suffClean = Lst_Init(FALSE);
2477 #endif
2478     srclist = Lst_Init (FALSE);
2479     transforms = Lst_Init (FALSE);
2480 
2481     sNum = 0;
2482     /*
2483      * Create null suffix for single-suffix rules (POSIX). The thing doesn't
2484      * actually go on the suffix list or everyone will think that's its
2485      * suffix.
2486      */
2487     emptySuff = suffNull = (Suff *) emalloc (sizeof (Suff));
2488 
2489     suffNull->name =   	    estrdup ("");
2490     suffNull->nameLen =     0;
2491     suffNull->searchPath =  Lst_Init (FALSE);
2492     Dir_Concat(suffNull->searchPath, dirSearchPath);
2493     suffNull->children =    Lst_Init (FALSE);
2494     suffNull->parents =	    Lst_Init (FALSE);
2495     suffNull->ref =	    Lst_Init (FALSE);
2496     suffNull->sNum =   	    sNum++;
2497     suffNull->flags =  	    SUFF_NULL;
2498     suffNull->refCount =    1;
2499 
2500 }
2501 
2502 
2503 /*-
2504  *----------------------------------------------------------------------
2505  * Suff_End --
2506  *	Cleanup the this module
2507  *
2508  * Results:
2509  *	None
2510  *
2511  * Side Effects:
2512  *	The memory is free'd.
2513  *----------------------------------------------------------------------
2514  */
2515 
2516 void
2517 Suff_End(void)
2518 {
2519 #ifdef CLEANUP
2520     Lst_Destroy(sufflist, SuffFree);
2521     Lst_Destroy(suffClean, SuffFree);
2522     if (suffNull)
2523 	SuffFree(suffNull);
2524     Lst_Destroy(srclist, NOFREE);
2525     Lst_Destroy(transforms, NOFREE);
2526 #endif
2527 }
2528 
2529 
2530 /********************* DEBUGGING FUNCTIONS **********************/
2531 
2532 static int SuffPrintName(ClientData s, ClientData dummy)
2533 {
2534     printf ("%s ", ((Suff *) s)->name);
2535     return (dummy ? 0 : 0);
2536 }
2537 
2538 static int
2539 SuffPrintSuff(ClientData sp, ClientData dummy)
2540 {
2541     Suff    *s = (Suff *) sp;
2542     int	    flags;
2543     int	    flag;
2544 
2545     printf ("# `%s' [%d] ", s->name, s->refCount);
2546 
2547     flags = s->flags;
2548     if (flags) {
2549 	fputs (" (", stdout);
2550 	while (flags) {
2551 	    flag = 1 << (ffs(flags) - 1);
2552 	    flags &= ~flag;
2553 	    switch (flag) {
2554 		case SUFF_NULL:
2555 		    printf ("NULL");
2556 		    break;
2557 		case SUFF_INCLUDE:
2558 		    printf ("INCLUDE");
2559 		    break;
2560 		case SUFF_LIBRARY:
2561 		    printf ("LIBRARY");
2562 		    break;
2563 	    }
2564 	    fputc(flags ? '|' : ')', stdout);
2565 	}
2566     }
2567     fputc ('\n', stdout);
2568     printf ("#\tTo: ");
2569     Lst_ForEach (s->parents, SuffPrintName, (ClientData)0);
2570     fputc ('\n', stdout);
2571     printf ("#\tFrom: ");
2572     Lst_ForEach (s->children, SuffPrintName, (ClientData)0);
2573     fputc ('\n', stdout);
2574     printf ("#\tSearch Path: ");
2575     Dir_PrintPath (s->searchPath);
2576     fputc ('\n', stdout);
2577     return (dummy ? 0 : 0);
2578 }
2579 
2580 static int
2581 SuffPrintTrans(ClientData tp, ClientData dummy)
2582 {
2583     GNode   *t = (GNode *) tp;
2584 
2585     printf ("%-16s: ", t->name);
2586     Targ_PrintType (t->type);
2587     fputc ('\n', stdout);
2588     Lst_ForEach (t->commands, Targ_PrintCmd, (ClientData)0);
2589     fputc ('\n', stdout);
2590     return(dummy ? 0 : 0);
2591 }
2592 
2593 void
2594 Suff_PrintAll(void)
2595 {
2596     printf ("#*** Suffixes:\n");
2597     Lst_ForEach (sufflist, SuffPrintSuff, (ClientData)0);
2598 
2599     printf ("#*** Transformations:\n");
2600     Lst_ForEach (transforms, SuffPrintTrans, (ClientData)0);
2601 }
2602