coredata.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 pickle, os, uuid
  12. from pathlib import PurePath
  13. from collections import OrderedDict
  14. from .mesonlib import MesonException, commonpath
  15. from .mesonlib import default_libdir, default_libexecdir, default_prefix
  16. import ast
  17. version = '0.42.0.dev1'
  18. backendlist = ['ninja', 'vs', 'vs2010', 'vs2015', 'vs2017', 'xcode']
  19. class UserOption:
  20. def __init__(self, name, description, choices):
  21. super().__init__()
  22. self.name = name
  23. self.choices = choices
  24. self.description = description
  25. def parse_string(self, valuestring):
  26. return valuestring
  27. # Check that the input is a valid value and return the
  28. # "cleaned" or "native" version. For example the Boolean
  29. # option could take the string "true" and return True.
  30. def validate_value(self, value):
  31. raise RuntimeError('Derived option class did not override validate_value.')
  32. class UserStringOption(UserOption):
  33. def __init__(self, name, description, value, choices=None):
  34. super().__init__(name, description, choices)
  35. self.set_value(value)
  36. def validate(self, value):
  37. if not isinstance(value, str):
  38. raise MesonException('Value "%s" for string option "%s" is not a string.' % (str(value), self.name))
  39. def set_value(self, newvalue):
  40. self.validate(newvalue)
  41. self.value = newvalue
  42. def validate_value(self, value):
  43. self.validate(value)
  44. return value
  45. class UserBooleanOption(UserOption):
  46. def __init__(self, name, description, value):
  47. super().__init__(name, description, [True, False])
  48. self.set_value(value)
  49. def tobool(self, thing):
  50. if isinstance(thing, bool):
  51. return thing
  52. if thing.lower() == 'true':
  53. return True
  54. if thing.lower() == 'false':
  55. return False
  56. raise MesonException('Value %s is not boolean (true or false).' % thing)
  57. def set_value(self, newvalue):
  58. self.value = self.tobool(newvalue)
  59. def parse_string(self, valuestring):
  60. if valuestring == 'false':
  61. return False
  62. if valuestring == 'true':
  63. return True
  64. raise MesonException('Value "%s" for boolean option "%s" is not a boolean.' % (valuestring, self.name))
  65. def __bool__(self):
  66. return self.value
  67. def validate_value(self, value):
  68. return self.tobool(value)
  69. class UserComboOption(UserOption):
  70. def __init__(self, name, description, choices, value):
  71. super().__init__(name, description, choices)
  72. if not isinstance(self.choices, list):
  73. raise MesonException('Combo choices must be an array.')
  74. for i in self.choices:
  75. if not isinstance(i, str):
  76. raise MesonException('Combo choice elements must be strings.')
  77. self.set_value(value)
  78. def set_value(self, newvalue):
  79. if newvalue not in self.choices:
  80. optionsstring = ', '.join(['"%s"' % (item,) for item in self.choices])
  81. raise MesonException('Value "%s" for combo option "%s" is not one of the choices. Possible choices are: %s.' % (newvalue, self.name, optionsstring))
  82. self.value = newvalue
  83. def validate_value(self, value):
  84. if value not in self.choices:
  85. raise MesonException('Value %s not one of accepted values.' % value)
  86. return value
  87. class UserStringArrayOption(UserOption):
  88. def __init__(self, name, description, value, **kwargs):
  89. super().__init__(name, description, kwargs.get('choices', []))
  90. self.set_value(value)
  91. def validate(self, value):
  92. if isinstance(value, str):
  93. if not value.startswith('['):
  94. raise MesonException('Valuestring does not define an array: ' + value)
  95. newvalue = ast.literal_eval(value)
  96. else:
  97. newvalue = value
  98. if not isinstance(newvalue, list):
  99. raise MesonException('"{0}" should be a string array, but it is not'.format(str(newvalue)))
  100. for i in newvalue:
  101. if not isinstance(i, str):
  102. raise MesonException('String array element "{0}" is not a string.'.format(str(newvalue)))
  103. return newvalue
  104. def set_value(self, newvalue):
  105. self.value = self.validate(newvalue)
  106. def validate_value(self, value):
  107. self.validate(value)
  108. return value
  109. # This class contains all data that must persist over multiple
  110. # invocations of Meson. It is roughly the same thing as
  111. # cmakecache.
  112. class CoreData:
  113. def __init__(self, options):
  114. self.guid = str(uuid.uuid4()).upper()
  115. self.test_guid = str(uuid.uuid4()).upper()
  116. self.regen_guid = str(uuid.uuid4()).upper()
  117. self.target_guids = {}
  118. self.version = version
  119. self.init_builtins(options)
  120. self.user_options = {}
  121. self.compiler_options = {}
  122. self.base_options = {}
  123. # These external_*args, are set via env vars CFLAGS, LDFLAGS, etc
  124. # but only when not cross-compiling.
  125. self.external_preprocess_args = {} # CPPFLAGS only
  126. self.external_args = {} # CPPFLAGS + CFLAGS
  127. self.external_link_args = {} # CFLAGS + LDFLAGS (with MSVC: only LDFLAGS)
  128. if options.cross_file is not None:
  129. self.cross_file = os.path.join(os.getcwd(), options.cross_file)
  130. else:
  131. self.cross_file = None
  132. self.wrap_mode = options.wrap_mode
  133. self.compilers = OrderedDict()
  134. self.cross_compilers = OrderedDict()
  135. self.deps = OrderedDict()
  136. self.modules = {}
  137. # Only to print a warning if it changes between Meson invocations.
  138. self.pkgconf_envvar = os.environ.get('PKG_CONFIG_PATH', '')
  139. def sanitize_prefix(self, prefix):
  140. if not os.path.isabs(prefix):
  141. raise MesonException('prefix value {!r} must be an absolute path'
  142. ''.format(prefix))
  143. if prefix.endswith('/') or prefix.endswith('\\'):
  144. # On Windows we need to preserve the trailing slash if the
  145. # string is of type 'C:\' because 'C:' is not an absolute path.
  146. if len(prefix) == 3 and prefix[1] == ':':
  147. pass
  148. else:
  149. prefix = prefix[:-1]
  150. return prefix
  151. def sanitize_dir_option_value(self, prefix, option, value):
  152. '''
  153. If the option is an installation directory option and the value is an
  154. absolute path, check that it resides within prefix and return the value
  155. as a path relative to the prefix.
  156. This way everyone can do f.ex, get_option('libdir') and be sure to get
  157. the library directory relative to prefix.
  158. '''
  159. if option.endswith('dir') and os.path.isabs(value) and \
  160. option not in builtin_dir_noprefix_options:
  161. # Value must be a subdir of the prefix
  162. # commonpath will always return a path in the native format, so we
  163. # must use pathlib.PurePath to do the same conversion before
  164. # comparing.
  165. if commonpath([value, prefix]) != str(PurePath(prefix)):
  166. m = 'The value of the {!r} option is {!r} which must be a ' \
  167. 'subdir of the prefix {!r}.\nNote that if you pass a ' \
  168. 'relative path, it is assumed to be a subdir of prefix.'
  169. raise MesonException(m.format(option, value, prefix))
  170. # Convert path to be relative to prefix
  171. skip = len(prefix) + 1
  172. value = value[skip:]
  173. return value
  174. def init_builtins(self, options):
  175. self.builtins = {}
  176. # Sanitize prefix
  177. options.prefix = self.sanitize_prefix(options.prefix)
  178. # Initialize other builtin options
  179. for key in get_builtin_options():
  180. if hasattr(options, key):
  181. value = getattr(options, key)
  182. value = self.sanitize_dir_option_value(options.prefix, key, value)
  183. setattr(options, key, value)
  184. else:
  185. value = get_builtin_option_default(key)
  186. args = [key] + builtin_options[key][1:-1] + [value]
  187. self.builtins[key] = builtin_options[key][0](*args)
  188. def get_builtin_option(self, optname):
  189. if optname in self.builtins:
  190. return self.builtins[optname].value
  191. raise RuntimeError('Tried to get unknown builtin option %s.' % optname)
  192. def set_builtin_option(self, optname, value):
  193. if optname == 'prefix':
  194. value = self.sanitize_prefix(value)
  195. elif optname in self.builtins:
  196. prefix = self.builtins['prefix'].value
  197. value = self.sanitize_dir_option_value(prefix, optname, value)
  198. else:
  199. raise RuntimeError('Tried to set unknown builtin option %s.' % optname)
  200. self.builtins[optname].set_value(value)
  201. def validate_option_value(self, option_name, override_value):
  202. for opts in (self.builtins, self.base_options, self.compiler_options, self.user_options):
  203. if option_name in opts:
  204. opt = opts[option_name]
  205. return opt.validate_value(override_value)
  206. raise MesonException('Tried to validate unknown option %s.' % option_name)
  207. def load(filename):
  208. load_fail_msg = 'Coredata file {!r} is corrupted. Try with a fresh build tree.'.format(filename)
  209. try:
  210. with open(filename, 'rb') as f:
  211. obj = pickle.load(f)
  212. except pickle.UnpicklingError:
  213. raise MesonException(load_fail_msg)
  214. if not isinstance(obj, CoreData):
  215. raise MesonException(load_fail_msg)
  216. if obj.version != version:
  217. raise MesonException('Build directory has been generated with Meson version %s, which is incompatible with current version %s.\nPlease delete this build directory AND create a new one.' %
  218. (obj.version, version))
  219. return obj
  220. def save(obj, filename):
  221. if obj.version != version:
  222. raise MesonException('Fatal version mismatch corruption.')
  223. with open(filename, 'wb') as f:
  224. pickle.dump(obj, f)
  225. def get_builtin_options():
  226. return list(builtin_options.keys())
  227. def is_builtin_option(optname):
  228. return optname in get_builtin_options()
  229. def get_builtin_option_choices(optname):
  230. if is_builtin_option(optname):
  231. if builtin_options[optname][0] == UserStringOption:
  232. return None
  233. elif builtin_options[optname][0] == UserBooleanOption:
  234. return [True, False]
  235. else:
  236. return builtin_options[optname][2]
  237. else:
  238. raise RuntimeError('Tried to get the supported values for an unknown builtin option \'%s\'.' % optname)
  239. def get_builtin_option_description(optname):
  240. if is_builtin_option(optname):
  241. return builtin_options[optname][1]
  242. else:
  243. raise RuntimeError('Tried to get the description for an unknown builtin option \'%s\'.' % optname)
  244. def get_builtin_option_default(optname):
  245. if is_builtin_option(optname):
  246. o = builtin_options[optname]
  247. if o[0] == UserComboOption:
  248. return o[3]
  249. return o[2]
  250. else:
  251. raise RuntimeError('Tried to get the default value for an unknown builtin option \'%s\'.' % optname)
  252. builtin_options = {
  253. 'buildtype': [UserComboOption, 'Build type to use.', ['plain', 'debug', 'debugoptimized', 'release', 'minsize'], 'debug'],
  254. 'strip': [UserBooleanOption, 'Strip targets on install.', False],
  255. 'unity': [UserComboOption, 'Unity build.', ['on', 'off', 'subprojects'], 'off'],
  256. 'prefix': [UserStringOption, 'Installation prefix.', default_prefix()],
  257. 'libdir': [UserStringOption, 'Library directory.', default_libdir()],
  258. 'libexecdir': [UserStringOption, 'Library executable directory.', default_libexecdir()],
  259. 'bindir': [UserStringOption, 'Executable directory.', 'bin'],
  260. 'sbindir': [UserStringOption, 'System executable directory.', 'sbin'],
  261. 'includedir': [UserStringOption, 'Header file directory.', 'include'],
  262. 'datadir': [UserStringOption, 'Data file directory.', 'share'],
  263. 'mandir': [UserStringOption, 'Manual page directory.', 'share/man'],
  264. 'infodir': [UserStringOption, 'Info page directory.', 'share/info'],
  265. 'localedir': [UserStringOption, 'Locale data directory.', 'share/locale'],
  266. # sysconfdir, localstatedir and sharedstatedir are a bit special. These defaults to ${prefix}/etc,
  267. # ${prefix}/var and ${prefix}/com but nobody uses that. Instead they always set it
  268. # manually to /etc, /var and /var/lib. This default values is thus pointless and not really used
  269. # but we set it to this for consistency with other systems.
  270. #
  271. # Projects installing to sysconfdir, localstatedir or sharedstatedir probably want
  272. # to set the following in project():
  273. #
  274. # default_options : ['sysconfdir=/etc', 'localstatedir=/var', 'sharedstatedir=/var/lib']
  275. 'sysconfdir': [UserStringOption, 'Sysconf data directory.', 'etc'],
  276. 'localstatedir': [UserStringOption, 'Localstate data directory.', 'var'],
  277. 'sharedstatedir': [UserStringOption, 'Architecture-independent data directory.', 'com'],
  278. 'werror': [UserBooleanOption, 'Treat warnings as errors.', False],
  279. 'warning_level': [UserComboOption, 'Compiler warning level to use.', ['1', '2', '3'], '1'],
  280. 'layout': [UserComboOption, 'Build directory layout.', ['mirror', 'flat'], 'mirror'],
  281. 'default_library': [UserComboOption, 'Default library type.', ['shared', 'static'], 'shared'],
  282. 'backend': [UserComboOption, 'Backend to use.', backendlist, 'ninja'],
  283. 'stdsplit': [UserBooleanOption, 'Split stdout and stderr in test logs.', True],
  284. 'errorlogs': [UserBooleanOption, "Whether to print the logs from failing tests.", True],
  285. }
  286. # Installation directories that can reside in a path outside of the prefix
  287. builtin_dir_noprefix_options = {'sysconfdir', 'localstatedir', 'sharedstatedir'}
  288. forbidden_target_names = {'clean': None,
  289. 'clean-ctlist': None,
  290. 'clean-gcno': None,
  291. 'clean-gcda': None,
  292. 'coverage': None,
  293. 'coverage-text': None,
  294. 'coverage-xml': None,
  295. 'coverage-html': None,
  296. 'phony': None,
  297. 'PHONY': None,
  298. 'all': None,
  299. 'test': None,
  300. 'benchmark': None,
  301. 'install': None,
  302. 'uninstall': None,
  303. 'build.ninja': None,
  304. 'scan-build': None,
  305. 'reconfigure': None,
  306. 'dist': None,
  307. 'distcheck': None,
  308. }