files: # Copyright 2012-2018 The Meson development team
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  
  #     http://www.apache.org/licenses/LICENSE-2.0
  
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  
  from . import mparser
  from . import environment
  from . import coredata
  from . import dependencies
  from . import mlog
  from . import build
  from . import optinterpreter
  from . import compilers
  from .wrap import wrap, WrapMode
  from . import mesonlib
  from .mesonlib import FileMode, Popen_safe, listify, extract_as_list, has_path_sep
  from .dependencies import ExternalProgram
  from .dependencies import InternalDependency, Dependency, NotFoundDependency, DependencyException
  from .interpreterbase import InterpreterBase
  from .interpreterbase import check_stringlist, flatten, noPosargs, noKwargs, stringArgs, permittedKwargs, noArgsFlattening
  from .interpreterbase import InterpreterException, InvalidArguments, InvalidCode, SubdirDoneRequest
  from .interpreterbase import InterpreterObject, MutableInterpreterObject, Disabler
  from .interpreterbase import FeatureNew, FeatureDeprecated, FeatureNewKwargs
  from .modules import ModuleReturnValue
  
  import os, sys, shutil, uuid
  import re, shlex
  import subprocess
  from collections import namedtuple
  from pathlib import PurePath
  
  import importlib
  
  permitted_method_kwargs = {
      'partial_dependency': {'compile_args', 'link_args', 'links', 'includes',
                             'sources'},
  }
  
  def stringifyUserArguments(args):
      if isinstance(args, list):
          return '[%s]' % ', '.join([stringifyUserArguments(x) for x in args])
      elif isinstance(args, dict):
          return '{%s}' % ', '.join(['%s : %s' % (stringifyUserArguments(k), stringifyUserArguments(v)) for k, v in args.items()])
      elif isinstance(args, int):
          return str(args)
      elif isinstance(args, str):
          return "'%s'" % args
      raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
  
  class ObjectHolder:
      def __init__(self, obj):
          self.held_object = obj
  
      def __repr__(self):
          return '<Holder: {!r}>'.format(self.held_object)
  
  class FeatureOptionHolder(InterpreterObject, ObjectHolder):
      def __init__(self, env, option):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, option)
          if option.is_auto():
              self.held_object = env.coredata.builtins['auto_features']
          self.name = option.name
          self.methods.update({'enabled': self.enabled_method,
                               'disabled': self.disabled_method,
                               'auto': self.auto_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def enabled_method(self, args, kwargs):
          return self.held_object.is_enabled()
  
      @noPosargs
      @permittedKwargs({})
      def disabled_method(self, args, kwargs):
          return self.held_object.is_disabled()
  
      @noPosargs
      @permittedKwargs({})
      def auto_method(self, args, kwargs):
          return self.held_object.is_auto()
  
  def extract_required_kwarg(kwargs):
      val = kwargs.get('required', True)
      disabled = False
      required = False
      feature = None
      if isinstance(val, FeatureOptionHolder):
          option = val.held_object
          feature = val.name
          if option.is_disabled():
              disabled = True
          elif option.is_enabled():
              required = True
      elif isinstance(required, bool):
          required = val
      else:
          raise InterpreterException('required keyword argument must be boolean or a feature option')
  
      # Keep boolean value in kwargs to simplify other places where this kwarg is
      # checked.
      kwargs['required'] = required
  
      return disabled, required, feature
  
  class TryRunResultHolder(InterpreterObject):
      def __init__(self, res):
          super().__init__()
          self.res = res
          self.methods.update({'returncode': self.returncode_method,
                               'compiled': self.compiled_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def returncode_method(self, args, kwargs):
          return self.res.returncode
  
      @noPosargs
      @permittedKwargs({})
      def compiled_method(self, args, kwargs):
          return self.res.compiled
  
      @noPosargs
      @permittedKwargs({})
      def stdout_method(self, args, kwargs):
          return self.res.stdout
  
      @noPosargs
      @permittedKwargs({})
      def stderr_method(self, args, kwargs):
          return self.res.stderr
  
  class RunProcess(InterpreterObject):
  
      def __init__(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir=False, check=False, capture=True):
          super().__init__()
          if not isinstance(cmd, ExternalProgram):
              raise AssertionError('BUG: RunProcess must be passed an ExternalProgram')
          self.capture = capture
          pc, self.stdout, self.stderr = self.run_command(cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir, check)
          self.returncode = pc.returncode
          self.methods.update({'returncode': self.returncode_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def run_command(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir, check=False):
          command_array = cmd.get_command() + args
          env = {'MESON_SOURCE_ROOT': source_dir,
                 'MESON_BUILD_ROOT': build_dir,
                 'MESON_SUBDIR': subdir,
                 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in mesonintrospect]),
                 }
          if in_builddir:
              cwd = os.path.join(build_dir, subdir)
          else:
              cwd = os.path.join(source_dir, subdir)
          child_env = os.environ.copy()
          child_env.update(env)
          stdout = subprocess.PIPE if self.capture else subprocess.DEVNULL
          mlog.debug('Running command:', ' '.join(command_array))
          try:
              p, o, e = Popen_safe(command_array, stdout=stdout, env=child_env, cwd=cwd)
              if self.capture:
                  mlog.debug('--- stdout ---')
                  mlog.debug(o)
              else:
                  o = ''
                  mlog.debug('--- stdout disabled ---')
              mlog.debug('--- stderr ---')
              mlog.debug(e)
              mlog.debug('')
  
              if check and p.returncode != 0:
                  raise InterpreterException('Command "{}" failed with status {}.'.format(' '.join(command_array), p.returncode))
  
              return p, o, e
          except FileNotFoundError:
              raise InterpreterException('Could not execute command "%s".' % ' '.join(command_array))
  
      @noPosargs
      @permittedKwargs({})
      def returncode_method(self, args, kwargs):
          return self.returncode
  
      @noPosargs
      @permittedKwargs({})
      def stdout_method(self, args, kwargs):
          return self.stdout
  
      @noPosargs
      @permittedKwargs({})
      def stderr_method(self, args, kwargs):
          return self.stderr
  
  class ConfigureFileHolder(InterpreterObject, ObjectHolder):
  
      def __init__(self, subdir, sourcename, targetname, configuration_data):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.ConfigureFile(subdir, sourcename,
                                                          targetname, configuration_data))
  
  
  class EnvironmentVariablesHolder(MutableInterpreterObject, ObjectHolder):
      def __init__(self):
          MutableInterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.EnvironmentVariables())
          self.methods.update({'set': self.set_method,
                               'append': self.append_method,
                               'prepend': self.prepend_method,
                               })
  
      def __repr__(self):
          repr_str = "<{0}: {1}>"
          return repr_str.format(self.__class__.__name__, self.held_object.envvars)
  
      def add_var(self, method, args, kwargs):
          if not isinstance(kwargs.get("separator", ""), str):
              raise InterpreterException("EnvironmentVariablesHolder methods 'separator'"
                                         " argument needs to be a string.")
          if len(args) < 2:
              raise InterpreterException("EnvironmentVariablesHolder methods require at least"
                                         "2 arguments, first is the name of the variable and"
                                         " following one are values")
          self.held_object.envvars.append((method, args[0], args[1:], kwargs))
  
      @stringArgs
      @permittedKwargs({'separator'})
      def set_method(self, args, kwargs):
          self.add_var(self.held_object.set, args, kwargs)
  
      @stringArgs
      @permittedKwargs({'separator'})
      def append_method(self, args, kwargs):
          self.add_var(self.held_object.append, args, kwargs)
  
      @stringArgs
      @permittedKwargs({'separator'})
      def prepend_method(self, args, kwargs):
          self.add_var(self.held_object.prepend, args, kwargs)
  
  
  class ConfigurationDataHolder(MutableInterpreterObject, ObjectHolder):
      def __init__(self):
          MutableInterpreterObject.__init__(self)
          self.used = False # These objects become immutable after use in configure_file.
          ObjectHolder.__init__(self, build.ConfigurationData())
          self.methods.update({'set': self.set_method,
                               'set10': self.set10_method,
                               'set_quoted': self.set_quoted_method,
                               'has': self.has_method,
                               'get': self.get_method,
                               'get_unquoted': self.get_unquoted_method,
                               'merge_from': self.merge_from_method,
                               })
  
      def is_used(self):
          return self.used
  
      def mark_used(self):
          self.used = True
  
      def validate_args(self, args, kwargs):
          if len(args) == 1 and isinstance(args[0], list) and len(args[0]) == 2:
              mlog.log(mlog.red('DEPRECATION:'),
                       '''Passing a list as the single argument to configuration_data.set is deprecated.
  This will become a hard error in the future''')
              args = args[0]
  
          if len(args) != 2:
              raise InterpreterException("Configuration set requires 2 arguments.")
          if self.used:
              raise InterpreterException("Can not set values on configuration object that has been used.")
          name = args[0]
          val = args[1]
          desc = kwargs.get('description', None)
          if not isinstance(name, str):
              raise InterpreterException("First argument to set must be a string.")
          if desc is not None and not isinstance(desc, str):
              raise InterpreterException('Description must be a string.')
  
          return name, val, desc
  
      @noArgsFlattening
      def set_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          self.held_object.values[name] = (val, desc)
  
      def set_quoted_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if not isinstance(val, str):
              raise InterpreterException("Second argument to set_quoted must be a string.")
          escaped_val = '\\"'.join(val.split('"'))
          self.held_object.values[name] = ('"' + escaped_val + '"', desc)
  
      def set10_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if val:
              self.held_object.values[name] = (1, desc)
          else:
              self.held_object.values[name] = (0, desc)
  
      def has_method(self, args, kwargs):
          return args[0] in self.held_object.values
  
      @FeatureNew('configuration_data.get()', '0.38.0')
      @noArgsFlattening
      def get_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              return self.held_object.get(name)[0]
          if len(args) > 1:
              return args[1]
          raise InterpreterException('Entry %s not in configuration data.' % name)
  
      @FeatureNew('get_unquoted', '0.44.0')
      def get_unquoted_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              val = self.held_object.get(name)[0]
          elif len(args) > 1:
              val = args[1]
          else:
              raise InterpreterException('Entry %s not in configuration data.' % name)
          if val[0] == '"' and val[-1] == '"':
              return val[1:-1]
          return val
  
      def get(self, name):
          return self.held_object.values[name] # (val, desc)
  
      def keys(self):
          return self.held_object.values.keys()
  
      def merge_from_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Merge_from takes one positional argument.')
          from_object = args[0]
          if not isinstance(from_object, ConfigurationDataHolder):
              raise InterpreterException('Merge_from argument must be a configuration data object.')
          from_object = from_object.held_object
          for k, v in from_object.values.items():
              self.held_object.values[k] = v
  
  # Interpreter objects can not be pickled so we must have
  # these wrappers.
  
  class DependencyHolder(InterpreterObject, ObjectHolder):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, dep)
          self.methods.update({'found': self.found_method,
                               'type_name': self.type_name_method,
                               'version': self.version_method,
                               'get_pkgconfig_variable': self.pkgconfig_method,
                               'get_configtool_variable': self.configtool_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def type_name_method(self, args, kwargs):
          return self.held_object.type_name
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          if self.held_object.type_name == 'internal':
              return True
          return self.held_object.found()
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      @permittedKwargs({'define_variable'})
      def pkgconfig_method(self, args, kwargs):
          args = listify(args)
          if len(args) != 1:
              raise InterpreterException('get_pkgconfig_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_pkgconfig_variable(varname, kwargs)
  
      @FeatureNew('get_configtool_variable', '0.44.0')
      @permittedKwargs({})
      def configtool_method(self, args, kwargs):
          args = listify(args)
          if len(args) != 1:
              raise InterpreterException('get_configtool_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_configtool_variable(varname)
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class InternalDependencyHolder(InterpreterObject, ObjectHolder):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, dep)
          self.methods.update({'found': self.found_method,
                               'version': self.version_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return True
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class ExternalProgramHolder(InterpreterObject, ObjectHolder):
      def __init__(self, ep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, ep)
          self.methods.update({'found': self.found_method,
                               'path': self.path_method})
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return self.found()
  
      @noPosargs
      @permittedKwargs({})
      def path_method(self, args, kwargs):
          return self.held_object.get_path()
  
      def found(self):
          return self.held_object.found()
  
      def get_command(self):
          return self.held_object.get_command()
  
      def get_name(self):
          return self.held_object.get_name()
  
  class ExternalLibraryHolder(InterpreterObject, ObjectHolder):
      def __init__(self, el):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, el)
          self.methods.update({'found': self.found_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      def found(self):
          return self.held_object.found()
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return self.found()
  
      def get_name(self):
          return self.held_object.name
  
      def get_compile_args(self):
          return self.held_object.get_compile_args()
  
      def get_link_args(self):
          return self.held_object.get_link_args()
  
      def get_exe_args(self):
          return self.held_object.get_exe_args()
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class GeneratorHolder(InterpreterObject, ObjectHolder):
      def __init__(self, interpreter, args, kwargs):
          InterpreterObject.__init__(self)
          self.interpreter = interpreter
          ObjectHolder.__init__(self, build.Generator(args, kwargs))
          self.methods.update({'process': self.process_method})
  
      @FeatureNewKwargs('generator.process', '0.45.0', ['preserve_path_from'])
      @permittedKwargs({'extra_args', 'preserve_path_from'})
      def process_method(self, args, kwargs):
          extras = mesonlib.stringlistify(kwargs.get('extra_args', []))
          if 'preserve_path_from' in kwargs:
              preserve_path_from = kwargs['preserve_path_from']
              if not isinstance(preserve_path_from, str):
                  raise InvalidArguments('Preserve_path_from must be a string.')
              preserve_path_from = os.path.normpath(preserve_path_from)
              if not os.path.isabs(preserve_path_from):
                  # This is a bit of a hack. Fix properly before merging.
                  raise InvalidArguments('Preserve_path_from must be an absolute path for now. Sorry.')
          else:
              preserve_path_from = None
          gl = self.held_object.process_files('Generator', args, self.interpreter,
                                              preserve_path_from, extra_args=extras)
          return GeneratedListHolder(gl)
  
  
  class GeneratedListHolder(InterpreterObject, ObjectHolder):
      def __init__(self, arg1, extra_args=[]):
          InterpreterObject.__init__(self)
          if isinstance(arg1, GeneratorHolder):
              ObjectHolder.__init__(self, build.GeneratedList(arg1.held_object, extra_args))
          else:
              ObjectHolder.__init__(self, arg1)
  
      def __repr__(self):
          r = '<{}: {!r}>'
          return r.format(self.__class__.__name__, self.held_object.get_outputs())
  
      def add_file(self, a):
          self.held_object.add_file(a)
  
  class BuildMachine(InterpreterObject, ObjectHolder):
      def __init__(self, compilers):
          self.compilers = compilers
          InterpreterObject.__init__(self)
          held_object = environment.MachineInfo(environment.detect_system(),
                                                environment.detect_cpu_family(self.compilers),
                                                environment.detect_cpu(self.compilers),
                                                sys.byteorder)
          ObjectHolder.__init__(self, held_object)
          self.methods.update({'system': self.system_method,
                               'cpu_family': self.cpu_family_method,
                               'cpu': self.cpu_method,
                               'endian': self.endian_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      @noPosargs
      @permittedKwargs({})
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      @noPosargs
      @permittedKwargs({})
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      @noPosargs
      @permittedKwargs({})
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  # This class will provide both host_machine and
  # target_machine
  class CrossMachineInfo(InterpreterObject, ObjectHolder):
      def __init__(self, cross_info):
          InterpreterObject.__init__(self)
          minimum_cross_info = {'cpu', 'cpu_family', 'endian', 'system'}
          if set(cross_info) < minimum_cross_info:
              raise InterpreterException(
                  'Machine info is currently {}\n'.format(cross_info) +
                  'but is missing {}.'.format(minimum_cross_info - set(cross_info)))
          self.info = cross_info
          minfo = environment.MachineInfo(cross_info['system'],
                                          cross_info['cpu_family'],
                                          cross_info['cpu'],
                                          cross_info['endian'])
          ObjectHolder.__init__(self, minfo)
          self.methods.update({'system': self.system_method,
                               'cpu': self.cpu_method,
                               'cpu_family': self.cpu_family_method,
                               'endian': self.endian_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      @noPosargs
      @permittedKwargs({})
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      @noPosargs
      @permittedKwargs({})
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      @noPosargs
      @permittedKwargs({})
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  class IncludeDirsHolder(InterpreterObject, ObjectHolder):
      def __init__(self, idobj):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, idobj)
  
  class Headers(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.install_subdir = kwargs.get('subdir', '')
          self.custom_install_dir = kwargs.get('install_dir', None)
          self.custom_install_mode = kwargs.get('install_mode', None)
          if self.custom_install_dir is not None:
              if not isinstance(self.custom_install_dir, str):
                  raise InterpreterException('Custom_install_dir must be a string.')
  
      def set_install_subdir(self, subdir):
          self.install_subdir = subdir
  
      def get_install_subdir(self):
          return self.install_subdir
  
      def get_sources(self):
          return self.sources
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_custom_install_mode(self):
          return self.custom_install_mode
  
  class DataHolder(InterpreterObject, ObjectHolder):
      def __init__(self, data):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, data)
  
      def get_source_subdir(self):
          return self.held_object.source_subdir
  
      def get_sources(self):
          return self.held_object.sources
  
      def get_install_dir(self):
          return self.held_object.install_dir
  
  class InstallDir(InterpreterObject):
      def __init__(self, src_subdir, inst_subdir, install_dir, install_mode, exclude, strip_directory):
          InterpreterObject.__init__(self)
          self.source_subdir = src_subdir
          self.installable_subdir = inst_subdir
          self.install_dir = install_dir
          self.install_mode = install_mode
          self.exclude = exclude
          self.strip_directory = strip_directory
  
  class Man(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.validate_sources()
          self.custom_install_dir = kwargs.get('install_dir', None)
          self.custom_install_mode = kwargs.get('install_mode', None)
          if self.custom_install_dir is not None and not isinstance(self.custom_install_dir, str):
              raise InterpreterException('Custom_install_dir must be a string.')
  
      def validate_sources(self):
          for s in self.sources:
              try:
                  num = int(s.split('.')[-1])
              except (IndexError, ValueError):
                  num = 0
              if num < 1 or num > 8:
                  raise InvalidArguments('Man file must have a file extension of a number between 1 and 8')
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_custom_install_mode(self):
          return self.custom_install_mode
  
      def get_sources(self):
          return self.sources
  
  class GeneratedObjectsHolder(InterpreterObject, ObjectHolder):
      def __init__(self, held_object):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, held_object)
  
  class TargetHolder(InterpreterObject, ObjectHolder):
      def __init__(self, target, interp):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, target)
          self.interpreter = interp
  
  class BuildTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          self.methods.update({'extract_objects': self.extract_objects_method,
                               'extract_all_objects': self.extract_all_objects_method,
                               'get_id': self.get_id_method,
                               'outdir': self.outdir_method,
                               'full_path': self.full_path_method,
                               'private_dir_include': self.private_dir_include_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.filename)
  
      def is_cross(self):
          return self.held_object.is_cross()
  
      @noPosargs
      @permittedKwargs({})
      def private_dir_include_method(self, args, kwargs):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [self.interpreter.backend.get_target_private_dir(self.held_object)]))
  
      @noPosargs
      @permittedKwargs({})
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      @noPosargs
      @permittedKwargs({})
      def outdir_method(self, args, kwargs):
          return self.interpreter.backend.get_target_dir(self.held_object)
  
      @permittedKwargs({})
      def extract_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_objects(args)
          return GeneratedObjectsHolder(gobjs)
  
      @FeatureNewKwargs('extract_all_objects', '0.46.0', ['recursive'])
      @noPosargs
      @permittedKwargs({'recursive'})
      def extract_all_objects_method(self, args, kwargs):
          recursive = kwargs.get('recursive', False)
          gobjs = self.held_object.extract_all_objects(recursive)
          if gobjs.objlist and 'recursive' not in kwargs:
              mlog.warning('extract_all_objects called without setting recursive '
                           'keyword argument. Meson currently defaults to '
                           'non-recursive to maintain backward compatibility but '
                           'the default will be changed in the future.')
          return GeneratedObjectsHolder(gobjs)
  
      @noPosargs
      @permittedKwargs({})
      def get_id_method(self, args, kwargs):
          return self.held_object.get_id()
  
  class ExecutableHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class StaticLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          # Set to True only when called from self.func_shared_lib().
          target.shared_library_only = False
  
  class BothLibrariesHolder(BuildTargetHolder):
      def __init__(self, shared_holder, static_holder, interp):
          # FIXME: This build target always represents the shared library, but
          # that should be configurable.
          super().__init__(shared_holder.held_object, interp)
          self.shared_holder = shared_holder
          self.static_holder = static_holder
          self.methods.update({'get_shared_lib': self.get_shared_lib_method,
                               'get_static_lib': self.get_static_lib_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}, {}: {}>'
          h1 = self.shared_holder.held_object
          h2 = self.static_holder.held_object
          return r.format(self.__class__.__name__, h1.get_id(), h1.filename, h2.get_id(), h2.filename)
  
      @noPosargs
      @permittedKwargs({})
      def get_shared_lib_method(self, args, kwargs):
          return self.shared_holder
  
      @noPosargs
      @permittedKwargs({})
      def get_static_lib_method(self, args, kwargs):
          return self.static_holder
  
  class SharedModuleHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class JarHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class CustomTargetIndexHolder(InterpreterObject, ObjectHolder):
      def __init__(self, object_to_hold):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, object_to_hold)
  
  class CustomTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          self.methods.update({'full_path': self.full_path_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
      @noPosargs
      @permittedKwargs({})
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      def __getitem__(self, index):
          return CustomTargetIndexHolder(self.held_object[index])
  
      def __setitem__(self, index, value):
          raise InterpreterException('Cannot set a member of a CustomTarget')
  
      def __delitem__(self, index):
          raise InterpreterException('Cannot delete a member of a CustomTarget')
  
      def outdir_include(self):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [os.path.join('@BUILD_ROOT@', self.interpreter.backend.get_target_dir(self.held_object))]))
  
  class RunTargetHolder(InterpreterObject, ObjectHolder):
      def __init__(self, name, command, args, dependencies, subdir, subproject):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.RunTarget(name, command, args, dependencies, subdir, subproject))
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
  class Test(InterpreterObject):
      def __init__(self, name, project, suite, exe, depends, is_parallel,
                   cmd_args, env, should_fail, timeout, workdir):
          InterpreterObject.__init__(self)
          self.name = name
          self.suite = suite
          self.project_name = project
          self.exe = exe
          self.depends = depends
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
  
      def get_exe(self):
          return self.exe
  
      def get_name(self):
          return self.name
  
  class SubprojectHolder(InterpreterObject, ObjectHolder):
  
      def __init__(self, subinterpreter):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, subinterpreter)
          self.methods.update({'get_variable': self.get_variable_method,
                               })
  
      @permittedKwargs({})
      def get_variable_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Get_variable takes one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Get_variable takes a string argument.')
          if varname not in self.held_object.variables:
              raise InvalidArguments('Requested variable "{0}" not found.'.format(varname))
          return self.held_object.variables[varname]
  
  class CompilerHolder(InterpreterObject):
      def __init__(self, compiler, env):
          InterpreterObject.__init__(self)
          self.compiler = compiler
          self.environment = env
          self.methods.update({'compiles': self.compiles_method,
                               'links': self.links_method,
                               'get_id': self.get_id_method,
                               'compute_int': self.compute_int_method,
                               'sizeof': self.sizeof_method,
                               'get_define': self.get_define_method,
                               'check_header': self.check_header_method,
                               'has_header': self.has_header_method,
                               'has_header_symbol': self.has_header_symbol_method,
                               'run': self.run_method,
                               'has_function': self.has_function_method,
                               'has_member': self.has_member_method,
                               'has_members': self.has_members_method,
                               'has_type': self.has_type_method,
                               'alignment': self.alignment_method,
                               'version': self.version_method,
                               'cmd_array': self.cmd_array_method,
                               'find_library': self.find_library_method,
                               'has_argument': self.has_argument_method,
                               'has_multi_arguments': self.has_multi_arguments_method,
                               'get_supported_arguments': self.get_supported_arguments_method,
                               'first_supported_argument': self.first_supported_argument_method,
                               'has_link_argument': self.has_link_argument_method,
                               'has_multi_link_arguments': self.has_multi_link_arguments_method,
                               'get_supported_link_arguments': self.get_supported_link_arguments_method,
                               'first_supported_link_argument': self.first_supported_link_argument_method,
                               'unittest_args': self.unittest_args_method,
                               'symbols_have_underscore_prefix': self.symbols_have_underscore_prefix_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.compiler.version
  
      @noPosargs
      @permittedKwargs({})
      def cmd_array_method(self, args, kwargs):
          return self.compiler.exelist
  
      def determine_args(self, kwargs):
          nobuiltins = kwargs.get('no_builtin_args', False)
          if not isinstance(nobuiltins, bool):
              raise InterpreterException('Type of no_builtin_args not a boolean.')
          args = []
          incdirs = extract_as_list(kwargs, 'include_directories')
          for i in incdirs:
              if not isinstance(i, IncludeDirsHolder):
                  raise InterpreterException('Include directories argument must be an include_directories object.')
              for idir in i.held_object.get_incdirs():
                  idir = os.path.join(self.environment.get_source_dir(),
                                      i.held_object.get_curdir(), idir)
                  args += self.compiler.get_include_args(idir, False)
          if not nobuiltins:
              opts = self.environment.coredata.compiler_options
              args += self.compiler.get_option_compile_args(opts)
              args += self.compiler.get_option_link_args(opts)
          args += mesonlib.stringlistify(kwargs.get('args', []))
          return args
  
      def determine_dependencies(self, kwargs):
          deps = kwargs.get('dependencies', None)
          if deps is not None:
              deps = listify(deps)
              final_deps = []
              for d in deps:
                  try:
                      d = d.held_object
                  except Exception:
                      pass
                  if isinstance(d, InternalDependency) or not isinstance(d, Dependency):
                      raise InterpreterException('Dependencies must be external dependencies')
                  final_deps.append(d)
              deps = final_deps
          return deps
  
      @permittedKwargs({
          'prefix',
          'args',
          'dependencies',
      })
      def alignment_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Alignment method takes exactly one positional argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = mesonlib.stringlistify(kwargs.get('args', []))
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.alignment(typename, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for alignment of "', mlog.bold(typename), '": ', result, sep='')
          return result
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def run_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Run method takes exactly one positional argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.run(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if not result.compiled:
                  h = mlog.red('DID NOT COMPILE')
              elif result.returncode == 0:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO (%d)' % result.returncode)
              mlog.log('Checking if "', mlog.bold(testname), '" runs: ', h, sep='')
          return TryRunResultHolder(result)
  
      @noPosargs
      @permittedKwargs({})
      def get_id_method(self, args, kwargs):
          return self.compiler.get_id()
  
      @noPosargs
      @permittedKwargs({})
      def symbols_have_underscore_prefix_method(self, args, kwargs):
          '''
          Check if the compiler prefixes _ (underscore) to global C symbols
          See: https://en.wikipedia.org/wiki/Name_mangling#C
          '''
          return self.compiler.symbols_have_underscore_prefix(self.environment)
  
      @noPosargs
      @permittedKwargs({})
      def unittest_args_method(self, args, kwargs):
          '''
          This function is deprecated and should not be used.
          It can be removed in a future version of Meson.
          '''
          if not hasattr(self.compiler, 'get_feature_args'):
              raise InterpreterException('This {} compiler has no feature arguments.'.format(self.compiler.get_display_language()))
          build_to_src = os.path.relpath(self.environment.get_source_dir(), self.environment.get_build_dir())
          return self.compiler.get_feature_args({'unittest': 'true'}, build_to_src)
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_member_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Has_member takes exactly two arguments.')
          check_stringlist(args)
          typename = args[0]
          membername = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_member must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, [membername], prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has member "', mlog.bold(membername), '": ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_members_method(self, args, kwargs):
          if len(args) < 2:
              raise InterpreterException('Has_members needs at least two arguments.')
          check_stringlist(args)
          typename = args[0]
          membernames = args[1:]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_members must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, membernames, prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          members = mlog.bold(', '.join(['"{}"'.format(m) for m in membernames]))
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has members ', members, ': ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_function_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_function takes exactly one argument.')
          check_stringlist(args)
          funcname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_function must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_function(funcname, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for function "', mlog.bold(funcname), '": ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_type_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_type takes exactly one argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_type must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_type(typename, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for type "', mlog.bold(typename), '": ', hadtxt, sep='')
          return had
  
      @FeatureNew('compiler.compute_int', '0.40.0')
      @permittedKwargs({
          'prefix',
          'low',
          'high',
          'guess',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def compute_int_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Compute_int takes exactly one argument.')
          check_stringlist(args)
          expression = args[0]
          prefix = kwargs.get('prefix', '')
          low = kwargs.get('low', None)
          high = kwargs.get('high', None)
          guess = kwargs.get('guess', None)
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of compute_int must be a string.')
          if low is not None and not isinstance(low, int):
              raise InterpreterException('Low argument of compute_int must be an int.')
          if high is not None and not isinstance(high, int):
              raise InterpreterException('High argument of compute_int must be an int.')
          if guess is not None and not isinstance(guess, int):
              raise InterpreterException('Guess argument of compute_int must be an int.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          res = self.compiler.compute_int(expression, low, high, guess, prefix, self.environment, extra_args, deps)
          mlog.log('Computing int of "%s": %d' % (expression, res))
          return res
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def sizeof_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Sizeof takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          esize = self.compiler.sizeof(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for size of "%s": %d' % (element, esize))
          return esize
  
      @FeatureNew('compiler.get_define', '0.40.0')
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def get_define_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_define() takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of get_define() must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          value = self.compiler.get_define(element, prefix, self.environment, extra_args, deps)
          mlog.log('Fetching value of define "%s": %s' % (element, value))
          return value
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def compiles_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('compiles method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.compiles(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" compiles: ', h, sep='')
          return result
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def links_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('links method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.links(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" links: ', h, sep='')
          return result
  
      @FeatureNew('check_header', '0.47.0')
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def check_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('check_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.check_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Check usable header "%s":' % hname, h)
          return haz
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('has_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Has header "%s":' % hname, h)
          return haz
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_header_symbol_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('has_header_symbol method takes exactly two arguments.')
          check_stringlist(args)
          hname = args[0]
          symbol = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header_symbol must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header_symbol(hname, symbol, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Header <{0}> has symbol "{1}":'.format(hname, symbol), h)
          return haz
  
      @permittedKwargs({
          'required',
          'dirs',
      })
      def find_library_method(self, args, kwargs):
          # TODO add dependencies support?
          if len(args) != 1:
              raise InterpreterException('find_library method takes one argument.')
          libname = args[0]
          if not isinstance(libname, str):
              raise InterpreterException('Library name not a string.')
  
          disabled, required, feature = extract_required_kwarg(kwargs)
          if disabled:
              mlog.log('Library', mlog.bold(libname), 'skipped: feature', mlog.bold(feature), 'disabled')
              lib = dependencies.ExternalLibrary(libname, None,
                                                 self.environment,
                                                 self.compiler.language,
                                                 silent=True)
              return ExternalLibraryHolder(lib)
  
          search_dirs = mesonlib.stringlistify(kwargs.get('dirs', []))
          for i in search_dirs:
              if not os.path.isabs(i):
                  raise InvalidCode('Search directory %s is not an absolute path.' % i)
          linkargs = self.compiler.find_library(libname, self.environment, search_dirs)
          if required and not linkargs:
              raise InterpreterException('{} library {!r} not found'.format(self.compiler.get_display_language(), libname))
          lib = dependencies.ExternalLibrary(libname, linkargs, self.environment,
                                             self.compiler.language)
          return ExternalLibraryHolder(lib)
  
      @permittedKwargs({})
      def has_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('has_argument takes exactly one argument.')
          return self.has_multi_arguments_method(args, kwargs)
  
      @permittedKwargs({})
      def has_multi_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports arguments {}:'.format(
                  self.compiler.get_display_language(), ' '.join(args)),
              h)
          return result
  
      @FeatureNew('compiler.get_supported_arguments', '0.43.0')
      @permittedKwargs({})
      def get_supported_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          supported_args = []
          for arg in args:
              if self.has_argument_method(arg, kwargs):
                  supported_args.append(arg)
          return supported_args
  
      @permittedKwargs({})
      def first_supported_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.has_argument_method(i, kwargs):
                  mlog.log('First supported argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported argument:', mlog.red('None'))
          return []
  
      @FeatureNew('has_link_argument', '0.46.0')
      @permittedKwargs({})
      def has_link_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('has_link_argument takes exactly one argument.')
          return self.has_multi_link_arguments_method(args, kwargs)
  
      @FeatureNew('has_multi_link_argument', '0.46.0')
      @permittedKwargs({})
      def has_multi_link_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_link_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports link arguments {}:'.format(
                  self.compiler.get_display_language(), ' '.join(args)),
              h)
          return result
  
      @FeatureNew('get_supported_link_arguments_method', '0.46.0')
      @permittedKwargs({})
      def get_supported_link_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          supported_args = []
          for arg in args:
              if self.has_link_argument_method(arg, kwargs):
                  supported_args.append(arg)
          return supported_args
  
      @FeatureNew('first_supported_link_argument_method', '0.46.0')
      @permittedKwargs({})
      def first_supported_link_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.has_link_argument_method(i, kwargs):
                  mlog.log('First supported link argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported link argument:', mlog.red('None'))
          return []
  
  ModuleState = namedtuple('ModuleState', [
      'build_to_src', 'subproject', 'subdir', 'current_lineno', 'environment',
      'project_name', 'project_version', 'backend', 'compilers', 'targets',
      'data', 'headers', 'man', 'global_args', 'project_args', 'build_machine',
      'host_machine', 'target_machine'])
  
  class ModuleHolder(InterpreterObject, ObjectHolder):
      def __init__(self, modname, module, interpreter):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, module)
          self.modname = modname
          self.interpreter = interpreter
  
      def method_call(self, method_name, args, kwargs):
          try:
              fn = getattr(self.held_object, method_name)
          except AttributeError:
              raise InvalidArguments('Module %s does not have method %s.' % (self.modname, method_name))
          if method_name.startswith('_'):
              raise InvalidArguments('Function {!r} in module {!r} is private.'.format(method_name, self.modname))
          if not getattr(fn, 'no-args-flattening', False):
              args = flatten(args)
          # This is not 100% reliable but we can't use hash()
          # because the Build object contains dicts and lists.
          num_targets = len(self.interpreter.build.targets)
          state = ModuleState(
              build_to_src=os.path.relpath(self.interpreter.environment.get_source_dir(),
                                           self.interpreter.environment.get_build_dir()),
              subproject=self.interpreter.subproject,
              subdir=self.interpreter.subdir,
              current_lineno=self.interpreter.current_lineno,
              environment=self.interpreter.environment,
              project_name=self.interpreter.build.project_name,
              project_version=self.interpreter.build.dep_manifest[self.interpreter.active_projectname],
              # The backend object is under-used right now, but we will need it:
              # https://github.com/mesonbuild/meson/issues/1419
              backend=self.interpreter.backend,
              compilers=self.interpreter.build.compilers,
              targets=self.interpreter.build.targets,
              data=self.interpreter.build.data,
              headers=self.interpreter.build.get_headers(),
              man=self.interpreter.build.get_man(),
              global_args=self.interpreter.build.global_args,
              project_args=self.interpreter.build.projects_args.get(self.interpreter.subproject, {}),
              build_machine=self.interpreter.builtin['build_machine'].held_object,
              host_machine=self.interpreter.builtin['host_machine'].held_object,
              target_machine=self.interpreter.builtin['target_machine'].held_object,
          )
          if self.held_object.is_snippet(method_name):
              value = fn(self.interpreter, state, args, kwargs)
              return self.interpreter.holderify(value)
          else:
              value = fn(state, args, kwargs)
              if num_targets != len(self.interpreter.build.targets):
                  raise InterpreterException('Extension module altered internal state illegally.')
              return self.interpreter.module_method_callback(value)
  
  class MesonMain(InterpreterObject):
      def __init__(self, build, interpreter):
          InterpreterObject.__init__(self)
          self.build = build
          self.interpreter = interpreter
          self._found_source_scripts = {}
          self.methods.update({'get_compiler': self.get_compiler_method,
                               'is_cross_build': self.is_cross_build_method,
                               'has_exe_wrapper': self.has_exe_wrapper_method,
                               'is_unity': self.is_unity_method,
                               'is_subproject': self.is_subproject_method,
                               'current_source_dir': self.current_source_dir_method,
                               'current_build_dir': self.current_build_dir_method,
                               'source_root': self.source_root_method,
                               'build_root': self.build_root_method,
                               'add_install_script': self.add_install_script_method,
                               'add_postconf_script': self.add_postconf_script_method,
                               'install_dependency_manifest': self.install_dependency_manifest_method,
                               'override_find_program': self.override_find_program_method,
                               'project_version': self.project_version_method,
                               'project_license': self.project_license_method,
                               'version': self.version_method,
                               'project_name': self.project_name_method,
                               'get_cross_property': self.get_cross_property_method,
                               'backend': self.backend_method,
                               })
  
      def _find_source_script(self, name, args):
          # Prefer scripts in the current source directory
          search_dir = os.path.join(self.interpreter.environment.source_dir,
                                    self.interpreter.subdir)
          key = (name, search_dir)
          if key in self._found_source_scripts:
              found = self._found_source_scripts[key]
          else:
              found = dependencies.ExternalProgram(name, search_dir=search_dir)
              if found.found():
                  self._found_source_scripts[key] = found
              else:
                  m = 'Script or command {!r} not found or not executable'
                  raise InterpreterException(m.format(name))
          return build.RunScript(found.get_command(), args)
  
      @permittedKwargs({})
      def add_install_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_install_script takes one or more arguments')
          check_stringlist(args, 'add_install_script args must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.install_scripts.append(script)
  
      @permittedKwargs({})
      def add_postconf_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_postconf_script takes one or more arguments')
          check_stringlist(args, 'add_postconf_script arguments must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.postconf_scripts.append(script)
  
      @noPosargs
      @permittedKwargs({})
      def current_source_dir_method(self, args, kwargs):
          src = self.interpreter.environment.source_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      @noPosargs
      @permittedKwargs({})
      def current_build_dir_method(self, args, kwargs):
          src = self.interpreter.environment.build_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      @noPosargs
      @permittedKwargs({})
      def backend_method(self, args, kwargs):
          return self.interpreter.backend.name
  
      @noPosargs
      @permittedKwargs({})
      def source_root_method(self, args, kwargs):
          return self.interpreter.environment.source_dir
  
      @noPosargs
      @permittedKwargs({})
      def build_root_method(self, args, kwargs):
          return self.interpreter.environment.build_dir
  
      @noPosargs
      @permittedKwargs({})
      def has_exe_wrapper_method(self, args, kwargs):
          if self.is_cross_build_method(None, None) and \
             'binaries' in self.build.environment.cross_info.config and \
             self.build.environment.cross_info.need_exe_wrapper():
              exe_wrap = self.build.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              if exe_wrap is None:
                  return False
          # We return True when exe_wrap is defined, when it's not needed, and
          # when we're compiling natively. The last two are semantically confusing.
          # Need to revisit this.
          return True
  
      @noPosargs
      @permittedKwargs({})
      def is_cross_build_method(self, args, kwargs):
          return self.build.environment.is_cross_build()
  
      @permittedKwargs({'native'})
      def get_compiler_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_compiler_method must have one and only one argument.')
          cname = args[0]
          native = kwargs.get('native', None)
          if native is None:
              if self.build.environment.is_cross_build():
                  native = False
              else:
                  native = True
          if not isinstance(native, bool):
              raise InterpreterException('Type of "native" must be a boolean.')
          if native:
              clist = self.build.compilers
          else:
              clist = self.build.cross_compilers
          if cname in clist:
              return CompilerHolder(clist[cname], self.build.environment)
          raise InterpreterException('Tried to access compiler for unspecified language "%s".' % cname)
  
      @noPosargs
      @permittedKwargs({})
      def is_unity_method(self, args, kwargs):
          optval = self.interpreter.environment.coredata.get_builtin_option('unity')
          if optval == 'on' or (optval == 'subprojects' and self.interpreter.subproject != ''):
              return True
          return False
  
      @noPosargs
      @permittedKwargs({})
      def is_subproject_method(self, args, kwargs):
          return self.interpreter.is_subproject()
  
      @permittedKwargs({})
      def install_dependency_manifest_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Must specify manifest install file name')
          if not isinstance(args[0], str):
              raise InterpreterException('Argument must be a string.')
          self.build.dep_manifest_name = args[0]
  
      @FeatureNew('override_find_program', '0.46.0')
      @permittedKwargs({})
      def override_find_program_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Override needs two arguments')
          name = args[0]
          exe = args[1]
          if not isinstance(name, str):
              raise InterpreterException('First argument must be a string')
          if hasattr(exe, 'held_object'):
              exe = exe.held_object
          if isinstance(exe, mesonlib.File):
              abspath = exe.absolute_path(self.interpreter.environment.source_dir,
                                          self.interpreter.environment.build_dir)
              if not os.path.exists(abspath):
                  raise InterpreterException('Tried to override %s with a file that does not exist.' % name)
              exe = dependencies.ExternalProgram(abspath)
          if not isinstance(exe, dependencies.ExternalProgram):
              # FIXME, make this
  
  [... the rest is omitted ...]
files: mesonbuild/interpreter.py
files: # Copyright 2012-2018 The Meson development team
  # Licensed under the Apache License, Version 2.0 (the "License");
  # you may not use this file except in compliance with the License.
  # You may obtain a copy of the License at
  
  #     http://www.apache.org/licenses/LICENSE-2.0
  
  # Unless required by applicable law or agreed to in writing, software
  # distributed under the License is distributed on an "AS IS" BASIS,
  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  # See the License for the specific language governing permissions and
  # limitations under the License.
  
  from . import mparser
  from . import environment
  from . import coredata
  from . import dependencies
  from . import mlog
  from . import build
  from . import optinterpreter
  from . import compilers
  from .wrap import wrap, WrapMode
  from . import mesonlib
  from .mesonlib import FileMode, Popen_safe, listify, extract_as_list, has_path_sep
  from .dependencies import ExternalProgram
  from .dependencies import InternalDependency, Dependency, NotFoundDependency, DependencyException
  from .interpreterbase import InterpreterBase
  from .interpreterbase import check_stringlist, flatten, noPosargs, noKwargs, stringArgs, permittedKwargs, noArgsFlattening
  from .interpreterbase import InterpreterException, InvalidArguments, InvalidCode, SubdirDoneRequest
  from .interpreterbase import InterpreterObject, MutableInterpreterObject, Disabler
  from .interpreterbase import FeatureNew, FeatureDeprecated, FeatureNewKwargs
  from .modules import ModuleReturnValue
  
  import os, sys, shutil, uuid
  import re, shlex
  import subprocess
  from collections import namedtuple
  from pathlib import PurePath
  
  import importlib
  
  permitted_method_kwargs = {
      'partial_dependency': {'compile_args', 'link_args', 'links', 'includes',
                             'sources'},
  }
  
  def stringifyUserArguments(args):
      if isinstance(args, list):
          return '[%s]' % ', '.join([stringifyUserArguments(x) for x in args])
      elif isinstance(args, dict):
          return '{%s}' % ', '.join(['%s : %s' % (stringifyUserArguments(k), stringifyUserArguments(v)) for k, v in args.items()])
      elif isinstance(args, int):
          return str(args)
      elif isinstance(args, str):
          return "'%s'" % args
      raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
  
  class ObjectHolder:
      def __init__(self, obj):
          self.held_object = obj
  
      def __repr__(self):
          return '<Holder: {!r}>'.format(self.held_object)
  
  class FeatureOptionHolder(InterpreterObject, ObjectHolder):
      def __init__(self, env, option):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, option)
          if option.is_auto():
              self.held_object = env.coredata.builtins['auto_features']
          self.name = option.name
          self.methods.update({'enabled': self.enabled_method,
                               'disabled': self.disabled_method,
                               'auto': self.auto_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def enabled_method(self, args, kwargs):
          return self.held_object.is_enabled()
  
      @noPosargs
      @permittedKwargs({})
      def disabled_method(self, args, kwargs):
          return self.held_object.is_disabled()
  
      @noPosargs
      @permittedKwargs({})
      def auto_method(self, args, kwargs):
          return self.held_object.is_auto()
  
  def extract_required_kwarg(kwargs):
      val = kwargs.get('required', True)
      disabled = False
      required = False
      feature = None
      if isinstance(val, FeatureOptionHolder):
          option = val.held_object
          feature = val.name
          if option.is_disabled():
              disabled = True
          elif option.is_enabled():
              required = True
      elif isinstance(required, bool):
          required = val
      else:
          raise InterpreterException('required keyword argument must be boolean or a feature option')
  
      # Keep boolean value in kwargs to simplify other places where this kwarg is
      # checked.
      kwargs['required'] = required
  
      return disabled, required, feature
  
  class TryRunResultHolder(InterpreterObject):
      def __init__(self, res):
          super().__init__()
          self.res = res
          self.methods.update({'returncode': self.returncode_method,
                               'compiled': self.compiled_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def returncode_method(self, args, kwargs):
          return self.res.returncode
  
      @noPosargs
      @permittedKwargs({})
      def compiled_method(self, args, kwargs):
          return self.res.compiled
  
      @noPosargs
      @permittedKwargs({})
      def stdout_method(self, args, kwargs):
          return self.res.stdout
  
      @noPosargs
      @permittedKwargs({})
      def stderr_method(self, args, kwargs):
          return self.res.stderr
  
  class RunProcess(InterpreterObject):
  
      def __init__(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir=False, check=False, capture=True):
          super().__init__()
          if not isinstance(cmd, ExternalProgram):
              raise AssertionError('BUG: RunProcess must be passed an ExternalProgram')
          self.capture = capture
          pc, self.stdout, self.stderr = self.run_command(cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir, check)
          self.returncode = pc.returncode
          self.methods.update({'returncode': self.returncode_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def run_command(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir, check=False):
          command_array = cmd.get_command() + args
          env = {'MESON_SOURCE_ROOT': source_dir,
                 'MESON_BUILD_ROOT': build_dir,
                 'MESON_SUBDIR': subdir,
                 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in mesonintrospect]),
                 }
          if in_builddir:
              cwd = os.path.join(build_dir, subdir)
          else:
              cwd = os.path.join(source_dir, subdir)
          child_env = os.environ.copy()
          child_env.update(env)
          stdout = subprocess.PIPE if self.capture else subprocess.DEVNULL
          mlog.debug('Running command:', ' '.join(command_array))
          try:
              p, o, e = Popen_safe(command_array, stdout=stdout, env=child_env, cwd=cwd)
              if self.capture:
                  mlog.debug('--- stdout ---')
                  mlog.debug(o)
              else:
                  o = ''
                  mlog.debug('--- stdout disabled ---')
              mlog.debug('--- stderr ---')
              mlog.debug(e)
              mlog.debug('')
  
              if check and p.returncode != 0:
                  raise InterpreterException('Command "{}" failed with status {}.'.format(' '.join(command_array), p.returncode))
  
              return p, o, e
          except FileNotFoundError:
              raise InterpreterException('Could not execute command "%s".' % ' '.join(command_array))
  
      @noPosargs
      @permittedKwargs({})
      def returncode_method(self, args, kwargs):
          return self.returncode
  
      @noPosargs
      @permittedKwargs({})
      def stdout_method(self, args, kwargs):
          return self.stdout
  
      @noPosargs
      @permittedKwargs({})
      def stderr_method(self, args, kwargs):
          return self.stderr
  
  class ConfigureFileHolder(InterpreterObject, ObjectHolder):
  
      def __init__(self, subdir, sourcename, targetname, configuration_data):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.ConfigureFile(subdir, sourcename,
                                                          targetname, configuration_data))
  
  
  class EnvironmentVariablesHolder(MutableInterpreterObject, ObjectHolder):
      def __init__(self):
          MutableInterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.EnvironmentVariables())
          self.methods.update({'set': self.set_method,
                               'append': self.append_method,
                               'prepend': self.prepend_method,
                               })
  
      def __repr__(self):
          repr_str = "<{0}: {1}>"
          return repr_str.format(self.__class__.__name__, self.held_object.envvars)
  
      def add_var(self, method, args, kwargs):
          if not isinstance(kwargs.get("separator", ""), str):
              raise InterpreterException("EnvironmentVariablesHolder methods 'separator'"
                                         " argument needs to be a string.")
          if len(args) < 2:
              raise InterpreterException("EnvironmentVariablesHolder methods require at least"
                                         "2 arguments, first is the name of the variable and"
                                         " following one are values")
          self.held_object.envvars.append((method, args[0], args[1:], kwargs))
  
      @stringArgs
      @permittedKwargs({'separator'})
      def set_method(self, args, kwargs):
          self.add_var(self.held_object.set, args, kwargs)
  
      @stringArgs
      @permittedKwargs({'separator'})
      def append_method(self, args, kwargs):
          self.add_var(self.held_object.append, args, kwargs)
  
      @stringArgs
      @permittedKwargs({'separator'})
      def prepend_method(self, args, kwargs):
          self.add_var(self.held_object.prepend, args, kwargs)
  
  
  class ConfigurationDataHolder(MutableInterpreterObject, ObjectHolder):
      def __init__(self):
          MutableInterpreterObject.__init__(self)
          self.used = False # These objects become immutable after use in configure_file.
          ObjectHolder.__init__(self, build.ConfigurationData())
          self.methods.update({'set': self.set_method,
                               'set10': self.set10_method,
                               'set_quoted': self.set_quoted_method,
                               'has': self.has_method,
                               'get': self.get_method,
                               'get_unquoted': self.get_unquoted_method,
                               'merge_from': self.merge_from_method,
                               })
  
      def is_used(self):
          return self.used
  
      def mark_used(self):
          self.used = True
  
      def validate_args(self, args, kwargs):
          if len(args) == 1 and isinstance(args[0], list) and len(args[0]) == 2:
              mlog.log(mlog.red('DEPRECATION:'),
                       '''Passing a list as the single argument to configuration_data.set is deprecated.
  This will become a hard error in the future''')
              args = args[0]
  
          if len(args) != 2:
              raise InterpreterException("Configuration set requires 2 arguments.")
          if self.used:
              raise InterpreterException("Can not set values on configuration object that has been used.")
          name = args[0]
          val = args[1]
          desc = kwargs.get('description', None)
          if not isinstance(name, str):
              raise InterpreterException("First argument to set must be a string.")
          if desc is not None and not isinstance(desc, str):
              raise InterpreterException('Description must be a string.')
  
          return name, val, desc
  
      @noArgsFlattening
      def set_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          self.held_object.values[name] = (val, desc)
  
      def set_quoted_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if not isinstance(val, str):
              raise InterpreterException("Second argument to set_quoted must be a string.")
          escaped_val = '\\"'.join(val.split('"'))
          self.held_object.values[name] = ('"' + escaped_val + '"', desc)
  
      def set10_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if val:
              self.held_object.values[name] = (1, desc)
          else:
              self.held_object.values[name] = (0, desc)
  
      def has_method(self, args, kwargs):
          return args[0] in self.held_object.values
  
      @FeatureNew('configuration_data.get()', '0.38.0')
      @noArgsFlattening
      def get_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              return self.held_object.get(name)[0]
          if len(args) > 1:
              return args[1]
          raise InterpreterException('Entry %s not in configuration data.' % name)
  
      @FeatureNew('get_unquoted', '0.44.0')
      def get_unquoted_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              val = self.held_object.get(name)[0]
          elif len(args) > 1:
              val = args[1]
          else:
              raise InterpreterException('Entry %s not in configuration data.' % name)
          if val[0] == '"' and val[-1] == '"':
              return val[1:-1]
          return val
  
      def get(self, name):
          return self.held_object.values[name] # (val, desc)
  
      def keys(self):
          return self.held_object.values.keys()
  
      def merge_from_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Merge_from takes one positional argument.')
          from_object = args[0]
          if not isinstance(from_object, ConfigurationDataHolder):
              raise InterpreterException('Merge_from argument must be a configuration data object.')
          from_object = from_object.held_object
          for k, v in from_object.values.items():
              self.held_object.values[k] = v
  
  # Interpreter objects can not be pickled so we must have
  # these wrappers.
  
  class DependencyHolder(InterpreterObject, ObjectHolder):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, dep)
          self.methods.update({'found': self.found_method,
                               'type_name': self.type_name_method,
                               'version': self.version_method,
                               'get_pkgconfig_variable': self.pkgconfig_method,
                               'get_configtool_variable': self.configtool_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def type_name_method(self, args, kwargs):
          return self.held_object.type_name
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          if self.held_object.type_name == 'internal':
              return True
          return self.held_object.found()
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      @permittedKwargs({'define_variable'})
      def pkgconfig_method(self, args, kwargs):
          args = listify(args)
          if len(args) != 1:
              raise InterpreterException('get_pkgconfig_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_pkgconfig_variable(varname, kwargs)
  
      @FeatureNew('get_configtool_variable', '0.44.0')
      @permittedKwargs({})
      def configtool_method(self, args, kwargs):
          args = listify(args)
          if len(args) != 1:
              raise InterpreterException('get_configtool_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_configtool_variable(varname)
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class InternalDependencyHolder(InterpreterObject, ObjectHolder):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, dep)
          self.methods.update({'found': self.found_method,
                               'version': self.version_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return True
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class ExternalProgramHolder(InterpreterObject, ObjectHolder):
      def __init__(self, ep):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, ep)
          self.methods.update({'found': self.found_method,
                               'path': self.path_method})
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return self.found()
  
      @noPosargs
      @permittedKwargs({})
      def path_method(self, args, kwargs):
          return self.held_object.get_path()
  
      def found(self):
          return self.held_object.found()
  
      def get_command(self):
          return self.held_object.get_command()
  
      def get_name(self):
          return self.held_object.get_name()
  
  class ExternalLibraryHolder(InterpreterObject, ObjectHolder):
      def __init__(self, el):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, el)
          self.methods.update({'found': self.found_method,
                               'partial_dependency': self.partial_dependency_method,
                               })
  
      def found(self):
          return self.held_object.found()
  
      @noPosargs
      @permittedKwargs({})
      def found_method(self, args, kwargs):
          return self.found()
  
      def get_name(self):
          return self.held_object.name
  
      def get_compile_args(self):
          return self.held_object.get_compile_args()
  
      def get_link_args(self):
          return self.held_object.get_link_args()
  
      def get_exe_args(self):
          return self.held_object.get_exe_args()
  
      @FeatureNew('dep.partial_dependency', '0.46.0')
      @noPosargs
      @permittedKwargs(permitted_method_kwargs['partial_dependency'])
      def partial_dependency_method(self, args, kwargs):
          return DependencyHolder(self.held_object.get_partial_dependency(**kwargs))
  
  class GeneratorHolder(InterpreterObject, ObjectHolder):
      def __init__(self, interpreter, args, kwargs):
          InterpreterObject.__init__(self)
          self.interpreter = interpreter
          ObjectHolder.__init__(self, build.Generator(args, kwargs))
          self.methods.update({'process': self.process_method})
  
      @FeatureNewKwargs('generator.process', '0.45.0', ['preserve_path_from'])
      @permittedKwargs({'extra_args', 'preserve_path_from'})
      def process_method(self, args, kwargs):
          extras = mesonlib.stringlistify(kwargs.get('extra_args', []))
          if 'preserve_path_from' in kwargs:
              preserve_path_from = kwargs['preserve_path_from']
              if not isinstance(preserve_path_from, str):
                  raise InvalidArguments('Preserve_path_from must be a string.')
              preserve_path_from = os.path.normpath(preserve_path_from)
              if not os.path.isabs(preserve_path_from):
                  # This is a bit of a hack. Fix properly before merging.
                  raise InvalidArguments('Preserve_path_from must be an absolute path for now. Sorry.')
          else:
              preserve_path_from = None
          gl = self.held_object.process_files('Generator', args, self.interpreter,
                                              preserve_path_from, extra_args=extras)
          return GeneratedListHolder(gl)
  
  
  class GeneratedListHolder(InterpreterObject, ObjectHolder):
      def __init__(self, arg1, extra_args=[]):
          InterpreterObject.__init__(self)
          if isinstance(arg1, GeneratorHolder):
              ObjectHolder.__init__(self, build.GeneratedList(arg1.held_object, extra_args))
          else:
              ObjectHolder.__init__(self, arg1)
  
      def __repr__(self):
          r = '<{}: {!r}>'
          return r.format(self.__class__.__name__, self.held_object.get_outputs())
  
      def add_file(self, a):
          self.held_object.add_file(a)
  
  class BuildMachine(InterpreterObject, ObjectHolder):
      def __init__(self, compilers):
          self.compilers = compilers
          InterpreterObject.__init__(self)
          held_object = environment.MachineInfo(environment.detect_system(),
                                                environment.detect_cpu_family(self.compilers),
                                                environment.detect_cpu(self.compilers),
                                                sys.byteorder)
          ObjectHolder.__init__(self, held_object)
          self.methods.update({'system': self.system_method,
                               'cpu_family': self.cpu_family_method,
                               'cpu': self.cpu_method,
                               'endian': self.endian_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      @noPosargs
      @permittedKwargs({})
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      @noPosargs
      @permittedKwargs({})
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      @noPosargs
      @permittedKwargs({})
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  # This class will provide both host_machine and
  # target_machine
  class CrossMachineInfo(InterpreterObject, ObjectHolder):
      def __init__(self, cross_info):
          InterpreterObject.__init__(self)
          minimum_cross_info = {'cpu', 'cpu_family', 'endian', 'system'}
          if set(cross_info) < minimum_cross_info:
              raise InterpreterException(
                  'Machine info is currently {}\n'.format(cross_info) +
                  'but is missing {}.'.format(minimum_cross_info - set(cross_info)))
          self.info = cross_info
          minfo = environment.MachineInfo(cross_info['system'],
                                          cross_info['cpu_family'],
                                          cross_info['cpu'],
                                          cross_info['endian'])
          ObjectHolder.__init__(self, minfo)
          self.methods.update({'system': self.system_method,
                               'cpu': self.cpu_method,
                               'cpu_family': self.cpu_family_method,
                               'endian': self.endian_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      @noPosargs
      @permittedKwargs({})
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      @noPosargs
      @permittedKwargs({})
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      @noPosargs
      @permittedKwargs({})
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  class IncludeDirsHolder(InterpreterObject, ObjectHolder):
      def __init__(self, idobj):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, idobj)
  
  class Headers(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.install_subdir = kwargs.get('subdir', '')
          self.custom_install_dir = kwargs.get('install_dir', None)
          self.custom_install_mode = kwargs.get('install_mode', None)
          if self.custom_install_dir is not None:
              if not isinstance(self.custom_install_dir, str):
                  raise InterpreterException('Custom_install_dir must be a string.')
  
      def set_install_subdir(self, subdir):
          self.install_subdir = subdir
  
      def get_install_subdir(self):
          return self.install_subdir
  
      def get_sources(self):
          return self.sources
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_custom_install_mode(self):
          return self.custom_install_mode
  
  class DataHolder(InterpreterObject, ObjectHolder):
      def __init__(self, data):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, data)
  
      def get_source_subdir(self):
          return self.held_object.source_subdir
  
      def get_sources(self):
          return self.held_object.sources
  
      def get_install_dir(self):
          return self.held_object.install_dir
  
  class InstallDir(InterpreterObject):
      def __init__(self, src_subdir, inst_subdir, install_dir, install_mode, exclude, strip_directory):
          InterpreterObject.__init__(self)
          self.source_subdir = src_subdir
          self.installable_subdir = inst_subdir
          self.install_dir = install_dir
          self.install_mode = install_mode
          self.exclude = exclude
          self.strip_directory = strip_directory
  
  class Man(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.validate_sources()
          self.custom_install_dir = kwargs.get('install_dir', None)
          self.custom_install_mode = kwargs.get('install_mode', None)
          if self.custom_install_dir is not None and not isinstance(self.custom_install_dir, str):
              raise InterpreterException('Custom_install_dir must be a string.')
  
      def validate_sources(self):
          for s in self.sources:
              try:
                  num = int(s.split('.')[-1])
              except (IndexError, ValueError):
                  num = 0
              if num < 1 or num > 8:
                  raise InvalidArguments('Man file must have a file extension of a number between 1 and 8')
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_custom_install_mode(self):
          return self.custom_install_mode
  
      def get_sources(self):
          return self.sources
  
  class GeneratedObjectsHolder(InterpreterObject, ObjectHolder):
      def __init__(self, held_object):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, held_object)
  
  class TargetHolder(InterpreterObject, ObjectHolder):
      def __init__(self, target, interp):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, target)
          self.interpreter = interp
  
  class BuildTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          self.methods.update({'extract_objects': self.extract_objects_method,
                               'extract_all_objects': self.extract_all_objects_method,
                               'get_id': self.get_id_method,
                               'outdir': self.outdir_method,
                               'full_path': self.full_path_method,
                               'private_dir_include': self.private_dir_include_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.filename)
  
      def is_cross(self):
          return self.held_object.is_cross()
  
      @noPosargs
      @permittedKwargs({})
      def private_dir_include_method(self, args, kwargs):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [self.interpreter.backend.get_target_private_dir(self.held_object)]))
  
      @noPosargs
      @permittedKwargs({})
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      @noPosargs
      @permittedKwargs({})
      def outdir_method(self, args, kwargs):
          return self.interpreter.backend.get_target_dir(self.held_object)
  
      @permittedKwargs({})
      def extract_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_objects(args)
          return GeneratedObjectsHolder(gobjs)
  
      @FeatureNewKwargs('extract_all_objects', '0.46.0', ['recursive'])
      @noPosargs
      @permittedKwargs({'recursive'})
      def extract_all_objects_method(self, args, kwargs):
          recursive = kwargs.get('recursive', False)
          gobjs = self.held_object.extract_all_objects(recursive)
          if gobjs.objlist and 'recursive' not in kwargs:
              mlog.warning('extract_all_objects called without setting recursive '
                           'keyword argument. Meson currently defaults to '
                           'non-recursive to maintain backward compatibility but '
                           'the default will be changed in the future.')
          return GeneratedObjectsHolder(gobjs)
  
      @noPosargs
      @permittedKwargs({})
      def get_id_method(self, args, kwargs):
          return self.held_object.get_id()
  
  class ExecutableHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class StaticLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          # Set to True only when called from self.func_shared_lib().
          target.shared_library_only = False
  
  class BothLibrariesHolder(BuildTargetHolder):
      def __init__(self, shared_holder, static_holder, interp):
          # FIXME: This build target always represents the shared library, but
          # that should be configurable.
          super().__init__(shared_holder.held_object, interp)
          self.shared_holder = shared_holder
          self.static_holder = static_holder
          self.methods.update({'get_shared_lib': self.get_shared_lib_method,
                               'get_static_lib': self.get_static_lib_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}, {}: {}>'
          h1 = self.shared_holder.held_object
          h2 = self.static_holder.held_object
          return r.format(self.__class__.__name__, h1.get_id(), h1.filename, h2.get_id(), h2.filename)
  
      @noPosargs
      @permittedKwargs({})
      def get_shared_lib_method(self, args, kwargs):
          return self.shared_holder
  
      @noPosargs
      @permittedKwargs({})
      def get_static_lib_method(self, args, kwargs):
          return self.static_holder
  
  class SharedModuleHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class JarHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class CustomTargetIndexHolder(InterpreterObject, ObjectHolder):
      def __init__(self, object_to_hold):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, object_to_hold)
  
  class CustomTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
          self.methods.update({'full_path': self.full_path_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
      @noPosargs
      @permittedKwargs({})
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      def __getitem__(self, index):
          return CustomTargetIndexHolder(self.held_object[index])
  
      def __setitem__(self, index, value):
          raise InterpreterException('Cannot set a member of a CustomTarget')
  
      def __delitem__(self, index):
          raise InterpreterException('Cannot delete a member of a CustomTarget')
  
      def outdir_include(self):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [os.path.join('@BUILD_ROOT@', self.interpreter.backend.get_target_dir(self.held_object))]))
  
  class RunTargetHolder(InterpreterObject, ObjectHolder):
      def __init__(self, name, command, args, dependencies, subdir, subproject):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, build.RunTarget(name, command, args, dependencies, subdir, subproject))
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
  class Test(InterpreterObject):
      def __init__(self, name, project, suite, exe, depends, is_parallel,
                   cmd_args, env, should_fail, timeout, workdir):
          InterpreterObject.__init__(self)
          self.name = name
          self.suite = suite
          self.project_name = project
          self.exe = exe
          self.depends = depends
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
  
      def get_exe(self):
          return self.exe
  
      def get_name(self):
          return self.name
  
  class SubprojectHolder(InterpreterObject, ObjectHolder):
  
      def __init__(self, subinterpreter):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, subinterpreter)
          self.methods.update({'get_variable': self.get_variable_method,
                               })
  
      @permittedKwargs({})
      def get_variable_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Get_variable takes one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Get_variable takes a string argument.')
          if varname not in self.held_object.variables:
              raise InvalidArguments('Requested variable "{0}" not found.'.format(varname))
          return self.held_object.variables[varname]
  
  class CompilerHolder(InterpreterObject):
      def __init__(self, compiler, env):
          InterpreterObject.__init__(self)
          self.compiler = compiler
          self.environment = env
          self.methods.update({'compiles': self.compiles_method,
                               'links': self.links_method,
                               'get_id': self.get_id_method,
                               'compute_int': self.compute_int_method,
                               'sizeof': self.sizeof_method,
                               'get_define': self.get_define_method,
                               'check_header': self.check_header_method,
                               'has_header': self.has_header_method,
                               'has_header_symbol': self.has_header_symbol_method,
                               'run': self.run_method,
                               'has_function': self.has_function_method,
                               'has_member': self.has_member_method,
                               'has_members': self.has_members_method,
                               'has_type': self.has_type_method,
                               'alignment': self.alignment_method,
                               'version': self.version_method,
                               'cmd_array': self.cmd_array_method,
                               'find_library': self.find_library_method,
                               'has_argument': self.has_argument_method,
                               'has_multi_arguments': self.has_multi_arguments_method,
                               'get_supported_arguments': self.get_supported_arguments_method,
                               'first_supported_argument': self.first_supported_argument_method,
                               'has_link_argument': self.has_link_argument_method,
                               'has_multi_link_arguments': self.has_multi_link_arguments_method,
                               'get_supported_link_arguments': self.get_supported_link_arguments_method,
                               'first_supported_link_argument': self.first_supported_link_argument_method,
                               'unittest_args': self.unittest_args_method,
                               'symbols_have_underscore_prefix': self.symbols_have_underscore_prefix_method,
                               })
  
      @noPosargs
      @permittedKwargs({})
      def version_method(self, args, kwargs):
          return self.compiler.version
  
      @noPosargs
      @permittedKwargs({})
      def cmd_array_method(self, args, kwargs):
          return self.compiler.exelist
  
      def determine_args(self, kwargs):
          nobuiltins = kwargs.get('no_builtin_args', False)
          if not isinstance(nobuiltins, bool):
              raise InterpreterException('Type of no_builtin_args not a boolean.')
          args = []
          incdirs = extract_as_list(kwargs, 'include_directories')
          for i in incdirs:
              if not isinstance(i, IncludeDirsHolder):
                  raise InterpreterException('Include directories argument must be an include_directories object.')
              for idir in i.held_object.get_incdirs():
                  idir = os.path.join(self.environment.get_source_dir(),
                                      i.held_object.get_curdir(), idir)
                  args += self.compiler.get_include_args(idir, False)
          if not nobuiltins:
              opts = self.environment.coredata.compiler_options
              args += self.compiler.get_option_compile_args(opts)
              args += self.compiler.get_option_link_args(opts)
          args += mesonlib.stringlistify(kwargs.get('args', []))
          return args
  
      def determine_dependencies(self, kwargs):
          deps = kwargs.get('dependencies', None)
          if deps is not None:
              deps = listify(deps)
              final_deps = []
              for d in deps:
                  try:
                      d = d.held_object
                  except Exception:
                      pass
                  if isinstance(d, InternalDependency) or not isinstance(d, Dependency):
                      raise InterpreterException('Dependencies must be external dependencies')
                  final_deps.append(d)
              deps = final_deps
          return deps
  
      @permittedKwargs({
          'prefix',
          'args',
          'dependencies',
      })
      def alignment_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Alignment method takes exactly one positional argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = mesonlib.stringlistify(kwargs.get('args', []))
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.alignment(typename, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for alignment of "', mlog.bold(typename), '": ', result, sep='')
          return result
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def run_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Run method takes exactly one positional argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.run(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if not result.compiled:
                  h = mlog.red('DID NOT COMPILE')
              elif result.returncode == 0:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO (%d)' % result.returncode)
              mlog.log('Checking if "', mlog.bold(testname), '" runs: ', h, sep='')
          return TryRunResultHolder(result)
  
      @noPosargs
      @permittedKwargs({})
      def get_id_method(self, args, kwargs):
          return self.compiler.get_id()
  
      @noPosargs
      @permittedKwargs({})
      def symbols_have_underscore_prefix_method(self, args, kwargs):
          '''
          Check if the compiler prefixes _ (underscore) to global C symbols
          See: https://en.wikipedia.org/wiki/Name_mangling#C
          '''
          return self.compiler.symbols_have_underscore_prefix(self.environment)
  
      @noPosargs
      @permittedKwargs({})
      def unittest_args_method(self, args, kwargs):
          '''
          This function is deprecated and should not be used.
          It can be removed in a future version of Meson.
          '''
          if not hasattr(self.compiler, 'get_feature_args'):
              raise InterpreterException('This {} compiler has no feature arguments.'.format(self.compiler.get_display_language()))
          build_to_src = os.path.relpath(self.environment.get_source_dir(), self.environment.get_build_dir())
          return self.compiler.get_feature_args({'unittest': 'true'}, build_to_src)
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_member_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Has_member takes exactly two arguments.')
          check_stringlist(args)
          typename = args[0]
          membername = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_member must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, [membername], prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has member "', mlog.bold(membername), '": ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_members_method(self, args, kwargs):
          if len(args) < 2:
              raise InterpreterException('Has_members needs at least two arguments.')
          check_stringlist(args)
          typename = args[0]
          membernames = args[1:]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_members must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, membernames, prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          members = mlog.bold(', '.join(['"{}"'.format(m) for m in membernames]))
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has members ', members, ': ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_function_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_function takes exactly one argument.')
          check_stringlist(args)
          funcname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_function must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_function(funcname, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for function "', mlog.bold(funcname), '": ', hadtxt, sep='')
          return had
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_type_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_type takes exactly one argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_type must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_type(typename, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for type "', mlog.bold(typename), '": ', hadtxt, sep='')
          return had
  
      @FeatureNew('compiler.compute_int', '0.40.0')
      @permittedKwargs({
          'prefix',
          'low',
          'high',
          'guess',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def compute_int_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Compute_int takes exactly one argument.')
          check_stringlist(args)
          expression = args[0]
          prefix = kwargs.get('prefix', '')
          low = kwargs.get('low', None)
          high = kwargs.get('high', None)
          guess = kwargs.get('guess', None)
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of compute_int must be a string.')
          if low is not None and not isinstance(low, int):
              raise InterpreterException('Low argument of compute_int must be an int.')
          if high is not None and not isinstance(high, int):
              raise InterpreterException('High argument of compute_int must be an int.')
          if guess is not None and not isinstance(guess, int):
              raise InterpreterException('Guess argument of compute_int must be an int.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          res = self.compiler.compute_int(expression, low, high, guess, prefix, self.environment, extra_args, deps)
          mlog.log('Computing int of "%s": %d' % (expression, res))
          return res
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def sizeof_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Sizeof takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          esize = self.compiler.sizeof(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for size of "%s": %d' % (element, esize))
          return esize
  
      @FeatureNew('compiler.get_define', '0.40.0')
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def get_define_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_define() takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of get_define() must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          value = self.compiler.get_define(element, prefix, self.environment, extra_args, deps)
          mlog.log('Fetching value of define "%s": %s' % (element, value))
          return value
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def compiles_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('compiles method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.compiles(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" compiles: ', h, sep='')
          return result
  
      @permittedKwargs({
          'name',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def links_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('links method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.links(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" links: ', h, sep='')
          return result
  
      @FeatureNew('check_header', '0.47.0')
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def check_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('check_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.check_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Check usable header "%s":' % hname, h)
          return haz
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('has_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Has header "%s":' % hname, h)
          return haz
  
      @permittedKwargs({
          'prefix',
          'no_builtin_args',
          'include_directories',
          'args',
          'dependencies',
      })
      def has_header_symbol_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('has_header_symbol method takes exactly two arguments.')
          check_stringlist(args)
          hname = args[0]
          symbol = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header_symbol must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header_symbol(hname, symbol, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Header <{0}> has symbol "{1}":'.format(hname, symbol), h)
          return haz
  
      @permittedKwargs({
          'required',
          'dirs',
      })
      def find_library_method(self, args, kwargs):
          # TODO add dependencies support?
          if len(args) != 1:
              raise InterpreterException('find_library method takes one argument.')
          libname = args[0]
          if not isinstance(libname, str):
              raise InterpreterException('Library name not a string.')
  
          disabled, required, feature = extract_required_kwarg(kwargs)
          if disabled:
              mlog.log('Library', mlog.bold(libname), 'skipped: feature', mlog.bold(feature), 'disabled')
              lib = dependencies.ExternalLibrary(libname, None,
                                                 self.environment,
                                                 self.compiler.language,
                                                 silent=True)
              return ExternalLibraryHolder(lib)
  
          search_dirs = mesonlib.stringlistify(kwargs.get('dirs', []))
          for i in search_dirs:
              if not os.path.isabs(i):
                  raise InvalidCode('Search directory %s is not an absolute path.' % i)
          linkargs = self.compiler.find_library(libname, self.environment, search_dirs)
          if required and not linkargs:
              raise InterpreterException('{} library {!r} not found'.format(self.compiler.get_display_language(), libname))
          lib = dependencies.ExternalLibrary(libname, linkargs, self.environment,
                                             self.compiler.language)
          return ExternalLibraryHolder(lib)
  
      @permittedKwargs({})
      def has_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('has_argument takes exactly one argument.')
          return self.has_multi_arguments_method(args, kwargs)
  
      @permittedKwargs({})
      def has_multi_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports arguments {}:'.format(
                  self.compiler.get_display_language(), ' '.join(args)),
              h)
          return result
  
      @FeatureNew('compiler.get_supported_arguments', '0.43.0')
      @permittedKwargs({})
      def get_supported_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          supported_args = []
          for arg in args:
              if self.has_argument_method(arg, kwargs):
                  supported_args.append(arg)
          return supported_args
  
      @permittedKwargs({})
      def first_supported_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.has_argument_method(i, kwargs):
                  mlog.log('First supported argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported argument:', mlog.red('None'))
          return []
  
      @FeatureNew('has_link_argument', '0.46.0')
      @permittedKwargs({})
      def has_link_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('has_link_argument takes exactly one argument.')
          return self.has_multi_link_arguments_method(args, kwargs)
  
      @FeatureNew('has_multi_link_argument', '0.46.0')
      @permittedKwargs({})
      def has_multi_link_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_link_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports link arguments {}:'.format(
                  self.compiler.get_display_language(), ' '.join(args)),
              h)
          return result
  
      @FeatureNew('get_supported_link_arguments_method', '0.46.0')
      @permittedKwargs({})
      def get_supported_link_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          supported_args = []
          for arg in args:
              if self.has_link_argument_method(arg, kwargs):
                  supported_args.append(arg)
          return supported_args
  
      @FeatureNew('first_supported_link_argument_method', '0.46.0')
      @permittedKwargs({})
      def first_supported_link_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.has_link_argument_method(i, kwargs):
                  mlog.log('First supported link argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported link argument:', mlog.red('None'))
          return []
  
  ModuleState = namedtuple('ModuleState', [
      'build_to_src', 'subproject', 'subdir', 'current_lineno', 'environment',
      'project_name', 'project_version', 'backend', 'compilers', 'targets',
      'data', 'headers', 'man', 'global_args', 'project_args', 'build_machine',
      'host_machine', 'target_machine'])
  
  class ModuleHolder(InterpreterObject, ObjectHolder):
      def __init__(self, modname, module, interpreter):
          InterpreterObject.__init__(self)
          ObjectHolder.__init__(self, module)
          self.modname = modname
          self.interpreter = interpreter
  
      def method_call(self, method_name, args, kwargs):
          try:
              fn = getattr(self.held_object, method_name)
          except AttributeError:
              raise InvalidArguments('Module %s does not have method %s.' % (self.modname, method_name))
          if method_name.startswith('_'):
              raise InvalidArguments('Function {!r} in module {!r} is private.'.format(method_name, self.modname))
          if not getattr(fn, 'no-args-flattening', False):
              args = flatten(args)
          # This is not 100% reliable but we can't use hash()
          # because the Build object contains dicts and lists.
          num_targets = len(self.interpreter.build.targets)
          state = ModuleState(
              build_to_src=os.path.relpath(self.interpreter.environment.get_source_dir(),
                                           self.interpreter.environment.get_build_dir()),
              subproject=self.interpreter.subproject,
              subdir=self.interpreter.subdir,
              current_lineno=self.interpreter.current_lineno,
              environment=self.interpreter.environment,
              project_name=self.interpreter.build.project_name,
              project_version=self.interpreter.build.dep_manifest[self.interpreter.active_projectname],
              # The backend object is under-used right now, but we will need it:
              # https://github.com/mesonbuild/meson/issues/1419
              backend=self.interpreter.backend,
              compilers=self.interpreter.build.compilers,
              targets=self.interpreter.build.targets,
              data=self.interpreter.build.data,
              headers=self.interpreter.build.get_headers(),
              man=self.interpreter.build.get_man(),
              global_args=self.interpreter.build.global_args,
              project_args=self.interpreter.build.projects_args.get(self.interpreter.subproject, {}),
              build_machine=self.interpreter.builtin['build_machine'].held_object,
              host_machine=self.interpreter.builtin['host_machine'].held_object,
              target_machine=self.interpreter.builtin['target_machine'].held_object,
          )
          if self.held_object.is_snippet(method_name):
              value = fn(self.interpreter, state, args, kwargs)
              return self.interpreter.holderify(value)
          else:
              value = fn(state, args, kwargs)
              if num_targets != len(self.interpreter.build.targets):
                  raise InterpreterException('Extension module altered internal state illegally.')
              return self.interpreter.module_method_callback(value)
  
  class MesonMain(InterpreterObject):
      def __init__(self, build, interpreter):
          InterpreterObject.__init__(self)
          self.build = build
          self.interpreter = interpreter
          self._found_source_scripts = {}
          self.methods.update({'get_compiler': self.get_compiler_method,
                               'is_cross_build': self.is_cross_build_method,
                               'has_exe_wrapper': self.has_exe_wrapper_method,
                               'is_unity': self.is_unity_method,
                               'is_subproject': self.is_subproject_method,
                               'current_source_dir': self.current_source_dir_method,
                               'current_build_dir': self.current_build_dir_method,
                               'source_root': self.source_root_method,
                               'build_root': self.build_root_method,
                               'add_install_script': self.add_install_script_method,
                               'add_postconf_script': self.add_postconf_script_method,
                               'install_dependency_manifest': self.install_dependency_manifest_method,
                               'override_find_program': self.override_find_program_method,
                               'project_version': self.project_version_method,
                               'project_license': self.project_license_method,
                               'version': self.version_method,
                               'project_name': self.project_name_method,
                               'get_cross_property': self.get_cross_property_method,
                               'backend': self.backend_method,
                               })
  
      def _find_source_script(self, name, args):
          # Prefer scripts in the current source directory
          search_dir = os.path.join(self.interpreter.environment.source_dir,
                                    self.interpreter.subdir)
          key = (name, search_dir)
          if key in self._found_source_scripts:
              found = self._found_source_scripts[key]
          else:
              found = dependencies.ExternalProgram(name, search_dir=search_dir)
              if found.found():
                  self._found_source_scripts[key] = found
              else:
                  m = 'Script or command {!r} not found or not executable'
                  raise InterpreterException(m.format(name))
          return build.RunScript(found.get_command(), args)
  
      @permittedKwargs({})
      def add_install_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_install_script takes one or more arguments')
          check_stringlist(args, 'add_install_script args must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.install_scripts.append(script)
  
      @permittedKwargs({})
      def add_postconf_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_postconf_script takes one or more arguments')
          check_stringlist(args, 'add_postconf_script arguments must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.postconf_scripts.append(script)
  
      @noPosargs
      @permittedKwargs({})
      def current_source_dir_method(self, args, kwargs):
          src = self.interpreter.environment.source_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      @noPosargs
      @permittedKwargs({})
      def current_build_dir_method(self, args, kwargs):
          src = self.interpreter.environment.build_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      @noPosargs
      @permittedKwargs({})
      def backend_method(self, args, kwargs):
          return self.interpreter.backend.name
  
      @noPosargs
      @permittedKwargs({})
      def source_root_method(self, args, kwargs):
          return self.interpreter.environment.source_dir
  
      @noPosargs
      @permittedKwargs({})
      def build_root_method(self, args, kwargs):
          return self.interpreter.environment.build_dir
  
      @noPosargs
      @permittedKwargs({})
      def has_exe_wrapper_method(self, args, kwargs):
          if self.is_cross_build_method(None, None) and \
             'binaries' in self.build.environment.cross_info.config and \
             self.build.environment.cross_info.need_exe_wrapper():
              exe_wrap = self.build.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              if exe_wrap is None:
                  return False
          # We return True when exe_wrap is defined, when it's not needed, and
          # when we're compiling natively. The last two are semantically confusing.
          # Need to revisit this.
          return True
  
      @noPosargs
      @permittedKwargs({})
      def is_cross_build_method(self, args, kwargs):
          return self.build.environment.is_cross_build()
  
      @permittedKwargs({'native'})
      def get_compiler_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_compiler_method must have one and only one argument.')
          cname = args[0]
          native = kwargs.get('native', None)
          if native is None:
              if self.build.environment.is_cross_build():
                  native = False
              else:
                  native = True
          if not isinstance(native, bool):
              raise InterpreterException('Type of "native" must be a boolean.')
          if native:
              clist = self.build.compilers
          else:
              clist = self.build.cross_compilers
          if cname in clist:
              return CompilerHolder(clist[cname], self.build.environment)
          raise InterpreterException('Tried to access compiler for unspecified language "%s".' % cname)
  
      @noPosargs
      @permittedKwargs({})
      def is_unity_method(self, args, kwargs):
          optval = self.interpreter.environment.coredata.get_builtin_option('unity')
          if optval == 'on' or (optval == 'subprojects' and self.interpreter.subproject != ''):
              return True
          return False
  
      @noPosargs
      @permittedKwargs({})
      def is_subproject_method(self, args, kwargs):
          return self.interpreter.is_subproject()
  
      @permittedKwargs({})
      def install_dependency_manifest_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Must specify manifest install file name')
          if not isinstance(args[0], str):
              raise InterpreterException('Argument must be a string.')
          self.build.dep_manifest_name = args[0]
  
      @FeatureNew('override_find_program', '0.46.0')
      @permittedKwargs({})
      def override_find_program_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Override needs two arguments')
          name = args[0]
          exe = args[1]
          if not isinstance(name, str):
              raise InterpreterException('First argument must be a string')
          if hasattr(exe, 'held_object'):
              exe = exe.held_object
          if isinstance(exe, mesonlib.File):
              abspath = exe.absolute_path(self.interpreter.environment.source_dir,
                                          self.interpreter.environment.build_dir)
              if not os.path.exists(abspath):
                  raise InterpreterException('Tried to override %s with a file that does not exist.' % name)
              exe = dependencies.ExternalProgram(abspath)
          if not isinstance(exe, dependencies.ExternalProgram):
              # FIXME, make this
  
  [... the rest is omitted ...]
files: mesonbuild/interpreter.py