When a Node has been built, don't walk the whole tree back to delete the parents...
[scons.git] / src / engine / SCons / Node / __init__.py
1 """SCons.Node
2
3 The Node package for the SCons software construction utility.
4
5 This is, in many ways, the heart of SCons.
6
7 A Node is where we encapsulate all of the dependency information about
8 any thing that SCons can build, or about any thing which SCons can use
9 to build some other thing.  The canonical "thing," of course, is a file,
10 but a Node can also represent something remote (like a web page) or
11 something completely abstract (like an Alias).
12
13 Each specific type of "thing" is specifically represented by a subclass
14 of the Node base class:  Node.FS.File for files, Node.Alias for aliases,
15 etc.  Dependency information is kept here in the base class, and
16 information specific to files/aliases/etc. is in the subclass.  The
17 goal, if we've done this correctly, is that any type of "thing" should
18 be able to depend on any other type of "thing."
19
20 """
21
22 #
23 # __COPYRIGHT__
24 #
25 # Permission is hereby granted, free of charge, to any person obtaining
26 # a copy of this software and associated documentation files (the
27 # "Software"), to deal in the Software without restriction, including
28 # without limitation the rights to use, copy, modify, merge, publish,
29 # distribute, sublicense, and/or sell copies of the Software, and to
30 # permit persons to whom the Software is furnished to do so, subject to
31 # the following conditions:
32 #
33 # The above copyright notice and this permission notice shall be included
34 # in all copies or substantial portions of the Software.
35 #
36 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
37 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
38 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
39 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
40 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
41 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
42 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
43 #
44
45 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
46
47
48
49 import copy
50 import string
51
52 from SCons.Debug import logInstanceCreation
53 import SCons.SConsign
54 import SCons.Util
55
56 # Node states
57 #
58 # These are in "priority" order, so that the maximum value for any
59 # child/dependency of a node represents the state of that node if
60 # it has no builder of its own.  The canonical example is a file
61 # system directory, which is only up to date if all of its children
62 # were up to date.
63 pending = 1
64 executing = 2
65 up_to_date = 3
66 executed = 4
67 failed = 5
68 stack = 6 # nodes that are in the current Taskmaster execution stack
69
70 # controls whether implicit depedencies are cached:
71 implicit_cache = 0
72
73 # controls whether implicit dep changes are ignored:
74 implicit_deps_unchanged = 0
75
76 # controls whether the cached implicit deps are ignored:
77 implicit_deps_changed = 0
78
79 # A variable that can be set to an interface-specific function be called
80 # to annotate a Node with information about its creation.
81 def do_nothing(node): pass
82
83 Annotate = do_nothing
84
85 class BuildInfo:
86     def __cmp__(self, other):
87         return cmp(self.__dict__, other.__dict__)
88
89 class Node:
90     """The base Node class, for entities that we know how to
91     build, or use to build other Nodes.
92     """
93
94     class Attrs:
95         pass
96
97     def __init__(self):
98         if __debug__: logInstanceCreation(self, 'Node')
99         # Note that we no longer explicitly initialize a self.builder
100         # attribute to None here.  That's because the self.builder
101         # attribute may be created on-the-fly later by a subclass (the
102         # canonical example being a builder to fetch a file from a
103         # source code system like CVS or Subversion).
104
105         # Each list of children that we maintain is accompanied by a
106         # dictionary used to look up quickly whether a node is already
107         # present in the list.  Empirical tests showed that it was
108         # fastest to maintain them as side-by-side Node attributes in
109         # this way, instead of wrapping up each list+dictionary pair in
110         # a class.  (Of course, we could always still do that in the
111         # future if we had a good reason to...).
112         self.sources = []       # source files used to build node
113         self.sources_dict = {}
114         self.depends = []       # explicit dependencies (from Depends)
115         self.depends_dict = {}
116         self.ignore = []        # dependencies to ignore
117         self.ignore_dict = {}
118         self.implicit = None    # implicit (scanned) dependencies (None means not scanned yet)
119         self.parents = {}
120         self.wkids = None       # Kids yet to walk, when it's an array
121         self.target_scanner = None      # explicit scanner from this node's Builder
122         self.source_scanner = None      # source scanner
123
124         self.env = None
125         self.state = None
126         self.precious = None
127         self.always_build = None
128         self.found_includes = {}
129         self.includes = None
130         self.overrides = {}     # construction variable overrides for building this node
131         self.attributes = self.Attrs() # Generic place to stick information about the Node.
132         self.side_effect = 0 # true iff this node is a side effect
133         self.side_effects = [] # the side effects of building this target
134         self.pre_actions = []
135         self.post_actions = []
136         self.linked = 0 # is this node linked to the build directory? 
137
138         # Let the interface in which the build engine is embedded
139         # annotate this Node with its own info (like a description of
140         # what line in what file created the node, for example).
141         Annotate(self)
142
143     def get_suffix(self):
144         return ''
145
146     def generate_build_dict(self):
147         """Return an appropriate dictionary of values for building
148         this Node."""
149         return {}
150
151     def get_build_env(self):
152         """Fetch the appropriate Environment to build this node."""
153         executor = self.get_executor()
154         return executor.get_build_env()
155
156     def set_executor(self, executor):
157         """Set the action executor for this node."""
158         self.executor = executor
159
160     def get_executor(self, create=1):
161         """Fetch the action executor for this node.  Create one if
162         there isn't already one, and requested to do so."""
163         try:
164             executor = self.executor
165         except AttributeError:
166             if not create:
167                 raise
168             import SCons.Executor
169             executor = SCons.Executor.Executor(self.builder.action,
170                                                self.builder.env,
171                                                [self.builder.overrides],
172                                                [self],
173                                                self.sources)
174             self.executor = executor
175         return executor
176
177     def retrieve_from_cache(self):
178         """Try to retrieve the node's content from a cache
179
180         This method is called from multiple threads in a parallel build,
181         so only do thread safe stuff here. Do thread unsafe stuff in
182         built().
183
184         Returns true iff the node was successfully retrieved.
185         """
186         return 0
187         
188     def build(self, **kw):
189         """Actually build the node.
190
191         This method is called from multiple threads in a parallel build,
192         so only do thread safe stuff here. Do thread unsafe stuff in
193         built().
194         """
195         if not self.has_builder():
196             return
197         def errfunc(stat, node=self):
198             raise SCons.Errors.BuildError(node=node, errstr="Error %d" % stat)
199         executor = self.get_executor()
200         apply(executor, (self, errfunc), kw)
201
202     def built(self):
203         """Called just after this node is sucessfully built."""
204         try:
205             new_binfo = self.binfo
206         except AttributeError:
207             pass
208         else:
209             self.store_info(new_binfo)
210
211         # Clear out the implicit dependency caches:
212         # XXX this really should somehow be made more general and put
213         #     under the control of the scanners.
214         if self.source_scanner:
215             self.found_includes = {}
216             self.includes = None
217             for parent in self.get_parents():
218                 parent.implicit = None
219                 parent.del_binfo()
220
221         # The content just changed, delete any cached info
222         # so it will get recalculated.
223         self.del_cinfo()
224
225     def postprocess(self):
226         """Clean up anything we don't need to hang onto after we've
227         been built."""
228         try:
229             executor = self.get_executor(create=None)
230         except AttributeError:
231             pass
232         else:
233             executor.cleanup()
234
235     def clear(self):
236         """Completely clear a Node of all its cached state (so that it
237         can be re-evaluated by interfaces that do continuous integration
238         builds).
239         """
240         self.set_state(None)
241         self.del_binfo()
242         self.del_cinfo()
243         try:
244             delattr(self, '_calculated_sig')
245         except AttributeError:
246             pass
247         self.includes = None
248         self.found_includes = {}
249         self.implicit = None
250
251     def visited(self):
252         """Called just after this node has been visited
253         without requiring a build.."""
254         pass
255
256     def depends_on(self, nodes):
257         """Does this node depend on any of 'nodes'?"""
258         for node in nodes:
259             if node in self.children():
260                 return 1
261
262         return 0
263
264     def builder_set(self, builder):
265         self.builder = builder
266
267     def has_builder(self):
268         """Return whether this Node has a builder or not.
269
270         In Boolean tests, this turns out to be a *lot* more efficient
271         than simply examining the builder attribute directly ("if
272         node.builder: ..."). When the builder attribute is examined
273         directly, it ends up calling __getattr__ for both the __len__
274         and __nonzero__ attributes on instances of our Builder Proxy
275         class(es), generating a bazillion extra calls and slowing
276         things down immensely.
277         """
278         try:
279             b = self.builder
280         except AttributeError:
281             # There was no explicit builder for this Node, so initialize
282             # the self.builder attribute to None now.
283             self.builder = None
284             b = self.builder
285         return not b is None
286
287     def is_derived(self):
288         """
289         Returns true iff this node is derived (i.e. built).
290
291         This should return true only for nodes whose path should be in
292         the build directory when duplicate=0 and should contribute their build
293         signatures when they are used as source files to other derived files. For
294         example: source with source builders are not derived in this sense,
295         and hence should not return true.
296         """
297         return self.has_builder() or self.side_effect
298
299     def is_pseudo_derived(self):
300         """
301         Returns true iff this node is built, but should use a source path
302         when duplicate=0 and should contribute a content signature (i.e.
303         source signature) when used as a source for other derived files.
304         """
305         return 0
306
307     def alter_targets(self):
308         """Return a list of alternate targets for this Node.
309         """
310         return [], None
311
312     def get_found_includes(self, env, scanner, target):
313         """Return the scanned include lines (implicit dependencies)
314         found in this node.
315
316         The default is no implicit dependencies.  We expect this method
317         to be overridden by any subclass that can be scanned for
318         implicit dependencies.
319         """
320         return []
321
322     def get_implicit_deps(self, env, scanner, target):
323         """Return a list of implicit dependencies for this node.
324
325         This method exists to handle recursive invocation of the scanner
326         on the implicit dependencies returned by the scanner, if the
327         scanner's recursive flag says that we should.
328         """
329         if not scanner:
330             return []
331
332         try:
333             recurse = scanner.recursive
334         except AttributeError:
335             recurse = None
336
337         nodes = [self]
338         seen = {}
339         seen[self] = 1
340         deps = []
341         while nodes:
342            n = nodes.pop(0)
343            d = filter(lambda x, seen=seen: not seen.has_key(x),
344                       n.get_found_includes(env, scanner, target))
345            if d:
346                deps.extend(d)
347                for n in d:
348                    seen[n] = 1
349                if recurse:
350                    nodes.extend(d)
351
352         return deps
353
354     # cache used to make implicit_factory fast.
355     implicit_factory_cache = {}
356     
357     def implicit_factory(self, path):
358         """
359         Turn a cache implicit dependency path into a node.
360         This is called so many times that doing caching
361         here is a significant perforamnce boost.
362         """
363         try:
364             return self.implicit_factory_cache[path]
365         except KeyError:
366             n = self.builder.source_factory(path)
367             self.implicit_factory_cache[path] = n
368             return n
369
370     def scan(self):
371         """Scan this node's dependents for implicit dependencies."""
372         # Don't bother scanning non-derived files, because we don't
373         # care what their dependencies are.
374         # Don't scan again, if we already have scanned.
375         if not self.implicit is None:
376             return
377         self.implicit = []
378         self.implicit_dict = {}
379         self._children_reset()
380         if not self.has_builder():
381             return
382
383         build_env = self.get_build_env()
384
385         # XXX Here's where we implement --implicit-cache.  This doesn't
386         # do anything right now, but we're probably going to re-implement
387         # as a way to cache #include lines from source files, so I want
388         # to keep this code around for now.
389         #
390         #if implicit_cache and not implicit_deps_changed:
391         #    implicit = self.get_stored_implicit()
392         #    if implicit is not None:
393         #        implicit = map(self.implicit_factory, implicit)
394         #        self._add_child(self.implicit, self.implicit_dict, implicit)
395         #        calc = build_env.get_calculator()
396         #        if implicit_deps_unchanged or calc.current(self, calc.bsig(self)):
397         #            return
398         #        else:
399         #            # one of this node's sources has changed, so
400         #            # we need to recalculate the implicit deps,
401         #            # and the bsig:
402         #            self.implicit = []
403         #            self.implicit_dict = {}
404         #            self._children_reset()
405         #            self.del_binfo()
406
407         for child in self.children(scan=0):
408             scanner = child.source_scanner
409             if scanner:
410                 self._add_child(self.implicit,
411                                 self.implicit_dict,
412                                 child.get_implicit_deps(build_env,
413                                                         scanner,
414                                                         self))
415
416         # scan this node itself for implicit dependencies
417         self._add_child(self.implicit,
418                         self.implicit_dict,
419                         self.get_implicit_deps(build_env,
420                                                self.target_scanner,
421                                                self))
422
423         # XXX See note above re: --implicit-cache.
424         #if implicit_cache:
425         #    self.store_implicit()
426
427     def scanner_key(self):
428         return None
429
430     def env_set(self, env, safe=0):
431         if safe and self.env:
432             return
433         self.env = env
434
435     def calculator(self):
436         import SCons.Defaults
437         
438         env = self.env or SCons.Defaults.DefaultEnvironment()
439         return env.get_calculator()
440
441     def calc_signature(self, calc):
442         """
443         Select and calculate the appropriate build signature for a node.
444
445         self - the node
446         calc - the signature calculation module
447         returns - the signature
448         """
449         try:
450             return self._calculated_sig
451         except AttributeError:
452             if self.is_derived():
453                 import SCons.Defaults
454                 
455                 env = self.env or SCons.Defaults.DefaultEnvironment()
456                 if env.use_build_signature():
457                     sig = self.calc_bsig(calc)
458                 else:
459                     sig = self.calc_csig(calc)
460             elif not self.rexists():
461                 sig = None
462             else:
463                 sig = self.calc_csig(calc)
464             self._calculated_sig = sig
465             return sig
466
467     def new_binfo(self):
468         return BuildInfo()
469
470     def del_binfo(self):
471         """Delete the bsig from this node."""
472         try:
473             delattr(self, 'binfo')
474         except AttributeError:
475             pass
476
477     def calc_bsig(self, calc):
478         try:
479             return self.binfo.bsig
480         except AttributeError:
481             self.binfo = self.gen_binfo(calc)
482             return self.binfo.bsig
483
484     def gen_binfo(self, calc):
485         """
486         Generate a node's build signature, the digested signatures
487         of its dependency files and build information.
488
489         node - the node whose sources will be collected
490         cache - alternate node to use for the signature cache
491         returns - the build signature
492
493         This no longer handles the recursive descent of the
494         node's children's signatures.  We expect that they're
495         already built and updated by someone else, if that's
496         what's wanted.
497         """
498
499         binfo = self.new_binfo()
500
501         children = self.children()
502
503         sigs = map(lambda n, c=calc: n.calc_signature(c), children)
504
505         binfo.bkids = map(str, children)
506         binfo.bkidsigs = sigs[:]
507
508         if self.has_builder():
509             executor = self.get_executor()
510             binfo.bact = str(executor)
511             binfo.bactsig = calc.module.signature(executor)
512             sigs.append(binfo.bactsig)
513
514         binfo.bsig = calc.module.collect(filter(None, sigs))
515
516         return binfo
517
518     def del_cinfo(self):
519         try:
520             del self.binfo.csig
521         except AttributeError:
522             pass
523
524     def calc_csig(self, calc):
525         try:
526             self.binfo
527         except:
528             self.binfo = self.new_binfo()
529         try:
530             return self.binfo.csig
531         except AttributeError:
532             self.binfo.csig = calc.module.signature(self)
533             self.store_info(self.binfo)
534             return self.binfo.csig
535
536     def store_info(self, obj):
537         """Make the build signature permanent (that is, store it in the
538         .sconsign file or equivalent)."""
539         pass
540
541     def get_stored_info(self):
542         return None
543
544     def get_stored_implicit(self):
545         """Fetch the stored implicit dependencies"""
546         return None
547
548     def set_precious(self, precious = 1):
549         """Set the Node's precious value."""
550         self.precious = precious
551
552     def set_always_build(self, always_build = 1):
553         """Set the Node's always_build value."""
554         self.always_build = always_build
555
556     def exists(self):
557         """Does this node exists?"""
558         # All node exist by default:
559         return 1
560     
561     def rexists(self):
562         """Does this node exist locally or in a repositiory?"""
563         # There are no repositories by default:
564         return self.exists()
565     
566     def prepare(self):
567         """Prepare for this Node to be created.
568         The default implemenation checks that all children either exist
569         or are derived.
570         """
571         def missing(node):
572             return not node.is_derived() and \
573                    not node.is_pseudo_derived() and \
574                    not node.linked and \
575                    not node.rexists()
576         missing_sources = filter(missing, self.children())
577         if missing_sources:
578             desc = "Source `%s' not found, needed by target `%s'." % (missing_sources[0], self)
579             raise SCons.Errors.StopError, desc
580
581     def remove(self):
582         """Remove this Node:  no-op by default."""
583         return None
584
585     def add_dependency(self, depend):
586         """Adds dependencies."""
587         try:
588             self._add_child(self.depends, self.depends_dict, depend)
589         except TypeError, e:
590             e = e.args[0]
591             if SCons.Util.is_List(e):
592                 s = map(str, e)
593             else:
594                 s = str(e)
595             raise SCons.Errors.UserError("attempted to add a non-Node dependency to %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
596
597     def add_ignore(self, depend):
598         """Adds dependencies to ignore."""
599         try:
600             self._add_child(self.ignore, self.ignore_dict, depend)
601         except TypeError, e:
602             e = e.args[0]
603             if SCons.Util.is_List(e):
604                 s = map(str, e)
605             else:
606                 s = str(e)
607             raise SCons.Errors.UserError("attempted to ignore a non-Node dependency of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
608
609     def add_source(self, source):
610         """Adds sources."""
611         try:
612             self._add_child(self.sources, self.sources_dict, source)
613         except TypeError, e:
614             e = e.args[0]
615             if SCons.Util.is_List(e):
616                 s = map(str, e)
617             else:
618                 s = str(e)
619             raise SCons.Errors.UserError("attempted to add a non-Node as source of %s:\n\t%s is a %s, not a Node" % (str(self), s, type(e)))
620
621     def _add_child(self, collection, dict, child):
622         """Adds 'child' to 'collection', first checking 'dict' to see
623         if it's already present."""
624         if type(child) is not type([]):
625             child = [child]
626         for c in child:
627             if not isinstance(c, Node):
628                 raise TypeError, c
629         added = None
630         for c in child:
631             if not dict.has_key(c):
632                 collection.append(c)
633                 dict[c] = 1
634                 added = 1
635             c.parents[self] = 1
636         if added:
637             self._children_reset()
638
639     def add_wkid(self, wkid):
640         """Add a node to the list of kids waiting to be evaluated"""
641         if self.wkids != None:
642             self.wkids.append(wkid)
643
644     def _children_reset(self):
645         try:
646             delattr(self, '_children')
647         except AttributeError:
648             pass
649
650     def children(self, scan=1):
651         """Return a list of the node's direct children, minus those
652         that are ignored by this node."""
653         if scan:
654             self.scan()
655         try:
656             return self._children
657         except AttributeError:
658             c = filter(lambda x, i=self.ignore: x not in i,
659                               self.all_children(scan=0))
660             self._children = c
661             return c
662
663     def all_children(self, scan=1):
664         """Return a list of all the node's direct children."""
665         # The return list may contain duplicate Nodes, especially in
666         # source trees where there are a lot of repeated #includes
667         # of a tangle of .h files.  Profiling shows, however, that
668         # eliminating the duplicates with a brute-force approach that
669         # preserves the order (that is, something like:
670         #
671         #       u = []
672         #       for n in list:
673         #           if n not in u:
674         #               u.append(n)"
675         #
676         # takes more cycles than just letting the underlying methods
677         # hand back cached values if a Node's information is requested
678         # multiple times.  (Other methods of removing duplicates, like
679         # using dictionary keys, lose the order, and the only ordered
680         # dictionary patterns I found all ended up using "not in"
681         # internally anyway...)
682         if scan:
683             self.scan()
684         if self.implicit is None:
685             return self.sources + self.depends
686         else:
687             return self.sources + self.depends + self.implicit
688
689     def get_parents(self):
690         return self.parents.keys()
691
692     def set_state(self, state):
693         self.state = state
694
695     def get_state(self):
696         return self.state
697
698     def current(self, calc=None):
699         """Default check for whether the Node is current: unknown Node
700         subtypes are always out of date, so they will always get built."""
701         return None
702
703     def children_are_up_to_date(self, calc):
704         """Alternate check for whether the Node is current:  If all of
705         our children were up-to-date, then this Node was up-to-date, too.
706
707         The SCons.Node.Alias and SCons.Node.Python.Value subclasses
708         rebind their current() method to this method."""
709         # Allow the children to calculate their signatures.
710         self.binfo = self.gen_binfo(calc)
711         state = 0
712         for kid in self.children(None):
713             s = kid.get_state()
714             if s and (not state or s > state):
715                 state = s
716         return (state == 0 or state == SCons.Node.up_to_date)
717
718     def is_literal(self):
719         """Always pass the string representation of a Node to
720         the command interpreter literally."""
721         return 1
722
723     def add_pre_action(self, act):
724         """Adds an Action performed on this Node only before
725         building it."""
726         self.pre_actions.append(act)
727
728     def add_post_action(self, act):
729         """Adds and Action performed on this Node only after
730         building it."""
731         self.post_actions.append(act)
732
733     def render_include_tree(self):
734         """
735         Return a text representation, suitable for displaying to the
736         user, of the include tree for the sources of this node.
737         """
738         if self.is_derived() and self.env:
739             env = self.get_build_env()
740             for s in self.sources:
741                 def f(node, env=env, scanner=s.source_scanner, target=self):
742                     return node.get_found_includes(env, scanner, target)
743                 return SCons.Util.render_tree(s, f, 1)
744         else:
745             return None
746
747     def get_abspath(self):
748         """
749         Return an absolute path to the Node.  This will return simply
750         str(Node) by default, but for Node types that have a concept of
751         relative path, this might return something different.
752         """
753         return str(self)
754
755     def for_signature(self):
756         """
757         Return a string representation of the Node that will always
758         be the same for this particular Node, no matter what.  This
759         is by contrast to the __str__() method, which might, for
760         instance, return a relative path for a file Node.  The purpose
761         of this method is to generate a value to be used in signature
762         calculation for the command line used to build a target, and
763         we use this method instead of str() to avoid unnecessary
764         rebuilds.  This method does not need to return something that
765         would actually work in a command line; it can return any kind of
766         nonsense, so long as it does not change.
767         """
768         return str(self)
769
770     def get_string(self, for_signature):
771         """This is a convenience function designed primarily to be
772         used in command generators (i.e., CommandGeneratorActions or
773         Environment variables that are callable), which are called
774         with a for_signature argument that is nonzero if the command
775         generator is being called to generate a signature for the
776         command line, which determines if we should rebuild or not.
777
778         Such command generators shoud use this method in preference
779         to str(Node) when converting a Node to a string, passing
780         in the for_signature parameter, such that we will call
781         Node.for_signature() or str(Node) properly, depending on whether
782         we are calculating a signature or actually constructing a
783         command line."""
784         if for_signature:
785             return self.for_signature()
786         return str(self)
787
788     def get_subst_proxy(self):
789         """
790         This method is expected to return an object that will function
791         exactly like this Node, except that it implements any additional
792         special features that we would like to be in effect for
793         Environment variable substitution.  The principle use is that
794         some Nodes would like to implement a __getattr__() method,
795         but putting that in the Node type itself has a tendency to kill
796         performance.  We instead put it in a proxy and return it from
797         this method.  It is legal for this method to return self
798         if no new functionality is needed for Environment substitution.
799         """
800         return self
801
802     def explain(self):
803         if not self.exists():
804             return "building `%s' because it doesn't exist\n" % self
805
806         old = self.get_stored_info()
807         if old is None:
808             return None
809
810         def dictify(kids, sigs):
811             result = {}
812             for k, s in zip(kids, sigs):
813                 result[k] = s
814             return result
815
816         osig = dictify(old.bkids, old.bkidsigs)
817
818         newkids = map(str, self.binfo.bkids)
819         nsig = dictify(newkids, self.binfo.bkidsigs)
820
821         lines = map(lambda x: "`%s' is no longer a dependency\n" % x,
822                     filter(lambda x, nk=newkids: not x in nk, old.bkids))
823
824         for k in newkids:
825             if not k in old.bkids:
826                 lines.append("`%s' is a new dependency\n" % k)
827             elif osig[k] != nsig[k]:
828                 lines.append("`%s' changed\n" % k)
829
830         if len(lines) == 0:
831             newact, newactsig = self.binfo.bact, self.binfo.bactsig
832             if old.bact != newact:
833                 lines.append("the build action changed:\n" +
834                              "%sold: %s\n" % (' '*15, old.bact) +
835                              "%snew: %s\n" % (' '*15, newact))
836
837         if len(lines) == 0:
838             lines.append("the dependency order changed:\n" +
839                          "%sold: %s\n" % (' '*15, old.bkids) +
840                          "%snew: %s\n" % (' '*15, newkids))
841
842         preamble = "rebuilding `%s' because" % self
843         if len(lines) == 1:
844             return "%s %s"  % (preamble, lines[0])
845         else:
846             lines = ["%s:\n" % preamble] + lines
847             return string.join(lines, ' '*11)
848
849 def get_children(node, parent): return node.children()
850 def ignore_cycle(node, stack): pass
851 def do_nothing(node, parent): pass
852
853 class Walker:
854     """An iterator for walking a Node tree.
855
856     This is depth-first, children are visited before the parent.
857     The Walker object can be initialized with any node, and
858     returns the next node on the descent with each next() call.
859     'kids_func' is an optional function that will be called to
860     get the children of a node instead of calling 'children'.
861     'cycle_func' is an optional function that will be called
862     when a cycle is detected.
863
864     This class does not get caught in node cycles caused, for example,
865     by C header file include loops.
866     """
867     def __init__(self, node, kids_func=get_children,
868                              cycle_func=ignore_cycle,
869                              eval_func=do_nothing):
870         self.kids_func = kids_func
871         self.cycle_func = cycle_func
872         self.eval_func = eval_func
873         node.wkids = copy.copy(kids_func(node, None))
874         self.stack = [node]
875         self.history = {} # used to efficiently detect and avoid cycles
876         self.history[node] = None
877
878     def next(self):
879         """Return the next node for this walk of the tree.
880
881         This function is intentionally iterative, not recursive,
882         to sidestep any issues of stack size limitations.
883         """
884
885         while self.stack:
886             if self.stack[-1].wkids:
887                 node = self.stack[-1].wkids.pop(0)
888                 if not self.stack[-1].wkids:
889                     self.stack[-1].wkids = None
890                 if self.history.has_key(node):
891                     self.cycle_func(node, self.stack)
892                 else:
893                     node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
894                     self.stack.append(node)
895                     self.history[node] = None
896             else:
897                 node = self.stack.pop()
898                 del self.history[node]
899                 if node:
900                     if self.stack:
901                         parent = self.stack[-1]
902                     else:
903                         parent = None
904                     self.eval_func(node, parent)
905                 return node
906
907     def is_done(self):
908         return not self.stack
909
910
911 arg2nodes_lookups = []