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__"
52 from SCons.Debug import logInstanceCreation
58 # These are in "priority" order, so that the maximum value for any
59 # child/dependency of a node represents the state of that node if
60 # it has no builder of its own. The canonical example is a file
61 # system directory, which is only up to date if all of its children
68 stack = 6 # nodes that are in the current Taskmaster execution stack
70 # controls whether implicit depedencies are cached:
73 # controls whether implicit dep changes are ignored:
74 implicit_deps_unchanged = 0
76 # controls whether the cached implicit deps are ignored:
77 implicit_deps_changed = 0
79 # A variable that can be set to an interface-specific function be called
80 # to annotate a Node with information about its creation.
81 def do_nothing(node): pass
86 def __cmp__(self, other):
87 return cmp(self.__dict__, other.__dict__)
90 """The base Node class, for entities that we know how to
91 build, or use to build other Nodes.
98 if __debug__: logInstanceCreation(self, 'Node')
99 # Note that we no longer explicitly initialize a self.builder
100 # attribute to None here. That's because the self.builder
101 # attribute may be created on-the-fly later by a subclass (the
102 # canonical example being a builder to fetch a file from a
103 # source code system like CVS or Subversion).
105 # Each list of children that we maintain is accompanied by a
106 # dictionary used to look up quickly whether a node is already
107 # present in the list. Empirical tests showed that it was
108 # fastest to maintain them as side-by-side Node attributes in
109 # this way, instead of wrapping up each list+dictionary pair in
110 # a class. (Of course, we could always still do that in the
111 # future if we had a good reason to...).
112 self.sources = [] # source files used to build node
113 self.sources_dict = {}
114 self.depends = [] # explicit dependencies (from Depends)
115 self.depends_dict = {}
116 self.ignore = [] # dependencies to ignore
117 self.ignore_dict = {}
118 self.implicit = None # implicit (scanned) dependencies (None means not scanned yet)
120 self.wkids = None # Kids yet to walk, when it's an array
121 self.target_scanner = None # explicit scanner from this node's Builder
122 self.source_scanner = None # source scanner
127 self.always_build = None
128 self.found_includes = {}
130 self.overrides = {} # construction variable overrides for building this node
131 self.attributes = self.Attrs() # Generic place to stick information about the Node.
132 self.side_effect = 0 # true iff this node is a side effect
133 self.side_effects = [] # the side effects of building this target
134 self.pre_actions = []
135 self.post_actions = []
136 self.linked = 0 # is this node linked to the build directory?
138 # Let the interface in which the build engine is embedded
139 # annotate this Node with its own info (like a description of
140 # what line in what file created the node, for example).
143 def get_suffix(self):
146 def generate_build_dict(self):
147 """Return an appropriate dictionary of values for building
151 def get_build_env(self):
152 """Fetch the appropriate Environment to build this node."""
153 executor = self.get_executor()
154 return executor.get_build_env()
156 def set_executor(self, executor):
157 """Set the action executor for this node."""
158 self.executor = executor
160 def get_executor(self, create=1):
161 """Fetch the action executor for this node. Create one if
162 there isn't already one, and requested to do so."""
164 executor = self.executor
165 except AttributeError:
168 import SCons.Executor
169 executor = SCons.Executor.Executor(self.builder.action,
171 [self.builder.overrides],
174 self.executor = executor
177 def retrieve_from_cache(self):
178 """Try to retrieve the node's content from a cache
180 This method is called from multiple threads in a parallel build,
181 so only do thread safe stuff here. Do thread unsafe stuff in
184 Returns true iff the node was successfully retrieved.
188 def build(self, **kw):
189 """Actually build the node.
191 This method is called from multiple threads in a parallel build,
192 so only do thread safe stuff here. Do thread unsafe stuff in
195 if not self.has_builder():
197 def errfunc(stat, node=self):
198 raise SCons.Errors.BuildError(node=node, errstr="Error %d" % stat)
199 executor = self.get_executor()
200 apply(executor, (self, errfunc), kw)
203 """Called just after this node is sucessfully built."""
205 new_binfo = self.binfo
206 except AttributeError:
209 self.store_info(new_binfo)
211 # Clear out the implicit dependency caches:
212 # XXX this really should somehow be made more general and put
213 # under the control of the scanners.
214 if self.source_scanner:
215 self.found_includes = {}
217 for parent in self.get_parents():
218 parent.implicit = None
221 # The content just changed, delete any cached info
222 # so it will get recalculated.
225 def postprocess(self):
226 """Clean up anything we don't need to hang onto after we've
229 executor = self.get_executor(create=None)
230 except AttributeError:
236 """Completely clear a Node of all its cached state (so that it
237 can be re-evaluated by interfaces that do continuous integration
244 delattr(self, '_calculated_sig')
245 except AttributeError:
248 self.found_includes = {}
252 """Called just after this node has been visited
253 without requiring a build.."""
256 def depends_on(self, nodes):
257 """Does this node depend on any of 'nodes'?"""
259 if node in self.children():
264 def builder_set(self, builder):
265 self.builder = builder
267 def has_builder(self):
268 """Return whether this Node has a builder or not.
270 In Boolean tests, this turns out to be a *lot* more efficient
271 than simply examining the builder attribute directly ("if
272 node.builder: ..."). When the builder attribute is examined
273 directly, it ends up calling __getattr__ for both the __len__
274 and __nonzero__ attributes on instances of our Builder Proxy
275 class(es), generating a bazillion extra calls and slowing
276 things down immensely.
280 except AttributeError:
281 # There was no explicit builder for this Node, so initialize
282 # the self.builder attribute to None now.
287 def is_derived(self):
289 Returns true iff this node is derived (i.e. built).
291 This should return true only for nodes whose path should be in
292 the build directory when duplicate=0 and should contribute their build
293 signatures when they are used as source files to other derived files. For
294 example: source with source builders are not derived in this sense,
295 and hence should not return true.
297 return self.has_builder() or self.side_effect
299 def is_pseudo_derived(self):
301 Returns true iff this node is built, but should use a source path
302 when duplicate=0 and should contribute a content signature (i.e.
303 source signature) when used as a source for other derived files.
307 def alter_targets(self):
308 """Return a list of alternate targets for this Node.
312 def get_found_includes(self, env, scanner, target):
313 """Return the scanned include lines (implicit dependencies)
316 The default is no implicit dependencies. We expect this method
317 to be overridden by any subclass that can be scanned for
318 implicit dependencies.
322 def get_implicit_deps(self, env, scanner, target):
323 """Return a list of implicit dependencies for this node.
325 This method exists to handle recursive invocation of the scanner
326 on the implicit dependencies returned by the scanner, if the
327 scanner's recursive flag says that we should.
333 recurse = scanner.recursive
334 except AttributeError:
343 d = filter(lambda x, seen=seen: not seen.has_key(x),
344 n.get_found_includes(env, scanner, target))
354 # cache used to make implicit_factory fast.
355 implicit_factory_cache = {}
357 def implicit_factory(self, path):
359 Turn a cache implicit dependency path into a node.
360 This is called so many times that doing caching
361 here is a significant perforamnce boost.
364 return self.implicit_factory_cache[path]
366 n = self.builder.source_factory(path)
367 self.implicit_factory_cache[path] = n
371 """Scan this node's dependents for implicit dependencies."""
372 # Don't bother scanning non-derived files, because we don't
373 # care what their dependencies are.
374 # Don't scan again, if we already have scanned.
375 if not self.implicit is None:
378 self.implicit_dict = {}
379 self._children_reset()
380 if not self.has_builder():
383 build_env = self.get_build_env()
385 # XXX Here's where we implement --implicit-cache. This doesn't
386 # do anything right now, but we're probably going to re-implement
387 # as a way to cache #include lines from source files, so I want
388 # to keep this code around for now.
390 #if implicit_cache and not implicit_deps_changed:
391 # implicit = self.get_stored_implicit()
392 # if implicit is not None:
393 # implicit = map(self.implicit_factory, implicit)
394 # self._add_child(self.implicit, self.implicit_dict, implicit)
395 # calc = build_env.get_calculator()
396 # if implicit_deps_unchanged or calc.current(self, calc.bsig(self)):
399 # # one of this node's sources has changed, so
400 # # we need to recalculate the implicit deps,
403 # self.implicit_dict = {}
404 # self._children_reset()
407 for child in self.children(scan=0):
408 scanner = child.source_scanner
410 self._add_child(self.implicit,
412 child.get_implicit_deps(build_env,
416 # scan this node itself for implicit dependencies
417 self._add_child(self.implicit,
419 self.get_implicit_deps(build_env,
423 # XXX See note above re: --implicit-cache.
425 # self.store_implicit()
427 def scanner_key(self):
430 def env_set(self, env, safe=0):
431 if safe and self.env:
435 def calculator(self):
436 import SCons.Defaults
438 env = self.env or SCons.Defaults.DefaultEnvironment()
439 return env.get_calculator()
441 def calc_signature(self, calc):
443 Select and calculate the appropriate build signature for a node.
446 calc - the signature calculation module
447 returns - the signature
450 return self._calculated_sig
451 except AttributeError:
452 if self.is_derived():
453 import SCons.Defaults
455 env = self.env or SCons.Defaults.DefaultEnvironment()
456 if env.use_build_signature():
457 sig = self.calc_bsig(calc)
459 sig = self.calc_csig(calc)
460 elif not self.rexists():
463 sig = self.calc_csig(calc)
464 self._calculated_sig = sig
471 """Delete the bsig from this node."""
473 delattr(self, 'binfo')
474 except AttributeError:
477 def calc_bsig(self, calc):
479 return self.binfo.bsig
480 except AttributeError:
481 self.binfo = self.gen_binfo(calc)
482 return self.binfo.bsig
484 def gen_binfo(self, calc):
486 Generate a node's build signature, the digested signatures
487 of its dependency files and build information.
489 node - the node whose sources will be collected
490 cache - alternate node to use for the signature cache
491 returns - the build signature
493 This no longer handles the recursive descent of the
494 node's children's signatures. We expect that they're
495 already built and updated by someone else, if that's
499 binfo = self.new_binfo()
501 children = self.children()
503 sigs = map(lambda n, c=calc: n.calc_signature(c), children)
505 binfo.bkids = map(str, children)
506 binfo.bkidsigs = sigs[:]
508 if self.has_builder():
509 executor = self.get_executor()
510 binfo.bact = str(executor)
511 binfo.bactsig = calc.module.signature(executor)
512 sigs.append(binfo.bactsig)
514 binfo.bsig = calc.module.collect(filter(None, sigs))
521 except AttributeError:
524 def calc_csig(self, calc):
528 self.binfo = self.new_binfo()
530 return self.binfo.csig
531 except AttributeError:
532 self.binfo.csig = calc.module.signature(self)
533 self.store_info(self.binfo)
534 return self.binfo.csig
536 def store_info(self, obj):
537 """Make the build signature permanent (that is, store it in the
538 .sconsign file or equivalent)."""
541 def get_stored_info(self):
544 def get_stored_implicit(self):
545 """Fetch the stored implicit dependencies"""
548 def set_precious(self, precious = 1):
549 """Set the Node's precious value."""
550 self.precious = precious
552 def set_always_build(self, always_build = 1):
553 """Set the Node's always_build value."""
554 self.always_build = always_build
557 """Does this node exists?"""
558 # All node exist by default:
562 """Does this node exist locally or in a repositiory?"""
563 # There are no repositories by default:
567 """Prepare for this Node to be created.
568 The default implemenation checks that all children either exist
572 return not node.is_derived() and \
573 not node.is_pseudo_derived() and \
574 not node.linked and \
576 missing_sources = filter(missing, self.children())
578 desc = "Source `%s' not found, needed by target `%s'." % (missing_sources[0], self)
579 raise SCons.Errors.StopError, desc
582 """Remove this Node: no-op by default."""
585 def add_dependency(self, depend):
586 """Adds dependencies."""
588 self._add_child(self.depends, self.depends_dict, depend)
591 if SCons.Util.is_List(e):
595 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)))
597 def add_ignore(self, depend):
598 """Adds dependencies to ignore."""
600 self._add_child(self.ignore, self.ignore_dict, depend)
603 if SCons.Util.is_List(e):
607 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)))
609 def add_source(self, source):
612 self._add_child(self.sources, self.sources_dict, source)
615 if SCons.Util.is_List(e):
619 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)))
621 def _add_child(self, collection, dict, child):
622 """Adds 'child' to 'collection', first checking 'dict' to see
623 if it's already present."""
624 if type(child) is not type([]):
627 if not isinstance(c, Node):
631 if not dict.has_key(c):
637 self._children_reset()
639 def add_wkid(self, wkid):
640 """Add a node to the list of kids waiting to be evaluated"""
641 if self.wkids != None:
642 self.wkids.append(wkid)
644 def _children_reset(self):
646 delattr(self, '_children')
647 except AttributeError:
650 def children(self, scan=1):
651 """Return a list of the node's direct children, minus those
652 that are ignored by this node."""
656 return self._children
657 except AttributeError:
658 c = filter(lambda x, i=self.ignore: x not in i,
659 self.all_children(scan=0))
663 def all_children(self, scan=1):
664 """Return a list of all the node's direct children."""
665 # The return list may contain duplicate Nodes, especially in
666 # source trees where there are a lot of repeated #includes
667 # of a tangle of .h files. Profiling shows, however, that
668 # eliminating the duplicates with a brute-force approach that
669 # preserves the order (that is, something like:
676 # takes more cycles than just letting the underlying methods
677 # hand back cached values if a Node's information is requested
678 # multiple times. (Other methods of removing duplicates, like
679 # using dictionary keys, lose the order, and the only ordered
680 # dictionary patterns I found all ended up using "not in"
681 # internally anyway...)
684 if self.implicit is None:
685 return self.sources + self.depends
687 return self.sources + self.depends + self.implicit
689 def get_parents(self):
690 return self.parents.keys()
692 def set_state(self, state):
698 def current(self, calc=None):
699 """Default check for whether the Node is current: unknown Node
700 subtypes are always out of date, so they will always get built."""
703 def children_are_up_to_date(self, calc):
704 """Alternate check for whether the Node is current: If all of
705 our children were up-to-date, then this Node was up-to-date, too.
707 The SCons.Node.Alias and SCons.Node.Python.Value subclasses
708 rebind their current() method to this method."""
709 # Allow the children to calculate their signatures.
710 self.binfo = self.gen_binfo(calc)
712 for kid in self.children(None):
714 if s and (not state or s > state):
716 return (state == 0 or state == SCons.Node.up_to_date)
718 def is_literal(self):
719 """Always pass the string representation of a Node to
720 the command interpreter literally."""
723 def add_pre_action(self, act):
724 """Adds an Action performed on this Node only before
726 self.pre_actions.append(act)
728 def add_post_action(self, act):
729 """Adds and Action performed on this Node only after
731 self.post_actions.append(act)
733 def render_include_tree(self):
735 Return a text representation, suitable for displaying to the
736 user, of the include tree for the sources of this node.
738 if self.is_derived() and self.env:
739 env = self.get_build_env()
740 for s in self.sources:
741 def f(node, env=env, scanner=s.source_scanner, target=self):
742 return node.get_found_includes(env, scanner, target)
743 return SCons.Util.render_tree(s, f, 1)
747 def get_abspath(self):
749 Return an absolute path to the Node. This will return simply
750 str(Node) by default, but for Node types that have a concept of
751 relative path, this might return something different.
755 def for_signature(self):
757 Return a string representation of the Node that will always
758 be the same for this particular Node, no matter what. This
759 is by contrast to the __str__() method, which might, for
760 instance, return a relative path for a file Node. The purpose
761 of this method is to generate a value to be used in signature
762 calculation for the command line used to build a target, and
763 we use this method instead of str() to avoid unnecessary
764 rebuilds. This method does not need to return something that
765 would actually work in a command line; it can return any kind of
766 nonsense, so long as it does not change.
770 def get_string(self, for_signature):
771 """This is a convenience function designed primarily to be
772 used in command generators (i.e., CommandGeneratorActions or
773 Environment variables that are callable), which are called
774 with a for_signature argument that is nonzero if the command
775 generator is being called to generate a signature for the
776 command line, which determines if we should rebuild or not.
778 Such command generators shoud use this method in preference
779 to str(Node) when converting a Node to a string, passing
780 in the for_signature parameter, such that we will call
781 Node.for_signature() or str(Node) properly, depending on whether
782 we are calculating a signature or actually constructing a
785 return self.for_signature()
788 def get_subst_proxy(self):
790 This method is expected to return an object that will function
791 exactly like this Node, except that it implements any additional
792 special features that we would like to be in effect for
793 Environment variable substitution. The principle use is that
794 some Nodes would like to implement a __getattr__() method,
795 but putting that in the Node type itself has a tendency to kill
796 performance. We instead put it in a proxy and return it from
797 this method. It is legal for this method to return self
798 if no new functionality is needed for Environment substitution.
803 if not self.exists():
804 return "building `%s' because it doesn't exist\n" % self
806 old = self.get_stored_info()
810 def dictify(kids, sigs):
812 for k, s in zip(kids, sigs):
816 osig = dictify(old.bkids, old.bkidsigs)
818 newkids = map(str, self.binfo.bkids)
819 nsig = dictify(newkids, self.binfo.bkidsigs)
821 lines = map(lambda x: "`%s' is no longer a dependency\n" % x,
822 filter(lambda x, nk=newkids: not x in nk, old.bkids))
825 if not k in old.bkids:
826 lines.append("`%s' is a new dependency\n" % k)
827 elif osig[k] != nsig[k]:
828 lines.append("`%s' changed\n" % k)
831 newact, newactsig = self.binfo.bact, self.binfo.bactsig
832 if old.bact != newact:
833 lines.append("the build action changed:\n" +
834 "%sold: %s\n" % (' '*15, old.bact) +
835 "%snew: %s\n" % (' '*15, newact))
838 lines.append("the dependency order changed:\n" +
839 "%sold: %s\n" % (' '*15, old.bkids) +
840 "%snew: %s\n" % (' '*15, newkids))
842 preamble = "rebuilding `%s' because" % self
844 return "%s %s" % (preamble, lines[0])
846 lines = ["%s:\n" % preamble] + lines
847 return string.join(lines, ' '*11)
849 def get_children(node, parent): return node.children()
850 def ignore_cycle(node, stack): pass
851 def do_nothing(node, parent): pass
854 """An iterator for walking a Node tree.
856 This is depth-first, children are visited before the parent.
857 The Walker object can be initialized with any node, and
858 returns the next node on the descent with each next() call.
859 'kids_func' is an optional function that will be called to
860 get the children of a node instead of calling 'children'.
861 'cycle_func' is an optional function that will be called
862 when a cycle is detected.
864 This class does not get caught in node cycles caused, for example,
865 by C header file include loops.
867 def __init__(self, node, kids_func=get_children,
868 cycle_func=ignore_cycle,
869 eval_func=do_nothing):
870 self.kids_func = kids_func
871 self.cycle_func = cycle_func
872 self.eval_func = eval_func
873 node.wkids = copy.copy(kids_func(node, None))
875 self.history = {} # used to efficiently detect and avoid cycles
876 self.history[node] = None
879 """Return the next node for this walk of the tree.
881 This function is intentionally iterative, not recursive,
882 to sidestep any issues of stack size limitations.
886 if self.stack[-1].wkids:
887 node = self.stack[-1].wkids.pop(0)
888 if not self.stack[-1].wkids:
889 self.stack[-1].wkids = None
890 if self.history.has_key(node):
891 self.cycle_func(node, self.stack)
893 node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
894 self.stack.append(node)
895 self.history[node] = None
897 node = self.stack.pop()
898 del self.history[node]
901 parent = self.stack[-1]
904 self.eval_func(node, parent)
908 return not self.stack
911 arg2nodes_lookups = []