introspection.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # Copyright 2018 The Meson development team
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. # Unless required by applicable law or agreed to in writing, software
  7. # distributed under the License is distributed on an "AS IS" BASIS,
  8. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. # See the License for the specific language governing permissions and
  10. # limitations under the License.
  11. # This class contains the basic functionality needed to run any interpreter
  12. # or an interpreter-based tool
  13. from . import AstInterpreter
  14. from .. import compilers, environment, mesonlib, mparser, optinterpreter
  15. from .. import coredata as cdata
  16. from ..interpreterbase import InvalidArguments
  17. from ..build import Executable, Jar, SharedLibrary, SharedModule, StaticLibrary
  18. import os
  19. build_target_functions = ['executable', 'jar', 'library', 'shared_library', 'shared_module', 'static_library', 'both_libraries']
  20. class IntrospectionHelper:
  21. # mimic an argparse namespace
  22. def __init__(self, cross_file):
  23. self.cross_file = cross_file
  24. self.native_file = None
  25. self.cmd_line_options = {}
  26. class IntrospectionInterpreter(AstInterpreter):
  27. # Interpreter to detect the options without a build directory
  28. # Most of the code is stolen from interperter.Interpreter
  29. def __init__(self, source_root, subdir, backend, cross_file=None, subproject='', subproject_dir='subprojects', env=None):
  30. super().__init__(source_root, subdir)
  31. options = IntrospectionHelper(cross_file)
  32. self.cross_file = cross_file
  33. if env is None:
  34. self.environment = environment.Environment(source_root, None, options)
  35. else:
  36. self.environment = env
  37. self.subproject = subproject
  38. self.subproject_dir = subproject_dir
  39. self.coredata = self.environment.get_coredata()
  40. self.option_file = os.path.join(self.source_root, self.subdir, 'meson_options.txt')
  41. self.backend = backend
  42. self.default_options = {'backend': self.backend}
  43. self.project_data = {}
  44. self.targets = []
  45. self.funcs.update({
  46. 'add_languages': self.func_add_languages,
  47. 'executable': self.func_executable,
  48. 'jar': self.func_jar,
  49. 'library': self.func_library,
  50. 'project': self.func_project,
  51. 'shared_library': self.func_shared_lib,
  52. 'shared_module': self.func_shared_module,
  53. 'static_library': self.func_static_lib,
  54. 'both_libraries': self.func_both_lib,
  55. })
  56. def func_project(self, node, args, kwargs):
  57. if len(args) < 1:
  58. raise InvalidArguments('Not enough arguments to project(). Needs at least the project name.')
  59. proj_name = args[0]
  60. proj_vers = kwargs.get('version', 'undefined')
  61. proj_langs = self.flatten_args(args[1:])
  62. if isinstance(proj_vers, mparser.ElementaryNode):
  63. proj_vers = proj_vers.value
  64. if not isinstance(proj_vers, str):
  65. proj_vers = 'undefined'
  66. self.project_data = {'descriptive_name': proj_name, 'version': proj_vers}
  67. if os.path.exists(self.option_file):
  68. oi = optinterpreter.OptionInterpreter(self.subproject)
  69. oi.process(self.option_file)
  70. self.coredata.merge_user_options(oi.options)
  71. def_opts = self.flatten_args(kwargs.get('default_options', []))
  72. self.project_default_options = mesonlib.stringlistify(def_opts)
  73. self.project_default_options = cdata.create_options_dict(self.project_default_options)
  74. self.default_options.update(self.project_default_options)
  75. self.coredata.set_default_options(self.default_options, self.subproject, self.environment.cmd_line_options)
  76. if not self.is_subproject() and 'subproject_dir' in kwargs:
  77. spdirname = kwargs['subproject_dir']
  78. if isinstance(spdirname, str):
  79. self.subproject_dir = spdirname
  80. if not self.is_subproject():
  81. self.project_data['subprojects'] = []
  82. subprojects_dir = os.path.join(self.source_root, self.subproject_dir)
  83. if os.path.isdir(subprojects_dir):
  84. for i in os.listdir(subprojects_dir):
  85. if os.path.isdir(os.path.join(subprojects_dir, i)):
  86. self.do_subproject(i)
  87. self.coredata.init_backend_options(self.backend)
  88. options = {k: v for k, v in self.environment.cmd_line_options.items() if k.startswith('backend_')}
  89. self.coredata.set_options(options)
  90. self.func_add_languages(None, proj_langs, None)
  91. def do_subproject(self, dirname):
  92. subproject_dir_abs = os.path.join(self.environment.get_source_dir(), self.subproject_dir)
  93. subpr = os.path.join(subproject_dir_abs, dirname)
  94. try:
  95. subi = IntrospectionInterpreter(subpr, '', self.backend, cross_file=self.cross_file, subproject=dirname, subproject_dir=self.subproject_dir, env=self.environment)
  96. subi.analyze()
  97. subi.project_data['name'] = dirname
  98. self.project_data['subprojects'] += [subi.project_data]
  99. except:
  100. return
  101. def func_add_languages(self, node, args, kwargs):
  102. args = self.flatten_args(args)
  103. need_cross_compiler = self.environment.is_cross_build()
  104. for lang in sorted(args, key=compilers.sort_clink):
  105. lang = lang.lower()
  106. if lang not in self.coredata.compilers:
  107. self.environment.detect_compilers(lang, need_cross_compiler)
  108. def build_target(self, node, args, kwargs, targetclass):
  109. if not args:
  110. return
  111. kwargs = self.flatten_kwargs(kwargs, True)
  112. name = self.flatten_args(args)[0]
  113. srcqueue = [node]
  114. if 'sources' in kwargs:
  115. srcqueue += kwargs['sources']
  116. source_nodes = []
  117. while srcqueue:
  118. curr = srcqueue.pop(0)
  119. arg_node = None
  120. if isinstance(curr, mparser.FunctionNode):
  121. arg_node = curr.args
  122. elif isinstance(curr, mparser.ArrayNode):
  123. arg_node = curr.args
  124. elif isinstance(curr, mparser.IdNode):
  125. # Try to resolve the ID and append the node to the queue
  126. id = curr.value
  127. if id in self.assignments and self.assignments[id]:
  128. node = self.assignments[id][0]
  129. if isinstance(node, (mparser.ArrayNode, mparser.IdNode, mparser.FunctionNode)):
  130. srcqueue += [node]
  131. if arg_node is None:
  132. continue
  133. elemetary_nodes = list(filter(lambda x: isinstance(x, (str, mparser.StringNode)), arg_node.arguments))
  134. srcqueue += list(filter(lambda x: isinstance(x, (mparser.FunctionNode, mparser.ArrayNode, mparser.IdNode)), arg_node.arguments))
  135. # Pop the first element if the function is a build target function
  136. if isinstance(curr, mparser.FunctionNode) and curr.func_name in build_target_functions:
  137. elemetary_nodes.pop(0)
  138. if elemetary_nodes:
  139. source_nodes += [curr]
  140. # Filter out kwargs from other target types. For example 'soversion'
  141. # passed to library() when default_library == 'static'.
  142. kwargs = {k: v for k, v in kwargs.items() if k in targetclass.known_kwargs}
  143. is_cross = False
  144. objects = []
  145. empty_sources = [] # Passing the unresolved sources list causes errors
  146. target = targetclass(name, self.subdir, self.subproject, is_cross, empty_sources, objects, self.environment, kwargs)
  147. self.targets += [{
  148. 'name': target.get_basename(),
  149. 'id': target.get_id(),
  150. 'type': target.get_typename(),
  151. 'defined_in': os.path.normpath(os.path.join(self.source_root, self.subdir, environment.build_filename)),
  152. 'subdir': self.subdir,
  153. 'build_by_default': target.build_by_default,
  154. 'sources': source_nodes,
  155. 'kwargs': kwargs,
  156. 'node': node,
  157. }]
  158. return
  159. def build_library(self, node, args, kwargs):
  160. default_library = self.coredata.get_builtin_option('default_library')
  161. if default_library == 'shared':
  162. return self.build_target(node, args, kwargs, SharedLibrary)
  163. elif default_library == 'static':
  164. return self.build_target(node, args, kwargs, StaticLibrary)
  165. elif default_library == 'both':
  166. return self.build_target(node, args, kwargs, SharedLibrary)
  167. def func_executable(self, node, args, kwargs):
  168. return self.build_target(node, args, kwargs, Executable)
  169. def func_static_lib(self, node, args, kwargs):
  170. return self.build_target(node, args, kwargs, StaticLibrary)
  171. def func_shared_lib(self, node, args, kwargs):
  172. return self.build_target(node, args, kwargs, SharedLibrary)
  173. def func_both_lib(self, node, args, kwargs):
  174. return self.build_target(node, args, kwargs, SharedLibrary)
  175. def func_shared_module(self, node, args, kwargs):
  176. return self.build_target(node, args, kwargs, SharedModule)
  177. def func_library(self, node, args, kwargs):
  178. return self.build_library(node, args, kwargs)
  179. def func_jar(self, node, args, kwargs):
  180. return self.build_target(node, args, kwargs, Jar)
  181. def func_build_target(self, node, args, kwargs):
  182. if 'target_type' not in kwargs:
  183. return
  184. target_type = kwargs.pop('target_type')
  185. if isinstance(target_type, mparser.ElementaryNode):
  186. target_type = target_type.value
  187. if target_type == 'executable':
  188. return self.build_target(node, args, kwargs, Executable)
  189. elif target_type == 'shared_library':
  190. return self.build_target(node, args, kwargs, SharedLibrary)
  191. elif target_type == 'static_library':
  192. return self.build_target(node, args, kwargs, StaticLibrary)
  193. elif target_type == 'both_libraries':
  194. return self.build_target(node, args, kwargs, SharedLibrary)
  195. elif target_type == 'library':
  196. return self.build_library(node, args, kwargs)
  197. elif target_type == 'jar':
  198. return self.build_target(node, args, kwargs, Jar)
  199. def is_subproject(self):
  200. return self.subproject != ''
  201. def analyze(self):
  202. self.load_root_meson_file()
  203. self.sanity_check_ast()
  204. self.parse_project()
  205. self.run()