build.py 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884
  1. # Copyright 2012-2017 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. import copy, os, re
  12. from pathlib import PurePath
  13. from collections import OrderedDict
  14. import itertools
  15. from . import environment
  16. from . import dependencies
  17. from . import mlog
  18. from .mesonlib import File, MesonException, listify, extract_as_list
  19. from .mesonlib import typeslistify, stringlistify, classify_unity_sources
  20. from .mesonlib import get_filenames_templates_dict, substitute_values
  21. from .mesonlib import for_windows, for_darwin, for_cygwin
  22. from .compilers import is_object, clike_langs, sort_clike, lang_suffixes
  23. known_basic_kwargs = {'install': True,
  24. 'c_pch': True,
  25. 'cpp_pch': True,
  26. 'c_args': True,
  27. 'objc_args': True,
  28. 'objcpp_args': True,
  29. 'cpp_args': True,
  30. 'cs_args': True,
  31. 'vala_args': True,
  32. 'fortran_args': True,
  33. 'd_args': True,
  34. 'd_import_dirs': True,
  35. 'd_unittest': True,
  36. 'd_module_versions': True,
  37. 'java_args': True,
  38. 'rust_args': True,
  39. 'link_args': True,
  40. 'link_depends': True,
  41. 'link_with': True,
  42. 'link_whole': True,
  43. 'implicit_include_directories': True,
  44. 'include_directories': True,
  45. 'dependencies': True,
  46. 'install_dir': True,
  47. 'main_class': True,
  48. 'name_suffix': True,
  49. 'gui_app': True,
  50. 'extra_files': True,
  51. 'install_rpath': True,
  52. 'build_rpath': True,
  53. 'resources': True,
  54. 'sources': True,
  55. 'objects': True,
  56. 'native': True,
  57. 'build_by_default': True,
  58. 'override_options': True,
  59. }
  60. # These contain kwargs supported by both static and shared libraries. These are
  61. # combined here because a library() call might be shared_library() or
  62. # static_library() at runtime based on the configuration.
  63. # FIXME: Find a way to pass that info down here so we can have proper target
  64. # kwargs checking when specifically using shared_library() or static_library().
  65. known_lib_kwargs = known_basic_kwargs.copy()
  66. known_lib_kwargs.update({'version': True, # Only for shared libs
  67. 'soversion': True, # Only for shared libs
  68. 'name_prefix': True,
  69. 'vs_module_defs': True, # Only for shared libs
  70. 'vala_header': True,
  71. 'vala_vapi': True,
  72. 'vala_gir': True,
  73. 'pic': True, # Only for static libs
  74. 'rust_crate_type': True, # Only for Rust libs
  75. })
  76. known_exe_kwargs = known_basic_kwargs.copy()
  77. known_exe_kwargs.update({'implib': True,
  78. })
  79. class InvalidArguments(MesonException):
  80. pass
  81. class Build:
  82. """A class that holds the status of one build including
  83. all dependencies and so on.
  84. """
  85. def __init__(self, environment):
  86. self.project_name = 'name of master project'
  87. self.project_version = None
  88. self.environment = environment
  89. self.projects = {}
  90. self.targets = OrderedDict()
  91. self.compilers = OrderedDict()
  92. self.cross_compilers = OrderedDict()
  93. self.global_args = {}
  94. self.projects_args = {}
  95. self.global_link_args = {}
  96. self.projects_link_args = {}
  97. self.tests = []
  98. self.benchmarks = []
  99. self.headers = []
  100. self.man = []
  101. self.data = []
  102. self.static_linker = None
  103. self.static_cross_linker = None
  104. self.subprojects = {}
  105. self.install_scripts = []
  106. self.postconf_scripts = []
  107. self.install_dirs = []
  108. self.dep_manifest_name = None
  109. self.dep_manifest = {}
  110. self.cross_stdlibs = {}
  111. self.test_setups = {}
  112. def add_compiler(self, compiler):
  113. if self.static_linker is None and compiler.needs_static_linker():
  114. self.static_linker = self.environment.detect_static_linker(compiler)
  115. lang = compiler.get_language()
  116. if lang not in self.compilers:
  117. self.compilers[lang] = compiler
  118. def add_cross_compiler(self, compiler):
  119. if not self.cross_compilers:
  120. self.static_cross_linker = self.environment.detect_static_linker(compiler)
  121. lang = compiler.get_language()
  122. if lang not in self.cross_compilers:
  123. self.cross_compilers[lang] = compiler
  124. def get_project(self):
  125. return self.projects['']
  126. def get_targets(self):
  127. return self.targets
  128. def get_tests(self):
  129. return self.tests
  130. def get_benchmarks(self):
  131. return self.benchmarks
  132. def get_headers(self):
  133. return self.headers
  134. def get_man(self):
  135. return self.man
  136. def get_data(self):
  137. return self.data
  138. def get_install_subdirs(self):
  139. return self.install_dirs
  140. def get_global_args(self, compiler):
  141. return self.global_args.get(compiler.get_language(), [])
  142. def get_project_args(self, compiler, project):
  143. args = self.projects_args.get(project)
  144. if not args:
  145. return []
  146. return args.get(compiler.get_language(), [])
  147. def get_global_link_args(self, compiler):
  148. return self.global_link_args.get(compiler.get_language(), [])
  149. def get_project_link_args(self, compiler, project):
  150. link_args = self.projects_link_args.get(project)
  151. if not link_args:
  152. return []
  153. return link_args.get(compiler.get_language(), [])
  154. class IncludeDirs:
  155. def __init__(self, curdir, dirs, is_system, extra_build_dirs=None):
  156. self.curdir = curdir
  157. self.incdirs = dirs
  158. self.is_system = is_system
  159. # Interpreter has validated that all given directories
  160. # actually exist.
  161. if extra_build_dirs is None:
  162. self.extra_build_dirs = []
  163. else:
  164. self.extra_build_dirs = extra_build_dirs
  165. def __repr__(self):
  166. r = '<{} {}/{}>'
  167. return r.format(self.__class__.__name__, self.curdir, self.incdirs)
  168. def get_curdir(self):
  169. return self.curdir
  170. def get_incdirs(self):
  171. return self.incdirs
  172. def get_extra_build_dirs(self):
  173. return self.extra_build_dirs
  174. class ExtractedObjects:
  175. '''
  176. Holds a list of sources for which the objects must be extracted
  177. '''
  178. def __init__(self, target, srclist, is_unity):
  179. self.target = target
  180. self.srclist = srclist
  181. if is_unity:
  182. self.check_unity_compatible()
  183. def __repr__(self):
  184. r = '<{0} {1!r}: {2}>'
  185. return r.format(self.__class__.__name__, self.target.name, self.srclist)
  186. def check_unity_compatible(self):
  187. # Figure out if the extracted object list is compatible with a Unity
  188. # build. When we're doing a Unified build, we go through the sources,
  189. # and create a single source file from each subset of the sources that
  190. # can be compiled with a specific compiler. Then we create one object
  191. # from each unified source file.
  192. # If the list of sources for which we want objects is the same as the
  193. # list of sources that go into each unified build, we're good.
  194. srclist_set = set(self.srclist)
  195. # Objects for all the sources are required, so we're compatible
  196. if srclist_set == set(self.target.sources):
  197. return
  198. # Check if the srclist is a subset (of the target's sources) that is
  199. # going to form a unified source file and a single object
  200. compsrcs = classify_unity_sources(self.target.compilers.values(),
  201. self.target.sources)
  202. for srcs in compsrcs.values():
  203. if srclist_set == set(srcs):
  204. return
  205. msg = 'Single object files can not be extracted in Unity builds. ' \
  206. 'You can only extract all the object files at once.'
  207. raise MesonException(msg)
  208. class EnvironmentVariables:
  209. def __init__(self):
  210. self.envvars = []
  211. def __repr__(self):
  212. repr_str = "<{0}: {1}>"
  213. return repr_str.format(self.__class__.__name__, self.envvars)
  214. def get_value(self, values, kwargs):
  215. separator = kwargs.get('separator', os.pathsep)
  216. value = ''
  217. for var in values:
  218. value += separator + var
  219. return separator, value.strip(separator)
  220. def set(self, env, name, values, kwargs):
  221. return self.get_value(values, kwargs)[1]
  222. def append(self, env, name, values, kwargs):
  223. sep, value = self.get_value(values, kwargs)
  224. if name in env:
  225. return env[name] + sep + value
  226. return value
  227. def prepend(self, env, name, values, kwargs):
  228. sep, value = self.get_value(values, kwargs)
  229. if name in env:
  230. return value + sep + env[name]
  231. return value
  232. def get_env(self, full_env):
  233. env = {}
  234. for method, name, values, kwargs in self.envvars:
  235. env[name] = method(full_env, name, values, kwargs)
  236. return env
  237. class Target:
  238. def __init__(self, name, subdir, subproject, build_by_default):
  239. if '/' in name or '\\' in name:
  240. # Fix failing test 53 when this becomes an error.
  241. mlog.warning('''Target "%s" has a path separator in its name.
  242. This is not supported, it can cause unexpected failures and will become
  243. a hard error in the future.''' % name)
  244. self.name = name
  245. self.subdir = subdir
  246. self.subproject = subproject
  247. self.build_by_default = build_by_default
  248. self.install = False
  249. self.build_always = False
  250. self.option_overrides = {}
  251. def get_basename(self):
  252. return self.name
  253. def get_subdir(self):
  254. return self.subdir
  255. def get_id(self):
  256. # This ID must also be a valid file name on all OSs.
  257. # It should also avoid shell metacharacters for obvious
  258. # reasons.
  259. base = self.name + self.type_suffix()
  260. if self.subproject == '':
  261. return base
  262. return self.subproject + '@@' + base
  263. def process_kwargs(self, kwargs):
  264. if 'build_by_default' in kwargs:
  265. self.build_by_default = kwargs['build_by_default']
  266. if not isinstance(self.build_by_default, bool):
  267. raise InvalidArguments('build_by_default must be a boolean value.')
  268. self.option_overrides = self.parse_overrides(kwargs)
  269. def parse_overrides(self, kwargs):
  270. result = {}
  271. overrides = stringlistify(kwargs.get('override_options', []))
  272. for o in overrides:
  273. if '=' not in o:
  274. raise InvalidArguments('Overrides must be of form "key=value"')
  275. k, v = o.split('=', 1)
  276. k = k.strip()
  277. v = v.strip()
  278. result[k] = v
  279. return result
  280. class BuildTarget(Target):
  281. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  282. super().__init__(name, subdir, subproject, True)
  283. self.is_cross = is_cross
  284. unity_opt = environment.coredata.get_builtin_option('unity')
  285. self.is_unity = unity_opt == 'on' or (unity_opt == 'subprojects' and subproject != '')
  286. self.environment = environment
  287. self.sources = []
  288. self.compilers = OrderedDict()
  289. self.objects = []
  290. self.external_deps = []
  291. self.include_dirs = []
  292. self.link_targets = []
  293. self.link_whole_targets = []
  294. self.link_depends = []
  295. self.name_prefix_set = False
  296. self.name_suffix_set = False
  297. self.filename = 'no_name'
  298. # The list of all files outputted by this target. Useful in cases such
  299. # as Vala which generates .vapi and .h besides the compiled output.
  300. self.outputs = [self.filename]
  301. self.need_install = False
  302. self.pch = {}
  303. self.extra_args = {}
  304. self.generated = []
  305. self.extra_files = []
  306. # Sources can be:
  307. # 1. Pre-existing source files in the source tree
  308. # 2. Pre-existing sources generated by configure_file in the build tree
  309. # 3. Sources files generated by another target or a Generator
  310. self.process_sourcelist(sources)
  311. # Objects can be:
  312. # 1. Pre-existing objects provided by the user with the `objects:` kwarg
  313. # 2. Compiled objects created by and extracted from another target
  314. self.process_objectlist(objects)
  315. self.process_compilers()
  316. self.process_kwargs(kwargs, environment)
  317. self.check_unknown_kwargs(kwargs)
  318. if not any([self.sources, self.generated, self.objects, self.link_whole]):
  319. raise InvalidArguments('Build target %s has no sources.' % name)
  320. self.process_compilers_late()
  321. self.validate_sources()
  322. self.validate_cross_install(environment)
  323. def __lt__(self, other):
  324. return self.get_id() < other.get_id()
  325. def __repr__(self):
  326. repr_str = "<{0} {1}: {2}>"
  327. return repr_str.format(self.__class__.__name__, self.get_id(), self.filename)
  328. def validate_cross_install(self, environment):
  329. if environment.is_cross_build() and not self.is_cross and self.install:
  330. raise InvalidArguments('Tried to install a natively built target in a cross build.')
  331. def check_unknown_kwargs(self, kwargs):
  332. # Override this method in derived classes that have more
  333. # keywords.
  334. self.check_unknown_kwargs_int(kwargs, known_basic_kwargs)
  335. def check_unknown_kwargs_int(self, kwargs, known_kwargs):
  336. unknowns = []
  337. for k in kwargs:
  338. if k not in known_kwargs:
  339. unknowns.append(k)
  340. if len(unknowns) > 0:
  341. mlog.warning('Unknown keyword argument(s) in target %s: %s.' %
  342. (self.name, ', '.join(unknowns)))
  343. def process_objectlist(self, objects):
  344. assert(isinstance(objects, list))
  345. for s in objects:
  346. if hasattr(s, 'held_object'):
  347. s = s.held_object
  348. if isinstance(s, (str, File, ExtractedObjects)):
  349. self.objects.append(s)
  350. elif isinstance(s, (GeneratedList, CustomTarget)):
  351. msg = 'Generated files are not allowed in the \'objects\' kwarg ' + \
  352. 'for target {!r}.\nIt is meant only for '.format(self.name) + \
  353. 'pre-built object files that are shipped with the\nsource ' + \
  354. 'tree. Try adding it in the list of sources.'
  355. raise InvalidArguments(msg)
  356. else:
  357. msg = 'Bad object of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  358. raise InvalidArguments(msg)
  359. def process_sourcelist(self, sources):
  360. sources = listify(sources)
  361. added_sources = {} # If the same source is defined multiple times, use it only once.
  362. for s in sources:
  363. # Holder unpacking. Ugly.
  364. if hasattr(s, 'held_object'):
  365. s = s.held_object
  366. if isinstance(s, File):
  367. if s not in added_sources:
  368. self.sources.append(s)
  369. added_sources[s] = True
  370. elif isinstance(s, (GeneratedList, CustomTarget, CustomTargetIndex)):
  371. self.generated.append(s)
  372. else:
  373. msg = 'Bad source of type {!r} in target {!r}.'.format(type(s).__name__, self.name)
  374. raise InvalidArguments(msg)
  375. @staticmethod
  376. def can_compile_remove_sources(compiler, sources):
  377. removed = False
  378. for s in sources[:]:
  379. if compiler.can_compile(s):
  380. sources.remove(s)
  381. removed = True
  382. return removed
  383. def process_compilers_late(self):
  384. """Processes additional compilers after kwargs have been evaluated.
  385. This can add extra compilers that might be required by keyword
  386. arguments, such as link_with or dependencies. It will also try to guess
  387. which compiler to use if one hasn't been selected already.
  388. """
  389. # Populate list of compilers
  390. if self.is_cross:
  391. compilers = self.environment.coredata.cross_compilers
  392. else:
  393. compilers = self.environment.coredata.compilers
  394. # If this library is linked against another library we need to consider
  395. # the languages of those libraries as well.
  396. if self.link_targets or self.link_whole_targets:
  397. extra = set()
  398. for t in itertools.chain(self.link_targets, self.link_whole_targets):
  399. for name, compiler in t.compilers.items():
  400. if name in clike_langs:
  401. extra.add((name, compiler))
  402. for name, compiler in sorted(extra, key=lambda p: sort_clike(p[0])):
  403. self.compilers[name] = compiler
  404. if not self.compilers:
  405. # No source files or parent targets, target consists of only object
  406. # files of unknown origin. Just add the first clike compiler
  407. # that we have and hope that it can link these objects
  408. for lang in clike_langs:
  409. if lang in compilers:
  410. self.compilers[lang] = compilers[lang]
  411. break
  412. def process_compilers(self):
  413. '''
  414. Populate self.compilers, which is the list of compilers that this
  415. target will use for compiling all its sources.
  416. We also add compilers that were used by extracted objects to simplify
  417. dynamic linker determination.
  418. '''
  419. if not self.sources and not self.generated and not self.objects:
  420. return
  421. # Populate list of compilers
  422. if self.is_cross:
  423. compilers = self.environment.coredata.cross_compilers
  424. else:
  425. compilers = self.environment.coredata.compilers
  426. # Pre-existing sources
  427. sources = list(self.sources)
  428. # All generated sources
  429. for gensrc in self.generated:
  430. for s in gensrc.get_outputs():
  431. # Generated objects can't be compiled, so don't use them for
  432. # compiler detection. If our target only has generated objects,
  433. # we will fall back to using the first c-like compiler we find,
  434. # which is what we need.
  435. if not is_object(s):
  436. sources.append(s)
  437. # Sources that were used to create our extracted objects
  438. for o in self.objects:
  439. if not isinstance(o, ExtractedObjects):
  440. continue
  441. for s in o.srclist:
  442. # Don't add Vala sources since that will pull in the Vala
  443. # compiler even though we will never use it since we are
  444. # dealing with compiled C code.
  445. if not s.endswith(lang_suffixes['vala']):
  446. sources.append(s)
  447. if sources:
  448. # For each source, try to add one compiler that can compile it.
  449. # It's ok if no compilers can do so, because users are expected to
  450. # be able to add arbitrary non-source files to the sources list.
  451. for s in sources:
  452. for lang, compiler in compilers.items():
  453. if compiler.can_compile(s):
  454. if lang not in self.compilers:
  455. self.compilers[lang] = compiler
  456. break
  457. # Re-sort according to clike_langs
  458. self.compilers = OrderedDict(sorted(self.compilers.items(),
  459. key=lambda t: sort_clike(t[0])))
  460. # If all our sources are Vala, our target also needs the C compiler but
  461. # it won't get added above.
  462. if 'vala' in self.compilers and 'c' not in self.compilers:
  463. self.compilers['c'] = compilers['c']
  464. def validate_sources(self):
  465. if not self.sources:
  466. return
  467. for lang in ('cs', 'java'):
  468. if lang in self.compilers:
  469. check_sources = list(self.sources)
  470. compiler = self.compilers[lang]
  471. if not self.can_compile_remove_sources(compiler, check_sources):
  472. m = 'No {} sources found in target {!r}'.format(lang, self.name)
  473. raise InvalidArguments(m)
  474. if check_sources:
  475. m = '{0} targets can only contain {0} files:\n'.format(lang.capitalize())
  476. m += '\n'.join([repr(c) for c in check_sources])
  477. raise InvalidArguments(m)
  478. # CSharp and Java targets can't contain any other file types
  479. assert(len(self.compilers) == 1)
  480. return
  481. def process_link_depends(self, sources, environment):
  482. """Process the link_depends keyword argument.
  483. This is designed to handle strings, Files, and the output of Custom
  484. Targets. Notably it doesn't handle generator() returned objects, since
  485. adding them as a link depends would inherently cause them to be
  486. generated twice, since the output needs to be passed to the ld_args and
  487. link_depends.
  488. """
  489. sources = listify(sources)
  490. for s in sources:
  491. if hasattr(s, 'held_object'):
  492. s = s.held_object
  493. if isinstance(s, File):
  494. self.link_depends.append(s)
  495. elif isinstance(s, str):
  496. self.link_depends.append(
  497. File.from_source_file(environment.source_dir, self.subdir, s))
  498. elif hasattr(s, 'get_outputs'):
  499. self.link_depends.extend(
  500. [File.from_built_file(s.subdir, p) for p in s.get_outputs()])
  501. else:
  502. raise InvalidArguments(
  503. 'Link_depends arguments must be strings, Files, '
  504. 'or a Custom Target, or lists thereof.')
  505. def get_original_kwargs(self):
  506. return self.kwargs
  507. def unpack_holder(self, d):
  508. d = listify(d)
  509. newd = []
  510. for i in d:
  511. if isinstance(i, list):
  512. i = self.unpack_holder(i)
  513. elif hasattr(i, 'held_object'):
  514. i = i.held_object
  515. for t in ['dependencies', 'link_with', 'include_directories', 'sources']:
  516. if hasattr(i, t):
  517. setattr(i, t, self.unpack_holder(getattr(i, t)))
  518. newd.append(i)
  519. return newd
  520. def copy_kwargs(self, kwargs):
  521. self.kwargs = copy.copy(kwargs)
  522. # This sucks quite badly. Arguments
  523. # are holders but they can't be pickled
  524. # so unpack those known.
  525. for k, v in self.kwargs.items():
  526. if isinstance(v, list):
  527. self.kwargs[k] = self.unpack_holder(v)
  528. if hasattr(v, 'held_object'):
  529. self.kwargs[k] = v.held_object
  530. for t in ['dependencies', 'link_with', 'include_directories', 'sources']:
  531. if t in self.kwargs:
  532. self.kwargs[t] = self.unpack_holder(self.kwargs[t])
  533. def extract_objects(self, srclist):
  534. obj_src = []
  535. for src in srclist:
  536. if not isinstance(src, str):
  537. raise MesonException('Object extraction arguments must be strings.')
  538. src = File(False, self.subdir, src)
  539. if src not in self.sources:
  540. raise MesonException('Tried to extract unknown source %s.' % src)
  541. obj_src.append(src)
  542. return ExtractedObjects(self, obj_src, self.is_unity)
  543. def extract_all_objects(self):
  544. return ExtractedObjects(self, self.sources, self.is_unity)
  545. def get_all_link_deps(self):
  546. return self.get_transitive_link_deps()
  547. def get_transitive_link_deps(self):
  548. result = []
  549. for i in self.link_targets:
  550. result += i.get_all_link_deps()
  551. return result
  552. def get_custom_install_dir(self):
  553. return self.install_dir
  554. def process_kwargs(self, kwargs, environment):
  555. super().process_kwargs(kwargs)
  556. self.copy_kwargs(kwargs)
  557. kwargs.get('modules', [])
  558. self.need_install = kwargs.get('install', self.need_install)
  559. llist = extract_as_list(kwargs, 'link_with')
  560. for linktarget in llist:
  561. # Sorry for this hack. Keyword targets are kept in holders
  562. # in kwargs. Unpack here without looking at the exact type.
  563. if hasattr(linktarget, "held_object"):
  564. linktarget = linktarget.held_object
  565. if isinstance(linktarget, dependencies.ExternalLibrary):
  566. raise MesonException('''An external library was used in link_with keyword argument, which
  567. is reserved for libraries built as part of this project. External
  568. libraries must be passed using the dependencies keyword argument
  569. instead, because they are conceptually "external dependencies",
  570. just like those detected with the dependency() function.''')
  571. self.link(linktarget)
  572. lwhole = extract_as_list(kwargs, 'link_whole')
  573. for linktarget in lwhole:
  574. # Sorry for this hack. Keyword targets are kept in holders
  575. # in kwargs. Unpack here without looking at the exact type.
  576. if hasattr(linktarget, "held_object"):
  577. linktarget = linktarget.held_object
  578. self.link_whole(linktarget)
  579. c_pchlist, cpp_pchlist, clist, cpplist, cslist, valalist, objclist, objcpplist, fortranlist, rustlist \
  580. = extract_as_list(kwargs, 'c_pch', 'cpp_pch', 'c_args', 'cpp_args', 'cs_args', 'vala_args', 'objc_args',
  581. 'objcpp_args', 'fortran_args', 'rust_args')
  582. self.add_pch('c', c_pchlist)
  583. self.add_pch('cpp', cpp_pchlist)
  584. compiler_args = {'c': clist, 'cpp': cpplist, 'cs': cslist, 'vala': valalist, 'objc': objclist, 'objcpp': objcpplist,
  585. 'fortran': fortranlist, 'rust': rustlist
  586. }
  587. for key, value in compiler_args.items():
  588. self.add_compiler_args(key, value)
  589. if not isinstance(self, Executable):
  590. self.vala_header = kwargs.get('vala_header', self.name + '.h')
  591. self.vala_vapi = kwargs.get('vala_vapi', self.name + '.vapi')
  592. self.vala_gir = kwargs.get('vala_gir', None)
  593. dlist = stringlistify(kwargs.get('d_args', []))
  594. self.add_compiler_args('d', dlist)
  595. dfeatures = dict()
  596. dfeature_unittest = kwargs.get('d_unittest', False)
  597. if dfeature_unittest:
  598. dfeatures['unittest'] = dfeature_unittest
  599. dfeature_versions = kwargs.get('d_module_versions', None)
  600. if dfeature_versions:
  601. dfeatures['versions'] = dfeature_versions
  602. dfeature_import_dirs = kwargs.get('d_import_dirs', None)
  603. if dfeature_import_dirs:
  604. dfeatures['import_dirs'] = dfeature_import_dirs
  605. if dfeatures:
  606. if 'd' in self.compilers:
  607. self.add_compiler_args('d', self.compilers['d'].get_feature_args(dfeatures))
  608. self.link_args = extract_as_list(kwargs, 'link_args')
  609. for i in self.link_args:
  610. if not isinstance(i, str):
  611. raise InvalidArguments('Link_args arguments must be strings.')
  612. for l in self.link_args:
  613. if '-Wl,-rpath' in l or l.startswith('-rpath'):
  614. mlog.warning('''Please do not define rpath with a linker argument, use install_rpath or build_rpath properties instead.
  615. This will become a hard error in a future Meson release.''')
  616. self.process_link_depends(kwargs.get('link_depends', []), environment)
  617. # Target-specific include dirs must be added BEFORE include dirs from
  618. # internal deps (added inside self.add_deps()) to override them.
  619. inclist = extract_as_list(kwargs, 'include_directories')
  620. self.add_include_dirs(inclist)
  621. # Add dependencies (which also have include_directories)
  622. deplist = extract_as_list(kwargs, 'dependencies')
  623. self.add_deps(deplist)
  624. # If an item in this list is False, the output corresponding to
  625. # the list index of that item will not be installed
  626. self.install_dir = typeslistify(kwargs.get('install_dir', [None]),
  627. (str, bool))
  628. main_class = kwargs.get('main_class', '')
  629. if not isinstance(main_class, str):
  630. raise InvalidArguments('Main class must be a string')
  631. self.main_class = main_class
  632. if isinstance(self, Executable):
  633. self.gui_app = kwargs.get('gui_app', False)
  634. if not isinstance(self.gui_app, bool):
  635. raise InvalidArguments('Argument gui_app must be boolean.')
  636. elif 'gui_app' in kwargs:
  637. raise InvalidArguments('Argument gui_app can only be used on executables.')
  638. extra_files = extract_as_list(kwargs, 'extra_files')
  639. for i in extra_files:
  640. assert(isinstance(i, File))
  641. trial = os.path.join(environment.get_source_dir(), i.subdir, i.fname)
  642. if not(os.path.isfile(trial)):
  643. raise InvalidArguments('Tried to add non-existing extra file %s.' % i)
  644. self.extra_files = extra_files
  645. self.install_rpath = kwargs.get('install_rpath', '')
  646. if not isinstance(self.install_rpath, str):
  647. raise InvalidArguments('Install_rpath is not a string.')
  648. self.build_rpath = kwargs.get('build_rpath', '')
  649. if not isinstance(self.build_rpath, str):
  650. raise InvalidArguments('Build_rpath is not a string.')
  651. resources = extract_as_list(kwargs, 'resources')
  652. for r in resources:
  653. if not isinstance(r, str):
  654. raise InvalidArguments('Resource argument is not a string.')
  655. trial = os.path.join(environment.get_source_dir(), self.subdir, r)
  656. if not os.path.isfile(trial):
  657. raise InvalidArguments('Tried to add non-existing resource %s.' % r)
  658. self.resources = resources
  659. if 'name_prefix' in kwargs:
  660. name_prefix = kwargs['name_prefix']
  661. if isinstance(name_prefix, list):
  662. if name_prefix:
  663. raise InvalidArguments('name_prefix array must be empty to signify null.')
  664. elif not isinstance(name_prefix, str):
  665. raise InvalidArguments('name_prefix must be a string.')
  666. self.prefix = name_prefix
  667. self.name_prefix_set = True
  668. if 'name_suffix' in kwargs:
  669. name_suffix = kwargs['name_suffix']
  670. if isinstance(name_suffix, list):
  671. if name_suffix:
  672. raise InvalidArguments('name_suffix array must be empty to signify null.')
  673. else:
  674. if not isinstance(name_suffix, str):
  675. raise InvalidArguments('name_suffix must be a string.')
  676. self.suffix = name_suffix
  677. self.name_suffix_set = True
  678. if isinstance(self, StaticLibrary):
  679. # You can't disable PIC on OS X. The compiler ignores -fno-PIC.
  680. # PIC is always on for Windows (all code is position-independent
  681. # since library loading is done differently)
  682. if for_darwin(self.is_cross, self.environment) or for_windows(self.is_cross, self.environment):
  683. self.pic = True
  684. elif '-fPIC' in clist + cpplist:
  685. mlog.warning("Use the 'pic' kwarg instead of passing -fPIC manually to static library {!r}".format(self.name))
  686. self.pic = True
  687. else:
  688. self.pic = kwargs.get('pic', False)
  689. if not isinstance(self.pic, bool):
  690. raise InvalidArguments('Argument pic to static library {!r} must be boolean'.format(self.name))
  691. self.implicit_include_directories = kwargs.get('implicit_include_directories', True)
  692. if not isinstance(self.implicit_include_directories, bool):
  693. raise InvalidArguments('Implicit_include_directories must be a boolean.')
  694. def get_filename(self):
  695. return self.filename
  696. def get_outputs(self):
  697. return self.outputs
  698. def get_extra_args(self, language):
  699. return self.extra_args.get(language, [])
  700. def get_dependencies(self):
  701. transitive_deps = []
  702. for t in self.link_targets + self.link_whole_targets:
  703. transitive_deps.append(t)
  704. if isinstance(t, StaticLibrary):
  705. transitive_deps += t.get_dependencies()
  706. return transitive_deps
  707. def get_source_subdir(self):
  708. return self.subdir
  709. def get_sources(self):
  710. return self.sources
  711. def get_objects(self):
  712. return self.objects
  713. def get_generated_sources(self):
  714. return self.generated
  715. def should_install(self):
  716. return self.need_install
  717. def has_pch(self):
  718. return len(self.pch) > 0
  719. def get_pch(self, language):
  720. try:
  721. return self.pch[language]
  722. except KeyError:
  723. return[]
  724. def get_include_dirs(self):
  725. return self.include_dirs
  726. def add_deps(self, deps):
  727. deps = listify(deps)
  728. for dep in deps:
  729. if hasattr(dep, 'held_object'):
  730. dep = dep.held_object
  731. if isinstance(dep, dependencies.InternalDependency):
  732. # Those parts that are internal.
  733. self.process_sourcelist(dep.sources)
  734. self.add_include_dirs(dep.include_directories)
  735. for l in dep.libraries:
  736. self.link(l)
  737. # Those parts that are external.
  738. extpart = dependencies.InternalDependency('undefined',
  739. [],
  740. dep.compile_args,
  741. dep.link_args,
  742. [], [], [])
  743. self.external_deps.append(extpart)
  744. # Deps of deps.
  745. self.add_deps(dep.ext_deps)
  746. elif isinstance(dep, dependencies.ExternalDependency):
  747. self.external_deps.append(dep)
  748. self.process_sourcelist(dep.get_sources())
  749. elif isinstance(dep, BuildTarget):
  750. raise InvalidArguments('''Tried to use a build target as a dependency.
  751. You probably should put it in link_with instead.''')
  752. else:
  753. # This is a bit of a hack. We do not want Build to know anything
  754. # about the interpreter so we can't import it and use isinstance.
  755. # This should be reliable enough.
  756. if hasattr(dep, 'project_args_frozen') or hasattr(dep, 'global_args_frozen'):
  757. raise InvalidArguments('Tried to use subproject object as a dependency.\n'
  758. 'You probably wanted to use a dependency declared in it instead.\n'
  759. 'Access it by calling get_variable() on the subproject object.')
  760. raise InvalidArguments('Argument is of an unacceptable type {!r}.\nMust be '
  761. 'either an external dependency (returned by find_library() or '
  762. 'dependency()) or an internal dependency (returned by '
  763. 'declare_dependency()).'.format(type(dep).__name__))
  764. def get_external_deps(self):
  765. return self.external_deps
  766. def link(self, target):
  767. for t in listify(target, unholder=True):
  768. if not isinstance(t, Target):
  769. raise InvalidArguments('{!r} is not a target.'.format(t))
  770. if not t.is_linkable_target():
  771. raise InvalidArguments('Link target {!r} is not linkable.'.format(t))
  772. if isinstance(self, SharedLibrary) and isinstance(t, StaticLibrary) and not t.pic:
  773. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  774. msg += "Use the 'pic' option to static_library to build with PIC."
  775. raise InvalidArguments(msg)
  776. if self.is_cross != t.is_cross:
  777. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  778. self.link_targets.append(t)
  779. def link_whole(self, target):
  780. for t in listify(target, unholder=True):
  781. if not isinstance(t, StaticLibrary):
  782. raise InvalidArguments('{!r} is not a static library.'.format(t))
  783. if isinstance(self, SharedLibrary) and not t.pic:
  784. msg = "Can't link non-PIC static library {!r} into shared library {!r}. ".format(t.name, self.name)
  785. msg += "Use the 'pic' option to static_library to build with PIC."
  786. raise InvalidArguments(msg)
  787. if self.is_cross != t.is_cross:
  788. raise InvalidArguments('Tried to mix cross built and native libraries in target {!r}'.format(self.name))
  789. self.link_whole_targets.append(t)
  790. def add_pch(self, language, pchlist):
  791. if not pchlist:
  792. return
  793. elif len(pchlist) == 1:
  794. if not environment.is_header(pchlist[0]):
  795. raise InvalidArguments('PCH argument %s is not a header.' % pchlist[0])
  796. elif len(pchlist) == 2:
  797. if environment.is_header(pchlist[0]):
  798. if not environment.is_source(pchlist[1]):
  799. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  800. elif environment.is_source(pchlist[0]):
  801. if not environment.is_header(pchlist[1]):
  802. raise InvalidArguments('PCH definition must contain one header and at most one source.')
  803. pchlist = [pchlist[1], pchlist[0]]
  804. else:
  805. raise InvalidArguments('PCH argument %s is of unknown type.' % pchlist[0])
  806. elif len(pchlist) > 2:
  807. raise InvalidArguments('PCH definition may have a maximum of 2 files.')
  808. self.pch[language] = pchlist
  809. def add_include_dirs(self, args):
  810. ids = []
  811. for a in args:
  812. # FIXME same hack, forcibly unpack from holder.
  813. if hasattr(a, 'held_object'):
  814. a = a.held_object
  815. if not isinstance(a, IncludeDirs):
  816. raise InvalidArguments('Include directory to be added is not an include directory object.')
  817. ids.append(a)
  818. self.include_dirs += ids
  819. def add_compiler_args(self, language, args):
  820. args = listify(args)
  821. for a in args:
  822. if not isinstance(a, (str, File)):
  823. raise InvalidArguments('A non-string passed to compiler args.')
  824. if language in self.extra_args:
  825. self.extra_args[language] += args
  826. else:
  827. self.extra_args[language] = args
  828. def get_aliases(self):
  829. return {}
  830. def get_langs_used_by_deps(self):
  831. '''
  832. Sometimes you want to link to a C++ library that exports C API, which
  833. means the linker must link in the C++ stdlib, and we must use a C++
  834. compiler for linking. The same is also applicable for objc/objc++, etc,
  835. so we can keep using clike_langs for the priority order.
  836. See: https://github.com/mesonbuild/meson/issues/1653
  837. '''
  838. langs = []
  839. # Check if any of the external libraries were written in this language
  840. for dep in self.external_deps:
  841. if dep.language not in langs:
  842. langs.append(dep.language)
  843. # Check if any of the internal libraries this target links to were
  844. # written in this language
  845. for link_target in itertools.chain(self.link_targets, self.link_whole_targets):
  846. for language in link_target.compilers:
  847. if language not in langs:
  848. langs.append(language)
  849. return langs
  850. def get_clike_dynamic_linker(self):
  851. '''
  852. We use the order of languages in `clike_langs` to determine which
  853. linker to use in case the target has sources compiled with multiple
  854. compilers. All languages other than those in this list have their own
  855. linker.
  856. Note that Vala outputs C code, so Vala sources can use any linker
  857. that can link compiled C. We don't actually need to add an exception
  858. for Vala here because of that.
  859. '''
  860. # Populate list of all compilers, not just those being used to compile
  861. # sources in this target
  862. if self.is_cross:
  863. all_compilers = self.environment.coredata.cross_compilers
  864. else:
  865. all_compilers = self.environment.coredata.compilers
  866. # Languages used by dependencies
  867. dep_langs = self.get_langs_used_by_deps()
  868. # Pick a compiler based on the language priority-order
  869. for l in clike_langs:
  870. if l in self.compilers or l in dep_langs:
  871. try:
  872. return all_compilers[l]
  873. except KeyError:
  874. raise MesonException(
  875. 'Could not get a dynamic linker for build target {!r}. '
  876. 'Requires a linker for language "{}", but that is not '
  877. 'a project language.'.format(self.name, l))
  878. m = 'Could not get a dynamic linker for build target {!r}'
  879. raise AssertionError(m.format(self.name))
  880. def get_using_msvc(self):
  881. '''
  882. Check if the dynamic linker is MSVC. Used by Executable, StaticLibrary,
  883. and SharedLibrary for deciding when to use MSVC-specific file naming
  884. and debug filenames.
  885. If at least some code is built with MSVC and the final library is
  886. linked with MSVC, we can be sure that some debug info will be
  887. generated. We only check the dynamic linker here because the static
  888. linker is guaranteed to be of the same type.
  889. Interesting cases:
  890. 1. The Vala compiler outputs C code to be compiled by whatever
  891. C compiler we're using, so all objects will still be created by the
  892. MSVC compiler.
  893. 2. If the target contains only objects, process_compilers guesses and
  894. picks the first compiler that smells right.
  895. '''
  896. linker = self.get_clike_dynamic_linker()
  897. if linker and linker.get_id() == 'msvc':
  898. return True
  899. return False
  900. def is_linkable_target(self):
  901. return False
  902. class Generator:
  903. def __init__(self, args, kwargs):
  904. if len(args) != 1:
  905. raise InvalidArguments('Generator requires exactly one positional argument: the executable')
  906. exe = args[0]
  907. if hasattr(exe, 'held_object'):
  908. exe = exe.held_object
  909. if not isinstance(exe, (Executable, dependencies.ExternalProgram)):
  910. raise InvalidArguments('First generator argument must be an executable.')
  911. self.exe = exe
  912. self.depfile = None
  913. self.capture = False
  914. self.process_kwargs(kwargs)
  915. def __repr__(self):
  916. repr_str = "<{0}: {1}>"
  917. return repr_str.format(self.__class__.__name__, self.exe)
  918. def get_exe(self):
  919. return self.exe
  920. def process_kwargs(self, kwargs):
  921. if 'arguments' not in kwargs:
  922. raise InvalidArguments('Generator must have "arguments" keyword argument.')
  923. args = kwargs['arguments']
  924. if isinstance(args, str):
  925. args = [args]
  926. if not isinstance(args, list):
  927. raise InvalidArguments('"Arguments" keyword argument must be a string or a list of strings.')
  928. for a in args:
  929. if not isinstance(a, str):
  930. raise InvalidArguments('A non-string object in "arguments" keyword argument.')
  931. self.arglist = args
  932. if 'output' not in kwargs:
  933. raise InvalidArguments('Generator must have "output" keyword argument.')
  934. outputs = listify(kwargs['output'])
  935. for rule in outputs:
  936. if not isinstance(rule, str):
  937. raise InvalidArguments('"output" may only contain strings.')
  938. if '@BASENAME@' not in rule and '@PLAINNAME@' not in rule:
  939. raise InvalidArguments('Every element of "output" must contain @BASENAME@ or @PLAINNAME@.')
  940. if '/' in rule or '\\' in rule:
  941. raise InvalidArguments('"outputs" must not contain a directory separator.')
  942. if len(outputs) > 1:
  943. for o in outputs:
  944. if '@OUTPUT@' in o:
  945. raise InvalidArguments('Tried to use @OUTPUT@ in a rule with more than one output.')
  946. self.outputs = outputs
  947. if 'depfile' in kwargs:
  948. depfile = kwargs['depfile']
  949. if not isinstance(depfile, str):
  950. raise InvalidArguments('Depfile must be a string.')
  951. if os.path.split(depfile)[1] != depfile:
  952. raise InvalidArguments('Depfile must be a plain filename without a subdirectory.')
  953. self.depfile = depfile
  954. if 'capture' in kwargs:
  955. capture = kwargs['capture']
  956. if not isinstance(capture, bool):
  957. raise InvalidArguments('Capture must be boolean.')
  958. self.capture = capture
  959. def get_base_outnames(self, inname):
  960. plainname = os.path.split(inname)[1]
  961. basename = os.path.splitext(plainname)[0]
  962. return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.outputs]
  963. def get_dep_outname(self, inname):
  964. if self.depfile is None:
  965. raise InvalidArguments('Tried to get dep name for rule that does not have dependency file defined.')
  966. plainname = os.path.split(inname)[1]
  967. basename = os.path.splitext(plainname)[0]
  968. return self.depfile.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname)
  969. def get_arglist(self, inname):
  970. plainname = os.path.split(inname)[1]
  971. basename = os.path.splitext(plainname)[0]
  972. return [x.replace('@BASENAME@', basename).replace('@PLAINNAME@', plainname) for x in self.arglist]
  973. def process_files(self, name, files, state, extra_args=[]):
  974. output = GeneratedList(self, extra_args=extra_args)
  975. for f in files:
  976. if isinstance(f, str):
  977. f = File.from_source_file(state.environment.source_dir, state.subdir, f)
  978. elif not isinstance(f, File):
  979. raise InvalidArguments('{} arguments must be strings or files not {!r}.'.format(name, f))
  980. output.add_file(f)
  981. return output
  982. class GeneratedList:
  983. def __init__(self, generator, extra_args=[]):
  984. if hasattr(generator, 'held_object'):
  985. generator = generator.held_object
  986. self.generator = generator
  987. self.name = self.generator.exe
  988. self.infilelist = []
  989. self.outfilelist = []
  990. self.outmap = {}
  991. self.extra_depends = []
  992. self.extra_args = extra_args
  993. def add_file(self, newfile):
  994. self.infilelist.append(newfile)
  995. outfiles = self.generator.get_base_outnames(newfile.fname)
  996. self.outfilelist += outfiles
  997. self.outmap[newfile] = outfiles
  998. def get_inputs(self):
  999. return self.infilelist
  1000. def get_outputs(self):
  1001. return self.outfilelist
  1002. def get_outputs_for(self, filename):
  1003. return self.outmap[filename]
  1004. def get_generator(self):
  1005. return self.generator
  1006. def get_extra_args(self):
  1007. return self.extra_args
  1008. class Executable(BuildTarget):
  1009. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1010. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1011. # Unless overridden, executables have no suffix or prefix. Except on
  1012. # Windows and with C#/Mono executables where the suffix is 'exe'
  1013. if not hasattr(self, 'prefix'):
  1014. self.prefix = ''
  1015. if not hasattr(self, 'suffix'):
  1016. # Executable for Windows or C#/Mono
  1017. if (for_windows(is_cross, environment) or
  1018. for_cygwin(is_cross, environment) or 'cs' in self.compilers):
  1019. self.suffix = 'exe'
  1020. else:
  1021. self.suffix = ''
  1022. self.filename = self.name
  1023. if self.suffix:
  1024. self.filename += '.' + self.suffix
  1025. self.outputs = [self.filename]
  1026. # The import library this target will generate
  1027. self.import_filename = None
  1028. # The import library that Visual Studio would generate (and accept)
  1029. self.vs_import_filename = None
  1030. # The import library that GCC would generate (and prefer)
  1031. self.gcc_import_filename = None
  1032. # if implib appears, this target is linkwith:-able, but that only means
  1033. # something on Windows platforms.
  1034. self.is_linkwithable = False
  1035. if 'implib' in kwargs and kwargs['implib']:
  1036. implib_basename = self.name + '.exe'
  1037. if not isinstance(kwargs['implib'], bool):
  1038. implib_basename = kwargs['implib']
  1039. self.is_linkwithable = True
  1040. if for_windows(is_cross, environment) or for_cygwin(is_cross, environment):
  1041. self.vs_import_filename = '{0}.lib'.format(implib_basename)
  1042. self.gcc_import_filename = 'lib{0}.a'.format(implib_basename)
  1043. if self.get_using_msvc():
  1044. self.import_filename = self.vs_import_filename
  1045. else:
  1046. self.import_filename = self.gcc_import_filename
  1047. def type_suffix(self):
  1048. return "@exe"
  1049. def check_unknown_kwargs(self, kwargs):
  1050. self.check_unknown_kwargs_int(kwargs, known_exe_kwargs)
  1051. def get_import_filename(self):
  1052. """
  1053. The name of the import library that will be outputted by the compiler
  1054. Returns None if there is no import library required for this platform
  1055. """
  1056. return self.import_filename
  1057. def get_import_filenameslist(self):
  1058. if self.import_filename:
  1059. return [self.vs_import_filename, self.gcc_import_filename]
  1060. return []
  1061. def is_linkable_target(self):
  1062. return self.is_linkwithable
  1063. class StaticLibrary(BuildTarget):
  1064. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1065. if 'pic' not in kwargs and 'b_staticpic' in environment.coredata.base_options:
  1066. kwargs['pic'] = environment.coredata.base_options['b_staticpic'].value
  1067. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1068. if 'cs' in self.compilers:
  1069. raise InvalidArguments('Static libraries not supported for C#.')
  1070. if 'rust' in self.compilers:
  1071. # If no crate type is specified, or it's the generic lib type, use rlib
  1072. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'lib':
  1073. mlog.debug('Defaulting Rust static library target crate type to rlib')
  1074. self.rust_crate_type = 'rlib'
  1075. # Don't let configuration proceed with a non-static crate type
  1076. elif self.rust_crate_type not in ['rlib', 'staticlib']:
  1077. raise InvalidArguments('Crate type "{0}" invalid for static libraries; must be "rlib" or "staticlib"'.format(self.rust_crate_type))
  1078. # By default a static library is named libfoo.a even on Windows because
  1079. # MSVC does not have a consistent convention for what static libraries
  1080. # are called. The MSVC CRT uses libfoo.lib syntax but nothing else uses
  1081. # it and GCC only looks for static libraries called foo.lib and
  1082. # libfoo.a. However, we cannot use foo.lib because that's the same as
  1083. # the import library. Using libfoo.a is ok because people using MSVC
  1084. # always pass the library filename while linking anyway.
  1085. if not hasattr(self, 'prefix'):
  1086. self.prefix = 'lib'
  1087. if not hasattr(self, 'suffix'):
  1088. if 'rust' in self.compilers:
  1089. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'rlib':
  1090. # default Rust static library suffix
  1091. self.suffix = 'rlib'
  1092. elif self.rust_crate_type == 'staticlib':
  1093. self.suffix = 'a'
  1094. else:
  1095. self.suffix = 'a'
  1096. self.filename = self.prefix + self.name + '.' + self.suffix
  1097. self.outputs = [self.filename]
  1098. def type_suffix(self):
  1099. return "@sta"
  1100. def check_unknown_kwargs(self, kwargs):
  1101. self.check_unknown_kwargs_int(kwargs, known_lib_kwargs)
  1102. def process_kwargs(self, kwargs, environment):
  1103. super().process_kwargs(kwargs, environment)
  1104. if 'rust_crate_type' in kwargs:
  1105. rust_crate_type = kwargs['rust_crate_type']
  1106. if isinstance(rust_crate_type, str):
  1107. self.rust_crate_type = rust_crate_type
  1108. else:
  1109. raise InvalidArguments('Invalid rust_crate_type "{0}": must be a string.'.format(rust_crate_type))
  1110. def is_linkable_target(self):
  1111. return True
  1112. class SharedLibrary(BuildTarget):
  1113. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1114. self.soversion = None
  1115. self.ltversion = None
  1116. self.vs_module_defs = None
  1117. # The import library this target will generate
  1118. self.import_filename = None
  1119. # The import library that Visual Studio would generate (and accept)
  1120. self.vs_import_filename = None
  1121. # The import library that GCC would generate (and prefer)
  1122. self.gcc_import_filename = None
  1123. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1124. if 'rust' in self.compilers:
  1125. # If no crate type is specified, or it's the generic lib type, use dylib
  1126. if not hasattr(self, 'rust_crate_type') or self.rust_crate_type == 'lib':
  1127. mlog.debug('Defaulting Rust dynamic library target crate type to "dylib"')
  1128. self.rust_crate_type = 'dylib'
  1129. # Don't let configuration proceed with a non-dynamic crate type
  1130. elif self.rust_crate_type not in ['dylib', 'cdylib']:
  1131. raise InvalidArguments('Crate type "{0}" invalid for dynamic libraries; must be "dylib" or "cdylib"'.format(self.rust_crate_type))
  1132. if not hasattr(self, 'prefix'):
  1133. self.prefix = None
  1134. if not hasattr(self, 'suffix'):
  1135. self.suffix = None
  1136. self.basic_filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1137. self.determine_filenames(is_cross, environment)
  1138. def determine_filenames(self, is_cross, env):
  1139. """
  1140. See https://github.com/mesonbuild/meson/pull/417 for details.
  1141. First we determine the filename template (self.filename_tpl), then we
  1142. set the output filename (self.filename).
  1143. The template is needed while creating aliases (self.get_aliases),
  1144. which are needed while generating .so shared libraries for Linux.
  1145. Besides this, there's also the import library name, which is only used
  1146. on Windows since on that platform the linker uses a separate library
  1147. called the "import library" during linking instead of the shared
  1148. library (DLL). The toolchain will output an import library in one of
  1149. two formats: GCC or Visual Studio.
  1150. When we're building with Visual Studio, the import library that will be
  1151. generated by the toolchain is self.vs_import_filename, and with
  1152. MinGW/GCC, it's self.gcc_import_filename. self.import_filename will
  1153. always contain the import library name this target will generate.
  1154. """
  1155. prefix = ''
  1156. suffix = ''
  1157. self.filename_tpl = self.basic_filename_tpl
  1158. # If the user already provided the prefix and suffix to us, we don't
  1159. # need to do any filename suffix/prefix detection.
  1160. # NOTE: manual prefix/suffix override is currently only tested for C/C++
  1161. if self.prefix is not None and self.suffix is not None:
  1162. pass
  1163. # C# and Mono
  1164. elif 'cs' in self.compilers:
  1165. prefix = ''
  1166. suffix = 'dll'
  1167. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1168. # C, C++, Swift, Vala
  1169. # Only Windows uses a separate import library for linking
  1170. # For all other targets/platforms import_filename stays None
  1171. elif for_windows(is_cross, env):
  1172. suffix = 'dll'
  1173. self.vs_import_filename = '{0}.lib'.format(self.name)
  1174. self.gcc_import_filename = 'lib{0}.dll.a'.format(self.name)
  1175. if self.get_using_msvc():
  1176. # Shared library is of the form foo.dll
  1177. prefix = ''
  1178. # Import library is called foo.lib
  1179. self.import_filename = self.vs_import_filename
  1180. # Assume GCC-compatible naming
  1181. else:
  1182. # Shared library is of the form libfoo.dll
  1183. prefix = 'lib'
  1184. # Import library is called libfoo.dll.a
  1185. self.import_filename = self.gcc_import_filename
  1186. # Shared library has the soversion if it is defined
  1187. if self.soversion:
  1188. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1189. else:
  1190. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1191. elif for_cygwin(is_cross, env):
  1192. suffix = 'dll'
  1193. self.gcc_import_filename = 'lib{0}.dll.a'.format(self.name)
  1194. # Shared library is of the form cygfoo.dll
  1195. # (ld --dll-search-prefix=cyg is the default)
  1196. prefix = 'cyg'
  1197. # Import library is called libfoo.dll.a
  1198. self.import_filename = self.gcc_import_filename
  1199. if self.soversion:
  1200. self.filename_tpl = '{0.prefix}{0.name}-{0.soversion}.{0.suffix}'
  1201. else:
  1202. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1203. elif for_darwin(is_cross, env):
  1204. prefix = 'lib'
  1205. suffix = 'dylib'
  1206. # On macOS, the filename can only contain the major version
  1207. if self.soversion:
  1208. # libfoo.X.dylib
  1209. self.filename_tpl = '{0.prefix}{0.name}.{0.soversion}.{0.suffix}'
  1210. else:
  1211. # libfoo.dylib
  1212. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1213. else:
  1214. prefix = 'lib'
  1215. suffix = 'so'
  1216. if self.ltversion:
  1217. # libfoo.so.X[.Y[.Z]] (.Y and .Z are optional)
  1218. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.ltversion}'
  1219. elif self.soversion:
  1220. # libfoo.so.X
  1221. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}.{0.soversion}'
  1222. else:
  1223. # No versioning, libfoo.so
  1224. self.filename_tpl = '{0.prefix}{0.name}.{0.suffix}'
  1225. if self.prefix is None:
  1226. self.prefix = prefix
  1227. if self.suffix is None:
  1228. self.suffix = suffix
  1229. self.filename = self.filename_tpl.format(self)
  1230. self.outputs = [self.filename]
  1231. def process_kwargs(self, kwargs, environment):
  1232. super().process_kwargs(kwargs, environment)
  1233. # Shared library version
  1234. if 'version' in kwargs:
  1235. self.ltversion = kwargs['version']
  1236. if not isinstance(self.ltversion, str):
  1237. raise InvalidArguments('Shared library version needs to be a string, not ' + type(self.ltversion).__name__)
  1238. if not re.fullmatch(r'[0-9]+(\.[0-9]+){0,2}', self.ltversion):
  1239. raise InvalidArguments('Invalid Shared library version "{0}". Must be of the form X.Y.Z where all three are numbers. Y and Z are optional.'.format(self.ltversion))
  1240. # Try to extract/deduce the soversion
  1241. if 'soversion' in kwargs:
  1242. self.soversion = kwargs['soversion']
  1243. if isinstance(self.soversion, int):
  1244. self.soversion = str(self.soversion)
  1245. if not isinstance(self.soversion, str):
  1246. raise InvalidArguments('Shared library soversion is not a string or integer.')
  1247. elif self.ltversion:
  1248. # library version is defined, get the soversion from that
  1249. # We replicate what Autotools does here and take the first
  1250. # number of the version by default.
  1251. self.soversion = self.ltversion.split('.')[0]
  1252. # Visual Studio module-definitions file
  1253. if 'vs_module_defs' in kwargs:
  1254. path = kwargs['vs_module_defs']
  1255. if hasattr(path, 'held_object'):
  1256. path = path.held_object
  1257. if isinstance(path, str):
  1258. if os.path.isabs(path):
  1259. self.vs_module_defs = File.from_absolute_file(path)
  1260. else:
  1261. self.vs_module_defs = File.from_source_file(environment.source_dir, self.subdir, path)
  1262. self.link_depends.append(self.vs_module_defs)
  1263. elif isinstance(path, File):
  1264. # When passing a generated file.
  1265. self.vs_module_defs = path
  1266. self.link_depends.append(path)
  1267. elif hasattr(path, 'get_filename'):
  1268. # When passing output of a Custom Target
  1269. path = File.from_built_file(path.subdir, path.get_filename())
  1270. self.vs_module_defs = path
  1271. self.link_depends.append(path)
  1272. else:
  1273. raise InvalidArguments(
  1274. 'Shared library vs_module_defs must be either a string, '
  1275. 'a file object or a Custom Target')
  1276. if 'rust_crate_type' in kwargs:
  1277. rust_crate_type = kwargs['rust_crate_type']
  1278. if isinstance(rust_crate_type, str):
  1279. self.rust_crate_type = rust_crate_type
  1280. else:
  1281. raise InvalidArguments('Invalid rust_crate_type "{0}": must be a string.'.format(rust_crate_type))
  1282. def check_unknown_kwargs(self, kwargs):
  1283. self.check_unknown_kwargs_int(kwargs, known_lib_kwargs)
  1284. def get_import_filename(self):
  1285. """
  1286. The name of the import library that will be outputted by the compiler
  1287. Returns None if there is no import library required for this platform
  1288. """
  1289. return self.import_filename
  1290. def get_import_filenameslist(self):
  1291. if self.import_filename:
  1292. return [self.vs_import_filename, self.gcc_import_filename]
  1293. return []
  1294. def get_all_link_deps(self):
  1295. return [self] + self.get_transitive_link_deps()
  1296. def get_aliases(self):
  1297. """
  1298. If the versioned library name is libfoo.so.0.100.0, aliases are:
  1299. * libfoo.so.0 (soversion) -> libfoo.so.0.100.0
  1300. * libfoo.so (unversioned; for linking) -> libfoo.so.0
  1301. Same for dylib:
  1302. * libfoo.dylib (unversioned; for linking) -> libfoo.0.dylib
  1303. """
  1304. aliases = {}
  1305. # Aliases are only useful with .so and .dylib libraries. Also if
  1306. # there's no self.soversion (no versioning), we don't need aliases.
  1307. if self.suffix not in ('so', 'dylib') or not self.soversion:
  1308. return {}
  1309. # With .so libraries, the minor and micro versions are also in the
  1310. # filename. If ltversion != soversion we create an soversion alias:
  1311. # libfoo.so.0 -> libfoo.so.0.100.0
  1312. # Where libfoo.so.0.100.0 is the actual library
  1313. if self.suffix == 'so' and self.ltversion and self.ltversion != self.soversion:
  1314. alias_tpl = self.filename_tpl.replace('ltversion', 'soversion')
  1315. ltversion_filename = alias_tpl.format(self)
  1316. aliases[ltversion_filename] = self.filename
  1317. # libfoo.so.0/libfoo.0.dylib is the actual library
  1318. else:
  1319. ltversion_filename = self.filename
  1320. # Unversioned alias:
  1321. # libfoo.so -> libfoo.so.0
  1322. # libfoo.dylib -> libfoo.0.dylib
  1323. aliases[self.basic_filename_tpl.format(self)] = ltversion_filename
  1324. return aliases
  1325. def type_suffix(self):
  1326. return "@sha"
  1327. def is_linkable_target(self):
  1328. return True
  1329. # A shared library that is meant to be used with dlopen rather than linking
  1330. # into something else.
  1331. class SharedModule(SharedLibrary):
  1332. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1333. if 'version' in kwargs:
  1334. raise MesonException('Shared modules must not specify the version kwarg.')
  1335. if 'soversion' in kwargs:
  1336. raise MesonException('Shared modules must not specify the soversion kwarg.')
  1337. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1338. self.import_filename = None
  1339. class CustomTarget(Target):
  1340. known_kwargs = {'input': True,
  1341. 'output': True,
  1342. 'command': True,
  1343. 'capture': False,
  1344. 'install': True,
  1345. 'install_dir': True,
  1346. 'build_always': True,
  1347. 'depends': True,
  1348. 'depend_files': True,
  1349. 'depfile': True,
  1350. 'build_by_default': True,
  1351. 'override_options': True,
  1352. }
  1353. def __init__(self, name, subdir, subproject, kwargs, absolute_paths=False):
  1354. super().__init__(name, subdir, subproject, False)
  1355. self.dependencies = []
  1356. self.extra_depends = []
  1357. self.depend_files = [] # Files that this target depends on but are not on the command line.
  1358. self.depfile = None
  1359. self.envvars = {}
  1360. self.ninja_pool = None
  1361. self.process_kwargs(kwargs)
  1362. self.extra_files = []
  1363. # Whether to use absolute paths for all files on the commandline
  1364. self.absolute_paths = absolute_paths
  1365. unknowns = []
  1366. for k in kwargs:
  1367. if k not in CustomTarget.known_kwargs:
  1368. unknowns.append(k)
  1369. if len(unknowns) > 0:
  1370. mlog.warning('Unknown keyword arguments in target %s: %s' %
  1371. (self.name, ', '.join(unknowns)))
  1372. def __lt__(self, other):
  1373. return self.get_id() < other.get_id()
  1374. def __repr__(self):
  1375. repr_str = "<{0} {1}: {2}>"
  1376. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1377. def get_id(self):
  1378. return self.name + self.type_suffix()
  1379. def get_target_dependencies(self):
  1380. deps = self.dependencies[:]
  1381. deps += self.extra_depends
  1382. for c in self.sources:
  1383. if hasattr(c, 'held_object'):
  1384. c = c.held_object
  1385. if isinstance(c, (BuildTarget, CustomTarget)):
  1386. deps.append(c)
  1387. return deps
  1388. def get_transitive_build_target_deps(self):
  1389. '''
  1390. Recursively fetch the build targets that this custom target depends on,
  1391. whether through `command:`, `depends:`, or `sources:` The recursion is
  1392. only performed on custom targets.
  1393. This is useful for setting PATH on Windows for finding required DLLs.
  1394. F.ex, if you have a python script that loads a C module that links to
  1395. other DLLs in your project.
  1396. '''
  1397. bdeps = set()
  1398. deps = self.get_target_dependencies()
  1399. for d in deps:
  1400. if isinstance(d, BuildTarget):
  1401. bdeps.add(d)
  1402. elif isinstance(d, CustomTarget):
  1403. bdeps.update(d.get_transitive_build_target_deps())
  1404. return bdeps
  1405. def flatten_command(self, cmd):
  1406. cmd = listify(cmd, unholder=True)
  1407. final_cmd = []
  1408. for c in cmd:
  1409. if isinstance(c, str):
  1410. final_cmd.append(c)
  1411. elif isinstance(c, File):
  1412. self.depend_files.append(c)
  1413. final_cmd.append(c)
  1414. elif isinstance(c, dependencies.ExternalProgram):
  1415. if not c.found():
  1416. m = 'Tried to use not-found external program {!r} in "command"'
  1417. raise InvalidArguments(m.format(c.name))
  1418. self.depend_files.append(File.from_absolute_file(c.get_path()))
  1419. final_cmd += c.get_command()
  1420. elif isinstance(c, (BuildTarget, CustomTarget)):
  1421. self.dependencies.append(c)
  1422. final_cmd.append(c)
  1423. elif isinstance(c, list):
  1424. final_cmd += self.flatten_command(c)
  1425. else:
  1426. raise InvalidArguments('Argument {!r} in "command" is invalid'.format(c))
  1427. return final_cmd
  1428. def process_kwargs(self, kwargs):
  1429. super().process_kwargs(kwargs)
  1430. self.sources = extract_as_list(kwargs, 'input', unholder=True)
  1431. if 'output' not in kwargs:
  1432. raise InvalidArguments('Missing keyword argument "output".')
  1433. self.outputs = listify(kwargs['output'])
  1434. # This will substitute values from the input into output and return it.
  1435. inputs = get_sources_string_names(self.sources)
  1436. values = get_filenames_templates_dict(inputs, [])
  1437. for i in self.outputs:
  1438. if not isinstance(i, str):
  1439. raise InvalidArguments('Output argument not a string.')
  1440. ipath = PurePath(i)
  1441. if ipath.is_absolute():
  1442. raise InvalidArguments('Output must not be an absolute path')
  1443. if '..' in ipath.parts:
  1444. raise InvalidArguments('Output path must not contain ".."')
  1445. if '@INPUT@' in i or '@INPUT0@' in i:
  1446. m = 'Output cannot contain @INPUT@ or @INPUT0@, did you ' \
  1447. 'mean @PLAINNAME@ or @BASENAME@?'
  1448. raise InvalidArguments(m)
  1449. # We already check this during substitution, but the error message
  1450. # will be unclear/confusing, so check it here.
  1451. if len(inputs) != 1 and ('@PLAINNAME@' in i or '@BASENAME@' in i):
  1452. m = "Output cannot contain @PLAINNAME@ or @BASENAME@ when " \
  1453. "there is more than one input (we can't know which to use)"
  1454. raise InvalidArguments(m)
  1455. self.outputs = substitute_values(self.outputs, values)
  1456. self.capture = kwargs.get('capture', False)
  1457. if self.capture and len(self.outputs) != 1:
  1458. raise InvalidArguments('Capturing can only output to a single file.')
  1459. if 'command' not in kwargs:
  1460. raise InvalidArguments('Missing keyword argument "command".')
  1461. if 'depfile' in kwargs:
  1462. depfile = kwargs['depfile']
  1463. if not isinstance(depfile, str):
  1464. raise InvalidArguments('Depfile must be a string.')
  1465. deppath = PurePath(depfile)
  1466. if deppath.is_absolute():
  1467. raise InvalidArguments('Depfile must not be an absolute path')
  1468. if '..' in deppath.parts:
  1469. raise InvalidArguments('Depfile must not contain ".."')
  1470. self.depfile = depfile
  1471. self.command = self.flatten_command(kwargs['command'])
  1472. if self.capture:
  1473. for c in self.command:
  1474. if isinstance(c, str) and '@OUTPUT@' in c:
  1475. raise InvalidArguments('@OUTPUT@ is not allowed when capturing output.')
  1476. if 'install' in kwargs:
  1477. self.install = kwargs['install']
  1478. if not isinstance(self.install, bool):
  1479. raise InvalidArguments('"install" must be boolean.')
  1480. if self.install:
  1481. if 'install_dir' not in kwargs:
  1482. raise InvalidArguments('"install_dir" must be specified '
  1483. 'when installing a target')
  1484. # If an item in this list is False, the output corresponding to
  1485. # the list index of that item will not be installed
  1486. self.install_dir = typeslistify(kwargs['install_dir'], (str, bool))
  1487. else:
  1488. self.install = False
  1489. self.install_dir = [None]
  1490. self.build_always = kwargs.get('build_always', False)
  1491. if not isinstance(self.build_always, bool):
  1492. raise InvalidArguments('Argument build_always must be a boolean.')
  1493. extra_deps, depend_files = extract_as_list(kwargs, 'depends', 'depend_files', pop = False)
  1494. for ed in extra_deps:
  1495. while hasattr(ed, 'held_object'):
  1496. ed = ed.held_object
  1497. if not isinstance(ed, (CustomTarget, BuildTarget)):
  1498. raise InvalidArguments('Can only depend on toplevel targets: custom_target or build_target (executable or a library)')
  1499. self.extra_depends.append(ed)
  1500. for i in depend_files:
  1501. if isinstance(i, (File, str)):
  1502. self.depend_files.append(i)
  1503. else:
  1504. mlog.debug(i)
  1505. raise InvalidArguments('Unknown type {!r} in depend_files.'.format(type(i).__name__))
  1506. def get_dependencies(self):
  1507. return self.dependencies
  1508. def should_install(self):
  1509. return self.install
  1510. def get_custom_install_dir(self):
  1511. return self.install_dir
  1512. def get_outputs(self):
  1513. return self.outputs
  1514. def get_filename(self):
  1515. return self.outputs[0]
  1516. def get_sources(self):
  1517. return self.sources
  1518. def get_generated_lists(self):
  1519. genlists = []
  1520. for c in self.sources:
  1521. if hasattr(c, 'held_object'):
  1522. c = c.held_object
  1523. if isinstance(c, GeneratedList):
  1524. genlists.append(c)
  1525. return genlists
  1526. def get_generated_sources(self):
  1527. return self.get_generated_lists()
  1528. def type_suffix(self):
  1529. return "@cus"
  1530. def __getitem__(self, index):
  1531. return CustomTargetIndex(self, self.outputs[index])
  1532. def __setitem__(self, index, value):
  1533. raise NotImplementedError
  1534. def __delitem__(self, index):
  1535. raise NotImplementedError
  1536. class RunTarget(Target):
  1537. def __init__(self, name, command, args, dependencies, subdir, subproject):
  1538. super().__init__(name, subdir, subproject, False)
  1539. self.command = command
  1540. self.args = args
  1541. self.dependencies = dependencies
  1542. def __lt__(self, other):
  1543. return self.get_id() < other.get_id()
  1544. def __repr__(self):
  1545. repr_str = "<{0} {1}: {2}>"
  1546. return repr_str.format(self.__class__.__name__, self.get_id(), self.command)
  1547. def get_dependencies(self):
  1548. return self.dependencies
  1549. def get_generated_sources(self):
  1550. return []
  1551. def get_sources(self):
  1552. return []
  1553. def should_install(self):
  1554. return False
  1555. def get_filename(self):
  1556. return self.name
  1557. def type_suffix(self):
  1558. return "@run"
  1559. class Jar(BuildTarget):
  1560. def __init__(self, name, subdir, subproject, is_cross, sources, objects, environment, kwargs):
  1561. super().__init__(name, subdir, subproject, is_cross, sources, objects, environment, kwargs)
  1562. for s in self.sources:
  1563. if not s.endswith('.java'):
  1564. raise InvalidArguments('Jar source %s is not a java file.' % s)
  1565. self.filename = self.name + '.jar'
  1566. self.outputs = [self.filename]
  1567. self.java_args = kwargs.get('java_args', [])
  1568. def get_main_class(self):
  1569. return self.main_class
  1570. def type_suffix(self):
  1571. return "@jar"
  1572. def get_java_args(self):
  1573. return self.java_args
  1574. def validate_cross_install(self, environment):
  1575. # All jar targets are installable.
  1576. pass
  1577. class CustomTargetIndex:
  1578. """A special opaque object returned by indexing a CustomTarget. This object
  1579. exists in meson, but acts as a proxy in the backends, making targets depend
  1580. on the CustomTarget it's derived from, but only adding one source file to
  1581. the sources.
  1582. """
  1583. def __init__(self, target, output):
  1584. self.target = target
  1585. self.output = output
  1586. def __repr__(self):
  1587. return '<CustomTargetIndex: {!r}[{}]>'.format(
  1588. self.target, self.target.output.index(self.output))
  1589. def get_outputs(self):
  1590. return [self.output]
  1591. def get_subdir(self):
  1592. return self.target.get_subdir()
  1593. class ConfigureFile:
  1594. def __init__(self, subdir, sourcename, targetname, configuration_data):
  1595. self.subdir = subdir
  1596. self.sourcename = sourcename
  1597. self.targetname = targetname
  1598. self.configuration_data = configuration_data
  1599. def __repr__(self):
  1600. repr_str = "<{0}: {1} -> {2}>"
  1601. src = os.path.join(self.subdir, self.sourcename)
  1602. dst = os.path.join(self.subdir, self.targetname)
  1603. return repr_str.format(self.__class__.__name__, src, dst)
  1604. def get_configuration_data(self):
  1605. return self.configuration_data
  1606. def get_subdir(self):
  1607. return self.subdir
  1608. def get_source_name(self):
  1609. return self.sourcename
  1610. def get_target_name(self):
  1611. return self.targetname
  1612. class ConfigurationData:
  1613. def __init__(self):
  1614. super().__init__()
  1615. self.values = {}
  1616. def __repr__(self):
  1617. return repr(self.values)
  1618. def __contains__(self, value):
  1619. return value in self.values
  1620. def get(self, name):
  1621. return self.values[name] # (val, desc)
  1622. def keys(self):
  1623. return self.values.keys()
  1624. # A bit poorly named, but this represents plain data files to copy
  1625. # during install.
  1626. class Data:
  1627. def __init__(self, sources, install_dir, install_mode=None):
  1628. self.sources = sources
  1629. self.install_dir = install_dir
  1630. self.install_mode = install_mode
  1631. self.sources = listify(self.sources)
  1632. for s in self.sources:
  1633. assert(isinstance(s, File))
  1634. class RunScript(dict):
  1635. def __init__(self, script, args):
  1636. super().__init__()
  1637. assert(isinstance(script, list))
  1638. assert(isinstance(args, list))
  1639. self['exe'] = script
  1640. self['args'] = args
  1641. class TestSetup:
  1642. def __init__(self, *, exe_wrapper=None, gdb=None, timeout_multiplier=None, env=None):
  1643. self.exe_wrapper = exe_wrapper
  1644. self.gdb = gdb
  1645. self.timeout_multiplier = timeout_multiplier
  1646. self.env = env
  1647. def get_sources_string_names(sources):
  1648. '''
  1649. For the specified list of @sources which can be strings, Files, or targets,
  1650. get all the output basenames.
  1651. '''
  1652. names = []
  1653. for s in sources:
  1654. if hasattr(s, 'held_object'):
  1655. s = s.held_object
  1656. if isinstance(s, str):
  1657. names.append(s)
  1658. elif isinstance(s, (BuildTarget, CustomTarget, GeneratedList)):
  1659. names += s.get_outputs()
  1660. elif isinstance(s, File):
  1661. names.append(s.fname)
  1662. else:
  1663. raise AssertionError('Unknown source type: {!r}'.format(s))
  1664. return names