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.

1071 lines
41 KiB

6 years ago
  1. #
  2. # Copyright (c) 2001 - 2017 The SCons Foundation
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining
  5. # a copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish,
  8. # distribute, sublicense, and/or sell copies of the Software, and to
  9. # permit persons to whom the Software is furnished to do so, subject to
  10. # the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  16. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  17. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. from __future__ import print_function
  23. import sys
  24. __doc__ = """
  25. Generic Taskmaster module for the SCons build engine.
  26. =====================================================
  27. This module contains the primary interface(s) between a wrapping user
  28. interface and the SCons build engine. There are two key classes here:
  29. Taskmaster
  30. ----------
  31. This is the main engine for walking the dependency graph and
  32. calling things to decide what does or doesn't need to be built.
  33. Task
  34. ----
  35. This is the base class for allowing a wrapping interface to
  36. decide what does or doesn't actually need to be done. The
  37. intention is for a wrapping interface to subclass this as
  38. appropriate for different types of behavior it may need.
  39. The canonical example is the SCons native Python interface,
  40. which has Task subclasses that handle its specific behavior,
  41. like printing "'foo' is up to date" when a top-level target
  42. doesn't need to be built, and handling the -c option by removing
  43. targets as its "build" action. There is also a separate subclass
  44. for suppressing this output when the -q option is used.
  45. The Taskmaster instantiates a Task object for each (set of)
  46. target(s) that it decides need to be evaluated and/or built.
  47. """
  48. __revision__ = "src/engine/SCons/Taskmaster.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  49. from itertools import chain
  50. import operator
  51. import sys
  52. import traceback
  53. import SCons.Errors
  54. import SCons.Node
  55. import SCons.Warnings
  56. StateString = SCons.Node.StateString
  57. NODE_NO_STATE = SCons.Node.no_state
  58. NODE_PENDING = SCons.Node.pending
  59. NODE_EXECUTING = SCons.Node.executing
  60. NODE_UP_TO_DATE = SCons.Node.up_to_date
  61. NODE_EXECUTED = SCons.Node.executed
  62. NODE_FAILED = SCons.Node.failed
  63. print_prepare = 0 # set by option --debug=prepare
  64. # A subsystem for recording stats about how different Nodes are handled by
  65. # the main Taskmaster loop. There's no external control here (no need for
  66. # a --debug= option); enable it by changing the value of CollectStats.
  67. CollectStats = None
  68. class Stats(object):
  69. """
  70. A simple class for holding statistics about the disposition of a
  71. Node by the Taskmaster. If we're collecting statistics, each Node
  72. processed by the Taskmaster gets one of these attached, in which case
  73. the Taskmaster records its decision each time it processes the Node.
  74. (Ideally, that's just once per Node.)
  75. """
  76. def __init__(self):
  77. """
  78. Instantiates a Taskmaster.Stats object, initializing all
  79. appropriate counters to zero.
  80. """
  81. self.considered = 0
  82. self.already_handled = 0
  83. self.problem = 0
  84. self.child_failed = 0
  85. self.not_built = 0
  86. self.side_effects = 0
  87. self.build = 0
  88. StatsNodes = []
  89. fmt = "%(considered)3d "\
  90. "%(already_handled)3d " \
  91. "%(problem)3d " \
  92. "%(child_failed)3d " \
  93. "%(not_built)3d " \
  94. "%(side_effects)3d " \
  95. "%(build)3d "
  96. def dump_stats():
  97. for n in sorted(StatsNodes, key=lambda a: str(a)):
  98. print((fmt % n.attributes.stats.__dict__) + str(n))
  99. class Task(object):
  100. """
  101. Default SCons build engine task.
  102. This controls the interaction of the actual building of node
  103. and the rest of the engine.
  104. This is expected to handle all of the normally-customizable
  105. aspects of controlling a build, so any given application
  106. *should* be able to do what it wants by sub-classing this
  107. class and overriding methods as appropriate. If an application
  108. needs to customize something by sub-classing Taskmaster (or
  109. some other build engine class), we should first try to migrate
  110. that functionality into this class.
  111. Note that it's generally a good idea for sub-classes to call
  112. these methods explicitly to update state, etc., rather than
  113. roll their own interaction with Taskmaster from scratch.
  114. """
  115. def __init__(self, tm, targets, top, node):
  116. self.tm = tm
  117. self.targets = targets
  118. self.top = top
  119. self.node = node
  120. self.exc_clear()
  121. def trace_message(self, method, node, description='node'):
  122. fmt = '%-20s %s %s\n'
  123. return fmt % (method + ':', description, self.tm.trace_node(node))
  124. def display(self, message):
  125. """
  126. Hook to allow the calling interface to display a message.
  127. This hook gets called as part of preparing a task for execution
  128. (that is, a Node to be built). As part of figuring out what Node
  129. should be built next, the actual target list may be altered,
  130. along with a message describing the alteration. The calling
  131. interface can subclass Task and provide a concrete implementation
  132. of this method to see those messages.
  133. """
  134. pass
  135. def prepare(self):
  136. """
  137. Called just before the task is executed.
  138. This is mainly intended to give the target Nodes a chance to
  139. unlink underlying files and make all necessary directories before
  140. the Action is actually called to build the targets.
  141. """
  142. global print_prepare
  143. T = self.tm.trace
  144. if T: T.write(self.trace_message(u'Task.prepare()', self.node))
  145. # Now that it's the appropriate time, give the TaskMaster a
  146. # chance to raise any exceptions it encountered while preparing
  147. # this task.
  148. self.exception_raise()
  149. if self.tm.message:
  150. self.display(self.tm.message)
  151. self.tm.message = None
  152. # Let the targets take care of any necessary preparations.
  153. # This includes verifying that all of the necessary sources
  154. # and dependencies exist, removing the target file(s), etc.
  155. #
  156. # As of April 2008, the get_executor().prepare() method makes
  157. # sure that all of the aggregate sources necessary to build this
  158. # Task's target(s) exist in one up-front check. The individual
  159. # target t.prepare() methods check that each target's explicit
  160. # or implicit dependencies exists, and also initialize the
  161. # .sconsign info.
  162. executor = self.targets[0].get_executor()
  163. if executor is None:
  164. return
  165. executor.prepare()
  166. for t in executor.get_action_targets():
  167. if print_prepare:
  168. print("Preparing target %s..."%t)
  169. for s in t.side_effects:
  170. print("...with side-effect %s..."%s)
  171. t.prepare()
  172. for s in t.side_effects:
  173. if print_prepare:
  174. print("...Preparing side-effect %s..."%s)
  175. s.prepare()
  176. def get_target(self):
  177. """Fetch the target being built or updated by this task.
  178. """
  179. return self.node
  180. def needs_execute(self):
  181. # TODO(deprecate): "return True" is the old default behavior;
  182. # change it to NotImplementedError (after running through the
  183. # Deprecation Cycle) so the desired behavior is explicitly
  184. # determined by which concrete subclass is used.
  185. #raise NotImplementedError
  186. msg = ('Taskmaster.Task is an abstract base class; instead of\n'
  187. '\tusing it directly, '
  188. 'derive from it and override the abstract methods.')
  189. SCons.Warnings.warn(SCons.Warnings.TaskmasterNeedsExecuteWarning, msg)
  190. return True
  191. def execute(self):
  192. """
  193. Called to execute the task.
  194. This method is called from multiple threads in a parallel build,
  195. so only do thread safe stuff here. Do thread unsafe stuff in
  196. prepare(), executed() or failed().
  197. """
  198. T = self.tm.trace
  199. if T: T.write(self.trace_message(u'Task.execute()', self.node))
  200. try:
  201. cached_targets = []
  202. for t in self.targets:
  203. if not t.retrieve_from_cache():
  204. break
  205. cached_targets.append(t)
  206. if len(cached_targets) < len(self.targets):
  207. # Remove targets before building. It's possible that we
  208. # partially retrieved targets from the cache, leaving
  209. # them in read-only mode. That might cause the command
  210. # to fail.
  211. #
  212. for t in cached_targets:
  213. try:
  214. t.fs.unlink(t.get_internal_path())
  215. except (IOError, OSError):
  216. pass
  217. self.targets[0].build()
  218. else:
  219. for t in cached_targets:
  220. t.cached = 1
  221. except SystemExit:
  222. exc_value = sys.exc_info()[1]
  223. raise SCons.Errors.ExplicitExit(self.targets[0], exc_value.code)
  224. except SCons.Errors.UserError:
  225. raise
  226. except SCons.Errors.BuildError:
  227. raise
  228. except Exception as e:
  229. buildError = SCons.Errors.convert_to_BuildError(e)
  230. buildError.node = self.targets[0]
  231. buildError.exc_info = sys.exc_info()
  232. raise buildError
  233. def executed_without_callbacks(self):
  234. """
  235. Called when the task has been successfully executed
  236. and the Taskmaster instance doesn't want to call
  237. the Node's callback methods.
  238. """
  239. T = self.tm.trace
  240. if T: T.write(self.trace_message('Task.executed_without_callbacks()',
  241. self.node))
  242. for t in self.targets:
  243. if t.get_state() == NODE_EXECUTING:
  244. for side_effect in t.side_effects:
  245. side_effect.set_state(NODE_NO_STATE)
  246. t.set_state(NODE_EXECUTED)
  247. def executed_with_callbacks(self):
  248. """
  249. Called when the task has been successfully executed and
  250. the Taskmaster instance wants to call the Node's callback
  251. methods.
  252. This may have been a do-nothing operation (to preserve build
  253. order), so we must check the node's state before deciding whether
  254. it was "built", in which case we call the appropriate Node method.
  255. In any event, we always call "visited()", which will handle any
  256. post-visit actions that must take place regardless of whether
  257. or not the target was an actual built target or a source Node.
  258. """
  259. global print_prepare
  260. T = self.tm.trace
  261. if T: T.write(self.trace_message('Task.executed_with_callbacks()',
  262. self.node))
  263. for t in self.targets:
  264. if t.get_state() == NODE_EXECUTING:
  265. for side_effect in t.side_effects:
  266. side_effect.set_state(NODE_NO_STATE)
  267. t.set_state(NODE_EXECUTED)
  268. if not t.cached:
  269. t.push_to_cache()
  270. t.built()
  271. t.visited()
  272. if (not print_prepare and
  273. (not hasattr(self, 'options') or not self.options.debug_includes)):
  274. t.release_target_info()
  275. else:
  276. t.visited()
  277. executed = executed_with_callbacks
  278. def failed(self):
  279. """
  280. Default action when a task fails: stop the build.
  281. Note: Although this function is normally invoked on nodes in
  282. the executing state, it might also be invoked on up-to-date
  283. nodes when using Configure().
  284. """
  285. self.fail_stop()
  286. def fail_stop(self):
  287. """
  288. Explicit stop-the-build failure.
  289. This sets failure status on the target nodes and all of
  290. their dependent parent nodes.
  291. Note: Although this function is normally invoked on nodes in
  292. the executing state, it might also be invoked on up-to-date
  293. nodes when using Configure().
  294. """
  295. T = self.tm.trace
  296. if T: T.write(self.trace_message('Task.failed_stop()', self.node))
  297. # Invoke will_not_build() to clean-up the pending children
  298. # list.
  299. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED))
  300. # Tell the taskmaster to not start any new tasks
  301. self.tm.stop()
  302. # We're stopping because of a build failure, but give the
  303. # calling Task class a chance to postprocess() the top-level
  304. # target under which the build failure occurred.
  305. self.targets = [self.tm.current_top]
  306. self.top = 1
  307. def fail_continue(self):
  308. """
  309. Explicit continue-the-build failure.
  310. This sets failure status on the target nodes and all of
  311. their dependent parent nodes.
  312. Note: Although this function is normally invoked on nodes in
  313. the executing state, it might also be invoked on up-to-date
  314. nodes when using Configure().
  315. """
  316. T = self.tm.trace
  317. if T: T.write(self.trace_message('Task.failed_continue()', self.node))
  318. self.tm.will_not_build(self.targets, lambda n: n.set_state(NODE_FAILED))
  319. def make_ready_all(self):
  320. """
  321. Marks all targets in a task ready for execution.
  322. This is used when the interface needs every target Node to be
  323. visited--the canonical example being the "scons -c" option.
  324. """
  325. T = self.tm.trace
  326. if T: T.write(self.trace_message('Task.make_ready_all()', self.node))
  327. self.out_of_date = self.targets[:]
  328. for t in self.targets:
  329. t.disambiguate().set_state(NODE_EXECUTING)
  330. for s in t.side_effects:
  331. # add disambiguate here to mirror the call on targets above
  332. s.disambiguate().set_state(NODE_EXECUTING)
  333. def make_ready_current(self):
  334. """
  335. Marks all targets in a task ready for execution if any target
  336. is not current.
  337. This is the default behavior for building only what's necessary.
  338. """
  339. global print_prepare
  340. T = self.tm.trace
  341. if T: T.write(self.trace_message(u'Task.make_ready_current()',
  342. self.node))
  343. self.out_of_date = []
  344. needs_executing = False
  345. for t in self.targets:
  346. try:
  347. t.disambiguate().make_ready()
  348. is_up_to_date = not t.has_builder() or \
  349. (not t.always_build and t.is_up_to_date())
  350. except EnvironmentError as e:
  351. raise SCons.Errors.BuildError(node=t, errstr=e.strerror, filename=e.filename)
  352. if not is_up_to_date:
  353. self.out_of_date.append(t)
  354. needs_executing = True
  355. if needs_executing:
  356. for t in self.targets:
  357. t.set_state(NODE_EXECUTING)
  358. for s in t.side_effects:
  359. # add disambiguate here to mirror the call on targets in first loop above
  360. s.disambiguate().set_state(NODE_EXECUTING)
  361. else:
  362. for t in self.targets:
  363. # We must invoke visited() to ensure that the node
  364. # information has been computed before allowing the
  365. # parent nodes to execute. (That could occur in a
  366. # parallel build...)
  367. t.visited()
  368. t.set_state(NODE_UP_TO_DATE)
  369. if (not print_prepare and
  370. (not hasattr(self, 'options') or not self.options.debug_includes)):
  371. t.release_target_info()
  372. make_ready = make_ready_current
  373. def postprocess(self):
  374. """
  375. Post-processes a task after it's been executed.
  376. This examines all the targets just built (or not, we don't care
  377. if the build was successful, or even if there was no build
  378. because everything was up-to-date) to see if they have any
  379. waiting parent Nodes, or Nodes waiting on a common side effect,
  380. that can be put back on the candidates list.
  381. """
  382. T = self.tm.trace
  383. if T: T.write(self.trace_message(u'Task.postprocess()', self.node))
  384. # We may have built multiple targets, some of which may have
  385. # common parents waiting for this build. Count up how many
  386. # targets each parent was waiting for so we can subtract the
  387. # values later, and so we *don't* put waiting side-effect Nodes
  388. # back on the candidates list if the Node is also a waiting
  389. # parent.
  390. targets = set(self.targets)
  391. pending_children = self.tm.pending_children
  392. parents = {}
  393. for t in targets:
  394. # A node can only be in the pending_children set if it has
  395. # some waiting_parents.
  396. if t.waiting_parents:
  397. if T: T.write(self.trace_message(u'Task.postprocess()',
  398. t,
  399. 'removing'))
  400. pending_children.discard(t)
  401. for p in t.waiting_parents:
  402. parents[p] = parents.get(p, 0) + 1
  403. for t in targets:
  404. if t.side_effects is not None:
  405. for s in t.side_effects:
  406. if s.get_state() == NODE_EXECUTING:
  407. s.set_state(NODE_NO_STATE)
  408. for p in s.waiting_parents:
  409. parents[p] = parents.get(p, 0) + 1
  410. for p in s.waiting_s_e:
  411. if p.ref_count == 0:
  412. self.tm.candidates.append(p)
  413. for p, subtract in parents.items():
  414. p.ref_count = p.ref_count - subtract
  415. if T: T.write(self.trace_message(u'Task.postprocess()',
  416. p,
  417. 'adjusted parent ref count'))
  418. if p.ref_count == 0:
  419. self.tm.candidates.append(p)
  420. for t in targets:
  421. t.postprocess()
  422. # Exception handling subsystem.
  423. #
  424. # Exceptions that occur while walking the DAG or examining Nodes
  425. # must be raised, but must be raised at an appropriate time and in
  426. # a controlled manner so we can, if necessary, recover gracefully,
  427. # possibly write out signature information for Nodes we've updated,
  428. # etc. This is done by having the Taskmaster tell us about the
  429. # exception, and letting
  430. def exc_info(self):
  431. """
  432. Returns info about a recorded exception.
  433. """
  434. return self.exception
  435. def exc_clear(self):
  436. """
  437. Clears any recorded exception.
  438. This also changes the "exception_raise" attribute to point
  439. to the appropriate do-nothing method.
  440. """
  441. self.exception = (None, None, None)
  442. self.exception_raise = self._no_exception_to_raise
  443. def exception_set(self, exception=None):
  444. """
  445. Records an exception to be raised at the appropriate time.
  446. This also changes the "exception_raise" attribute to point
  447. to the method that will, in fact
  448. """
  449. if not exception:
  450. exception = sys.exc_info()
  451. self.exception = exception
  452. self.exception_raise = self._exception_raise
  453. def _no_exception_to_raise(self):
  454. pass
  455. def _exception_raise(self):
  456. """
  457. Raises a pending exception that was recorded while getting a
  458. Task ready for execution.
  459. """
  460. exc = self.exc_info()[:]
  461. try:
  462. exc_type, exc_value, exc_traceback = exc
  463. except ValueError:
  464. exc_type, exc_value = exc
  465. exc_traceback = None
  466. # raise exc_type(exc_value).with_traceback(exc_traceback)
  467. if sys.version_info[0] == 2:
  468. exec("raise exc_type, exc_value, exc_traceback")
  469. else: # sys.version_info[0] == 3:
  470. if isinstance(exc_value, Exception): #hasattr(exc_value, 'with_traceback'):
  471. # If exc_value is an exception, then just reraise
  472. exec("raise exc_value.with_traceback(exc_traceback)")
  473. else:
  474. # else we'll create an exception using the value and raise that
  475. exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
  476. # raise e.__class__, e.__class__(e), sys.exc_info()[2]
  477. # exec("raise exc_type(exc_value).with_traceback(exc_traceback)")
  478. class AlwaysTask(Task):
  479. def needs_execute(self):
  480. """
  481. Always returns True (indicating this Task should always
  482. be executed).
  483. Subclasses that need this behavior (as opposed to the default
  484. of only executing Nodes that are out of date w.r.t. their
  485. dependencies) can use this as follows:
  486. class MyTaskSubclass(SCons.Taskmaster.Task):
  487. needs_execute = SCons.Taskmaster.Task.execute_always
  488. """
  489. return True
  490. class OutOfDateTask(Task):
  491. def needs_execute(self):
  492. """
  493. Returns True (indicating this Task should be executed) if this
  494. Task's target state indicates it needs executing, which has
  495. already been determined by an earlier up-to-date check.
  496. """
  497. return self.targets[0].get_state() == SCons.Node.executing
  498. def find_cycle(stack, visited):
  499. if stack[-1] in visited:
  500. return None
  501. visited.add(stack[-1])
  502. for n in stack[-1].waiting_parents:
  503. stack.append(n)
  504. if stack[0] == stack[-1]:
  505. return stack
  506. if find_cycle(stack, visited):
  507. return stack
  508. stack.pop()
  509. return None
  510. class Taskmaster(object):
  511. """
  512. The Taskmaster for walking the dependency DAG.
  513. """
  514. def __init__(self, targets=[], tasker=None, order=None, trace=None):
  515. self.original_top = targets
  516. self.top_targets_left = targets[:]
  517. self.top_targets_left.reverse()
  518. self.candidates = []
  519. if tasker is None:
  520. tasker = OutOfDateTask
  521. self.tasker = tasker
  522. if not order:
  523. order = lambda l: l
  524. self.order = order
  525. self.message = None
  526. self.trace = trace
  527. self.next_candidate = self.find_next_candidate
  528. self.pending_children = set()
  529. def find_next_candidate(self):
  530. """
  531. Returns the next candidate Node for (potential) evaluation.
  532. The candidate list (really a stack) initially consists of all of
  533. the top-level (command line) targets provided when the Taskmaster
  534. was initialized. While we walk the DAG, visiting Nodes, all the
  535. children that haven't finished processing get pushed on to the
  536. candidate list. Each child can then be popped and examined in
  537. turn for whether *their* children are all up-to-date, in which
  538. case a Task will be created for their actual evaluation and
  539. potential building.
  540. Here is where we also allow candidate Nodes to alter the list of
  541. Nodes that should be examined. This is used, for example, when
  542. invoking SCons in a source directory. A source directory Node can
  543. return its corresponding build directory Node, essentially saying,
  544. "Hey, you really need to build this thing over here instead."
  545. """
  546. try:
  547. return self.candidates.pop()
  548. except IndexError:
  549. pass
  550. try:
  551. node = self.top_targets_left.pop()
  552. except IndexError:
  553. return None
  554. self.current_top = node
  555. alt, message = node.alter_targets()
  556. if alt:
  557. self.message = message
  558. self.candidates.append(node)
  559. self.candidates.extend(self.order(alt))
  560. node = self.candidates.pop()
  561. return node
  562. def no_next_candidate(self):
  563. """
  564. Stops Taskmaster processing by not returning a next candidate.
  565. Note that we have to clean-up the Taskmaster candidate list
  566. because the cycle detection depends on the fact all nodes have
  567. been processed somehow.
  568. """
  569. while self.candidates:
  570. candidates = self.candidates
  571. self.candidates = []
  572. self.will_not_build(candidates)
  573. return None
  574. def _validate_pending_children(self):
  575. """
  576. Validate the content of the pending_children set. Assert if an
  577. internal error is found.
  578. This function is used strictly for debugging the taskmaster by
  579. checking that no invariants are violated. It is not used in
  580. normal operation.
  581. The pending_children set is used to detect cycles in the
  582. dependency graph. We call a "pending child" a child that is
  583. found in the "pending" state when checking the dependencies of
  584. its parent node.
  585. A pending child can occur when the Taskmaster completes a loop
  586. through a cycle. For example, let's imagine a graph made of
  587. three nodes (A, B and C) making a cycle. The evaluation starts
  588. at node A. The Taskmaster first considers whether node A's
  589. child B is up-to-date. Then, recursively, node B needs to
  590. check whether node C is up-to-date. This leaves us with a
  591. dependency graph looking like::
  592. Next candidate \
  593. \
  594. Node A (Pending) --> Node B(Pending) --> Node C (NoState)
  595. ^ |
  596. | |
  597. +-------------------------------------+
  598. Now, when the Taskmaster examines the Node C's child Node A,
  599. it finds that Node A is in the "pending" state. Therefore,
  600. Node A is a pending child of node C.
  601. Pending children indicate that the Taskmaster has potentially
  602. loop back through a cycle. We say potentially because it could
  603. also occur when a DAG is evaluated in parallel. For example,
  604. consider the following graph::
  605. Node A (Pending) --> Node B(Pending) --> Node C (Pending) --> ...
  606. | ^
  607. | |
  608. +----------> Node D (NoState) --------+
  609. /
  610. Next candidate /
  611. The Taskmaster first evaluates the nodes A, B, and C and
  612. starts building some children of node C. Assuming, that the
  613. maximum parallel level has not been reached, the Taskmaster
  614. will examine Node D. It will find that Node C is a pending
  615. child of Node D.
  616. In summary, evaluating a graph with a cycle will always
  617. involve a pending child at one point. A pending child might
  618. indicate either a cycle or a diamond-shaped DAG. Only a
  619. fraction of the nodes ends-up being a "pending child" of
  620. another node. This keeps the pending_children set small in
  621. practice.
  622. We can differentiate between the two cases if we wait until
  623. the end of the build. At this point, all the pending children
  624. nodes due to a diamond-shaped DAG will have been properly
  625. built (or will have failed to build). But, the pending
  626. children involved in a cycle will still be in the pending
  627. state.
  628. The taskmaster removes nodes from the pending_children set as
  629. soon as a pending_children node moves out of the pending
  630. state. This also helps to keep the pending_children set small.
  631. """
  632. for n in self.pending_children:
  633. assert n.state in (NODE_PENDING, NODE_EXECUTING), \
  634. (str(n), StateString[n.state])
  635. assert len(n.waiting_parents) != 0, (str(n), len(n.waiting_parents))
  636. for p in n.waiting_parents:
  637. assert p.ref_count > 0, (str(n), str(p), p.ref_count)
  638. def trace_message(self, message):
  639. return 'Taskmaster: %s\n' % message
  640. def trace_node(self, node):
  641. return '<%-10s %-3s %s>' % (StateString[node.get_state()],
  642. node.ref_count,
  643. repr(str(node)))
  644. def _find_next_ready_node(self):
  645. """
  646. Finds the next node that is ready to be built.
  647. This is *the* main guts of the DAG walk. We loop through the
  648. list of candidates, looking for something that has no un-built
  649. children (i.e., that is a leaf Node or has dependencies that are
  650. all leaf Nodes or up-to-date). Candidate Nodes are re-scanned
  651. (both the target Node itself and its sources, which are always
  652. scanned in the context of a given target) to discover implicit
  653. dependencies. A Node that must wait for some children to be
  654. built will be put back on the candidates list after the children
  655. have finished building. A Node that has been put back on the
  656. candidates list in this way may have itself (or its sources)
  657. re-scanned, in order to handle generated header files (e.g.) and
  658. the implicit dependencies therein.
  659. Note that this method does not do any signature calculation or
  660. up-to-date check itself. All of that is handled by the Task
  661. class. This is purely concerned with the dependency graph walk.
  662. """
  663. self.ready_exc = None
  664. T = self.trace
  665. if T: T.write(SCons.Util.UnicodeType('\n') + self.trace_message('Looking for a node to evaluate'))
  666. while True:
  667. node = self.next_candidate()
  668. if node is None:
  669. if T: T.write(self.trace_message('No candidate anymore.') + u'\n')
  670. return None
  671. node = node.disambiguate()
  672. state = node.get_state()
  673. # For debugging only:
  674. #
  675. # try:
  676. # self._validate_pending_children()
  677. # except:
  678. # self.ready_exc = sys.exc_info()
  679. # return node
  680. if CollectStats:
  681. if not hasattr(node.attributes, 'stats'):
  682. node.attributes.stats = Stats()
  683. StatsNodes.append(node)
  684. S = node.attributes.stats
  685. S.considered = S.considered + 1
  686. else:
  687. S = None
  688. if T: T.write(self.trace_message(u' Considering node %s and its children:' % self.trace_node(node)))
  689. if state == NODE_NO_STATE:
  690. # Mark this node as being on the execution stack:
  691. node.set_state(NODE_PENDING)
  692. elif state > NODE_PENDING:
  693. # Skip this node if it has already been evaluated:
  694. if S: S.already_handled = S.already_handled + 1
  695. if T: T.write(self.trace_message(u' already handled (executed)'))
  696. continue
  697. executor = node.get_executor()
  698. try:
  699. children = executor.get_all_children()
  700. except SystemExit:
  701. exc_value = sys.exc_info()[1]
  702. e = SCons.Errors.ExplicitExit(node, exc_value.code)
  703. self.ready_exc = (SCons.Errors.ExplicitExit, e)
  704. if T: T.write(self.trace_message(' SystemExit'))
  705. return node
  706. except Exception as e:
  707. # We had a problem just trying to figure out the
  708. # children (like a child couldn't be linked in to a
  709. # VariantDir, or a Scanner threw something). Arrange to
  710. # raise the exception when the Task is "executed."
  711. self.ready_exc = sys.exc_info()
  712. if S: S.problem = S.problem + 1
  713. if T: T.write(self.trace_message(' exception %s while scanning children.\n' % e))
  714. return node
  715. children_not_visited = []
  716. children_pending = set()
  717. children_not_ready = []
  718. children_failed = False
  719. for child in chain(executor.get_all_prerequisites(), children):
  720. childstate = child.get_state()
  721. if T: T.write(self.trace_message(u' ' + self.trace_node(child)))
  722. if childstate == NODE_NO_STATE:
  723. children_not_visited.append(child)
  724. elif childstate == NODE_PENDING:
  725. children_pending.add(child)
  726. elif childstate == NODE_FAILED:
  727. children_failed = True
  728. if childstate <= NODE_EXECUTING:
  729. children_not_ready.append(child)
  730. # These nodes have not even been visited yet. Add
  731. # them to the list so that on some next pass we can
  732. # take a stab at evaluating them (or their children).
  733. children_not_visited.reverse()
  734. self.candidates.extend(self.order(children_not_visited))
  735. # if T and children_not_visited:
  736. # T.write(self.trace_message(' adding to candidates: %s' % map(str, children_not_visited)))
  737. # T.write(self.trace_message(' candidates now: %s\n' % map(str, self.candidates)))
  738. # Skip this node if any of its children have failed.
  739. #
  740. # This catches the case where we're descending a top-level
  741. # target and one of our children failed while trying to be
  742. # built by a *previous* descent of an earlier top-level
  743. # target.
  744. #
  745. # It can also occur if a node is reused in multiple
  746. # targets. One first descends though the one of the
  747. # target, the next time occurs through the other target.
  748. #
  749. # Note that we can only have failed_children if the
  750. # --keep-going flag was used, because without it the build
  751. # will stop before diving in the other branch.
  752. #
  753. # Note that even if one of the children fails, we still
  754. # added the other children to the list of candidate nodes
  755. # to keep on building (--keep-going).
  756. if children_failed:
  757. for n in executor.get_action_targets():
  758. n.set_state(NODE_FAILED)
  759. if S: S.child_failed = S.child_failed + 1
  760. if T: T.write(self.trace_message('****** %s\n' % self.trace_node(node)))
  761. continue
  762. if children_not_ready:
  763. for child in children_not_ready:
  764. # We're waiting on one or more derived targets
  765. # that have not yet finished building.
  766. if S: S.not_built = S.not_built + 1
  767. # Add this node to the waiting parents lists of
  768. # anything we're waiting on, with a reference
  769. # count so we can be put back on the list for
  770. # re-evaluation when they've all finished.
  771. node.ref_count = node.ref_count + child.add_to_waiting_parents(node)
  772. if T: T.write(self.trace_message(u' adjusted ref count: %s, child %s' %
  773. (self.trace_node(node), repr(str(child)))))
  774. if T:
  775. for pc in children_pending:
  776. T.write(self.trace_message(' adding %s to the pending children set\n' %
  777. self.trace_node(pc)))
  778. self.pending_children = self.pending_children | children_pending
  779. continue
  780. # Skip this node if it has side-effects that are
  781. # currently being built:
  782. wait_side_effects = False
  783. for se in executor.get_action_side_effects():
  784. if se.get_state() == NODE_EXECUTING:
  785. se.add_to_waiting_s_e(node)
  786. wait_side_effects = True
  787. if wait_side_effects:
  788. if S: S.side_effects = S.side_effects + 1
  789. continue
  790. # The default when we've gotten through all of the checks above:
  791. # this node is ready to be built.
  792. if S: S.build = S.build + 1
  793. if T: T.write(self.trace_message(u'Evaluating %s\n' %
  794. self.trace_node(node)))
  795. # For debugging only:
  796. #
  797. # try:
  798. # self._validate_pending_children()
  799. # except:
  800. # self.ready_exc = sys.exc_info()
  801. # return node
  802. return node
  803. return None
  804. def next_task(self):
  805. """
  806. Returns the next task to be executed.
  807. This simply asks for the next Node to be evaluated, and then wraps
  808. it in the specific Task subclass with which we were initialized.
  809. """
  810. node = self._find_next_ready_node()
  811. if node is None:
  812. return None
  813. executor = node.get_executor()
  814. if executor is None:
  815. return None
  816. tlist = executor.get_all_targets()
  817. task = self.tasker(self, tlist, node in self.original_top, node)
  818. try:
  819. task.make_ready()
  820. except Exception as e :
  821. # We had a problem just trying to get this task ready (like
  822. # a child couldn't be linked to a VariantDir when deciding
  823. # whether this node is current). Arrange to raise the
  824. # exception when the Task is "executed."
  825. self.ready_exc = sys.exc_info()
  826. if self.ready_exc:
  827. task.exception_set(self.ready_exc)
  828. self.ready_exc = None
  829. return task
  830. def will_not_build(self, nodes, node_func=lambda n: None):
  831. """
  832. Perform clean-up about nodes that will never be built. Invokes
  833. a user defined function on all of these nodes (including all
  834. of their parents).
  835. """
  836. T = self.trace
  837. pending_children = self.pending_children
  838. to_visit = set(nodes)
  839. pending_children = pending_children - to_visit
  840. if T:
  841. for n in nodes:
  842. T.write(self.trace_message(' removing node %s from the pending children set\n' %
  843. self.trace_node(n)))
  844. try:
  845. while len(to_visit):
  846. node = to_visit.pop()
  847. node_func(node)
  848. # Prune recursion by flushing the waiting children
  849. # list immediately.
  850. parents = node.waiting_parents
  851. node.waiting_parents = set()
  852. to_visit = to_visit | parents
  853. pending_children = pending_children - parents
  854. for p in parents:
  855. p.ref_count = p.ref_count - 1
  856. if T: T.write(self.trace_message(' removing parent %s from the pending children set\n' %
  857. self.trace_node(p)))
  858. except KeyError:
  859. # The container to_visit has been emptied.
  860. pass
  861. # We have the stick back the pending_children list into the
  862. # taskmaster because the python 1.5.2 compatibility does not
  863. # allow us to use in-place updates
  864. self.pending_children = pending_children
  865. def stop(self):
  866. """
  867. Stops the current build completely.
  868. """
  869. self.next_candidate = self.no_next_candidate
  870. def cleanup(self):
  871. """
  872. Check for dependency cycles.
  873. """
  874. if not self.pending_children:
  875. return
  876. nclist = [(n, find_cycle([n], set())) for n in self.pending_children]
  877. genuine_cycles = [
  878. node for node,cycle in nclist
  879. if cycle or node.get_state() != NODE_EXECUTED
  880. ]
  881. if not genuine_cycles:
  882. # All of the "cycles" found were single nodes in EXECUTED state,
  883. # which is to say, they really weren't cycles. Just return.
  884. return
  885. desc = 'Found dependency cycle(s):\n'
  886. for node, cycle in nclist:
  887. if cycle:
  888. desc = desc + " " + " -> ".join(map(str, cycle)) + "\n"
  889. else:
  890. desc = desc + \
  891. " Internal Error: no cycle found for node %s (%s) in state %s\n" % \
  892. (node, repr(node), StateString[node.get_state()])
  893. raise SCons.Errors.UserError(desc)
  894. # Local Variables:
  895. # tab-width:4
  896. # indent-tabs-mode:nil
  897. # End:
  898. # vim: set expandtab tabstop=4 shiftwidth=4: