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