Home | History | Annotate | Line # | Download | only in make
suff.c revision 1.350
      1 /*	$NetBSD: suff.c,v 1.350 2021/04/04 10:05:08 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 /*
     72  * Maintain suffix lists and find implicit dependents using suffix
     73  * transformation rules such as ".c.o".
     74  *
     75  * Interface:
     76  *	Suff_Init	Initialize the module.
     77  *
     78  *	Suff_End	Clean up the module.
     79  *
     80  *	Suff_ExtendPaths
     81  *			Extend the search path of each suffix to include the
     82  *			default search path.
     83  *
     84  *	Suff_ClearSuffixes
     85  *			Clear out all the suffixes and transformations.
     86  *
     87  *	Suff_IsTransform
     88  *			See if the passed string is a transformation rule.
     89  *
     90  *	Suff_AddSuffix	Add the passed string as another known suffix.
     91  *
     92  *	Suff_GetPath	Return the search path for the given suffix.
     93  *
     94  *	Suff_AddInclude
     95  *			Mark the given suffix as denoting an include file.
     96  *
     97  *	Suff_AddLib	Mark the given suffix as denoting a library.
     98  *
     99  *	Suff_AddTransform
    100  *			Add another transformation to the suffix graph.
    101  *
    102  *	Suff_SetNull	Define the suffix to consider the suffix of
    103  *			any file that doesn't have a known one.
    104  *
    105  *	Suff_FindDeps	Find implicit sources for and the location of
    106  *			a target based on its suffix. Returns the
    107  *			bottom-most node added to the graph or NULL
    108  *			if the target had no implicit sources.
    109  *
    110  *	Suff_FindPath	Return the appropriate path to search in order to
    111  *			find the node.
    112  */
    113 
    114 #include "make.h"
    115 #include "dir.h"
    116 
    117 /*	"@(#)suff.c	8.4 (Berkeley) 3/21/94"	*/
    118 MAKE_RCSID("$NetBSD: suff.c,v 1.350 2021/04/04 10:05:08 rillig Exp $");
    119 
    120 typedef List SuffixList;
    121 typedef ListNode SuffixListNode;
    122 
    123 typedef List CandidateList;
    124 typedef ListNode CandidateListNode;
    125 
    126 /* The defined suffixes, such as '.c', '.o', '.l'. */
    127 static SuffixList sufflist = LST_INIT;
    128 #ifdef CLEANUP
    129 /* The suffixes to be cleaned up at the end. */
    130 static SuffixList suffClean = LST_INIT;
    131 #endif
    132 
    133 /*
    134  * The transformation rules, such as '.c.o' to transform '.c' into '.o',
    135  * or simply '.c' to transform 'file.c' into 'file'.
    136  */
    137 static GNodeList transforms = LST_INIT;
    138 
    139 /*
    140  * Counter for assigning suffix numbers.
    141  * TODO: What are these suffix numbers used for?
    142  */
    143 static int sNum = 0;
    144 
    145 typedef enum SuffixFlags {
    146 	SUFF_NONE	= 0,
    147 
    148 	/*
    149 	 * This suffix marks include files.  Their search path ends up in the
    150 	 * undocumented special variable '.INCLUDES'.
    151 	 */
    152 	SUFF_INCLUDE	= 1 << 0,
    153 
    154 	/*
    155 	 * This suffix marks library files.  Their search path ends up in the
    156 	 * undocumented special variable '.LIBS'.
    157 	 */
    158 	SUFF_LIBRARY	= 1 << 1,
    159 
    160 	/*
    161 	 * The empty suffix.
    162 	 *
    163 	 * XXX: What is the difference between the empty suffix and the null
    164 	 * suffix?
    165 	 *
    166 	 * XXX: Why is SUFF_NULL needed at all? Wouldn't nameLen == 0 mean
    167 	 * the same?
    168 	 */
    169 	SUFF_NULL	= 1 << 2
    170 
    171 } SuffixFlags;
    172 
    173 ENUM_FLAGS_RTTI_3(SuffixFlags,
    174     SUFF_INCLUDE, SUFF_LIBRARY, SUFF_NULL);
    175 
    176 typedef List SuffixListList;
    177 
    178 /*
    179  * A suffix such as ".c" or ".o" that is used in suffix transformation rules
    180  * such as ".c.o:".
    181  */
    182 typedef struct Suffix {
    183 	/* The suffix itself, such as ".c" */
    184 	char *name;
    185 	/* Length of the name, to avoid strlen calls */
    186 	size_t nameLen;
    187 	/* Type of suffix */
    188 	SuffixFlags flags;
    189 	/* The path along which files of this suffix may be found */
    190 	SearchPath *searchPath;
    191 	/* The suffix number; TODO: document the purpose of this number */
    192 	int sNum;
    193 	/* Reference count of list membership and several other places */
    194 	int refCount;
    195 	/* Suffixes we have a transformation to */
    196 	SuffixList parents;
    197 	/* Suffixes we have a transformation from */
    198 	SuffixList children;
    199 
    200 	/* Lists in which this suffix is referenced.
    201 	 *
    202 	 * XXX: These lists are used nowhere, they are just appended to, for
    203 	 * no apparent reason.  They do have the side effect of increasing
    204 	 * refCount though. */
    205 	SuffixListList ref;
    206 } Suffix;
    207 
    208 /*
    209  * A candidate when searching for implied sources.
    210  *
    211  * For example, when "src.o" is to be made, a typical candidate is "src.c"
    212  * via the transformation rule ".c.o".  If that doesn't exist, maybe there is
    213  * another transformation rule ".pas.c" that would make "src.pas" an indirect
    214  * candidate as well.  The first such chain that leads to an existing file or
    215  * node is finally chosen to be made.
    216  */
    217 typedef struct Candidate {
    218 	/* The file or node to look for. */
    219 	char *file;
    220 	/* The prefix from which file was formed.
    221 	 * Its memory is shared among all candidates. */
    222 	char *prefix;
    223 	/* The suffix on the file. */
    224 	Suffix *suff;
    225 
    226 	/* The candidate that can be made from this,
    227 	 * or NULL for the top-level candidate. */
    228 	struct Candidate *parent;
    229 	/* The node describing the file. */
    230 	GNode *node;
    231 
    232 	/* Count of existing children, only used for memory management, so we
    233 	 * don't free this candidate too early or too late. */
    234 	int numChildren;
    235 #ifdef DEBUG_SRC
    236 	CandidateList childrenList;
    237 #endif
    238 } Candidate;
    239 
    240 typedef struct CandidateSearcher {
    241 
    242 	CandidateList list;
    243 
    244 	/*
    245 	 * TODO: Add HashSet for seen entries, to avoid endless loops such as
    246 	 * in suff-transform-endless.mk.
    247 	 */
    248 
    249 } CandidateSearcher;
    250 
    251 
    252 /* TODO: Document the difference between nullSuff and emptySuff. */
    253 /* The NULL suffix for this run */
    254 static Suffix *nullSuff;
    255 /* The empty suffix required for POSIX single-suffix transformation rules */
    256 static Suffix *emptySuff;
    257 
    258 
    259 static Suffix *
    260 Suffix_Ref(Suffix *suff)
    261 {
    262 	suff->refCount++;
    263 	return suff;
    264 }
    265 
    266 /* Change the value of a Suffix variable, adjusting the reference counts. */
    267 static void
    268 Suffix_Reassign(Suffix **var, Suffix *suff)
    269 {
    270 	if (*var != NULL)
    271 		(*var)->refCount--;
    272 	*var = suff;
    273 	suff->refCount++;
    274 }
    275 
    276 /* Set a Suffix variable to NULL, adjusting the reference count. */
    277 static void
    278 Suffix_Unassign(Suffix **var)
    279 {
    280 	if (*var != NULL)
    281 		(*var)->refCount--;
    282 	*var = NULL;
    283 }
    284 
    285 /*
    286  * See if pref is a prefix of str.
    287  * Return NULL if it ain't, pointer to character in str after prefix if so.
    288  */
    289 static const char *
    290 StrTrimPrefix(const char *pref, const char *str)
    291 {
    292 	while (*str != '\0' && *pref == *str) {
    293 		pref++;
    294 		str++;
    295 	}
    296 
    297 	return *pref != '\0' ? NULL : str;
    298 }
    299 
    300 /*
    301  * See if suff is a suffix of str, and if so, return the pointer to the suffix
    302  * in str, which at the same time marks the end of the prefix.
    303  */
    304 static const char *
    305 StrTrimSuffix(const char *str, size_t strLen, const char *suff, size_t suffLen)
    306 {
    307 	const char *suffInStr;
    308 	size_t i;
    309 
    310 	if (strLen < suffLen)
    311 		return NULL;
    312 
    313 	suffInStr = str + strLen - suffLen;
    314 	for (i = 0; i < suffLen; i++)
    315 		if (suff[i] != suffInStr[i])
    316 			return NULL;
    317 
    318 	return suffInStr;
    319 }
    320 
    321 /*
    322  * See if suff is a suffix of name, and if so, return the end of the prefix
    323  * in name.
    324  */
    325 static const char *
    326 Suffix_TrimSuffix(const Suffix *suff, size_t nameLen, const char *nameEnd)
    327 {
    328 	return StrTrimSuffix(nameEnd - nameLen, nameLen,
    329 	    suff->name, suff->nameLen);
    330 }
    331 
    332 static bool
    333 Suffix_IsSuffix(const Suffix *suff, size_t nameLen, const char *nameEnd)
    334 {
    335 	return Suffix_TrimSuffix(suff, nameLen, nameEnd) != NULL;
    336 }
    337 
    338 static Suffix *
    339 FindSuffixByNameLen(const char *name, size_t nameLen)
    340 {
    341 	SuffixListNode *ln;
    342 
    343 	for (ln = sufflist.first; ln != NULL; ln = ln->next) {
    344 		Suffix *suff = ln->datum;
    345 		if (suff->nameLen == nameLen &&
    346 		    memcmp(suff->name, name, nameLen) == 0)
    347 			return suff;
    348 	}
    349 	return NULL;
    350 }
    351 
    352 static Suffix *
    353 FindSuffixByName(const char *name)
    354 {
    355 	return FindSuffixByNameLen(name, strlen(name));
    356 }
    357 
    358 static GNode *
    359 FindTransformByName(const char *name)
    360 {
    361 	GNodeListNode *ln;
    362 
    363 	for (ln = transforms.first; ln != NULL; ln = ln->next) {
    364 		GNode *gn = ln->datum;
    365 		if (strcmp(gn->name, name) == 0)
    366 			return gn;
    367 	}
    368 	return NULL;
    369 }
    370 
    371 static void
    372 SuffixList_Unref(SuffixList *list, Suffix *suff)
    373 {
    374 	SuffixListNode *ln = Lst_FindDatum(list, suff);
    375 	if (ln != NULL) {
    376 		Lst_Remove(list, ln);
    377 		suff->refCount--;
    378 	}
    379 }
    380 
    381 /* Free up all memory associated with the given suffix structure. */
    382 static void
    383 Suffix_Free(Suffix *suff)
    384 {
    385 
    386 	if (suff == nullSuff)
    387 		nullSuff = NULL;
    388 
    389 	if (suff == emptySuff)
    390 		emptySuff = NULL;
    391 
    392 #if 0
    393 	/* We don't delete suffixes in order, so we cannot use this */
    394 	if (suff->refCount != 0)
    395 		Punt("Internal error deleting suffix `%s' with refcount = %d",
    396 		    suff->name, suff->refCount);
    397 #endif
    398 
    399 	Lst_Done(&suff->ref);
    400 	Lst_Done(&suff->children);
    401 	Lst_Done(&suff->parents);
    402 	SearchPath_Free(suff->searchPath);
    403 
    404 	free(suff->name);
    405 	free(suff);
    406 }
    407 
    408 static void
    409 SuffFree(void *p)
    410 {
    411 	Suffix_Free(p);
    412 }
    413 
    414 /* Remove the suffix from the list, and free if it is otherwise unused. */
    415 static void
    416 SuffixList_Remove(SuffixList *list, Suffix *suff)
    417 {
    418 	SuffixList_Unref(list, suff);
    419 	if (suff->refCount == 0) {
    420 		/* XXX: can lead to suff->refCount == -1 */
    421 		SuffixList_Unref(&sufflist, suff);
    422 		DEBUG1(SUFF, "Removing suffix \"%s\"\n", suff->name);
    423 		SuffFree(suff);
    424 	}
    425 }
    426 
    427 /*
    428  * Insert the suffix into the list, keeping the list ordered by suffix
    429  * number.
    430  */
    431 static void
    432 SuffixList_Insert(SuffixList *list, Suffix *suff)
    433 {
    434 	SuffixListNode *ln;
    435 	Suffix *listSuff = NULL;
    436 
    437 	for (ln = list->first; ln != NULL; ln = ln->next) {
    438 		listSuff = ln->datum;
    439 		if (listSuff->sNum >= suff->sNum)
    440 			break;
    441 	}
    442 
    443 	if (ln == NULL) {
    444 		DEBUG2(SUFF, "inserting \"%s\" (%d) at end of list\n",
    445 		    suff->name, suff->sNum);
    446 		Lst_Append(list, Suffix_Ref(suff));
    447 		Lst_Append(&suff->ref, list);
    448 	} else if (listSuff->sNum != suff->sNum) {
    449 		DEBUG4(SUFF, "inserting \"%s\" (%d) before \"%s\" (%d)\n",
    450 		    suff->name, suff->sNum, listSuff->name, listSuff->sNum);
    451 		Lst_InsertBefore(list, ln, Suffix_Ref(suff));
    452 		Lst_Append(&suff->ref, list);
    453 	} else {
    454 		DEBUG2(SUFF, "\"%s\" (%d) is already there\n",
    455 		    suff->name, suff->sNum);
    456 	}
    457 }
    458 
    459 static void
    460 Relate(Suffix *srcSuff, Suffix *targSuff)
    461 {
    462 	SuffixList_Insert(&targSuff->children, srcSuff);
    463 	SuffixList_Insert(&srcSuff->parents, targSuff);
    464 }
    465 
    466 static Suffix *
    467 Suffix_New(const char *name)
    468 {
    469 	Suffix *suff = bmake_malloc(sizeof *suff);
    470 
    471 	suff->name = bmake_strdup(name);
    472 	suff->nameLen = strlen(suff->name);
    473 	suff->searchPath = SearchPath_New();
    474 	Lst_Init(&suff->children);
    475 	Lst_Init(&suff->parents);
    476 	Lst_Init(&suff->ref);
    477 	suff->sNum = sNum++;
    478 	suff->flags = SUFF_NONE;
    479 	suff->refCount = 1; /* XXX: why 1? It's not assigned anywhere yet. */
    480 
    481 	return suff;
    482 }
    483 
    484 /*
    485  * Nuke the list of suffixes but keep all transformation rules around. The
    486  * transformation graph is destroyed in this process, but we leave the list
    487  * of rules so when a new graph is formed, the rules will remain. This
    488  * function is called when a line '.SUFFIXES:' with an empty suffixes list is
    489  * encountered in a makefile.
    490  */
    491 void
    492 Suff_ClearSuffixes(void)
    493 {
    494 #ifdef CLEANUP
    495 	Lst_MoveAll(&suffClean, &sufflist);
    496 #endif
    497 	DEBUG0(SUFF, "Clearing all suffixes\n");
    498 	Lst_Init(&sufflist);
    499 	sNum = 0;
    500 	if (nullSuff != NULL)
    501 		SuffFree(nullSuff);
    502 	emptySuff = nullSuff = Suffix_New("");
    503 
    504 	SearchPath_AddAll(nullSuff->searchPath, &dirSearchPath);
    505 	nullSuff->flags = SUFF_NULL;
    506 }
    507 
    508 /*
    509  * Parse a transformation string such as ".c.o" to find its two component
    510  * suffixes (the source ".c" and the target ".o").  If there are no such
    511  * suffixes, try a single-suffix transformation as well.
    512  *
    513  * Return true if the string is a valid transformation.
    514  */
    515 static bool
    516 ParseTransform(const char *str, Suffix **out_src, Suffix **out_targ)
    517 {
    518 	SuffixListNode *ln;
    519 	Suffix *single = NULL;
    520 
    521 	/*
    522 	 * Loop looking first for a suffix that matches the start of the
    523 	 * string and then for one that exactly matches the rest of it. If
    524 	 * we can find two that meet these criteria, we've successfully
    525 	 * parsed the string.
    526 	 */
    527 	for (ln = sufflist.first; ln != NULL; ln = ln->next) {
    528 		Suffix *src = ln->datum;
    529 
    530 		if (StrTrimPrefix(src->name, str) == NULL)
    531 			continue;
    532 
    533 		if (str[src->nameLen] == '\0') {
    534 			single = src;
    535 		} else {
    536 			Suffix *targ = FindSuffixByName(str + src->nameLen);
    537 			if (targ != NULL) {
    538 				*out_src = src;
    539 				*out_targ = targ;
    540 				return true;
    541 			}
    542 		}
    543 	}
    544 
    545 	if (single != NULL) {
    546 		/*
    547 		 * There was a suffix that encompassed the entire string, so we
    548 		 * assume it was a transformation to the null suffix (thank you
    549 		 * POSIX; search for "single suffix" or "single-suffix").
    550 		 *
    551 		 * We still prefer to find a double rule over a singleton,
    552 		 * hence we leave this check until the end.
    553 		 *
    554 		 * XXX: Use emptySuff over nullSuff?
    555 		 */
    556 		*out_src = single;
    557 		*out_targ = nullSuff;
    558 		return true;
    559 	}
    560 	return false;
    561 }
    562 
    563 /*
    564  * Return true if the given string is a transformation rule, that is, a
    565  * concatenation of two known suffixes such as ".c.o" or a single suffix
    566  * such as ".o".
    567  */
    568 bool
    569 Suff_IsTransform(const char *str)
    570 {
    571 	Suffix *src, *targ;
    572 
    573 	return ParseTransform(str, &src, &targ);
    574 }
    575 
    576 /*
    577  * Add the transformation rule to the list of rules and place the
    578  * transformation itself in the graph.
    579  *
    580  * The transformation is linked to the two suffixes mentioned in the name.
    581  *
    582  * Input:
    583  *	name		must have the form ".from.to" or just ".from"
    584  *
    585  * Results:
    586  *	The created or existing transformation node in the transforms list
    587  */
    588 GNode *
    589 Suff_AddTransform(const char *name)
    590 {
    591 	Suffix *srcSuff;
    592 	Suffix *targSuff;
    593 
    594 	GNode *gn = FindTransformByName(name);
    595 	if (gn == NULL) {
    596 		/*
    597 		 * Make a new graph node for the transformation. It will be
    598 		 * filled in by the Parse module.
    599 		 */
    600 		gn = GNode_New(name);
    601 		Lst_Append(&transforms, gn);
    602 	} else {
    603 		/*
    604 		 * New specification for transformation rule. Just nuke the
    605 		 * old list of commands so they can be filled in again. We
    606 		 * don't actually free the commands themselves, because a
    607 		 * given command can be attached to several different
    608 		 * transformations.
    609 		 */
    610 		Lst_Done(&gn->commands);
    611 		Lst_Init(&gn->commands);
    612 		Lst_Done(&gn->children);
    613 		Lst_Init(&gn->children);
    614 	}
    615 
    616 	gn->type = OP_TRANSFORM;
    617 
    618 	{
    619 		/* TODO: Avoid the redundant parsing here. */
    620 		bool ok = ParseTransform(name, &srcSuff, &targSuff);
    621 		assert(ok);
    622 		(void)ok;
    623 	}
    624 
    625 	/* Link the two together in the proper relationship and order. */
    626 	DEBUG2(SUFF, "defining transformation from `%s' to `%s'\n",
    627 	    srcSuff->name, targSuff->name);
    628 	Relate(srcSuff, targSuff);
    629 
    630 	return gn;
    631 }
    632 
    633 /*
    634  * Handle the finish of a transformation definition, removing the
    635  * transformation from the graph if it has neither commands nor sources.
    636  *
    637  * If the node has no commands or children, the children and parents lists
    638  * of the affected suffixes are altered.
    639  *
    640  * Input:
    641  *	gn		Node for transformation
    642  */
    643 void
    644 Suff_EndTransform(GNode *gn)
    645 {
    646 	Suffix *srcSuff, *targSuff;
    647 	SuffixList *srcSuffParents;
    648 
    649 	if ((gn->type & OP_DOUBLEDEP) && !Lst_IsEmpty(&gn->cohorts))
    650 		gn = gn->cohorts.last->datum;
    651 
    652 	if (!(gn->type & OP_TRANSFORM))
    653 		return;
    654 
    655 	if (!Lst_IsEmpty(&gn->commands) || !Lst_IsEmpty(&gn->children)) {
    656 		DEBUG1(SUFF, "transformation %s complete\n", gn->name);
    657 		return;
    658 	}
    659 
    660 	/*
    661 	 * SuffParseTransform() may fail for special rules which are not
    662 	 * actual transformation rules. (e.g. .DEFAULT)
    663 	 */
    664 	if (!ParseTransform(gn->name, &srcSuff, &targSuff))
    665 		return;
    666 
    667 	DEBUG2(SUFF, "deleting incomplete transformation from `%s' to `%s'\n",
    668 	    srcSuff->name, targSuff->name);
    669 
    670 	/*
    671 	 * Remember the parents since srcSuff could be deleted in
    672 	 * SuffixList_Remove.
    673 	 */
    674 	srcSuffParents = &srcSuff->parents;
    675 	SuffixList_Remove(&targSuff->children, srcSuff);
    676 	SuffixList_Remove(srcSuffParents, targSuff);
    677 }
    678 
    679 /*
    680  * Called from Suff_AddSuffix to search through the list of
    681  * existing transformation rules and rebuild the transformation graph when
    682  * it has been destroyed by Suff_ClearSuffixes. If the given rule is a
    683  * transformation involving this suffix and another, existing suffix, the
    684  * proper relationship is established between the two.
    685  *
    686  * The appropriate links will be made between this suffix and others if
    687  * transformation rules exist for it.
    688  *
    689  * Input:
    690  *	transform	Transformation to test
    691  *	suff		Suffix to rebuild
    692  */
    693 static void
    694 RebuildGraph(GNode *transform, Suffix *suff)
    695 {
    696 	const char *name = transform->name;
    697 	size_t nameLen = strlen(name);
    698 	const char *toName;
    699 
    700 	/* See if it is a transformation from this suffix to another suffix. */
    701 	toName = StrTrimPrefix(suff->name, name);
    702 	if (toName != NULL) {
    703 		Suffix *to = FindSuffixByName(toName);
    704 		if (to != NULL) {
    705 			Relate(suff, to);
    706 			return;
    707 		}
    708 	}
    709 
    710 	/* See if it is a transformation from another suffix to this suffix. */
    711 	toName = Suffix_TrimSuffix(suff, nameLen, name + nameLen);
    712 	if (toName != NULL) {
    713 		Suffix *from = FindSuffixByNameLen(name,
    714 		    (size_t)(toName - name));
    715 		if (from != NULL)
    716 			Relate(from, suff);
    717 	}
    718 }
    719 
    720 /*
    721  * During Suff_AddSuffix, search through the list of existing targets and find
    722  * if any of the existing targets can be turned into a transformation rule.
    723  *
    724  * If such a target is found and the target is the current main target, the
    725  * main target is set to NULL and the next target examined (if that exists)
    726  * becomes the main target.
    727  *
    728  * Results:
    729  *	true iff a new main target has been selected.
    730  */
    731 static bool
    732 UpdateTarget(GNode *target, GNode **inout_main, Suffix *suff,
    733 	     bool *inout_removedMain)
    734 {
    735 	Suffix *srcSuff, *targSuff;
    736 	char *ptr;
    737 
    738 	if (*inout_main == NULL && *inout_removedMain &&
    739 	    !(target->type & OP_NOTARGET)) {
    740 		DEBUG1(MAKE, "Setting main node to \"%s\"\n", target->name);
    741 		*inout_main = target;
    742 		Targ_SetMain(target);
    743 		/*
    744 		 * XXX: Why could it be a good idea to return true here?
    745 		 * The main task of this function is to turn ordinary nodes
    746 		 * into transformations, no matter whether or not a new .MAIN
    747 		 * node has been found.
    748 		 */
    749 		/*
    750 		 * XXX: Even when changing this to false, none of the existing
    751 		 * unit tests fails.
    752 		 */
    753 		return true;
    754 	}
    755 
    756 	if (target->type == OP_TRANSFORM)
    757 		return false;
    758 
    759 	/*
    760 	 * XXX: What about a transformation ".cpp.c"?  If ".c" is added as
    761 	 * a new suffix, it seems wrong that this transformation would be
    762 	 * skipped just because ".c" happens to be a prefix of ".cpp".
    763 	 */
    764 	ptr = strstr(target->name, suff->name);
    765 	if (ptr == NULL)
    766 		return false;
    767 
    768 	/*
    769 	 * XXX: In suff-rebuild.mk, in the line '.SUFFIXES: .c .b .a', this
    770 	 * condition prevents the rule '.b.c' from being added again during
    771 	 * Suff_AddSuffix(".b").
    772 	 *
    773 	 * XXX: Removing this paragraph makes suff-add-later.mk use massive
    774 	 * amounts of memory.
    775 	 */
    776 	if (ptr == target->name)
    777 		return false;
    778 
    779 	if (ParseTransform(target->name, &srcSuff, &targSuff)) {
    780 		if (*inout_main == target) {
    781 			DEBUG1(MAKE,
    782 			    "Setting main node from \"%s\" back to null\n",
    783 			    target->name);
    784 			*inout_removedMain = true;
    785 			*inout_main = NULL;
    786 			Targ_SetMain(NULL);
    787 		}
    788 		Lst_Done(&target->children);
    789 		Lst_Init(&target->children);
    790 		target->type = OP_TRANSFORM;
    791 
    792 		/*
    793 		 * Link the two together in the proper relationship and order.
    794 		 */
    795 		DEBUG2(SUFF, "defining transformation from `%s' to `%s'\n",
    796 		    srcSuff->name, targSuff->name);
    797 		Relate(srcSuff, targSuff);
    798 	}
    799 	return false;
    800 }
    801 
    802 /*
    803  * Look at all existing targets to see if adding this suffix will make one
    804  * of the current targets mutate into a suffix rule.
    805  *
    806  * This is ugly, but other makes treat all targets that start with a '.' as
    807  * suffix rules.
    808  */
    809 static void
    810 UpdateTargets(GNode **inout_main, Suffix *suff)
    811 {
    812 	bool removedMain = false;
    813 	GNodeListNode *ln;
    814 
    815 	for (ln = Targ_List()->first; ln != NULL; ln = ln->next) {
    816 		GNode *gn = ln->datum;
    817 		if (UpdateTarget(gn, inout_main, suff, &removedMain))
    818 			break;
    819 	}
    820 }
    821 
    822 /*
    823  * Add the suffix to the end of the list of known suffixes.
    824  * Should we restructure the suffix graph? Make doesn't.
    825  *
    826  * A GNode is created for the suffix (XXX: this sounds completely wrong) and
    827  * a Suffix structure is created and added to the suffixes list unless the
    828  * suffix was already known.
    829  * The mainNode passed can be modified if a target mutated into a
    830  * transform and that target happened to be the main target.
    831  *
    832  * Input:
    833  *	name		the name of the suffix to add
    834  */
    835 void
    836 Suff_AddSuffix(const char *name, GNode **inout_main)
    837 {
    838 	GNodeListNode *ln;
    839 
    840 	Suffix *suff = FindSuffixByName(name);
    841 	if (suff != NULL)
    842 		return;
    843 
    844 	suff = Suffix_New(name);
    845 	Lst_Append(&sufflist, suff);
    846 	DEBUG1(SUFF, "Adding suffix \"%s\"\n", suff->name);
    847 
    848 	UpdateTargets(inout_main, suff);
    849 
    850 	/*
    851 	 * Look for any existing transformations from or to this suffix.
    852 	 * XXX: Only do this after a Suff_ClearSuffixes?
    853 	 */
    854 	for (ln = transforms.first; ln != NULL; ln = ln->next)
    855 		RebuildGraph(ln->datum, suff);
    856 }
    857 
    858 /* Return the search path for the given suffix, or NULL. */
    859 SearchPath *
    860 Suff_GetPath(const char *sname)
    861 {
    862 	Suffix *suff = FindSuffixByName(sname);
    863 	return suff != NULL ? suff->searchPath : NULL;
    864 }
    865 
    866 /*
    867  * Extend the search paths for all suffixes to include the default search
    868  * path (dirSearchPath).
    869  *
    870  * The default search path can be defined using the special target '.PATH'.
    871  * The search path of each suffix can be defined using the special target
    872  * '.PATH<suffix>'.
    873  *
    874  * If paths were specified for the ".h" suffix, the directories are stuffed
    875  * into a global variable called ".INCLUDES" with each directory preceded by
    876  * '-I'. The same is done for the ".a" suffix, except the variable is called
    877  * ".LIBS" and the flag is '-L'.
    878  */
    879 void
    880 Suff_ExtendPaths(void)
    881 {
    882 	SuffixListNode *ln;
    883 	char *flags;
    884 	SearchPath *includesPath = SearchPath_New();
    885 	SearchPath *libsPath = SearchPath_New();
    886 
    887 	for (ln = sufflist.first; ln != NULL; ln = ln->next) {
    888 		Suffix *suff = ln->datum;
    889 		if (!Lst_IsEmpty(&suff->searchPath->dirs)) {
    890 #ifdef INCLUDES
    891 			if (suff->flags & SUFF_INCLUDE)
    892 				SearchPath_AddAll(includesPath,
    893 				    suff->searchPath);
    894 #endif
    895 #ifdef LIBRARIES
    896 			if (suff->flags & SUFF_LIBRARY)
    897 				SearchPath_AddAll(libsPath, suff->searchPath);
    898 #endif
    899 			SearchPath_AddAll(suff->searchPath, &dirSearchPath);
    900 		} else {
    901 			SearchPath_Free(suff->searchPath);
    902 			suff->searchPath = Dir_CopyDirSearchPath();
    903 		}
    904 	}
    905 
    906 	flags = SearchPath_ToFlags(includesPath, "-I");
    907 	Global_Set(".INCLUDES", flags);
    908 	free(flags);
    909 
    910 	flags = SearchPath_ToFlags(libsPath, "-L");
    911 	Global_Set(".LIBS", flags);
    912 	free(flags);
    913 
    914 	SearchPath_Free(includesPath);
    915 	SearchPath_Free(libsPath);
    916 }
    917 
    918 /*
    919  * Add the given suffix as a type of file which gets included.
    920  * Called when a '.INCLUDES: .h' line is parsed.
    921  * To have an effect, the suffix must already exist.
    922  * This affects the magic variable '.INCLUDES'.
    923  */
    924 void
    925 Suff_AddInclude(const char *suffName)
    926 {
    927 	Suffix *suff = FindSuffixByName(suffName);
    928 	if (suff != NULL)
    929 		suff->flags |= SUFF_INCLUDE;
    930 }
    931 
    932 /*
    933  * Add the given suffix as a type of file which is a library.
    934  * Called when a '.LIBS: .a' line is parsed.
    935  * To have an effect, the suffix must already exist.
    936  * This affects the magic variable '.LIBS'.
    937  */
    938 void
    939 Suff_AddLib(const char *suffName)
    940 {
    941 	Suffix *suff = FindSuffixByName(suffName);
    942 	if (suff != NULL)
    943 		suff->flags |= SUFF_LIBRARY;
    944 }
    945 
    946 /********** Implicit Source Search Functions *********/
    947 
    948 static void
    949 CandidateSearcher_Init(CandidateSearcher *cs)
    950 {
    951 	Lst_Init(&cs->list);
    952 }
    953 
    954 static void
    955 CandidateSearcher_Done(CandidateSearcher *cs)
    956 {
    957 	Lst_Done(&cs->list);
    958 }
    959 
    960 static void
    961 CandidateSearcher_Add(CandidateSearcher *cs, Candidate *cand)
    962 {
    963 	/* TODO: filter duplicates */
    964 	Lst_Append(&cs->list, cand);
    965 }
    966 
    967 static void
    968 CandidateSearcher_AddIfNew(CandidateSearcher *cs, Candidate *cand)
    969 {
    970 	/* TODO: filter duplicates */
    971 	if (Lst_FindDatum(&cs->list, cand) == NULL)
    972 		Lst_Append(&cs->list, cand);
    973 }
    974 
    975 static void
    976 CandidateSearcher_MoveAll(CandidateSearcher *cs, CandidateList *list)
    977 {
    978 	/* TODO: filter duplicates */
    979 	Lst_MoveAll(&cs->list, list);
    980 }
    981 
    982 
    983 #ifdef DEBUG_SRC
    984 static void
    985 CandidateList_PrintAddrs(CandidateList *list)
    986 {
    987 	CandidateListNode *ln;
    988 
    989 	for (ln = list->first; ln != NULL; ln = ln->next) {
    990 		Candidate *cand = ln->datum;
    991 		debug_printf(" %p:%s", cand, cand->file);
    992 	}
    993 	debug_printf("\n");
    994 }
    995 #endif
    996 
    997 static Candidate *
    998 Candidate_New(char *name, char *prefix, Suffix *suff, Candidate *parent,
    999 	      GNode *gn)
   1000 {
   1001 	Candidate *cand = bmake_malloc(sizeof *cand);
   1002 
   1003 	cand->file = name;
   1004 	cand->prefix = prefix;
   1005 	cand->suff = Suffix_Ref(suff);
   1006 	cand->parent = parent;
   1007 	cand->node = gn;
   1008 	cand->numChildren = 0;
   1009 #ifdef DEBUG_SRC
   1010 	Lst_Init(&cand->childrenList);
   1011 #endif
   1012 
   1013 	return cand;
   1014 }
   1015 
   1016 /* Add a new candidate to the list. */
   1017 /*ARGSUSED*/
   1018 static void
   1019 CandidateList_Add(CandidateList *list, char *srcName, Candidate *targ,
   1020 		  Suffix *suff, const char *debug_tag)
   1021 {
   1022 	Candidate *cand = Candidate_New(srcName, targ->prefix, suff, targ,
   1023 	    NULL);
   1024 	targ->numChildren++;
   1025 	Lst_Append(list, cand);
   1026 
   1027 #ifdef DEBUG_SRC
   1028 	Lst_Append(&targ->childrenList, cand);
   1029 	debug_printf("%s add suff %p:%s candidate %p:%s to list %p:",
   1030 	    debug_tag, targ, targ->file, cand, cand->file, list);
   1031 	CandidateList_PrintAddrs(list);
   1032 #endif
   1033 }
   1034 
   1035 /*
   1036  * Add all candidates to the list that can be formed by applying a suffix to
   1037  * the candidate.
   1038  */
   1039 static void
   1040 CandidateList_AddCandidatesFor(CandidateList *list, Candidate *cand)
   1041 {
   1042 	SuffixListNode *ln;
   1043 	for (ln = cand->suff->children.first; ln != NULL; ln = ln->next) {
   1044 		Suffix *suff = ln->datum;
   1045 
   1046 		if ((suff->flags & SUFF_NULL) && suff->name[0] != '\0') {
   1047 			/*
   1048 			 * If the suffix has been marked as the NULL suffix,
   1049 			 * also create a candidate for a file with no suffix
   1050 			 * attached.
   1051 			 */
   1052 			CandidateList_Add(list, bmake_strdup(cand->prefix),
   1053 			    cand, suff, "1");
   1054 		}
   1055 
   1056 		CandidateList_Add(list, str_concat2(cand->prefix, suff->name),
   1057 		    cand, suff, "2");
   1058 	}
   1059 }
   1060 
   1061 /*
   1062  * Free the first candidate in the list that is not referenced anymore.
   1063  * Return whether a candidate was removed.
   1064  */
   1065 static bool
   1066 RemoveCandidate(CandidateList *srcs)
   1067 {
   1068 	CandidateListNode *ln;
   1069 
   1070 #ifdef DEBUG_SRC
   1071 	debug_printf("cleaning list %p:", srcs);
   1072 	CandidateList_PrintAddrs(srcs);
   1073 #endif
   1074 
   1075 	for (ln = srcs->first; ln != NULL; ln = ln->next) {
   1076 		Candidate *src = ln->datum;
   1077 
   1078 		if (src->numChildren == 0) {
   1079 			if (src->parent == NULL)
   1080 				free(src->prefix);
   1081 			else {
   1082 #ifdef DEBUG_SRC
   1083 				/* XXX: Lst_RemoveDatum */
   1084 				CandidateListNode *ln2;
   1085 				ln2 = Lst_FindDatum(&src->parent->childrenList,
   1086 				    src);
   1087 				if (ln2 != NULL)
   1088 					Lst_Remove(&src->parent->childrenList,
   1089 					    ln2);
   1090 #endif
   1091 				src->parent->numChildren--;
   1092 			}
   1093 #ifdef DEBUG_SRC
   1094 			debug_printf("free: list %p src %p:%s children %d\n",
   1095 			    srcs, src, src->file, src->numChildren);
   1096 			Lst_Done(&src->childrenList);
   1097 #endif
   1098 			Lst_Remove(srcs, ln);
   1099 			free(src->file);
   1100 			free(src);
   1101 			return true;
   1102 		}
   1103 #ifdef DEBUG_SRC
   1104 		else {
   1105 			debug_printf("keep: list %p src %p:%s children %d:",
   1106 			    srcs, src, src->file, src->numChildren);
   1107 			CandidateList_PrintAddrs(&src->childrenList);
   1108 		}
   1109 #endif
   1110 	}
   1111 
   1112 	return false;
   1113 }
   1114 
   1115 /* Find the first existing file/target in srcs. */
   1116 static Candidate *
   1117 FindThem(CandidateList *srcs, CandidateSearcher *cs)
   1118 {
   1119 	HashSet seen;
   1120 
   1121 	HashSet_Init(&seen);
   1122 
   1123 	while (!Lst_IsEmpty(srcs)) {
   1124 		Candidate *src = Lst_Dequeue(srcs);
   1125 
   1126 #ifdef DEBUG_SRC
   1127 		debug_printf("remove from list %p src %p:%s\n",
   1128 		    srcs, src, src->file);
   1129 #endif
   1130 		DEBUG1(SUFF, "\ttrying %s...", src->file);
   1131 
   1132 		/*
   1133 		 * A file is considered to exist if either a node exists in the
   1134 		 * graph for it or the file actually exists.
   1135 		 */
   1136 		if (Targ_FindNode(src->file) != NULL) {
   1137 		found:
   1138 			HashSet_Done(&seen);
   1139 			DEBUG0(SUFF, "got it\n");
   1140 			return src;
   1141 		}
   1142 
   1143 		{
   1144 			char *file = Dir_FindFile(src->file,
   1145 			    src->suff->searchPath);
   1146 			if (file != NULL) {
   1147 				free(file);
   1148 				goto found;
   1149 			}
   1150 		}
   1151 
   1152 		DEBUG0(SUFF, "not there\n");
   1153 
   1154 		if (HashSet_Add(&seen, src->file))
   1155 			CandidateList_AddCandidatesFor(srcs, src);
   1156 		else {
   1157 			DEBUG1(SUFF, "FindThem: skipping duplicate \"%s\"\n",
   1158 			    src->file);
   1159 		}
   1160 
   1161 		CandidateSearcher_Add(cs, src);
   1162 	}
   1163 
   1164 	HashSet_Done(&seen);
   1165 	return NULL;
   1166 }
   1167 
   1168 /*
   1169  * See if any of the children of the candidate's GNode is one from which the
   1170  * target can be transformed. If there is one, a candidate is put together
   1171  * for it and returned.
   1172  */
   1173 static Candidate *
   1174 FindCmds(Candidate *targ, CandidateSearcher *cs)
   1175 {
   1176 	GNodeListNode *gln;
   1177 	GNode *tgn;		/* Target GNode */
   1178 	GNode *sgn;		/* Source GNode */
   1179 	size_t prefLen;		/* The length of the defined prefix */
   1180 	Suffix *suff;		/* Suffix of the matching candidate */
   1181 	Candidate *ret;		/* Return value */
   1182 
   1183 	tgn = targ->node;
   1184 	prefLen = strlen(targ->prefix);
   1185 
   1186 	for (gln = tgn->children.first; gln != NULL; gln = gln->next) {
   1187 		const char *base;
   1188 
   1189 		sgn = gln->datum;
   1190 
   1191 		if (sgn->type & OP_OPTIONAL && Lst_IsEmpty(&tgn->commands)) {
   1192 			/*
   1193 			 * We haven't looked to see if .OPTIONAL files exist
   1194 			 * yet, so don't use one as the implicit source.
   1195 			 * This allows us to use .OPTIONAL in .depend files so
   1196 			 * make won't complain "don't know how to make xxx.h"
   1197 			 * when a dependent file has been moved/deleted.
   1198 			 */
   1199 			continue;
   1200 		}
   1201 
   1202 		base = str_basename(sgn->name);
   1203 		if (strncmp(base, targ->prefix, prefLen) != 0)
   1204 			continue;
   1205 		/* The node matches the prefix, see if it has a known suffix. */
   1206 		suff = FindSuffixByName(base + prefLen);
   1207 		if (suff == NULL)
   1208 			continue;
   1209 
   1210 		/*
   1211 		 * It even has a known suffix, see if there's a transformation
   1212 		 * defined between the node's suffix and the target's suffix.
   1213 		 *
   1214 		 * XXX: Handle multi-stage transformations here, too.
   1215 		 */
   1216 
   1217 		if (Lst_FindDatum(&suff->parents, targ->suff) != NULL)
   1218 			break;
   1219 	}
   1220 
   1221 	if (gln == NULL)
   1222 		return NULL;
   1223 
   1224 	ret = Candidate_New(bmake_strdup(sgn->name), targ->prefix, suff, targ,
   1225 	    sgn);
   1226 	targ->numChildren++;
   1227 #ifdef DEBUG_SRC
   1228 	debug_printf("3 add targ %p:%s ret %p:%s\n",
   1229 	    targ, targ->file, ret, ret->file);
   1230 	Lst_Append(&targ->childrenList, ret);
   1231 #endif
   1232 	CandidateSearcher_Add(cs, ret);
   1233 	DEBUG1(SUFF, "\tusing existing source %s\n", sgn->name);
   1234 	return ret;
   1235 }
   1236 
   1237 static void
   1238 ExpandWildcards(GNodeListNode *cln, GNode *pgn)
   1239 {
   1240 	GNode *cgn = cln->datum;
   1241 	StringList expansions;
   1242 
   1243 	if (!Dir_HasWildcards(cgn->name))
   1244 		return;
   1245 
   1246 	/*
   1247 	 * Expand the word along the chosen path
   1248 	 */
   1249 	Lst_Init(&expansions);
   1250 	SearchPath_Expand(Suff_FindPath(cgn), cgn->name, &expansions);
   1251 
   1252 	while (!Lst_IsEmpty(&expansions)) {
   1253 		GNode *gn;
   1254 		/*
   1255 		 * Fetch next expansion off the list and find its GNode
   1256 		 */
   1257 		char *cp = Lst_Dequeue(&expansions);
   1258 
   1259 		DEBUG1(SUFF, "%s...", cp);
   1260 		gn = Targ_GetNode(cp);
   1261 
   1262 		/* Add gn to the parents child list before the original child */
   1263 		Lst_InsertBefore(&pgn->children, cln, gn);
   1264 		Lst_Append(&gn->parents, pgn);
   1265 		pgn->unmade++;
   1266 	}
   1267 
   1268 	Lst_Done(&expansions);
   1269 
   1270 	DEBUG0(SUFF, "\n");
   1271 
   1272 	/*
   1273 	 * Now the source is expanded, remove it from the list of children to
   1274 	 * keep it from being processed.
   1275 	 */
   1276 	pgn->unmade--;
   1277 	Lst_Remove(&pgn->children, cln);
   1278 	Lst_Remove(&cgn->parents, Lst_FindDatum(&cgn->parents, pgn));
   1279 }
   1280 
   1281 /*
   1282  * Break the result into a vector of strings whose nodes we can find, then
   1283  * add those nodes to the members list.
   1284  *
   1285  * Unfortunately, we can't use Str_Words because it doesn't understand about
   1286  * variable expressions with spaces in them.
   1287  */
   1288 static void
   1289 ExpandChildrenRegular(char *cp, GNode *pgn, GNodeList *members)
   1290 {
   1291 	char *start;
   1292 
   1293 	pp_skip_hspace(&cp);
   1294 	start = cp;
   1295 	while (*cp != '\0') {
   1296 		if (*cp == ' ' || *cp == '\t') {
   1297 			GNode *gn;
   1298 			/*
   1299 			 * White-space -- terminate element, find the node,
   1300 			 * add it, skip any further spaces.
   1301 			 */
   1302 			*cp++ = '\0';
   1303 			gn = Targ_GetNode(start);
   1304 			Lst_Append(members, gn);
   1305 			pp_skip_hspace(&cp);
   1306 			/* Continue at the next non-space. */
   1307 			start = cp;
   1308 		} else if (*cp == '$') {
   1309 			/* Skip over the variable expression. */
   1310 			const char *nested_p = cp;
   1311 			FStr junk;
   1312 
   1313 			(void)Var_Parse(&nested_p, pgn, VARE_PARSE_ONLY, &junk);
   1314 			/* TODO: handle errors */
   1315 			if (junk.str == var_Error) {
   1316 				Parse_Error(PARSE_FATAL,
   1317 				    "Malformed variable expression at \"%s\"",
   1318 				    cp);
   1319 				cp++;
   1320 			} else {
   1321 				cp += nested_p - cp;
   1322 			}
   1323 
   1324 			FStr_Done(&junk);
   1325 		} else if (cp[0] == '\\' && cp[1] != '\0') {
   1326 			/* Escaped something -- skip over it. */
   1327 			/*
   1328 			 * XXX: In other places, escaping at this syntactical
   1329 			 * position is done by a '$', not a '\'.  The '\' is
   1330 			 * only used in variable modifiers.
   1331 			 */
   1332 			cp += 2;
   1333 		} else {
   1334 			cp++;
   1335 		}
   1336 	}
   1337 
   1338 	if (cp != start) {
   1339 		/*
   1340 		 * Stuff left over -- add it to the list too
   1341 		 */
   1342 		GNode *gn = Targ_GetNode(start);
   1343 		Lst_Append(members, gn);
   1344 	}
   1345 }
   1346 
   1347 /*
   1348  * Expand the names of any children of a given node that contain variable
   1349  * expressions or file wildcards into actual targets.
   1350  *
   1351  * The expanded node is removed from the parent's list of children, and the
   1352  * parent's unmade counter is decremented, but other nodes may be added.
   1353  *
   1354  * Input:
   1355  *	cln		Child to examine
   1356  *	pgn		Parent node being processed
   1357  */
   1358 static void
   1359 ExpandChildren(GNodeListNode *cln, GNode *pgn)
   1360 {
   1361 	GNode *cgn = cln->datum;
   1362 	char *cp;		/* Expanded value */
   1363 
   1364 	if (!Lst_IsEmpty(&cgn->order_pred) || !Lst_IsEmpty(&cgn->order_succ))
   1365 		/* It is all too hard to process the result of .ORDER */
   1366 		return;
   1367 
   1368 	if (cgn->type & OP_WAIT)
   1369 		/* Ignore these (& OP_PHONY ?) */
   1370 		return;
   1371 
   1372 	/*
   1373 	 * First do variable expansion -- this takes precedence over wildcard
   1374 	 * expansion. If the result contains wildcards, they'll be gotten to
   1375 	 * later since the resulting words are tacked on to the end of the
   1376 	 * children list.
   1377 	 */
   1378 	if (strchr(cgn->name, '$') == NULL) {
   1379 		ExpandWildcards(cln, pgn);
   1380 		return;
   1381 	}
   1382 
   1383 	DEBUG1(SUFF, "Expanding \"%s\"...", cgn->name);
   1384 	(void)Var_Subst(cgn->name, pgn, VARE_UNDEFERR, &cp);
   1385 	/* TODO: handle errors */
   1386 
   1387 	{
   1388 		GNodeList members = LST_INIT;
   1389 
   1390 		if (cgn->type & OP_ARCHV) {
   1391 			/*
   1392 			 * Node was an 'archive(member)' target, so
   1393 			 * call on the Arch module to find the nodes for us,
   1394 			 * expanding variables in the parent's scope.
   1395 			 */
   1396 			char *p = cp;
   1397 			(void)Arch_ParseArchive(&p, &members, pgn);
   1398 		} else {
   1399 			ExpandChildrenRegular(cp, pgn, &members);
   1400 		}
   1401 
   1402 		/*
   1403 		 * Add all elements of the members list to the parent node.
   1404 		 */
   1405 		while (!Lst_IsEmpty(&members)) {
   1406 			GNode *gn = Lst_Dequeue(&members);
   1407 
   1408 			DEBUG1(SUFF, "%s...", gn->name);
   1409 			/*
   1410 			 * Add gn to the parents child list before the
   1411 			 * original child.
   1412 			 */
   1413 			Lst_InsertBefore(&pgn->children, cln, gn);
   1414 			Lst_Append(&gn->parents, pgn);
   1415 			pgn->unmade++;
   1416 			/* Expand wildcards on new node */
   1417 			ExpandWildcards(cln->prev, pgn);
   1418 		}
   1419 		Lst_Done(&members);
   1420 
   1421 		free(cp);
   1422 	}
   1423 
   1424 	DEBUG0(SUFF, "\n");
   1425 
   1426 	/*
   1427 	 * Now the source is expanded, remove it from the list of children to
   1428 	 * keep it from being processed.
   1429 	 */
   1430 	pgn->unmade--;
   1431 	Lst_Remove(&pgn->children, cln);
   1432 	Lst_Remove(&cgn->parents, Lst_FindDatum(&cgn->parents, pgn));
   1433 }
   1434 
   1435 static void
   1436 ExpandAllChildren(GNode *gn)
   1437 {
   1438 	GNodeListNode *ln, *nln;
   1439 
   1440 	for (ln = gn->children.first; ln != NULL; ln = nln) {
   1441 		nln = ln->next;
   1442 		ExpandChildren(ln, gn);
   1443 	}
   1444 }
   1445 
   1446 /*
   1447  * Find a path along which to expand the node.
   1448  *
   1449  * If the node has a known suffix, use that path.
   1450  * If it has no known suffix, use the default system search path.
   1451  *
   1452  * Input:
   1453  *	gn		Node being examined
   1454  *
   1455  * Results:
   1456  *	The appropriate path to search for the GNode.
   1457  */
   1458 SearchPath *
   1459 Suff_FindPath(GNode *gn)
   1460 {
   1461 	Suffix *suff = gn->suffix;
   1462 
   1463 	if (suff == NULL) {
   1464 		char *name = gn->name;
   1465 		size_t nameLen = strlen(gn->name);
   1466 		SuffixListNode *ln;
   1467 		for (ln = sufflist.first; ln != NULL; ln = ln->next)
   1468 			if (Suffix_IsSuffix(ln->datum, nameLen, name + nameLen))
   1469 				break;
   1470 
   1471 		DEBUG1(SUFF, "Wildcard expanding \"%s\"...", gn->name);
   1472 		if (ln != NULL)
   1473 			suff = ln->datum;
   1474 		/*
   1475 		 * XXX: Here we can save the suffix so we don't have to do
   1476 		 * this again.
   1477 		 */
   1478 	}
   1479 
   1480 	if (suff != NULL) {
   1481 		DEBUG1(SUFF, "suffix is \"%s\"...\n", suff->name);
   1482 		return suff->searchPath;
   1483 	} else {
   1484 		DEBUG0(SUFF, "\n");
   1485 		return &dirSearchPath;	/* Use default search path */
   1486 	}
   1487 }
   1488 
   1489 /*
   1490  * Apply a transformation rule, given the source and target nodes and
   1491  * suffixes.
   1492  *
   1493  * The source and target are linked and the commands from the transformation
   1494  * are added to the target node's commands list. The target also inherits all
   1495  * the sources for the transformation rule.
   1496  *
   1497  * Results:
   1498  *	true if successful, false if not.
   1499  */
   1500 static bool
   1501 ApplyTransform(GNode *tgn, GNode *sgn, Suffix *tsuff, Suffix *ssuff)
   1502 {
   1503 	GNodeListNode *ln;
   1504 	char *tname;		/* Name of transformation rule */
   1505 	GNode *gn;		/* Node for the transformation rule */
   1506 
   1507 	/* Form the proper links between the target and source. */
   1508 	Lst_Append(&tgn->children, sgn);
   1509 	Lst_Append(&sgn->parents, tgn);
   1510 	tgn->unmade++;
   1511 
   1512 	/* Locate the transformation rule itself. */
   1513 	tname = str_concat2(ssuff->name, tsuff->name);
   1514 	gn = FindTransformByName(tname);
   1515 	free(tname);
   1516 
   1517 	/* This can happen when linking an OP_MEMBER and OP_ARCHV node. */
   1518 	if (gn == NULL)
   1519 		return false;
   1520 
   1521 	DEBUG3(SUFF, "\tapplying %s -> %s to \"%s\"\n",
   1522 	    ssuff->name, tsuff->name, tgn->name);
   1523 
   1524 	/* Record last child; Make_HandleUse may add child nodes. */
   1525 	ln = tgn->children.last;
   1526 
   1527 	/* Apply the rule. */
   1528 	Make_HandleUse(gn, tgn);
   1529 
   1530 	/* Deal with wildcards and variables in any acquired sources. */
   1531 	ln = ln != NULL ? ln->next : NULL;
   1532 	while (ln != NULL) {
   1533 		GNodeListNode *nln = ln->next;
   1534 		ExpandChildren(ln, tgn);
   1535 		ln = nln;
   1536 	}
   1537 
   1538 	/*
   1539 	 * Keep track of another parent to which this node is transformed so
   1540 	 * the .IMPSRC variable can be set correctly for the parent.
   1541 	 */
   1542 	Lst_Append(&sgn->implicitParents, tgn);
   1543 
   1544 	return true;
   1545 }
   1546 
   1547 /*
   1548  * Member has a known suffix, so look for a transformation rule from
   1549  * it to a possible suffix of the archive.
   1550  *
   1551  * Rather than searching through the entire list, we just look at
   1552  * suffixes to which the member's suffix may be transformed.
   1553  */
   1554 static void
   1555 ExpandMember(GNode *gn, const char *eoarch, GNode *mem, Suffix *memSuff)
   1556 {
   1557 	GNodeListNode *ln;
   1558 	size_t nameLen = (size_t)(eoarch - gn->name);
   1559 
   1560 	/* Use first matching suffix... */
   1561 	for (ln = memSuff->parents.first; ln != NULL; ln = ln->next)
   1562 		if (Suffix_IsSuffix(ln->datum, nameLen, eoarch))
   1563 			break;
   1564 
   1565 	if (ln != NULL) {
   1566 		/* Got one -- apply it */
   1567 		Suffix *suff = ln->datum;
   1568 		if (!ApplyTransform(gn, mem, suff, memSuff)) {
   1569 			DEBUG2(SUFF, "\tNo transformation from %s -> %s\n",
   1570 			    memSuff->name, suff->name);
   1571 		}
   1572 	}
   1573 }
   1574 
   1575 static void FindDeps(GNode *, CandidateSearcher *);
   1576 
   1577 /*
   1578  * Locate dependencies for an OP_ARCHV node.
   1579  *
   1580  * Input:
   1581  *	gn		Node for which to locate dependencies
   1582  *
   1583  * Side Effects:
   1584  *	Same as Suff_FindDeps
   1585  */
   1586 static void
   1587 FindDepsArchive(GNode *gn, CandidateSearcher *cs)
   1588 {
   1589 	char *eoarch;		/* End of archive portion */
   1590 	char *eoname;		/* End of member portion */
   1591 	GNode *mem;		/* Node for member */
   1592 	Suffix *memSuff;
   1593 	const char *name;	/* Start of member's name */
   1594 
   1595 	/*
   1596 	 * The node is an archive(member) pair. so we must find a
   1597 	 * suffix for both of them.
   1598 	 */
   1599 	eoarch = strchr(gn->name, '(');
   1600 	eoname = strchr(eoarch, ')');
   1601 
   1602 	/*
   1603 	 * Caller guarantees the format `libname(member)', via
   1604 	 * Arch_ParseArchive.
   1605 	 */
   1606 	assert(eoarch != NULL);
   1607 	assert(eoname != NULL);
   1608 
   1609 	*eoname = '\0';		/* Nuke parentheses during suffix search */
   1610 	*eoarch = '\0';		/* So a suffix can be found */
   1611 
   1612 	name = eoarch + 1;
   1613 
   1614 	/*
   1615 	 * To simplify things, call Suff_FindDeps recursively on the member
   1616 	 * now, so we can simply compare the member's .PREFIX and .TARGET
   1617 	 * variables to locate its suffix. This allows us to figure out the
   1618 	 * suffix to use for the archive without having to do a quadratic
   1619 	 * search over the suffix list, backtracking for each one.
   1620 	 */
   1621 	mem = Targ_GetNode(name);
   1622 	FindDeps(mem, cs);
   1623 
   1624 	/* Create the link between the two nodes right off. */
   1625 	Lst_Append(&gn->children, mem);
   1626 	Lst_Append(&mem->parents, gn);
   1627 	gn->unmade++;
   1628 
   1629 	/* Copy in the variables from the member node to this one. */
   1630 	Var_Set(gn, PREFIX, GNode_VarPrefix(mem));
   1631 	Var_Set(gn, TARGET, GNode_VarTarget(mem));
   1632 
   1633 	memSuff = mem->suffix;
   1634 	if (memSuff == NULL) {	/* Didn't know what it was. */
   1635 		DEBUG0(SUFF, "using null suffix\n");
   1636 		memSuff = nullSuff;
   1637 	}
   1638 
   1639 
   1640 	/* Set the other two local variables required for this target. */
   1641 	Var_Set(gn, MEMBER, name);
   1642 	Var_Set(gn, ARCHIVE, gn->name);
   1643 	/* Set $@ for compatibility with other makes. */
   1644 	Var_Set(gn, TARGET, gn->name);
   1645 
   1646 	/*
   1647 	 * Now we've got the important local variables set, expand any sources
   1648 	 * that still contain variables or wildcards in their names.
   1649 	 */
   1650 	ExpandAllChildren(gn);
   1651 
   1652 	if (memSuff != NULL)
   1653 		ExpandMember(gn, eoarch, mem, memSuff);
   1654 
   1655 	/*
   1656 	 * Replace the opening and closing parens now we've no need of the
   1657 	 * separate pieces.
   1658 	 */
   1659 	*eoarch = '(';
   1660 	*eoname = ')';
   1661 
   1662 	/*
   1663 	 * Pretend gn appeared to the left of a dependency operator so the
   1664 	 * user needn't provide a transformation from the member to the
   1665 	 * archive.
   1666 	 */
   1667 	if (!GNode_IsTarget(gn))
   1668 		gn->type |= OP_DEPENDS;
   1669 
   1670 	/*
   1671 	 * Flag the member as such so we remember to look in the archive for
   1672 	 * its modification time. The OP_JOIN | OP_MADE is needed because
   1673 	 * this target should never get made.
   1674 	 */
   1675 	mem->type |= OP_MEMBER | OP_JOIN | OP_MADE;
   1676 }
   1677 
   1678 /*
   1679  * If the node is a library, it is the arch module's job to find it
   1680  * and set the TARGET variable accordingly. We merely provide the
   1681  * search path, assuming all libraries end in ".a" (if the suffix
   1682  * hasn't been defined, there's nothing we can do for it, so we just
   1683  * set the TARGET variable to the node's name in order to give it a
   1684  * value).
   1685  */
   1686 static void
   1687 FindDepsLib(GNode *gn)
   1688 {
   1689 	Suffix *suff = FindSuffixByName(LIBSUFF);
   1690 	if (suff != NULL) {
   1691 		Suffix_Reassign(&gn->suffix, suff);
   1692 		Arch_FindLib(gn, suff->searchPath);
   1693 	} else {
   1694 		Suffix_Unassign(&gn->suffix);
   1695 		Var_Set(gn, TARGET, gn->name);
   1696 	}
   1697 
   1698 	/*
   1699 	 * Because a library (-lfoo) target doesn't follow the standard
   1700 	 * filesystem conventions, we don't set the regular variables for
   1701 	 * the thing. .PREFIX is simply made empty.
   1702 	 */
   1703 	Var_Set(gn, PREFIX, "");
   1704 }
   1705 
   1706 static void
   1707 FindDepsRegularKnown(const char *name, size_t nameLen, GNode *gn,
   1708 		     CandidateList *srcs, CandidateList *targs)
   1709 {
   1710 	SuffixListNode *ln;
   1711 	Candidate *targ;
   1712 	char *pref;
   1713 
   1714 	for (ln = sufflist.first; ln != NULL; ln = ln->next) {
   1715 		Suffix *suff = ln->datum;
   1716 		if (!Suffix_IsSuffix(suff, nameLen, name + nameLen))
   1717 			continue;
   1718 
   1719 		pref = bmake_strldup(name, (size_t)(nameLen - suff->nameLen));
   1720 		targ = Candidate_New(bmake_strdup(gn->name), pref, suff, NULL,
   1721 		    gn);
   1722 
   1723 		CandidateList_AddCandidatesFor(srcs, targ);
   1724 
   1725 		/* Record the target so we can nuke it. */
   1726 		Lst_Append(targs, targ);
   1727 	}
   1728 }
   1729 
   1730 static void
   1731 FindDepsRegularUnknown(GNode *gn, const char *sopref,
   1732 		       CandidateList *srcs, CandidateList *targs)
   1733 {
   1734 	Candidate *targ;
   1735 
   1736 	if (!Lst_IsEmpty(targs) || nullSuff == NULL)
   1737 		return;
   1738 
   1739 	DEBUG1(SUFF, "\tNo known suffix on %s. Using .NULL suffix\n", gn->name);
   1740 
   1741 	targ = Candidate_New(bmake_strdup(gn->name), bmake_strdup(sopref),
   1742 	    nullSuff, NULL, gn);
   1743 
   1744 	/*
   1745 	 * Only use the default suffix rules if we don't have commands
   1746 	 * defined for this gnode; traditional make programs used to not
   1747 	 * define suffix rules if the gnode had children but we don't do
   1748 	 * this anymore.
   1749 	 */
   1750 	if (Lst_IsEmpty(&gn->commands))
   1751 		CandidateList_AddCandidatesFor(srcs, targ);
   1752 	else {
   1753 		DEBUG0(SUFF, "not ");
   1754 	}
   1755 
   1756 	DEBUG0(SUFF, "adding suffix rules\n");
   1757 
   1758 	Lst_Append(targs, targ);
   1759 }
   1760 
   1761 /*
   1762  * Deal with finding the thing on the default search path. We always do
   1763  * that, not only if the node is only a source (not on the lhs of a
   1764  * dependency operator or [XXX] it has neither children or commands) as
   1765  * the old pmake did.
   1766  */
   1767 static void
   1768 FindDepsRegularPath(GNode *gn, Candidate *targ)
   1769 {
   1770 	if (gn->type & (OP_PHONY | OP_NOPATH))
   1771 		return;
   1772 
   1773 	free(gn->path);
   1774 	gn->path = Dir_FindFile(gn->name,
   1775 	    (targ == NULL ? &dirSearchPath :
   1776 		targ->suff->searchPath));
   1777 	if (gn->path == NULL)
   1778 		return;
   1779 
   1780 	Var_Set(gn, TARGET, gn->path);
   1781 
   1782 	if (targ != NULL) {
   1783 		/*
   1784 		 * Suffix known for the thing -- trim the suffix off
   1785 		 * the path to form the proper .PREFIX variable.
   1786 		 */
   1787 		size_t savep = strlen(gn->path) - targ->suff->nameLen;
   1788 		char savec;
   1789 
   1790 		Suffix_Reassign(&gn->suffix, targ->suff);
   1791 
   1792 		savec = gn->path[savep];
   1793 		gn->path[savep] = '\0';
   1794 
   1795 		Var_Set(gn, PREFIX, str_basename(gn->path));
   1796 
   1797 		gn->path[savep] = savec;
   1798 	} else {
   1799 		/*
   1800 		 * The .PREFIX gets the full path if the target has no
   1801 		 * known suffix.
   1802 		 */
   1803 		Suffix_Unassign(&gn->suffix);
   1804 		Var_Set(gn, PREFIX, str_basename(gn->path));
   1805 	}
   1806 }
   1807 
   1808 /*
   1809  * Locate implicit dependencies for regular targets.
   1810  *
   1811  * Input:
   1812  *	gn		Node for which to find sources
   1813  *
   1814  * Side Effects:
   1815  *	Same as Suff_FindDeps
   1816  */
   1817 static void
   1818 FindDepsRegular(GNode *gn, CandidateSearcher *cs)
   1819 {
   1820 	/* List of sources at which to look */
   1821 	CandidateList srcs = LST_INIT;
   1822 	/*
   1823 	 * List of targets to which things can be transformed.
   1824 	 * They all have the same file, but different suff and prefix fields.
   1825 	 */
   1826 	CandidateList targs = LST_INIT;
   1827 	Candidate *bottom;	/* Start of found transformation path */
   1828 	Candidate *src;
   1829 	Candidate *targ;
   1830 
   1831 	const char *name = gn->name;
   1832 	size_t nameLen = strlen(name);
   1833 
   1834 #ifdef DEBUG_SRC
   1835 	DEBUG1(SUFF, "FindDepsRegular \"%s\"\n", gn->name);
   1836 #endif
   1837 
   1838 	/*
   1839 	 * We're caught in a catch-22 here. On the one hand, we want to use
   1840 	 * any transformation implied by the target's sources, but we can't
   1841 	 * examine the sources until we've expanded any variables/wildcards
   1842 	 * they may hold, and we can't do that until we've set up the
   1843 	 * target's local variables and we can't do that until we know what
   1844 	 * the proper suffix for the target is (in case there are two
   1845 	 * suffixes one of which is a suffix of the other) and we can't know
   1846 	 * that until we've found its implied source, which we may not want
   1847 	 * to use if there's an existing source that implies a different
   1848 	 * transformation.
   1849 	 *
   1850 	 * In an attempt to get around this, which may not work all the time,
   1851 	 * but should work most of the time, we look for implied sources
   1852 	 * first, checking transformations to all possible suffixes of the
   1853 	 * target, use what we find to set the target's local variables,
   1854 	 * expand the children, then look for any overriding transformations
   1855 	 * they imply. Should we find one, we discard the one we found before.
   1856 	 */
   1857 	bottom = NULL;
   1858 	targ = NULL;
   1859 
   1860 	if (!(gn->type & OP_PHONY)) {
   1861 
   1862 		FindDepsRegularKnown(name, nameLen, gn, &srcs, &targs);
   1863 
   1864 		/* Handle target of unknown suffix... */
   1865 		FindDepsRegularUnknown(gn, name, &srcs, &targs);
   1866 
   1867 		/*
   1868 		 * Using the list of possible sources built up from the target
   1869 		 * suffix(es), try and find an existing file/target that
   1870 		 * matches.
   1871 		 */
   1872 		bottom = FindThem(&srcs, cs);
   1873 
   1874 		if (bottom == NULL) {
   1875 			/*
   1876 			 * No known transformations -- use the first suffix
   1877 			 * found for setting the local variables.
   1878 			 */
   1879 			if (targs.first != NULL)
   1880 				targ = targs.first->datum;
   1881 			else
   1882 				targ = NULL;
   1883 		} else {
   1884 			/*
   1885 			 * Work up the transformation path to find the suffix
   1886 			 * of the target to which the transformation was made.
   1887 			 */
   1888 			for (targ = bottom;
   1889 			     targ->parent != NULL; targ = targ->parent)
   1890 				continue;
   1891 		}
   1892 	}
   1893 
   1894 	Var_Set(gn, TARGET, GNode_Path(gn));
   1895 	Var_Set(gn, PREFIX, targ != NULL ? targ->prefix : gn->name);
   1896 
   1897 	/*
   1898 	 * Now we've got the important local variables set, expand any sources
   1899 	 * that still contain variables or wildcards in their names.
   1900 	 */
   1901 	{
   1902 		GNodeListNode *ln, *nln;
   1903 		for (ln = gn->children.first; ln != NULL; ln = nln) {
   1904 			nln = ln->next;
   1905 			ExpandChildren(ln, gn);
   1906 		}
   1907 	}
   1908 
   1909 	if (targ == NULL) {
   1910 		DEBUG1(SUFF, "\tNo valid suffix on %s\n", gn->name);
   1911 
   1912 	sfnd_abort:
   1913 		FindDepsRegularPath(gn, targ);
   1914 		goto sfnd_return;
   1915 	}
   1916 
   1917 	/*
   1918 	 * If the suffix indicates that the target is a library, mark that in
   1919 	 * the node's type field.
   1920 	 */
   1921 	if (targ->suff->flags & SUFF_LIBRARY)
   1922 		gn->type |= OP_LIB;
   1923 
   1924 	/*
   1925 	 * Check for overriding transformation rule implied by sources
   1926 	 */
   1927 	if (!Lst_IsEmpty(&gn->children)) {
   1928 		src = FindCmds(targ, cs);
   1929 
   1930 		if (src != NULL) {
   1931 			/*
   1932 			 * Free up all the candidates in the transformation
   1933 			 * path, up to but not including the parent node.
   1934 			 */
   1935 			while (bottom != NULL && bottom->parent != NULL) {
   1936 				CandidateSearcher_AddIfNew(cs, bottom);
   1937 				bottom = bottom->parent;
   1938 			}
   1939 			bottom = src;
   1940 		}
   1941 	}
   1942 
   1943 	if (bottom == NULL) {
   1944 		/* No idea from where it can come -- return now. */
   1945 		goto sfnd_abort;
   1946 	}
   1947 
   1948 	/*
   1949 	 * We now have a list of candidates headed by 'bottom' and linked via
   1950 	 * their 'parent' pointers. What we do next is create links between
   1951 	 * source and target nodes (which may or may not have been created)
   1952 	 * and set the necessary local variables in each target.
   1953 	 *
   1954 	 * The commands for each target are set from the commands of the
   1955 	 * transformation rule used to get from the src suffix to the targ
   1956 	 * suffix. Note that this causes the commands list of the original
   1957 	 * node, gn, to be replaced with the commands of the final
   1958 	 * transformation rule.
   1959 	 */
   1960 	if (bottom->node == NULL)
   1961 		bottom->node = Targ_GetNode(bottom->file);
   1962 
   1963 	for (src = bottom; src->parent != NULL; src = src->parent) {
   1964 		targ = src->parent;
   1965 
   1966 		Suffix_Reassign(&src->node->suffix, src->suff);
   1967 
   1968 		if (targ->node == NULL)
   1969 			targ->node = Targ_GetNode(targ->file);
   1970 
   1971 		ApplyTransform(targ->node, src->node,
   1972 		    targ->suff, src->suff);
   1973 
   1974 		if (targ->node != gn) {
   1975 			/*
   1976 			 * Finish off the dependency-search process for any
   1977 			 * nodes between bottom and gn (no point in questing
   1978 			 * around the filesystem for their implicit source
   1979 			 * when it's already known). Note that the node
   1980 			 * can't have any sources that need expanding, since
   1981 			 * SuffFindThem will stop on an existing node, so all
   1982 			 * we need to do is set the standard variables.
   1983 			 */
   1984 			targ->node->type |= OP_DEPS_FOUND;
   1985 			Var_Set(targ->node, PREFIX, targ->prefix);
   1986 			Var_Set(targ->node, TARGET, targ->node->name);
   1987 		}
   1988 	}
   1989 
   1990 	Suffix_Reassign(&gn->suffix, src->suff);
   1991 
   1992 	/*
   1993 	 * Nuke the transformation path and the candidates left over in the
   1994 	 * two lists.
   1995 	 */
   1996 sfnd_return:
   1997 	if (bottom != NULL)
   1998 		CandidateSearcher_AddIfNew(cs, bottom);
   1999 
   2000 	while (RemoveCandidate(&srcs) || RemoveCandidate(&targs))
   2001 		continue;
   2002 
   2003 	CandidateSearcher_MoveAll(cs, &srcs);
   2004 	CandidateSearcher_MoveAll(cs, &targs);
   2005 }
   2006 
   2007 static void
   2008 CandidateSearcher_CleanUp(CandidateSearcher *cs)
   2009 {
   2010 	while (RemoveCandidate(&cs->list))
   2011 		continue;
   2012 	assert(Lst_IsEmpty(&cs->list));
   2013 }
   2014 
   2015 
   2016 /*
   2017  * Find implicit sources for the target.
   2018  *
   2019  * Nodes are added to the graph as children of the passed-in node. The nodes
   2020  * are marked to have their IMPSRC variable filled in. The PREFIX variable
   2021  * is set for the given node and all its implied children.
   2022  *
   2023  * The path found by this target is the shortest path in the transformation
   2024  * graph, which may pass through nonexistent targets, to an existing target.
   2025  * The search continues on all paths from the root suffix until a file is
   2026  * found. I.e. if there's a path .o -> .c -> .l -> .l,v from the root and the
   2027  * .l,v file exists but the .c and .l files don't, the search will branch out
   2028  * in all directions from .o and again from all the nodes on the next level
   2029  * until the .l,v node is encountered.
   2030  */
   2031 void
   2032 Suff_FindDeps(GNode *gn)
   2033 {
   2034 	CandidateSearcher cs;
   2035 
   2036 	CandidateSearcher_Init(&cs);
   2037 
   2038 	FindDeps(gn, &cs);
   2039 
   2040 	CandidateSearcher_CleanUp(&cs);
   2041 	CandidateSearcher_Done(&cs);
   2042 }
   2043 
   2044 static void
   2045 FindDeps(GNode *gn, CandidateSearcher *cs)
   2046 {
   2047 	if (gn->type & OP_DEPS_FOUND)
   2048 		return;
   2049 	gn->type |= OP_DEPS_FOUND;
   2050 
   2051 	/* Make sure we have these set, may get revised below. */
   2052 	Var_Set(gn, TARGET, GNode_Path(gn));
   2053 	Var_Set(gn, PREFIX, gn->name);
   2054 
   2055 	DEBUG1(SUFF, "SuffFindDeps \"%s\"\n", gn->name);
   2056 
   2057 	if (gn->type & OP_ARCHV)
   2058 		FindDepsArchive(gn, cs);
   2059 	else if (gn->type & OP_LIB)
   2060 		FindDepsLib(gn);
   2061 	else
   2062 		FindDepsRegular(gn, cs);
   2063 }
   2064 
   2065 /*
   2066  * Define which suffix is the null suffix.
   2067  *
   2068  * Need to handle the changing of the null suffix gracefully so the old
   2069  * transformation rules don't just go away.
   2070  *
   2071  * Input:
   2072  *	name		Name of null suffix
   2073  */
   2074 void
   2075 Suff_SetNull(const char *name)
   2076 {
   2077 	Suffix *suff = FindSuffixByName(name);
   2078 	if (suff == NULL) {
   2079 		Parse_Error(PARSE_WARNING,
   2080 		    "Desired null suffix %s not defined.",
   2081 		    name);
   2082 		return;
   2083 	}
   2084 
   2085 	if (nullSuff != NULL)
   2086 		nullSuff->flags &= ~(unsigned)SUFF_NULL;
   2087 	suff->flags |= SUFF_NULL;
   2088 	/* XXX: Here's where the transformation mangling would take place. */
   2089 	nullSuff = suff;
   2090 }
   2091 
   2092 /* Initialize the suffixes module. */
   2093 void
   2094 Suff_Init(void)
   2095 {
   2096 	/*
   2097 	 * Create null suffix for single-suffix rules (POSIX). The thing
   2098 	 * doesn't actually go on the suffix list or everyone will think
   2099 	 * that's its suffix.
   2100 	 */
   2101 	Suff_ClearSuffixes();
   2102 }
   2103 
   2104 
   2105 /* Clean up the suffixes module. */
   2106 void
   2107 Suff_End(void)
   2108 {
   2109 #ifdef CLEANUP
   2110 	Lst_DoneCall(&sufflist, SuffFree);
   2111 	Lst_DoneCall(&suffClean, SuffFree);
   2112 	if (nullSuff != NULL)
   2113 		SuffFree(nullSuff);
   2114 	Lst_Done(&transforms);
   2115 #endif
   2116 }
   2117 
   2118 
   2119 static void
   2120 PrintSuffNames(const char *prefix, SuffixList *suffs)
   2121 {
   2122 	SuffixListNode *ln;
   2123 
   2124 	debug_printf("#\t%s: ", prefix);
   2125 	for (ln = suffs->first; ln != NULL; ln = ln->next) {
   2126 		Suffix *suff = ln->datum;
   2127 		debug_printf("%s ", suff->name);
   2128 	}
   2129 	debug_printf("\n");
   2130 }
   2131 
   2132 static void
   2133 Suffix_Print(Suffix *suff)
   2134 {
   2135 	debug_printf("# \"%s\" (num %d, ref %d)",
   2136 	    suff->name, suff->sNum, suff->refCount);
   2137 	if (suff->flags != 0) {
   2138 		char flags_buf[SuffixFlags_ToStringSize];
   2139 
   2140 		debug_printf(" (%s)",
   2141 		    SuffixFlags_ToString(flags_buf, suff->flags));
   2142 	}
   2143 	debug_printf("\n");
   2144 
   2145 	PrintSuffNames("To", &suff->parents);
   2146 	PrintSuffNames("From", &suff->children);
   2147 
   2148 	debug_printf("#\tSearch Path: ");
   2149 	SearchPath_Print(suff->searchPath);
   2150 	debug_printf("\n");
   2151 }
   2152 
   2153 static void
   2154 PrintTransformation(GNode *t)
   2155 {
   2156 	debug_printf("%-16s:", t->name);
   2157 	Targ_PrintType(t->type);
   2158 	debug_printf("\n");
   2159 	Targ_PrintCmds(t);
   2160 	debug_printf("\n");
   2161 }
   2162 
   2163 void
   2164 Suff_PrintAll(void)
   2165 {
   2166 	debug_printf("#*** Suffixes:\n");
   2167 	{
   2168 		SuffixListNode *ln;
   2169 		for (ln = sufflist.first; ln != NULL; ln = ln->next)
   2170 			Suffix_Print(ln->datum);
   2171 	}
   2172 
   2173 	debug_printf("#*** Transformations:\n");
   2174 	{
   2175 		GNodeListNode *ln;
   2176 		for (ln = transforms.first; ln != NULL; ln = ln->next)
   2177 			PrintTransformation(ln->datum);
   2178 	}
   2179 }
   2180