You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1734 lines
60 KiB

6 years ago
  1. """SCons.Node
  2. The Node package for the SCons software construction utility.
  3. This is, in many ways, the heart of SCons.
  4. A Node is where we encapsulate all of the dependency information about
  5. any thing that SCons can build, or about any thing which SCons can use
  6. to build some other thing. The canonical "thing," of course, is a file,
  7. but a Node can also represent something remote (like a web page) or
  8. something completely abstract (like an Alias).
  9. Each specific type of "thing" is specifically represented by a subclass
  10. of the Node base class: Node.FS.File for files, Node.Alias for aliases,
  11. etc. Dependency information is kept here in the base class, and
  12. information specific to files/aliases/etc. is in the subclass. The
  13. goal, if we've done this correctly, is that any type of "thing" should
  14. be able to depend on any other type of "thing."
  15. """
  16. from __future__ import print_function
  17. #
  18. # Copyright (c) 2001 - 2017 The SCons Foundation
  19. #
  20. # Permission is hereby granted, free of charge, to any person obtaining
  21. # a copy of this software and associated documentation files (the
  22. # "Software"), to deal in the Software without restriction, including
  23. # without limitation the rights to use, copy, modify, merge, publish,
  24. # distribute, sublicense, and/or sell copies of the Software, and to
  25. # permit persons to whom the Software is furnished to do so, subject to
  26. # the following conditions:
  27. #
  28. # The above copyright notice and this permission notice shall be included
  29. # in all copies or substantial portions of the Software.
  30. #
  31. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  32. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  33. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  34. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  35. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  36. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  37. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  38. __revision__ = "src/engine/SCons/Node/__init__.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  39. import collections
  40. import copy
  41. from itertools import chain
  42. import SCons.Debug
  43. from SCons.Debug import logInstanceCreation
  44. import SCons.Executor
  45. import SCons.Memoize
  46. import SCons.Util
  47. from SCons.Debug import Trace
  48. from SCons.compat import with_metaclass, NoSlotsPyPy
  49. print_duplicate = 0
  50. def classname(obj):
  51. return str(obj.__class__).split('.')[-1]
  52. # Set to false if we're doing a dry run. There's more than one of these
  53. # little treats
  54. do_store_info = True
  55. # Node states
  56. #
  57. # These are in "priority" order, so that the maximum value for any
  58. # child/dependency of a node represents the state of that node if
  59. # it has no builder of its own. The canonical example is a file
  60. # system directory, which is only up to date if all of its children
  61. # were up to date.
  62. no_state = 0
  63. pending = 1
  64. executing = 2
  65. up_to_date = 3
  66. executed = 4
  67. failed = 5
  68. StateString = {
  69. 0 : "no_state",
  70. 1 : "pending",
  71. 2 : "executing",
  72. 3 : "up_to_date",
  73. 4 : "executed",
  74. 5 : "failed",
  75. }
  76. # controls whether implicit dependencies are cached:
  77. implicit_cache = 0
  78. # controls whether implicit dep changes are ignored:
  79. implicit_deps_unchanged = 0
  80. # controls whether the cached implicit deps are ignored:
  81. implicit_deps_changed = 0
  82. # A variable that can be set to an interface-specific function be called
  83. # to annotate a Node with information about its creation.
  84. def do_nothing(node): pass
  85. Annotate = do_nothing
  86. # Gets set to 'True' if we're running in interactive mode. Is
  87. # currently used to release parts of a target's info during
  88. # clean builds and update runs (see release_target_info).
  89. interactive = False
  90. def is_derived_none(node):
  91. raise NotImplementedError
  92. def is_derived_node(node):
  93. """
  94. Returns true if this node is derived (i.e. built).
  95. """
  96. return node.has_builder() or node.side_effect
  97. _is_derived_map = {0 : is_derived_none,
  98. 1 : is_derived_node}
  99. def exists_none(node):
  100. raise NotImplementedError
  101. def exists_always(node):
  102. return 1
  103. def exists_base(node):
  104. return node.stat() is not None
  105. def exists_entry(node):
  106. """Return if the Entry exists. Check the file system to see
  107. what we should turn into first. Assume a file if there's no
  108. directory."""
  109. node.disambiguate()
  110. return _exists_map[node._func_exists](node)
  111. def exists_file(node):
  112. # Duplicate from source path if we are set up to do this.
  113. if node.duplicate and not node.is_derived() and not node.linked:
  114. src = node.srcnode()
  115. if src is not node:
  116. # At this point, src is meant to be copied in a variant directory.
  117. src = src.rfile()
  118. if src.get_abspath() != node.get_abspath():
  119. if src.exists():
  120. node.do_duplicate(src)
  121. # Can't return 1 here because the duplication might
  122. # not actually occur if the -n option is being used.
  123. else:
  124. # The source file does not exist. Make sure no old
  125. # copy remains in the variant directory.
  126. if print_duplicate:
  127. print("dup: no src for %s, unlinking old variant copy"%self)
  128. if exists_base(node) or node.islink():
  129. node.fs.unlink(node.get_internal_path())
  130. # Return None explicitly because the Base.exists() call
  131. # above will have cached its value if the file existed.
  132. return None
  133. return exists_base(node)
  134. _exists_map = {0 : exists_none,
  135. 1 : exists_always,
  136. 2 : exists_base,
  137. 3 : exists_entry,
  138. 4 : exists_file}
  139. def rexists_none(node):
  140. raise NotImplementedError
  141. def rexists_node(node):
  142. return node.exists()
  143. def rexists_base(node):
  144. return node.rfile().exists()
  145. _rexists_map = {0 : rexists_none,
  146. 1 : rexists_node,
  147. 2 : rexists_base}
  148. def get_contents_none(node):
  149. raise NotImplementedError
  150. def get_contents_entry(node):
  151. """Fetch the contents of the entry. Returns the exact binary
  152. contents of the file."""
  153. try:
  154. node = node.disambiguate(must_exist=1)
  155. except SCons.Errors.UserError:
  156. # There was nothing on disk with which to disambiguate
  157. # this entry. Leave it as an Entry, but return a null
  158. # string so calls to get_contents() in emitters and the
  159. # like (e.g. in qt.py) don't have to disambiguate by hand
  160. # or catch the exception.
  161. return ''
  162. else:
  163. return _get_contents_map[node._func_get_contents](node)
  164. def get_contents_dir(node):
  165. """Return content signatures and names of all our children
  166. separated by new-lines. Ensure that the nodes are sorted."""
  167. contents = []
  168. for n in sorted(node.children(), key=lambda t: t.name):
  169. contents.append('%s %s\n' % (n.get_csig(), n.name))
  170. return ''.join(contents)
  171. def get_contents_file(node):
  172. if not node.rexists():
  173. return b''
  174. fname = node.rfile().get_abspath()
  175. try:
  176. with open(fname, "rb") as fp:
  177. contents = fp.read()
  178. except EnvironmentError as e:
  179. if not e.filename:
  180. e.filename = fname
  181. raise
  182. return contents
  183. _get_contents_map = {0 : get_contents_none,
  184. 1 : get_contents_entry,
  185. 2 : get_contents_dir,
  186. 3 : get_contents_file}
  187. def target_from_source_none(node, prefix, suffix, splitext):
  188. raise NotImplementedError
  189. def target_from_source_base(node, prefix, suffix, splitext):
  190. return node.dir.Entry(prefix + splitext(node.name)[0] + suffix)
  191. _target_from_source_map = {0 : target_from_source_none,
  192. 1 : target_from_source_base}
  193. #
  194. # The new decider subsystem for Nodes
  195. #
  196. # We would set and overwrite the changed_since_last_build function
  197. # before, but for being able to use slots (less memory!) we now have
  198. # a dictionary of the different decider functions. Then in the Node
  199. # subclasses we simply store the index to the decider that should be
  200. # used by it.
  201. #
  202. #
  203. # First, the single decider functions
  204. #
  205. def changed_since_last_build_node(node, target, prev_ni):
  206. """
  207. Must be overridden in a specific subclass to return True if this
  208. Node (a dependency) has changed since the last time it was used
  209. to build the specified target. prev_ni is this Node's state (for
  210. example, its file timestamp, length, maybe content signature)
  211. as of the last time the target was built.
  212. Note that this method is called through the dependency, not the
  213. target, because a dependency Node must be able to use its own
  214. logic to decide if it changed. For example, File Nodes need to
  215. obey if we're configured to use timestamps, but Python Value Nodes
  216. never use timestamps and always use the content. If this method
  217. were called through the target, then each Node's implementation
  218. of this method would have to have more complicated logic to
  219. handle all the different Node types on which it might depend.
  220. """
  221. raise NotImplementedError
  222. def changed_since_last_build_alias(node, target, prev_ni):
  223. cur_csig = node.get_csig()
  224. try:
  225. return cur_csig != prev_ni.csig
  226. except AttributeError:
  227. return 1
  228. def changed_since_last_build_entry(node, target, prev_ni):
  229. node.disambiguate()
  230. return _decider_map[node.changed_since_last_build](node, target, prev_ni)
  231. def changed_since_last_build_state_changed(node, target, prev_ni):
  232. return (node.state != SCons.Node.up_to_date)
  233. def decide_source(node, target, prev_ni):
  234. return target.get_build_env().decide_source(node, target, prev_ni)
  235. def decide_target(node, target, prev_ni):
  236. return target.get_build_env().decide_target(node, target, prev_ni)
  237. def changed_since_last_build_python(node, target, prev_ni):
  238. cur_csig = node.get_csig()
  239. try:
  240. return cur_csig != prev_ni.csig
  241. except AttributeError:
  242. return 1
  243. #
  244. # Now, the mapping from indices to decider functions
  245. #
  246. _decider_map = {0 : changed_since_last_build_node,
  247. 1 : changed_since_last_build_alias,
  248. 2 : changed_since_last_build_entry,
  249. 3 : changed_since_last_build_state_changed,
  250. 4 : decide_source,
  251. 5 : decide_target,
  252. 6 : changed_since_last_build_python}
  253. do_store_info = True
  254. #
  255. # The new store_info subsystem for Nodes
  256. #
  257. # We would set and overwrite the store_info function
  258. # before, but for being able to use slots (less memory!) we now have
  259. # a dictionary of the different functions. Then in the Node
  260. # subclasses we simply store the index to the info method that should be
  261. # used by it.
  262. #
  263. #
  264. # First, the single info functions
  265. #
  266. def store_info_pass(node):
  267. pass
  268. def store_info_file(node):
  269. # Merge our build information into the already-stored entry.
  270. # This accommodates "chained builds" where a file that's a target
  271. # in one build (SConstruct file) is a source in a different build.
  272. # See test/chained-build.py for the use case.
  273. if do_store_info:
  274. node.dir.sconsign().store_info(node.name, node)
  275. store_info_map = {0 : store_info_pass,
  276. 1 : store_info_file}
  277. # Classes for signature info for Nodes.
  278. class NodeInfoBase(object):
  279. """
  280. The generic base class for signature information for a Node.
  281. Node subclasses should subclass NodeInfoBase to provide their own
  282. logic for dealing with their own Node-specific signature information.
  283. """
  284. __slots__ = ('__weakref__',)
  285. current_version_id = 2
  286. def update(self, node):
  287. try:
  288. field_list = self.field_list
  289. except AttributeError:
  290. return
  291. for f in field_list:
  292. try:
  293. delattr(self, f)
  294. except AttributeError:
  295. pass
  296. try:
  297. func = getattr(node, 'get_' + f)
  298. except AttributeError:
  299. pass
  300. else:
  301. setattr(self, f, func())
  302. def convert(self, node, val):
  303. pass
  304. def merge(self, other):
  305. """
  306. Merge the fields of another object into this object. Already existing
  307. information is overwritten by the other instance's data.
  308. WARNING: If a '__dict__' slot is added, it should be updated instead of
  309. replaced.
  310. """
  311. state = other.__getstate__()
  312. self.__setstate__(state)
  313. def format(self, field_list=None, names=0):
  314. if field_list is None:
  315. try:
  316. field_list = self.field_list
  317. except AttributeError:
  318. field_list = list(getattr(self, '__dict__', {}).keys())
  319. for obj in type(self).mro():
  320. for slot in getattr(obj, '__slots__', ()):
  321. if slot not in ('__weakref__', '__dict__'):
  322. field_list.append(slot)
  323. field_list.sort()
  324. fields = []
  325. for field in field_list:
  326. try:
  327. f = getattr(self, field)
  328. except AttributeError:
  329. f = None
  330. f = str(f)
  331. if names:
  332. f = field + ': ' + f
  333. fields.append(f)
  334. return fields
  335. def __getstate__(self):
  336. """
  337. Return all fields that shall be pickled. Walk the slots in the class
  338. hierarchy and add those to the state dictionary. If a '__dict__' slot is
  339. available, copy all entries to the dictionary. Also include the version
  340. id, which is fixed for all instances of a class.
  341. """
  342. state = getattr(self, '__dict__', {}).copy()
  343. for obj in type(self).mro():
  344. for name in getattr(obj,'__slots__',()):
  345. if hasattr(self, name):
  346. state[name] = getattr(self, name)
  347. state['_version_id'] = self.current_version_id
  348. try:
  349. del state['__weakref__']
  350. except KeyError:
  351. pass
  352. return state
  353. def __setstate__(self, state):
  354. """
  355. Restore the attributes from a pickled state. The version is discarded.
  356. """
  357. # TODO check or discard version
  358. del state['_version_id']
  359. for key, value in state.items():
  360. if key not in ('__weakref__',):
  361. setattr(self, key, value)
  362. class BuildInfoBase(object):
  363. """
  364. The generic base class for build information for a Node.
  365. This is what gets stored in a .sconsign file for each target file.
  366. It contains a NodeInfo instance for this node (signature information
  367. that's specific to the type of Node) and direct attributes for the
  368. generic build stuff we have to track: sources, explicit dependencies,
  369. implicit dependencies, and action information.
  370. """
  371. __slots__ = ("bsourcesigs", "bdependsigs", "bimplicitsigs", "bactsig",
  372. "bsources", "bdepends", "bact", "bimplicit", "__weakref__")
  373. current_version_id = 2
  374. def __init__(self):
  375. # Create an object attribute from the class attribute so it ends up
  376. # in the pickled data in the .sconsign file.
  377. self.bsourcesigs = []
  378. self.bdependsigs = []
  379. self.bimplicitsigs = []
  380. self.bactsig = None
  381. def merge(self, other):
  382. """
  383. Merge the fields of another object into this object. Already existing
  384. information is overwritten by the other instance's data.
  385. WARNING: If a '__dict__' slot is added, it should be updated instead of
  386. replaced.
  387. """
  388. state = other.__getstate__()
  389. self.__setstate__(state)
  390. def __getstate__(self):
  391. """
  392. Return all fields that shall be pickled. Walk the slots in the class
  393. hierarchy and add those to the state dictionary. If a '__dict__' slot is
  394. available, copy all entries to the dictionary. Also include the version
  395. id, which is fixed for all instances of a class.
  396. """
  397. state = getattr(self, '__dict__', {}).copy()
  398. for obj in type(self).mro():
  399. for name in getattr(obj,'__slots__',()):
  400. if hasattr(self, name):
  401. state[name] = getattr(self, name)
  402. state['_version_id'] = self.current_version_id
  403. try:
  404. del state['__weakref__']
  405. except KeyError:
  406. pass
  407. return state
  408. def __setstate__(self, state):
  409. """
  410. Restore the attributes from a pickled state.
  411. """
  412. # TODO check or discard version
  413. del state['_version_id']
  414. for key, value in state.items():
  415. if key not in ('__weakref__',):
  416. setattr(self, key, value)
  417. class Node(object, with_metaclass(NoSlotsPyPy)):
  418. """The base Node class, for entities that we know how to
  419. build, or use to build other Nodes.
  420. """
  421. __slots__ = ['sources',
  422. 'sources_set',
  423. '_specific_sources',
  424. 'depends',
  425. 'depends_set',
  426. 'ignore',
  427. 'ignore_set',
  428. 'prerequisites',
  429. 'implicit',
  430. 'waiting_parents',
  431. 'waiting_s_e',
  432. 'ref_count',
  433. 'wkids',
  434. 'env',
  435. 'state',
  436. 'precious',
  437. 'noclean',
  438. 'nocache',
  439. 'cached',
  440. 'always_build',
  441. 'includes',
  442. 'attributes',
  443. 'side_effect',
  444. 'side_effects',
  445. 'linked',
  446. '_memo',
  447. 'executor',
  448. 'binfo',
  449. 'ninfo',
  450. 'builder',
  451. 'is_explicit',
  452. 'implicit_set',
  453. 'changed_since_last_build',
  454. 'store_info',
  455. 'pseudo',
  456. '_tags',
  457. '_func_is_derived',
  458. '_func_exists',
  459. '_func_rexists',
  460. '_func_get_contents',
  461. '_func_target_from_source']
  462. class Attrs(object):
  463. __slots__ = ('shared', '__dict__')
  464. def __init__(self):
  465. if SCons.Debug.track_instances: logInstanceCreation(self, 'Node.Node')
  466. # Note that we no longer explicitly initialize a self.builder
  467. # attribute to None here. That's because the self.builder
  468. # attribute may be created on-the-fly later by a subclass (the
  469. # canonical example being a builder to fetch a file from a
  470. # source code system like CVS or Subversion).
  471. # Each list of children that we maintain is accompanied by a
  472. # dictionary used to look up quickly whether a node is already
  473. # present in the list. Empirical tests showed that it was
  474. # fastest to maintain them as side-by-side Node attributes in
  475. # this way, instead of wrapping up each list+dictionary pair in
  476. # a class. (Of course, we could always still do that in the
  477. # future if we had a good reason to...).
  478. self.sources = [] # source files used to build node
  479. self.sources_set = set()
  480. self._specific_sources = False
  481. self.depends = [] # explicit dependencies (from Depends)
  482. self.depends_set = set()
  483. self.ignore = [] # dependencies to ignore
  484. self.ignore_set = set()
  485. self.prerequisites = None
  486. self.implicit = None # implicit (scanned) dependencies (None means not scanned yet)
  487. self.waiting_parents = set()
  488. self.waiting_s_e = set()
  489. self.ref_count = 0
  490. self.wkids = None # Kids yet to walk, when it's an array
  491. self.env = None
  492. self.state = no_state
  493. self.precious = None
  494. self.pseudo = False
  495. self.noclean = 0
  496. self.nocache = 0
  497. self.cached = 0 # is this node pulled from cache?
  498. self.always_build = None
  499. self.includes = None
  500. self.attributes = self.Attrs() # Generic place to stick information about the Node.
  501. self.side_effect = 0 # true iff this node is a side effect
  502. self.side_effects = [] # the side effects of building this target
  503. self.linked = 0 # is this node linked to the variant directory?
  504. self.changed_since_last_build = 0
  505. self.store_info = 0
  506. self._tags = None
  507. self._func_is_derived = 1
  508. self._func_exists = 1
  509. self._func_rexists = 1
  510. self._func_get_contents = 0
  511. self._func_target_from_source = 0
  512. self.clear_memoized_values()
  513. # Let the interface in which the build engine is embedded
  514. # annotate this Node with its own info (like a description of
  515. # what line in what file created the node, for example).
  516. Annotate(self)
  517. def disambiguate(self, must_exist=None):
  518. return self
  519. def get_suffix(self):
  520. return ''
  521. @SCons.Memoize.CountMethodCall
  522. def get_build_env(self):
  523. """Fetch the appropriate Environment to build this node.
  524. """
  525. try:
  526. return self._memo['get_build_env']
  527. except KeyError:
  528. pass
  529. result = self.get_executor().get_build_env()
  530. self._memo['get_build_env'] = result
  531. return result
  532. def get_build_scanner_path(self, scanner):
  533. """Fetch the appropriate scanner path for this node."""
  534. return self.get_executor().get_build_scanner_path(scanner)
  535. def set_executor(self, executor):
  536. """Set the action executor for this node."""
  537. self.executor = executor
  538. def get_executor(self, create=1):
  539. """Fetch the action executor for this node. Create one if
  540. there isn't already one, and requested to do so."""
  541. try:
  542. executor = self.executor
  543. except AttributeError:
  544. if not create:
  545. raise
  546. try:
  547. act = self.builder.action
  548. except AttributeError:
  549. executor = SCons.Executor.Null(targets=[self])
  550. else:
  551. executor = SCons.Executor.Executor(act,
  552. self.env or self.builder.env,
  553. [self.builder.overrides],
  554. [self],
  555. self.sources)
  556. self.executor = executor
  557. return executor
  558. def executor_cleanup(self):
  559. """Let the executor clean up any cached information."""
  560. try:
  561. executor = self.get_executor(create=None)
  562. except AttributeError:
  563. pass
  564. else:
  565. if executor is not None:
  566. executor.cleanup()
  567. def reset_executor(self):
  568. "Remove cached executor; forces recompute when needed."
  569. try:
  570. delattr(self, 'executor')
  571. except AttributeError:
  572. pass
  573. def push_to_cache(self):
  574. """Try to push a node into a cache
  575. """
  576. pass
  577. def retrieve_from_cache(self):
  578. """Try to retrieve the node's content from a cache
  579. This method is called from multiple threads in a parallel build,
  580. so only do thread safe stuff here. Do thread unsafe stuff in
  581. built().
  582. Returns true if the node was successfully retrieved.
  583. """
  584. return 0
  585. #
  586. # Taskmaster interface subsystem
  587. #
  588. def make_ready(self):
  589. """Get a Node ready for evaluation.
  590. This is called before the Taskmaster decides if the Node is
  591. up-to-date or not. Overriding this method allows for a Node
  592. subclass to be disambiguated if necessary, or for an implicit
  593. source builder to be attached.
  594. """
  595. pass
  596. def prepare(self):
  597. """Prepare for this Node to be built.
  598. This is called after the Taskmaster has decided that the Node
  599. is out-of-date and must be rebuilt, but before actually calling
  600. the method to build the Node.
  601. This default implementation checks that explicit or implicit
  602. dependencies either exist or are derived, and initializes the
  603. BuildInfo structure that will hold the information about how
  604. this node is, uh, built.
  605. (The existence of source files is checked separately by the
  606. Executor, which aggregates checks for all of the targets built
  607. by a specific action.)
  608. Overriding this method allows for for a Node subclass to remove
  609. the underlying file from the file system. Note that subclass
  610. methods should call this base class method to get the child
  611. check and the BuildInfo structure.
  612. """
  613. if self.depends is not None:
  614. for d in self.depends:
  615. if d.missing():
  616. msg = "Explicit dependency `%s' not found, needed by target `%s'."
  617. raise SCons.Errors.StopError(msg % (d, self))
  618. if self.implicit is not None:
  619. for i in self.implicit:
  620. if i.missing():
  621. msg = "Implicit dependency `%s' not found, needed by target `%s'."
  622. raise SCons.Errors.StopError(msg % (i, self))
  623. self.binfo = self.get_binfo()
  624. def build(self, **kw):
  625. """Actually build the node.
  626. This is called by the Taskmaster after it's decided that the
  627. Node is out-of-date and must be rebuilt, and after the prepare()
  628. method has gotten everything, uh, prepared.
  629. This method is called from multiple threads in a parallel build,
  630. so only do thread safe stuff here. Do thread unsafe stuff
  631. in built().
  632. """
  633. try:
  634. self.get_executor()(self, **kw)
  635. except SCons.Errors.BuildError as e:
  636. e.node = self
  637. raise
  638. def built(self):
  639. """Called just after this node is successfully built."""
  640. # Clear the implicit dependency caches of any Nodes
  641. # waiting for this Node to be built.
  642. for parent in self.waiting_parents:
  643. parent.implicit = None
  644. self.clear()
  645. if self.pseudo:
  646. if self.exists():
  647. raise SCons.Errors.UserError("Pseudo target " + str(self) + " must not exist")
  648. else:
  649. if not self.exists() and do_store_info:
  650. SCons.Warnings.warn(SCons.Warnings.TargetNotBuiltWarning,
  651. "Cannot find target " + str(self) + " after building")
  652. self.ninfo.update(self)
  653. def visited(self):
  654. """Called just after this node has been visited (with or
  655. without a build)."""
  656. try:
  657. binfo = self.binfo
  658. except AttributeError:
  659. # Apparently this node doesn't need build info, so
  660. # don't bother calculating or storing it.
  661. pass
  662. else:
  663. self.ninfo.update(self)
  664. SCons.Node.store_info_map[self.store_info](self)
  665. def release_target_info(self):
  666. """Called just after this node has been marked
  667. up-to-date or was built completely.
  668. This is where we try to release as many target node infos
  669. as possible for clean builds and update runs, in order
  670. to minimize the overall memory consumption.
  671. By purging attributes that aren't needed any longer after
  672. a Node (=File) got built, we don't have to care that much how
  673. many KBytes a Node actually requires...as long as we free
  674. the memory shortly afterwards.
  675. @see: built() and File.release_target_info()
  676. """
  677. pass
  678. #
  679. #
  680. #
  681. def add_to_waiting_s_e(self, node):
  682. self.waiting_s_e.add(node)
  683. def add_to_waiting_parents(self, node):
  684. """
  685. Returns the number of nodes added to our waiting parents list:
  686. 1 if we add a unique waiting parent, 0 if not. (Note that the
  687. returned values are intended to be used to increment a reference
  688. count, so don't think you can "clean up" this function by using
  689. True and False instead...)
  690. """
  691. wp = self.waiting_parents
  692. if node in wp:
  693. return 0
  694. wp.add(node)
  695. return 1
  696. def postprocess(self):
  697. """Clean up anything we don't need to hang onto after we've
  698. been built."""
  699. self.executor_cleanup()
  700. self.waiting_parents = set()
  701. def clear(self):
  702. """Completely clear a Node of all its cached state (so that it
  703. can be re-evaluated by interfaces that do continuous integration
  704. builds).
  705. """
  706. # The del_binfo() call here isn't necessary for normal execution,
  707. # but is for interactive mode, where we might rebuild the same
  708. # target and need to start from scratch.
  709. self.del_binfo()
  710. self.clear_memoized_values()
  711. self.ninfo = self.new_ninfo()
  712. self.executor_cleanup()
  713. try:
  714. delattr(self, '_calculated_sig')
  715. except AttributeError:
  716. pass
  717. self.includes = None
  718. def clear_memoized_values(self):
  719. self._memo = {}
  720. def builder_set(self, builder):
  721. self.builder = builder
  722. try:
  723. del self.executor
  724. except AttributeError:
  725. pass
  726. def has_builder(self):
  727. """Return whether this Node has a builder or not.
  728. In Boolean tests, this turns out to be a *lot* more efficient
  729. than simply examining the builder attribute directly ("if
  730. node.builder: ..."). When the builder attribute is examined
  731. directly, it ends up calling __getattr__ for both the __len__
  732. and __nonzero__ attributes on instances of our Builder Proxy
  733. class(es), generating a bazillion extra calls and slowing
  734. things down immensely.
  735. """
  736. try:
  737. b = self.builder
  738. except AttributeError:
  739. # There was no explicit builder for this Node, so initialize
  740. # the self.builder attribute to None now.
  741. b = self.builder = None
  742. return b is not None
  743. def set_explicit(self, is_explicit):
  744. self.is_explicit = is_explicit
  745. def has_explicit_builder(self):
  746. """Return whether this Node has an explicit builder
  747. This allows an internal Builder created by SCons to be marked
  748. non-explicit, so that it can be overridden by an explicit
  749. builder that the user supplies (the canonical example being
  750. directories)."""
  751. try:
  752. return self.is_explicit
  753. except AttributeError:
  754. self.is_explicit = None
  755. return self.is_explicit
  756. def get_builder(self, default_builder=None):
  757. """Return the set builder, or a specified default value"""
  758. try:
  759. return self.builder
  760. except AttributeError:
  761. return default_builder
  762. multiple_side_effect_has_builder = has_builder
  763. def is_derived(self):
  764. """
  765. Returns true if this node is derived (i.e. built).
  766. This should return true only for nodes whose path should be in
  767. the variant directory when duplicate=0 and should contribute their build
  768. signatures when they are used as source files to other derived files. For
  769. example: source with source builders are not derived in this sense,
  770. and hence should not return true.
  771. """
  772. return _is_derived_map[self._func_is_derived](self)
  773. def alter_targets(self):
  774. """Return a list of alternate targets for this Node.
  775. """
  776. return [], None
  777. def get_found_includes(self, env, scanner, path):
  778. """Return the scanned include lines (implicit dependencies)
  779. found in this node.
  780. The default is no implicit dependencies. We expect this method
  781. to be overridden by any subclass that can be scanned for
  782. implicit dependencies.
  783. """
  784. return []
  785. def get_implicit_deps(self, env, initial_scanner, path_func, kw = {}):
  786. """Return a list of implicit dependencies for this node.
  787. This method exists to handle recursive invocation of the scanner
  788. on the implicit dependencies returned by the scanner, if the
  789. scanner's recursive flag says that we should.
  790. """
  791. nodes = [self]
  792. seen = set(nodes)
  793. dependencies = []
  794. path_memo = {}
  795. root_node_scanner = self._get_scanner(env, initial_scanner, None, kw)
  796. while nodes:
  797. node = nodes.pop(0)
  798. scanner = node._get_scanner(env, initial_scanner, root_node_scanner, kw)
  799. if not scanner:
  800. continue
  801. try:
  802. path = path_memo[scanner]
  803. except KeyError:
  804. path = path_func(scanner)
  805. path_memo[scanner] = path
  806. included_deps = [x for x in node.get_found_includes(env, scanner, path) if x not in seen]
  807. if included_deps:
  808. dependencies.extend(included_deps)
  809. seen.update(included_deps)
  810. nodes.extend(scanner.recurse_nodes(included_deps))
  811. return dependencies
  812. def _get_scanner(self, env, initial_scanner, root_node_scanner, kw):
  813. if initial_scanner:
  814. # handle explicit scanner case
  815. scanner = initial_scanner.select(self)
  816. else:
  817. # handle implicit scanner case
  818. scanner = self.get_env_scanner(env, kw)
  819. if scanner:
  820. scanner = scanner.select(self)
  821. if not scanner:
  822. # no scanner could be found for the given node's scanner key;
  823. # thus, make an attempt at using a default.
  824. scanner = root_node_scanner
  825. return scanner
  826. def get_env_scanner(self, env, kw={}):
  827. return env.get_scanner(self.scanner_key())
  828. def get_target_scanner(self):
  829. return self.builder.target_scanner
  830. def get_source_scanner(self, node):
  831. """Fetch the source scanner for the specified node
  832. NOTE: "self" is the target being built, "node" is
  833. the source file for which we want to fetch the scanner.
  834. Implies self.has_builder() is true; again, expect to only be
  835. called from locations where this is already verified.
  836. This function may be called very often; it attempts to cache
  837. the scanner found to improve performance.
  838. """
  839. scanner = None
  840. try:
  841. scanner = self.builder.source_scanner
  842. except AttributeError:
  843. pass
  844. if not scanner:
  845. # The builder didn't have an explicit scanner, so go look up
  846. # a scanner from env['SCANNERS'] based on the node's scanner
  847. # key (usually the file extension).
  848. scanner = self.get_env_scanner(self.get_build_env())
  849. if scanner:
  850. scanner = scanner.select(node)
  851. return scanner
  852. def add_to_implicit(self, deps):
  853. if not hasattr(self, 'implicit') or self.implicit is None:
  854. self.implicit = []
  855. self.implicit_set = set()
  856. self._children_reset()
  857. self._add_child(self.implicit, self.implicit_set, deps)
  858. def scan(self):
  859. """Scan this node's dependents for implicit dependencies."""
  860. # Don't bother scanning non-derived files, because we don't
  861. # care what their dependencies are.
  862. # Don't scan again, if we already have scanned.
  863. if self.implicit is not None:
  864. return
  865. self.implicit = []
  866. self.implicit_set = set()
  867. self._children_reset()
  868. if not self.has_builder():
  869. return
  870. build_env = self.get_build_env()
  871. executor = self.get_executor()
  872. # Here's where we implement --implicit-cache.
  873. if implicit_cache and not implicit_deps_changed:
  874. implicit = self.get_stored_implicit()
  875. if implicit is not None:
  876. # We now add the implicit dependencies returned from the
  877. # stored .sconsign entry to have already been converted
  878. # to Nodes for us. (We used to run them through a
  879. # source_factory function here.)
  880. # Update all of the targets with them. This
  881. # essentially short-circuits an N*M scan of the
  882. # sources for each individual target, which is a hell
  883. # of a lot more efficient.
  884. for tgt in executor.get_all_targets():
  885. tgt.add_to_implicit(implicit)
  886. if implicit_deps_unchanged or self.is_up_to_date():
  887. return
  888. # one of this node's sources has changed,
  889. # so we must recalculate the implicit deps for all targets
  890. for tgt in executor.get_all_targets():
  891. tgt.implicit = []
  892. tgt.implicit_set = set()
  893. # Have the executor scan the sources.
  894. executor.scan_sources(self.builder.source_scanner)
  895. # If there's a target scanner, have the executor scan the target
  896. # node itself and associated targets that might be built.
  897. scanner = self.get_target_scanner()
  898. if scanner:
  899. executor.scan_targets(scanner)
  900. def scanner_key(self):
  901. return None
  902. def select_scanner(self, scanner):
  903. """Selects a scanner for this Node.
  904. This is a separate method so it can be overridden by Node
  905. subclasses (specifically, Node.FS.Dir) that *must* use their
  906. own Scanner and don't select one the Scanner.Selector that's
  907. configured for the target.
  908. """
  909. return scanner.select(self)
  910. def env_set(self, env, safe=0):
  911. if safe and self.env:
  912. return
  913. self.env = env
  914. #
  915. # SIGNATURE SUBSYSTEM
  916. #
  917. NodeInfo = NodeInfoBase
  918. BuildInfo = BuildInfoBase
  919. def new_ninfo(self):
  920. ninfo = self.NodeInfo()
  921. return ninfo
  922. def get_ninfo(self):
  923. try:
  924. return self.ninfo
  925. except AttributeError:
  926. self.ninfo = self.new_ninfo()
  927. return self.ninfo
  928. def new_binfo(self):
  929. binfo = self.BuildInfo()
  930. return binfo
  931. def get_binfo(self):
  932. """
  933. Fetch a node's build information.
  934. node - the node whose sources will be collected
  935. cache - alternate node to use for the signature cache
  936. returns - the build signature
  937. This no longer handles the recursive descent of the
  938. node's children's signatures. We expect that they're
  939. already built and updated by someone else, if that's
  940. what's wanted.
  941. """
  942. try:
  943. return self.binfo
  944. except AttributeError:
  945. pass
  946. binfo = self.new_binfo()
  947. self.binfo = binfo
  948. executor = self.get_executor()
  949. ignore_set = self.ignore_set
  950. if self.has_builder():
  951. binfo.bact = str(executor)
  952. binfo.bactsig = SCons.Util.MD5signature(executor.get_contents())
  953. if self._specific_sources:
  954. sources = [ s for s in self.sources if not s in ignore_set]
  955. else:
  956. sources = executor.get_unignored_sources(self, self.ignore)
  957. seen = set()
  958. binfo.bsources = [s for s in sources if s not in seen and not seen.add(s)]
  959. binfo.bsourcesigs = [s.get_ninfo() for s in binfo.bsources]
  960. binfo.bdepends = self.depends
  961. binfo.bdependsigs = [d.get_ninfo() for d in self.depends if d not in ignore_set]
  962. binfo.bimplicit = self.implicit or []
  963. binfo.bimplicitsigs = [i.get_ninfo() for i in binfo.bimplicit if i not in ignore_set]
  964. return binfo
  965. def del_binfo(self):
  966. """Delete the build info from this node."""
  967. try:
  968. delattr(self, 'binfo')
  969. except AttributeError:
  970. pass
  971. def get_csig(self):
  972. try:
  973. return self.ninfo.csig
  974. except AttributeError:
  975. ninfo = self.get_ninfo()
  976. ninfo.csig = SCons.Util.MD5signature(self.get_contents())
  977. return self.ninfo.csig
  978. def get_cachedir_csig(self):
  979. return self.get_csig()
  980. def get_stored_info(self):
  981. return None
  982. def get_stored_implicit(self):
  983. """Fetch the stored implicit dependencies"""
  984. return None
  985. #
  986. #
  987. #
  988. def set_precious(self, precious = 1):
  989. """Set the Node's precious value."""
  990. self.precious = precious
  991. def set_pseudo(self, pseudo = True):
  992. """Set the Node's precious value."""
  993. self.pseudo = pseudo
  994. def set_noclean(self, noclean = 1):
  995. """Set the Node's noclean value."""
  996. # Make sure noclean is an integer so the --debug=stree
  997. # output in Util.py can use it as an index.
  998. self.noclean = noclean and 1 or 0
  999. def set_nocache(self, nocache = 1):
  1000. """Set the Node's nocache value."""
  1001. # Make sure nocache is an integer so the --debug=stree
  1002. # output in Util.py can use it as an index.
  1003. self.nocache = nocache and 1 or 0
  1004. def set_always_build(self, always_build = 1):
  1005. """Set the Node's always_build value."""
  1006. self.always_build = always_build
  1007. def exists(self):
  1008. """Does this node exists?"""
  1009. return _exists_map[self._func_exists](self)
  1010. def rexists(self):
  1011. """Does this node exist locally or in a repositiory?"""
  1012. # There are no repositories by default:
  1013. return _rexists_map[self._func_rexists](self)
  1014. def get_contents(self):
  1015. """Fetch the contents of the entry."""
  1016. return _get_contents_map[self._func_get_contents](self)
  1017. def missing(self):
  1018. return not self.is_derived() and \
  1019. not self.linked and \
  1020. not self.rexists()
  1021. def remove(self):
  1022. """Remove this Node: no-op by default."""
  1023. return None
  1024. def add_dependency(self, depend):
  1025. """Adds dependencies."""
  1026. try:
  1027. self._add_child(self.depends, self.depends_set, depend)
  1028. except TypeError as e:
  1029. e = e.args[0]
  1030. if SCons.Util.is_List(e):
  1031. s = list(map(str, e))
  1032. else:
  1033. s = str(e)
  1034. 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)))
  1035. def add_prerequisite(self, prerequisite):
  1036. """Adds prerequisites"""
  1037. if self.prerequisites is None:
  1038. self.prerequisites = SCons.Util.UniqueList()
  1039. self.prerequisites.extend(prerequisite)
  1040. self._children_reset()
  1041. def add_ignore(self, depend):
  1042. """Adds dependencies to ignore."""
  1043. try:
  1044. self._add_child(self.ignore, self.ignore_set, depend)
  1045. except TypeError as e:
  1046. e = e.args[0]
  1047. if SCons.Util.is_List(e):
  1048. s = list(map(str, e))
  1049. else:
  1050. s = str(e)
  1051. 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)))
  1052. def add_source(self, source):
  1053. """Adds sources."""
  1054. if self._specific_sources:
  1055. return
  1056. try:
  1057. self._add_child(self.sources, self.sources_set, source)
  1058. except TypeError as e:
  1059. e = e.args[0]
  1060. if SCons.Util.is_List(e):
  1061. s = list(map(str, e))
  1062. else:
  1063. s = str(e)
  1064. 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)))
  1065. def _add_child(self, collection, set, child):
  1066. """Adds 'child' to 'collection', first checking 'set' to see if it's
  1067. already present."""
  1068. added = None
  1069. for c in child:
  1070. if c not in set:
  1071. set.add(c)
  1072. collection.append(c)
  1073. added = 1
  1074. if added:
  1075. self._children_reset()
  1076. def set_specific_source(self, source):
  1077. self.add_source(source)
  1078. self._specific_sources = True
  1079. def add_wkid(self, wkid):
  1080. """Add a node to the list of kids waiting to be evaluated"""
  1081. if self.wkids is not None:
  1082. self.wkids.append(wkid)
  1083. def _children_reset(self):
  1084. self.clear_memoized_values()
  1085. # We need to let the Executor clear out any calculated
  1086. # build info that it's cached so we can re-calculate it.
  1087. self.executor_cleanup()
  1088. @SCons.Memoize.CountMethodCall
  1089. def _children_get(self):
  1090. try:
  1091. return self._memo['_children_get']
  1092. except KeyError:
  1093. pass
  1094. # The return list may contain duplicate Nodes, especially in
  1095. # source trees where there are a lot of repeated #includes
  1096. # of a tangle of .h files. Profiling shows, however, that
  1097. # eliminating the duplicates with a brute-force approach that
  1098. # preserves the order (that is, something like:
  1099. #
  1100. # u = []
  1101. # for n in list:
  1102. # if n not in u:
  1103. # u.append(n)"
  1104. #
  1105. # takes more cycles than just letting the underlying methods
  1106. # hand back cached values if a Node's information is requested
  1107. # multiple times. (Other methods of removing duplicates, like
  1108. # using dictionary keys, lose the order, and the only ordered
  1109. # dictionary patterns I found all ended up using "not in"
  1110. # internally anyway...)
  1111. if self.ignore_set:
  1112. iter = chain.from_iterable([_f for _f in [self.sources, self.depends, self.implicit] if _f])
  1113. children = []
  1114. for i in iter:
  1115. if i not in self.ignore_set:
  1116. children.append(i)
  1117. else:
  1118. children = self.all_children(scan=0)
  1119. self._memo['_children_get'] = children
  1120. return children
  1121. def all_children(self, scan=1):
  1122. """Return a list of all the node's direct children."""
  1123. if scan:
  1124. self.scan()
  1125. # The return list may contain duplicate Nodes, especially in
  1126. # source trees where there are a lot of repeated #includes
  1127. # of a tangle of .h files. Profiling shows, however, that
  1128. # eliminating the duplicates with a brute-force approach that
  1129. # preserves the order (that is, something like:
  1130. #
  1131. # u = []
  1132. # for n in list:
  1133. # if n not in u:
  1134. # u.append(n)"
  1135. #
  1136. # takes more cycles than just letting the underlying methods
  1137. # hand back cached values if a Node's information is requested
  1138. # multiple times. (Other methods of removing duplicates, like
  1139. # using dictionary keys, lose the order, and the only ordered
  1140. # dictionary patterns I found all ended up using "not in"
  1141. # internally anyway...)
  1142. return list(chain.from_iterable([_f for _f in [self.sources, self.depends, self.implicit] if _f]))
  1143. def children(self, scan=1):
  1144. """Return a list of the node's direct children, minus those
  1145. that are ignored by this node."""
  1146. if scan:
  1147. self.scan()
  1148. return self._children_get()
  1149. def set_state(self, state):
  1150. self.state = state
  1151. def get_state(self):
  1152. return self.state
  1153. def get_env(self):
  1154. env = self.env
  1155. if not env:
  1156. import SCons.Defaults
  1157. env = SCons.Defaults.DefaultEnvironment()
  1158. return env
  1159. def Decider(self, function):
  1160. foundkey = None
  1161. for k, v in _decider_map.items():
  1162. if v == function:
  1163. foundkey = k
  1164. break
  1165. if not foundkey:
  1166. foundkey = len(_decider_map)
  1167. _decider_map[foundkey] = function
  1168. self.changed_since_last_build = foundkey
  1169. def Tag(self, key, value):
  1170. """ Add a user-defined tag. """
  1171. if not self._tags:
  1172. self._tags = {}
  1173. self._tags[key] = value
  1174. def GetTag(self, key):
  1175. """ Return a user-defined tag. """
  1176. if not self._tags:
  1177. return None
  1178. return self._tags.get(key, None)
  1179. def changed(self, node=None, allowcache=False):
  1180. """
  1181. Returns if the node is up-to-date with respect to the BuildInfo
  1182. stored last time it was built. The default behavior is to compare
  1183. it against our own previously stored BuildInfo, but the stored
  1184. BuildInfo from another Node (typically one in a Repository)
  1185. can be used instead.
  1186. Note that we now *always* check every dependency. We used to
  1187. short-circuit the check by returning as soon as we detected
  1188. any difference, but we now rely on checking every dependency
  1189. to make sure that any necessary Node information (for example,
  1190. the content signature of an #included .h file) is updated.
  1191. The allowcache option was added for supporting the early
  1192. release of the executor/builder structures, right after
  1193. a File target was built. When set to true, the return
  1194. value of this changed method gets cached for File nodes.
  1195. Like this, the executor isn't needed any longer for subsequent
  1196. calls to changed().
  1197. @see: FS.File.changed(), FS.File.release_target_info()
  1198. """
  1199. t = 0
  1200. if t: Trace('changed(%s [%s], %s)' % (self, classname(self), node))
  1201. if node is None:
  1202. node = self
  1203. result = False
  1204. bi = node.get_stored_info().binfo
  1205. then = bi.bsourcesigs + bi.bdependsigs + bi.bimplicitsigs
  1206. children = self.children()
  1207. diff = len(children) - len(then)
  1208. if diff:
  1209. # The old and new dependency lists are different lengths.
  1210. # This always indicates that the Node must be rebuilt.
  1211. # We also extend the old dependency list with enough None
  1212. # entries to equal the new dependency list, for the benefit
  1213. # of the loop below that updates node information.
  1214. then.extend([None] * diff)
  1215. if t: Trace(': old %s new %s' % (len(then), len(children)))
  1216. result = True
  1217. for child, prev_ni in zip(children, then):
  1218. if _decider_map[child.changed_since_last_build](child, self, prev_ni):
  1219. if t: Trace(': %s changed' % child)
  1220. result = True
  1221. contents = self.get_executor().get_contents()
  1222. if self.has_builder():
  1223. import SCons.Util
  1224. newsig = SCons.Util.MD5signature(contents)
  1225. if bi.bactsig != newsig:
  1226. if t: Trace(': bactsig %s != newsig %s' % (bi.bactsig, newsig))
  1227. result = True
  1228. if not result:
  1229. if t: Trace(': up to date')
  1230. if t: Trace('\n')
  1231. return result
  1232. def is_up_to_date(self):
  1233. """Default check for whether the Node is current: unknown Node
  1234. subtypes are always out of date, so they will always get built."""
  1235. return None
  1236. def children_are_up_to_date(self):
  1237. """Alternate check for whether the Node is current: If all of
  1238. our children were up-to-date, then this Node was up-to-date, too.
  1239. The SCons.Node.Alias and SCons.Node.Python.Value subclasses
  1240. rebind their current() method to this method."""
  1241. # Allow the children to calculate their signatures.
  1242. self.binfo = self.get_binfo()
  1243. if self.always_build:
  1244. return None
  1245. state = 0
  1246. for kid in self.children(None):
  1247. s = kid.get_state()
  1248. if s and (not state or s > state):
  1249. state = s
  1250. return (state == 0 or state == SCons.Node.up_to_date)
  1251. def is_literal(self):
  1252. """Always pass the string representation of a Node to
  1253. the command interpreter literally."""
  1254. return 1
  1255. def render_include_tree(self):
  1256. """
  1257. Return a text representation, suitable for displaying to the
  1258. user, of the include tree for the sources of this node.
  1259. """
  1260. if self.is_derived():
  1261. env = self.get_build_env()
  1262. if env:
  1263. for s in self.sources:
  1264. scanner = self.get_source_scanner(s)
  1265. if scanner:
  1266. path = self.get_build_scanner_path(scanner)
  1267. else:
  1268. path = None
  1269. def f(node, env=env, scanner=scanner, path=path):
  1270. return node.get_found_includes(env, scanner, path)
  1271. return SCons.Util.render_tree(s, f, 1)
  1272. else:
  1273. return None
  1274. def get_abspath(self):
  1275. """
  1276. Return an absolute path to the Node. This will return simply
  1277. str(Node) by default, but for Node types that have a concept of
  1278. relative path, this might return something different.
  1279. """
  1280. return str(self)
  1281. def for_signature(self):
  1282. """
  1283. Return a string representation of the Node that will always
  1284. be the same for this particular Node, no matter what. This
  1285. is by contrast to the __str__() method, which might, for
  1286. instance, return a relative path for a file Node. The purpose
  1287. of this method is to generate a value to be used in signature
  1288. calculation for the command line used to build a target, and
  1289. we use this method instead of str() to avoid unnecessary
  1290. rebuilds. This method does not need to return something that
  1291. would actually work in a command line; it can return any kind of
  1292. nonsense, so long as it does not change.
  1293. """
  1294. return str(self)
  1295. def get_string(self, for_signature):
  1296. """This is a convenience function designed primarily to be
  1297. used in command generators (i.e., CommandGeneratorActions or
  1298. Environment variables that are callable), which are called
  1299. with a for_signature argument that is nonzero if the command
  1300. generator is being called to generate a signature for the
  1301. command line, which determines if we should rebuild or not.
  1302. Such command generators should use this method in preference
  1303. to str(Node) when converting a Node to a string, passing
  1304. in the for_signature parameter, such that we will call
  1305. Node.for_signature() or str(Node) properly, depending on whether
  1306. we are calculating a signature or actually constructing a
  1307. command line."""
  1308. if for_signature:
  1309. return self.for_signature()
  1310. return str(self)
  1311. def get_subst_proxy(self):
  1312. """
  1313. This method is expected to return an object that will function
  1314. exactly like this Node, except that it implements any additional
  1315. special features that we would like to be in effect for
  1316. Environment variable substitution. The principle use is that
  1317. some Nodes would like to implement a __getattr__() method,
  1318. but putting that in the Node type itself has a tendency to kill
  1319. performance. We instead put it in a proxy and return it from
  1320. this method. It is legal for this method to return self
  1321. if no new functionality is needed for Environment substitution.
  1322. """
  1323. return self
  1324. def explain(self):
  1325. if not self.exists():
  1326. return "building `%s' because it doesn't exist\n" % self
  1327. if self.always_build:
  1328. return "rebuilding `%s' because AlwaysBuild() is specified\n" % self
  1329. old = self.get_stored_info()
  1330. if old is None:
  1331. return None
  1332. old = old.binfo
  1333. old.prepare_dependencies()
  1334. try:
  1335. old_bkids = old.bsources + old.bdepends + old.bimplicit
  1336. old_bkidsigs = old.bsourcesigs + old.bdependsigs + old.bimplicitsigs
  1337. except AttributeError:
  1338. return "Cannot explain why `%s' is being rebuilt: No previous build information found\n" % self
  1339. new = self.get_binfo()
  1340. new_bkids = new.bsources + new.bdepends + new.bimplicit
  1341. new_bkidsigs = new.bsourcesigs + new.bdependsigs + new.bimplicitsigs
  1342. osig = dict(list(zip(old_bkids, old_bkidsigs)))
  1343. nsig = dict(list(zip(new_bkids, new_bkidsigs)))
  1344. # The sources and dependencies we'll want to report are all stored
  1345. # as relative paths to this target's directory, but we want to
  1346. # report them relative to the top-level SConstruct directory,
  1347. # so we only print them after running them through this lambda
  1348. # to turn them into the right relative Node and then return
  1349. # its string.
  1350. def stringify( s, E=self.dir.Entry ) :
  1351. if hasattr( s, 'dir' ) :
  1352. return str(E(s))
  1353. return str(s)
  1354. lines = []
  1355. removed = [x for x in old_bkids if not x in new_bkids]
  1356. if removed:
  1357. removed = list(map(stringify, removed))
  1358. fmt = "`%s' is no longer a dependency\n"
  1359. lines.extend([fmt % s for s in removed])
  1360. for k in new_bkids:
  1361. if not k in old_bkids:
  1362. lines.append("`%s' is a new dependency\n" % stringify(k))
  1363. elif _decider_map[k.changed_since_last_build](k, self, osig[k]):
  1364. lines.append("`%s' changed\n" % stringify(k))
  1365. if len(lines) == 0 and old_bkids != new_bkids:
  1366. lines.append("the dependency order changed:\n" +
  1367. "%sold: %s\n" % (' '*15, list(map(stringify, old_bkids))) +
  1368. "%snew: %s\n" % (' '*15, list(map(stringify, new_bkids))))
  1369. if len(lines) == 0:
  1370. def fmt_with_title(title, strlines):
  1371. lines = strlines.split('\n')
  1372. sep = '\n' + ' '*(15 + len(title))
  1373. return ' '*15 + title + sep.join(lines) + '\n'
  1374. if old.bactsig != new.bactsig:
  1375. if old.bact == new.bact:
  1376. lines.append("the contents of the build action changed\n" +
  1377. fmt_with_title('action: ', new.bact))
  1378. # lines.append("the contents of the build action changed [%s] [%s]\n"%(old.bactsig,new.bactsig) +
  1379. # fmt_with_title('action: ', new.bact))
  1380. else:
  1381. lines.append("the build action changed:\n" +
  1382. fmt_with_title('old: ', old.bact) +
  1383. fmt_with_title('new: ', new.bact))
  1384. if len(lines) == 0:
  1385. return "rebuilding `%s' for unknown reasons\n" % self
  1386. preamble = "rebuilding `%s' because" % self
  1387. if len(lines) == 1:
  1388. return "%s %s" % (preamble, lines[0])
  1389. else:
  1390. lines = ["%s:\n" % preamble] + lines
  1391. return ( ' '*11).join(lines)
  1392. class NodeList(collections.UserList):
  1393. def __str__(self):
  1394. return str(list(map(str, self.data)))
  1395. def get_children(node, parent): return node.children()
  1396. def ignore_cycle(node, stack): pass
  1397. def do_nothing(node, parent): pass
  1398. class Walker(object):
  1399. """An iterator for walking a Node tree.
  1400. This is depth-first, children are visited before the parent.
  1401. The Walker object can be initialized with any node, and
  1402. returns the next node on the descent with each get_next() call.
  1403. 'kids_func' is an optional function that will be called to
  1404. get the children of a node instead of calling 'children'.
  1405. 'cycle_func' is an optional function that will be called
  1406. when a cycle is detected.
  1407. This class does not get caught in node cycles caused, for example,
  1408. by C header file include loops.
  1409. """
  1410. def __init__(self, node, kids_func=get_children,
  1411. cycle_func=ignore_cycle,
  1412. eval_func=do_nothing):
  1413. self.kids_func = kids_func
  1414. self.cycle_func = cycle_func
  1415. self.eval_func = eval_func
  1416. node.wkids = copy.copy(kids_func(node, None))
  1417. self.stack = [node]
  1418. self.history = {} # used to efficiently detect and avoid cycles
  1419. self.history[node] = None
  1420. def get_next(self):
  1421. """Return the next node for this walk of the tree.
  1422. This function is intentionally iterative, not recursive,
  1423. to sidestep any issues of stack size limitations.
  1424. """
  1425. while self.stack:
  1426. if self.stack[-1].wkids:
  1427. node = self.stack[-1].wkids.pop(0)
  1428. if not self.stack[-1].wkids:
  1429. self.stack[-1].wkids = None
  1430. if node in self.history:
  1431. self.cycle_func(node, self.stack)
  1432. else:
  1433. node.wkids = copy.copy(self.kids_func(node, self.stack[-1]))
  1434. self.stack.append(node)
  1435. self.history[node] = None
  1436. else:
  1437. node = self.stack.pop()
  1438. del self.history[node]
  1439. if node:
  1440. if self.stack:
  1441. parent = self.stack[-1]
  1442. else:
  1443. parent = None
  1444. self.eval_func(node, parent)
  1445. return node
  1446. return None
  1447. def is_done(self):
  1448. return not self.stack
  1449. arg2nodes_lookups = []
  1450. # Local Variables:
  1451. # tab-width:4
  1452. # indent-tabs-mode:nil
  1453. # End:
  1454. # vim: set expandtab tabstop=4 shiftwidth=4: