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.

421 lines
15 KiB

6 years ago
  1. """SCons.Scanner
  2. The Scanner package for the SCons software construction utility.
  3. """
  4. #
  5. # Copyright (c) 2001 - 2017 The SCons Foundation
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files (the
  9. # "Software"), to deal in the Software without restriction, including
  10. # without limitation the rights to use, copy, modify, merge, publish,
  11. # distribute, sublicense, and/or sell copies of the Software, and to
  12. # permit persons to whom the Software is furnished to do so, subject to
  13. # the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be included
  16. # in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  19. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  20. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. #
  26. __revision__ = "src/engine/SCons/Scanner/__init__.py rel_3.0.0:4395:8972f6a2f699 2017/09/18 12:59:24 bdbaddog"
  27. import re
  28. import SCons.Node.FS
  29. import SCons.Util
  30. class _Null(object):
  31. pass
  32. # This is used instead of None as a default argument value so None can be
  33. # used as an actual argument value.
  34. _null = _Null
  35. def Scanner(function, *args, **kw):
  36. """
  37. Public interface factory function for creating different types
  38. of Scanners based on the different types of "functions" that may
  39. be supplied.
  40. TODO: Deprecate this some day. We've moved the functionality
  41. inside the Base class and really don't need this factory function
  42. any more. It was, however, used by some of our Tool modules, so
  43. the call probably ended up in various people's custom modules
  44. patterned on SCons code.
  45. """
  46. if SCons.Util.is_Dict(function):
  47. return Selector(function, *args, **kw)
  48. else:
  49. return Base(function, *args, **kw)
  50. class FindPathDirs(object):
  51. """
  52. A class to bind a specific E{*}PATH variable name to a function that
  53. will return all of the E{*}path directories.
  54. """
  55. def __init__(self, variable):
  56. self.variable = variable
  57. def __call__(self, env, dir=None, target=None, source=None, argument=None):
  58. import SCons.PathList
  59. try:
  60. path = env[self.variable]
  61. except KeyError:
  62. return ()
  63. dir = dir or env.fs._cwd
  64. path = SCons.PathList.PathList(path).subst_path(env, target, source)
  65. return tuple(dir.Rfindalldirs(path))
  66. class Base(object):
  67. """
  68. The base class for dependency scanners. This implements
  69. straightforward, single-pass scanning of a single file.
  70. """
  71. def __init__(self,
  72. function,
  73. name = "NONE",
  74. argument = _null,
  75. skeys = _null,
  76. path_function = None,
  77. # Node.FS.Base so that, by default, it's okay for a
  78. # scanner to return a Dir, File or Entry.
  79. node_class = SCons.Node.FS.Base,
  80. node_factory = None,
  81. scan_check = None,
  82. recursive = None):
  83. """
  84. Construct a new scanner object given a scanner function.
  85. 'function' - a scanner function taking two or three
  86. arguments and returning a list of strings.
  87. 'name' - a name for identifying this scanner object.
  88. 'argument' - an optional argument that, if specified, will be
  89. passed to both the scanner function and the path_function.
  90. 'skeys' - an optional list argument that can be used to determine
  91. which scanner should be used for a given Node. In the case of File
  92. nodes, for example, the 'skeys' would be file suffixes.
  93. 'path_function' - a function that takes four or five arguments
  94. (a construction environment, Node for the directory containing
  95. the SConscript file that defined the primary target, list of
  96. target nodes, list of source nodes, and optional argument for
  97. this instance) and returns a tuple of the directories that can
  98. be searched for implicit dependency files. May also return a
  99. callable() which is called with no args and returns the tuple
  100. (supporting Bindable class).
  101. 'node_class' - the class of Nodes which this scan will return.
  102. If node_class is None, then this scanner will not enforce any
  103. Node conversion and will return the raw results from the
  104. underlying scanner function.
  105. 'node_factory' - the factory function to be called to translate
  106. the raw results returned by the scanner function into the
  107. expected node_class objects.
  108. 'scan_check' - a function to be called to first check whether
  109. this node really needs to be scanned.
  110. 'recursive' - specifies that this scanner should be invoked
  111. recursively on all of the implicit dependencies it returns
  112. (the canonical example being #include lines in C source files).
  113. May be a callable, which will be called to filter the list
  114. of nodes found to select a subset for recursive scanning
  115. (the canonical example being only recursively scanning
  116. subdirectories within a directory).
  117. The scanner function's first argument will be a Node that should
  118. be scanned for dependencies, the second argument will be an
  119. Environment object, the third argument will be the tuple of paths
  120. returned by the path_function, and the fourth argument will be
  121. the value passed into 'argument', and the returned list should
  122. contain the Nodes for all the direct dependencies of the file.
  123. Examples:
  124. s = Scanner(my_scanner_function)
  125. s = Scanner(function = my_scanner_function)
  126. s = Scanner(function = my_scanner_function, argument = 'foo')
  127. """
  128. # Note: this class could easily work with scanner functions that take
  129. # something other than a filename as an argument (e.g. a database
  130. # node) and a dependencies list that aren't file names. All that
  131. # would need to be changed is the documentation.
  132. self.function = function
  133. self.path_function = path_function
  134. self.name = name
  135. self.argument = argument
  136. if skeys is _null:
  137. if SCons.Util.is_Dict(function):
  138. skeys = list(function.keys())
  139. else:
  140. skeys = []
  141. self.skeys = skeys
  142. self.node_class = node_class
  143. self.node_factory = node_factory
  144. self.scan_check = scan_check
  145. if callable(recursive):
  146. self.recurse_nodes = recursive
  147. elif recursive:
  148. self.recurse_nodes = self._recurse_all_nodes
  149. else:
  150. self.recurse_nodes = self._recurse_no_nodes
  151. def path(self, env, dir=None, target=None, source=None):
  152. if not self.path_function:
  153. return ()
  154. if self.argument is not _null:
  155. return self.path_function(env, dir, target, source, self.argument)
  156. else:
  157. return self.path_function(env, dir, target, source)
  158. def __call__(self, node, env, path=()):
  159. """
  160. This method scans a single object. 'node' is the node
  161. that will be passed to the scanner function, and 'env' is the
  162. environment that will be passed to the scanner function. A list of
  163. direct dependency nodes for the specified node will be returned.
  164. """
  165. if self.scan_check and not self.scan_check(node, env):
  166. return []
  167. self = self.select(node)
  168. if not self.argument is _null:
  169. node_list = self.function(node, env, path, self.argument)
  170. else:
  171. node_list = self.function(node, env, path)
  172. kw = {}
  173. if hasattr(node, 'dir'):
  174. kw['directory'] = node.dir
  175. node_factory = env.get_factory(self.node_factory)
  176. nodes = []
  177. for l in node_list:
  178. if self.node_class and not isinstance(l, self.node_class):
  179. l = node_factory(l, **kw)
  180. nodes.append(l)
  181. return nodes
  182. def __eq__(self, other):
  183. try:
  184. return self.__dict__ == other.__dict__
  185. except AttributeError:
  186. # other probably doesn't have a __dict__
  187. return self.__dict__ == other
  188. def __hash__(self):
  189. return id(self)
  190. def __str__(self):
  191. return self.name
  192. def add_skey(self, skey):
  193. """Add a skey to the list of skeys"""
  194. self.skeys.append(skey)
  195. def get_skeys(self, env=None):
  196. if env and SCons.Util.is_String(self.skeys):
  197. return env.subst_list(self.skeys)[0]
  198. return self.skeys
  199. def select(self, node):
  200. if SCons.Util.is_Dict(self.function):
  201. key = node.scanner_key()
  202. try:
  203. return self.function[key]
  204. except KeyError:
  205. return None
  206. else:
  207. return self
  208. def _recurse_all_nodes(self, nodes):
  209. return nodes
  210. def _recurse_no_nodes(self, nodes):
  211. return []
  212. # recurse_nodes = _recurse_no_nodes
  213. def add_scanner(self, skey, scanner):
  214. self.function[skey] = scanner
  215. self.add_skey(skey)
  216. class Selector(Base):
  217. """
  218. A class for selecting a more specific scanner based on the
  219. scanner_key() (suffix) for a specific Node.
  220. TODO: This functionality has been moved into the inner workings of
  221. the Base class, and this class will be deprecated at some point.
  222. (It was never exposed directly as part of the public interface,
  223. although it is used by the Scanner() factory function that was
  224. used by various Tool modules and therefore was likely a template
  225. for custom modules that may be out there.)
  226. """
  227. def __init__(self, dict, *args, **kw):
  228. Base.__init__(self, None, *args, **kw)
  229. self.dict = dict
  230. self.skeys = list(dict.keys())
  231. def __call__(self, node, env, path=()):
  232. return self.select(node)(node, env, path)
  233. def select(self, node):
  234. try:
  235. return self.dict[node.scanner_key()]
  236. except KeyError:
  237. return None
  238. def add_scanner(self, skey, scanner):
  239. self.dict[skey] = scanner
  240. self.add_skey(skey)
  241. class Current(Base):
  242. """
  243. A class for scanning files that are source files (have no builder)
  244. or are derived files and are current (which implies that they exist,
  245. either locally or in a repository).
  246. """
  247. def __init__(self, *args, **kw):
  248. def current_check(node, env):
  249. return not node.has_builder() or node.is_up_to_date()
  250. kw['scan_check'] = current_check
  251. Base.__init__(self, *args, **kw)
  252. class Classic(Current):
  253. """
  254. A Scanner subclass to contain the common logic for classic CPP-style
  255. include scanning, but which can be customized to use different
  256. regular expressions to find the includes.
  257. Note that in order for this to work "out of the box" (without
  258. overriding the find_include() and sort_key() methods), the regular
  259. expression passed to the constructor must return the name of the
  260. include file in group 0.
  261. """
  262. def __init__(self, name, suffixes, path_variable, regex, *args, **kw):
  263. self.cre = re.compile(regex, re.M)
  264. def _scan(node, _, path=(), self=self):
  265. node = node.rfile()
  266. if not node.exists():
  267. return []
  268. return self.scan(node, path)
  269. kw['function'] = _scan
  270. kw['path_function'] = FindPathDirs(path_variable)
  271. # Allow recursive to propagate if child class specifies.
  272. # In this case resource scanner needs to specify a filter on which files
  273. # get recursively processed. Previously was hardcoded to 1 instead of
  274. # defaulted to 1.
  275. kw['recursive'] = kw.get('recursive', 1)
  276. kw['skeys'] = suffixes
  277. kw['name'] = name
  278. Current.__init__(self, *args, **kw)
  279. def find_include(self, include, source_dir, path):
  280. n = SCons.Node.FS.find_file(include, (source_dir,) + tuple(path))
  281. return n, include
  282. def sort_key(self, include):
  283. return SCons.Node.FS._my_normcase(include)
  284. def find_include_names(self, node):
  285. return self.cre.findall(node.get_text_contents())
  286. def scan(self, node, path=()):
  287. # cache the includes list in node so we only scan it once:
  288. if node.includes is not None:
  289. includes = node.includes
  290. else:
  291. includes = self.find_include_names(node)
  292. # Intern the names of the include files. Saves some memory
  293. # if the same header is included many times.
  294. node.includes = list(map(SCons.Util.silent_intern, includes))
  295. # This is a hand-coded DSU (decorate-sort-undecorate, or
  296. # Schwartzian transform) pattern. The sort key is the raw name
  297. # of the file as specifed on the #include line (including the
  298. # " or <, since that may affect what file is found), which lets
  299. # us keep the sort order constant regardless of whether the file
  300. # is actually found in a Repository or locally.
  301. nodes = []
  302. source_dir = node.get_dir()
  303. if callable(path):
  304. path = path()
  305. for include in includes:
  306. n, i = self.find_include(include, source_dir, path)
  307. if n is None:
  308. SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
  309. "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
  310. else:
  311. nodes.append((self.sort_key(include), n))
  312. return [pair[1] for pair in sorted(nodes)]
  313. class ClassicCPP(Classic):
  314. """
  315. A Classic Scanner subclass which takes into account the type of
  316. bracketing used to include the file, and uses classic CPP rules
  317. for searching for the files based on the bracketing.
  318. Note that in order for this to work, the regular expression passed
  319. to the constructor must return the leading bracket in group 0, and
  320. the contained filename in group 1.
  321. """
  322. def find_include(self, include, source_dir, path):
  323. include = list(map(SCons.Util.to_str, include))
  324. if include[0] == '"':
  325. paths = (source_dir,) + tuple(path)
  326. else:
  327. paths = tuple(path) + (source_dir,)
  328. n = SCons.Node.FS.find_file(include[1], paths)
  329. i = SCons.Util.silent_intern(include[1])
  330. return n, i
  331. def sort_key(self, include):
  332. return SCons.Node.FS._my_normcase(' '.join(include))
  333. # Local Variables:
  334. # tab-width:4
  335. # indent-tabs-mode:nil
  336. # End:
  337. # vim: set expandtab tabstop=4 shiftwidth=4: