Clear out dependent-child caches when a node is rebuilt. (Kevin Quick)
[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.waiting_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
123         self.backup_source_scanner = None
124
125         self.env = None
126         self.state = None
127         self.precious = None
128         self.always_build = None
129         self.found_includes = {}
130         self.includes = None
131         self.overrides = {}     # construction variable overrides for building this node
132         self.attributes = self.Attrs() # Generic place to stick information about the Node.
133         self.side_effect = 0 # true iff this node is a side effect
134         self.side_effects = [] # the side effects of building this target
135         self.pre_actions = []
136         self.post_actions = []
137         self.linked = 0 # is this node linked to the build directory? 
138
139         # Let the interface in which the build engine is embedded
140         # annotate this Node with its own info (like a description of
141         # what line in what file created the node, for example).
142         Annotate(self)
143
144     def get_suffix(self):
145         return ''
146
147     def generate_build_dict(self):
148         """Return an appropriate dictionary of values for building
149         this Node."""
150         return {}
151
152     def get_build_env(self):
153         """Fetch the appropriate Environment to build this node."""
154         executor = self.get_executor()
155         return executor.get_build_env()
156
157     def set_executor(self, executor):
158         """Set the action executor for this node."""
159         self.executor = executor
160
161     def get_executor(self, create=1):
162         """Fetch the action executor for this node.  Create one if
163         there isn't already one, and requested to do so."""
164         try:
165             executor = self.executor
166         except AttributeError:
167             if not create:
168                 raise
169             import SCons.Executor
170             executor = SCons.Executor.Executor(self.builder.action,
171                                                self.builder.env,
172                                                [self.builder.overrides],
173                                                [self],
174                                                self.sources)
175             self.executor = executor
176         return executor
177
178     def retrieve_from_cache(self):
179         """Try to retrieve the node's content from a cache
180
181         This method is called from multiple threads in a parallel build,
182         so only do thread safe stuff here. Do thread unsafe stuff in
183         built().
184
185         Returns true iff the node was successfully retrieved.
186         """
187         return 0
188         
189     def build(self, **kw):
190         """Actually build the node.
191
192         This method is called from multiple threads in a parallel build,
193         so only do thread safe stuff here. Do thread unsafe stuff in
194         built().
195         """
196         if not self.has_builder():
197             return
198         def errfunc(stat, node=self):
199             raise SCons.Errors.BuildError(node=node, errstr="Error %d" % stat)
200         executor = self.get_executor()
201         apply(executor, (self, errfunc), kw)
202
203     def built(self):
204         """Called just after this node is sucessfully built."""
205
206         # Clear the implicit dependency caches of any Nodes
207         # waiting for this Node to be built.
208         for parent in self.waiting_parents:
209             parent.implicit = None
210             parent.del_binfo()
211         
212         try:
213             new_binfo = self.binfo
214         except AttributeError:
215             # Node arrived here without build info; apparently it
216             # doesn't need it, so don't bother calculating or storing
217             # it.
218             new_binfo = None
219
220         # Reset this Node's cached state since it was just built and
221         # various state has changed.
222         save_state = self.get_state()
223         self.clear()
224         self.set_state(save_state)
225
226         # Had build info, so it should be stored in the signature
227         # cache.  However, if the build info included a content
228         # signature then it should be recalculated before being
229         # stored.
230         
231         if new_binfo:
232             if hasattr(new_binfo, 'csig'):
233                 new_binfo = self.gen_binfo()  # sets self.binfo
234             else:
235                 self.binfo = new_binfo
236             self.store_info(new_binfo)
237
238     def add_to_waiting_parents(self, node):
239         self.waiting_parents.append(node)
240
241     def call_for_all_waiting_parents(self, func):
242         func(self)
243         for parent in self.waiting_parents:
244             parent.call_for_all_waiting_parents(func)
245
246     def postprocess(self):
247         """Clean up anything we don't need to hang onto after we've
248         been built."""
249         try:
250             executor = self.get_executor(create=None)
251         except AttributeError:
252             pass
253         else:
254             executor.cleanup()
255
256     def clear(self):
257         """Completely clear a Node of all its cached state (so that it
258         can be re-evaluated by interfaces that do continuous integration
259         builds).
260         """
261         self.set_state(None)
262         self.del_binfo()
263         self.del_cinfo()
264         try:
265             delattr(self, '_calculated_sig')
266         except AttributeError:
267             pass
268         self.includes = None
269         self.found_includes = {}
270         self.implicit = None
271
272         self.waiting_parents = []
273
274     def visited(self):
275         """Called just after this node has been visited
276         without requiring a build.."""
277         pass
278
279     def depends_on(self, nodes):
280         """Does this node depend on any of 'nodes'?"""
281         for node in nodes:
282             if node in self.children():
283                 return 1
284
285         return 0
286
287     def builder_set(self, builder):
288         self.builder = builder
289
290     def has_builder(self):
291         """Return whether this Node has a builder or not.
292
293         In Boolean tests, this turns out to be a *lot* more efficient
294         than simply examining the builder attribute directly ("if
295         node.builder: ..."). When the builder attribute is examined
296         directly, it ends up calling __getattr__ for both the __len__
297         and __nonzero__ attributes on instances of our Builder Proxy
298         class(es), generating a bazillion extra calls and slowing
299         things down immensely.
300         """
301         try:
302             b = self.builder
303         except AttributeError:
304             # There was no explicit builder for this Node, so initialize
305             # the self.builder attribute to None now.
306             self.builder = None
307             b = self.builder
308         return not b is None
309
310     multiple_side_effect_has_builder = has_builder
311
312     def is_derived(self):
313         """
314         Returns true iff this node is derived (i.e. built).
315
316         This should return true only for nodes whose path should be in
317         the build directory when duplicate=0 and should contribute their build
318         signatures when they are used as source files to other derived files. For
319         example: source with source builders are not derived in this sense,
320         and hence should not return true.
321         """
322         return self.has_builder() or self.side_effect
323
324     def is_pseudo_derived(self):
325         """
326         Returns true iff this node is built, but should use a source path
327         when duplicate=0 and should contribute a content signature (i.e.
328         source signature) when used as a source for other derived files.
329         """
330         return 0
331
332     def alter_targets(self):
333         """Return a list of alternate targets for this Node.
334         """
335         return [], None
336
337     def get_found_includes(self, env, scanner, target):
338         """Return the scanned include lines (implicit dependencies)
339         found in this node.
340
341         The default is no implicit dependencies.  We expect this method
342         to be overridden by any subclass that can be scanned for
343         implicit dependencies.
344         """
345         return []
346
347     def get_implicit_deps(self, env, scanner, target):
348         """Return a list of implicit dependencies for this node.
349
350         This method exists to handle recursive invocation of the scanner
351         on the implicit dependencies returned by the scanner, if the
352         scanner's recursive flag says that we should.
353         """
354         if not scanner:
355             return []
356
357         # Give the scanner a chance to select a more specific scanner
358         # for this Node.
359         scanner = scanner.select(self)
360
361         try:
362             recurse = scanner.recursive
363         except AttributeError:
364             recurse = None
365
366         nodes = [self]
367         seen = {}
368         seen[self] = 1
369         deps = []
370         while nodes:
371            n = nodes.pop(0)
372            d = filter(lambda x, seen=seen: not seen.has_key(x),
373                       n.get_found_includes(env, scanner, target))
374            if d:
375                deps.extend(d)
376                for n in d:
377                    seen[n] = 1
378                if recurse:
379                    nodes.extend(d)
380
381         return deps
382
383     # cache used to make implicit_factory fast.
384     implicit_factory_cache = {}
385     
386     def implicit_factory(self, path):
387         """
388         Turn a cache implicit dependency path into a node.
389         This is called so many times that doing caching
390         here is a significant performance boost.
391         """
392         try:
393             return self.implicit_factory_cache[path]
394         except KeyError:
395             n = self.builder.source_factory(path)
396             self.implicit_factory_cache[path] = n
397             return n
398
399     def get_source_scanner(self, node):
400         """Fetch the source scanner for the specified node
401
402         NOTE:  "self" is the target being built, "node" is
403         the source file for which we want to fetch the scanner.
404         """
405         if self.source_scanner:
406             return self.source_scanner
407         try:
408             scanner = self.builder.source_scanner
409             if scanner:
410                 return scanner
411         except AttributeError:
412             pass
413         return node.backup_source_scanner or None
414
415     def scan(self):
416         """Scan this node's dependents for implicit dependencies."""
417         # Don't bother scanning non-derived files, because we don't
418         # care what their dependencies are.
419         # Don't scan again, if we already have scanned.
420         if not self.implicit is None:
421             return
422         self.implicit = []
423         self.implicit_dict = {}
424         self._children_reset()
425         if not self.has_builder():
426             return
427
428         build_env = self.get_build_env()
429
430         # Here's where we implement --implicit-cache.
431         if implicit_cache and not implicit_deps_changed:
432             implicit = self.get_stored_implicit()
433             if implicit is not None:
434                 implicit = map(self.implicit_factory, implicit)
435                 self._add_child(self.implicit, self.implicit_dict, implicit)
436                 calc = build_env.get_calculator()
437                 if implicit_deps_unchanged or self.current(calc, scan=0):
438                     return
439                 else:
440                     # one of this node's sources has changed, so
441                     # we need to recalculate the implicit deps,
442                     # and the bsig:
443                     self.implicit = []
444                     self.implicit_dict = {}
445                     self._children_reset()
446                     self.del_binfo()
447
448         for child in self.children(scan=0):
449             scanner = self.get_source_scanner(child)
450             if scanner:
451                 deps = child.get_implicit_deps(build_env, scanner, self)
452                 self._add_child(self.implicit, self.implicit_dict, deps)
453
454         # scan this node itself for implicit dependencies
455         deps = self.get_implicit_deps(build_env, self.target_scanner, self)
456         self._add_child(self.implicit, self.implicit_dict, deps)
457
458         # XXX See note above re: --implicit-cache.
459         #if implicit_cache:
460         #    self.store_implicit()
461
462     def scanner_key(self):
463         return None
464
465     def env_set(self, env, safe=0):
466         if safe and self.env:
467             return
468         self.env = env
469
470     def calculator(self):
471         import SCons.Defaults
472         
473         env = self.env or SCons.Defaults.DefaultEnvironment()
474         return env.get_calculator()
475
476     def calc_signature(self, calc=None):
477         """
478         Select and calculate the appropriate build signature for a node.
479
480         self - the node
481         calc - the signature calculation module
482         returns - the signature
483         """
484         try:
485             return self._calculated_sig
486         except AttributeError:
487             if self.is_derived():
488                 import SCons.Defaults
489                 
490                 env = self.env or SCons.Defaults.DefaultEnvironment()
491                 if env.use_build_signature():
492                     sig = self.calc_bsig(calc)
493                 else:
494                     sig = self.calc_csig(calc)
495             elif not self.rexists():
496                 sig = None
497             else:
498                 sig = self.calc_csig(calc)
499             self._calculated_sig = sig
500             return sig
501
502     def new_binfo(self):
503         return BuildInfo()
504
505     def del_binfo(self):
506         """Delete the bsig from this node."""
507         try:
508             delattr(self, 'binfo')
509         except AttributeError:
510             pass
511
512     def calc_bsig(self, calc=None):
513         try:
514             return self.binfo.bsig
515         except AttributeError:
516             self.binfo = self.gen_binfo(calc)
517             return self.binfo.bsig
518
519     def gen_binfo(self, calc=None, scan=1):
520         """
521         Generate a node's build signature, the digested signatures
522         of its dependency files and build information.
523
524         node - the node whose sources will be collected
525         cache - alternate node to use for the signature cache
526         returns - the build signature
527
528         This no longer handles the recursive descent of the
529         node's children's signatures.  We expect that they're
530         already built and updated by someone else, if that's
531         what's wanted.
532         """
533
534         if calc is None:
535             calc = self.calculator()
536
537         binfo = self.new_binfo()
538
539         if scan:
540             self.scan()
541
542         sources = self.filter_ignore(self.sources)
543         depends = self.filter_ignore(self.depends)
544         if self.implicit is None:
545             implicit = []
546         else:
547             implicit = self.filter_ignore(self.implicit)
548
549         def calc_signature(node, calc=calc):
550             return node.calc_signature(calc)
551         sourcesigs = map(calc_signature, sources)
552         dependsigs = map(calc_signature, depends)
553         implicitsigs = map(calc_signature, implicit)
554
555         sigs = sourcesigs + dependsigs + implicitsigs
556
557         if self.has_builder():
558             executor = self.get_executor()
559             binfo.bact = executor.strfunction()
560             binfo.bactsig = calc.module.signature(executor)
561             sigs.append(binfo.bactsig)
562
563         binfo.bsources = map(str, sources)
564         binfo.bdepends = map(str, depends)
565         binfo.bimplicit = map(str, implicit)
566
567         binfo.bsourcesigs = sourcesigs
568         binfo.bdependsigs = dependsigs
569         binfo.bimplicitsigs = implicitsigs
570
571         binfo.bsig = calc.module.collect(filter(None, sigs))
572
573         return binfo
574
575     def del_cinfo(self):
576         try:
577             del self.binfo.csig
578         except AttributeError:
579             pass
580
581     def calc_csig(self, calc=None):
582         try:
583             binfo = self.binfo
584         except AttributeError:
585             binfo = self.binfo = self.new_binfo()
586         try:
587             return binfo.csig
588         except AttributeError:
589             if calc is None:
590                 calc = self.calculator()
591             binfo.csig = calc.module.signature(self)
592             self.store_info(binfo)
593             return binfo.csig
594
595     def store_info(self, obj):
596         """Make the build signature permanent (that is, store it in the
597         .sconsign file or equivalent)."""
598         pass
599
600     def get_stored_info(self):
601         return None
602
603     def get_stored_implicit(self):
604         """Fetch the stored implicit dependencies"""
605         return None
606
607     def set_precious(self, precious = 1):
608         """Set the Node's precious value."""
609         self.precious = precious
610
611     def set_always_build(self, always_build = 1):
612         """Set the Node's always_build value."""
613         self.always_build = always_build
614
615     def exists(self):
616         """Does this node exists?"""
617         # All node exist by default:
618         return 1
619     
620     def rexists(self):
621         """Does this node exist locally or in a repositiory?"""
622         # There are no repositories by default:
623         return self.exists()
624     
625     def prepare(self):
626         """Prepare for this Node to be created.
627         The default implemenation checks that all children either exist
628         or are derived.
629         """
630         def missing(node):
631             return not node.is_derived() and \
632                    not node.is_pseudo_derived() and \
633                    not node.linked and \
634                    not node.rexists()
635         missing_sources = filter(missing, self.children())
636         if missing_sources:
637             desc = "Source `%s' not found, needed by target `%s'." % (missing_sources[0], self)
638             raise SCons.Errors.StopError, desc
639
640     def remove(self):
641         """Remove this Node:  no-op by default."""
642         return None
643
644     def add_dependency(self, depend):
645         """Adds dependencies."""
646         try:
647             self._add_child(self.depends, self.depends_dict, depend)
648         except TypeError, e:
649             e = e.args[0]
650             if SCons.Util.is_List(e):
651                 s = map(str, e)
652             else:
653                 s = str(e)
654             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)))
655
656     def add_ignore(self, depend):
657         """Adds dependencies to ignore."""
658         try:
659             self._add_child(self.ignore, self.ignore_dict, depend)
660         except TypeError, e:
661             e = e.args[0]
662             if SCons.Util.is_List(e):
663                 s = map(str, e)
664             else:
665                 s = str(e)
666             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)))
667
668     def add_source(self, source):
669         """Adds sources."""
670         try:
671             self._add_child(self.sources, self.sources_dict, source)
672         except TypeError, e:
673             e = e.args[0]
674             if SCons.Util.is_List(e):
675                 s = map(str, e)
676             else:
677                 s = str(e)
678             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)))
679
680     def _add_child(self, collection, dict, child):
681         """Adds 'child' to 'collection', first checking 'dict' to see
682         if it's already present."""
683         if type(child) is not type([]):
684             child = [child]
685         for c in child:
686             if not isinstance(c, Node):
687                 raise TypeError, c
688         added = None
689         for c in child:
690             if not dict.has_key(c):
691                 collection.append(c)
692                 dict[c] = 1
693                 added = 1
694         if added:
695             self._children_reset()
696
697     def add_wkid(self, wkid):
698         """Add a node to the list of kids waiting to be evaluated"""
699         if self.wkids != None:
700             self.wkids.append(wkid)
701
702     def _children_reset(self):
703         try:
704             delattr(self, '_children')
705         except AttributeError:
706             pass
707
708     def filter_ignore(self, nodelist):
709         ignore = self.ignore
710         result = []
711         for node in nodelist:
712             if node not in ignore:
713                 result.append(node)
714         return result
715
716     def children(self, scan=1):
717         """Return a list of the node's direct children, minus those
718         that are ignored by this node."""
719         if scan:
720             self.scan()
721         try:
722             return self._children
723         except AttributeError:
724             c = self.all_children(scan=0)
725             self._children = self.filter_ignore(c)
726             return self._children
727
728     def all_children(self, scan=1):
729         """Return a list of all the node's direct children."""
730         # The return list may contain duplicate Nodes, especially in
731         # source trees where there are a lot of repeated #includes
732         # of a tangle of .h files.  Profiling shows, however, that
733         # eliminating the duplicates with a brute-force approach that
734         # preserves the order (that is, something like:
735         #
736         #       u = []
737         #       for n in list:
738         #           if n not in u:
739         #               u.append(n)"
740         #
741         # takes more cycles than just letting the underlying methods
742         # hand back cached values if a Node's information is requested
743         # multiple times.  (Other methods of removing duplicates, like
744         # using dictionary keys, lose the order, and the only ordered
745         # dictionary patterns I found all ended up using "not in"
746         # internally anyway...)
747         if scan:
748             self.scan()
749         if self.implicit is None:
750             return self.sources + self.depends
751         else:
752             return self.sources + self.depends + self.implicit
753
754     def set_state(self, state):
755         self.state = state
756
757     def get_state(self):
758         return self.state
759
760     def current(self, calc=None):
761         """Default check for whether the Node is current: unknown Node
762         subtypes are always out of date, so they will always get built."""
763         return None
764
765     def children_are_up_to_date(self, calc=None):
766         """Alternate check for whether the Node is current:  If all of
767         our children were up-to-date, then this Node was up-to-date, too.
768
769         The SCons.Node.Alias and SCons.Node.Python.Value subclasses
770         rebind their current() method to this method."""
771         # Allow the children to calculate their signatures.
772         self.binfo = self.gen_binfo(calc)
773         state = 0
774         for kid in self.children(None):
775             s = kid.get_state()
776             if s and (not state or s > state):
777                 state = s
778         return (state == 0 or state == SCons.Node.up_to_date)
779
780     def is_literal(self):
781         """Always pass the string representation of a Node to
782         the command interpreter literally."""
783         return 1
784
785     def add_pre_action(self, act):
786         """Adds an Action performed on this Node only before
787         building it."""
788         self.pre_actions.append(act)
789
790     def add_post_action(self, act):
791         """Adds and Action performed on this Node only after
792         building it."""
793         self.post_actions.append(act)
794
795     def render_include_tree(self):
796         """
797         Return a text representation, suitable for displaying to the
798         user, of the include tree for the sources of this node.
799         """
800         if self.is_derived() and self.env:
801             env = self.get_build_env()
802             for s in self.sources:
803                 scanner = self.get_source_scanner(s)
804                 def f(node, env=env, scanner=scanner, target=self):
805                     return node.get_found_includes(env, scanner, target)
806                 return SCons.Util.render_tree(s, f, 1)
807         else:
808             return None
809
810     def get_abspath(self):
811         """
812         Return an absolute path to the Node.  This will return simply
813         str(Node) by default, but for Node types that have a concept of
814         relative path, this might return something different.
815         """
816         return str(self)
817
818     def for_signature(self):
819         """
820         Return a string representation of the Node that will always
821         be the same for this particular Node, no matter what.  This
822         is by contrast to the __str__() method, which might, for
823         instance, return a relative path for a file Node.  The purpose
824         of this method is to generate a value to be used in signature
825         calculation for the command line used to build a target, and
826         we use this method instead of str() to avoid unnecessary
827         rebuilds.  This method does not need to return something that
828         would actually work in a command line; it can return any kind of
829         nonsense, so long as it does not change.
830         """
831         return str(self)
832
833     def get_string(self, for_signature):
834         """This is a convenience function designed primarily to be
835         used in command generators (i.e., CommandGeneratorActions or
836         Environment variables that are callable), which are called
837         with a for_signature argument that is nonzero if the command
838         generator is being called to generate a signature for the
839         command line, which determines if we should rebuild or not.
840
841         Such command generators should use this method in preference
842         to str(Node) when converting a Node to a string, passing
843         in the for_signature parameter, such that we will call
844         Node.for_signature() or str(Node) properly, depending on whether
845         we are calculating a signature or actually constructing a
846         command line."""
847         if for_signature:
848             return self.for_signature()
849         return str(self)
850
851     def get_subst_proxy(self):
852         """
853         This method is expected to return an object that will function
854         exactly like this Node, except that it implements any additional
855         special features that we would like to be in effect for
856         Environment variable substitution.  The principle use is that
857         some Nodes would like to implement a __getattr__() method,
858         but putting that in the Node type itself has a tendency to kill
859         performance.  We instead put it in a proxy and return it from
860         this method.  It is legal for this method to return self
861         if no new functionality is needed for Environment substitution.
862         """
863         return self
864
865     def explain(self):
866         if not self.exists():
867             return "building `%s' because it doesn't exist\n" % self
868
869         old = self.get_stored_info()
870         if old is None:
871             return None
872
873         def dictify(result, kids, sigs):
874             for k, s in zip(kids, sigs):
875                 result[k] = s
876
877         try:
878             old_bkids = old.bsources + old.bdepends + old.bimplicit
879         except AttributeError:
880             return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self
881
882         osig = {}
883         dictify(osig, old.bsources, old.bsourcesigs)
884         dictify(osig, old.bdepends, old.bdependsigs)
885         dictify(osig, old.bimplicit, old.bimplicitsigs)
886
887         new_bsources = map(str, self.binfo.bsources)
888         new_bdepends = map(str, self.binfo.bdepends)
889         new_bimplicit = map(str, self.binfo.bimplicit)
890
891         nsig = {}
892         dictify(nsig, new_bsources, self.binfo.bsourcesigs)
893         dictify(nsig, new_bdepends, self.binfo.bdependsigs)
894         dictify(nsig, new_bimplicit, self.binfo.bimplicitsigs)
895
896         new_bkids = new_bsources + new_bdepends + new_bimplicit
897         lines = map(lambda x: "`%s' is no longer a dependency\n" % x,
898                     filter(lambda x, nk=new_bkids: not x in nk, old_bkids))
899
900         for k in new_bkids:
901             if not k in old_bkids:
902                 lines.append("`%s' is a new dependency\n" % k)
903             elif osig[k] != nsig[k]:
904                 lines.append("`%s' changed\n" % k)
905
906         if len(lines) == 0 and old_bkids != new_bkids:
907             lines.append("the dependency order changed:\n" +
908                          "%sold: %s\n" % (' '*15, old_bkids) +
909                          "%snew: %s\n" % (' '*15, new_bkids))
910
911         if len(lines) == 0:
912             newact, newactsig = self.binfo.bact, self.binfo.bactsig
913             def fmt_with_title(title, strlines):
914                 lines = string.split(strlines, '\n')
915                 sep = '\n' + ' '*(15 + len(title))
916                 return ' '*15 + title + string.join(lines, sep) + '\n'
917             if old.bactsig != newactsig:
918                 if old.bact == newact:
919                     lines.append("the contents of the build action changed\n" +
920                                  fmt_with_title('action: ', newact))
921                 else:
922                     lines.append("the build action changed:\n" +
923                                  fmt_with_title('old: ', old.bact) +
924                                  fmt_with_title('new: ', newact))
925
926         if len(lines) == 0:
927             return "rebuilding `%s' for unknown reasons" % self
928
929         preamble = "rebuilding `%s' because" % self
930         if len(lines) == 1:
931             return "%s %s"  % (preamble, lines[0])
932         else:
933             lines = ["%s:\n" % preamble] + lines
934             return string.join(lines, ' '*11)
935
936 def get_children(node, parent): return node.children()
937 def ignore_cycle(node, stack): pass
938 def do_nothing(node, parent): pass
939
940 class Walker:
941     """An iterator for walking a Node tree.
942
943     This is depth-first, children are visited before the parent.
944     The Walker object can be initialized with any node, and
945     returns the next node on the descent with each next() call.
946     'kids_func' is an optional function that will be called to
947     get the children of a node instead of calling 'children'.
948     'cycle_func' is an optional function that will be called
949     when a cycle is detected.
950
951     This class does not get caught in node cycles caused, for example,
952     by C header file include loops.
953     """
954     def __init__(self, node, kids_func=get_children,
955                              cycle_func=ignore_cycle,
956                              eval_func=do_nothing):
957         self.kids_func = kids_func
958         self.cycle_func = cycle_func
959         self.eval_func = eval_func
960         node.wkids = copy.copy(kids_func(node, None))
961         self.stack = [node]
962         self.history = {} # used to efficiently detect and avoid cycles
963         self.history[node] = None
964
965     def next(self):
966         """Return the next node for this walk of the tree.
967
968         This function is intentionally iterative, not recursive,
969         to sidestep any issues of stack size limitations.
970         """
971
972         while self.stack:
973             if self.stack[-1].wkids:
974                 node = self.stack[-1].wkids.pop(0)
975                 if not self.stack[-1].wkids:
976                     self.stack[-1].wkids = None
977                 if self.history.has_key(node):
978                     self.cycle_func(node, self.stack)
979                 else:
980                     node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
981                     self.stack.append(node)
982                     self.history[node] = None
983             else:
984                 node = self.stack.pop()
985                 del self.history[node]
986                 if node:
987                     if self.stack:
988                         parent = self.stack[-1]
989                     else:
990                         parent = None
991                     self.eval_func(node, parent)
992                 return node
993         return None
994
995     def is_done(self):
996         return not self.stack
997
998
999 arg2nodes_lookups = []