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.

878 lines
33 KiB

6 years ago
  1. """
  2. SCons.Builder
  3. Builder object subsystem.
  4. A Builder object is a callable that encapsulates information about how
  5. to execute actions to create a target Node (file) from source Nodes
  6. (files), and how to create those dependencies for tracking.
  7. The main entry point here is the Builder() factory method. This provides
  8. a procedural interface that creates the right underlying Builder object
  9. based on the keyword arguments supplied and the types of the arguments.
  10. The goal is for this external interface to be simple enough that the
  11. vast majority of users can create new Builders as necessary to support
  12. building new types of files in their configurations, without having to
  13. dive any deeper into this subsystem.
  14. The base class here is BuilderBase. This is a concrete base class which
  15. does, in fact, represent the Builder objects that we (or users) create.
  16. There is also a proxy that looks like a Builder:
  17. CompositeBuilder
  18. This proxies for a Builder with an action that is actually a
  19. dictionary that knows how to map file suffixes to a specific
  20. action. This is so that we can invoke different actions
  21. (compilers, compile options) for different flavors of source
  22. files.
  23. Builders and their proxies have the following public interface methods
  24. used by other modules:
  25. - __call__()
  26. THE public interface. Calling a Builder object (with the
  27. use of internal helper methods) sets up the target and source
  28. dependencies, appropriate mapping to a specific action, and the
  29. environment manipulation necessary for overridden construction
  30. variable. This also takes care of warning about possible mistakes
  31. in keyword arguments.
  32. - add_emitter()
  33. Adds an emitter for a specific file suffix, used by some Tool
  34. modules to specify that (for example) a yacc invocation on a .y
  35. can create a .h *and* a .c file.
  36. - add_action()
  37. Adds an action for a specific file suffix, heavily used by
  38. Tool modules to add their specific action(s) for turning
  39. a source file into an object file to the global static
  40. and shared object file Builders.
  41. There are the following methods for internal use within this module:
  42. - _execute()
  43. The internal method that handles the heavily lifting when a
  44. Builder is called. This is used so that the __call__() methods
  45. can set up warning about possible mistakes in keyword-argument
  46. overrides, and *then* execute all of the steps necessary so that
  47. the warnings only occur once.
  48. - get_name()
  49. Returns the Builder's name within a specific Environment,
  50. primarily used to try to return helpful information in error
  51. messages.
  52. - adjust_suffix()
  53. - get_prefix()
  54. - get_suffix()
  55. - get_src_suffix()
  56. - set_src_suffix()
  57. Miscellaneous stuff for handling the prefix and suffix
  58. manipulation we use in turning source file names into target
  59. file names.
  60. """
  61. #
  62. # Copyright (c) 2001 - 2017 The SCons Foundation
  63. #
  64. # Permission is hereby granted, free of charge, to any person obtaining
  65. # a copy of this software and associated documentation files (the
  66. # "Software"), to deal in the Software without restriction, including
  67. # without limitation the rights to use, copy, modify, merge, publish,
  68. # distribute, sublicense, and/or sell copies of the Software, and to
  69. # permit persons to whom the Software is furnished to do so, subject to
  70. # the following conditions:
  71. #
  72. # The above copyright notice and this permission notice shall be included
  73. # in all copies or substantial portions of the Software.
  74. #
  75. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  76. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  77. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  78. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  79. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  80. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  81. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  82. __revision__ = "src/engine/SCons/Builder.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  83. import collections
  84. import SCons.Action
  85. import SCons.Debug
  86. from SCons.Debug import logInstanceCreation
  87. from SCons.Errors import InternalError, UserError
  88. import SCons.Executor
  89. import SCons.Memoize
  90. import SCons.Util
  91. import SCons.Warnings
  92. class _Null(object):
  93. pass
  94. _null = _Null
  95. def match_splitext(path, suffixes = []):
  96. if suffixes:
  97. matchsuf = [S for S in suffixes if path[-len(S):] == S]
  98. if matchsuf:
  99. suf = max([(len(_f),_f) for _f in matchsuf])[1]
  100. return [path[:-len(suf)], path[-len(suf):]]
  101. return SCons.Util.splitext(path)
  102. class DictCmdGenerator(SCons.Util.Selector):
  103. """This is a callable class that can be used as a
  104. command generator function. It holds on to a dictionary
  105. mapping file suffixes to Actions. It uses that dictionary
  106. to return the proper action based on the file suffix of
  107. the source file."""
  108. def __init__(self, dict=None, source_ext_match=1):
  109. SCons.Util.Selector.__init__(self, dict)
  110. self.source_ext_match = source_ext_match
  111. def src_suffixes(self):
  112. return list(self.keys())
  113. def add_action(self, suffix, action):
  114. """Add a suffix-action pair to the mapping.
  115. """
  116. self[suffix] = action
  117. def __call__(self, target, source, env, for_signature):
  118. if not source:
  119. return []
  120. if self.source_ext_match:
  121. suffixes = self.src_suffixes()
  122. ext = None
  123. for src in map(str, source):
  124. my_ext = match_splitext(src, suffixes)[1]
  125. if ext and my_ext != ext:
  126. raise UserError("While building `%s' from `%s': Cannot build multiple sources with different extensions: %s, %s"
  127. % (repr(list(map(str, target))), src, ext, my_ext))
  128. ext = my_ext
  129. else:
  130. ext = match_splitext(str(source[0]), self.src_suffixes())[1]
  131. if not ext:
  132. #return ext
  133. raise UserError("While building `%s': "
  134. "Cannot deduce file extension from source files: %s"
  135. % (repr(list(map(str, target))), repr(list(map(str, source)))))
  136. try:
  137. ret = SCons.Util.Selector.__call__(self, env, source, ext)
  138. except KeyError as e:
  139. raise UserError("Ambiguous suffixes after environment substitution: %s == %s == %s" % (e.args[0], e.args[1], e.args[2]))
  140. if ret is None:
  141. raise UserError("While building `%s' from `%s': Don't know how to build from a source file with suffix `%s'. Expected a suffix in this list: %s." % \
  142. (repr(list(map(str, target))), repr(list(map(str, source))), ext, repr(list(self.keys()))))
  143. return ret
  144. class CallableSelector(SCons.Util.Selector):
  145. """A callable dictionary that will, in turn, call the value it
  146. finds if it can."""
  147. def __call__(self, env, source):
  148. value = SCons.Util.Selector.__call__(self, env, source)
  149. if callable(value):
  150. value = value(env, source)
  151. return value
  152. class DictEmitter(SCons.Util.Selector):
  153. """A callable dictionary that maps file suffixes to emitters.
  154. When called, it finds the right emitter in its dictionary for the
  155. suffix of the first source file, and calls that emitter to get the
  156. right lists of targets and sources to return. If there's no emitter
  157. for the suffix in its dictionary, the original target and source are
  158. returned.
  159. """
  160. def __call__(self, target, source, env):
  161. emitter = SCons.Util.Selector.__call__(self, env, source)
  162. if emitter:
  163. target, source = emitter(target, source, env)
  164. return (target, source)
  165. class ListEmitter(collections.UserList):
  166. """A callable list of emitters that calls each in sequence,
  167. returning the result.
  168. """
  169. def __call__(self, target, source, env):
  170. for e in self.data:
  171. target, source = e(target, source, env)
  172. return (target, source)
  173. # These are a common errors when calling a Builder;
  174. # they are similar to the 'target' and 'source' keyword args to builders,
  175. # so we issue warnings when we see them. The warnings can, of course,
  176. # be disabled.
  177. misleading_keywords = {
  178. 'targets' : 'target',
  179. 'sources' : 'source',
  180. }
  181. class OverrideWarner(collections.UserDict):
  182. """A class for warning about keyword arguments that we use as
  183. overrides in a Builder call.
  184. This class exists to handle the fact that a single Builder call
  185. can actually invoke multiple builders. This class only emits the
  186. warnings once, no matter how many Builders are invoked.
  187. """
  188. def __init__(self, dict):
  189. collections.UserDict.__init__(self, dict)
  190. if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.OverrideWarner')
  191. self.already_warned = None
  192. def warn(self):
  193. if self.already_warned:
  194. return
  195. for k in list(self.keys()):
  196. if k in misleading_keywords:
  197. alt = misleading_keywords[k]
  198. msg = "Did you mean to use `%s' instead of `%s'?" % (alt, k)
  199. SCons.Warnings.warn(SCons.Warnings.MisleadingKeywordsWarning, msg)
  200. self.already_warned = 1
  201. def Builder(**kw):
  202. """A factory for builder objects."""
  203. composite = None
  204. if 'generator' in kw:
  205. if 'action' in kw:
  206. raise UserError("You must not specify both an action and a generator.")
  207. kw['action'] = SCons.Action.CommandGeneratorAction(kw['generator'], {})
  208. del kw['generator']
  209. elif 'action' in kw:
  210. source_ext_match = kw.get('source_ext_match', 1)
  211. if 'source_ext_match' in kw:
  212. del kw['source_ext_match']
  213. if SCons.Util.is_Dict(kw['action']):
  214. composite = DictCmdGenerator(kw['action'], source_ext_match)
  215. kw['action'] = SCons.Action.CommandGeneratorAction(composite, {})
  216. kw['src_suffix'] = composite.src_suffixes()
  217. else:
  218. kw['action'] = SCons.Action.Action(kw['action'])
  219. if 'emitter' in kw:
  220. emitter = kw['emitter']
  221. if SCons.Util.is_String(emitter):
  222. # This allows users to pass in an Environment
  223. # variable reference (like "$FOO") as an emitter.
  224. # We will look in that Environment variable for
  225. # a callable to use as the actual emitter.
  226. var = SCons.Util.get_environment_var(emitter)
  227. if not var:
  228. raise UserError("Supplied emitter '%s' does not appear to refer to an Environment variable" % emitter)
  229. kw['emitter'] = EmitterProxy(var)
  230. elif SCons.Util.is_Dict(emitter):
  231. kw['emitter'] = DictEmitter(emitter)
  232. elif SCons.Util.is_List(emitter):
  233. kw['emitter'] = ListEmitter(emitter)
  234. result = BuilderBase(**kw)
  235. if not composite is None:
  236. result = CompositeBuilder(result, composite)
  237. return result
  238. def _node_errors(builder, env, tlist, slist):
  239. """Validate that the lists of target and source nodes are
  240. legal for this builder and environment. Raise errors or
  241. issue warnings as appropriate.
  242. """
  243. # First, figure out if there are any errors in the way the targets
  244. # were specified.
  245. for t in tlist:
  246. if t.side_effect:
  247. raise UserError("Multiple ways to build the same target were specified for: %s" % t)
  248. if t.has_explicit_builder():
  249. if not t.env is None and not t.env is env:
  250. action = t.builder.action
  251. t_contents = t.builder.action.get_contents(tlist, slist, t.env)
  252. contents = builder.action.get_contents(tlist, slist, env)
  253. if t_contents == contents:
  254. msg = "Two different environments were specified for target %s,\n\tbut they appear to have the same action: %s" % (t, action.genstring(tlist, slist, t.env))
  255. SCons.Warnings.warn(SCons.Warnings.DuplicateEnvironmentWarning, msg)
  256. else:
  257. msg = "Two environments with different actions were specified for the same target: %s\n(action 1: %s)\n(action 2: %s)" % (t,t_contents.decode('utf-8'),contents.decode('utf-8'))
  258. raise UserError(msg)
  259. if builder.multi:
  260. if t.builder != builder:
  261. msg = "Two different builders (%s and %s) were specified for the same target: %s" % (t.builder.get_name(env), builder.get_name(env), t)
  262. raise UserError(msg)
  263. # TODO(batch): list constructed each time!
  264. if t.get_executor().get_all_targets() != tlist:
  265. msg = "Two different target lists have a target in common: %s (from %s and from %s)" % (t, list(map(str, t.get_executor().get_all_targets())), list(map(str, tlist)))
  266. raise UserError(msg)
  267. elif t.sources != slist:
  268. msg = "Multiple ways to build the same target were specified for: %s (from %s and from %s)" % (t, list(map(str, t.sources)), list(map(str, slist)))
  269. raise UserError(msg)
  270. if builder.single_source:
  271. if len(slist) > 1:
  272. raise UserError("More than one source given for single-source builder: targets=%s sources=%s" % (list(map(str,tlist)), list(map(str,slist))))
  273. class EmitterProxy(object):
  274. """This is a callable class that can act as a
  275. Builder emitter. It holds on to a string that
  276. is a key into an Environment dictionary, and will
  277. look there at actual build time to see if it holds
  278. a callable. If so, we will call that as the actual
  279. emitter."""
  280. def __init__(self, var):
  281. self.var = SCons.Util.to_String(var)
  282. def __call__(self, target, source, env):
  283. emitter = self.var
  284. # Recursively substitute the variable.
  285. # We can't use env.subst() because it deals only
  286. # in strings. Maybe we should change that?
  287. while SCons.Util.is_String(emitter) and emitter in env:
  288. emitter = env[emitter]
  289. if callable(emitter):
  290. target, source = emitter(target, source, env)
  291. elif SCons.Util.is_List(emitter):
  292. for e in emitter:
  293. target, source = e(target, source, env)
  294. return (target, source)
  295. def __eq__(self, other):
  296. return self.var == other.var
  297. def __lt__(self, other):
  298. return self.var < other.var
  299. class BuilderBase(object):
  300. """Base class for Builders, objects that create output
  301. nodes (files) from input nodes (files).
  302. """
  303. def __init__(self, action = None,
  304. prefix = '',
  305. suffix = '',
  306. src_suffix = '',
  307. target_factory = None,
  308. source_factory = None,
  309. target_scanner = None,
  310. source_scanner = None,
  311. emitter = None,
  312. multi = 0,
  313. env = None,
  314. single_source = 0,
  315. name = None,
  316. chdir = _null,
  317. is_explicit = 1,
  318. src_builder = None,
  319. ensure_suffix = False,
  320. **overrides):
  321. if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.BuilderBase')
  322. self._memo = {}
  323. self.action = action
  324. self.multi = multi
  325. if SCons.Util.is_Dict(prefix):
  326. prefix = CallableSelector(prefix)
  327. self.prefix = prefix
  328. if SCons.Util.is_Dict(suffix):
  329. suffix = CallableSelector(suffix)
  330. self.env = env
  331. self.single_source = single_source
  332. if 'overrides' in overrides:
  333. SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning,
  334. "The \"overrides\" keyword to Builder() creation has been deprecated;\n" +\
  335. "\tspecify the items as keyword arguments to the Builder() call instead.")
  336. overrides.update(overrides['overrides'])
  337. del overrides['overrides']
  338. if 'scanner' in overrides:
  339. SCons.Warnings.warn(SCons.Warnings.DeprecatedBuilderKeywordsWarning,
  340. "The \"scanner\" keyword to Builder() creation has been deprecated;\n"
  341. "\tuse: source_scanner or target_scanner as appropriate.")
  342. del overrides['scanner']
  343. self.overrides = overrides
  344. self.set_suffix(suffix)
  345. self.set_src_suffix(src_suffix)
  346. self.ensure_suffix = ensure_suffix
  347. self.target_factory = target_factory
  348. self.source_factory = source_factory
  349. self.target_scanner = target_scanner
  350. self.source_scanner = source_scanner
  351. self.emitter = emitter
  352. # Optional Builder name should only be used for Builders
  353. # that don't get attached to construction environments.
  354. if name:
  355. self.name = name
  356. self.executor_kw = {}
  357. if not chdir is _null:
  358. self.executor_kw['chdir'] = chdir
  359. self.is_explicit = is_explicit
  360. if src_builder is None:
  361. src_builder = []
  362. elif not SCons.Util.is_List(src_builder):
  363. src_builder = [ src_builder ]
  364. self.src_builder = src_builder
  365. def __nonzero__(self):
  366. raise InternalError("Do not test for the Node.builder attribute directly; use Node.has_builder() instead")
  367. def __bool__(self):
  368. return self.__nonzero__()
  369. def get_name(self, env):
  370. """Attempts to get the name of the Builder.
  371. Look at the BUILDERS variable of env, expecting it to be a
  372. dictionary containing this Builder, and return the key of the
  373. dictionary. If there's no key, then return a directly-configured
  374. name (if there is one) or the name of the class (by default)."""
  375. try:
  376. index = list(env['BUILDERS'].values()).index(self)
  377. return list(env['BUILDERS'].keys())[index]
  378. except (AttributeError, KeyError, TypeError, ValueError):
  379. try:
  380. return self.name
  381. except AttributeError:
  382. return str(self.__class__)
  383. def __eq__(self, other):
  384. return self.__dict__ == other.__dict__
  385. def splitext(self, path, env=None):
  386. if not env:
  387. env = self.env
  388. if env:
  389. suffixes = self.src_suffixes(env)
  390. else:
  391. suffixes = []
  392. return match_splitext(path, suffixes)
  393. def _adjustixes(self, files, pre, suf, ensure_suffix=False):
  394. if not files:
  395. return []
  396. result = []
  397. if not SCons.Util.is_List(files):
  398. files = [files]
  399. for f in files:
  400. if SCons.Util.is_String(f):
  401. f = SCons.Util.adjustixes(f, pre, suf, ensure_suffix)
  402. result.append(f)
  403. return result
  404. def _create_nodes(self, env, target = None, source = None):
  405. """Create and return lists of target and source nodes.
  406. """
  407. src_suf = self.get_src_suffix(env)
  408. target_factory = env.get_factory(self.target_factory)
  409. source_factory = env.get_factory(self.source_factory)
  410. source = self._adjustixes(source, None, src_suf)
  411. slist = env.arg2nodes(source, source_factory)
  412. pre = self.get_prefix(env, slist)
  413. suf = self.get_suffix(env, slist)
  414. if target is None:
  415. try:
  416. t_from_s = slist[0].target_from_source
  417. except AttributeError:
  418. raise UserError("Do not know how to create a target from source `%s'" % slist[0])
  419. except IndexError:
  420. tlist = []
  421. else:
  422. splitext = lambda S: self.splitext(S,env)
  423. tlist = [ t_from_s(pre, suf, splitext) ]
  424. else:
  425. target = self._adjustixes(target, pre, suf, self.ensure_suffix)
  426. tlist = env.arg2nodes(target, target_factory, target=target, source=source)
  427. if self.emitter:
  428. # The emitter is going to do str(node), but because we're
  429. # being called *from* a builder invocation, the new targets
  430. # don't yet have a builder set on them and will look like
  431. # source files. Fool the emitter's str() calls by setting
  432. # up a temporary builder on the new targets.
  433. new_targets = []
  434. for t in tlist:
  435. if not t.is_derived():
  436. t.builder_set(self)
  437. new_targets.append(t)
  438. orig_tlist = tlist[:]
  439. orig_slist = slist[:]
  440. target, source = self.emitter(target=tlist, source=slist, env=env)
  441. # Now delete the temporary builders that we attached to any
  442. # new targets, so that _node_errors() doesn't do weird stuff
  443. # to them because it thinks they already have builders.
  444. for t in new_targets:
  445. if t.builder is self:
  446. # Only delete the temporary builder if the emitter
  447. # didn't change it on us.
  448. t.builder_set(None)
  449. # Have to call arg2nodes yet again, since it is legal for
  450. # emitters to spit out strings as well as Node instances.
  451. tlist = env.arg2nodes(target, target_factory,
  452. target=orig_tlist, source=orig_slist)
  453. slist = env.arg2nodes(source, source_factory,
  454. target=orig_tlist, source=orig_slist)
  455. return tlist, slist
  456. def _execute(self, env, target, source, overwarn={}, executor_kw={}):
  457. # We now assume that target and source are lists or None.
  458. if self.src_builder:
  459. source = self.src_builder_sources(env, source, overwarn)
  460. if self.single_source and len(source) > 1 and target is None:
  461. result = []
  462. if target is None: target = [None]*len(source)
  463. for tgt, src in zip(target, source):
  464. if not tgt is None: tgt = [tgt]
  465. if not src is None: src = [src]
  466. result.extend(self._execute(env, tgt, src, overwarn))
  467. return SCons.Node.NodeList(result)
  468. overwarn.warn()
  469. tlist, slist = self._create_nodes(env, target, source)
  470. # Check for errors with the specified target/source lists.
  471. _node_errors(self, env, tlist, slist)
  472. # The targets are fine, so find or make the appropriate Executor to
  473. # build this particular list of targets from this particular list of
  474. # sources.
  475. executor = None
  476. key = None
  477. if self.multi:
  478. try:
  479. executor = tlist[0].get_executor(create = 0)
  480. except (AttributeError, IndexError):
  481. pass
  482. else:
  483. executor.add_sources(slist)
  484. if executor is None:
  485. if not self.action:
  486. fmt = "Builder %s must have an action to build %s."
  487. raise UserError(fmt % (self.get_name(env or self.env),
  488. list(map(str,tlist))))
  489. key = self.action.batch_key(env or self.env, tlist, slist)
  490. if key:
  491. try:
  492. executor = SCons.Executor.GetBatchExecutor(key)
  493. except KeyError:
  494. pass
  495. else:
  496. executor.add_batch(tlist, slist)
  497. if executor is None:
  498. executor = SCons.Executor.Executor(self.action, env, [],
  499. tlist, slist, executor_kw)
  500. if key:
  501. SCons.Executor.AddBatchExecutor(key, executor)
  502. # Now set up the relevant information in the target Nodes themselves.
  503. for t in tlist:
  504. t.cwd = env.fs.getcwd()
  505. t.builder_set(self)
  506. t.env_set(env)
  507. t.add_source(slist)
  508. t.set_executor(executor)
  509. t.set_explicit(self.is_explicit)
  510. return SCons.Node.NodeList(tlist)
  511. def __call__(self, env, target=None, source=None, chdir=_null, **kw):
  512. # We now assume that target and source are lists or None.
  513. # The caller (typically Environment.BuilderWrapper) is
  514. # responsible for converting any scalar values to lists.
  515. if chdir is _null:
  516. ekw = self.executor_kw
  517. else:
  518. ekw = self.executor_kw.copy()
  519. ekw['chdir'] = chdir
  520. if 'chdir' in ekw and SCons.Util.is_String(ekw['chdir']):
  521. ekw['chdir'] = env.subst(ekw['chdir'])
  522. if kw:
  523. if 'srcdir' in kw:
  524. def prependDirIfRelative(f, srcdir=kw['srcdir']):
  525. import os.path
  526. if SCons.Util.is_String(f) and not os.path.isabs(f):
  527. f = os.path.join(srcdir, f)
  528. return f
  529. if not SCons.Util.is_List(source):
  530. source = [source]
  531. source = list(map(prependDirIfRelative, source))
  532. del kw['srcdir']
  533. if self.overrides:
  534. env_kw = self.overrides.copy()
  535. env_kw.update(kw)
  536. else:
  537. env_kw = kw
  538. else:
  539. env_kw = self.overrides
  540. env = env.Override(env_kw)
  541. return self._execute(env, target, source, OverrideWarner(kw), ekw)
  542. def adjust_suffix(self, suff):
  543. if suff and not suff[0] in [ '.', '_', '$' ]:
  544. return '.' + suff
  545. return suff
  546. def get_prefix(self, env, sources=[]):
  547. prefix = self.prefix
  548. if callable(prefix):
  549. prefix = prefix(env, sources)
  550. return env.subst(prefix)
  551. def set_suffix(self, suffix):
  552. if not callable(suffix):
  553. suffix = self.adjust_suffix(suffix)
  554. self.suffix = suffix
  555. def get_suffix(self, env, sources=[]):
  556. suffix = self.suffix
  557. if callable(suffix):
  558. suffix = suffix(env, sources)
  559. return env.subst(suffix)
  560. def set_src_suffix(self, src_suffix):
  561. if not src_suffix:
  562. src_suffix = []
  563. elif not SCons.Util.is_List(src_suffix):
  564. src_suffix = [ src_suffix ]
  565. self.src_suffix = [callable(suf) and suf or self.adjust_suffix(suf) for suf in src_suffix]
  566. def get_src_suffix(self, env):
  567. """Get the first src_suffix in the list of src_suffixes."""
  568. ret = self.src_suffixes(env)
  569. if not ret:
  570. return ''
  571. return ret[0]
  572. def add_emitter(self, suffix, emitter):
  573. """Add a suffix-emitter mapping to this Builder.
  574. This assumes that emitter has been initialized with an
  575. appropriate dictionary type, and will throw a TypeError if
  576. not, so the caller is responsible for knowing that this is an
  577. appropriate method to call for the Builder in question.
  578. """
  579. self.emitter[suffix] = emitter
  580. def add_src_builder(self, builder):
  581. """
  582. Add a new Builder to the list of src_builders.
  583. This requires wiping out cached values so that the computed
  584. lists of source suffixes get re-calculated.
  585. """
  586. self._memo = {}
  587. self.src_builder.append(builder)
  588. def _get_sdict(self, env):
  589. """
  590. Returns a dictionary mapping all of the source suffixes of all
  591. src_builders of this Builder to the underlying Builder that
  592. should be called first.
  593. This dictionary is used for each target specified, so we save a
  594. lot of extra computation by memoizing it for each construction
  595. environment.
  596. Note that this is re-computed each time, not cached, because there
  597. might be changes to one of our source Builders (or one of their
  598. source Builders, and so on, and so on...) that we can't "see."
  599. The underlying methods we call cache their computed values,
  600. though, so we hope repeatedly aggregating them into a dictionary
  601. like this won't be too big a hit. We may need to look for a
  602. better way to do this if performance data show this has turned
  603. into a significant bottleneck.
  604. """
  605. sdict = {}
  606. for bld in self.get_src_builders(env):
  607. for suf in bld.src_suffixes(env):
  608. sdict[suf] = bld
  609. return sdict
  610. def src_builder_sources(self, env, source, overwarn={}):
  611. sdict = self._get_sdict(env)
  612. src_suffixes = self.src_suffixes(env)
  613. lengths = list(set(map(len, src_suffixes)))
  614. def match_src_suffix(name, src_suffixes=src_suffixes, lengths=lengths):
  615. node_suffixes = [name[-l:] for l in lengths]
  616. for suf in src_suffixes:
  617. if suf in node_suffixes:
  618. return suf
  619. return None
  620. result = []
  621. for s in SCons.Util.flatten(source):
  622. if SCons.Util.is_String(s):
  623. match_suffix = match_src_suffix(env.subst(s))
  624. if not match_suffix and not '.' in s:
  625. src_suf = self.get_src_suffix(env)
  626. s = self._adjustixes(s, None, src_suf)[0]
  627. else:
  628. match_suffix = match_src_suffix(s.name)
  629. if match_suffix:
  630. try:
  631. bld = sdict[match_suffix]
  632. except KeyError:
  633. result.append(s)
  634. else:
  635. tlist = bld._execute(env, None, [s], overwarn)
  636. # If the subsidiary Builder returned more than one
  637. # target, then filter out any sources that this
  638. # Builder isn't capable of building.
  639. if len(tlist) > 1:
  640. tlist = [t for t in tlist if match_src_suffix(t.name)]
  641. result.extend(tlist)
  642. else:
  643. result.append(s)
  644. source_factory = env.get_factory(self.source_factory)
  645. return env.arg2nodes(result, source_factory)
  646. def _get_src_builders_key(self, env):
  647. return id(env)
  648. @SCons.Memoize.CountDictCall(_get_src_builders_key)
  649. def get_src_builders(self, env):
  650. """
  651. Returns the list of source Builders for this Builder.
  652. This exists mainly to look up Builders referenced as
  653. strings in the 'BUILDER' variable of the construction
  654. environment and cache the result.
  655. """
  656. memo_key = id(env)
  657. try:
  658. memo_dict = self._memo['get_src_builders']
  659. except KeyError:
  660. memo_dict = {}
  661. self._memo['get_src_builders'] = memo_dict
  662. else:
  663. try:
  664. return memo_dict[memo_key]
  665. except KeyError:
  666. pass
  667. builders = []
  668. for bld in self.src_builder:
  669. if SCons.Util.is_String(bld):
  670. try:
  671. bld = env['BUILDERS'][bld]
  672. except KeyError:
  673. continue
  674. builders.append(bld)
  675. memo_dict[memo_key] = builders
  676. return builders
  677. def _subst_src_suffixes_key(self, env):
  678. return id(env)
  679. @SCons.Memoize.CountDictCall(_subst_src_suffixes_key)
  680. def subst_src_suffixes(self, env):
  681. """
  682. The suffix list may contain construction variable expansions,
  683. so we have to evaluate the individual strings. To avoid doing
  684. this over and over, we memoize the results for each construction
  685. environment.
  686. """
  687. memo_key = id(env)
  688. try:
  689. memo_dict = self._memo['subst_src_suffixes']
  690. except KeyError:
  691. memo_dict = {}
  692. self._memo['subst_src_suffixes'] = memo_dict
  693. else:
  694. try:
  695. return memo_dict[memo_key]
  696. except KeyError:
  697. pass
  698. suffixes = [env.subst(x) for x in self.src_suffix]
  699. memo_dict[memo_key] = suffixes
  700. return suffixes
  701. def src_suffixes(self, env):
  702. """
  703. Returns the list of source suffixes for all src_builders of this
  704. Builder.
  705. This is essentially a recursive descent of the src_builder "tree."
  706. (This value isn't cached because there may be changes in a
  707. src_builder many levels deep that we can't see.)
  708. """
  709. sdict = {}
  710. suffixes = self.subst_src_suffixes(env)
  711. for s in suffixes:
  712. sdict[s] = 1
  713. for builder in self.get_src_builders(env):
  714. for s in builder.src_suffixes(env):
  715. if s not in sdict:
  716. sdict[s] = 1
  717. suffixes.append(s)
  718. return suffixes
  719. class CompositeBuilder(SCons.Util.Proxy):
  720. """A Builder Proxy whose main purpose is to always have
  721. a DictCmdGenerator as its action, and to provide access
  722. to the DictCmdGenerator's add_action() method.
  723. """
  724. def __init__(self, builder, cmdgen):
  725. if SCons.Debug.track_instances: logInstanceCreation(self, 'Builder.CompositeBuilder')
  726. SCons.Util.Proxy.__init__(self, builder)
  727. # cmdgen should always be an instance of DictCmdGenerator.
  728. self.cmdgen = cmdgen
  729. self.builder = builder
  730. __call__ = SCons.Util.Delegate('__call__')
  731. def add_action(self, suffix, action):
  732. self.cmdgen.add_action(suffix, action)
  733. self.set_src_suffix(self.cmdgen.src_suffixes())
  734. def is_a_Builder(obj):
  735. """"Returns True if the specified obj is one of our Builder classes.
  736. The test is complicated a bit by the fact that CompositeBuilder
  737. is a proxy, not a subclass of BuilderBase.
  738. """
  739. return (isinstance(obj, BuilderBase)
  740. or isinstance(obj, CompositeBuilder)
  741. or callable(obj))
  742. # Local Variables:
  743. # tab-width:4
  744. # indent-tabs-mode:nil
  745. # End:
  746. # vim: set expandtab tabstop=4 shiftwidth=4: