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