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