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