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.

670 lines
22 KiB

6 years ago
  1. """SCons.Executor
  2. A module for executing actions with specific lists of target and source
  3. Nodes.
  4. """
  5. #
  6. # Copyright (c) 2001 - 2017 The SCons Foundation
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining
  9. # a copy of this software and associated documentation files (the
  10. # "Software"), to deal in the Software without restriction, including
  11. # without limitation the rights to use, copy, modify, merge, publish,
  12. # distribute, sublicense, and/or sell copies of the Software, and to
  13. # permit persons to whom the Software is furnished to do so, subject to
  14. # the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included
  17. # in all copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  20. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  21. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. from __future__ import print_function
  27. __revision__ = "src/engine/SCons/Executor.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  28. import collections
  29. import SCons.Debug
  30. from SCons.Debug import logInstanceCreation
  31. import SCons.Errors
  32. import SCons.Memoize
  33. from SCons.compat import with_metaclass, NoSlotsPyPy
  34. class Batch(object):
  35. """Remembers exact association between targets
  36. and sources of executor."""
  37. __slots__ = ('targets',
  38. 'sources')
  39. def __init__(self, targets=[], sources=[]):
  40. self.targets = targets
  41. self.sources = sources
  42. class TSList(collections.UserList):
  43. """A class that implements $TARGETS or $SOURCES expansions by wrapping
  44. an executor Method. This class is used in the Executor.lvars()
  45. to delay creation of NodeList objects until they're needed.
  46. Note that we subclass collections.UserList purely so that the
  47. is_Sequence() function will identify an object of this class as
  48. a list during variable expansion. We're not really using any
  49. collections.UserList methods in practice.
  50. """
  51. def __init__(self, func):
  52. self.func = func
  53. def __getattr__(self, attr):
  54. nl = self.func()
  55. return getattr(nl, attr)
  56. def __getitem__(self, i):
  57. nl = self.func()
  58. return nl[i]
  59. def __getslice__(self, i, j):
  60. nl = self.func()
  61. i = max(i, 0); j = max(j, 0)
  62. return nl[i:j]
  63. def __str__(self):
  64. nl = self.func()
  65. return str(nl)
  66. def __repr__(self):
  67. nl = self.func()
  68. return repr(nl)
  69. class TSObject(object):
  70. """A class that implements $TARGET or $SOURCE expansions by wrapping
  71. an Executor method.
  72. """
  73. def __init__(self, func):
  74. self.func = func
  75. def __getattr__(self, attr):
  76. n = self.func()
  77. return getattr(n, attr)
  78. def __str__(self):
  79. n = self.func()
  80. if n:
  81. return str(n)
  82. return ''
  83. def __repr__(self):
  84. n = self.func()
  85. if n:
  86. return repr(n)
  87. return ''
  88. def rfile(node):
  89. """
  90. A function to return the results of a Node's rfile() method,
  91. if it exists, and the Node itself otherwise (if it's a Value
  92. Node, e.g.).
  93. """
  94. try:
  95. rfile = node.rfile
  96. except AttributeError:
  97. return node
  98. else:
  99. return rfile()
  100. def execute_nothing(obj, target, kw):
  101. return 0
  102. def execute_action_list(obj, target, kw):
  103. """Actually execute the action list."""
  104. env = obj.get_build_env()
  105. kw = obj.get_kw(kw)
  106. status = 0
  107. for act in obj.get_action_list():
  108. args = ([], [], env)
  109. status = act(*args, **kw)
  110. if isinstance(status, SCons.Errors.BuildError):
  111. status.executor = obj
  112. raise status
  113. elif status:
  114. msg = "Error %s" % status
  115. raise SCons.Errors.BuildError(
  116. errstr=msg,
  117. node=obj.batches[0].targets,
  118. executor=obj,
  119. action=act)
  120. return status
  121. _do_execute_map = {0 : execute_nothing,
  122. 1 : execute_action_list}
  123. def execute_actions_str(obj):
  124. env = obj.get_build_env()
  125. return "\n".join([action.genstring(obj.get_all_targets(),
  126. obj.get_all_sources(),
  127. env)
  128. for action in obj.get_action_list()])
  129. def execute_null_str(obj):
  130. return ''
  131. _execute_str_map = {0 : execute_null_str,
  132. 1 : execute_actions_str}
  133. class Executor(object, with_metaclass(NoSlotsPyPy)):
  134. """A class for controlling instances of executing an action.
  135. This largely exists to hold a single association of an action,
  136. environment, list of environment override dictionaries, targets
  137. and sources for later processing as needed.
  138. """
  139. __slots__ = ('pre_actions',
  140. 'post_actions',
  141. 'env',
  142. 'overridelist',
  143. 'batches',
  144. 'builder_kw',
  145. '_memo',
  146. 'lvars',
  147. '_changed_sources_list',
  148. '_changed_targets_list',
  149. '_unchanged_sources_list',
  150. '_unchanged_targets_list',
  151. 'action_list',
  152. '_do_execute',
  153. '_execute_str')
  154. def __init__(self, action, env=None, overridelist=[{}],
  155. targets=[], sources=[], builder_kw={}):
  156. if SCons.Debug.track_instances: logInstanceCreation(self, 'Executor.Executor')
  157. self.set_action_list(action)
  158. self.pre_actions = []
  159. self.post_actions = []
  160. self.env = env
  161. self.overridelist = overridelist
  162. if targets or sources:
  163. self.batches = [Batch(targets[:], sources[:])]
  164. else:
  165. self.batches = []
  166. self.builder_kw = builder_kw
  167. self._do_execute = 1
  168. self._execute_str = 1
  169. self._memo = {}
  170. def get_lvars(self):
  171. try:
  172. return self.lvars
  173. except AttributeError:
  174. self.lvars = {
  175. 'CHANGED_SOURCES' : TSList(self._get_changed_sources),
  176. 'CHANGED_TARGETS' : TSList(self._get_changed_targets),
  177. 'SOURCE' : TSObject(self._get_source),
  178. 'SOURCES' : TSList(self._get_sources),
  179. 'TARGET' : TSObject(self._get_target),
  180. 'TARGETS' : TSList(self._get_targets),
  181. 'UNCHANGED_SOURCES' : TSList(self._get_unchanged_sources),
  182. 'UNCHANGED_TARGETS' : TSList(self._get_unchanged_targets),
  183. }
  184. return self.lvars
  185. def _get_changes(self):
  186. cs = []
  187. ct = []
  188. us = []
  189. ut = []
  190. for b in self.batches:
  191. # don't add targets marked always build to unchanged lists
  192. # add to changed list as they always need to build
  193. if not b.targets[0].always_build and b.targets[0].is_up_to_date():
  194. us.extend(list(map(rfile, b.sources)))
  195. ut.extend(b.targets)
  196. else:
  197. cs.extend(list(map(rfile, b.sources)))
  198. ct.extend(b.targets)
  199. self._changed_sources_list = SCons.Util.NodeList(cs)
  200. self._changed_targets_list = SCons.Util.NodeList(ct)
  201. self._unchanged_sources_list = SCons.Util.NodeList(us)
  202. self._unchanged_targets_list = SCons.Util.NodeList(ut)
  203. def _get_changed_sources(self, *args, **kw):
  204. try:
  205. return self._changed_sources_list
  206. except AttributeError:
  207. self._get_changes()
  208. return self._changed_sources_list
  209. def _get_changed_targets(self, *args, **kw):
  210. try:
  211. return self._changed_targets_list
  212. except AttributeError:
  213. self._get_changes()
  214. return self._changed_targets_list
  215. def _get_source(self, *args, **kw):
  216. return rfile(self.batches[0].sources[0]).get_subst_proxy()
  217. def _get_sources(self, *args, **kw):
  218. return SCons.Util.NodeList([rfile(n).get_subst_proxy() for n in self.get_all_sources()])
  219. def _get_target(self, *args, **kw):
  220. return self.batches[0].targets[0].get_subst_proxy()
  221. def _get_targets(self, *args, **kw):
  222. return SCons.Util.NodeList([n.get_subst_proxy() for n in self.get_all_targets()])
  223. def _get_unchanged_sources(self, *args, **kw):
  224. try:
  225. return self._unchanged_sources_list
  226. except AttributeError:
  227. self._get_changes()
  228. return self._unchanged_sources_list
  229. def _get_unchanged_targets(self, *args, **kw):
  230. try:
  231. return self._unchanged_targets_list
  232. except AttributeError:
  233. self._get_changes()
  234. return self._unchanged_targets_list
  235. def get_action_targets(self):
  236. if not self.action_list:
  237. return []
  238. targets_string = self.action_list[0].get_targets(self.env, self)
  239. if targets_string[0] == '$':
  240. targets_string = targets_string[1:]
  241. return self.get_lvars()[targets_string]
  242. def set_action_list(self, action):
  243. import SCons.Util
  244. if not SCons.Util.is_List(action):
  245. if not action:
  246. import SCons.Errors
  247. raise SCons.Errors.UserError("Executor must have an action.")
  248. action = [action]
  249. self.action_list = action
  250. def get_action_list(self):
  251. if self.action_list is None:
  252. return []
  253. return self.pre_actions + self.action_list + self.post_actions
  254. def get_all_targets(self):
  255. """Returns all targets for all batches of this Executor."""
  256. result = []
  257. for batch in self.batches:
  258. result.extend(batch.targets)
  259. return result
  260. def get_all_sources(self):
  261. """Returns all sources for all batches of this Executor."""
  262. result = []
  263. for batch in self.batches:
  264. result.extend(batch.sources)
  265. return result
  266. def get_all_children(self):
  267. """Returns all unique children (dependencies) for all batches
  268. of this Executor.
  269. The Taskmaster can recognize when it's already evaluated a
  270. Node, so we don't have to make this list unique for its intended
  271. canonical use case, but we expect there to be a lot of redundancy
  272. (long lists of batched .cc files #including the same .h files
  273. over and over), so removing the duplicates once up front should
  274. save the Taskmaster a lot of work.
  275. """
  276. result = SCons.Util.UniqueList([])
  277. for target in self.get_all_targets():
  278. result.extend(target.children())
  279. return result
  280. def get_all_prerequisites(self):
  281. """Returns all unique (order-only) prerequisites for all batches
  282. of this Executor.
  283. """
  284. result = SCons.Util.UniqueList([])
  285. for target in self.get_all_targets():
  286. if target.prerequisites is not None:
  287. result.extend(target.prerequisites)
  288. return result
  289. def get_action_side_effects(self):
  290. """Returns all side effects for all batches of this
  291. Executor used by the underlying Action.
  292. """
  293. result = SCons.Util.UniqueList([])
  294. for target in self.get_action_targets():
  295. result.extend(target.side_effects)
  296. return result
  297. @SCons.Memoize.CountMethodCall
  298. def get_build_env(self):
  299. """Fetch or create the appropriate build Environment
  300. for this Executor.
  301. """
  302. try:
  303. return self._memo['get_build_env']
  304. except KeyError:
  305. pass
  306. # Create the build environment instance with appropriate
  307. # overrides. These get evaluated against the current
  308. # environment's construction variables so that users can
  309. # add to existing values by referencing the variable in
  310. # the expansion.
  311. overrides = {}
  312. for odict in self.overridelist:
  313. overrides.update(odict)
  314. import SCons.Defaults
  315. env = self.env or SCons.Defaults.DefaultEnvironment()
  316. build_env = env.Override(overrides)
  317. self._memo['get_build_env'] = build_env
  318. return build_env
  319. def get_build_scanner_path(self, scanner):
  320. """Fetch the scanner path for this executor's targets and sources.
  321. """
  322. env = self.get_build_env()
  323. try:
  324. cwd = self.batches[0].targets[0].cwd
  325. except (IndexError, AttributeError):
  326. cwd = None
  327. return scanner.path(env, cwd,
  328. self.get_all_targets(),
  329. self.get_all_sources())
  330. def get_kw(self, kw={}):
  331. result = self.builder_kw.copy()
  332. result.update(kw)
  333. result['executor'] = self
  334. return result
  335. # use extra indirection because with new-style objects (Python 2.2
  336. # and above) we can't override special methods, and nullify() needs
  337. # to be able to do this.
  338. def __call__(self, target, **kw):
  339. return _do_execute_map[self._do_execute](self, target, kw)
  340. def cleanup(self):
  341. self._memo = {}
  342. def add_sources(self, sources):
  343. """Add source files to this Executor's list. This is necessary
  344. for "multi" Builders that can be called repeatedly to build up
  345. a source file list for a given target."""
  346. # TODO(batch): extend to multiple batches
  347. assert (len(self.batches) == 1)
  348. # TODO(batch): remove duplicates?
  349. sources = [x for x in sources if x not in self.batches[0].sources]
  350. self.batches[0].sources.extend(sources)
  351. def get_sources(self):
  352. return self.batches[0].sources
  353. def add_batch(self, targets, sources):
  354. """Add pair of associated target and source to this Executor's list.
  355. This is necessary for "batch" Builders that can be called repeatedly
  356. to build up a list of matching target and source files that will be
  357. used in order to update multiple target files at once from multiple
  358. corresponding source files, for tools like MSVC that support it."""
  359. self.batches.append(Batch(targets, sources))
  360. def prepare(self):
  361. """
  362. Preparatory checks for whether this Executor can go ahead
  363. and (try to) build its targets.
  364. """
  365. for s in self.get_all_sources():
  366. if s.missing():
  367. msg = "Source `%s' not found, needed by target `%s'."
  368. raise SCons.Errors.StopError(msg % (s, self.batches[0].targets[0]))
  369. def add_pre_action(self, action):
  370. self.pre_actions.append(action)
  371. def add_post_action(self, action):
  372. self.post_actions.append(action)
  373. # another extra indirection for new-style objects and nullify...
  374. def __str__(self):
  375. return _execute_str_map[self._execute_str](self)
  376. def nullify(self):
  377. self.cleanup()
  378. self._do_execute = 0
  379. self._execute_str = 0
  380. @SCons.Memoize.CountMethodCall
  381. def get_contents(self):
  382. """Fetch the signature contents. This is the main reason this
  383. class exists, so we can compute this once and cache it regardless
  384. of how many target or source Nodes there are.
  385. """
  386. try:
  387. return self._memo['get_contents']
  388. except KeyError:
  389. pass
  390. env = self.get_build_env()
  391. action_list = self.get_action_list()
  392. all_targets = self.get_all_targets()
  393. all_sources = self.get_all_sources()
  394. result = bytearray("",'utf-8').join([action.get_contents(all_targets,
  395. all_sources,
  396. env)
  397. for action in action_list])
  398. self._memo['get_contents'] = result
  399. return result
  400. def get_timestamp(self):
  401. """Fetch a time stamp for this Executor. We don't have one, of
  402. course (only files do), but this is the interface used by the
  403. timestamp module.
  404. """
  405. return 0
  406. def scan_targets(self, scanner):
  407. # TODO(batch): scan by batches
  408. self.scan(scanner, self.get_all_targets())
  409. def scan_sources(self, scanner):
  410. # TODO(batch): scan by batches
  411. if self.batches[0].sources:
  412. self.scan(scanner, self.get_all_sources())
  413. def scan(self, scanner, node_list):
  414. """Scan a list of this Executor's files (targets or sources) for
  415. implicit dependencies and update all of the targets with them.
  416. This essentially short-circuits an N*M scan of the sources for
  417. each individual target, which is a hell of a lot more efficient.
  418. """
  419. env = self.get_build_env()
  420. path = self.get_build_scanner_path
  421. kw = self.get_kw()
  422. # TODO(batch): scan by batches)
  423. deps = []
  424. for node in node_list:
  425. node.disambiguate()
  426. deps.extend(node.get_implicit_deps(env, scanner, path, kw))
  427. deps.extend(self.get_implicit_deps())
  428. for tgt in self.get_all_targets():
  429. tgt.add_to_implicit(deps)
  430. def _get_unignored_sources_key(self, node, ignore=()):
  431. return (node,) + tuple(ignore)
  432. @SCons.Memoize.CountDictCall(_get_unignored_sources_key)
  433. def get_unignored_sources(self, node, ignore=()):
  434. key = (node,) + tuple(ignore)
  435. try:
  436. memo_dict = self._memo['get_unignored_sources']
  437. except KeyError:
  438. memo_dict = {}
  439. self._memo['get_unignored_sources'] = memo_dict
  440. else:
  441. try:
  442. return memo_dict[key]
  443. except KeyError:
  444. pass
  445. if node:
  446. # TODO: better way to do this (it's a linear search,
  447. # but it may not be critical path)?
  448. sourcelist = []
  449. for b in self.batches:
  450. if node in b.targets:
  451. sourcelist = b.sources
  452. break
  453. else:
  454. sourcelist = self.get_all_sources()
  455. if ignore:
  456. idict = {}
  457. for i in ignore:
  458. idict[i] = 1
  459. sourcelist = [s for s in sourcelist if s not in idict]
  460. memo_dict[key] = sourcelist
  461. return sourcelist
  462. def get_implicit_deps(self):
  463. """Return the executor's implicit dependencies, i.e. the nodes of
  464. the commands to be executed."""
  465. result = []
  466. build_env = self.get_build_env()
  467. for act in self.get_action_list():
  468. deps = act.get_implicit_deps(self.get_all_targets(),
  469. self.get_all_sources(),
  470. build_env)
  471. result.extend(deps)
  472. return result
  473. _batch_executors = {}
  474. def GetBatchExecutor(key):
  475. return _batch_executors[key]
  476. def AddBatchExecutor(key, executor):
  477. assert key not in _batch_executors
  478. _batch_executors[key] = executor
  479. nullenv = None
  480. import SCons.Util
  481. class NullEnvironment(SCons.Util.Null):
  482. import SCons.CacheDir
  483. _CacheDir_path = None
  484. _CacheDir = SCons.CacheDir.CacheDir(None)
  485. def get_CacheDir(self):
  486. return self._CacheDir
  487. def get_NullEnvironment():
  488. """Use singleton pattern for Null Environments."""
  489. global nullenv
  490. if nullenv is None:
  491. nullenv = NullEnvironment()
  492. return nullenv
  493. class Null(object, with_metaclass(NoSlotsPyPy)):
  494. """A null Executor, with a null build Environment, that does
  495. nothing when the rest of the methods call it.
  496. This might be able to disappear when we refactor things to
  497. disassociate Builders from Nodes entirely, so we're not
  498. going to worry about unit tests for this--at least for now.
  499. """
  500. __slots__ = ('pre_actions',
  501. 'post_actions',
  502. 'env',
  503. 'overridelist',
  504. 'batches',
  505. 'builder_kw',
  506. '_memo',
  507. 'lvars',
  508. '_changed_sources_list',
  509. '_changed_targets_list',
  510. '_unchanged_sources_list',
  511. '_unchanged_targets_list',
  512. 'action_list',
  513. '_do_execute',
  514. '_execute_str')
  515. def __init__(self, *args, **kw):
  516. if SCons.Debug.track_instances: logInstanceCreation(self, 'Executor.Null')
  517. self.batches = [Batch(kw['targets'][:], [])]
  518. def get_build_env(self):
  519. return get_NullEnvironment()
  520. def get_build_scanner_path(self):
  521. return None
  522. def cleanup(self):
  523. pass
  524. def prepare(self):
  525. pass
  526. def get_unignored_sources(self, *args, **kw):
  527. return tuple(())
  528. def get_action_targets(self):
  529. return []
  530. def get_action_list(self):
  531. return []
  532. def get_all_targets(self):
  533. return self.batches[0].targets
  534. def get_all_sources(self):
  535. return self.batches[0].targets[0].sources
  536. def get_all_children(self):
  537. return self.batches[0].targets[0].children()
  538. def get_all_prerequisites(self):
  539. return []
  540. def get_action_side_effects(self):
  541. return []
  542. def __call__(self, *args, **kw):
  543. return 0
  544. def get_contents(self):
  545. return ''
  546. def _morph(self):
  547. """Morph this Null executor to a real Executor object."""
  548. batches = self.batches
  549. self.__class__ = Executor
  550. self.__init__([])
  551. self.batches = batches
  552. # The following methods require morphing this Null Executor to a
  553. # real Executor object.
  554. def add_pre_action(self, action):
  555. self._morph()
  556. self.add_pre_action(action)
  557. def add_post_action(self, action):
  558. self._morph()
  559. self.add_post_action(action)
  560. def set_action_list(self, action):
  561. self._morph()
  562. self.set_action_list(action)
  563. # Local Variables:
  564. # tab-width:4
  565. # indent-tabs-mode:nil
  566. # End:
  567. # vim: set expandtab tabstop=4 shiftwidth=4: