3 The Node package for the SCons software construction utility.
5 This is, in many ways, the heart of SCons.
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).
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."
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:
33 # The above copyright notice and this permission notice shall be included
34 # in all copies or substantial portions of the Software.
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.
45 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
53 from SCons.Debug import logInstanceCreation
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
71 stack = 6 # nodes that are in the current Taskmaster execution stack
83 # controls whether implicit dependencies are cached:
86 # controls whether implicit dep changes are ignored:
87 implicit_deps_unchanged = 0
89 # controls whether the cached implicit deps are ignored:
90 implicit_deps_changed = 0
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
99 def __cmp__(self, other):
100 return cmp(self.__dict__, other.__dict__)
103 """The base Node class, for entities that we know how to
104 build, or use to build other Nodes.
107 __metaclass__ = SCons.Memoize.Memoized_Metaclass
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).
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
138 self.state = no_state
140 self.always_build = None
141 self.found_includes = {}
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?
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).
155 def get_suffix(self):
158 def get_build_env(self):
159 """Fetch the appropriate Environment to build this node.
161 return self.get_executor().get_build_env()
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)
167 def set_executor(self, executor):
168 """Set the action executor for this node."""
169 self.executor = executor
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."""
175 executor = self.executor
176 except AttributeError:
180 act = self.builder.action
181 except AttributeError:
182 executor = SCons.Executor.Null()
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],
193 self.executor = executor
196 def executor_cleanup(self):
197 """Let the executor clean up any cached information."""
199 executor = self.get_executor(create=None)
200 except AttributeError:
205 def reset_executor(self):
206 "Remove cached executor; forces recompute when needed."
208 delattr(self, 'executor')
209 except AttributeError:
212 def retrieve_from_cache(self):
213 """Try to retrieve the node's content from a cache
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
219 Returns true iff the node was successfully retrieved.
223 def build(self, **kw):
224 """Actually build the node.
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
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)
236 """Called just after this node is successfully built."""
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
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
252 # Reset this Node's cached state since it was just built and
253 # various state has changed.
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
262 if hasattr(new_binfo, 'csig'):
263 new_binfo = self.gen_binfo() # sets self.binfo
265 self.binfo = new_binfo
266 self.store_info(new_binfo)
268 def add_to_waiting_parents(self, node):
269 self.waiting_parents.append(node)
271 def call_for_all_waiting_parents(self, func):
273 for parent in self.waiting_parents:
274 parent.call_for_all_waiting_parents(func)
276 def postprocess(self):
277 """Clean up anything we don't need to hang onto after we've
279 self.executor_cleanup()
282 """Completely clear a Node of all its cached state (so that it
283 can be re-evaluated by interfaces that do continuous integration
287 self.executor_cleanup()
291 delattr(self, '_calculated_sig')
292 except AttributeError:
295 self.found_includes = {}
298 self.waiting_parents = []
301 """Called just after this node has been visited
302 without requiring a build.."""
305 def builder_set(self, builder):
307 self.builder = builder
309 def has_builder(self):
310 """Return whether this Node has a builder or not.
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.
322 except AttributeError:
323 # There was no explicit builder for this Node, so initialize
324 # the self.builder attribute to None now.
329 def set_explicit(self, is_explicit):
330 self.is_explicit = is_explicit
332 def has_explicit_builder(self):
333 """Return whether this Node has an explicit builder
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
340 return self.is_explicit
341 except AttributeError:
342 self.is_explicit = None
343 return self.is_explicit
345 def get_builder(self, default_builder=None):
346 """Return the set builder, or a specified default value"""
349 except AttributeError:
350 return default_builder
352 multiple_side_effect_has_builder = has_builder
354 def is_derived(self):
356 Returns true iff this node is derived (i.e. built).
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.
365 return self.has_builder() or self.side_effect
367 def is_pseudo_derived(self):
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.
375 def alter_targets(self):
376 """Return a list of alternate targets for this Node.
380 def get_found_includes(self, env, scanner, path):
381 """Return the scanned include lines (implicit dependencies)
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.
390 def get_implicit_deps(self, env, scanner, path):
391 """Return a list of implicit dependencies for this node.
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.
400 # Give the scanner a chance to select a more specific scanner
402 scanner = scanner.select(self)
410 d = filter(lambda x, seen=seen: not seen.has_key(x),
411 n.get_found_includes(env, scanner, path))
416 nodes.extend(scanner.recurse_nodes(d))
420 def implicit_factory(self, path):
422 Turn a cache implicit dependency path into a node.
423 This is called so many times that doing caching
424 here is a significant performance boost.
427 return self.builder.source_factory(path)
429 def get_scanner(self, env, kw={}):
430 return env.get_scanner(self.scanner_key())
432 def get_source_scanner(self, node):
433 """Fetch the source scanner for the specified node
435 NOTE: "self" is the target being built, "node" is
436 the source file for which we want to fetch the scanner.
438 Implies self.has_builder() is true; again, expect to only be
439 called from locations where this is already verified.
441 This function may be called very often; it attempts to cache
442 the scanner found to improve performance.
446 scanner = self.builder.source_scanner
447 except AttributeError:
450 # The builder didn't have an explicit scanner, so go look up
451 # a scanner from env['SCANNERS'] based on the node's scanner
452 # key (usually the file extension).
453 scanner = self.get_scanner(self.get_build_env())
455 scanner = scanner.select(node)
458 def add_to_implicit(self, deps):
459 if not hasattr(self, 'implicit') or self.implicit is None:
461 self.implicit_dict = {}
462 self._children_reset()
463 self._add_child(self.implicit, self.implicit_dict, deps)
466 """Scan this node's dependents for implicit dependencies."""
467 # Don't bother scanning non-derived files, because we don't
468 # care what their dependencies are.
469 # Don't scan again, if we already have scanned.
470 if not self.implicit is None:
473 self.implicit_dict = {}
474 self._children_reset()
475 if not self.has_builder():
478 build_env = self.get_build_env()
480 # Here's where we implement --implicit-cache.
481 if implicit_cache and not implicit_deps_changed:
482 implicit = self.get_stored_implicit()
483 if implicit is not None:
484 implicit = map(self.implicit_factory, implicit)
485 self._add_child(self.implicit, self.implicit_dict, implicit)
486 calc = build_env.get_calculator()
487 if implicit_deps_unchanged or self.current(calc):
490 # one of this node's sources has changed, so
491 # we need to recalculate the implicit deps,
494 self.implicit_dict = {}
495 self._children_reset()
498 scanner = self.builder.source_scanner
499 self.get_executor().scan(scanner)
501 # scan this node itself for implicit dependencies
502 scanner = self.builder.target_scanner
504 path = self.get_build_scanner_path(scanner)
505 deps = self.get_implicit_deps(build_env, scanner, path)
506 self._add_child(self.implicit, self.implicit_dict, deps)
508 # XXX See note above re: --implicit-cache.
510 # self.store_implicit()
512 def scanner_key(self):
515 def env_set(self, env, safe=0):
516 if safe and self.env:
520 def calculator(self):
521 import SCons.Defaults
523 env = self.env or SCons.Defaults.DefaultEnvironment()
524 return env.get_calculator()
526 def calc_signature(self, calc=None):
528 Select and calculate the appropriate build signature for a node.
532 calc - the signature calculation module
533 returns - the signature
535 if self.is_derived():
536 import SCons.Defaults
538 env = self.env or SCons.Defaults.DefaultEnvironment()
539 if env.use_build_signature():
540 return self.calc_bsig(calc)
541 elif not self.rexists():
543 return self.calc_csig(calc)
549 """Delete the bsig from this node."""
551 delattr(self, 'binfo')
552 except AttributeError:
555 def calc_bsig(self, calc=None):
557 return self.binfo.bsig
558 except AttributeError:
559 self.binfo = self.gen_binfo(calc)
560 return self.binfo.bsig
562 def gen_binfo(self, calc=None, scan=1):
564 Generate a node's build signature, the digested signatures
565 of its dependency files and build information.
567 node - the node whose sources will be collected
568 cache - alternate node to use for the signature cache
569 returns - the build signature
571 This no longer handles the recursive descent of the
572 node's children's signatures. We expect that they're
573 already built and updated by someone else, if that's
579 calc = self.calculator()
581 binfo = self.new_binfo()
586 executor = self.get_executor()
588 sourcelist, sourcesigs, bsources = executor.get_source_binfo(calc, self.ignore)
589 depends = self.depends
590 implicit = self.implicit or []
593 depends = filter(self.do_not_ignore, depends)
594 implicit = filter(self.do_not_ignore, implicit)
596 def calc_signature(node, calc=calc):
597 return node.calc_signature(calc)
598 dependsigs = map(calc_signature, depends)
599 implicitsigs = map(calc_signature, implicit)
601 sigs = sourcesigs + dependsigs + implicitsigs
603 if self.has_builder():
604 binfo.bact = str(executor)
605 binfo.bactsig = calc.module.signature(executor)
606 sigs.append(binfo.bactsig)
608 binfo.bsources = bsources
609 binfo.bdepends = map(str, depends)
610 binfo.bimplicit = map(str, implicit)
612 binfo.bsourcesigs = sourcesigs
613 binfo.bdependsigs = dependsigs
614 binfo.bimplicitsigs = implicitsigs
616 binfo.bsig = calc.module.collect(filter(None, sigs))
623 except AttributeError:
626 def calc_csig(self, calc=None):
629 except AttributeError:
630 binfo = self.binfo = self.new_binfo()
633 except AttributeError:
635 calc = self.calculator()
636 binfo.csig = calc.module.signature(self)
637 self.store_info(binfo)
640 def store_info(self, obj):
641 """Make the build signature permanent (that is, store it in the
642 .sconsign file or equivalent)."""
645 def get_stored_info(self):
648 def get_stored_implicit(self):
649 """Fetch the stored implicit dependencies"""
652 def set_precious(self, precious = 1):
653 """Set the Node's precious value."""
654 self.precious = precious
656 def set_always_build(self, always_build = 1):
657 """Set the Node's always_build value."""
658 self.always_build = always_build
661 """Does this node exists?"""
662 # All node exist by default:
666 """Does this node exist locally or in a repositiory?"""
667 # There are no repositories by default:
672 return not self.is_derived() and \
673 not self.is_pseudo_derived() and \
674 not self.linked and \
678 """Prepare for this Node to be created.
679 The default implemenation checks that all children either exist
683 if not self.implicit is None:
684 l = l + self.implicit
685 missing_sources = self.get_executor().get_missing_sources() \
686 + filter(lambda c: c.missing(), l)
688 desc = "Source `%s' not found, needed by target `%s'." % (missing_sources[0], self)
689 raise SCons.Errors.StopError, desc
692 """Remove this Node: no-op by default."""
695 def add_dependency(self, depend):
696 """Adds dependencies."""
698 self._add_child(self.depends, self.depends_dict, depend)
701 if SCons.Util.is_List(e):
705 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)))
707 def add_ignore(self, depend):
708 """Adds dependencies to ignore."""
710 self._add_child(self.ignore, self.ignore_dict, depend)
713 if SCons.Util.is_List(e):
717 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)))
719 def add_source(self, source):
722 self._add_child(self.sources, self.sources_dict, source)
725 if SCons.Util.is_List(e):
729 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)))
731 def _add_child(self, collection, dict, child):
732 """Adds 'child' to 'collection', first checking 'dict' to see
733 if it's already present."""
734 if type(child) is not type([]):
737 if not isinstance(c, Node):
741 if not dict.has_key(c):
746 self._children_reset()
748 def add_wkid(self, wkid):
749 """Add a node to the list of kids waiting to be evaluated"""
750 if self.wkids != None:
751 self.wkids.append(wkid)
753 def _children_reset(self):
755 # We need to let the Executor clear out any calculated
756 # bsig info that it's cached so we can re-calculate it.
757 self.executor_cleanup()
759 def do_not_ignore(self, node):
760 return node not in self.ignore
762 def _all_children_get(self):
763 # The return list may contain duplicate Nodes, especially in
764 # source trees where there are a lot of repeated #includes
765 # of a tangle of .h files. Profiling shows, however, that
766 # eliminating the duplicates with a brute-force approach that
767 # preserves the order (that is, something like:
774 # takes more cycles than just letting the underlying methods
775 # hand back cached values if a Node's information is requested
776 # multiple times. (Other methods of removing duplicates, like
777 # using dictionary keys, lose the order, and the only ordered
778 # dictionary patterns I found all ended up using "not in"
779 # internally anyway...)
780 if self.implicit is None:
781 return self.sources + self.depends
783 return self.sources + self.depends + self.implicit
785 def _children_get(self):
787 children = self._all_children_get()
789 children = filter(self.do_not_ignore, children)
792 def all_children(self, scan=1):
793 """Return a list of all the node's direct children."""
796 return self._all_children_get()
798 def children(self, scan=1):
799 """Return a list of the node's direct children, minus those
800 that are ignored by this node."""
803 return self._children_get()
805 def set_state(self, state):
811 def current(self, calc=None):
812 """Default check for whether the Node is current: unknown Node
813 subtypes are always out of date, so they will always get built."""
816 def children_are_up_to_date(self, calc=None):
817 """Alternate check for whether the Node is current: If all of
818 our children were up-to-date, then this Node was up-to-date, too.
820 The SCons.Node.Alias and SCons.Node.Python.Value subclasses
821 rebind their current() method to this method."""
822 # Allow the children to calculate their signatures.
823 self.binfo = self.gen_binfo(calc)
824 if self.always_build:
827 for kid in self.children(None):
829 if s and (not state or s > state):
831 return (state == 0 or state == SCons.Node.up_to_date)
833 def is_literal(self):
834 """Always pass the string representation of a Node to
835 the command interpreter literally."""
838 def add_pre_action(self, act):
839 """Adds an Action performed on this Node only before
841 self.pre_actions.append(act)
842 # executor must be recomputed to include new pre-actions
843 self.reset_executor()
845 def add_post_action(self, act):
846 """Adds and Action performed on this Node only after
848 self.post_actions.append(act)
849 # executor must be recomputed to include new pre-actions
850 self.reset_executor()
852 def render_include_tree(self):
854 Return a text representation, suitable for displaying to the
855 user, of the include tree for the sources of this node.
857 if self.is_derived() and self.env:
858 env = self.get_build_env()
859 for s in self.sources:
860 scanner = self.get_source_scanner(s)
861 path = self.get_build_scanner_path(scanner)
862 def f(node, env=env, scanner=scanner, path=path):
863 return node.get_found_includes(env, scanner, path)
864 return SCons.Util.render_tree(s, f, 1)
868 def get_abspath(self):
870 Return an absolute path to the Node. This will return simply
871 str(Node) by default, but for Node types that have a concept of
872 relative path, this might return something different.
876 def for_signature(self):
878 Return a string representation of the Node that will always
879 be the same for this particular Node, no matter what. This
880 is by contrast to the __str__() method, which might, for
881 instance, return a relative path for a file Node. The purpose
882 of this method is to generate a value to be used in signature
883 calculation for the command line used to build a target, and
884 we use this method instead of str() to avoid unnecessary
885 rebuilds. This method does not need to return something that
886 would actually work in a command line; it can return any kind of
887 nonsense, so long as it does not change.
891 def get_string(self, for_signature):
892 """This is a convenience function designed primarily to be
893 used in command generators (i.e., CommandGeneratorActions or
894 Environment variables that are callable), which are called
895 with a for_signature argument that is nonzero if the command
896 generator is being called to generate a signature for the
897 command line, which determines if we should rebuild or not.
899 Such command generators should use this method in preference
900 to str(Node) when converting a Node to a string, passing
901 in the for_signature parameter, such that we will call
902 Node.for_signature() or str(Node) properly, depending on whether
903 we are calculating a signature or actually constructing a
906 return self.for_signature()
909 def get_subst_proxy(self):
911 This method is expected to return an object that will function
912 exactly like this Node, except that it implements any additional
913 special features that we would like to be in effect for
914 Environment variable substitution. The principle use is that
915 some Nodes would like to implement a __getattr__() method,
916 but putting that in the Node type itself has a tendency to kill
917 performance. We instead put it in a proxy and return it from
918 this method. It is legal for this method to return self
919 if no new functionality is needed for Environment substitution.
924 if not self.exists():
925 return "building `%s' because it doesn't exist\n" % self
927 old = self.get_stored_info()
931 def dictify(result, kids, sigs):
932 for k, s in zip(kids, sigs):
936 old_bkids = old.bsources + old.bdepends + old.bimplicit
937 except AttributeError:
938 return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self
941 dictify(osig, old.bsources, old.bsourcesigs)
942 dictify(osig, old.bdepends, old.bdependsigs)
943 dictify(osig, old.bimplicit, old.bimplicitsigs)
945 new_bsources = map(str, self.binfo.bsources)
946 new_bdepends = map(str, self.binfo.bdepends)
947 new_bimplicit = map(str, self.binfo.bimplicit)
950 dictify(nsig, new_bsources, self.binfo.bsourcesigs)
951 dictify(nsig, new_bdepends, self.binfo.bdependsigs)
952 dictify(nsig, new_bimplicit, self.binfo.bimplicitsigs)
954 new_bkids = new_bsources + new_bdepends + new_bimplicit
955 lines = map(lambda x: "`%s' is no longer a dependency\n" % x,
956 filter(lambda x, nk=new_bkids: not x in nk, old_bkids))
959 if not k in old_bkids:
960 lines.append("`%s' is a new dependency\n" % k)
961 elif osig[k] != nsig[k]:
962 lines.append("`%s' changed\n" % k)
964 if len(lines) == 0 and old_bkids != new_bkids:
965 lines.append("the dependency order changed:\n" +
966 "%sold: %s\n" % (' '*15, old_bkids) +
967 "%snew: %s\n" % (' '*15, new_bkids))
970 newact, newactsig = self.binfo.bact, self.binfo.bactsig
971 def fmt_with_title(title, strlines):
972 lines = string.split(strlines, '\n')
973 sep = '\n' + ' '*(15 + len(title))
974 return ' '*15 + title + string.join(lines, sep) + '\n'
975 if old.bactsig != newactsig:
976 if old.bact == newact:
977 lines.append("the contents of the build action changed\n" +
978 fmt_with_title('action: ', newact))
980 lines.append("the build action changed:\n" +
981 fmt_with_title('old: ', old.bact) +
982 fmt_with_title('new: ', newact))
985 return "rebuilding `%s' for unknown reasons\n" % self
987 preamble = "rebuilding `%s' because" % self
989 return "%s %s" % (preamble, lines[0])
991 lines = ["%s:\n" % preamble] + lines
992 return string.join(lines, ' '*11)
995 ul = UserList.UserList([2])
1002 class NodeList(UserList.UserList):
1004 return str(map(str, self.data))
1008 if not SCons.Memoize.has_metaclass:
1010 class Node(SCons.Memoize.Memoizer, _Base):
1011 def __init__(self, *args, **kw):
1012 apply(_Base.__init__, (self,)+args, kw)
1013 SCons.Memoize.Memoizer.__init__(self)
1016 def get_children(node, parent): return node.children()
1017 def ignore_cycle(node, stack): pass
1018 def do_nothing(node, parent): pass
1021 """An iterator for walking a Node tree.
1023 This is depth-first, children are visited before the parent.
1024 The Walker object can be initialized with any node, and
1025 returns the next node on the descent with each next() call.
1026 'kids_func' is an optional function that will be called to
1027 get the children of a node instead of calling 'children'.
1028 'cycle_func' is an optional function that will be called
1029 when a cycle is detected.
1031 This class does not get caught in node cycles caused, for example,
1032 by C header file include loops.
1034 def __init__(self, node, kids_func=get_children,
1035 cycle_func=ignore_cycle,
1036 eval_func=do_nothing):
1037 self.kids_func = kids_func
1038 self.cycle_func = cycle_func
1039 self.eval_func = eval_func
1040 node.wkids = copy.copy(kids_func(node, None))
1042 self.history = {} # used to efficiently detect and avoid cycles
1043 self.history[node] = None
1046 """Return the next node for this walk of the tree.
1048 This function is intentionally iterative, not recursive,
1049 to sidestep any issues of stack size limitations.
1053 if self.stack[-1].wkids:
1054 node = self.stack[-1].wkids.pop(0)
1055 if not self.stack[-1].wkids:
1056 self.stack[-1].wkids = None
1057 if self.history.has_key(node):
1058 self.cycle_func(node, self.stack)
1060 node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
1061 self.stack.append(node)
1062 self.history[node] = None
1064 node = self.stack.pop()
1065 del self.history[node]
1068 parent = self.stack[-1]
1071 self.eval_func(node, parent)
1076 return not self.stack
1079 arg2nodes_lookups = []