interpreter.py 117 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749
  1. # Copyright 2012-2016 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. from . import mparser
  12. from . import environment
  13. from . import coredata
  14. from . import dependencies
  15. from . import mlog
  16. from . import build
  17. from . import optinterpreter
  18. from . import compilers
  19. from .wrap import wrap
  20. from . import mesonlib
  21. import os, sys, subprocess, shutil, uuid, re
  22. from functools import wraps
  23. import importlib
  24. run_depr_printed = False
  25. class InterpreterException(mesonlib.MesonException):
  26. pass
  27. class InvalidCode(InterpreterException):
  28. pass
  29. class InvalidArguments(InterpreterException):
  30. pass
  31. # Decorators for method calls.
  32. def check_stringlist(a, msg='Arguments must be strings.'):
  33. if not isinstance(a, list):
  34. mlog.debug('Not a list:', str(a))
  35. raise InvalidArguments('Argument not a list.')
  36. if not all(isinstance(s, str) for s in a):
  37. mlog.debug('Element not a string:', str(a))
  38. raise InvalidArguments(msg)
  39. def noPosargs(f):
  40. @wraps(f)
  41. def wrapped(self, node, args, kwargs):
  42. if len(args) != 0:
  43. raise InvalidArguments('Function does not take positional arguments.')
  44. return f(self, node, args, kwargs)
  45. return wrapped
  46. def noKwargs(f):
  47. @wraps(f)
  48. def wrapped(self, node, args, kwargs):
  49. if len(kwargs) != 0:
  50. raise InvalidArguments('Function does not take keyword arguments.')
  51. return f(self, node, args, kwargs)
  52. return wrapped
  53. def stringArgs(f):
  54. @wraps(f)
  55. def wrapped(self, node, args, kwargs):
  56. assert(isinstance(args, list))
  57. check_stringlist(args)
  58. return f(self, node, args, kwargs)
  59. return wrapped
  60. def stringifyUserArguments(args):
  61. if isinstance(args, list):
  62. return '[%s]' % ', '.join([stringifyUserArguments(x) for x in args])
  63. elif isinstance(args, int):
  64. return str(args)
  65. elif isinstance(args, str):
  66. return "'%s'" % args
  67. raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  68. class InterpreterObject():
  69. def __init__(self):
  70. self.methods = {}
  71. def method_call(self, method_name, args, kwargs):
  72. if method_name in self.methods:
  73. return self.methods[method_name](args, kwargs)
  74. raise InvalidCode('Unknown method "%s" in object.' % method_name)
  75. class TryRunResultHolder(InterpreterObject):
  76. def __init__(self, res):
  77. super().__init__()
  78. self.res = res
  79. self.methods.update({'returncode' : self.returncode_method,
  80. 'compiled' : self.compiled_method,
  81. 'stdout' : self.stdout_method,
  82. 'stderr' : self.stderr_method,
  83. })
  84. def returncode_method(self, args, kwargs):
  85. return self.res.returncode
  86. def compiled_method(self, args, kwargs):
  87. return self.res.compiled
  88. def stdout_method(self, args, kwargs):
  89. return self.res.stdout
  90. def stderr_method(self, args, kwargs):
  91. return self.res.stderr
  92. class RunProcess(InterpreterObject):
  93. def __init__(self, command_array, source_dir, build_dir, subdir, in_builddir=False):
  94. super().__init__()
  95. pc = self.run_command(command_array, source_dir, build_dir, subdir, in_builddir)
  96. (stdout, stderr) = pc.communicate()
  97. self.returncode = pc.returncode
  98. if sys.stdout.encoding:
  99. self.stdout = stdout.decode(encoding=sys.stdout.encoding, errors='ignore').replace('\r\n', '\n')
  100. else:
  101. self.stdout = stdout.decode(errors='ignore').replace('\r\n', '\n')
  102. if sys.stderr.encoding:
  103. self.stderr = stderr.decode(encoding=sys.stderr.encoding, errors='ignore').replace('\r\n', '\n')
  104. else:
  105. self.stderr = stderr.decode(errors='ignore').replace('\r\n', '\n')
  106. self.methods.update({'returncode' : self.returncode_method,
  107. 'stdout' : self.stdout_method,
  108. 'stderr' : self.stderr_method,
  109. })
  110. def run_command(self, command_array, source_dir, build_dir, subdir, in_builddir):
  111. cmd_name = command_array[0]
  112. env = {'MESON_SOURCE_ROOT' : source_dir,
  113. 'MESON_BUILD_ROOT' : build_dir,
  114. 'MESON_SUBDIR' : subdir}
  115. if in_builddir:
  116. cwd = os.path.join(build_dir, subdir)
  117. else:
  118. cwd = os.path.join(source_dir, subdir)
  119. child_env = os.environ.copy()
  120. child_env.update(env)
  121. mlog.debug('Running command:', ' '.join(command_array))
  122. try:
  123. return subprocess.Popen(command_array, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  124. env=child_env, cwd=cwd)
  125. except FileNotFoundError:
  126. pass
  127. # Was not a command, is a program in path?
  128. exe = shutil.which(cmd_name)
  129. if exe is not None:
  130. command_array = [exe] + command_array[1:]
  131. return subprocess.Popen(command_array, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  132. env=child_env, cwd=cwd)
  133. # No? Maybe it is a script in the source tree.
  134. fullpath = os.path.join(source_dir, subdir, cmd_name)
  135. command_array = [fullpath] + command_array[1:]
  136. try:
  137. return subprocess.Popen(command_array, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  138. env=child_env, cwd=cwd)
  139. except FileNotFoundError:
  140. raise InterpreterException('Could not execute command "%s".' % cmd_name)
  141. def returncode_method(self, args, kwargs):
  142. return self.returncode
  143. def stdout_method(self, args, kwargs):
  144. return self.stdout
  145. def stderr_method(self, args, kwargs):
  146. return self.stderr
  147. class ConfigureFileHolder(InterpreterObject):
  148. def __init__(self, subdir, sourcename, targetname, configuration_data):
  149. InterpreterObject.__init__(self)
  150. self.held_object = build.ConfigureFile(subdir, sourcename, targetname, configuration_data)
  151. class EnvironmentVariablesHolder(InterpreterObject):
  152. def __init__(self):
  153. super().__init__()
  154. self.held_object = build.EnvironmentVariables()
  155. self.methods.update({'set': self.set_method,
  156. 'append': self.append_method,
  157. 'prepend' : self.prepend_method,
  158. })
  159. @stringArgs
  160. def add_var(self, method, args, kwargs):
  161. if not isinstance(kwargs.get("separator", ""), str):
  162. raise InterpreterException("EnvironmentVariablesHolder methods 'separator'"
  163. " argument needs to be a string.")
  164. if len(args) < 2:
  165. raise InterpreterException("EnvironmentVariablesHolder methods require at least"
  166. "2 arguments, first is the name of the variable and"
  167. " following one are values")
  168. self.held_object.envvars.append((method, args[0], args[1:], kwargs))
  169. def set_method(self, args, kwargs):
  170. self.add_var(self.held_object.set, args, kwargs)
  171. def append_method(self, args, kwargs):
  172. self.add_var(self.held_object.append, args, kwargs)
  173. def prepend_method(self, args, kwargs):
  174. self.add_var(self.held_object.prepend, args, kwargs)
  175. class ConfigurationDataHolder(InterpreterObject):
  176. def __init__(self):
  177. super().__init__()
  178. self.used = False # These objects become immutable after use in configure_file.
  179. self.held_object = build.ConfigurationData()
  180. self.methods.update({'set': self.set_method,
  181. 'set10': self.set10_method,
  182. 'set_quoted': self.set_quoted_method,
  183. 'has' : self.has_method,
  184. })
  185. def is_used(self):
  186. return self.used
  187. def mark_used(self):
  188. self.used = True
  189. def validate_args(self, args, kwargs):
  190. if len(args) != 2:
  191. raise InterpreterException("Configuration set requires 2 arguments.")
  192. if self.used:
  193. raise InterpreterException("Can not set values on configuration object that has been used.")
  194. name = args[0]
  195. val = args[1]
  196. desc = kwargs.get('description', None)
  197. if not isinstance(name, str):
  198. raise InterpreterException("First argument to set must be a string.")
  199. if desc is not None and not isinstance(desc, str):
  200. raise InterpreterException('Description must be a string.')
  201. return (name, val, desc)
  202. def set_method(self, args, kwargs):
  203. (name, val, desc) = self.validate_args(args, kwargs)
  204. self.held_object.values[name] = (val, desc)
  205. def set_quoted_method(self, args, kwargs):
  206. (name, val, desc) = self.validate_args(args, kwargs)
  207. if not isinstance(val, str):
  208. raise InterpreterException("Second argument to set_quoted must be a string.")
  209. escaped_val = '\\"'.join(val.split('"'))
  210. self.held_object.values[name] = ('"' + escaped_val + '"', desc)
  211. def set10_method(self, args, kwargs):
  212. (name, val, desc) = self.validate_args(args, kwargs)
  213. if val:
  214. self.held_object.values[name] = (1, desc)
  215. else:
  216. self.held_object.values[name] = (0, desc)
  217. def has_method(self, args, kwargs):
  218. return args[0] in self.held_object.values
  219. def get(self, name):
  220. return self.held_object.values[name] # (val, desc)
  221. def keys(self):
  222. return self.held_object.values.keys()
  223. # Interpreter objects can not be pickled so we must have
  224. # these wrappers.
  225. class DependencyHolder(InterpreterObject):
  226. def __init__(self, dep):
  227. InterpreterObject.__init__(self)
  228. self.held_object = dep
  229. self.methods.update({'found' : self.found_method,
  230. 'version': self.version_method})
  231. def found_method(self, args, kwargs):
  232. return self.held_object.found()
  233. def version_method(self, args, kwargs):
  234. return self.held_object.get_version()
  235. class InternalDependencyHolder(InterpreterObject):
  236. def __init__(self, dep):
  237. InterpreterObject.__init__(self)
  238. self.held_object = dep
  239. self.methods.update({'found' : self.found_method,
  240. 'version': self.version_method,
  241. })
  242. def found_method(self, args, kwargs):
  243. return True
  244. def version_method(self, args, kwargs):
  245. return self.held_object.get_version()
  246. class ExternalProgramHolder(InterpreterObject):
  247. def __init__(self, ep):
  248. InterpreterObject.__init__(self)
  249. self.held_object = ep
  250. self.methods.update({'found': self.found_method,
  251. 'path': self.path_method})
  252. def found_method(self, args, kwargs):
  253. return self.found()
  254. def path_method(self, args, kwargs):
  255. return self.get_command()
  256. def found(self):
  257. return self.held_object.found()
  258. def get_command(self):
  259. return self.held_object.fullpath
  260. def get_name(self):
  261. return self.held_object.name
  262. class ExternalLibraryHolder(InterpreterObject):
  263. def __init__(self, el):
  264. InterpreterObject.__init__(self)
  265. self.held_object = el
  266. self.methods.update({'found': self.found_method})
  267. def found(self):
  268. return self.held_object.found()
  269. def found_method(self, args, kwargs):
  270. return self.found()
  271. def get_filename(self):
  272. return self.held_object.fullpath
  273. def get_name(self):
  274. return self.held_object.name
  275. def get_compile_args(self):
  276. return self.held_object.get_compile_args()
  277. def get_link_args(self):
  278. return self.held_object.get_link_args()
  279. def get_exe_args(self):
  280. return self.held_object.get_exe_args()
  281. class GeneratorHolder(InterpreterObject):
  282. def __init__(self, interpreter, args, kwargs):
  283. super().__init__()
  284. self.interpreter = interpreter
  285. self.held_object = build.Generator(args, kwargs)
  286. self.methods.update({'process' : self.process_method})
  287. def process_method(self, args, kwargs):
  288. check_stringlist(args)
  289. extras = mesonlib.stringlistify(kwargs.get('extra_args', []))
  290. gl = GeneratedListHolder(self, extras)
  291. [gl.add_file(os.path.join(self.interpreter.subdir, a)) for a in args]
  292. return gl
  293. class GeneratedListHolder(InterpreterObject):
  294. def __init__(self, arg1, extra_args=[]):
  295. super().__init__()
  296. if isinstance(arg1, GeneratorHolder):
  297. self.held_object = build.GeneratedList(arg1.held_object, extra_args)
  298. else:
  299. self.held_object = arg1
  300. def add_file(self, a):
  301. self.held_object.add_file(a)
  302. class BuildMachine(InterpreterObject):
  303. def __init__(self, compilers):
  304. self.compilers = compilers
  305. InterpreterObject.__init__(self)
  306. self.methods.update({'system' : self.system_method,
  307. 'cpu_family' : self.cpu_family_method,
  308. 'cpu' : self.cpu_method,
  309. 'endian' : self.endian_method,
  310. })
  311. def cpu_family_method(self, args, kwargs):
  312. return environment.detect_cpu_family(self.compilers)
  313. def cpu_method(self, args, kwargs):
  314. return environment.detect_cpu(self.compilers)
  315. def system_method(self, args, kwargs):
  316. return environment.detect_system()
  317. def endian_method(self, args, kwargs):
  318. return sys.byteorder
  319. # This class will provide both host_machine and
  320. # target_machine
  321. class CrossMachineInfo(InterpreterObject):
  322. def __init__(self, cross_info):
  323. InterpreterObject.__init__(self)
  324. minimum_cross_info = {'cpu', 'cpu_family', 'endian', 'system'}
  325. if set(cross_info) < minimum_cross_info:
  326. raise InterpreterException(
  327. 'Machine info is currently {}\n'.format(cross_info) +
  328. 'but is missing {}.'.format(minimum_cross_info - set(cross_info)))
  329. self.info = cross_info
  330. self.methods.update({'system' : self.system_method,
  331. 'cpu' : self.cpu_method,
  332. 'cpu_family' : self.cpu_family_method,
  333. 'endian' : self.endian_method,
  334. })
  335. def system_method(self, args, kwargs):
  336. return self.info['system']
  337. def cpu_method(self, args, kwargs):
  338. return self.info['cpu']
  339. def cpu_family_method(self, args, kwargs):
  340. return self.info['cpu_family']
  341. def endian_method(self, args, kwargs):
  342. return self.info['endian']
  343. class IncludeDirsHolder(InterpreterObject):
  344. def __init__(self, idobj):
  345. super().__init__()
  346. self.held_object = idobj
  347. class Headers(InterpreterObject):
  348. def __init__(self, src_subdir, sources, kwargs):
  349. InterpreterObject.__init__(self)
  350. self.sources = sources
  351. self.source_subdir = src_subdir
  352. self.install_subdir = kwargs.get('subdir', '')
  353. self.custom_install_dir = kwargs.get('install_dir', None)
  354. if self.custom_install_dir is not None:
  355. if not isinstance(self.custom_install_dir, str):
  356. raise InterpreterException('Custom_install_dir must be a string.')
  357. def set_install_subdir(self, subdir):
  358. self.install_subdir = subdir
  359. def get_install_subdir(self):
  360. return self.install_subdir
  361. def get_source_subdir(self):
  362. return self.source_subdir
  363. def get_sources(self):
  364. return self.sources
  365. def get_custom_install_dir(self):
  366. return self.custom_install_dir
  367. class DataHolder(InterpreterObject):
  368. def __init__(self, in_sourcetree, source_subdir, sources, kwargs):
  369. super().__init__()
  370. kwsource = mesonlib.stringlistify(kwargs.get('sources', []))
  371. sources += kwsource
  372. check_stringlist(sources)
  373. install_dir = kwargs.get('install_dir', None)
  374. if not isinstance(install_dir, str):
  375. raise InterpreterException('Custom_install_dir must be a string.')
  376. self.held_object = build.Data(in_sourcetree, source_subdir, sources, install_dir)
  377. def get_source_subdir(self):
  378. return self.held_object.source_subdir
  379. def get_sources(self):
  380. return self.held_object.sources
  381. def get_install_dir(self):
  382. return self.held_object.install_dir
  383. class InstallDir(InterpreterObject):
  384. def __init__(self, source_subdir, installable_subdir, install_dir):
  385. InterpreterObject.__init__(self)
  386. self.source_subdir = source_subdir
  387. self.installable_subdir = installable_subdir
  388. self.install_dir = install_dir
  389. class Man(InterpreterObject):
  390. def __init__(self, source_subdir, sources, kwargs):
  391. InterpreterObject.__init__(self)
  392. self.source_subdir = source_subdir
  393. self.sources = sources
  394. self.validate_sources()
  395. if len(kwargs) > 1:
  396. raise InvalidArguments('Man function takes at most one keyword arguments.')
  397. self.custom_install_dir = kwargs.get('install_dir', None)
  398. if self.custom_install_dir is not None and not isinstance(self.custom_install_dir, str):
  399. raise InterpreterException('Custom_install_dir must be a string.')
  400. def validate_sources(self):
  401. for s in self.sources:
  402. try:
  403. num = int(s.split('.')[-1])
  404. except (IndexError, ValueError):
  405. num = 0
  406. if num < 1 or num > 8:
  407. raise InvalidArguments('Man file must have a file extension of a number between 1 and 8')
  408. def get_custom_install_dir(self):
  409. return self.custom_install_dir
  410. def get_sources(self):
  411. return self.sources
  412. def get_source_subdir(self):
  413. return self.source_subdir
  414. class GeneratedObjectsHolder(InterpreterObject):
  415. def __init__(self, held_object):
  416. super().__init__()
  417. self.held_object = held_object
  418. class BuildTargetHolder(InterpreterObject):
  419. def __init__(self, target, interp):
  420. super().__init__()
  421. self.held_object = target
  422. self.interpreter = interp
  423. self.methods.update({'extract_objects' : self.extract_objects_method,
  424. 'extract_all_objects' : self.extract_all_objects_method,
  425. 'get_id': self.get_id_method,
  426. 'outdir' : self.outdir_method,
  427. 'full_path' : self.full_path_method,
  428. 'private_dir_include' : self.private_dir_include_method,
  429. })
  430. def is_cross(self):
  431. return self.held_object.is_cross()
  432. def private_dir_include_method(self, args, kwargs):
  433. return IncludeDirsHolder(build.IncludeDirs('', [], False,
  434. [self.interpreter.backend.get_target_private_dir(self.held_object)]))
  435. def full_path_method(self, args, kwargs):
  436. return self.interpreter.backend.get_target_filename_abs(self.held_object)
  437. def outdir_method(self, args, kwargs):
  438. return self.interpreter.backend.get_target_dir(self.held_object)
  439. def extract_objects_method(self, args, kwargs):
  440. gobjs = self.held_object.extract_objects(args)
  441. return GeneratedObjectsHolder(gobjs)
  442. def extract_all_objects_method(self, args, kwargs):
  443. gobjs = self.held_object.extract_all_objects()
  444. return GeneratedObjectsHolder(gobjs)
  445. def get_id_method(self, args, kwargs):
  446. return self.held_object.get_id()
  447. class ExecutableHolder(BuildTargetHolder):
  448. def __init__(self, target, interp):
  449. super().__init__(target, interp)
  450. class StaticLibraryHolder(BuildTargetHolder):
  451. def __init__(self, target, interp):
  452. super().__init__(target, interp)
  453. class SharedLibraryHolder(BuildTargetHolder):
  454. def __init__(self, target, interp):
  455. super().__init__(target, interp)
  456. class JarHolder(BuildTargetHolder):
  457. def __init__(self, target, interp):
  458. super().__init__(target, interp)
  459. class CustomTargetHolder(InterpreterObject):
  460. def __init__(self, object_to_hold, interp):
  461. super().__init__()
  462. self.held_object = object_to_hold
  463. self.interpreter = interp
  464. self.methods.update({'full_path' : self.full_path_method,
  465. })
  466. def full_path_method(self, args, kwargs):
  467. return self.interpreter.backend.get_target_filename_abs(self.held_object)
  468. class RunTargetHolder(InterpreterObject):
  469. def __init__(self, name, command, args, dependencies, subdir):
  470. self.held_object = build.RunTarget(name, command, args, dependencies, subdir)
  471. class Test(InterpreterObject):
  472. def __init__(self, name, suite, exe, is_parallel, cmd_args, env, should_fail, valgrind_args, timeout, workdir):
  473. InterpreterObject.__init__(self)
  474. self.name = name
  475. self.suite = suite
  476. self.exe = exe
  477. self.is_parallel = is_parallel
  478. self.cmd_args = cmd_args
  479. self.env = env
  480. self.should_fail = should_fail
  481. self.valgrind_args = valgrind_args
  482. self.timeout = timeout
  483. self.workdir = workdir
  484. def get_exe(self):
  485. return self.exe
  486. def get_name(self):
  487. return self.name
  488. class SubprojectHolder(InterpreterObject):
  489. def __init__(self, subinterpreter):
  490. super().__init__()
  491. self.held_object = subinterpreter
  492. self.methods.update({'get_variable' : self.get_variable_method,
  493. })
  494. def get_variable_method(self, args, kwargs):
  495. if len(args) != 1:
  496. raise InterpreterException('Get_variable takes one argument.')
  497. varname = args[0]
  498. if not isinstance(varname, str):
  499. raise InterpreterException('Get_variable takes a string argument.')
  500. return self.held_object.variables[varname]
  501. class CompilerHolder(InterpreterObject):
  502. def __init__(self, compiler, env):
  503. InterpreterObject.__init__(self)
  504. self.compiler = compiler
  505. self.environment = env
  506. self.methods.update({'compiles': self.compiles_method,
  507. 'links': self.links_method,
  508. 'get_id': self.get_id_method,
  509. 'sizeof': self.sizeof_method,
  510. 'has_header': self.has_header_method,
  511. 'has_header_symbol': self.has_header_symbol_method,
  512. 'run' : self.run_method,
  513. 'has_function' : self.has_function_method,
  514. 'has_member' : self.has_member_method,
  515. 'has_members' : self.has_members_method,
  516. 'has_type' : self.has_type_method,
  517. 'alignment' : self.alignment_method,
  518. 'version' : self.version_method,
  519. 'cmd_array' : self.cmd_array_method,
  520. 'find_library': self.find_library_method,
  521. 'has_argument' : self.has_argument_method,
  522. 'first_supported_argument' : self.first_supported_argument_method,
  523. 'unittest_args' : self.unittest_args_method,
  524. })
  525. def version_method(self, args, kwargs):
  526. return self.compiler.version
  527. def cmd_array_method(self, args, kwargs):
  528. return self.compiler.exelist
  529. def determine_args(self, kwargs):
  530. nobuiltins = kwargs.get('no_builtin_args', False)
  531. if not isinstance(nobuiltins, bool):
  532. raise InterpreterException('Type of no_builtin_args not a boolean.')
  533. args = []
  534. if not nobuiltins:
  535. opts = self.environment.coredata.compiler_options
  536. args += self.compiler.get_option_compile_args(opts)
  537. args += self.compiler.get_option_link_args(opts)
  538. args += mesonlib.stringlistify(kwargs.get('args', []))
  539. return args
  540. def determine_dependencies(self, kwargs, allowed_dep_types=None):
  541. deps = kwargs.get('dependencies', None)
  542. if allowed_dep_types is None:
  543. allowed_dep_types = (dependencies.Dependency, dependencies.ExternalLibrary)
  544. if deps is not None:
  545. if not isinstance(deps, list):
  546. deps = [deps]
  547. final_deps = []
  548. for d in deps:
  549. try:
  550. d = d.held_object
  551. except Exception:
  552. pass
  553. if not isinstance(d, allowed_dep_types):
  554. raise InterpreterException('Dependencies must be external deps')
  555. final_deps.append(d)
  556. deps = final_deps
  557. return deps
  558. def alignment_method(self, args, kwargs):
  559. if len(args) != 1:
  560. raise InterpreterException('Alignment method takes exactly one positional argument.')
  561. check_stringlist(args)
  562. typename = args[0]
  563. extra_args = mesonlib.stringlistify(kwargs.get('args', []))
  564. result = self.compiler.alignment(typename, self.environment, extra_args)
  565. mlog.log('Checking for alignment of "', mlog.bold(typename), '": ', result, sep='')
  566. return result
  567. def run_method(self, args, kwargs):
  568. if len(args) != 1:
  569. raise InterpreterException('Run method takes exactly one positional argument.')
  570. check_stringlist(args)
  571. code = args[0]
  572. testname = kwargs.get('name', '')
  573. if not isinstance(testname, str):
  574. raise InterpreterException('Testname argument must be a string.')
  575. extra_args = self.determine_args(kwargs)
  576. deps = self.determine_dependencies(kwargs)
  577. result = self.compiler.run(code, self.environment, extra_args, deps)
  578. if len(testname) > 0:
  579. if not result.compiled:
  580. h = mlog.red('DID NOT COMPILE')
  581. elif result.returncode == 0:
  582. h = mlog.green('YES')
  583. else:
  584. h = mlog.red('NO (%d)' % result.returncode)
  585. mlog.log('Checking if "', mlog.bold(testname), '" runs : ', h, sep='')
  586. return TryRunResultHolder(result)
  587. def get_id_method(self, args, kwargs):
  588. return self.compiler.get_id()
  589. def unittest_args_method(self, args, kwargs):
  590. # At time, only D compilers have this feature.
  591. if not hasattr(self.compiler, 'get_unittest_args'):
  592. raise InterpreterException('This {} compiler has no unittest arguments.'.format(self.compiler.language))
  593. return self.compiler.get_unittest_args()
  594. def has_member_method(self, args, kwargs):
  595. if len(args) != 2:
  596. raise InterpreterException('Has_member takes exactly two arguments.')
  597. check_stringlist(args)
  598. typename = args[0]
  599. membername = args[1]
  600. prefix = kwargs.get('prefix', '')
  601. if not isinstance(prefix, str):
  602. raise InterpreterException('Prefix argument of has_member must be a string.')
  603. extra_args = self.determine_args(kwargs)
  604. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  605. had = self.compiler.has_members(typename, [membername], prefix,
  606. self.environment, extra_args, deps)
  607. if had:
  608. hadtxt = mlog.green('YES')
  609. else:
  610. hadtxt = mlog.red('NO')
  611. mlog.log('Checking whether type "', mlog.bold(typename),
  612. '" has member "', mlog.bold(membername), '": ', hadtxt, sep='')
  613. return had
  614. def has_members_method(self, args, kwargs):
  615. check_stringlist(args)
  616. typename = args[0]
  617. membernames = args[1:]
  618. prefix = kwargs.get('prefix', '')
  619. if not isinstance(prefix, str):
  620. raise InterpreterException('Prefix argument of has_members must be a string.')
  621. extra_args = self.determine_args(kwargs)
  622. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  623. had = self.compiler.has_members(typename, membernames, prefix,
  624. self.environment, extra_args, deps)
  625. if had:
  626. hadtxt = mlog.green('YES')
  627. else:
  628. hadtxt = mlog.red('NO')
  629. members = mlog.bold(', '.join(['"{}"'.format(m) for m in membernames]))
  630. mlog.log('Checking whether type "', mlog.bold(typename),
  631. '" has members ', members, ': ', hadtxt, sep='')
  632. return had
  633. def has_function_method(self, args, kwargs):
  634. if len(args) != 1:
  635. raise InterpreterException('Has_function takes exactly one argument.')
  636. check_stringlist(args)
  637. funcname = args[0]
  638. prefix = kwargs.get('prefix', '')
  639. if not isinstance(prefix, str):
  640. raise InterpreterException('Prefix argument of has_function must be a string.')
  641. extra_args = self.determine_args(kwargs)
  642. deps = self.determine_dependencies(kwargs)
  643. had = self.compiler.has_function(funcname, prefix, self.environment, extra_args, deps)
  644. if had:
  645. hadtxt = mlog.green('YES')
  646. else:
  647. hadtxt = mlog.red('NO')
  648. mlog.log('Checking for function "', mlog.bold(funcname), '": ', hadtxt, sep='')
  649. return had
  650. def has_type_method(self, args, kwargs):
  651. if len(args) != 1:
  652. raise InterpreterException('Has_type takes exactly one argument.')
  653. check_stringlist(args)
  654. typename = args[0]
  655. prefix = kwargs.get('prefix', '')
  656. if not isinstance(prefix, str):
  657. raise InterpreterException('Prefix argument of has_type must be a string.')
  658. extra_args = self.determine_args(kwargs)
  659. deps = self.determine_dependencies(kwargs)
  660. had = self.compiler.has_type(typename, prefix, self.environment, extra_args, deps)
  661. if had:
  662. hadtxt = mlog.green('YES')
  663. else:
  664. hadtxt = mlog.red('NO')
  665. mlog.log('Checking for type "', mlog.bold(typename), '": ', hadtxt, sep='')
  666. return had
  667. def sizeof_method(self, args, kwargs):
  668. if len(args) != 1:
  669. raise InterpreterException('Sizeof takes exactly one argument.')
  670. check_stringlist(args)
  671. element = args[0]
  672. prefix = kwargs.get('prefix', '')
  673. if not isinstance(prefix, str):
  674. raise InterpreterException('Prefix argument of sizeof must be a string.')
  675. extra_args = self.determine_args(kwargs)
  676. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  677. esize = self.compiler.sizeof(element, prefix, self.environment, extra_args, deps)
  678. mlog.log('Checking for size of "%s": %d' % (element, esize))
  679. return esize
  680. def compiles_method(self, args, kwargs):
  681. if len(args) != 1:
  682. raise InterpreterException('compiles method takes exactly one argument.')
  683. check_stringlist(args)
  684. code = args[0]
  685. testname = kwargs.get('name', '')
  686. if not isinstance(testname, str):
  687. raise InterpreterException('Testname argument must be a string.')
  688. extra_args = self.determine_args(kwargs)
  689. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  690. result = self.compiler.compiles(code, self.environment, extra_args, deps)
  691. if len(testname) > 0:
  692. if result:
  693. h = mlog.green('YES')
  694. else:
  695. h = mlog.red('NO')
  696. mlog.log('Checking if "', mlog.bold(testname), '" compiles : ', h, sep='')
  697. return result
  698. def links_method(self, args, kwargs):
  699. if len(args) != 1:
  700. raise InterpreterException('links method takes exactly one argument.')
  701. check_stringlist(args)
  702. code = args[0]
  703. testname = kwargs.get('name', '')
  704. if not isinstance(testname, str):
  705. raise InterpreterException('Testname argument must be a string.')
  706. extra_args = self.determine_args(kwargs)
  707. deps = self.determine_dependencies(kwargs)
  708. result = self.compiler.links(code, self.environment, extra_args, deps)
  709. if len(testname) > 0:
  710. if result:
  711. h = mlog.green('YES')
  712. else:
  713. h = mlog.red('NO')
  714. mlog.log('Checking if "', mlog.bold(testname), '" links : ', h, sep='')
  715. return result
  716. def has_header_method(self, args, kwargs):
  717. if len(args) != 1:
  718. raise InterpreterException('has_header method takes exactly one argument.')
  719. check_stringlist(args)
  720. string = args[0]
  721. extra_args = self.determine_args(kwargs)
  722. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  723. haz = self.compiler.has_header(string, self.environment, extra_args, deps)
  724. if haz:
  725. h = mlog.green('YES')
  726. else:
  727. h = mlog.red('NO')
  728. mlog.log('Has header "%s":' % string, h)
  729. return haz
  730. def has_header_symbol_method(self, args, kwargs):
  731. if len(args) != 2:
  732. raise InterpreterException('has_header_symbol method takes exactly two arguments.')
  733. check_stringlist(args)
  734. hname = args[0]
  735. symbol = args[1]
  736. prefix = kwargs.get('prefix', '')
  737. if not isinstance(prefix, str):
  738. raise InterpreterException('Prefix argument of has_function must be a string.')
  739. extra_args = self.determine_args(kwargs)
  740. deps = self.determine_dependencies(kwargs, allowed_dep_types=(dependencies.Dependency,))
  741. haz = self.compiler.has_header_symbol(hname, symbol, prefix, self.environment, extra_args, deps)
  742. if haz:
  743. h = mlog.green('YES')
  744. else:
  745. h = mlog.red('NO')
  746. mlog.log('Header <{0}> has symbol "{1}":'.format(hname, symbol), h)
  747. return haz
  748. def find_library_method(self, args, kwargs):
  749. # TODO add dependencies support?
  750. if len(args) != 1:
  751. raise InterpreterException('find_library method takes one argument.')
  752. libname = args[0]
  753. if not isinstance(libname, str):
  754. raise InterpreterException('Library name not a string.')
  755. required = kwargs.get('required', True)
  756. if not isinstance(required, bool):
  757. raise InterpreterException('required must be boolean.')
  758. search_dirs = mesonlib.stringlistify(kwargs.get('dirs', []))
  759. for i in search_dirs:
  760. if not os.path.isabs(i):
  761. raise InvalidCode('Search directory %s is not an absolute path.' % i)
  762. linkargs = self.compiler.find_library(libname, self.environment, search_dirs)
  763. if required and linkargs is None:
  764. raise InterpreterException('Library {} not found'.format(libname))
  765. lib = dependencies.ExternalLibrary(libname, linkargs)
  766. return ExternalLibraryHolder(lib)
  767. def has_argument_method(self, args, kwargs):
  768. args = mesonlib.stringlistify(args)
  769. if len(args) != 1:
  770. raise InterpreterException('Has_arg takes exactly one argument.')
  771. result = self.compiler.has_argument(args[0], self.environment)
  772. if result:
  773. h = mlog.green('YES')
  774. else:
  775. h = mlog.red('NO')
  776. mlog.log('Compiler for {} supports argument {}:'.format(self.compiler.language, args[0]), h)
  777. return result
  778. def first_supported_argument_method(self, args, kwargs):
  779. for i in mesonlib.stringlistify(args):
  780. if self.compiler.has_argument(i, self.environment):
  781. mlog.log('First supported argument:', mlog.bold(i))
  782. return [i]
  783. mlog.log('First supported argument:', mlog.red('None'))
  784. return []
  785. class ModuleState:
  786. pass
  787. class ModuleHolder(InterpreterObject):
  788. def __init__(self, modname, module, interpreter):
  789. InterpreterObject.__init__(self)
  790. self.modname = modname
  791. self.held_object = module
  792. self.interpreter = interpreter
  793. def method_call(self, method_name, args, kwargs):
  794. try:
  795. fn = getattr(self.held_object, method_name)
  796. except AttributeError:
  797. raise InvalidArguments('Module %s does not have method %s.' % (self.modname, method_name))
  798. state = ModuleState()
  799. state.build_to_src = os.path.relpath(self.interpreter.environment.get_source_dir(),
  800. self.interpreter.environment.get_build_dir())
  801. state.subdir = self.interpreter.subdir
  802. state.environment = self.interpreter.environment
  803. state.project_name = self.interpreter.build.project_name
  804. state.project_version = self.interpreter.build.dep_manifest[self.interpreter.active_projectname]
  805. state.compilers = self.interpreter.build.compilers
  806. state.targets = self.interpreter.build.targets
  807. state.headers = self.interpreter.build.get_headers()
  808. state.man = self.interpreter.build.get_man()
  809. state.global_args = self.interpreter.build.global_args
  810. value = fn(state, args, kwargs)
  811. return self.interpreter.module_method_callback(value)
  812. class MesonMain(InterpreterObject):
  813. def __init__(self, build, interpreter):
  814. InterpreterObject.__init__(self)
  815. self.build = build
  816. self.interpreter = interpreter
  817. self.methods.update({'get_compiler': self.get_compiler_method,
  818. 'is_cross_build' : self.is_cross_build_method,
  819. 'has_exe_wrapper' : self.has_exe_wrapper_method,
  820. 'is_unity' : self.is_unity_method,
  821. 'is_subproject' : self.is_subproject_method,
  822. 'current_source_dir' : self.current_source_dir_method,
  823. 'current_build_dir' : self.current_build_dir_method,
  824. 'source_root' : self.source_root_method,
  825. 'build_root' : self.build_root_method,
  826. 'add_install_script' : self.add_install_script_method,
  827. 'add_postconf_script' : self.add_postconf_script_method,
  828. 'install_dependency_manifest': self.install_dependency_manifest_method,
  829. 'project_version': self.project_version_method,
  830. 'version': self.version_method,
  831. 'project_name' : self.project_name_method,
  832. 'get_cross_property': self.get_cross_property_method,
  833. })
  834. def add_install_script_method(self, args, kwargs):
  835. if len(args) != 1:
  836. raise InterpreterException('Set_install_script takes exactly one argument.')
  837. check_stringlist(args)
  838. scriptbase = args[0]
  839. scriptfile = os.path.join(self.interpreter.environment.source_dir,
  840. self.interpreter.subdir, scriptbase)
  841. if not os.path.isfile(scriptfile):
  842. raise InterpreterException('Can not find install script %s.' % scriptbase)
  843. self.build.install_scripts.append(build.InstallScript([scriptfile]))
  844. def add_postconf_script_method(self, args, kwargs):
  845. if len(args) < 1:
  846. raise InterpreterException('Not enough arguments')
  847. check_stringlist(args, 'add_postconf_script arguments must be strings.')
  848. scriptbase = args[0]
  849. search_dir = os.path.join(self.interpreter.environment.source_dir,
  850. self.interpreter.subdir)
  851. exe = dependencies.ExternalProgram(scriptbase, search_dir=search_dir)
  852. extras = args[1:]
  853. self.build.postconf_scripts.append({'exe': exe, 'args': extras})
  854. def current_source_dir_method(self, args, kwargs):
  855. src = self.interpreter.environment.source_dir
  856. sub = self.interpreter.subdir
  857. if sub == '':
  858. return src
  859. return os.path.join(src, sub)
  860. def current_build_dir_method(self, args, kwargs):
  861. src = self.interpreter.environment.build_dir
  862. sub = self.interpreter.subdir
  863. if sub == '':
  864. return src
  865. return os.path.join(src, sub)
  866. def source_root_method(self, args, kwargs):
  867. return self.interpreter.environment.source_dir
  868. def build_root_method(self, args, kwargs):
  869. return self.interpreter.environment.build_dir
  870. def has_exe_wrapper_method(self, args, kwargs):
  871. if self.is_cross_build_method(None, None) and \
  872. 'binaries' in self.build.environment.cross_info.config and \
  873. self.build.environment.cross_info.need_exe_wrapper():
  874. exe_wrap = self.build.environment.cross_info.config['binaries'].get('exe_wrapper', None)
  875. if exe_wrap is None:
  876. return False
  877. # We return True when exe_wrap is defined, when it's not needed, and
  878. # when we're compiling natively. The last two are semantically confusing.
  879. # Need to revisit this.
  880. return True
  881. def is_cross_build_method(self, args, kwargs):
  882. return self.build.environment.is_cross_build()
  883. def get_compiler_method(self, args, kwargs):
  884. if len(args) != 1:
  885. raise InterpreterException('get_compiler_method must have one and only one argument.')
  886. cname = args[0]
  887. native = kwargs.get('native', None)
  888. if native is None:
  889. if self.build.environment.is_cross_build():
  890. native = False
  891. else:
  892. native = True
  893. if not isinstance(native, bool):
  894. raise InterpreterException('Type of "native" must be a boolean.')
  895. if native:
  896. clist = self.build.compilers
  897. else:
  898. clist = self.build.cross_compilers
  899. for c in clist:
  900. if c.get_language() == cname:
  901. return CompilerHolder(c, self.build.environment)
  902. raise InterpreterException('Tried to access compiler for unspecified language "%s".' % cname)
  903. def is_unity_method(self, args, kwargs):
  904. return self.build.environment.coredata.get_builtin_option('unity')
  905. def is_subproject_method(self, args, kwargs):
  906. return self.interpreter.is_subproject()
  907. def install_dependency_manifest_method(self, args, kwargs):
  908. if len(args) != 1:
  909. raise InterpreterException('Must specify manifest install file name')
  910. if not isinstance(args[0], str):
  911. raise InterpreterException('Argument must be a string.')
  912. self.build.dep_manifest_name = args[0]
  913. def project_version_method(self, args, kwargs):
  914. return self.build.dep_manifest[self.interpreter.active_projectname]['version']
  915. def version_method(self, args, kwargs):
  916. return coredata.version
  917. def project_name_method(self, args, kwargs):
  918. return self.interpreter.active_projectname
  919. def get_cross_property_method(self, args, kwargs):
  920. if len(args) < 1 or len(args) > 2:
  921. raise InterpreterException('Must have one or two arguments.')
  922. propname = args[0]
  923. if not isinstance(propname, str):
  924. raise InterpreterException('Property name must be string.')
  925. try:
  926. props = self.interpreter.environment.cross_info.get_properties()
  927. return props[propname]
  928. except Exception:
  929. if len(args) == 2:
  930. return args[1]
  931. raise InterpreterException('Unknown cross property: %s.' % propname)
  932. class Interpreter():
  933. def __init__(self, build, backend, subproject='', subdir='', subproject_dir='subprojects'):
  934. self.build = build
  935. self.environment = build.environment
  936. self.coredata = self.environment.get_coredata()
  937. self.backend = backend
  938. self.subproject = subproject
  939. self.subdir = subdir
  940. self.source_root = build.environment.get_source_dir()
  941. self.subproject_dir = subproject_dir
  942. option_file = os.path.join(self.source_root, self.subdir, 'meson_options.txt')
  943. if os.path.exists(option_file):
  944. oi = optinterpreter.OptionInterpreter(self.subproject, \
  945. self.build.environment.cmd_line_options.projectoptions)
  946. oi.process(option_file)
  947. self.build.environment.merge_options(oi.options)
  948. mesonfile = os.path.join(self.source_root, self.subdir, environment.build_filename)
  949. if not os.path.isfile(mesonfile):
  950. raise InvalidArguments('Missing Meson file in %s' % mesonfile)
  951. with open(mesonfile, encoding='utf8') as mf:
  952. code = mf.read()
  953. if len(code.strip()) == 0:
  954. raise InvalidCode('Builder file is empty.')
  955. assert(isinstance(code, str))
  956. try:
  957. self.ast = mparser.Parser(code).parse()
  958. except mesonlib.MesonException as me:
  959. me.file = environment.build_filename
  960. raise me
  961. self.sanity_check_ast()
  962. self.variables = {}
  963. self.builtin = {}
  964. self.generators = []
  965. self.visited_subdirs = {}
  966. self.global_args_frozen = False
  967. self.subprojects = {}
  968. self.subproject_stack = []
  969. self.build_func_dict()
  970. self.parse_project()
  971. self.builtin['build_machine'] = BuildMachine(self.coredata.compilers)
  972. if not self.build.environment.is_cross_build():
  973. self.builtin['host_machine'] = self.builtin['build_machine']
  974. self.builtin['target_machine'] = self.builtin['build_machine']
  975. else:
  976. cross_info = self.build.environment.cross_info
  977. if cross_info.has_host():
  978. self.builtin['host_machine'] = CrossMachineInfo(cross_info.config['host_machine'])
  979. else:
  980. self.builtin['host_machine'] = self.builtin['build_machine']
  981. if cross_info.has_target():
  982. self.builtin['target_machine'] = CrossMachineInfo(cross_info.config['target_machine'])
  983. else:
  984. self.builtin['target_machine'] = self.builtin['host_machine']
  985. self.builtin['meson'] = MesonMain(build, self)
  986. self.build_def_files = [os.path.join(self.subdir, environment.build_filename)]
  987. def build_func_dict(self):
  988. self.funcs = {'project' : self.func_project,
  989. 'message' : self.func_message,
  990. 'error' : self.func_error,
  991. 'executable': self.func_executable,
  992. 'dependency' : self.func_dependency,
  993. 'static_library' : self.func_static_lib,
  994. 'shared_library' : self.func_shared_lib,
  995. 'library' : self.func_library,
  996. 'jar' : self.func_jar,
  997. 'build_target': self.func_build_target,
  998. 'custom_target' : self.func_custom_target,
  999. 'run_target' : self.func_run_target,
  1000. 'generator' : self.func_generator,
  1001. 'test' : self.func_test,
  1002. 'benchmark' : self.func_benchmark,
  1003. 'install_headers' : self.func_install_headers,
  1004. 'install_man' : self.func_install_man,
  1005. 'subdir' : self.func_subdir,
  1006. 'install_data' : self.func_install_data,
  1007. 'install_subdir' : self.func_install_subdir,
  1008. 'configure_file' : self.func_configure_file,
  1009. 'include_directories' : self.func_include_directories,
  1010. 'add_global_arguments' : self.func_add_global_arguments,
  1011. 'add_global_link_arguments' : self.func_add_global_link_arguments,
  1012. 'add_languages' : self.func_add_languages,
  1013. 'find_program' : self.func_find_program,
  1014. 'find_library' : self.func_find_library,
  1015. 'configuration_data' : self.func_configuration_data,
  1016. 'run_command' : self.func_run_command,
  1017. 'gettext' : self.func_gettext,
  1018. 'option' : self.func_option,
  1019. 'get_option' : self.func_get_option,
  1020. 'subproject' : self.func_subproject,
  1021. 'vcs_tag' : self.func_vcs_tag,
  1022. 'set_variable' : self.func_set_variable,
  1023. 'is_variable' : self.func_is_variable,
  1024. 'get_variable' : self.func_get_variable,
  1025. 'import' : self.func_import,
  1026. 'files' : self.func_files,
  1027. 'declare_dependency': self.func_declare_dependency,
  1028. 'assert': self.func_assert,
  1029. 'environment' : self.func_environment,
  1030. }
  1031. def parse_project(self):
  1032. """
  1033. Parses project() and initializes languages, compilers etc. Do this
  1034. early because we need this before we parse the rest of the AST.
  1035. """
  1036. self.evaluate_codeblock(self.ast, end=1)
  1037. def module_method_callback(self, invalues):
  1038. unwrap_single = False
  1039. if invalues is None:
  1040. return
  1041. if not isinstance(invalues, list):
  1042. unwrap_single = True
  1043. invalues = [invalues]
  1044. outvalues = []
  1045. for v in invalues:
  1046. if isinstance(v, build.CustomTarget):
  1047. self.add_target(v.name, v)
  1048. outvalues.append(CustomTargetHolder(v, self))
  1049. elif isinstance(v, (int, str)):
  1050. outvalues.append(v)
  1051. elif isinstance(v, build.Executable):
  1052. self.add_target(v.name, v)
  1053. outvalues.append(ExecutableHolder(v))
  1054. elif isinstance(v, list):
  1055. outvalues.append(self.module_method_callback(v))
  1056. elif isinstance(v, build.GeneratedList):
  1057. outvalues.append(GeneratedListHolder(v))
  1058. elif isinstance(v, build.RunTarget):
  1059. self.add_target(v.name, v)
  1060. elif isinstance(v, build.InstallScript):
  1061. self.build.install_scripts.append(v)
  1062. elif isinstance(v, build.Data):
  1063. self.build.data.append(v)
  1064. else:
  1065. print(v)
  1066. raise InterpreterException('Module returned a value of unknown type.')
  1067. if len(outvalues) == 1 and unwrap_single:
  1068. return outvalues[0]
  1069. return outvalues
  1070. def get_build_def_files(self):
  1071. return self.build_def_files
  1072. def get_variables(self):
  1073. return self.variables
  1074. def sanity_check_ast(self):
  1075. if not isinstance(self.ast, mparser.CodeBlockNode):
  1076. raise InvalidCode('AST is of invalid type. Possibly a bug in the parser.')
  1077. if len(self.ast.lines) == 0:
  1078. raise InvalidCode('No statements in code.')
  1079. first = self.ast.lines[0]
  1080. if not isinstance(first, mparser.FunctionNode) or first.func_name != 'project':
  1081. raise InvalidCode('First statement must be a call to project')
  1082. args = self.reduce_arguments(first.args)[0]
  1083. if len(args) < 2:
  1084. raise InvalidArguments('Not enough arguments to project(). Needs at least the project name and one language')
  1085. def check_cross_stdlibs(self):
  1086. if self.build.environment.is_cross_build():
  1087. cross_info = self.build.environment.cross_info
  1088. for c in self.build.cross_compilers:
  1089. l = c.language
  1090. try:
  1091. di = mesonlib.stringlistify(cross_info.get_stdlib(l))
  1092. if len(di) != 2:
  1093. raise InterpreterException('Stdlib definition for %s should have exactly two elements.' \
  1094. % l)
  1095. projname, depname = di
  1096. subproj = self.do_subproject(projname, {})
  1097. self.build.cross_stdlibs[l] = subproj.get_variable_method([depname], {})
  1098. except KeyError as e:
  1099. pass
  1100. def run(self):
  1101. # Evaluate everything after the first line, which is project() because
  1102. # we already parsed that in self.parse_project()
  1103. self.evaluate_codeblock(self.ast, start=1)
  1104. mlog.log('Build targets in project:', mlog.bold(str(len(self.build.targets))))
  1105. def evaluate_codeblock(self, node, start=0, end=None):
  1106. if node is None:
  1107. return
  1108. if not isinstance(node, mparser.CodeBlockNode):
  1109. e = InvalidCode('Tried to execute a non-codeblock. Possibly a bug in the parser.')
  1110. e.lineno = node.lineno
  1111. e.colno = node.colno
  1112. raise e
  1113. statements = node.lines[start:end]
  1114. i = 0
  1115. while i < len(statements):
  1116. cur = statements[i]
  1117. try:
  1118. self.evaluate_statement(cur)
  1119. except Exception as e:
  1120. if not(hasattr(e, 'lineno')):
  1121. e.lineno = cur.lineno
  1122. e.colno = cur.colno
  1123. e.file = os.path.join(self.subdir, 'meson.build')
  1124. raise e
  1125. i += 1 # In THE FUTURE jump over blocks and stuff.
  1126. def get_variable(self, varname):
  1127. if varname in self.builtin:
  1128. return self.builtin[varname]
  1129. if varname in self.variables:
  1130. return self.variables[varname]
  1131. raise InvalidCode('Unknown variable "%s".' % varname)
  1132. def func_set_variable(self, node, args, kwargs):
  1133. if len(args) != 2:
  1134. raise InvalidCode('Set_variable takes two arguments.')
  1135. varname = args[0]
  1136. value = self.to_native(args[1])
  1137. self.set_variable(varname, value)
  1138. @noKwargs
  1139. def func_get_variable(self, node, args, kwargs):
  1140. if len(args)<1 or len(args)>2:
  1141. raise InvalidCode('Get_variable takes one or two arguments.')
  1142. varname = args[0]
  1143. if not isinstance(varname, str):
  1144. raise InterpreterException('First argument must be a string.')
  1145. try:
  1146. return self.variables[varname]
  1147. except KeyError:
  1148. pass
  1149. if len(args) == 2:
  1150. return args[1]
  1151. raise InterpreterException('Tried to get unknown variable "%s".' % varname)
  1152. @stringArgs
  1153. @noKwargs
  1154. def func_is_variable(self, node, args, kwargs):
  1155. if len(args) != 1:
  1156. raise InvalidCode('Is_variable takes two arguments.')
  1157. varname = args[0]
  1158. return varname in self.variables
  1159. @stringArgs
  1160. @noKwargs
  1161. def func_import(self, node, args, kwargs):
  1162. if len(args) != 1:
  1163. raise InvalidCode('Import takes one argument.')
  1164. modname = args[0]
  1165. if not modname in self.environment.coredata.modules:
  1166. module = importlib.import_module('mesonbuild.modules.' + modname).initialize()
  1167. self.environment.coredata.modules[modname] = module
  1168. return ModuleHolder(modname, self.environment.coredata.modules[modname], self)
  1169. @stringArgs
  1170. @noKwargs
  1171. def func_files(self, node, args, kwargs):
  1172. return [mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, fname) for fname in args]
  1173. @noPosargs
  1174. def func_declare_dependency(self, node, args, kwargs):
  1175. version = kwargs.get('version', self.project_version)
  1176. if not isinstance(version, str):
  1177. raise InterpreterException('Version must be a string.')
  1178. incs = kwargs.get('include_directories', [])
  1179. if not isinstance(incs, list):
  1180. incs = [incs]
  1181. libs = kwargs.get('link_with', [])
  1182. if not isinstance(libs, list):
  1183. libs = [libs]
  1184. sources = kwargs.get('sources', [])
  1185. if not isinstance(sources, list):
  1186. sources = [sources]
  1187. sources = self.source_strings_to_files(self.flatten(sources))
  1188. deps = kwargs.get('dependencies', [])
  1189. if not isinstance(deps, list):
  1190. deps = [deps]
  1191. compile_args = mesonlib.stringlistify(kwargs.get('compile_args', []))
  1192. link_args = mesonlib.stringlistify(kwargs.get('link_args', []))
  1193. final_deps = []
  1194. for d in deps:
  1195. try:
  1196. d = d.held_object
  1197. except Exception:
  1198. pass
  1199. if not isinstance(d, (dependencies.Dependency, dependencies.ExternalLibrary, dependencies.InternalDependency)):
  1200. raise InterpreterException('Dependencies must be external deps')
  1201. final_deps.append(d)
  1202. dep = dependencies.InternalDependency(version, incs, compile_args, link_args, libs, sources, final_deps)
  1203. return InternalDependencyHolder(dep)
  1204. @noKwargs
  1205. def func_assert(self, node, args, kwargs):
  1206. if len(args) != 2:
  1207. raise InterpreterException('Assert takes exactly two arguments')
  1208. value, message = args
  1209. if not isinstance(value, bool):
  1210. raise InterpreterException('Assert value not bool.')
  1211. if not isinstance(message, str):
  1212. raise InterpreterException('Assert message not a string.')
  1213. if not value:
  1214. raise InterpreterException('Assert failed: ' + message)
  1215. def set_variable(self, varname, variable):
  1216. if variable is None:
  1217. raise InvalidCode('Can not assign None to variable.')
  1218. if not isinstance(varname, str):
  1219. raise InvalidCode('First argument to set_variable must be a string.')
  1220. if not self.is_assignable(variable):
  1221. raise InvalidCode('Assigned value not of assignable type.')
  1222. if re.match('[_a-zA-Z][_0-9a-zA-Z]*$', varname) is None:
  1223. raise InvalidCode('Invalid variable name: ' + varname)
  1224. if varname in self.builtin:
  1225. raise InvalidCode('Tried to overwrite internal variable "%s"' % varname)
  1226. self.variables[varname] = variable
  1227. def evaluate_statement(self, cur):
  1228. if isinstance(cur, mparser.FunctionNode):
  1229. return self.function_call(cur)
  1230. elif isinstance(cur, mparser.AssignmentNode):
  1231. return self.assignment(cur)
  1232. elif isinstance(cur, mparser.MethodNode):
  1233. return self.method_call(cur)
  1234. elif isinstance(cur, mparser.StringNode):
  1235. return cur.value
  1236. elif isinstance(cur, mparser.BooleanNode):
  1237. return cur.value
  1238. elif isinstance(cur, mparser.IfClauseNode):
  1239. return self.evaluate_if(cur)
  1240. elif isinstance(cur, mparser.IdNode):
  1241. return self.get_variable(cur.value)
  1242. elif isinstance(cur, mparser.ComparisonNode):
  1243. return self.evaluate_comparison(cur)
  1244. elif isinstance(cur, mparser.ArrayNode):
  1245. return self.evaluate_arraystatement(cur)
  1246. elif isinstance(cur, mparser.NumberNode):
  1247. return cur.value
  1248. elif isinstance(cur, mparser.AndNode):
  1249. return self.evaluate_andstatement(cur)
  1250. elif isinstance(cur, mparser.OrNode):
  1251. return self.evaluate_orstatement(cur)
  1252. elif isinstance(cur, mparser.NotNode):
  1253. return self.evaluate_notstatement(cur)
  1254. elif isinstance(cur, mparser.UMinusNode):
  1255. return self.evaluate_uminusstatement(cur)
  1256. elif isinstance(cur, mparser.ArithmeticNode):
  1257. return self.evaluate_arithmeticstatement(cur)
  1258. elif isinstance(cur, mparser.ForeachClauseNode):
  1259. return self.evaluate_foreach(cur)
  1260. elif isinstance(cur, mparser.PlusAssignmentNode):
  1261. return self.evaluate_plusassign(cur)
  1262. elif isinstance(cur, mparser.IndexNode):
  1263. return self.evaluate_indexing(cur)
  1264. elif isinstance(cur, mparser.TernaryNode):
  1265. return self.evaluate_ternary(cur)
  1266. elif self.is_elementary_type(cur):
  1267. return cur
  1268. else:
  1269. raise InvalidCode("Unknown statement.")
  1270. def validate_arguments(self, args, argcount, arg_types):
  1271. if argcount is not None:
  1272. if argcount != len(args):
  1273. raise InvalidArguments('Expected %d arguments, got %d.' %
  1274. (argcount, len(args)))
  1275. for i in range(min(len(args), len(arg_types))):
  1276. wanted = arg_types[i]
  1277. actual = args[i]
  1278. if wanted != None:
  1279. if not isinstance(actual, wanted):
  1280. raise InvalidArguments('Incorrect argument type.')
  1281. def func_run_command(self, node, args, kwargs):
  1282. if len(args) < 1:
  1283. raise InterpreterException('Not enough arguments')
  1284. cmd = args[0]
  1285. cargs = args[1:]
  1286. if isinstance(cmd, ExternalProgramHolder):
  1287. cmd = cmd.get_command()
  1288. elif isinstance(cmd, str):
  1289. cmd = [cmd]
  1290. else:
  1291. raise InterpreterException('First argument is of incorrect type.')
  1292. expanded_args = []
  1293. for a in mesonlib.flatten(cargs):
  1294. if isinstance(a, str):
  1295. expanded_args.append(a)
  1296. elif isinstance(a, mesonlib.File):
  1297. if a.is_built:
  1298. raise InterpreterException('Can not use generated files in run_command.')
  1299. expanded_args.append(os.path.join(self.environment.get_source_dir(), str(a)))
  1300. else:
  1301. raise InterpreterException('Run_command arguments must be strings or the output of files().')
  1302. args = cmd + expanded_args
  1303. in_builddir = kwargs.get('in_builddir', False)
  1304. mlog.debug('Running command:', ' '.join(args))
  1305. if not isinstance(in_builddir, bool):
  1306. raise InterpreterException('in_builddir must be boolean.')
  1307. return RunProcess(args, self.environment.source_dir, self.environment.build_dir,
  1308. self.subdir, in_builddir)
  1309. @stringArgs
  1310. def func_gettext(self, nodes, args, kwargs):
  1311. raise InterpreterException('Gettext() function has been moved to module i18n. Import it and use i18n.gettext() instead')
  1312. def func_option(self, nodes, args, kwargs):
  1313. raise InterpreterException('Tried to call option() in build description file. All options must be in the option file.')
  1314. @stringArgs
  1315. def func_subproject(self, nodes, args, kwargs):
  1316. if len(args) != 1:
  1317. raise InterpreterException('Subproject takes exactly one argument')
  1318. dirname = args[0]
  1319. return self.do_subproject(dirname, kwargs)
  1320. def do_subproject(self, dirname, kwargs):
  1321. if self.subdir != '':
  1322. segs = os.path.split(self.subdir)
  1323. if len(segs) != 2 or segs[0] != self.subproject_dir:
  1324. raise InterpreterException('Subprojects must be defined at the root directory.')
  1325. if dirname in self.subproject_stack:
  1326. fullstack = self.subproject_stack + [dirname]
  1327. incpath = ' => '.join(fullstack)
  1328. raise InterpreterException('Recursive include of subprojects: %s.' % incpath)
  1329. if dirname in self.subprojects:
  1330. return self.subprojects[dirname]
  1331. r = wrap.Resolver(os.path.join(self.build.environment.get_source_dir(), self.subproject_dir))
  1332. resolved = r.resolve(dirname)
  1333. if resolved is None:
  1334. msg = 'Subproject directory {!r} does not exist and can not be downloaded.'
  1335. raise InterpreterException(msg.format(os.path.join(self.subproject_dir, dirname)))
  1336. subdir = os.path.join(self.subproject_dir, resolved)
  1337. os.makedirs(os.path.join(self.build.environment.get_build_dir(), subdir), exist_ok=True)
  1338. self.global_args_frozen = True
  1339. mlog.log('\nExecuting subproject ', mlog.bold(dirname), '.\n', sep='')
  1340. subi = Interpreter(self.build, self.backend, dirname, subdir, self.subproject_dir)
  1341. subi.subprojects = self.subprojects
  1342. subi.subproject_stack = self.subproject_stack + [dirname]
  1343. current_active = self.active_projectname
  1344. subi.run()
  1345. if 'version' in kwargs:
  1346. pv = subi.project_version
  1347. wanted = kwargs['version']
  1348. if pv == 'undefined' or not mesonlib.version_compare(pv, wanted):
  1349. raise InterpreterException('Subproject %s version is %s but %s required.' % (dirname, pv, wanted))
  1350. self.active_projectname = current_active
  1351. mlog.log('\nSubproject', mlog.bold(dirname), 'finished.')
  1352. self.build.subprojects[dirname] = True
  1353. self.subprojects.update(subi.subprojects)
  1354. self.subprojects[dirname] = SubprojectHolder(subi)
  1355. self.build_def_files += subi.build_def_files
  1356. return self.subprojects[dirname]
  1357. @stringArgs
  1358. @noKwargs
  1359. def func_get_option(self, nodes, args, kwargs):
  1360. if len(args) != 1:
  1361. raise InterpreterException('Argument required for get_option.')
  1362. optname = args[0]
  1363. try:
  1364. return self.environment.get_coredata().get_builtin_option(optname)
  1365. except RuntimeError:
  1366. pass
  1367. try:
  1368. return self.environment.coredata.compiler_options[optname].value
  1369. except KeyError:
  1370. pass
  1371. if not coredata.is_builtin_option(optname) and self.is_subproject():
  1372. optname = self.subproject + ':' + optname
  1373. try:
  1374. return self.environment.coredata.user_options[optname].value
  1375. except KeyError:
  1376. pass
  1377. if optname.endswith('_link_args'):
  1378. try:
  1379. lang = optname[:-10]
  1380. return self.coredata.external_link_args[lang]
  1381. except KeyError:
  1382. pass
  1383. if optname.endswith('_args'):
  1384. try:
  1385. lang = optname[:-5]
  1386. return self.coredata.external_args[lang]
  1387. except KeyError:
  1388. pass
  1389. raise InterpreterException('Tried to access unknown option "%s".' % optname)
  1390. @noKwargs
  1391. def func_configuration_data(self, node, args, kwargs):
  1392. if len(args) != 0:
  1393. raise InterpreterException('configuration_data takes no arguments')
  1394. return ConfigurationDataHolder()
  1395. def parse_default_options(self, default_options):
  1396. if not isinstance(default_options, list):
  1397. default_options = [default_options]
  1398. for option in default_options:
  1399. if not isinstance(option, str):
  1400. mlog.debug(option)
  1401. raise InterpreterException('Default options must be strings')
  1402. if '=' not in option:
  1403. raise InterpreterException('All default options must be of type key=value.')
  1404. key, value = option.split('=', 1)
  1405. if coredata.is_builtin_option(key):
  1406. if not self.environment.had_argument_for(key):
  1407. self.coredata.set_builtin_option(key, value)
  1408. # If this was set on the command line, do not override.
  1409. else:
  1410. newoptions = [option] + self.environment.cmd_line_options.projectoptions
  1411. self.environment.cmd_line_options.projectoptions = newoptions
  1412. @stringArgs
  1413. def func_project(self, node, args, kwargs):
  1414. if not self.is_subproject():
  1415. self.build.project_name = args[0]
  1416. if self.environment.first_invocation and 'default_options' in kwargs:
  1417. self.parse_default_options(kwargs['default_options'])
  1418. self.active_projectname = args[0]
  1419. self.project_version = kwargs.get('version', 'undefined')
  1420. proj_license = mesonlib.stringlistify(kwargs.get('license', 'unknown'))
  1421. self.build.dep_manifest[args[0]] = {'version': self.project_version,
  1422. 'license': proj_license}
  1423. if self.subproject in self.build.projects:
  1424. raise InvalidCode('Second call to project().')
  1425. if not self.is_subproject() and 'subproject_dir' in kwargs:
  1426. self.subproject_dir = kwargs['subproject_dir']
  1427. if 'meson_version' in kwargs:
  1428. cv = coredata.version
  1429. pv = kwargs['meson_version']
  1430. if not mesonlib.version_compare(cv, pv):
  1431. raise InterpreterException('Meson version is %s but project requires %s.' % (cv, pv))
  1432. self.build.projects[self.subproject] = args[0]
  1433. mlog.log('Project name: ', mlog.bold(args[0]), sep='')
  1434. self.add_languages(args[1:], True)
  1435. langs = self.coredata.compilers.keys()
  1436. if 'vala' in langs:
  1437. if not 'c' in langs:
  1438. raise InterpreterException('Compiling Vala requires C. Add C to your project languages and rerun Meson.')
  1439. if not self.is_subproject():
  1440. self.check_cross_stdlibs()
  1441. @stringArgs
  1442. def func_add_languages(self, node, args, kwargs):
  1443. return self.add_languages(args, kwargs.get('required', True))
  1444. @noKwargs
  1445. def func_message(self, node, args, kwargs):
  1446. # reduce arguments again to avoid flattening posargs
  1447. (posargs, _) = self.reduce_arguments(node.args)
  1448. if len(posargs) != 1:
  1449. raise InvalidArguments('Expected 1 argument, got %d' % len(posargs))
  1450. arg = posargs[0]
  1451. if isinstance(arg, list):
  1452. argstr = stringifyUserArguments(arg)
  1453. elif isinstance(arg, str):
  1454. argstr = arg
  1455. elif isinstance(arg, int):
  1456. argstr = str(arg)
  1457. else:
  1458. raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  1459. mlog.log(mlog.bold('Message:'), argstr)
  1460. @noKwargs
  1461. def func_error(self, node, args, kwargs):
  1462. self.validate_arguments(args, 1, [str])
  1463. raise InterpreterException('Error encountered: ' + args[0])
  1464. def detect_compilers(self, lang, need_cross_compiler):
  1465. cross_comp = None
  1466. if lang == 'c':
  1467. comp = self.environment.detect_c_compiler(False)
  1468. if need_cross_compiler:
  1469. cross_comp = self.environment.detect_c_compiler(True)
  1470. elif lang == 'cpp':
  1471. comp = self.environment.detect_cpp_compiler(False)
  1472. if need_cross_compiler:
  1473. cross_comp = self.environment.detect_cpp_compiler(True)
  1474. elif lang == 'objc':
  1475. comp = self.environment.detect_objc_compiler(False)
  1476. if need_cross_compiler:
  1477. cross_comp = self.environment.detect_objc_compiler(True)
  1478. elif lang == 'objcpp':
  1479. comp = self.environment.detect_objcpp_compiler(False)
  1480. if need_cross_compiler:
  1481. cross_comp = self.environment.detect_objcpp_compiler(True)
  1482. elif lang == 'java':
  1483. comp = self.environment.detect_java_compiler()
  1484. if need_cross_compiler:
  1485. cross_comp = comp # Java is platform independent.
  1486. elif lang == 'cs':
  1487. comp = self.environment.detect_cs_compiler()
  1488. if need_cross_compiler:
  1489. cross_comp = comp # C# is platform independent.
  1490. elif lang == 'vala':
  1491. comp = self.environment.detect_vala_compiler()
  1492. if need_cross_compiler:
  1493. cross_comp = comp # Vala is too (I think).
  1494. elif lang == 'd':
  1495. comp = self.environment.detect_d_compiler()
  1496. if need_cross_compiler:
  1497. cross_comp = comp # D as well (AFAIK).
  1498. elif lang == 'rust':
  1499. comp = self.environment.detect_rust_compiler()
  1500. if need_cross_compiler:
  1501. cross_comp = comp # FIXME, probably not correct.
  1502. elif lang == 'fortran':
  1503. comp = self.environment.detect_fortran_compiler(False)
  1504. if need_cross_compiler:
  1505. cross_comp = self.environment.detect_fortran_compiler(True)
  1506. elif lang == 'swift':
  1507. comp = self.environment.detect_swift_compiler()
  1508. if need_cross_compiler:
  1509. raise InterpreterException('Cross compilation with Swift is not working yet.')
  1510. # cross_comp = self.environment.detect_fortran_compiler(True)
  1511. else:
  1512. raise InvalidCode('Tried to use unknown language "%s".' % lang)
  1513. comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
  1514. self.coredata.compilers[lang] = comp
  1515. if cross_comp is not None:
  1516. cross_comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
  1517. self.coredata.cross_compilers[lang] = cross_comp
  1518. new_options = cross_comp.get_options()
  1519. else:
  1520. new_options = comp.get_options()
  1521. optprefix = lang + '_'
  1522. for i in new_options:
  1523. if not i.startswith(optprefix):
  1524. raise InterpreterException('Internal error, %s has incorrect prefix.' % i)
  1525. cmd_prefix = i + '='
  1526. for cmd_arg in self.environment.cmd_line_options.projectoptions:
  1527. if cmd_arg.startswith(cmd_prefix):
  1528. value = cmd_arg.split('=', 1)[1]
  1529. new_options[i].set_value(value)
  1530. new_options.update(self.coredata.compiler_options)
  1531. self.coredata.compiler_options = new_options
  1532. return (comp, cross_comp)
  1533. def add_languages(self, args, required):
  1534. success = True
  1535. need_cross_compiler = self.environment.is_cross_build() and self.environment.cross_info.need_cross_compiler()
  1536. for lang in args:
  1537. lang = lang.lower()
  1538. if lang in self.coredata.compilers:
  1539. comp = self.coredata.compilers[lang]
  1540. cross_comp = self.coredata.cross_compilers.get(lang, None)
  1541. else:
  1542. try:
  1543. (comp, cross_comp) = self.detect_compilers(lang, need_cross_compiler)
  1544. except Exception:
  1545. if not required:
  1546. mlog.log('Compiler for language', mlog.bold(lang), 'not found.')
  1547. success = False
  1548. continue
  1549. else:
  1550. raise
  1551. mlog.log('Native %s compiler: ' % lang, mlog.bold(' '.join(comp.get_exelist())), ' (%s %s)' % (comp.id, comp.version), sep='')
  1552. compiler_is_linker = False
  1553. if hasattr(comp, 'get_linker_exelist'):
  1554. compiler_is_linker = (comp.get_exelist() == comp.get_linker_exelist())
  1555. if not comp.get_language() in self.coredata.external_args:
  1556. (ext_compile_args, ext_link_args) = environment.get_args_from_envvars(comp.get_language(), compiler_is_linker)
  1557. self.coredata.external_args[comp.get_language()] = ext_compile_args
  1558. self.coredata.external_link_args[comp.get_language()] = ext_link_args
  1559. self.build.add_compiler(comp)
  1560. if need_cross_compiler:
  1561. mlog.log('Cross %s compiler: ' % lang, mlog.bold(' '.join(cross_comp.get_exelist())), ' (%s %s)' % (cross_comp.id, cross_comp.version), sep='')
  1562. self.build.add_cross_compiler(cross_comp)
  1563. if self.environment.is_cross_build() and not need_cross_compiler:
  1564. self.build.add_cross_compiler(comp)
  1565. self.add_base_options(comp)
  1566. return success
  1567. def add_base_options(self, compiler):
  1568. proj_opt = self.environment.cmd_line_options.projectoptions
  1569. for optname in compiler.base_options:
  1570. if optname in self.coredata.base_options:
  1571. continue
  1572. oobj = compilers.base_options[optname]
  1573. for po in proj_opt:
  1574. if po.startswith(optname + '='):
  1575. oobj.set_value(po.split('=', 1)[1])
  1576. break
  1577. self.coredata.base_options[optname] = oobj
  1578. def func_find_program(self, node, args, kwargs):
  1579. self.validate_arguments(args, 1, [str])
  1580. required = kwargs.get('required', True)
  1581. if not isinstance(required, bool):
  1582. raise InvalidArguments('"required" argument must be a boolean.')
  1583. exename = args[0]
  1584. # Search for scripts relative to current subdir.
  1585. # Do not cache found programs because find_program('foobar')
  1586. # might give different results when run from different source dirs.
  1587. search_dir = os.path.join(self.environment.get_source_dir(), self.subdir)
  1588. extprog = dependencies.ExternalProgram(exename, search_dir=search_dir)
  1589. progobj = ExternalProgramHolder(extprog)
  1590. if required and not progobj.found():
  1591. raise InvalidArguments('Program "%s" not found.' % exename)
  1592. return progobj
  1593. def func_find_library(self, node, args, kwargs):
  1594. mlog.log(mlog.red('DEPRECATION:'), 'find_library() is removed, use the corresponding method in compiler object instead.')
  1595. def func_dependency(self, node, args, kwargs):
  1596. self.validate_arguments(args, 1, [str])
  1597. name = args[0]
  1598. identifier = dependencies.get_dep_identifier(name, kwargs)
  1599. # Check if we've already searched for and found this dep
  1600. cached_dep = None
  1601. if identifier in self.coredata.deps:
  1602. cached_dep = self.coredata.deps[identifier]
  1603. if 'version' in kwargs:
  1604. wanted = kwargs['version']
  1605. found = cached_dep.get_version()
  1606. if not cached_dep.found() or not mesonlib.version_compare(found, wanted):
  1607. # Cached dep has the wrong version. Check if an external
  1608. # dependency or a fallback dependency provides it.
  1609. cached_dep = None
  1610. if cached_dep:
  1611. dep = cached_dep
  1612. else:
  1613. # We need to actually search for this dep
  1614. exception = None
  1615. dep = None
  1616. try:
  1617. dep = dependencies.find_external_dependency(name, self.environment, kwargs)
  1618. except dependencies.DependencyException as e:
  1619. exception = e
  1620. pass
  1621. if not dep or not dep.found():
  1622. if 'fallback' in kwargs:
  1623. fallback_dep = self.dependency_fallback(name, kwargs)
  1624. if fallback_dep:
  1625. return fallback_dep
  1626. if not dep:
  1627. raise exception
  1628. self.coredata.deps[identifier] = dep
  1629. return DependencyHolder(dep)
  1630. def dependency_fallback(self, name, kwargs):
  1631. fbinfo = kwargs['fallback']
  1632. check_stringlist(fbinfo)
  1633. if len(fbinfo) != 2:
  1634. raise InterpreterException('Fallback info must have exactly two items.')
  1635. dirname, varname = fbinfo
  1636. try:
  1637. self.do_subproject(dirname, {})
  1638. except:
  1639. mlog.log('Also couldn\'t find a fallback subproject in',
  1640. mlog.bold(os.path.join(self.subproject_dir, dirname)),
  1641. 'for the dependency', mlog.bold(name))
  1642. if kwargs.get('required', True):
  1643. raise
  1644. else:
  1645. return None
  1646. try:
  1647. dep = self.subprojects[dirname].get_variable_method([varname], {})
  1648. except KeyError:
  1649. raise InterpreterException('Fallback variable {!r} in the subproject {!r} does not exist'.format(varname, dirname))
  1650. if not isinstance(dep, (DependencyHolder, InternalDependencyHolder)):
  1651. raise InterpreterException('Fallback variable {!r} in the subproject {!r} is not a dependency object.'.format(varname, dirname))
  1652. # Check if the version of the declared dependency matches what we want
  1653. if 'version' in kwargs:
  1654. wanted = kwargs['version']
  1655. found = dep.version_method([], {})
  1656. if found == 'undefined' or not mesonlib.version_compare(found, wanted):
  1657. m = 'Subproject "{0}" dependency "{1}" version is "{2}" but "{3}" is required.'
  1658. raise InterpreterException(m.format(dirname, varname, found, wanted))
  1659. mlog.log('Found a', mlog.green('fallback'), 'subproject',
  1660. mlog.bold(os.path.join(self.subproject_dir, dirname)), 'for',
  1661. mlog.bold(name))
  1662. return dep
  1663. def func_executable(self, node, args, kwargs):
  1664. return self.build_target(node, args, kwargs, ExecutableHolder)
  1665. def func_static_lib(self, node, args, kwargs):
  1666. return self.build_target(node, args, kwargs, StaticLibraryHolder)
  1667. def func_shared_lib(self, node, args, kwargs):
  1668. return self.build_target(node, args, kwargs, SharedLibraryHolder)
  1669. def func_library(self, node, args, kwargs):
  1670. if self.coredata.get_builtin_option('default_library') == 'shared':
  1671. return self.func_shared_lib(node, args, kwargs)
  1672. return self.func_static_lib(node, args, kwargs)
  1673. def func_jar(self, node, args, kwargs):
  1674. return self.build_target(node, args, kwargs, JarHolder)
  1675. def func_build_target(self, node, args, kwargs):
  1676. if 'target_type' not in kwargs:
  1677. raise InterpreterException('Missing target_type keyword argument')
  1678. target_type = kwargs.pop('target_type')
  1679. if target_type == 'executable':
  1680. return self.func_executable(node, args, kwargs)
  1681. elif target_type == 'shared_library':
  1682. return self.func_shared_lib(node, args, kwargs)
  1683. elif target_type == 'static_library':
  1684. return self.func_static_lib(node, args, kwargs)
  1685. elif target_type == 'library':
  1686. return self.func_library(node, args, kwargs)
  1687. elif target_type == 'jar':
  1688. return self.func_jar(node, args, kwargs)
  1689. else:
  1690. raise InterpreterException('Unknown target_type.')
  1691. def func_vcs_tag(self, node, args, kwargs):
  1692. fallback = kwargs.pop('fallback', None)
  1693. if not isinstance(fallback, str):
  1694. raise InterpreterException('Keyword argument fallback must exist and be a string.')
  1695. replace_string = kwargs.pop('replace_string', '@VCS_TAG@')
  1696. regex_selector = '(.*)' # default regex selector for custom command: use complete output
  1697. vcs_cmd = kwargs.get('command', None)
  1698. if vcs_cmd and not isinstance(vcs_cmd, list):
  1699. vcs_cmd = [vcs_cmd]
  1700. source_dir = os.path.normpath(os.path.join(self.environment.get_source_dir(), self.subdir))
  1701. if vcs_cmd:
  1702. # Is the command an executable in path or maybe a script in the source tree?
  1703. vcs_cmd[0] = shutil.which(vcs_cmd[0]) or os.path.join(source_dir, vcs_cmd[0])
  1704. else:
  1705. vcs = mesonlib.detect_vcs(source_dir)
  1706. if vcs:
  1707. mlog.log('Found %s repository at %s' % (vcs['name'], vcs['wc_dir']))
  1708. vcs_cmd = vcs['get_rev'].split()
  1709. regex_selector = vcs['rev_regex']
  1710. else:
  1711. vcs_cmd = [' '] # executing this cmd will fail in vcstagger.py and force to use the fallback string
  1712. # vcstagger.py parameters: infile, outfile, fallback, source_dir, replace_string, regex_selector, command...
  1713. kwargs['command'] = [sys.executable,
  1714. self.environment.get_build_command(),
  1715. '--internal',
  1716. 'vcstagger',
  1717. '@INPUT0@',
  1718. '@OUTPUT0@',
  1719. fallback,
  1720. source_dir,
  1721. replace_string,
  1722. regex_selector] + vcs_cmd
  1723. kwargs.setdefault('build_always', True)
  1724. return self.func_custom_target(node, [kwargs['output']], kwargs)
  1725. @stringArgs
  1726. def func_custom_target(self, node, args, kwargs):
  1727. if len(args) != 1:
  1728. raise InterpreterException('Incorrect number of arguments')
  1729. name = args[0]
  1730. tg = CustomTargetHolder(build.CustomTarget(name, self.subdir, kwargs), self)
  1731. self.add_target(name, tg.held_object)
  1732. return tg
  1733. def func_run_target(self, node, args, kwargs):
  1734. global run_depr_printed
  1735. if len(args) > 1:
  1736. if not run_depr_printed:
  1737. mlog.log(mlog.red('DEPRECATION'), 'positional version of run_target is deprecated, use the keyword version instead.')
  1738. run_depr_printed = True
  1739. if 'command' in kwargs:
  1740. raise InterpreterException('Can not have command both in positional and keyword arguments.')
  1741. all_args = args[1:]
  1742. deps = []
  1743. elif len(args) == 1:
  1744. if not 'command' in kwargs:
  1745. raise InterpreterException('Missing "command" keyword argument')
  1746. all_args = kwargs['command']
  1747. if not isinstance(all_args, list):
  1748. all_args = [all_args]
  1749. deps = kwargs.get('depends', [])
  1750. if not isinstance(deps, list):
  1751. deps = [deps]
  1752. else:
  1753. raise InterpreterException('Run_target needs at least one positional argument.')
  1754. cleaned_args = []
  1755. for i in mesonlib.flatten(all_args):
  1756. try:
  1757. i = i.held_object
  1758. except AttributeError:
  1759. pass
  1760. if not isinstance(i, (str, build.BuildTarget, build.CustomTarget, dependencies.ExternalProgram, mesonlib.File)):
  1761. mlog.debug('Wrong type:', str(i))
  1762. raise InterpreterException('Invalid argument to run_target.')
  1763. cleaned_args.append(i)
  1764. name = args[0]
  1765. if not isinstance(name, str):
  1766. raise InterpreterException('First argument must be a string.')
  1767. cleaned_deps = []
  1768. for d in deps:
  1769. try:
  1770. d = d.held_object
  1771. except AttributeError:
  1772. pass
  1773. if not isinstance(d, (build.BuildTarget, build.CustomTarget)):
  1774. raise InterpreterException('Depends items must be build targets.')
  1775. cleaned_deps.append(d)
  1776. command = cleaned_args[0]
  1777. cmd_args = cleaned_args[1:]
  1778. tg = RunTargetHolder(name, command, cmd_args, cleaned_deps, self.subdir)
  1779. self.add_target(name, tg.held_object)
  1780. return tg
  1781. def func_generator(self, node, args, kwargs):
  1782. gen = GeneratorHolder(self, args, kwargs)
  1783. self.generators.append(gen)
  1784. return gen
  1785. def func_benchmark(self, node, args, kwargs):
  1786. self.add_test(node, args, kwargs, False)
  1787. def func_test(self, node, args, kwargs):
  1788. self.add_test(node, args, kwargs, True)
  1789. def add_test(self, node, args, kwargs, is_base_test):
  1790. if len(args) != 2:
  1791. raise InterpreterException('Incorrect number of arguments')
  1792. if not isinstance(args[0], str):
  1793. raise InterpreterException('First argument of test must be a string.')
  1794. if not isinstance(args[1], (ExecutableHolder, JarHolder, ExternalProgramHolder)):
  1795. raise InterpreterException('Second argument must be executable.')
  1796. par = kwargs.get('is_parallel', True)
  1797. if not isinstance(par, bool):
  1798. raise InterpreterException('Keyword argument is_parallel must be a boolean.')
  1799. cmd_args = kwargs.get('args', [])
  1800. if not isinstance(cmd_args, list):
  1801. cmd_args = [cmd_args]
  1802. for i in cmd_args:
  1803. if not isinstance(i, (str, mesonlib.File)):
  1804. raise InterpreterException('Command line arguments must be strings')
  1805. envlist = kwargs.get('env', [])
  1806. if isinstance(envlist, EnvironmentVariablesHolder):
  1807. env = envlist.held_object
  1808. else:
  1809. if not isinstance(envlist, list):
  1810. envlist = [envlist]
  1811. env = {}
  1812. for e in envlist:
  1813. if '=' not in e:
  1814. raise InterpreterException('Env var definition must be of type key=val.')
  1815. (k, val) = e.split('=', 1)
  1816. k = k.strip()
  1817. val = val.strip()
  1818. if ' ' in k:
  1819. raise InterpreterException('Env var key must not have spaces in it.')
  1820. env[k] = val
  1821. valgrind_args = kwargs.get('valgrind_args', [])
  1822. if not isinstance(valgrind_args, list):
  1823. valgrind_args = [valgrind_args]
  1824. for a in valgrind_args:
  1825. if not isinstance(a, str):
  1826. raise InterpreterException('Valgrind_arg not a string.')
  1827. should_fail = kwargs.get('should_fail', False)
  1828. if not isinstance(should_fail, bool):
  1829. raise InterpreterException('Keyword argument should_fail must be a boolean.')
  1830. timeout = kwargs.get('timeout', 30)
  1831. if 'workdir' in kwargs:
  1832. workdir = kwargs['workdir']
  1833. if not isinstance(workdir, str):
  1834. raise InterpreterException('Workdir keyword argument must be a string.')
  1835. if not os.path.isabs(workdir):
  1836. raise InterpreterException('Workdir keyword argument must be an absolute path.')
  1837. else:
  1838. workdir = None
  1839. if not isinstance(timeout, int):
  1840. raise InterpreterException('Timeout must be an integer.')
  1841. suite = mesonlib.stringlistify(kwargs.get('suite', ''))
  1842. if self.is_subproject():
  1843. newsuite = []
  1844. for s in suite:
  1845. if len(s) > 0:
  1846. s = '.' + s
  1847. newsuite.append(self.subproject.replace(' ', '_').replace('.', '_') + s)
  1848. suite = newsuite
  1849. t = Test(args[0], suite, args[1].held_object, par, cmd_args, env, should_fail, valgrind_args, timeout, workdir)
  1850. if is_base_test:
  1851. self.build.tests.append(t)
  1852. mlog.debug('Adding test "', mlog.bold(args[0]), '".', sep='')
  1853. else:
  1854. self.build.benchmarks.append(t)
  1855. mlog.debug('Adding benchmark "', mlog.bold(args[0]), '".', sep='')
  1856. @stringArgs
  1857. def func_install_headers(self, node, args, kwargs):
  1858. h = Headers(self.subdir, args, kwargs)
  1859. self.build.headers.append(h)
  1860. return h
  1861. @stringArgs
  1862. def func_install_man(self, node, args, kwargs):
  1863. m = Man(self.subdir, args, kwargs)
  1864. self.build.man.append(m)
  1865. return m
  1866. @noKwargs
  1867. def func_subdir(self, node, args, kwargs):
  1868. self.validate_arguments(args, 1, [str])
  1869. if '..' in args[0]:
  1870. raise InvalidArguments('Subdir contains ..')
  1871. if self.subdir == '' and args[0] == self.subproject_dir:
  1872. raise InvalidArguments('Must not go into subprojects dir with subdir(), use subproject() instead.')
  1873. prev_subdir = self.subdir
  1874. subdir = os.path.join(prev_subdir, args[0])
  1875. if subdir in self.visited_subdirs:
  1876. raise InvalidArguments('Tried to enter directory "%s", which has already been visited.'\
  1877. % subdir)
  1878. self.visited_subdirs[subdir] = True
  1879. self.subdir = subdir
  1880. try:
  1881. os.makedirs(os.path.join(self.environment.build_dir, subdir))
  1882. except FileExistsError:
  1883. pass
  1884. buildfilename = os.path.join(self.subdir, environment.build_filename)
  1885. self.build_def_files.append(buildfilename)
  1886. absname = os.path.join(self.environment.get_source_dir(), buildfilename)
  1887. if not os.path.isfile(absname):
  1888. self.subdir = prev_subdir
  1889. raise InterpreterException('Nonexistant build def file %s.' % buildfilename)
  1890. with open(absname, encoding='utf8') as f:
  1891. code = f.read()
  1892. assert(isinstance(code, str))
  1893. try:
  1894. codeblock = mparser.Parser(code).parse()
  1895. except mesonlib.MesonException as me:
  1896. me.file = buildfilename
  1897. raise me
  1898. self.evaluate_codeblock(codeblock)
  1899. self.subdir = prev_subdir
  1900. @stringArgs
  1901. def func_install_data(self, node, args, kwargs):
  1902. data = DataHolder(True, self.subdir, args, kwargs)
  1903. self.build.data.append(data.held_object)
  1904. return data
  1905. @stringArgs
  1906. def func_install_subdir(self, node, args, kwargs):
  1907. if len(args) != 1:
  1908. raise InvalidArguments('Install_subdir requires exactly one argument.')
  1909. if not 'install_dir' in kwargs:
  1910. raise InvalidArguments('Missing keyword argument install_dir')
  1911. install_dir = kwargs['install_dir']
  1912. if not isinstance(install_dir, str):
  1913. raise InvalidArguments('Keyword argument install_dir not a string.')
  1914. idir = InstallDir(self.subdir, args[0], install_dir)
  1915. self.build.install_dirs.append(idir)
  1916. return idir
  1917. def func_configure_file(self, node, args, kwargs):
  1918. if len(args) > 0:
  1919. raise InterpreterException("configure_file takes only keyword arguments.")
  1920. if not 'output' in kwargs:
  1921. raise InterpreterException('Required keyword argument "output" not defined.')
  1922. inputfile = kwargs.get('input', None)
  1923. output = kwargs['output']
  1924. if not isinstance(inputfile, (str, type(None))):
  1925. raise InterpreterException('Input must be a string.')
  1926. if not isinstance(output, str):
  1927. raise InterpreterException('Output must be a string.')
  1928. if os.path.split(output)[0] != '':
  1929. raise InterpreterException('Output file name must not contain a subdirectory.')
  1930. if 'configuration' in kwargs:
  1931. conf = kwargs['configuration']
  1932. if not isinstance(conf, ConfigurationDataHolder):
  1933. raise InterpreterException('Argument "configuration" is not of type configuration_data')
  1934. ofile_abs = os.path.join(self.environment.build_dir, self.subdir, output)
  1935. if inputfile is not None:
  1936. # Normalize the path of the conffile to avoid duplicates
  1937. # This is especially important to convert '/' to '\' on Windows
  1938. conffile = os.path.normpath(os.path.join(self.subdir, inputfile))
  1939. if conffile not in self.build_def_files:
  1940. self.build_def_files.append(conffile)
  1941. os.makedirs(os.path.join(self.environment.build_dir, self.subdir), exist_ok=True)
  1942. ifile_abs = os.path.join(self.environment.source_dir, self.subdir, inputfile)
  1943. mesonlib.do_conf_file(ifile_abs, ofile_abs, conf.held_object)
  1944. else:
  1945. mesonlib.dump_conf_header(ofile_abs, conf.held_object)
  1946. conf.mark_used()
  1947. elif 'command' in kwargs:
  1948. if 'input' not in kwargs:
  1949. raise InterpreterException('Required keyword input missing.')
  1950. res = self.func_run_command(node, kwargs['command'], {})
  1951. if res.returncode != 0:
  1952. raise InterpreterException('Running configure command failed.\n%s\n%s' %
  1953. (res.stdout, res.stderr))
  1954. else:
  1955. raise InterpreterException('Configure_file must have either "configuration" or "command".')
  1956. if isinstance(kwargs.get('install_dir', None), str):
  1957. self.build.data.append(DataHolder(False, self.subdir, [output], kwargs).held_object)
  1958. return mesonlib.File.from_built_file(self.subdir, output)
  1959. @stringArgs
  1960. def func_include_directories(self, node, args, kwargs):
  1961. absbase = os.path.join(self.environment.get_source_dir(), self.subdir)
  1962. for a in args:
  1963. absdir = os.path.join(absbase, a)
  1964. if not os.path.isdir(absdir):
  1965. raise InvalidArguments('Include dir %s does not exist.' % a)
  1966. is_system = kwargs.get('is_system', False)
  1967. if not isinstance(is_system, bool):
  1968. raise InvalidArguments('Is_system must be boolean.')
  1969. i = IncludeDirsHolder(build.IncludeDirs(self.subdir, args, is_system))
  1970. return i
  1971. @stringArgs
  1972. def func_add_global_arguments(self, node, args, kwargs):
  1973. if self.subproject != '':
  1974. raise InvalidCode('Global arguments can not be set in subprojects because there is no way to make that reliable.')
  1975. if self.global_args_frozen:
  1976. raise InvalidCode('Tried to set global arguments after a build target has been declared.\nThis is not permitted. Please declare all global arguments before your targets.')
  1977. if not 'language' in kwargs:
  1978. raise InvalidCode('Missing language definition in add_global_arguments')
  1979. lang = kwargs['language'].lower()
  1980. if lang in self.build.global_args:
  1981. self.build.global_args[lang] += args
  1982. else:
  1983. self.build.global_args[lang] = args
  1984. @stringArgs
  1985. def func_add_global_link_arguments(self, node, args, kwargs):
  1986. if self.subproject != '':
  1987. raise InvalidCode('Global arguments can not be set in subprojects because there is no way to make that reliable.')
  1988. if self.global_args_frozen:
  1989. raise InvalidCode('Tried to set global arguments after a build target has been declared.\nThis is not permitted. Please declare all global arguments before your targets.')
  1990. if not 'language' in kwargs:
  1991. raise InvalidCode('Missing language definition in add_global_arguments')
  1992. lang = kwargs['language'].lower()
  1993. if lang in self.build.global_link_args:
  1994. self.build.global_link_args[lang] += args
  1995. else:
  1996. self.build.global_link_args[lang] = args
  1997. def func_environment(self, node, args, kwargs):
  1998. return EnvironmentVariablesHolder()
  1999. def flatten(self, args):
  2000. if isinstance(args, mparser.StringNode):
  2001. return args.value
  2002. if isinstance(args, (int, str, InterpreterObject)):
  2003. return args
  2004. result = []
  2005. for a in args:
  2006. if isinstance(a, list):
  2007. rest = self.flatten(a)
  2008. result = result + rest
  2009. elif isinstance(a, mparser.StringNode):
  2010. result.append(a.value)
  2011. else:
  2012. result.append(a)
  2013. return result
  2014. def source_strings_to_files(self, sources):
  2015. results = []
  2016. for s in sources:
  2017. if isinstance(s, (mesonlib.File, GeneratedListHolder,
  2018. CustomTargetHolder)):
  2019. pass
  2020. elif isinstance(s, str):
  2021. s = mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, s)
  2022. else:
  2023. raise InterpreterException("Source item is not string or File-type object.")
  2024. results.append(s)
  2025. return results
  2026. def add_target(self, name, tobj):
  2027. if name == '':
  2028. raise InterpreterException('Target name must not be empty.')
  2029. if name in coredata.forbidden_target_names:
  2030. raise InvalidArguments('Target name "%s" is reserved for Meson\'s internal use. Please rename.'\
  2031. % name)
  2032. # To permit an executable and a shared library to have the
  2033. # same name, such as "foo.exe" and "libfoo.a".
  2034. idname = tobj.get_id()
  2035. if idname in self.build.targets:
  2036. raise InvalidCode('Tried to create target "%s", but a target of that name already exists.' % name)
  2037. self.build.targets[idname] = tobj
  2038. if idname not in self.coredata.target_guids:
  2039. self.coredata.target_guids[idname] = str(uuid.uuid4()).upper()
  2040. def build_target(self, node, args, kwargs, targetholder):
  2041. if len(args) == 0:
  2042. raise InterpreterException('Target does not have a name.')
  2043. name = args[0]
  2044. sources = args[1:]
  2045. if self.environment.is_cross_build():
  2046. if kwargs.get('native', False):
  2047. is_cross = False
  2048. else:
  2049. is_cross = True
  2050. else:
  2051. is_cross = False
  2052. try:
  2053. kw_src = self.flatten(kwargs['sources'])
  2054. if not isinstance(kw_src, list):
  2055. kw_src = [kw_src]
  2056. except KeyError:
  2057. kw_src = []
  2058. sources += kw_src
  2059. sources = self.source_strings_to_files(sources)
  2060. objs = self.flatten(kwargs.get('objects', []))
  2061. kwargs['dependencies'] = self.flatten(kwargs.get('dependencies', []))
  2062. if not isinstance(objs, list):
  2063. objs = [objs]
  2064. self.check_sources_exist(os.path.join(self.source_root, self.subdir), sources)
  2065. if targetholder is ExecutableHolder:
  2066. targetclass = build.Executable
  2067. elif targetholder is SharedLibraryHolder:
  2068. targetclass = build.SharedLibrary
  2069. elif targetholder is StaticLibraryHolder:
  2070. targetclass = build.StaticLibrary
  2071. elif targetholder is JarHolder:
  2072. targetclass = build.Jar
  2073. else:
  2074. mlog.debug('Unknown target type:', str(targetholder))
  2075. raise RuntimeError('Unreachable code')
  2076. target = targetclass(name, self.subdir, self.subproject, is_cross, sources, objs, self.environment, kwargs)
  2077. if is_cross:
  2078. self.add_cross_stdlib_info(target)
  2079. l = targetholder(target, self)
  2080. self.add_target(name, l.held_object)
  2081. self.global_args_frozen = True
  2082. return l
  2083. def get_used_languages(self, target):
  2084. result = {}
  2085. for i in target.sources:
  2086. for c in self.build.compilers:
  2087. if c.can_compile(i):
  2088. result[c.language] = True
  2089. break
  2090. return result
  2091. def add_cross_stdlib_info(self, target):
  2092. for l in self.get_used_languages(target):
  2093. if self.environment.cross_info.has_stdlib(l) and \
  2094. self.subproject != self.environment.cross_info.get_stdlib(l)[0]:
  2095. target.add_external_deps(self.build.cross_stdlibs[l])
  2096. def check_sources_exist(self, subdir, sources):
  2097. for s in sources:
  2098. if not isinstance(s, str):
  2099. continue # This means a generated source and they always exist.
  2100. fname = os.path.join(subdir, s)
  2101. if not os.path.isfile(fname):
  2102. raise InterpreterException('Tried to add non-existing source %s.' % s)
  2103. def function_call(self, node):
  2104. func_name = node.func_name
  2105. (posargs, kwargs) = self.reduce_arguments(node.args)
  2106. if func_name in self.funcs:
  2107. return self.funcs[func_name](node, self.flatten(posargs), kwargs)
  2108. else:
  2109. raise InvalidCode('Unknown function "%s".' % func_name)
  2110. def is_assignable(self, value):
  2111. return isinstance(value, (InterpreterObject, dependencies.Dependency,
  2112. str, int, list, mesonlib.File))
  2113. def assignment(self, node):
  2114. assert(isinstance(node, mparser.AssignmentNode))
  2115. var_name = node.var_name
  2116. if not isinstance(var_name, str):
  2117. raise InvalidArguments('Tried to assign value to a non-variable.')
  2118. value = self.evaluate_statement(node.value)
  2119. value = self.to_native(value)
  2120. if not self.is_assignable(value):
  2121. raise InvalidCode('Tried to assign an invalid value to variable.')
  2122. self.set_variable(var_name, value)
  2123. return value
  2124. def reduce_arguments(self, args):
  2125. assert(isinstance(args, mparser.ArgumentNode))
  2126. if args.incorrect_order():
  2127. raise InvalidArguments('All keyword arguments must be after positional arguments.')
  2128. reduced_pos = [self.evaluate_statement(arg) for arg in args.arguments]
  2129. reduced_kw = {}
  2130. for key in args.kwargs.keys():
  2131. if not isinstance(key, str):
  2132. raise InvalidArguments('Keyword argument name is not a string.')
  2133. a = args.kwargs[key]
  2134. reduced_kw[key] = self.evaluate_statement(a)
  2135. if not isinstance(reduced_pos, list):
  2136. reduced_pos = [reduced_pos]
  2137. return (reduced_pos, reduced_kw)
  2138. def bool_method_call(self, obj, method_name, args):
  2139. obj = self.to_native(obj)
  2140. (posargs, _) = self.reduce_arguments(args)
  2141. if method_name == 'to_string':
  2142. if len(posargs) == 0:
  2143. if obj == True:
  2144. return 'true'
  2145. else:
  2146. return 'false'
  2147. elif len(posargs) == 2 and isinstance(posargs[0], str) and isinstance(posargs[1], str):
  2148. if obj == True:
  2149. return posargs[0]
  2150. else:
  2151. return posargs[1]
  2152. else:
  2153. raise InterpreterException('bool.to_string() must have either no arguments or exactly two string arguments.')
  2154. elif method_name == 'to_int':
  2155. if obj == True:
  2156. return 1
  2157. else:
  2158. return 0
  2159. else:
  2160. raise InterpreterException('Unknown method "%s" for a boolean.' % method_name)
  2161. def int_method_call(self, obj, method_name, args):
  2162. obj = self.to_native(obj)
  2163. (posargs, _) = self.reduce_arguments(args)
  2164. if method_name == 'is_even':
  2165. if len(posargs) == 0:
  2166. return obj % 2 == 0
  2167. else:
  2168. raise InterpreterException('int.is_even() must have no arguments.')
  2169. elif method_name == 'is_odd':
  2170. if len(posargs) == 0:
  2171. return obj % 2 != 0
  2172. else:
  2173. raise InterpreterException('int.is_odd() must have no arguments.')
  2174. else:
  2175. raise InterpreterException('Unknown method "%s" for an integer.' % method_name)
  2176. def string_method_call(self, obj, method_name, args):
  2177. obj = self.to_native(obj)
  2178. (posargs, _) = self.reduce_arguments(args)
  2179. if method_name == 'strip':
  2180. return obj.strip()
  2181. elif method_name == 'format':
  2182. return self.format_string(obj, args)
  2183. elif method_name == 'to_upper':
  2184. return obj.upper()
  2185. elif method_name == 'to_lower':
  2186. return obj.lower()
  2187. elif method_name == 'underscorify':
  2188. return re.sub(r'[^a-zA-Z0-9]', '_', obj)
  2189. elif method_name == 'split':
  2190. if len(posargs) > 1:
  2191. raise InterpreterException('Split() must have at most one argument.')
  2192. elif len(posargs) == 1:
  2193. s = posargs[0]
  2194. if not isinstance(s, str):
  2195. raise InterpreterException('Split() argument must be a string')
  2196. return obj.split(s)
  2197. else:
  2198. return obj.split()
  2199. elif method_name == 'startswith' or method_name == 'contains' or method_name == 'endswith':
  2200. s = posargs[0]
  2201. if not isinstance(s, str):
  2202. raise InterpreterException('Argument must be a string.')
  2203. if method_name == 'startswith':
  2204. return obj.startswith(s)
  2205. elif method_name == 'contains':
  2206. return obj.find(s) >= 0
  2207. return obj.endswith(s)
  2208. elif method_name == 'to_int':
  2209. try:
  2210. return int(obj)
  2211. except Exception:
  2212. raise InterpreterException('String can not be converted to int: ' + obj)
  2213. elif method_name == 'join':
  2214. if len(posargs) != 1:
  2215. raise InterpreterException('Join() takes exactly one argument.')
  2216. strlist = posargs[0]
  2217. check_stringlist(strlist)
  2218. return obj.join(strlist)
  2219. elif method_name == 'version_compare':
  2220. if len(posargs) != 1:
  2221. raise InterpreterException('Version_compare() takes exactly one argument.')
  2222. cmpr = posargs[0]
  2223. if not isinstance(cmpr, str):
  2224. raise InterpreterException('Version_compare() argument must be a string.')
  2225. return mesonlib.version_compare(obj, cmpr)
  2226. raise InterpreterException('Unknown method "%s" for a string.' % method_name)
  2227. def to_native(self, arg):
  2228. if isinstance(arg, (mparser.StringNode, mparser.NumberNode,
  2229. mparser.BooleanNode)):
  2230. return arg.value
  2231. return arg
  2232. def format_string(self, templ, args):
  2233. templ = self.to_native(templ)
  2234. if isinstance(args, mparser.ArgumentNode):
  2235. args = args.arguments
  2236. for (i, arg) in enumerate(args):
  2237. arg = self.to_native(self.evaluate_statement(arg))
  2238. if isinstance(arg, bool): # Python boolean is upper case.
  2239. arg = str(arg).lower()
  2240. templ = templ.replace('@{}@'.format(i), str(arg))
  2241. return templ
  2242. def method_call(self, node):
  2243. invokable = node.source_object
  2244. if isinstance(invokable, mparser.IdNode):
  2245. object_name = invokable.value
  2246. obj = self.get_variable(object_name)
  2247. else:
  2248. obj = self.evaluate_statement(invokable)
  2249. method_name = node.name
  2250. if method_name == 'extract_objects' and self.environment.coredata.get_builtin_option('unity'):
  2251. raise InterpreterException('Single object files can not be extracted in Unity builds.')
  2252. args = node.args
  2253. if isinstance(obj, mparser.StringNode):
  2254. obj = obj.get_value()
  2255. if isinstance(obj, str):
  2256. return self.string_method_call(obj, method_name, args)
  2257. if isinstance(obj, bool):
  2258. return self.bool_method_call(obj, method_name, args)
  2259. if isinstance(obj, int):
  2260. return self.int_method_call(obj, method_name, args)
  2261. if isinstance(obj, list):
  2262. return self.array_method_call(obj, method_name, self.reduce_arguments(args)[0])
  2263. if not isinstance(obj, InterpreterObject):
  2264. raise InvalidArguments('Variable "%s" is not callable.' % object_name)
  2265. (args, kwargs) = self.reduce_arguments(args)
  2266. if method_name == 'extract_objects':
  2267. self.validate_extraction(obj.held_object)
  2268. return obj.method_call(method_name, self.flatten(args), kwargs)
  2269. # Only permit object extraction from the same subproject
  2270. def validate_extraction(self, buildtarget):
  2271. if not self.subdir.startswith(self.subproject_dir):
  2272. if buildtarget.subdir.startswith(self.subproject_dir):
  2273. raise InterpreterException('Tried to extract objects from a subproject target.')
  2274. else:
  2275. if not buildtarget.subdir.startswith(self.subproject_dir):
  2276. raise InterpreterException('Tried to extract objects from the main project from a subproject.')
  2277. if self.subdir.split('/')[1] != buildtarget.subdir.split('/')[1]:
  2278. raise InterpreterException('Tried to extract objects from a different subproject.')
  2279. def array_method_call(self, obj, method_name, args):
  2280. if method_name == 'contains':
  2281. return self.check_contains(obj, args)
  2282. elif method_name == 'length':
  2283. return len(obj)
  2284. elif method_name == 'get':
  2285. index = args[0]
  2286. if not isinstance(index, int):
  2287. raise InvalidArguments('Array index must be a number.')
  2288. if index < -len(obj) or index >= len(obj):
  2289. raise InvalidArguments('Array index %s is out of bounds for array of size %d.' % (index, len(obj)))
  2290. return obj[index]
  2291. raise InterpreterException('Arrays do not have a method called "%s".' % method_name)
  2292. def check_contains(self, obj, args):
  2293. if len(args) != 1:
  2294. raise InterpreterException('Contains method takes exactly one argument.')
  2295. item = args[0]
  2296. for element in obj:
  2297. if isinstance(element, list):
  2298. found = self.check_contains(element, args)
  2299. if found:
  2300. return True
  2301. try:
  2302. if element == item:
  2303. return True
  2304. except Exception:
  2305. pass
  2306. return False
  2307. def evaluate_if(self, node):
  2308. assert(isinstance(node, mparser.IfClauseNode))
  2309. for i in node.ifs:
  2310. result = self.evaluate_statement(i.condition)
  2311. if not(isinstance(result, bool)):
  2312. print(result)
  2313. raise InvalidCode('If clause does not evaluate to true or false.')
  2314. if result:
  2315. self.evaluate_codeblock(i.block)
  2316. return
  2317. if not isinstance(node.elseblock, mparser.EmptyNode):
  2318. self.evaluate_codeblock(node.elseblock)
  2319. def evaluate_ternary(self, node):
  2320. assert(isinstance(node, mparser.TernaryNode))
  2321. result = self.evaluate_statement(node.condition)
  2322. if not isinstance(result, bool):
  2323. raise InterpreterException('Ternary condition is not boolean.')
  2324. if result:
  2325. return self.evaluate_statement(node.trueblock)
  2326. else:
  2327. return self.evaluate_statement(node.falseblock)
  2328. def evaluate_foreach(self, node):
  2329. assert(isinstance(node, mparser.ForeachClauseNode))
  2330. varname = node.varname.value
  2331. items = self.evaluate_statement(node.items)
  2332. if not isinstance(items, list):
  2333. raise InvalidArguments('Items of foreach loop is not an array')
  2334. for item in items:
  2335. self.set_variable(varname, item)
  2336. self.evaluate_codeblock(node.block)
  2337. def evaluate_plusassign(self, node):
  2338. assert(isinstance(node, mparser.PlusAssignmentNode))
  2339. varname = node.var_name
  2340. addition = self.evaluate_statement(node.value)
  2341. # Remember that all variables are immutable. We must always create a
  2342. # full new variable and then assign it.
  2343. old_variable = self.get_variable(varname)
  2344. if isinstance(old_variable, str):
  2345. if not isinstance(addition, str):
  2346. raise InvalidArguments('The += operator requires a string on the right hand side if the variable on the left is a string')
  2347. new_value = old_variable + addition
  2348. elif isinstance(old_variable, int):
  2349. if not isinstance(addition, int):
  2350. raise InvalidArguments('The += operator requires an int on the right hand side if the variable on the left is an int')
  2351. new_value = old_variable + addition
  2352. elif not isinstance(old_variable, list):
  2353. raise InvalidArguments('The += operator currently only works with arrays, strings or ints ')
  2354. # Add other data types here.
  2355. else:
  2356. if isinstance(addition, list):
  2357. new_value = old_variable + addition
  2358. else:
  2359. new_value = old_variable + [addition]
  2360. self.set_variable(varname, new_value)
  2361. def evaluate_indexing(self, node):
  2362. assert(isinstance(node, mparser.IndexNode))
  2363. iobject = self.evaluate_statement(node.iobject)
  2364. if not isinstance(iobject, list):
  2365. raise InterpreterException('Tried to index a non-array object.')
  2366. index = self.evaluate_statement(node.index)
  2367. if not isinstance(index, int):
  2368. raise InterpreterException('Index value is not an integer.')
  2369. if index < -len(iobject) or index >= len(iobject):
  2370. raise InterpreterException('Index %d out of bounds of array of size %d.' % (index, len(iobject)))
  2371. return iobject[index]
  2372. def is_elementary_type(self, v):
  2373. return isinstance(v, (int, float, str, bool, list))
  2374. def evaluate_comparison(self, node):
  2375. v1 = self.evaluate_statement(node.left)
  2376. v2 = self.evaluate_statement(node.right)
  2377. if self.is_elementary_type(v1):
  2378. val1 = v1
  2379. else:
  2380. val1 = v1.value
  2381. if self.is_elementary_type(v2):
  2382. val2 = v2
  2383. else:
  2384. val2 = v2.value
  2385. if node.ctype == '==':
  2386. return val1 == val2
  2387. elif node.ctype == '!=':
  2388. return val1 != val2
  2389. elif node.ctype == '<':
  2390. return val1 < val2
  2391. elif node.ctype == '<=':
  2392. return val1 <= val2
  2393. elif node.ctype == '>':
  2394. return val1 > val2
  2395. elif node.ctype == '>=':
  2396. return val1 >= val2
  2397. else:
  2398. raise InvalidCode('You broke my compare eval.')
  2399. def evaluate_andstatement(self, cur):
  2400. l = self.evaluate_statement(cur.left)
  2401. if isinstance(l, mparser.BooleanNode):
  2402. l = l.value
  2403. if not isinstance(l, bool):
  2404. raise InterpreterException('First argument to "and" is not a boolean.')
  2405. if not l:
  2406. return False
  2407. r = self.evaluate_statement(cur.right)
  2408. if isinstance(r, mparser.BooleanNode):
  2409. r = r.value
  2410. if not isinstance(r, bool):
  2411. raise InterpreterException('Second argument to "and" is not a boolean.')
  2412. return r
  2413. def evaluate_orstatement(self, cur):
  2414. l = self.evaluate_statement(cur.left)
  2415. if isinstance(l, mparser.BooleanNode):
  2416. l = l.get_value()
  2417. if not isinstance(l, bool):
  2418. raise InterpreterException('First argument to "or" is not a boolean.')
  2419. if l:
  2420. return True
  2421. r = self.evaluate_statement(cur.right)
  2422. if isinstance(r, mparser.BooleanNode):
  2423. r = r.get_value()
  2424. if not isinstance(r, bool):
  2425. raise InterpreterException('Second argument to "or" is not a boolean.')
  2426. return r
  2427. def evaluate_notstatement(self, cur):
  2428. v = self.evaluate_statement(cur.value)
  2429. if isinstance(v, mparser.BooleanNode):
  2430. v = v.value
  2431. if not isinstance(v, bool):
  2432. raise InterpreterException('Argument to "not" is not a boolean.')
  2433. return not v
  2434. def evaluate_uminusstatement(self, cur):
  2435. v = self.evaluate_statement(cur.value)
  2436. if isinstance(v, mparser.NumberNode):
  2437. v = v.value
  2438. if not isinstance(v, int):
  2439. raise InterpreterException('Argument to negation is not an integer.')
  2440. return -v
  2441. def evaluate_arithmeticstatement(self, cur):
  2442. l = self.to_native(self.evaluate_statement(cur.left))
  2443. r = self.to_native(self.evaluate_statement(cur.right))
  2444. if cur.operation == 'add':
  2445. try:
  2446. return l + r
  2447. except Exception as e:
  2448. raise InvalidCode('Invalid use of addition: ' + str(e))
  2449. elif cur.operation == 'sub':
  2450. if not isinstance(l, int) or not isinstance(r, int):
  2451. raise InvalidCode('Subtraction works only with integers.')
  2452. return l - r
  2453. elif cur.operation == 'mul':
  2454. if not isinstance(l, int) or not isinstance(r, int):
  2455. raise InvalidCode('Multiplication works only with integers.')
  2456. return l * r
  2457. elif cur.operation == 'div':
  2458. if not isinstance(l, int) or not isinstance(r, int):
  2459. raise InvalidCode('Division works only with integers.')
  2460. return l // r
  2461. elif cur.operation == 'mod':
  2462. if not isinstance(l, int) or not isinstance(r, int):
  2463. raise InvalidCode('Modulo works only with integers.')
  2464. return l % r
  2465. else:
  2466. raise InvalidCode('You broke me.')
  2467. def evaluate_arraystatement(self, cur):
  2468. (arguments, kwargs) = self.reduce_arguments(cur.args)
  2469. if len(kwargs) > 0:
  2470. raise InvalidCode('Keyword arguments are invalid in array construction.')
  2471. return arguments
  2472. def is_subproject(self):
  2473. return self.subproject != ''