files: # Copyright 2012-2016 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.
  
  import os, pickle, re
  from .. import build
  from .. import dependencies
  from .. import mesonlib
  from .. import mlog
  from .. import compilers
  import json
  import subprocess
  from ..mesonlib import MesonException
  from ..mesonlib import get_compiler_for_source, classify_unity_sources
  from ..compilers import CompilerArgs
  from collections import OrderedDict
  import shlex
  
  class CleanTrees:
      '''
      Directories outputted by custom targets that have to be manually cleaned
      because on Linux `ninja clean` only deletes empty directories.
      '''
      def __init__(self, build_dir, trees):
          self.build_dir = build_dir
          self.trees = trees
  
  class InstallData:
      def __init__(self, source_dir, build_dir, prefix, strip_bin, mesonintrospect):
          self.source_dir = source_dir
          self.build_dir = build_dir
          self.prefix = prefix
          self.strip_bin = strip_bin
          self.targets = []
          self.headers = []
          self.man = []
          self.data = []
          self.po_package_name = ''
          self.po = []
          self.install_scripts = []
          self.install_subdirs = []
          self.mesonintrospect = mesonintrospect
  
  class ExecutableSerialisation:
      def __init__(self, name, fname, cmd_args, env, is_cross, exe_wrapper,
                   workdir, extra_paths, capture):
          self.name = name
          self.fname = fname
          self.cmd_args = cmd_args
          self.env = env
          self.is_cross = is_cross
          self.exe_runner = exe_wrapper
          self.workdir = workdir
          self.extra_paths = extra_paths
          self.capture = capture
  
  class TestSerialisation:
      def __init__(self, name, project, suite, fname, is_cross_built, exe_wrapper, is_parallel,
                   cmd_args, env, should_fail, timeout, workdir, extra_paths):
          self.name = name
          self.project_name = project
          self.suite = suite
          self.fname = fname
          self.is_cross_built = is_cross_built
          self.exe_runner = exe_wrapper
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
          self.extra_paths = extra_paths
  
  class OptionProxy:
      def __init__(self, name, value):
          self.name = name
          self.value = value
  
  class OptionOverrideProxy:
      '''Mimic an option list but transparently override
      selected option values.'''
      def __init__(self, overrides, *options):
          self.overrides = overrides
          self.options = options
  
      def __getitem__(self, option_name):
          for opts in self.options:
              if option_name in opts:
                  return self._get_override(option_name, opts[option_name])
          raise KeyError('Option not found', option_name)
  
      def _get_override(self, option_name, base_opt):
          if option_name in self.overrides:
              return OptionProxy(base_opt.name, base_opt.validate_value(self.overrides[option_name]))
          return base_opt
  
  # This class contains the basic functionality that is needed by all backends.
  # Feel free to move stuff in and out of it as you see fit.
  class Backend:
      def __init__(self, build):
          self.build = build
          self.environment = build.environment
          self.processed_targets = {}
          self.build_to_src = os.path.relpath(self.environment.get_source_dir(),
                                              self.environment.get_build_dir())
  
      def get_target_filename(self, t):
          if isinstance(t, build.CustomTarget):
              if len(t.get_outputs()) != 1:
                  mlog.warning('custom_target {!r} has more than one output! '
                               'Using the first one.'.format(t.name))
              filename = t.get_outputs()[0]
          else:
              assert(isinstance(t, build.BuildTarget))
              filename = t.get_filename()
          return os.path.join(self.get_target_dir(t), filename)
  
      def get_target_filename_abs(self, target):
          return os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))
  
      def get_builtin_options_for_target(self, target):
          return OptionOverrideProxy(target.option_overrides,
                                     self.environment.coredata.builtins)
  
      def get_base_options_for_target(self, target):
          return OptionOverrideProxy(target.option_overrides,
                                     self.environment.coredata.builtins,
                                     self.environment.coredata.base_options)
  
      def get_compiler_options_for_target(self, target):
          return OptionOverrideProxy(target.option_overrides,
                                     # no code depends on builtins for now
                                     self.environment.coredata.compiler_options)
  
      def get_option_for_target(self, option_name, target):
          if option_name in target.option_overrides:
              override = target.option_overrides[option_name]
              return self.environment.coredata.validate_option_value(option_name, override)
          return self.environment.coredata.get_builtin_option(option_name)
  
      def get_target_filename_for_linking(self, target):
          # On some platforms (msvc for instance), the file that is used for
          # dynamic linking is not the same as the dynamic library itself. This
          # file is called an import library, and we want to link against that.
          # On all other platforms, we link to the library directly.
          if isinstance(target, build.SharedLibrary):
              link_lib = target.get_import_filename() or target.get_filename()
              return os.path.join(self.get_target_dir(target), link_lib)
          elif isinstance(target, build.StaticLibrary):
              return os.path.join(self.get_target_dir(target), target.get_filename())
          elif isinstance(target, build.Executable):
              if target.import_filename:
                  return os.path.join(self.get_target_dir(target), target.get_import_filename())
              else:
                  return None
          raise AssertionError('BUG: Tried to link to {!r} which is not linkable'.format(target))
  
      def get_target_dir(self, target):
          if self.environment.coredata.get_builtin_option('layout') == 'mirror':
              dirname = target.get_subdir()
          else:
              dirname = 'meson-out'
          return dirname
  
      def get_target_dir_relative_to(self, t, o):
          '''Get a target dir relative to another target's directory'''
          target_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
          othert_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(o))
          return os.path.relpath(target_dir, othert_dir)
  
      def get_target_source_dir(self, target):
          # if target dir is empty, avoid extraneous trailing / from os.path.join()
          target_dir = self.get_target_dir(target)
          if target_dir:
              return os.path.join(self.build_to_src, target_dir)
          return self.build_to_src
  
      def get_target_private_dir(self, target):
          return os.path.join(self.get_target_dir(target), target.get_id())
  
      def get_target_private_dir_abs(self, target):
          return os.path.join(self.environment.get_build_dir(), self.get_target_private_dir(target))
  
      def get_target_generated_dir(self, target, gensrc, src):
          """
          Takes a BuildTarget, a generator source (CustomTarget or GeneratedList),
          and a generated source filename.
          Returns the full path of the generated source relative to the build root
          """
          # CustomTarget generators output to the build dir of the CustomTarget
          if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)):
              return os.path.join(self.get_target_dir(gensrc), src)
          # GeneratedList generators output to the private build directory of the
          # target that the GeneratedList is used in
          return os.path.join(self.get_target_private_dir(target), src)
  
      def get_unity_source_file(self, target, suffix):
          osrc = target.name + '-unity.' + suffix
          return mesonlib.File.from_built_file(self.get_target_private_dir(target), osrc)
  
      def generate_unity_files(self, target, unity_src):
          abs_files = []
          result = []
          compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
  
          def init_language_file(suffix):
              unity_src = self.get_unity_source_file(target, suffix)
              outfileabs = unity_src.absolute_path(self.environment.get_source_dir(),
                                                   self.environment.get_build_dir())
              outfileabs_tmp = outfileabs + '.tmp'
              abs_files.append(outfileabs)
              outfileabs_tmp_dir = os.path.dirname(outfileabs_tmp)
              if not os.path.exists(outfileabs_tmp_dir):
                  os.makedirs(outfileabs_tmp_dir)
              result.append(unity_src)
              return open(outfileabs_tmp, 'w')
  
          # For each language, generate a unity source file and return the list
          for comp, srcs in compsrcs.items():
              with init_language_file(comp.get_default_suffix()) as ofile:
                  for src in srcs:
                      ofile.write('#include<%s>\n' % src)
          [mesonlib.replace_if_different(x, x + '.tmp') for x in abs_files]
          return result
  
      def relpath(self, todir, fromdir):
          return os.path.relpath(os.path.join('dummyprefixdir', todir),
                                 os.path.join('dummyprefixdir', fromdir))
  
      def flatten_object_list(self, target, proj_dir_to_build_root=''):
          obj_list = []
          for obj in target.get_objects():
              if isinstance(obj, str):
                  o = os.path.join(proj_dir_to_build_root,
                                   self.build_to_src, target.get_subdir(), obj)
                  obj_list.append(o)
              elif isinstance(obj, mesonlib.File):
                  obj_list.append(obj.rel_to_builddir(self.build_to_src))
              elif isinstance(obj, build.ExtractedObjects):
                  obj_list += self.determine_ext_objs(target, obj, proj_dir_to_build_root)
              else:
                  raise MesonException('Unknown data type in object list.')
          return obj_list
  
      def serialize_executable(self, exe, cmd_args, workdir, env={},
                               extra_paths=None, capture=None):
          import hashlib
          if extra_paths is None:
              # The callee didn't check if we needed extra paths, so check it here
              if mesonlib.is_windows() or mesonlib.is_cygwin():
                  extra_paths = self.determine_windows_extra_paths(exe, [])
              else:
                  extra_paths = []
          # Can't just use exe.name here; it will likely be run more than once
          if isinstance(exe, (dependencies.ExternalProgram,
                              build.BuildTarget, build.CustomTarget)):
              basename = exe.name
          else:
              basename = os.path.basename(exe)
          # Take a digest of the cmd args, env, workdir, and capture. This avoids
          # collisions and also makes the name deterministic over regenerations
          # which avoids a rebuild by Ninja because the cmdline stays the same.
          data = bytes(str(sorted(env.items())) + str(cmd_args) + str(workdir) + str(capture),
                       encoding='utf-8')
          digest = hashlib.sha1(data).hexdigest()
          scratch_file = 'meson_exe_{0}_{1}.dat'.format(basename, digest)
          exe_data = os.path.join(self.environment.get_scratch_dir(), scratch_file)
          with open(exe_data, 'wb') as f:
              if isinstance(exe, dependencies.ExternalProgram):
                  exe_cmd = exe.get_command()
                  exe_needs_wrapper = False
              elif isinstance(exe, (build.BuildTarget, build.CustomTarget)):
                  exe_cmd = [self.get_target_filename_abs(exe)]
                  exe_needs_wrapper = exe.is_cross
              else:
                  exe_cmd = [exe]
                  exe_needs_wrapper = False
              is_cross_built = exe_needs_wrapper and \
                  self.environment.is_cross_build() and \
                  self.environment.cross_info.need_cross_compiler() and \
                  self.environment.cross_info.need_exe_wrapper()
              if is_cross_built:
                  exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              else:
                  exe_wrapper = None
              es = ExecutableSerialisation(basename, exe_cmd, cmd_args, env,
                                           is_cross_built, exe_wrapper, workdir,
                                           extra_paths, capture)
              pickle.dump(es, f)
          return exe_data
  
      def serialize_tests(self):
          test_data = os.path.join(self.environment.get_scratch_dir(), 'meson_test_setup.dat')
          with open(test_data, 'wb') as datafile:
              self.write_test_file(datafile)
          benchmark_data = os.path.join(self.environment.get_scratch_dir(), 'meson_benchmark_setup.dat')
          with open(benchmark_data, 'wb') as datafile:
              self.write_benchmark_file(datafile)
          return test_data, benchmark_data
  
      def determine_linker(self, target):
          '''
          If we're building a static library, there is only one static linker.
          Otherwise, we query the target for the dynamic linker.
          '''
          if isinstance(target, build.StaticLibrary):
              if target.is_cross:
                  return self.build.static_cross_linker
              else:
                  return self.build.static_linker
          l = target.get_clike_dynamic_linker()
          if not l:
              m = "Couldn't determine linker for target {!r}"
              raise MesonException(m.format(target.name))
          return l
  
      def rpaths_for_bundled_shared_libraries(self, target):
          paths = []
          for dep in target.external_deps:
              if isinstance(dep, (dependencies.ExternalLibrary, dependencies.PkgConfigDependency)):
                  la = dep.link_args
                  if len(la) == 1 and os.path.isabs(la[0]):
                      # The only link argument is an absolute path to a library file.
                      libpath = la[0]
                      if libpath.startswith(('/usr/lib', '/lib')):
                          # No point in adding system paths.
                          continue
                      if os.path.splitext(libpath)[1] not in ['.dll', '.lib', '.so']:
                          continue
                      absdir = os.path.dirname(libpath)
                      if absdir.startswith(self.environment.get_source_dir()):
                          rel_to_src = absdir[len(self.environment.get_source_dir()) + 1:]
                          assert not os.path.isabs(rel_to_src), 'rel_to_src: {} is absolute'.format(rel_to_src)
                          paths.append(os.path.join(self.build_to_src, rel_to_src))
                      else:
                          paths.append(absdir)
          return paths
  
      def determine_rpath_dirs(self, target):
          link_deps = target.get_all_link_deps()
          result = []
          for ld in link_deps:
              if ld is target:
                  continue
              prospective = self.get_target_dir(ld)
              if prospective not in result:
                  result.append(prospective)
          for rp in self.rpaths_for_bundled_shared_libraries(target):
              if rp not in result:
                  result += [rp]
          return result
  
      def object_filename_from_source(self, target, source, is_unity):
          assert isinstance(source, mesonlib.File)
          build_dir = self.environment.get_build_dir()
          rel_src = source.rel_to_builddir(self.build_to_src)
  
          if (not self.environment.is_source(rel_src) or
             self.environment.is_header(rel_src)) and not is_unity:
              return None
  
          # foo.vala files compile down to foo.c and then foo.c.o, not foo.vala.o
          if rel_src.endswith(('.vala', '.gs')):
              # See description in generate_vala_compile for this logic.
              if source.is_built:
                  if os.path.isabs(rel_src):
                      rel_src = rel_src[len(build_dir) + 1:]
                  rel_src = os.path.relpath(rel_src, self.get_target_private_dir(target))
              else:
                  rel_src = os.path.basename(rel_src)
              if is_unity:
                  return 'meson-generated_' + rel_src[:-5] + '.c.' + self.environment.get_object_suffix()
              # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
              source = 'meson-generated_' + rel_src[:-5] + '.c'
          elif source.is_built:
              if os.path.isabs(rel_src):
                  rel_src = rel_src[len(build_dir) + 1:]
              targetdir = self.get_target_private_dir(target)
              # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
              source = 'meson-generated_' + os.path.relpath(rel_src, targetdir)
          else:
              if os.path.isabs(rel_src):
                  # Not from the source directory; hopefully this doesn't conflict with user's source files.
                  source = os.path.basename(rel_src)
              else:
                  source = os.path.relpath(os.path.join(build_dir, rel_src),
                                           os.path.join(self.environment.get_source_dir(), target.get_subdir()))
          return source.replace('/', '_').replace('\\', '_') + '.' + self.environment.get_object_suffix()
  
      def determine_ext_objs(self, target, extobj, proj_dir_to_build_root):
          result = []
          targetdir = self.get_target_private_dir(extobj.target)
          # With unity builds, there's just one object that contains all the
          # sources, and we only support extracting all the objects in this mode,
          # so just return that.
          if self.is_unity(target):
              comp = get_compiler_for_source(extobj.target.compilers.values(),
                                             extobj.srclist[0])
              # There is a potential conflict here, but it is unlikely that
              # anyone both enables unity builds and has a file called foo-unity.cpp.
              osrc = self.get_unity_source_file(extobj.target,
                                                comp.get_default_suffix())
              objname = self.object_filename_from_source(extobj.target, osrc, True)
              objname = objname.replace('/', '_').replace('\\', '_')
              objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
              return [objpath]
          for osrc in extobj.srclist:
              objname = self.object_filename_from_source(extobj.target, osrc, False)
              if objname:
                  objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
                  result.append(objpath)
          return result
  
      def get_pch_include_args(self, compiler, target):
          args = []
          pchpath = self.get_target_private_dir(target)
          includeargs = compiler.get_include_args(pchpath, False)
          p = target.get_pch(compiler.get_language())
          if p:
              args += compiler.get_pch_use_args(pchpath, p[0])
          return includeargs + args
  
      @staticmethod
      def escape_extra_args(compiler, args):
          # No extra escaping/quoting needed when not running on Windows
          if not mesonlib.is_windows():
              return args
          extra_args = []
          # Compiler-specific escaping is needed for -D args but not for any others
          if compiler.get_id() == 'msvc':
              # MSVC needs escaping when a -D argument ends in \ or \"
              for arg in args:
                  if arg.startswith('-D') or arg.startswith('/D'):
                      # Without extra escaping for these two, the next character
                      # gets eaten
                      if arg.endswith('\\'):
                          arg += '\\'
                      elif arg.endswith('\\"'):
                          arg = arg[:-2] + '\\\\"'
                  extra_args.append(arg)
          else:
              # MinGW GCC needs all backslashes in defines to be doubly-escaped
              # FIXME: Not sure about Cygwin or Clang
              for arg in args:
                  if arg.startswith('-D') or arg.startswith('/D'):
                      arg = arg.replace('\\', '\\\\')
                  extra_args.append(arg)
          return extra_args
  
      def generate_basic_compiler_args(self, target, compiler, no_warn_args=False):
          # Create an empty commands list, and start adding arguments from
          # various sources in the order in which they must override each other
          # starting from hard-coded defaults followed by build options and so on.
          commands = CompilerArgs(compiler)
  
          copt_proxy = self.get_compiler_options_for_target(target)
          # First, the trivial ones that are impossible to override.
          #
          # Add -nostdinc/-nostdinc++ if needed; can't be overridden
          commands += self.get_cross_stdlib_args(target, compiler)
          # Add things like /NOLOGO or -pipe; usually can't be overridden
          commands += compiler.get_always_args()
          # Only add warning-flags by default if the buildtype enables it, and if
          # we weren't explicitly asked to not emit warnings (for Vala, f.ex)
          if no_warn_args:
              commands += compiler.get_no_warn_args()
          elif self.get_option_for_target('buildtype', target) != 'plain':
              commands += compiler.get_warn_args(self.get_option_for_target('warning_level', target))
          # Add -Werror if werror=true is set in the build options set on the
          # command-line or default_options inside project(). This only sets the
          # action to be done for warnings if/when they are emitted, so it's ok
          # to set it after get_no_warn_args() or get_warn_args().
          if self.get_option_for_target('werror', target):
              commands += compiler.get_werror_args()
          # Add compile args for c_* or cpp_* build options set on the
          # command-line or default_options inside project().
          commands += compiler.get_option_compile_args(copt_proxy)
          # Add buildtype args: optimization level, debugging, etc.
          commands += compiler.get_buildtype_args(self.get_option_for_target('buildtype', target))
          # Add compile args added using add_project_arguments()
          commands += self.build.get_project_args(compiler, target.subproject)
          # Add compile args added using add_global_arguments()
          # These override per-project arguments
          commands += self.build.get_global_args(compiler)
          if not target.is_cross:
              # Compile args added from the env: CFLAGS/CXXFLAGS, etc. We want these
              # to override all the defaults, but not the per-target compile args.
              commands += self.environment.coredata.external_args[compiler.get_language()]
          # Always set -fPIC for shared libraries
          if isinstance(target, build.SharedLibrary):
              commands += compiler.get_pic_args()
          # Set -fPIC for static libraries by default unless explicitly disabled
          if isinstance(target, build.StaticLibrary) and target.pic:
              commands += compiler.get_pic_args()
          # Add compile args needed to find external dependencies. Link args are
          # added while generating the link command.
          # NOTE: We must preserve the order in which external deps are
          # specified, so we reverse the list before iterating over it.
          for dep in reversed(target.get_external_deps()):
              if not dep.found():
                  continue
  
              if compiler.language == 'vala':
                  if isinstance(dep, dependencies.PkgConfigDependency):
                      if dep.name == 'glib-2.0' and dep.version_reqs is not None:
                          for req in dep.version_reqs:
                              if req.startswith(('>=', '==')):
                                  commands += ['--target-glib', req[2:]]
                                  break
                      commands += ['--pkg', dep.name]
                  elif isinstance(dep, dependencies.ExternalLibrary):
                      commands += dep.get_link_args('vala')
              else:
                  commands += dep.get_compile_args()
              # Qt needs -fPIC for executables
              # XXX: We should move to -fPIC for all executables
              if isinstance(target, build.Executable):
                  commands += dep.get_exe_args(compiler)
              # For 'automagic' deps: Boost and GTest. Also dependency('threads').
              # pkg-config puts the thread flags itself via `Cflags:`
              if dep.need_threads():
                  commands += compiler.thread_flags(self.environment)
          # Fortran requires extra include directives.
          if compiler.language == 'fortran':
              for lt in target.link_targets:
                  priv_dir = self.get_target_private_dir(lt)
                  commands += compiler.get_include_args(priv_dir, False)
          return commands
  
      def build_target_link_arguments(self, compiler, deps):
          args = []
          for d in deps:
              if not (d.is_linkable_target()):
                  raise RuntimeError('Tried to link with a non-library target "%s".' % d.get_basename())
              d_arg = self.get_target_filename_for_linking(d)
              if not d_arg:
                  continue
              if isinstance(compiler, (compilers.LLVMDCompiler, compilers.DmdDCompiler)):
                  d_arg = '-L' + d_arg
              args.append(d_arg)
          return args
  
      def determine_windows_extra_paths(self, target, extra_bdeps):
          '''On Windows there is no such thing as an rpath.
          We must determine all locations of DLLs that this exe
          links to and return them so they can be used in unit
          tests.'''
          result = []
          prospectives = []
          if isinstance(target, build.Executable):
              prospectives = target.get_transitive_link_deps()
              # External deps
              for deppath in self.rpaths_for_bundled_shared_libraries(target):
                  result.append(os.path.normpath(os.path.join(self.environment.get_build_dir(), deppath)))
          for bdep in extra_bdeps:
              prospectives += bdep.get_transitive_link_deps()
          # Internal deps
          for ld in prospectives:
              if ld == '' or ld == '.':
                  continue
              dirseg = os.path.join(self.environment.get_build_dir(), self.get_target_dir(ld))
              if dirseg not in result:
                  result.append(dirseg)
          return result
  
      def write_benchmark_file(self, datafile):
          self.write_test_serialisation(self.build.get_benchmarks(), datafile)
  
      def write_test_file(self, datafile):
          self.write_test_serialisation(self.build.get_tests(), datafile)
  
      def write_test_serialisation(self, tests, datafile):
          arr = []
          for t in tests:
              exe = t.get_exe()
              if isinstance(exe, dependencies.ExternalProgram):
                  cmd = exe.get_command()
              else:
                  cmd = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(t.get_exe()))]
              is_cross = self.environment.is_cross_build() and \
                  self.environment.cross_info.need_cross_compiler() and \
                  self.environment.cross_info.need_exe_wrapper()
              if isinstance(exe, build.BuildTarget):
                  is_cross = is_cross and exe.is_cross
              if isinstance(exe, dependencies.ExternalProgram):
                  # E.g. an external verifier or simulator program run on a generated executable.
                  # Can always be run.
                  is_cross = False
              if is_cross:
                  exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              else:
                  exe_wrapper = None
              if mesonlib.is_windows() or mesonlib.is_cygwin():
                  extra_paths = self.determine_windows_extra_paths(exe, [])
              else:
                  extra_paths = []
              cmd_args = []
              for a in t.cmd_args:
                  if hasattr(a, 'held_object'):
                      a = a.held_object
                  if isinstance(a, mesonlib.File):
                      a = os.path.join(self.environment.get_build_dir(), a.rel_to_builddir(self.build_to_src))
                      cmd_args.append(a)
                  elif isinstance(a, str):
                      cmd_args.append(a)
                  elif isinstance(a, build.Target):
                      cmd_args.append(self.get_target_filename(a))
                  else:
                      raise MesonException('Bad object in test command.')
              ts = TestSerialisation(t.get_name(), t.project_name, t.suite, cmd, is_cross,
                                     exe_wrapper, t.is_parallel, cmd_args, t.env,
                                     t.should_fail, t.timeout, t.workdir, extra_paths)
              arr.append(ts)
          pickle.dump(arr, datafile)
  
      def generate_depmf_install(self, d):
          if self.build.dep_manifest_name is None:
              return
          ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json')
          ofilename = os.path.join(self.environment.get_prefix(), self.build.dep_manifest_name)
          mfobj = {'type': 'dependency manifest', 'version': '1.0', 'projects': self.build.dep_manifest}
          with open(ifilename, 'w') as f:
              f.write(json.dumps(mfobj))
          # Copy file from, to, and with mode unchanged
          d.data.append([ifilename, ofilename, None])
  
      def get_regen_filelist(self):
          '''List of all files whose alteration means that the build
          definition needs to be regenerated.'''
          deps = [os.path.join(self.build_to_src, df)
                  for df in self.interpreter.get_build_def_files()]
          if self.environment.is_cross_build():
              deps.append(os.path.join(self.build_to_src,
                                       self.environment.coredata.cross_file))
          deps.append('meson-private/coredata.dat')
          if os.path.exists(os.path.join(self.environment.get_source_dir(), 'meson_options.txt')):
              deps.append(os.path.join(self.build_to_src, 'meson_options.txt'))
          for sp in self.build.subprojects.keys():
              fname = os.path.join(self.environment.get_source_dir(), sp, 'meson_options.txt')
              if os.path.isfile(fname):
                  deps.append(os.path.join(self.build_to_src, sp, 'meson_options.txt'))
          return deps
  
      def exe_object_to_cmd_array(self, exe):
          if self.environment.is_cross_build() and \
             self.environment.cross_info.need_exe_wrapper() and \
             isinstance(exe, build.BuildTarget) and exe.is_cross:
              if 'exe_wrapper' not in self.environment.cross_info.config['binaries']:
                  s = 'Can not use target %s as a generator because it is cross-built\n'
                  s += 'and no exe wrapper is defined. You might want to set it to native instead.'
                  s = s % exe.name
                  raise MesonException(s)
          if isinstance(exe, build.BuildTarget):
              exe_arr = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(exe))]
          else:
              exe_arr = exe.get_command()
          return exe_arr
  
      def replace_extra_args(self, args, genlist):
          final_args = []
          for a in args:
              if a == '@EXTRA_ARGS@':
                  final_args += genlist.get_extra_args()
              else:
                  final_args.append(a)
          return final_args
  
      def replace_outputs(self, args, private_dir, output_list):
          newargs = []
          regex = re.compile('@OUTPUT(\d+)@')
          for arg in args:
              m = regex.search(arg)
              while m is not None:
                  index = int(m.group(1))
                  src = '@OUTPUT%d@' % index
                  arg = arg.replace(src, os.path.join(private_dir, output_list[index]))
                  m = regex.search(arg)
              newargs.append(arg)
          return newargs
  
      def get_build_by_default_targets(self):
          result = OrderedDict()
          # Get all build and custom targets that must be built by default
          for name, t in self.build.get_targets().items():
              if t.build_by_default or t.install or t.build_always:
                  result[name] = t
          # Get all targets used as test executables and arguments. These must
          # also be built by default. XXX: Sometime in the future these should be
          # built only before running tests.
          for t in self.build.get_tests():
              exe = t.exe
              if hasattr(exe, 'held_object'):
                  exe = exe.held_object
              if isinstance(exe, (build.CustomTarget, build.BuildTarget)):
                  result[exe.get_id()] = exe
              for arg in t.cmd_args:
                  if hasattr(arg, 'held_object'):
                      arg = arg.held_object
                  if not isinstance(arg, (build.CustomTarget, build.BuildTarget)):
                      continue
                  result[arg.get_id()] = arg
          return result
  
      def get_custom_target_provided_libraries(self, target):
          libs = []
          for t in target.get_generated_sources():
              if not isinstance(t, build.CustomTarget):
                  continue
              for f in t.get_outputs():
                  if self.environment.is_library(f):
                      libs.append(os.path.join(self.get_target_dir(t), f))
          return libs
  
      def is_unity(self, target):
          optval = self.get_option_for_target('unity', target)
          if optval == 'on' or (optval == 'subprojects' and target.subproject != ''):
              return True
          return False
  
      def get_custom_target_sources(self, target):
          '''
          Custom target sources can be of various object types; strings, File,
          BuildTarget, even other CustomTargets.
          Returns the path to them relative to the build root directory.
          '''
          srcs = []
          for i in target.get_sources():
              if hasattr(i, 'held_object'):
                  i = i.held_object
              if isinstance(i, str):
                  fname = [os.path.join(self.build_to_src, target.subdir, i)]
              elif isinstance(i, build.BuildTarget):
                  fname = [self.get_target_filename(i)]
              elif isinstance(i, build.CustomTarget):
                  fname = [os.path.join(self.get_target_dir(i), p) for p in i.get_outputs()]
              elif isinstance(i, build.GeneratedList):
                  fname = [os.path.join(self.get_target_private_dir(target), p) for p in i.get_outputs()]
              else:
                  fname = [i.rel_to_builddir(self.build_to_src)]
              if target.absolute_paths:
                  fname = [os.path.join(self.environment.get_build_dir(), f) for f in fname]
              srcs += fname
          return srcs
  
      def get_custom_target_depend_files(self, target, absolute_paths=False):
          deps = []
          for i in target.depend_files:
              if isinstance(i, mesonlib.File):
                  if absolute_paths:
                      deps.append(i.absolute_path(self.environment.get_source_dir(),
                                                  self.environment.get_build_dir()))
                  else:
                      deps.append(i.rel_to_builddir(self.build_to_src))
              else:
                  if absolute_paths:
                      deps.append(os.path.join(self.environment.get_source_dir(), target.subdir, i))
                  else:
                      deps.append(os.path.join(self.build_to_src, target.subdir, i))
          return deps
  
      def eval_custom_target_command(self, target, absolute_outputs=False):
          # We want the outputs to be absolute only when using the VS backend
          # XXX: Maybe allow the vs backend to use relative paths too?
          source_root = self.build_to_src
          build_root = '.'
          outdir = self.get_target_dir(target)
          if absolute_outputs:
              source_root = self.environment.get_source_dir()
              build_root = self.environment.get_source_dir()
              outdir = os.path.join(self.environment.get_build_dir(), outdir)
          outputs = []
          for i in target.get_outputs():
              outputs.append(os.path.join(outdir, i))
          inputs = self.get_custom_target_sources(target)
          # Evaluate the command list
          cmd = []
          for i in target.command:
              if isinstance(i, build.Executable):
                  cmd += self.exe_object_to_cmd_array(i)
                  continue
              elif isinstance(i, build.CustomTarget):
                  # GIR scanner will attempt to execute this binary but
                  # it assumes that it is in path, so always give it a full path.
                  tmp = i.get_outputs()[0]
                  i = os.path.join(self.get_target_dir(i), tmp)
              elif isinstance(i, mesonlib.File):
                  i = i.rel_to_builddir(self.build_to_src)
                  if target.absolute_paths:
                      i = os.path.join(self.environment.get_build_dir(), i)
              # FIXME: str types are blindly added ignoring 'target.absolute_paths'
              # because we can't know if they refer to a file or just a string
              elif not isinstance(i, str):
                  err_msg = 'Argument {0} is of unknown type {1}'
                  raise RuntimeError(err_msg.format(str(i), str(type(i))))
              elif '@SOURCE_ROOT@' in i:
                  i = i.replace('@SOURCE_ROOT@', source_root)
              elif '@BUILD_ROOT@' in i:
                  i = i.replace('@BUILD_ROOT@', build_root)
              elif '@DEPFILE@' in i:
                  if target.depfile is None:
                      msg = 'Custom target {!r} has @DEPFILE@ but no depfile ' \
                            'keyword argument.'.format(target.name)
                      raise MesonException(msg)
                  dfilename = os.path.join(outdir, target.depfile)
                  i = i.replace('@DEPFILE@', dfilename)
              elif '@PRIVATE_OUTDIR_' in i:
                  match = re.search('@PRIVATE_OUTDIR_(ABS_)?([^/\s*]*)@', i)
                  if not match:
                      msg = 'Custom target {!r} has an invalid argument {!r}' \
                            ''.format(target.name, i)
                      raise MesonException(msg)
                  source = match.group(0)
                  if match.group(1) is None and not target.absolute_paths:
                      lead_dir = ''
                  else:
                      lead_dir = self.environment.get_build_dir()
                  i = i.replace(source, os.path.join(lead_dir, outdir))
              cmd.append(i)
          # Substitute the rest of the template strings
          values = mesonlib.get_filenames_templates_dict(inputs, outputs)
          cmd = mesonlib.substitute_values(cmd, values)
          # This should not be necessary but removing it breaks
          # building GStreamer on Windows. The underlying issue
          # is problems with quoting backslashes on Windows
          # which is the seventh circle of hell. The downside is
          # that this breaks custom targets whose command lines
          # have backslashes. If you try to fix this be sure to
          # check that it does not break GST.
          #
          # The bug causes file paths such as c:\foo to get escaped
          # into c:\\foo.
          #
          # Unfortunately we have not been able to come up with an
          # isolated test case for this so unless you manage to come up
          # with one, the only way is to test the building with Gst's
          # setup. Note this in your MR or ping us and we will get it
          # fixed.
          #
          # https://github.com/mesonbuild/meson/pull/737
          cmd = [i.replace('\\', '/') for i in cmd]
          return inputs, outputs, cmd
  
      def run_postconf_scripts(self):
          env = {'MESON_SOURCE_ROOT': self.environment.get_source_dir(),
                 'MESON_BUILD_ROOT': self.environment.get_build_dir(),
                 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in self.environment.get_build_command() + ['introspect']]),
                 }
          child_env = os.environ.copy()
          child_env.update(env)
  
          for s in self.build.postconf_scripts:
              cmd = s['exe'] + s['args']
              subprocess.check_call(cmd, env=child_env)
  
files: mesonbuild/backend/backends.py
files: # Copyright 2012-2016 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.
  
  import os, pickle, re
  from .. import build
  from .. import dependencies
  from .. import mesonlib
  from .. import mlog
  from .. import compilers
  import json
  import subprocess
  from ..mesonlib import MesonException
  from ..mesonlib import get_compiler_for_source, classify_unity_sources
  from ..compilers import CompilerArgs
  from collections import OrderedDict
  import shlex
  
  class CleanTrees:
      '''
      Directories outputted by custom targets that have to be manually cleaned
      because on Linux `ninja clean` only deletes empty directories.
      '''
      def __init__(self, build_dir, trees):
          self.build_dir = build_dir
          self.trees = trees
  
  class InstallData:
      def __init__(self, source_dir, build_dir, prefix, strip_bin, mesonintrospect):
          self.source_dir = source_dir
          self.build_dir = build_dir
          self.prefix = prefix
          self.strip_bin = strip_bin
          self.targets = []
          self.headers = []
          self.man = []
          self.data = []
          self.po_package_name = ''
          self.po = []
          self.install_scripts = []
          self.install_subdirs = []
          self.mesonintrospect = mesonintrospect
  
  class ExecutableSerialisation:
      def __init__(self, name, fname, cmd_args, env, is_cross, exe_wrapper,
                   workdir, extra_paths, capture):
          self.name = name
          self.fname = fname
          self.cmd_args = cmd_args
          self.env = env
          self.is_cross = is_cross
          self.exe_runner = exe_wrapper
          self.workdir = workdir
          self.extra_paths = extra_paths
          self.capture = capture
  
  class TestSerialisation:
      def __init__(self, name, project, suite, fname, is_cross_built, exe_wrapper, is_parallel,
                   cmd_args, env, should_fail, timeout, workdir, extra_paths):
          self.name = name
          self.project_name = project
          self.suite = suite
          self.fname = fname
          self.is_cross_built = is_cross_built
          self.exe_runner = exe_wrapper
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
          self.extra_paths = extra_paths
  
  class OptionProxy:
      def __init__(self, name, value):
          self.name = name
          self.value = value
  
  class OptionOverrideProxy:
      '''Mimic an option list but transparently override
      selected option values.'''
      def __init__(self, overrides, options):
          self.overrides = overrides
          self.options = options
  
      def __getitem__(self, option_name):
          base_opt = self.options[option_name]
          if option_name in self.overrides:
              return OptionProxy(base_opt.name, base_opt.validate_value(self.overrides[option_name]))
          return base_opt
  
  # This class contains the basic functionality that is needed by all backends.
  # Feel free to move stuff in and out of it as you see fit.
  class Backend:
      def __init__(self, build):
          self.build = build
          self.environment = build.environment
          self.processed_targets = {}
          self.build_to_src = os.path.relpath(self.environment.get_source_dir(),
                                              self.environment.get_build_dir())
  
      def get_target_filename(self, t):
          if isinstance(t, build.CustomTarget):
              if len(t.get_outputs()) != 1:
                  mlog.warning('custom_target {!r} has more than one output! '
                               'Using the first one.'.format(t.name))
              filename = t.get_outputs()[0]
          else:
              assert(isinstance(t, build.BuildTarget))
              filename = t.get_filename()
          return os.path.join(self.get_target_dir(t), filename)
  
      def get_target_filename_abs(self, target):
          return os.path.join(self.environment.get_build_dir(), self.get_target_filename(target))
  
      def get_option_for_target(self, option_name, target):
          if option_name in target.option_overrides:
              override = target.option_overrides[option_name]
              return self.environment.coredata.validate_option_value(option_name, override)
          return self.environment.coredata.get_builtin_option(option_name)
  
      def get_target_filename_for_linking(self, target):
          # On some platforms (msvc for instance), the file that is used for
          # dynamic linking is not the same as the dynamic library itself. This
          # file is called an import library, and we want to link against that.
          # On all other platforms, we link to the library directly.
          if isinstance(target, build.SharedLibrary):
              link_lib = target.get_import_filename() or target.get_filename()
              return os.path.join(self.get_target_dir(target), link_lib)
          elif isinstance(target, build.StaticLibrary):
              return os.path.join(self.get_target_dir(target), target.get_filename())
          elif isinstance(target, build.Executable):
              if target.import_filename:
                  return os.path.join(self.get_target_dir(target), target.get_import_filename())
              else:
                  return None
          raise AssertionError('BUG: Tried to link to {!r} which is not linkable'.format(target))
  
      def get_target_dir(self, target):
          if self.environment.coredata.get_builtin_option('layout') == 'mirror':
              dirname = target.get_subdir()
          else:
              dirname = 'meson-out'
          return dirname
  
      def get_target_dir_relative_to(self, t, o):
          '''Get a target dir relative to another target's directory'''
          target_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(t))
          othert_dir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(o))
          return os.path.relpath(target_dir, othert_dir)
  
      def get_target_source_dir(self, target):
          # if target dir is empty, avoid extraneous trailing / from os.path.join()
          target_dir = self.get_target_dir(target)
          if target_dir:
              return os.path.join(self.build_to_src, target_dir)
          return self.build_to_src
  
      def get_target_private_dir(self, target):
          return os.path.join(self.get_target_dir(target), target.get_id())
  
      def get_target_private_dir_abs(self, target):
          return os.path.join(self.environment.get_build_dir(), self.get_target_private_dir(target))
  
      def get_target_generated_dir(self, target, gensrc, src):
          """
          Takes a BuildTarget, a generator source (CustomTarget or GeneratedList),
          and a generated source filename.
          Returns the full path of the generated source relative to the build root
          """
          # CustomTarget generators output to the build dir of the CustomTarget
          if isinstance(gensrc, (build.CustomTarget, build.CustomTargetIndex)):
              return os.path.join(self.get_target_dir(gensrc), src)
          # GeneratedList generators output to the private build directory of the
          # target that the GeneratedList is used in
          return os.path.join(self.get_target_private_dir(target), src)
  
      def get_unity_source_file(self, target, suffix):
          osrc = target.name + '-unity.' + suffix
          return mesonlib.File.from_built_file(self.get_target_private_dir(target), osrc)
  
      def generate_unity_files(self, target, unity_src):
          abs_files = []
          result = []
          compsrcs = classify_unity_sources(target.compilers.values(), unity_src)
  
          def init_language_file(suffix):
              unity_src = self.get_unity_source_file(target, suffix)
              outfileabs = unity_src.absolute_path(self.environment.get_source_dir(),
                                                   self.environment.get_build_dir())
              outfileabs_tmp = outfileabs + '.tmp'
              abs_files.append(outfileabs)
              outfileabs_tmp_dir = os.path.dirname(outfileabs_tmp)
              if not os.path.exists(outfileabs_tmp_dir):
                  os.makedirs(outfileabs_tmp_dir)
              result.append(unity_src)
              return open(outfileabs_tmp, 'w')
  
          # For each language, generate a unity source file and return the list
          for comp, srcs in compsrcs.items():
              with init_language_file(comp.get_default_suffix()) as ofile:
                  for src in srcs:
                      ofile.write('#include<%s>\n' % src)
          [mesonlib.replace_if_different(x, x + '.tmp') for x in abs_files]
          return result
  
      def relpath(self, todir, fromdir):
          return os.path.relpath(os.path.join('dummyprefixdir', todir),
                                 os.path.join('dummyprefixdir', fromdir))
  
      def flatten_object_list(self, target, proj_dir_to_build_root=''):
          obj_list = []
          for obj in target.get_objects():
              if isinstance(obj, str):
                  o = os.path.join(proj_dir_to_build_root,
                                   self.build_to_src, target.get_subdir(), obj)
                  obj_list.append(o)
              elif isinstance(obj, mesonlib.File):
                  obj_list.append(obj.rel_to_builddir(self.build_to_src))
              elif isinstance(obj, build.ExtractedObjects):
                  obj_list += self.determine_ext_objs(target, obj, proj_dir_to_build_root)
              else:
                  raise MesonException('Unknown data type in object list.')
          return obj_list
  
      def serialize_executable(self, exe, cmd_args, workdir, env={},
                               extra_paths=None, capture=None):
          import hashlib
          if extra_paths is None:
              # The callee didn't check if we needed extra paths, so check it here
              if mesonlib.is_windows() or mesonlib.is_cygwin():
                  extra_paths = self.determine_windows_extra_paths(exe, [])
              else:
                  extra_paths = []
          # Can't just use exe.name here; it will likely be run more than once
          if isinstance(exe, (dependencies.ExternalProgram,
                              build.BuildTarget, build.CustomTarget)):
              basename = exe.name
          else:
              basename = os.path.basename(exe)
          # Take a digest of the cmd args, env, workdir, and capture. This avoids
          # collisions and also makes the name deterministic over regenerations
          # which avoids a rebuild by Ninja because the cmdline stays the same.
          data = bytes(str(sorted(env.items())) + str(cmd_args) + str(workdir) + str(capture),
                       encoding='utf-8')
          digest = hashlib.sha1(data).hexdigest()
          scratch_file = 'meson_exe_{0}_{1}.dat'.format(basename, digest)
          exe_data = os.path.join(self.environment.get_scratch_dir(), scratch_file)
          with open(exe_data, 'wb') as f:
              if isinstance(exe, dependencies.ExternalProgram):
                  exe_cmd = exe.get_command()
                  exe_needs_wrapper = False
              elif isinstance(exe, (build.BuildTarget, build.CustomTarget)):
                  exe_cmd = [self.get_target_filename_abs(exe)]
                  exe_needs_wrapper = exe.is_cross
              else:
                  exe_cmd = [exe]
                  exe_needs_wrapper = False
              is_cross_built = exe_needs_wrapper and \
                  self.environment.is_cross_build() and \
                  self.environment.cross_info.need_cross_compiler() and \
                  self.environment.cross_info.need_exe_wrapper()
              if is_cross_built:
                  exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              else:
                  exe_wrapper = None
              es = ExecutableSerialisation(basename, exe_cmd, cmd_args, env,
                                           is_cross_built, exe_wrapper, workdir,
                                           extra_paths, capture)
              pickle.dump(es, f)
          return exe_data
  
      def serialize_tests(self):
          test_data = os.path.join(self.environment.get_scratch_dir(), 'meson_test_setup.dat')
          with open(test_data, 'wb') as datafile:
              self.write_test_file(datafile)
          benchmark_data = os.path.join(self.environment.get_scratch_dir(), 'meson_benchmark_setup.dat')
          with open(benchmark_data, 'wb') as datafile:
              self.write_benchmark_file(datafile)
          return test_data, benchmark_data
  
      def determine_linker(self, target):
          '''
          If we're building a static library, there is only one static linker.
          Otherwise, we query the target for the dynamic linker.
          '''
          if isinstance(target, build.StaticLibrary):
              if target.is_cross:
                  return self.build.static_cross_linker
              else:
                  return self.build.static_linker
          l = target.get_clike_dynamic_linker()
          if not l:
              m = "Couldn't determine linker for target {!r}"
              raise MesonException(m.format(target.name))
          return l
  
      def rpaths_for_bundled_shared_libraries(self, target):
          paths = []
          for dep in target.external_deps:
              if isinstance(dep, (dependencies.ExternalLibrary, dependencies.PkgConfigDependency)):
                  la = dep.link_args
                  if len(la) == 1 and os.path.isabs(la[0]):
                      # The only link argument is an absolute path to a library file.
                      libpath = la[0]
                      if libpath.startswith(('/usr/lib', '/lib')):
                          # No point in adding system paths.
                          continue
                      if os.path.splitext(libpath)[1] not in ['.dll', '.lib', '.so']:
                          continue
                      absdir = os.path.dirname(libpath)
                      if absdir.startswith(self.environment.get_source_dir()):
                          rel_to_src = absdir[len(self.environment.get_source_dir()) + 1:]
                          assert not os.path.isabs(rel_to_src), 'rel_to_src: {} is absolute'.format(rel_to_src)
                          paths.append(os.path.join(self.build_to_src, rel_to_src))
                      else:
                          paths.append(absdir)
          return paths
  
      def determine_rpath_dirs(self, target):
          link_deps = target.get_all_link_deps()
          result = []
          for ld in link_deps:
              if ld is target:
                  continue
              prospective = self.get_target_dir(ld)
              if prospective not in result:
                  result.append(prospective)
          for rp in self.rpaths_for_bundled_shared_libraries(target):
              if rp not in result:
                  result += [rp]
          return result
  
      def object_filename_from_source(self, target, source, is_unity):
          assert isinstance(source, mesonlib.File)
          build_dir = self.environment.get_build_dir()
          rel_src = source.rel_to_builddir(self.build_to_src)
  
          if (not self.environment.is_source(rel_src) or
             self.environment.is_header(rel_src)) and not is_unity:
              return None
  
          # foo.vala files compile down to foo.c and then foo.c.o, not foo.vala.o
          if rel_src.endswith(('.vala', '.gs')):
              # See description in generate_vala_compile for this logic.
              if source.is_built:
                  if os.path.isabs(rel_src):
                      rel_src = rel_src[len(build_dir) + 1:]
                  rel_src = os.path.relpath(rel_src, self.get_target_private_dir(target))
              else:
                  rel_src = os.path.basename(rel_src)
              if is_unity:
                  return 'meson-generated_' + rel_src[:-5] + '.c.' + self.environment.get_object_suffix()
              # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
              source = 'meson-generated_' + rel_src[:-5] + '.c'
          elif source.is_built:
              if os.path.isabs(rel_src):
                  rel_src = rel_src[len(build_dir) + 1:]
              targetdir = self.get_target_private_dir(target)
              # A meson- prefixed directory is reserved; hopefully no-one creates a file name with such a weird prefix.
              source = 'meson-generated_' + os.path.relpath(rel_src, targetdir)
          else:
              if os.path.isabs(rel_src):
                  # Not from the source directory; hopefully this doesn't conflict with user's source files.
                  source = os.path.basename(rel_src)
              else:
                  source = os.path.relpath(os.path.join(build_dir, rel_src),
                                           os.path.join(self.environment.get_source_dir(), target.get_subdir()))
          return source.replace('/', '_').replace('\\', '_') + '.' + self.environment.get_object_suffix()
  
      def determine_ext_objs(self, target, extobj, proj_dir_to_build_root):
          result = []
          targetdir = self.get_target_private_dir(extobj.target)
          # With unity builds, there's just one object that contains all the
          # sources, and we only support extracting all the objects in this mode,
          # so just return that.
          if self.is_unity(target):
              comp = get_compiler_for_source(extobj.target.compilers.values(),
                                             extobj.srclist[0])
              # There is a potential conflict here, but it is unlikely that
              # anyone both enables unity builds and has a file called foo-unity.cpp.
              osrc = self.get_unity_source_file(extobj.target,
                                                comp.get_default_suffix())
              objname = self.object_filename_from_source(extobj.target, osrc, True)
              objname = objname.replace('/', '_').replace('\\', '_')
              objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
              return [objpath]
          for osrc in extobj.srclist:
              objname = self.object_filename_from_source(extobj.target, osrc, False)
              if objname:
                  objpath = os.path.join(proj_dir_to_build_root, targetdir, objname)
                  result.append(objpath)
          return result
  
      def get_pch_include_args(self, compiler, target):
          args = []
          pchpath = self.get_target_private_dir(target)
          includeargs = compiler.get_include_args(pchpath, False)
          p = target.get_pch(compiler.get_language())
          if p:
              args += compiler.get_pch_use_args(pchpath, p[0])
          return includeargs + args
  
      @staticmethod
      def escape_extra_args(compiler, args):
          # No extra escaping/quoting needed when not running on Windows
          if not mesonlib.is_windows():
              return args
          extra_args = []
          # Compiler-specific escaping is needed for -D args but not for any others
          if compiler.get_id() == 'msvc':
              # MSVC needs escaping when a -D argument ends in \ or \"
              for arg in args:
                  if arg.startswith('-D') or arg.startswith('/D'):
                      # Without extra escaping for these two, the next character
                      # gets eaten
                      if arg.endswith('\\'):
                          arg += '\\'
                      elif arg.endswith('\\"'):
                          arg = arg[:-2] + '\\\\"'
                  extra_args.append(arg)
          else:
              # MinGW GCC needs all backslashes in defines to be doubly-escaped
              # FIXME: Not sure about Cygwin or Clang
              for arg in args:
                  if arg.startswith('-D') or arg.startswith('/D'):
                      arg = arg.replace('\\', '\\\\')
                  extra_args.append(arg)
          return extra_args
  
      def generate_basic_compiler_args(self, target, compiler, no_warn_args=False):
          # Create an empty commands list, and start adding arguments from
          # various sources in the order in which they must override each other
          # starting from hard-coded defaults followed by build options and so on.
          commands = CompilerArgs(compiler)
  
          copt_proxy = OptionOverrideProxy(target.option_overrides, self.environment.coredata.compiler_options)
          # First, the trivial ones that are impossible to override.
          #
          # Add -nostdinc/-nostdinc++ if needed; can't be overridden
          commands += self.get_cross_stdlib_args(target, compiler)
          # Add things like /NOLOGO or -pipe; usually can't be overridden
          commands += compiler.get_always_args()
          # Only add warning-flags by default if the buildtype enables it, and if
          # we weren't explicitly asked to not emit warnings (for Vala, f.ex)
          if no_warn_args:
              commands += compiler.get_no_warn_args()
          elif self.get_option_for_target('buildtype', target) != 'plain':
              commands += compiler.get_warn_args(self.get_option_for_target('warning_level', target))
          # Add -Werror if werror=true is set in the build options set on the
          # command-line or default_options inside project(). This only sets the
          # action to be done for warnings if/when they are emitted, so it's ok
          # to set it after get_no_warn_args() or get_warn_args().
          if self.get_option_for_target('werror', target):
              commands += compiler.get_werror_args()
          # Add compile args for c_* or cpp_* build options set on the
          # command-line or default_options inside project().
          commands += compiler.get_option_compile_args(copt_proxy)
          # Add buildtype args: optimization level, debugging, etc.
          commands += compiler.get_buildtype_args(self.get_option_for_target('buildtype', target))
          # Add compile args added using add_project_arguments()
          commands += self.build.get_project_args(compiler, target.subproject)
          # Add compile args added using add_global_arguments()
          # These override per-project arguments
          commands += self.build.get_global_args(compiler)
          if not target.is_cross:
              # Compile args added from the env: CFLAGS/CXXFLAGS, etc. We want these
              # to override all the defaults, but not the per-target compile args.
              commands += self.environment.coredata.external_args[compiler.get_language()]
          # Always set -fPIC for shared libraries
          if isinstance(target, build.SharedLibrary):
              commands += compiler.get_pic_args()
          # Set -fPIC for static libraries by default unless explicitly disabled
          if isinstance(target, build.StaticLibrary) and target.pic:
              commands += compiler.get_pic_args()
          # Add compile args needed to find external dependencies. Link args are
          # added while generating the link command.
          # NOTE: We must preserve the order in which external deps are
          # specified, so we reverse the list before iterating over it.
          for dep in reversed(target.get_external_deps()):
              if not dep.found():
                  continue
  
              if compiler.language == 'vala':
                  if isinstance(dep, dependencies.PkgConfigDependency):
                      if dep.name == 'glib-2.0' and dep.version_reqs is not None:
                          for req in dep.version_reqs:
                              if req.startswith(('>=', '==')):
                                  commands += ['--target-glib', req[2:]]
                                  break
                      commands += ['--pkg', dep.name]
                  elif isinstance(dep, dependencies.ExternalLibrary):
                      commands += dep.get_link_args('vala')
              else:
                  commands += dep.get_compile_args()
              # Qt needs -fPIC for executables
              # XXX: We should move to -fPIC for all executables
              if isinstance(target, build.Executable):
                  commands += dep.get_exe_args(compiler)
              # For 'automagic' deps: Boost and GTest. Also dependency('threads').
              # pkg-config puts the thread flags itself via `Cflags:`
              if dep.need_threads():
                  commands += compiler.thread_flags(self.environment)
          # Fortran requires extra include directives.
          if compiler.language == 'fortran':
              for lt in target.link_targets:
                  priv_dir = self.get_target_private_dir(lt)
                  commands += compiler.get_include_args(priv_dir, False)
          return commands
  
      def build_target_link_arguments(self, compiler, deps):
          args = []
          for d in deps:
              if not (d.is_linkable_target()):
                  raise RuntimeError('Tried to link with a non-library target "%s".' % d.get_basename())
              d_arg = self.get_target_filename_for_linking(d)
              if not d_arg:
                  continue
              if isinstance(compiler, (compilers.LLVMDCompiler, compilers.DmdDCompiler)):
                  d_arg = '-L' + d_arg
              args.append(d_arg)
          return args
  
      def determine_windows_extra_paths(self, target, extra_bdeps):
          '''On Windows there is no such thing as an rpath.
          We must determine all locations of DLLs that this exe
          links to and return them so they can be used in unit
          tests.'''
          result = []
          prospectives = []
          if isinstance(target, build.Executable):
              prospectives = target.get_transitive_link_deps()
              # External deps
              for deppath in self.rpaths_for_bundled_shared_libraries(target):
                  result.append(os.path.normpath(os.path.join(self.environment.get_build_dir(), deppath)))
          for bdep in extra_bdeps:
              prospectives += bdep.get_transitive_link_deps()
          # Internal deps
          for ld in prospectives:
              if ld == '' or ld == '.':
                  continue
              dirseg = os.path.join(self.environment.get_build_dir(), self.get_target_dir(ld))
              if dirseg not in result:
                  result.append(dirseg)
          return result
  
      def write_benchmark_file(self, datafile):
          self.write_test_serialisation(self.build.get_benchmarks(), datafile)
  
      def write_test_file(self, datafile):
          self.write_test_serialisation(self.build.get_tests(), datafile)
  
      def write_test_serialisation(self, tests, datafile):
          arr = []
          for t in tests:
              exe = t.get_exe()
              if isinstance(exe, dependencies.ExternalProgram):
                  cmd = exe.get_command()
              else:
                  cmd = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(t.get_exe()))]
              is_cross = self.environment.is_cross_build() and \
                  self.environment.cross_info.need_cross_compiler() and \
                  self.environment.cross_info.need_exe_wrapper()
              if isinstance(exe, build.BuildTarget):
                  is_cross = is_cross and exe.is_cross
              if isinstance(exe, dependencies.ExternalProgram):
                  # E.g. an external verifier or simulator program run on a generated executable.
                  # Can always be run.
                  is_cross = False
              if is_cross:
                  exe_wrapper = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              else:
                  exe_wrapper = None
              if mesonlib.is_windows() or mesonlib.is_cygwin():
                  extra_paths = self.determine_windows_extra_paths(exe, [])
              else:
                  extra_paths = []
              cmd_args = []
              for a in t.cmd_args:
                  if hasattr(a, 'held_object'):
                      a = a.held_object
                  if isinstance(a, mesonlib.File):
                      a = os.path.join(self.environment.get_build_dir(), a.rel_to_builddir(self.build_to_src))
                      cmd_args.append(a)
                  elif isinstance(a, str):
                      cmd_args.append(a)
                  elif isinstance(a, build.Target):
                      cmd_args.append(self.get_target_filename(a))
                  else:
                      raise MesonException('Bad object in test command.')
              ts = TestSerialisation(t.get_name(), t.project_name, t.suite, cmd, is_cross,
                                     exe_wrapper, t.is_parallel, cmd_args, t.env,
                                     t.should_fail, t.timeout, t.workdir, extra_paths)
              arr.append(ts)
          pickle.dump(arr, datafile)
  
      def generate_depmf_install(self, d):
          if self.build.dep_manifest_name is None:
              return
          ifilename = os.path.join(self.environment.get_build_dir(), 'depmf.json')
          ofilename = os.path.join(self.environment.get_prefix(), self.build.dep_manifest_name)
          mfobj = {'type': 'dependency manifest', 'version': '1.0', 'projects': self.build.dep_manifest}
          with open(ifilename, 'w') as f:
              f.write(json.dumps(mfobj))
          # Copy file from, to, and with mode unchanged
          d.data.append([ifilename, ofilename, None])
  
      def get_regen_filelist(self):
          '''List of all files whose alteration means that the build
          definition needs to be regenerated.'''
          deps = [os.path.join(self.build_to_src, df)
                  for df in self.interpreter.get_build_def_files()]
          if self.environment.is_cross_build():
              deps.append(os.path.join(self.build_to_src,
                                       self.environment.coredata.cross_file))
          deps.append('meson-private/coredata.dat')
          if os.path.exists(os.path.join(self.environment.get_source_dir(), 'meson_options.txt')):
              deps.append(os.path.join(self.build_to_src, 'meson_options.txt'))
          for sp in self.build.subprojects.keys():
              fname = os.path.join(self.environment.get_source_dir(), sp, 'meson_options.txt')
              if os.path.isfile(fname):
                  deps.append(os.path.join(self.build_to_src, sp, 'meson_options.txt'))
          return deps
  
      def exe_object_to_cmd_array(self, exe):
          if self.environment.is_cross_build() and \
             self.environment.cross_info.need_exe_wrapper() and \
             isinstance(exe, build.BuildTarget) and exe.is_cross:
              if 'exe_wrapper' not in self.environment.cross_info.config['binaries']:
                  s = 'Can not use target %s as a generator because it is cross-built\n'
                  s += 'and no exe wrapper is defined. You might want to set it to native instead.'
                  s = s % exe.name
                  raise MesonException(s)
          if isinstance(exe, build.BuildTarget):
              exe_arr = [os.path.join(self.environment.get_build_dir(), self.get_target_filename(exe))]
          else:
              exe_arr = exe.get_command()
          return exe_arr
  
      def replace_extra_args(self, args, genlist):
          final_args = []
          for a in args:
              if a == '@EXTRA_ARGS@':
                  final_args += genlist.get_extra_args()
              else:
                  final_args.append(a)
          return final_args
  
      def replace_outputs(self, args, private_dir, output_list):
          newargs = []
          regex = re.compile('@OUTPUT(\d+)@')
          for arg in args:
              m = regex.search(arg)
              while m is not None:
                  index = int(m.group(1))
                  src = '@OUTPUT%d@' % index
                  arg = arg.replace(src, os.path.join(private_dir, output_list[index]))
                  m = regex.search(arg)
              newargs.append(arg)
          return newargs
  
      def get_build_by_default_targets(self):
          result = OrderedDict()
          # Get all build and custom targets that must be built by default
          for name, t in self.build.get_targets().items():
              if t.build_by_default or t.install or t.build_always:
                  result[name] = t
          # Get all targets used as test executables and arguments. These must
          # also be built by default. XXX: Sometime in the future these should be
          # built only before running tests.
          for t in self.build.get_tests():
              exe = t.exe
              if hasattr(exe, 'held_object'):
                  exe = exe.held_object
              if isinstance(exe, (build.CustomTarget, build.BuildTarget)):
                  result[exe.get_id()] = exe
              for arg in t.cmd_args:
                  if hasattr(arg, 'held_object'):
                      arg = arg.held_object
                  if not isinstance(arg, (build.CustomTarget, build.BuildTarget)):
                      continue
                  result[arg.get_id()] = arg
          return result
  
      def get_custom_target_provided_libraries(self, target):
          libs = []
          for t in target.get_generated_sources():
              if not isinstance(t, build.CustomTarget):
                  continue
              for f in t.get_outputs():
                  if self.environment.is_library(f):
                      libs.append(os.path.join(self.get_target_dir(t), f))
          return libs
  
      def is_unity(self, target):
          optval = self.get_option_for_target('unity', target)
          if optval == 'on' or (optval == 'subprojects' and target.subproject != ''):
              return True
          return False
  
      def get_custom_target_sources(self, target):
          '''
          Custom target sources can be of various object types; strings, File,
          BuildTarget, even other CustomTargets.
          Returns the path to them relative to the build root directory.
          '''
          srcs = []
          for i in target.get_sources():
              if hasattr(i, 'held_object'):
                  i = i.held_object
              if isinstance(i, str):
                  fname = [os.path.join(self.build_to_src, target.subdir, i)]
              elif isinstance(i, build.BuildTarget):
                  fname = [self.get_target_filename(i)]
              elif isinstance(i, build.CustomTarget):
                  fname = [os.path.join(self.get_target_dir(i), p) for p in i.get_outputs()]
              elif isinstance(i, build.GeneratedList):
                  fname = [os.path.join(self.get_target_private_dir(target), p) for p in i.get_outputs()]
              else:
                  fname = [i.rel_to_builddir(self.build_to_src)]
              if target.absolute_paths:
                  fname = [os.path.join(self.environment.get_build_dir(), f) for f in fname]
              srcs += fname
          return srcs
  
      def get_custom_target_depend_files(self, target, absolute_paths=False):
          deps = []
          for i in target.depend_files:
              if isinstance(i, mesonlib.File):
                  if absolute_paths:
                      deps.append(i.absolute_path(self.environment.get_source_dir(),
                                                  self.environment.get_build_dir()))
                  else:
                      deps.append(i.rel_to_builddir(self.build_to_src))
              else:
                  if absolute_paths:
                      deps.append(os.path.join(self.environment.get_source_dir(), target.subdir, i))
                  else:
                      deps.append(os.path.join(self.build_to_src, target.subdir, i))
          return deps
  
      def eval_custom_target_command(self, target, absolute_outputs=False):
          # We want the outputs to be absolute only when using the VS backend
          # XXX: Maybe allow the vs backend to use relative paths too?
          source_root = self.build_to_src
          build_root = '.'
          outdir = self.get_target_dir(target)
          if absolute_outputs:
              source_root = self.environment.get_source_dir()
              build_root = self.environment.get_source_dir()
              outdir = os.path.join(self.environment.get_build_dir(), outdir)
          outputs = []
          for i in target.get_outputs():
              outputs.append(os.path.join(outdir, i))
          inputs = self.get_custom_target_sources(target)
          # Evaluate the command list
          cmd = []
          for i in target.command:
              if isinstance(i, build.Executable):
                  cmd += self.exe_object_to_cmd_array(i)
                  continue
              elif isinstance(i, build.CustomTarget):
                  # GIR scanner will attempt to execute this binary but
                  # it assumes that it is in path, so always give it a full path.
                  tmp = i.get_outputs()[0]
                  i = os.path.join(self.get_target_dir(i), tmp)
              elif isinstance(i, mesonlib.File):
                  i = i.rel_to_builddir(self.build_to_src)
                  if target.absolute_paths:
                      i = os.path.join(self.environment.get_build_dir(), i)
              # FIXME: str types are blindly added ignoring 'target.absolute_paths'
              # because we can't know if they refer to a file or just a string
              elif not isinstance(i, str):
                  err_msg = 'Argument {0} is of unknown type {1}'
                  raise RuntimeError(err_msg.format(str(i), str(type(i))))
              elif '@SOURCE_ROOT@' in i:
                  i = i.replace('@SOURCE_ROOT@', source_root)
              elif '@BUILD_ROOT@' in i:
                  i = i.replace('@BUILD_ROOT@', build_root)
              elif '@DEPFILE@' in i:
                  if target.depfile is None:
                      msg = 'Custom target {!r} has @DEPFILE@ but no depfile ' \
                            'keyword argument.'.format(target.name)
                      raise MesonException(msg)
                  dfilename = os.path.join(outdir, target.depfile)
                  i = i.replace('@DEPFILE@', dfilename)
              elif '@PRIVATE_OUTDIR_' in i:
                  match = re.search('@PRIVATE_OUTDIR_(ABS_)?([^/\s*]*)@', i)
                  if not match:
                      msg = 'Custom target {!r} has an invalid argument {!r}' \
                            ''.format(target.name, i)
                      raise MesonException(msg)
                  source = match.group(0)
                  if match.group(1) is None and not target.absolute_paths:
                      lead_dir = ''
                  else:
                      lead_dir = self.environment.get_build_dir()
                  i = i.replace(source, os.path.join(lead_dir, outdir))
              cmd.append(i)
          # Substitute the rest of the template strings
          values = mesonlib.get_filenames_templates_dict(inputs, outputs)
          cmd = mesonlib.substitute_values(cmd, values)
          # This should not be necessary but removing it breaks
          # building GStreamer on Windows. The underlying issue
          # is problems with quoting backslashes on Windows
          # which is the seventh circle of hell. The downside is
          # that this breaks custom targets whose command lines
          # have backslashes. If you try to fix this be sure to
          # check that it does not break GST.
          #
          # The bug causes file paths such as c:\foo to get escaped
          # into c:\\foo.
          #
          # Unfortunately we have not been able to come up with an
          # isolated test case for this so unless you manage to come up
          # with one, the only way is to test the building with Gst's
          # setup. Note this in your MR or ping us and we will get it
          # fixed.
          #
          # https://github.com/mesonbuild/meson/pull/737
          cmd = [i.replace('\\', '/') for i in cmd]
          return inputs, outputs, cmd
  
      def run_postconf_scripts(self):
          env = {'MESON_SOURCE_ROOT': self.environment.get_source_dir(),
                 'MESON_BUILD_ROOT': self.environment.get_build_dir(),
                 'MESONINTROSPECT': ' '.join([shlex.quote(x) for x in self.environment.get_build_command() + ['introspect']]),
                 }
          child_env = os.environ.copy()
          child_env.update(env)
  
          for s in self.build.postconf_scripts:
              cmd = s['exe'] + s['args']
              subprocess.check_call(cmd, env=child_env)
  
files: mesonbuild/backend/backends.py
files: # Copyright 2012-2017 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.
  
  import os, pickle, re, shlex, subprocess
  from collections import OrderedDict
  import itertools
  from pathlib import PurePath
  
  from . import backends
  from .. import modules
  from .. import environment, mesonlib
  from .. import build
  from .. import mlog
  from .. import dependencies
  from .. import compilers
  from ..compilers import CompilerArgs
  from ..linkers import ArLinker
  from ..mesonlib import File, MesonException, OrderedSet
  from ..mesonlib import get_compiler_for_source, has_path_sep
  from .backends import CleanTrees, InstallData
  from ..build import InvalidArguments
  
  if mesonlib.is_windows():
      quote_func = lambda s: '"{}"'.format(s)
      execute_wrapper = 'cmd /c'
      rmfile_prefix = 'del /f /s /q {} &&'
  else:
      quote_func = shlex.quote
      execute_wrapper = ''
      rmfile_prefix = 'rm -f {} &&'
  
  def ninja_quote(text, is_build_line=False):
      if is_build_line:
          qcs = ('$', ' ', ':')
      else:
          qcs = ('$', ' ')
      for char in qcs:
          text = text.replace(char, '$' + char)
      if '\n' in text:
          errmsg = '''Ninja does not support newlines in rules. The content was:
  
  %s
  
  Please report this error with a test case to the Meson bug tracker.''' % text
          raise MesonException(errmsg)
      return text
  
  
  class NinjaBuildElement:
      def __init__(self, all_outputs, outfilenames, rule, infilenames):
          if isinstance(outfilenames, str):
              self.outfilenames = [outfilenames]
          else:
              self.outfilenames = outfilenames
          assert(isinstance(rule, str))
          self.rule = rule
          if isinstance(infilenames, str):
              self.infilenames = [infilenames]
          else:
              self.infilenames = infilenames
          self.deps = set()
          self.orderdeps = set()
          self.elems = []
          self.all_outputs = all_outputs
  
      def add_dep(self, dep):
          if isinstance(dep, list):
              self.deps.update(dep)
          else:
              self.deps.add(dep)
  
      def add_orderdep(self, dep):
          if isinstance(dep, list):
              self.orderdeps.update(dep)
          else:
              self.orderdeps.add(dep)
  
      def add_item(self, name, elems):
          if isinstance(elems, str):
              elems = [elems]
          self.elems.append((name, elems))
  
      def write(self, outfile):
          self.check_outputs()
          line = 'build %s: %s %s' % (' '.join([ninja_quote(i, True) for i in self.outfilenames]),
                                      self.rule,
                                      ' '.join([ninja_quote(i, True) for i in self.infilenames]))
          if len(self.deps) > 0:
              line += ' | ' + ' '.join([ninja_quote(x, True) for x in self.deps])
          if len(self.orderdeps) > 0:
              line += ' || ' + ' '.join([ninja_quote(x, True) for x in self.orderdeps])
          line += '\n'
          # This is the only way I could find to make this work on all
          # platforms including Windows command shell. Slash is a dir separator
          # on Windows, too, so all characters are unambiguous and, more importantly,
          # do not require quoting, unless explicitely specified, which is necessary for
          # the csc compiler.
          line = line.replace('\\', '/')
          outfile.write(line)
  
          # All the entries that should remain unquoted
          raw_names = {'DEPFILE', 'DESC', 'pool', 'description'}
  
          for e in self.elems:
              (name, elems) = e
              should_quote = name not in raw_names
              line = ' %s = ' % name
              newelems = []
              for i in elems:
                  if not should_quote or i == '&&': # Hackety hack hack
                      quoter = ninja_quote
                  else:
                      quoter = lambda x: ninja_quote(quote_func(x))
                  i = i.replace('\\', '\\\\')
                  if quote_func('') == '""':
                      i = i.replace('"', '\\"')
                  newelems.append(quoter(i))
              line += ' '.join(newelems)
              line += '\n'
              outfile.write(line)
          outfile.write('\n')
  
      def check_outputs(self):
          for n in self.outfilenames:
              if n in self.all_outputs:
                  raise MesonException('Multiple producers for Ninja target "%s". Please rename your targets.' % n)
              self.all_outputs[n] = True
  
  class NinjaBackend(backends.Backend):
  
      def __init__(self, build):
          super().__init__(build)
          self.name = 'ninja'
          self.ninja_filename = 'build.ninja'
          self.target_arg_cache = {}
          self.fortran_deps = {}
          self.all_outputs = {}
  
      def create_target_alias(self, to_target, outfile):
          # We need to use aliases for targets that might be used as directory
          # names to workaround a Ninja bug that breaks `ninja -t clean`.
          # This is used for 'reserved' targets such as 'test', 'install',
          # 'benchmark', etc, and also for RunTargets.
          # https://github.com/mesonbuild/meson/issues/1644
          if not to_target.startswith('meson-'):
              m = 'Invalid usage of create_target_alias with {!r}'
              raise AssertionError(m.format(to_target))
          from_target = to_target[len('meson-'):]
          elem = NinjaBuildElement(self.all_outputs, from_target, 'phony', to_target)
          elem.write(outfile)
  
      def detect_vs_dep_prefix(self, tempfilename):
          '''VS writes its dependency in a locale dependent format.
          Detect the search prefix to use.'''
          for compiler in self.build.compilers.values():
              # Have to detect the dependency format
              if compiler.id == 'msvc':
                  break
          else:
              # None of our compilers are MSVC, we're done.
              return open(tempfilename, 'a')
          filename = os.path.join(self.environment.get_scratch_dir(),
                                  'incdetect.c')
          with open(filename, 'w') as f:
              f.write('''#include<stdio.h>
  int dummy;
  ''')
  
          # The output of cl dependency information is language
          # and locale dependent. Any attempt at converting it to
          # Python strings leads to failure. We _must_ do this detection
          # in raw byte mode and write the result in raw bytes.
          pc = subprocess.Popen(['cl', '/showIncludes', '/c', 'incdetect.c'],
                                cwd=self.environment.get_scratch_dir(),
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          (stdo, _) = pc.communicate()
  
          # We want to match 'Note: including file: ' in the line
          # 'Note: including file: d:\MyDir\include\stdio.h', however
          # different locales have different messages with a different
          # number of colons. Match up to the the drive name 'd:\'.
          matchre = re.compile(rb"^(.*\s)[a-zA-Z]:\\.*stdio.h$")
          for line in stdo.split(b'\r\n'):
              match = matchre.match(line)
              if match:
                  with open(tempfilename, 'ab') as binfile:
                      binfile.write(b'msvc_deps_prefix = ' + match.group(1) + b'\n')
                  return open(tempfilename, 'a')
          raise MesonException('Could not determine vs dep dependency prefix string.')
  
      def generate(self, interp):
          self.interpreter = interp
          self.ninja_command = environment.detect_ninja(log=True)
          if self.ninja_command is None:
              raise MesonException('Could not detect Ninja v1.5 or newer')
          outfilename = os.path.join(self.environment.get_build_dir(), self.ninja_filename)
          tempfilename = outfilename + '~'
          with open(tempfilename, 'w') as outfile:
              outfile.write('# This is the build file for project "%s"\n' %
                            self.build.get_project())
              outfile.write('# It is autogenerated by the Meson build system.\n')
              outfile.write('# Do not edit by hand.\n\n')
              outfile.write('ninja_required_version = 1.5.1\n\n')
          with self.detect_vs_dep_prefix(tempfilename) as outfile:
              self.generate_rules(outfile)
              self.generate_phony(outfile)
              outfile.write('# Build rules for targets\n\n')
              for t in self.build.get_targets().values():
                  self.generate_target(t, outfile)
              outfile.write('# Test rules\n\n')
              self.generate_tests(outfile)
              outfile.write('# Install rules\n\n')
              self.generate_install(outfile)
              self.generate_dist(outfile)
              if 'b_coverage' in self.environment.coredata.base_options and \
                      self.environment.coredata.base_options['b_coverage'].value:
                  outfile.write('# Coverage rules\n\n')
                  self.generate_coverage_rules(outfile)
              outfile.write('# Suffix\n\n')
              self.generate_utils(outfile)
              self.generate_ending(outfile)
          # Only overwrite the old build file after the new one has been
          # fully created.
          os.replace(tempfilename, outfilename)
          self.generate_compdb()
  
      # http://clang.llvm.org/docs/JSONCompilationDatabase.html
      def generate_compdb(self):
          pch_compilers = ['%s_PCH' % i for i in self.build.compilers]
          native_compilers = ['%s_COMPILER' % i for i in self.build.compilers]
          cross_compilers = ['%s_CROSS_COMPILER' % i for i in self.build.cross_compilers]
          ninja_compdb = [self.ninja_command, '-t', 'compdb'] + pch_compilers + native_compilers + cross_compilers
          builddir = self.environment.get_build_dir()
          try:
              jsondb = subprocess.check_output(ninja_compdb, cwd=builddir)
              with open(os.path.join(builddir, 'compile_commands.json'), 'wb') as f:
                  f.write(jsondb)
          except Exception:
              mlog.warning('Could not create compilation database.')
  
      # Get all generated headers. Any source file might need them so
      # we need to add an order dependency to them.
      def get_generated_headers(self, target):
          header_deps = []
          # XXX: Why don't we add deps to CustomTarget headers here?
          for genlist in target.get_generated_sources():
              if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              for src in genlist.get_outputs():
                  if self.environment.is_header(src):
                      header_deps.append(self.get_target_generated_dir(target, genlist, src))
          if 'vala' in target.compilers and not isinstance(target, build.Executable):
              vala_header = File.from_built_file(self.get_target_dir(target), target.vala_header)
              header_deps.append(vala_header)
          # Recurse and find generated headers
          for dep in itertools.chain(target.link_targets, target.link_whole_targets):
              if isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
                  header_deps += self.get_generated_headers(dep)
          return header_deps
  
      def get_target_generated_sources(self, target):
          """
          Returns a dictionary with the keys being the path to the file
          (relative to the build directory) of that type and the value
          being the GeneratorList or CustomTarget that generated it.
          """
          srcs = OrderedDict()
          for gensrc in target.get_generated_sources():
              for s in gensrc.get_outputs():
                  f = self.get_target_generated_dir(target, gensrc, s)
                  srcs[f] = s
          return srcs
  
      def get_target_sources(self, target):
          srcs = OrderedDict()
          for s in target.get_sources():
              # BuildTarget sources are always mesonlib.File files which are
              # either in the source root, or generated with configure_file and
              # in the build root
              if not isinstance(s, File):
                  raise InvalidArguments('All sources in target {!r} must be of type mesonlib.File'.format(s))
              f = s.rel_to_builddir(self.build_to_src)
              srcs[f] = s
          return srcs
  
      # Languages that can mix with C or C++ but don't support unity builds yet
      # because the syntax we use for unity builds is specific to C/++/ObjC/++.
      # Assembly files cannot be unitified and neither can LLVM IR files
      langs_cant_unity = ('d', 'fortran')
  
      def get_target_source_can_unity(self, target, source):
          if isinstance(source, File):
              source = source.fname
          if self.environment.is_llvm_ir(source) or \
             self.environment.is_assembly(source):
              return False
          suffix = os.path.splitext(source)[1][1:]
          for lang in self.langs_cant_unity:
              if lang not in target.compilers:
                  continue
              if suffix in target.compilers[lang].file_suffixes:
                  return False
          return True
  
      def generate_target(self, target, outfile):
          if isinstance(target, build.CustomTarget):
              self.generate_custom_target(target, outfile)
          if isinstance(target, build.RunTarget):
              self.generate_run_target(target, outfile)
          name = target.get_id()
          if name in self.processed_targets:
              return
          self.processed_targets[name] = True
          # Generate rules for all dependency targets
          self.process_target_dependencies(target, outfile)
          # If target uses a language that cannot link to C objects,
          # just generate for that language and return.
          if isinstance(target, build.Jar):
              self.generate_jar_target(target, outfile)
              return
          if 'rust' in target.compilers:
              self.generate_rust_target(target, outfile)
              return
          if 'cs' in target.compilers:
              self.generate_cs_target(target, outfile)
              return
          if 'swift' in target.compilers:
              self.generate_swift_target(target, outfile)
              return
  
          # Now we handle the following languages:
          # ObjC++, ObjC, C++, C, D, Fortran, Vala
  
          # target_sources:
          #   Pre-existing target C/C++ sources to be built; dict of full path to
          #   source relative to build root and the original File object.
          # generated_sources:
          #   GeneratedList and CustomTarget sources to be built; dict of the full
          #   path to source relative to build root and the generating target/list
          # vala_generated_sources:
          #   Array of sources generated by valac that have to be compiled
          if 'vala' in target.compilers:
              # Sources consumed by valac are filtered out. These only contain
              # C/C++ sources, objects, generated libs, and unknown sources now.
              target_sources, generated_sources, \
                  vala_generated_sources = self.generate_vala_compile(target, outfile)
          else:
              target_sources = self.get_target_sources(target)
              generated_sources = self.get_target_generated_sources(target)
              vala_generated_sources = []
          self.scan_fortran_module_outputs(target)
          # Generate rules for GeneratedLists
          self.generate_generator_list_rules(target, outfile)
  
          # Generate rules for building the remaining source files in this target
          outname = self.get_target_filename(target)
          obj_list = []
          use_pch = self.environment.coredata.base_options.get('b_pch', False)
          is_unity = self.is_unity(target)
          if use_pch and target.has_pch():
              pch_objects = self.generate_pch(target, outfile)
          else:
              pch_objects = []
          header_deps = []
          unity_src = []
          unity_deps = [] # Generated sources that must be built before compiling a Unity target.
          header_deps += self.get_generated_headers(target)
  
          if is_unity:
              # Warn about incompatible sources if a unity build is enabled
              langs = set(target.compilers.keys())
              langs_cant = langs.intersection(self.langs_cant_unity)
              if langs_cant:
                  langs_are = langs = ', '.join(langs_cant).upper()
                  langs_are += ' are' if len(langs_cant) > 1 else ' is'
                  msg = '{} not supported in Unity builds yet, so {} ' \
                        'sources in the {!r} target will be compiled normally' \
                        ''.format(langs_are, langs, target.name)
                  mlog.log(mlog.red('FIXME'), msg)
  
          # Get a list of all generated headers that will be needed while building
          # this target's sources (generated sources and pre-existing sources).
          # This will be set as dependencies of all the target's sources. At the
          # same time, also deal with generated sources that need to be compiled.
          generated_source_files = []
          for rel_src, gensrc in generated_sources.items():
              dirpart, fnamepart = os.path.split(rel_src)
              raw_src = File(True, dirpart, fnamepart)
              if self.environment.is_source(rel_src) and not self.environment.is_header(rel_src):
                  if is_unity and self.get_target_source_can_unity(target, rel_src):
                      unity_deps.append(raw_src)
                      abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
                      unity_src.append(abs_src)
                  else:
                      generated_source_files.append(raw_src)
              elif self.environment.is_object(rel_src):
                  obj_list.append(rel_src)
              elif self.environment.is_library(rel_src):
                  pass
              else:
                  # Assume anything not specifically a source file is a header. This is because
                  # people generate files with weird suffixes (.inc, .fh) that they then include
                  # in their source files.
                  header_deps.append(raw_src)
          # These are the generated source files that need to be built for use by
          # this target. We create the Ninja build file elements for this here
          # because we need `header_deps` to be fully generated in the above loop.
          for src in generated_source_files:
              if self.environment.is_llvm_ir(src):
                  o = self.generate_llvm_ir_compile(target, outfile, src)
              else:
                  o = self.generate_single_compile(target, outfile, src, True,
                                                   header_deps=header_deps)
              obj_list.append(o)
  
          # Generate compilation targets for C sources generated from Vala
          # sources. This can be extended to other $LANG->C compilers later if
          # necessary. This needs to be separate for at least Vala
          vala_generated_source_files = []
          for src in vala_generated_sources:
              dirpart, fnamepart = os.path.split(src)
              raw_src = File(True, dirpart, fnamepart)
              if is_unity:
                  unity_src.append(os.path.join(self.environment.get_build_dir(), src))
                  header_deps.append(raw_src)
              else:
                  # Generated targets are ordered deps because the must exist
                  # before the sources compiling them are used. After the first
                  # compile we get precise dependency info from dep files.
                  # This should work in all cases. If it does not, then just
                  # move them from orderdeps to proper deps.
                  if self.environment.is_header(src):
                      header_deps.append(raw_src)
                  else:
                      # We gather all these and generate compile rules below
                      # after `header_deps` (above) is fully generated
                      vala_generated_source_files.append(raw_src)
          for src in vala_generated_source_files:
              # Passing 'vala' here signifies that we want the compile
              # arguments to be specialized for C code generated by
              # valac. For instance, no warnings should be emitted.
              obj_list.append(self.generate_single_compile(target, outfile, src, 'vala', [], header_deps))
  
          # Generate compile targets for all the pre-existing sources for this target
          for f, src in target_sources.items():
              if not self.environment.is_header(src):
                  if self.environment.is_llvm_ir(src):
                      obj_list.append(self.generate_llvm_ir_compile(target, outfile, src))
                  elif is_unity and self.get_target_source_can_unity(target, src):
                      abs_src = os.path.join(self.environment.get_build_dir(),
                                             src.rel_to_builddir(self.build_to_src))
                      unity_src.append(abs_src)
                  else:
                      obj_list.append(self.generate_single_compile(target, outfile, src, False, [], header_deps))
          obj_list += self.flatten_object_list(target)
          if is_unity:
              for src in self.generate_unity_files(target, unity_src):
                  obj_list.append(self.generate_single_compile(target, outfile, src, True, unity_deps + header_deps))
          linker = self.determine_linker(target)
          elem = self.generate_link(target, outfile, outname, obj_list, linker, pch_objects)
          self.generate_shlib_aliases(target, self.get_target_dir(target))
          elem.write(outfile)
  
      def process_target_dependencies(self, target, outfile):
          for t in target.get_dependencies():
              if t.get_id() not in self.processed_targets:
                  self.generate_target(t, outfile)
  
      def custom_target_generator_inputs(self, target, outfile):
          for s in target.sources:
              if hasattr(s, 'held_object'):
                  s = s.held_object
              if isinstance(s, build.GeneratedList):
                  self.generate_genlist_for_target(s, target, outfile)
  
      def unwrap_dep_list(self, target):
          deps = []
          for i in target.get_dependencies():
              # FIXME, should not grab element at zero but rather expand all.
              if isinstance(i, list):
                  i = i[0]
              # Add a dependency on all the outputs of this target
              for output in i.get_outputs():
                  deps.append(os.path.join(self.get_target_dir(i), output))
          return deps
  
      def generate_custom_target(self, target, outfile):
          self.custom_target_generator_inputs(target, outfile)
          (srcs, ofilenames, cmd) = self.eval_custom_target_command(target)
          deps = self.unwrap_dep_list(target)
          deps += self.get_custom_target_depend_files(target)
          desc = 'Generating {0} with a {1} command.'
          if target.build_always:
              deps.append('PHONY')
          if target.depfile is None:
              rulename = 'CUSTOM_COMMAND'
          else:
              rulename = 'CUSTOM_COMMAND_DEP'
          elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs)
          elem.add_dep(deps)
          for d in target.extra_depends:
              # Add a dependency on all the outputs of this target
              for output in d.get_outputs():
                  elem.add_dep(os.path.join(self.get_target_dir(d), output))
          serialize = False
          extra_paths = []
          # If the target requires capturing stdout, then use the serialized
          # executable wrapper to capture that output and save it to a file.
          if target.capture:
              serialize = True
          # If the command line requires a newline, also use the wrapper, as
          # ninja does not support them in its build rule syntax.
          if any('\n' in c for c in cmd):
              serialize = True
          # Windows doesn't have -rpath, so for EXEs that need DLLs built within
          # the project, we need to set PATH so the DLLs are found. We use
          # a serialized executable wrapper for that and check if the
          # CustomTarget command needs extra paths first.
          if mesonlib.is_windows() or mesonlib.is_cygwin():
              extra_bdeps = target.get_transitive_build_target_deps()
              extra_paths = self.determine_windows_extra_paths(target.command[0], extra_bdeps)
              if extra_paths:
                  serialize = True
          if serialize:
              exe_data = self.serialize_executable(target.command[0], cmd[1:],
                                                   # All targets are built from the build dir
                                                   self.environment.get_build_dir(),
                                                   extra_paths=extra_paths,
                                                   capture=ofilenames[0] if target.capture else None)
              cmd = self.environment.get_build_command() + ['--internal', 'exe', exe_data]
              cmd_type = 'meson_exe.py custom'
          else:
              cmd_type = 'custom'
          if target.depfile is not None:
              rel_dfile = os.path.join(self.get_target_dir(target), target.depfile)
              abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
              os.makedirs(abs_pdir, exist_ok=True)
              elem.add_item('DEPFILE', rel_dfile)
          cmd = self.replace_paths(target, cmd)
          elem.add_item('COMMAND', cmd)
          elem.add_item('description', desc.format(target.name, cmd_type))
          elem.write(outfile)
          self.processed_targets[target.get_id()] = True
  
      def generate_run_target(self, target, outfile):
          cmd = self.environment.get_build_command() + ['--internal', 'commandrunner']
          deps = self.unwrap_dep_list(target)
          arg_strings = []
          for i in target.args:
              if isinstance(i, str):
                  arg_strings.append(i)
              elif isinstance(i, (build.BuildTarget, build.CustomTarget)):
                  relfname = self.get_target_filename(i)
                  arg_strings.append(os.path.join(self.environment.get_build_dir(), relfname))
                  deps.append(relfname)
              elif isinstance(i, mesonlib.File):
                  relfname = i.rel_to_builddir(self.build_to_src)
                  arg_strings.append(os.path.join(self.environment.get_build_dir(), relfname))
              else:
                  raise AssertionError('Unreachable code in generate_run_target: ' + str(i))
          if target.subproject != '':
              subproject_prefix = '{}@@'.format(target.subproject)
          else:
              subproject_prefix = ''
          target_name = 'meson-{}{}'.format(subproject_prefix, target.name)
          elem = NinjaBuildElement(self.all_outputs, target_name, 'CUSTOM_COMMAND', [])
          cmd += [self.environment.get_source_dir(),
                  self.environment.get_build_dir(),
                  target.subdir] + self.environment.get_build_command()
          texe = target.command
          try:
              texe = texe.held_object
          except AttributeError:
              pass
          if isinstance(texe, build.Executable):
              abs_exe = os.path.join(self.environment.get_build_dir(), self.get_target_filename(texe))
              deps.append(self.get_target_filename(texe))
              if self.environment.is_cross_build() and \
                 self.environment.cross_info.need_exe_wrapper():
                  exe_wrap = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
                  if exe_wrap is not None:
                      cmd += [exe_wrap]
              cmd.append(abs_exe)
          elif isinstance(texe, dependencies.ExternalProgram):
              cmd += texe.get_command()
          elif isinstance(texe, build.CustomTarget):
              deps.append(self.get_target_filename(texe))
              cmd += [os.path.join(self.environment.get_build_dir(), self.get_target_filename(texe))]
          elif isinstance(texe, mesonlib.File):
              cmd.append(texe.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir()))
          else:
              cmd.append(target.command)
          cmd += arg_strings
  
          elem.add_dep(deps)
          cmd = self.replace_paths(target, cmd)
          elem.add_item('COMMAND', cmd)
          elem.add_item('description', 'Running external command %s.' % target.name)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above with the name the user specified
          self.create_target_alias(target_name, outfile)
          self.processed_targets[target.get_id()] = True
  
      def generate_coverage_rules(self, outfile):
          e = NinjaBuildElement(self.all_outputs, 'meson-coverage', 'CUSTOM_COMMAND', 'PHONY')
          e.add_item('COMMAND', self.environment.get_build_command() +
                     ['--internal', 'coverage',
                      self.environment.get_source_dir(),
                      self.environment.get_build_dir(),
                      self.environment.get_log_dir()])
          e.add_item('description', 'Generates coverage reports.')
          e.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-coverage', outfile)
          self.generate_coverage_legacy_rules(outfile)
  
      def generate_coverage_legacy_rules(self, outfile):
          (gcovr_exe, gcovr_new_rootdir, lcov_exe, genhtml_exe) = environment.find_coverage_tools()
          added_rule = False
          if gcovr_exe:
              # gcovr >= 3.1 interprets rootdir differently
              if gcovr_new_rootdir:
                  rootdir = self.environment.get_build_dir()
              else:
                  rootdir = self.environment.get_source_dir(),
              added_rule = True
              elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-xml', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-x', '-r', rootdir,
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.xml')])
              elem.add_item('DESC', 'Generating XML coverage report.')
              elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-xml', outfile)
              elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-text', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-r', rootdir,
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.txt')])
              elem.add_item('DESC', 'Generating text coverage report.')
              elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-text', outfile)
          if lcov_exe and genhtml_exe:
              added_rule = True
              htmloutdir = os.path.join(self.environment.get_log_dir(), 'coveragereport')
              covinfo = os.path.join(self.environment.get_log_dir(), 'coverage.info')
              phony_elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-html', outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
  
              subproject_dir = self.build.get_subproject_dir()
              command = [lcov_exe,
                         '--directory', self.environment.get_build_dir(),
                         '--capture',
                         '--output-file', covinfo,
                         '--no-checksum',
                         '&&', lcov_exe,
                         '--extract',
                         covinfo,
                         os.path.join(self.environment.get_source_dir(), '*'),
                         '--output-file', covinfo,
                         '&&', lcov_exe,
                         '--remove',
                         covinfo,
                         os.path.join(self.environment.get_source_dir(), subproject_dir, '*'),
                         '--output-file', covinfo,
                         '&&', genhtml_exe,
                         '--prefix', self.environment.get_build_dir(),
                         '--output-directory', htmloutdir,
                         '--title', 'Code coverage',
                         '--legend',
                         '--show-details',
                         covinfo]
              elem.add_item('COMMAND', command)
              elem.add_item('DESC', 'Generating HTML coverage report.')
              elem.write(outfile)
          elif gcovr_exe and gcovr_new_rootdir:
              added_rule = True
              htmloutdir = os.path.join(self.environment.get_log_dir(), 'coveragereport')
              phony_elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-html', outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
              command = [gcovr_exe, '--html', '--html-details', '-r', self.environment.get_build_dir(),
                         '-o', os.path.join(htmloutdir, 'index.html')]
              elem.add_item('COMMAND', command)
              elem.add_item('DESC', 'Generating HTML coverage report.')
              elem.write(outfile)
          if not added_rule:
              mlog.warning('coverage requested but neither gcovr nor lcov/genhtml found.')
  
      def generate_install(self, outfile):
          install_data_file = os.path.join(self.environment.get_scratch_dir(), 'install.dat')
          if self.environment.is_cross_build():
              bins = self.environment.cross_info.config['binaries']
              if 'strip' not in bins:
                  mlog.warning('Cross file does not specify strip binary, result will not be stripped.')
                  strip_bin = None
              else:
                  strip_bin = mesonlib.stringlistify(bins['strip'])
          else:
              strip_bin = self.environment.native_strip_bin
          d = InstallData(self.environment.get_source_dir(),
                          self.environment.get_build_dir(),
                          self.environment.get_prefix(),
                          strip_bin, self.environment.get_build_command() + ['introspect'])
          elem = NinjaBuildElement(self.all_outputs, 'meson-install', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_dep('all')
          elem.add_item('DESC', 'Installing files.')
          elem.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'install', install_data_file])
          elem.add_item('pool', 'console')
          self.generate_depmf_install(d)
          self.generate_target_install(d)
          self.generate_header_install(d)
          self.generate_man_install(d)
          self.generate_data_install(d)
          self.generate_custom_install_script(d)
          self.generate_subdir_install(d)
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-install', outfile)
  
          with open(install_data_file, 'wb') as ofile:
              pickle.dump(d, ofile)
  
      def generate_target_install(self, d):
          for t in self.build.get_targets().values():
              if not t.should_install():
                  continue
              # Find the installation directory.
              outdirs = t.get_custom_install_dir()
              custom_install_dir = False
              if outdirs[0] is not None and outdirs[0] is not True:
                  # Either the value is set, or is set to False which means
                  # we want this specific output out of many outputs to not
                  # be installed.
                  custom_install_dir = True
              elif isinstance(t, build.SharedModule):
                  outdirs[0] = self.environment.get_shared_module_dir()
              elif isinstance(t, build.SharedLibrary):
                  outdirs[0] = self.environment.get_shared_lib_dir()
              elif isinstance(t, build.StaticLibrary):
                  outdirs[0] = self.environment.get_static_lib_dir()
              elif isinstance(t, build.Executable):
                  outdirs[0] = self.environment.get_bindir()
              else:
                  assert(isinstance(t, build.BuildTarget))
                  # XXX: Add BuildTarget-specific install dir cases here
                  outdirs[0] = self.environment.get_libdir()
              # Sanity-check the outputs and install_dirs
              num_outdirs, num_out = len(outdirs), len(t.get_outputs())
              if num_outdirs != 1 and num_outdirs != num_out:
                  m = 'Target {!r} has {} outputs: {!r}, but only {} "install_dir"s were found.\n' \
                      "Pass 'false' for outputs that should not be installed and 'true' for\n" \
                      'using the default installation directory for an output.'
                  raise MesonException(m.format(t.name, num_out, t.get_outputs(), num_outdirs))
              # Install the target output(s)
              if isinstance(t, build.BuildTarget):
                  should_strip = self.get_option_for_target('strip', t)
                  # Install primary build output (library/executable/jar, etc)
                  # Done separately because of strip/aliases/rpath
                  if outdirs[0] is not False:
                      i = [self.get_target_filename(t), outdirs[0],
                           t.get_aliases(), should_strip, t.install_rpath]
                      d.targets.append(i)
                      # On toolchains/platforms that use an import library for
                      # linking (separate from the shared library with all the
                      # code), we need to install that too (dll.a/.lib).
                      if (isinstance(t, build.SharedLibrary) or isinstance(t, build.Executable)) and t.get_import_filename():
                          if custom_install_dir:
                              # If the DLL is installed into a custom directory,
                              # install the import library into the same place so
                              # it doesn't go into a surprising place
                              implib_install_dir = outdirs[0]
                          else:
                              implib_install_dir = self.environment.get_import_lib_dir()
                          # Install the import library.
                          i = [self.get_target_filename_for_linking(t),
                               implib_install_dir,
                               # It has no aliases, should not be stripped, and
                               # doesn't have an install_rpath
                               {}, False, '']
                          d.targets.append(i)
                  # Install secondary outputs. Only used for Vala right now.
                  if num_outdirs > 1:
                      for output, outdir in zip(t.get_outputs()[1:], outdirs[1:]):
                          # User requested that we not install this output
                          if outdir is False:
                              continue
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdir, {}, False, None])
              elif isinstance(t, build.CustomTarget):
                  # If only one install_dir is specified, assume that all
                  # outputs will be installed into it. This is for
                  # backwards-compatibility and because it makes sense to
                  # avoid repetition since this is a common use-case.
                  #
                  # To selectively install only some outputs, pass `false` as
                  # the install_dir for the corresponding output by index
                  if num_outdirs == 1 and num_out > 1:
                      for output in t.get_outputs():
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdirs[0], {}, False, None])
                  else:
                      for output, outdir in zip(t.get_outputs(), outdirs):
                          # User requested that we not install this output
                          if outdir is False:
                              continue
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdir, {}, False, None])
  
      def generate_custom_install_script(self, d):
          result = []
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for i in self.build.install_scripts:
              exe = i['exe']
              args = i['args']
              fixed_args = []
              for a in args:
                  a = a.replace('@SOURCE_ROOT@', srcdir)
                  a = a.replace('@BUILD_ROOT@', builddir)
                  fixed_args.append(a)
              result.append(build.RunScript(exe, fixed_args))
          d.install_scripts = result
  
      def generate_header_install(self, d):
          incroot = self.environment.get_includedir()
          headers = self.build.get_headers()
  
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for h in headers:
              outdir = h.get_custom_install_dir()
              if outdir is None:
                  outdir = os.path.join(incroot, h.get_install_subdir())
              for f in h.get_sources():
                  if not isinstance(f, File):
                      msg = 'Invalid header type {!r} can\'t be installed'
                      raise MesonException(msg.format(f))
                  abspath = f.absolute_path(srcdir, builddir)
                  i = [abspath, outdir]
                  d.headers.append(i)
  
      def generate_man_install(self, d):
          manroot = self.environment.get_mandir()
          man = self.build.get_man()
          for m in man:
              for f in m.get_sources():
                  num = f.split('.')[-1]
                  subdir = m.get_custom_install_dir()
                  if subdir is None:
                      subdir = os.path.join(manroot, 'man' + num)
                  srcabs = f.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
                  dstabs = os.path.join(subdir, os.path.basename(f.fname) + '.gz')
                  i = [srcabs, dstabs]
                  d.man.append(i)
  
      def generate_data_install(self, d):
          data = self.build.get_data()
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for de in data:
              assert(isinstance(de, build.Data))
              subdir = de.install_dir
              if not subdir:
                  subdir = os.path.join(self.environment.get_datadir(), self.interpreter.build.project_name)
              for src_file, dst_name in zip(de.sources, de.rename):
                  assert(isinstance(src_file, mesonlib.File))
                  dst_abs = os.path.join(subdir, dst_name)
                  i = [src_file.absolute_path(srcdir, builddir), dst_abs, de.install_mode]
                  d.data.append(i)
  
      def generate_subdir_install(self, d):
          for sd in self.build.get_install_subdirs():
              src_dir = os.path.join(self.environment.get_source_dir(),
                                     sd.source_subdir,
                                     sd.installable_subdir).rstrip('/')
              dst_dir = os.path.join(self.environment.get_prefix(),
                                     sd.install_dir)
              if not sd.strip_directory:
                  dst_dir = os.path.join(dst_dir, os.path.basename(src_dir))
              d.install_subdirs.append([src_dir, dst_dir, sd.install_mode,
                                        sd.exclude])
  
      def generate_tests(self, outfile):
          self.serialize_tests()
          cmd = self.environment.get_build_command(True) + ['test', '--no-rebuild']
          if not self.environment.coredata.get_builtin_option('stdsplit'):
              cmd += ['--no-stdsplit']
          if self.environment.coredata.get_builtin_option('errorlogs'):
              cmd += ['--print-errorlogs']
          elem = NinjaBuildElement(self.all_outputs, 'meson-test', 'CUSTOM_COMMAND', ['all', 'PHONY'])
          elem.add_item('COMMAND', cmd)
          elem.add_item('DESC', 'Running all tests.')
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the above-defined meson-test target
          self.create_target_alias('meson-test', outfile)
  
          # And then benchmarks.
          cmd = self.environment.get_build_command(True) + [
              'test', '--benchmark', '--logbase',
              'benchmarklog', '--num-processes=1', '--no-rebuild']
          elem = NinjaBuildElement(self.all_outputs, 'meson-benchmark', 'CUSTOM_COMMAND', ['all', 'PHONY'])
          elem.add_item('COMMAND', cmd)
          elem.add_item('DESC', 'Running benchmark suite.')
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the above-defined meson-benchmark target
          self.create_target_alias('meson-benchmark', outfile)
  
      def generate_rules(self, outfile):
          outfile.write('# Rules for compiling.\n\n')
          self.generate_compile_rules(outfile)
          outfile.write('# Rules for linking.\n\n')
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          if num_pools > 0:
              outfile.write('''pool link_pool
    depth = %d
  
  ''' % num_pools)
          if self.environment.is_cross_build():
              self.generate_static_link_rules(True, outfile)
          self.generate_static_link_rules(False, outfile)
          self.generate_dynamic_link_rules(outfile)
          outfile.write('# Other rules\n\n')
          outfile.write('rule CUSTOM_COMMAND\n')
          outfile.write(' command = $COMMAND\n')
          outfile.write(' description = $DESC\n')
          outfile.write(' restat = 1\n\n')
          # Ninja errors out if you have deps = gcc but no depfile, so we must
          # have two rules for custom commands.
          outfile.write('rule CUSTOM_COMMAND_DEP\n')
          outfile.write(' command = $COMMAND\n')
          outfile.write(' description = $DESC\n')
          outfile.write(' deps = gcc\n')
          outfile.write(' depfile = $DEPFILE\n')
          outfile.write(' restat = 1\n\n')
          outfile.write('rule REGENERATE_BUILD\n')
          c = [ninja_quote(quote_func(x)) for x in self.environment.get_build_command()] + \
              ['--internal',
               'regenerate',
               ninja_quote(quote_func(self.environment.get_source_dir())),
               ninja_quote(quote_func(self.environment.get_build_dir()))]
          outfile.write(" command = " + ' '.join(c) + ' --backend ninja\n')
          outfile.write(' description = Regenerating build files.\n')
          outfile.write(' generator = 1\n\n')
          outfile.write('\n')
  
      def generate_phony(self, outfile):
          outfile.write('# Phony build target, always out of date\n')
          outfile.write('build PHONY: phony\n')
          outfile.write('\n')
  
      def generate_jar_target(self, target, outfile):
          fname = target.get_filename()
          outname_rel = os.path.join(self.get_target_dir(target), fname)
          src_list = target.get_sources()
          class_list = []
          compiler = target.compilers['java']
          c = 'c'
          m = ''
          e = ''
          f = 'f'
          main_class = target.get_main_class()
          if main_class != '':
              e = 'e'
          for src in src_list:
              plain_class_path = self.generate_single_java_compile(src, target, compiler, outfile)
              class_list.append(plain_class_path)
          class_dep_list = [os.path.join(self.get_target_private_dir(target), i) for i in class_list]
          jar_rule = 'java_LINKER'
          commands = [c + m + e + f]
          if e != '':
              commands.append(main_class)
          commands.append(self.get_target_filename(target))
          # Java compilation can produce an arbitrary number of output
          # class files for a single source file. Thus tell jar to just
          # grab everything in the final package.
          commands += ['-C', self.get_target_private_dir(target), '.']
          elem = NinjaBuildElement(self.all_outputs, outname_rel, jar_rule, [])
          elem.add_dep(class_dep_list)
          elem.add_item('ARGS', commands)
          elem.write(outfile)
  
      def generate_cs_resource_tasks(self, target, outfile):
          args = []
          deps = []
          for r in target.resources:
              rel_sourcefile = os.path.join(self.build_to_src, target.subdir, r)
              if r.endswith('.resources'):
                  a = '-resource:' + rel_sourcefile
              elif r.endswith('.txt') or r.endswith('.resx'):
                  ofilebase = os.path.splitext(os.path.basename(r))[0] + '.resources'
                  ofilename = os.path.join(self.get_target_private_dir(target), ofilebase)
                  elem = NinjaBuildElement(self.all_outputs, ofilename, "CUSTOM_COMMAND", rel_sourcefile)
                  elem.add_item('COMMAND', ['resgen', rel_sourcefile, ofilename])
                  elem.add_item('DESC', 'Compiling resource %s.' % rel_sourcefile)
                  elem.write(outfile)
                  deps.append(ofilename)
                  a = '-resource:' + ofilename
              else:
                  raise InvalidArguments('Unknown resource file %s.' % r)
              args.append(a)
          return args, deps
  
      def generate_cs_target(self, target, outfile):
          buildtype = self.get_option_for_target('buildtype', target)
          fname = target.get_filename()
          outname_rel = os.path.join(self.get_target_dir(target), fname)
          src_list = target.get_sources()
          compiler = target.compilers['cs']
          rel_srcs = [os.path.normpath(s.rel_to_builddir(self.build_to_src)) for s in src_list]
          deps = []
          commands = CompilerArgs(compiler, target.extra_args.get('cs', []))
          commands += compiler.get_buildtype_args(buildtype)
          if isinstance(target, build.Executable):
              commands.append('-target:exe')
          elif isinstance(target, build.SharedLibrary):
              commands.append('-target:library')
          else:
              raise MesonException('Unknown C# target type.')
          (resource_args, resource_deps) = self.generate_cs_resource_tasks(target, outfile)
          commands += resource_args
          deps += resource_deps
          commands += compiler.get_output_args(outname_rel)
          for l in target.link_targets:
              lname = os.path.join(self.get_target_dir(l), l.get_filename())
              commands += compiler.get_link_args(lname)
              deps.append(lname)
          if '-g' in commands:
              outputs = [outname_rel, outname_rel + '.mdb']
          else:
              outputs = [outname_rel]
          generated_sources = self.get_target_generated_sources(target)
          for rel_src in generated_sources.keys():
              dirpart, fnamepart = os.path.split(rel_src)
              if rel_src.lower().endswith('.cs'):
                  rel_srcs.append(os.path.normpath(rel_src))
              deps.append(os.path.normpath(rel_src))
  
          for dep in target.get_external_deps():
              commands.extend_direct(dep.get_link_args())
          commands += self.build.get_project_args(compiler, target.subproject)
          commands += self.build.get_global_args(compiler)
  
          elem = NinjaBuildElement(self.all_outputs, outputs, 'cs_COMPILER', rel_srcs)
          elem.add_dep(deps)
          elem.add_item('ARGS', commands)
          elem.write(outfile)
  
          self.generate_generator_list_rules(target, outfile)
  
      def generate_single_java_compile(self, src, target, compiler, outfile):
          args = []
          args += compiler.get_buildtype_args(self.get_option_for_target('buildtype', target))
          args += self.build.get_global_args(compiler)
          args += self.build.get_project_args(compiler, target.subproject)
          args += target.get_java_args()
          args += compiler.get_output_args(self.get_target_private_dir(target))
          for i in target.include_dirs:
              for idir in i.get_incdirs():
                  args += ['-sourcepath', os.path.join(self.build_to_src, i.curdir, idir)]
          rel_src = src.rel_to_builddir(self.build_to_src)
          plain_class_path = src.fname[:-4] + 'class'
          rel_obj = os.path.join(self.get_target_private_dir(target), plain_class_path)
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler.get_language() + '_COMPILER', rel_src)
          element.add_item('ARGS', args)
          element.write(outfile)
          return plain_class_path
  
      def generate_java_link(self, outfile):
          rule = 'rule java_LINKER\n'
          command = ' command = jar $ARGS\n'
          description = ' description = Creating JAR $out.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def determine_dep_vapis(self, target):
          """
          Peek into the sources of BuildTargets we're linking with, and if any of
          them was built with Vala, assume that it also generated a .vapi file of
          the same name as the BuildTarget and return the path to it relative to
          the build directory.
          """
          result = OrderedSet()
          for dep in itertools.chain(target.link_targets, target.link_whole_targets):
              for i in dep.sources:
                  if hasattr(i, 'fname'):
                      i = i.fname
                  if i.endswith('vala'):
                      vapiname = dep.vala_vapi
                      fullname = os.path.join(self.get_target_dir(dep), vapiname)
                      result.add(fullname)
                      break
          return list(result)
  
      def split_vala_sources(self, t):
          """
          Splits the target's sources into .vala, .gs, .vapi, and other sources.
          Handles both pre-existing and generated sources.
  
          Returns a tuple (vala, vapi, others) each of which is a dictionary with
          the keys being the path to the file (relative to the build directory)
          and the value being the object that generated or represents the file.
          """
          vala = OrderedDict()
          vapi = OrderedDict()
          others = OrderedDict()
          othersgen = OrderedDict()
          # Split pre-existing sources
          for s in t.get_sources():
              # BuildTarget sources are always mesonlib.File files which are
              # either in the source root, or generated with configure_file and
              # in the build root
              if not isinstance(s, File):
                  msg = 'All sources in target {!r} must be of type ' \
                        'mesonlib.File, not {!r}'.format(t, s)
                  raise InvalidArguments(msg)
              f = s.rel_to_builddir(self.build_to_src)
              if s.endswith(('.vala', '.gs')):
                  srctype = vala
              elif s.endswith('.vapi'):
                  srctype = vapi
              else:
                  srctype = others
              srctype[f] = s
          # Split generated sources
          for gensrc in t.get_generated_sources():
              for s in gensrc.get_outputs():
                  f = self.get_target_generated_dir(t, gensrc, s)
                  if s.endswith(('.vala', '.gs')):
                      srctype = vala
                  elif s.endswith('.vapi'):
                      srctype = vapi
                  # Generated non-Vala (C/C++) sources. Won't be used for
                  # generating the Vala compile rule below.
                  else:
                      srctype = othersgen
                  # Duplicate outputs are disastrous
                  if f in srctype and srctype[f] is not gensrc:
                      msg = 'Duplicate output {0!r} from {1!r} {2!r}; ' \
                            'conflicts with {0!r} from {4!r} {3!r}' \
                            ''.format(f, type(gensrc).__name__, gensrc.name,
                                      srctype[f].name, type(srctype[f]).__name__)
                      raise InvalidArguments(msg)
                  # Store 'somefile.vala': GeneratedList (or CustomTarget)
                  srctype[f] = gensrc
          return vala, vapi, (others, othersgen)
  
      def generate_vala_compile(self, target, outfile):
          """Vala is compiled into C. Set up all necessary build steps here."""
          (vala_src, vapi_src, other_src) = self.split_vala_sources(target)
          extra_dep_files = []
          if not vala_src:
              msg = 'Vala library {!r} has no Vala or Genie source files.'
              raise InvalidArguments(msg.format(target.name))
  
          valac = target.compilers['vala']
          c_out_dir = self.get_target_private_dir(target)
          # C files generated by valac
          vala_c_src = []
          # Files generated by valac
          valac_outputs = []
          # All sources that are passed to valac on the commandline
          all_files = list(vapi_src.keys())
          # Passed as --basedir
          srcbasedir = os.path.join(self.build_to_src, target.get_subdir())
          for (vala_file, gensrc) in vala_src.items():
              all_files.append(vala_file)
              # Figure out where the Vala compiler will write the compiled C file
              #
              # If the Vala file is in a subdir of the build dir (in our case
              # because it was generated/built by something else), and is also
              # a subdir of --basedir (because the builddir is in the source
              # tree, and the target subdir is the source root), the subdir
              # components from the source root till the private builddir will be
              # duplicated inside the private builddir. Otherwise, just the
              # basename will be used.
              #
              # If the Vala file is outside the build directory, the paths from
              # the --basedir till the subdir will be duplicated inside the
              # private builddir.
              if isinstance(gensrc, (build.CustomTarget, build.GeneratedList)) or gensrc.is_built:
                  vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
                  # Check if the vala file is in a subdir of --basedir
                  abs_srcbasedir = os.path.join(self.environment.get_source_dir(), target.get_subdir())
                  abs_vala_file = os.path.join(self.environment.get_build_dir(), vala_file)
                  if PurePath(os.path.commonpath((abs_srcbasedir, abs_vala_file))) == PurePath(abs_srcbasedir):
                      vala_c_subdir = PurePath(abs_vala_file).parent.relative_to(abs_srcbasedir)
                      vala_c_file = os.path.join(vala_c_subdir, vala_c_file)
              else:
                  path_to_target = os.path.join(self.build_to_src, target.get_subdir())
                  if vala_file.startswith(path_to_target):
                      vala_c_file = os.path.splitext(os.path.relpath(vala_file, path_to_target))[0] + '.c'
                  else:
                      vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
              # All this will be placed inside the c_out_dir
              vala_c_file = os.path.join(c_out_dir, vala_c_file)
              vala_c_src.append(vala_c_file)
              valac_outputs.append(vala_c_file)
  
          args = self.generate_basic_compiler_args(target, valac)
          args += valac.get_colorout_args(self.environment.coredata.base_options.get('b_colorout').value)
          # Tell Valac to output everything in our private directory. Sadly this
          # means it will also preserve the directory components of Vala sources
          # found inside the build tree (generated sources).
          args += ['--directory', c_out_dir]
          args += ['--basedir', srcbasedir]
          if not isinstance(target, build.Executable):
              # Library name
              args += ['--library', target.name]
              # Outputted header
              hname = os.path.join(self.get_target_dir(target), target.vala_header)
              args += ['--header', hname]
              if self.is_unity(target):
                  # Without this the declarations will get duplicated in the .c
                  # files and cause a build failure when all of them are
                  # #include-d in one .c file.
                  # https://github.com/mesonbuild/meson/issues/1969
                  args += ['--use-header']
              valac_outputs.append(hname)
              # Outputted vapi file
              vapiname = os.path.join(self.get_target_dir(target), target.vala_vapi)
              # Force valac to write the vapi and gir files in the target build dir.
              # Without this, it will write it inside c_out_dir
              args += ['--vapi', os.path.join('..', target.vala_vapi)]
              valac_outputs.append(vapiname)
              target.outputs += [target.vala_header, target.vala_vapi]
              # Install header and vapi to default locations if user requests this
              if len(target.install_dir) > 1 and target.install_dir[1] is True:
                  target.install_dir[1] = self.environment.get_includedir()
              if len(target.install_dir) > 2 and target.install_dir[2] is True:
                  target.install_dir[2] = os.path.join(self.environment.get_datadir(), 'vala', 'vapi')
              # Generate GIR if requested
              if isinstance(target.vala_gir, str):
                  girname = os.path.join(self.get_target_dir(target), target.vala_gir)
                  args += ['--gir', os.path.join('..', target.vala_gir)]
                  valac_outputs.append(girname)
                  target.outputs.append(target.vala_gir)
                  # Install GIR to default location if requested by user
                  if len(target.install_dir) > 3 and target.install_dir[3] is True:
                      target.install_dir[3] = os.path.join(self.environment.get_datadir(), 'gir-1.0')
          # Detect gresources and add --gresources arguments for each
          for (gres, gensrc) in other_src[1].items():
              if isinstance(gensrc, modules.GResourceTarget):
                  gres_xml, = self.get_custom_target_sources(gensrc)
                  args += ['--gresources=' + gres_xml]
          extra_args = []
  
          for a in target.extra_args.get('vala', []):
              if isinstance(a, File):
                  relname = a.rel_to_builddir(self.build_to_src)
                  extra_dep_files.append(relname)
                  extra_args.append(relname)
              else:
                  extra_args.append(a)
          dependency_vapis = self.determine_dep_vapis(target)
          extra_dep_files += dependency_vapis
          args += extra_args
          element = NinjaBuildElement(self.all_outputs, valac_outputs,
                                      valac.get_language() + '_COMPILER',
                                      all_files + dependency_vapis)
          element.add_item('ARGS', args)
          element.add_dep(extra_dep_files)
          element.write(outfile)
          return other_src[0], other_src[1], vala_c_src
  
      def generate_rust_target(self, target, outfile):
          rustc = target.compilers['rust']
          relsrc = []
          for i in target.get_sources():
              if not rustc.can_compile(i):
                  raise InvalidArguments('Rust target %s contains a non-rust source file.' % target.get_basename())
              relsrc.append(i.rel_to_builddir(self.build_to_src))
          target_name = os.path.join(target.subdir, target.get_filename())
          args = ['--crate-type']
          if isinstance(target, build.Executable):
              cratetype = 'bin'
          elif hasattr(target, 'rust_crate_type'):
              cratetype = target.rust_crate_type
          elif isinstance(target, build.SharedLibrary):
              cratetype = 'dylib'
          elif isinstance(target, build.StaticLibrary):
              cratetype = 'rlib'
          else:
              raise InvalidArguments('Unknown target type for rustc.')
          args.append(cratetype)
          args += ['--crate-name', target.name]
          args += rustc.get_buildtype_args(self.get_option_for_target('buildtype', target))
          depfile = os.path.join(target.subdir, target.name + '.d')
          args += ['--emit', 'dep-info={}'.format(depfile), '--emit', 'link']
          args += target.get_extra_args('rust')
          args += ['-o', os.path.join(target.subdir, target.get_filename())]
          orderdeps = [os.path.join(t.subdir, t.get_filename()) for t in target.link_targets]
          linkdirs = OrderedDict()
          for d in target.link_targets:
              linkdirs[d.subdir] = True
              # specify `extern CRATE_NAME=OUTPUT_FILE` for each Rust
              # dependency, so that collisions with libraries in rustc's
              # sysroot don't cause ambiguity
              args += ['--extern', '{}={}'.format(d.name, os.path.join(d.subdir, d.filename))]
          for d in linkdirs.keys():
              if d == '':
                  d = '.'
              args += ['-L', d]
          has_shared_deps = False
          for dep in target.get_dependencies():
              if isinstance(dep, build.SharedLibrary):
                  has_shared_deps = True
          if isinstance(target, build.SharedLibrary) or has_shared_deps:
              # add prefer-dynamic if any of the Rust libraries we link
              # against are dynamic, otherwise we'll end up with
              # multiple implementations of crates
              args += ['-C', 'prefer-dynamic']
  
              # build the usual rpath arguments as well...
  
              # Set runtime-paths so we can run executables without needing to set
              # LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows.
              if has_path_sep(target.name):
                  # Target names really should not have slashes in them, but
                  # unfortunately we did not check for that and some downstream projects
                  # now have them. Once slashes are forbidden, remove this bit.
                  target_slashname_workaround_dir = os.path.join(os.path.dirname(target.name),
                                                                 self.get_target_dir(target))
              else:
                  target_slashname_workaround_dir = self.get_target_dir(target)
              rpath_args = rustc.build_rpath_args(self.environment.get_build_dir(),
                                                  target_slashname_workaround_dir,
                                                  self.determine_rpath_dirs(target),
                                                  target.build_rpath,
                                                  target.install_rpath)
              # ... but then add rustc's sysroot to account for rustup
              # installations
              for rpath_arg in rpath_args:
                  args += ['-C', 'link-arg=' + rpath_arg + ':' + os.path.join(rustc.get_sysroot(), 'lib')]
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          compiler_name = 'rust%s_COMPILER' % crstr
          element = NinjaBuildElement(self.all_outputs, target_name, compiler_name, relsrc)
          if len(orderdeps) > 0:
              element.add_orderdep(orderdeps)
          element.add_item('ARGS', args)
          element.add_item('targetdep', depfile)
          element.add_item('cratetype', cratetype)
          element.write(outfile)
          if isinstance(target, build.SharedLibrary):
              self.generate_shsym(outfile, target)
  
      def swift_module_file_name(self, target):
          return os.path.join(self.get_target_private_dir(target),
                              self.target_swift_modulename(target) + '.swiftmodule')
  
      def target_swift_modulename(self, target):
          return target.name
  
      def is_swift_target(self, target):
          for s in target.sources:
              if s.endswith('swift'):
                  return True
          return False
  
      def determine_swift_dep_modules(self, target):
          result = []
          for l in target.link_targets:
              if self.is_swift_target(l):
                  result.append(self.swift_module_file_name(l))
          return result
  
      def determine_swift_dep_dirs(self, target):
          result = []
          for l in target.link_targets:
              result.append(self.get_target_private_dir_abs(l))
          return result
  
      def get_swift_link_deps(self, target):
          result = []
          for l in target.link_targets:
              result.append(self.get_target_filename(l))
          return result
  
      def split_swift_generated_sources(self, target):
          all_srcs = self.get_target_generated_sources(target)
          srcs = []
          others = []
          for i in all_srcs:
              if i.endswith('.swift'):
                  srcs.append(i)
              else:
                  others.append(i)
          return srcs, others
  
      def generate_swift_target(self, target, outfile):
          module_name = self.target_swift_modulename(target)
          swiftc = target.compilers['swift']
          abssrc = []
          abs_headers = []
          header_imports = []
          for i in target.get_sources():
              if swiftc.can_compile(i):
                  relsrc = i.rel_to_builddir(self.build_to_src)
                  abss = os.path.normpath(os.path.join(self.environment.get_build_dir(), relsrc))
                  abssrc.append(abss)
              elif self.environment.is_header(i):
                  relh = i.rel_to_builddir(self.build_to_src)
                  absh = os.path.normpath(os.path.join(self.environment.get_build_dir(), relh))
                  abs_headers.append(absh)
                  header_imports += swiftc.get_header_import_args(absh)
              else:
                  raise InvalidArguments('Swift target %s contains a non-swift source file.' % target.get_basename())
          os.makedirs(self.get_target_private_dir_abs(target), exist_ok=True)
          compile_args = swiftc.get_compile_only_args()
          compile_args += swiftc.get_module_args(module_name)
          compile_args += self.build.get_project_args(swiftc, target.subproject)
          compile_args += self.build.get_global_args(swiftc)
          for i in reversed(target.get_include_dirs()):
              basedir = i.get_curdir()
              for d in i.get_incdirs():
                  if d not in ('', '.'):
                      expdir = os.path.join(basedir, d)
                  else:
                      expdir = basedir
                  srctreedir = os.path.normpath(os.path.join(self.environment.get_build_dir(), self.build_to_src, expdir))
                  sargs = swiftc.get_include_args(srctreedir)
                  compile_args += sargs
          link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target)))
          link_args += self.build.get_project_link_args(swiftc, target.subproject)
          link_args += self.build.get_global_link_args(swiftc)
          rundir = self.get_target_private_dir(target)
          out_module_name = self.swift_module_file_name(target)
          in_module_files = self.determine_swift_dep_modules(target)
          abs_module_dirs = self.determine_swift_dep_dirs(target)
          module_includes = []
          for x in abs_module_dirs:
              module_includes += swiftc.get_include_args(x)
          link_deps = self.get_swift_link_deps(target)
          abs_link_deps = [os.path.join(self.environment.get_build_dir(), x) for x in link_deps]
          for d in target.link_targets:
              reldir = self.get_target_dir(d)
              if reldir == '':
                  reldir = '.'
              link_args += ['-L', os.path.normpath(os.path.join(self.environment.get_build_dir(), reldir))]
          (rel_generated, _) = self.split_swift_generated_sources(target)
          abs_generated = [os.path.join(self.environment.get_build_dir(), x) for x in rel_generated]
          # We need absolute paths because swiftc needs to be invoked in a subdir
          # and this is the easiest way about it.
          objects = [] # Relative to swift invocation dir
          rel_objects = [] # Relative to build.ninja
          for i in abssrc + abs_generated:
              base = os.path.basename(i)
              oname = os.path.splitext(base)[0] + '.o'
              objects.append(oname)
              rel_objects.append(os.path.join(self.get_target_private_dir(target), oname))
  
          # Swiftc does not seem to be able to emit objects and module files in one go.
          elem = NinjaBuildElement(self.all_outputs, rel_objects,
                                   'swift_COMPILER',
                                   abssrc)
          elem.add_dep(in_module_files + rel_generated)
          elem.add_dep(abs_headers)
          elem.add_item('ARGS', compile_args + header_imports + abs_generated + module_includes)
          elem.add_item('RUNDIR', rundir)
          elem.write(outfile)
          elem = NinjaBuildElement(self.all_outputs, out_module_name,
                                   'swift_COMPILER',
                                   abssrc)
          elem.add_dep(in_module_files + rel_generated)
          elem.add_item('ARGS', compile_args + abs_generated + module_includes + swiftc.get_mod_gen_args())
          elem.add_item('RUNDIR', rundir)
          elem.write(outfile)
          if isinstance(target, build.StaticLibrary):
              elem = self.generate_link(target, outfile, self.get_target_filename(target),
                                        rel_objects, self.build.static_linker)
              elem.write(outfile)
          elif isinstance(target, build.Executable):
              elem = NinjaBuildElement(self.all_outputs, self.get_target_filename(target), 'swift_COMPILER', [])
              elem.add_dep(rel_objects)
              elem.add_dep(link_deps)
              elem.add_item('ARGS', link_args + swiftc.get_std_exe_link_args() + objects + abs_link_deps)
              elem.add_item('RUNDIR', rundir)
              elem.write(outfile)
          else:
              raise MesonException('Swift supports only executable and static library targets.')
  
      def generate_static_link_rules(self, is_cross, outfile):
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          if 'java' in self.build.compilers:
              if not is_cross:
                  self.generate_java_link(outfile)
          if is_cross:
              if self.environment.cross_info.need_cross_compiler():
                  static_linker = self.build.static_cross_linker
              else:
                  static_linker = self.build.static_linker
              crstr = '_CROSS'
          else:
              static_linker = self.build.static_linker
              crstr = ''
          if static_linker is None:
              return
          rule = 'rule STATIC%s_LINKER\n' % crstr
          # We don't use @file.rsp on Windows with ArLinker because llvm-ar and
          # gcc-ar blindly pass the --plugin argument to `ar` and you cannot pass
          # options as arguments while using the @file.rsp syntax.
          # See: https://github.com/mesonbuild/meson/issues/1646
          if mesonlib.is_windows() and not isinstance(static_linker, ArLinker):
              command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = $LINK_ARGS {output_args} $in
  '''
          else:
              command_template = ' command = {executable} $LINK_ARGS {output_args} $in\n'
          cmdlist = []
          # FIXME: Must normalize file names with pathlib.Path before writing
          #        them out to fix this properly on Windows. See:
          # https://github.com/mesonbuild/meson/issues/1517
          # https://github.com/mesonbuild/meson/issues/1526
          if isinstance(static_linker, ArLinker) and not mesonlib.is_windows():
              # `ar` has no options to overwrite archives. It always appends,
              # which is never what we want. Delete an existing library first if
              # it exists. https://github.com/mesonbuild/meson/issues/1355
              cmdlist = [execute_wrapper, rmfile_prefix.format('$out')]
          cmdlist += static_linker.get_exelist()
          command = command_template.format(
              executable=' '.join(cmdlist),
              output_args=' '.join(static_linker.get_output_args('$out')))
          description = ' description = Linking static target $out.\n\n'
          outfile.write(rule)
          outfile.write(command)
          if num_pools > 0:
              outfile.write(' pool = link_pool\n')
          outfile.write(description)
  
      def generate_dynamic_link_rules(self, outfile):
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          ctypes = [(self.build.compilers, False)]
          if self.environment.is_cross_build():
              if self.environment.cross_info.need_cross_compiler():
                  ctypes.append((self.build.cross_compilers, True))
              else:
                  # Native compiler masquerades as the cross compiler.
                  ctypes.append((self.build.compilers, True))
          else:
              ctypes.append((self.build.cross_compilers, True))
          for (complist, is_cross) in ctypes:
              for langname, compiler in complist.items():
                  if langname == 'java' \
                          or langname == 'vala' \
                          or langname == 'rust' \
                          or langname == 'cs':
                      continue
                  crstr = ''
                  cross_args = []
                  if is_cross:
                      crstr = '_CROSS'
                      try:
                          cross_args = self.environment.cross_info.config['properties'][langname + '_link_args']
                      except KeyError:
                          pass
                  rule = 'rule %s%s_LINKER\n' % (langname, crstr)
                  if mesonlib.is_windows():
                      command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = $ARGS  {output_args} $in $LINK_ARGS {cross_args} $aliasing
  '''
                  else:
                      command_template = ' command = {executable} $ARGS {output_args} $in $LINK_ARGS {cross_args} $aliasing\n'
                  command = command_template.format(
                      executable=' '.join(compiler.get_linker_exelist()),
                      cross_args=' '.join(cross_args),
                      output_args=' '.join(compiler.get_linker_output_args('$out'))
                  )
                  description = ' description = Linking target $out.\n'
                  outfile.write(rule)
                  outfile.write(command)
                  if num_pools > 0:
                      outfile.write(' pool = link_pool\n')
                  outfile.write(description)
                  outfile.write('\n')
          outfile.write('\n')
          args = [ninja_quote(quote_func(x)) for x in self.environment.get_build_command()] + \
              ['--internal',
               'symbolextractor',
               '$in',
               '$out']
          symrule = 'rule SHSYM\n'
          symcmd = ' command = ' + ' '.join(args) + ' $CROSS\n'
          synstat = ' restat = 1\n'
          syndesc = ' description = Generating symbol file $out.\n'
          outfile.write(symrule)
          outfile.write(symcmd)
          outfile.write(synstat)
          outfile.write(syndesc)
          outfile.write('\n')
  
      def generate_java_compile_rule(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Java object $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_cs_compile_rule(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
  
          if mesonlib.is_windows():
              command = ''' command = {executable}  @$out.rsp
   rspfile = $out.rsp
   rspfile_content =  $ARGS  $in
  '''.format(executable=invoc)
          else:
              command = ' command = %s $ARGS $in\n' % invoc
  
          description = ' description = Compiling C Sharp target $out.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_vala_compile_rules(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Vala source $in.\n'
          restat = ' restat = 1\n' # ValaC does this always to take advantage of it.
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write(restat)
          outfile.write('\n')
  
      def generate_rust_compile_rules(self, compiler, outfile, is_cross):
          crstr = ''
          if is_cross:
              crstr = '_CROSS'
          rule = 'rule %s%s_COMPILER\n' % (compiler.get_language(), crstr)
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Rust source $in.\n'
          depfile = ' depfile = $targetdep\n'
  
          depstyle = ' deps = gcc\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write(depfile)
          outfile.write(depstyle)
          outfile.write('\n')
  
      def generate_swift_compile_rules(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          full_exe = [ninja_quote(x) for x in self.environment.get_build_command()] + [
              '--internal',
              'dirchanger',
              '$RUNDIR',
          ]
          invoc = (' '.join(full_exe) + ' ' +
                   ' '.join(ninja_quote(i) for i in compiler.get_exelist()))
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Swift source $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_fortran_dep_hack(self, outfile):
          if mesonlib.is_windows():
              cmd = 'cmd /C ""'
          else:
              cmd = 'true'
          template = '''# Workaround for these issues:
  # https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485
  rule FORTRAN_DEP_HACK
   command = %s
   description = Dep hack
   restat = 1
  
  '''
          outfile.write(template % cmd)
  
      def generate_llvm_ir_compile_rule(self, compiler, is_cross, outfile):
          if getattr(self, 'created_llvm_ir_rule', False):
              return
          rule = 'rule llvm_ir{}_COMPILER\n'.format('_CROSS' if is_cross else '')
          if mesonlib.is_windows():
              command_template = ' command = {executable} @$out.rsp\n' \
                                 ' rspfile = $out.rsp\n' \
                                 ' rspfile_content = {cross_args} $ARGS {output_args} {compile_only_args} $in\n'
          else:
              command_template = ' command = {executable} {cross_args} $ARGS {output_args} {compile_only_args} $in\n'
          command = command_template.format(
              executable=' '.join([ninja_quote(i) for i in compiler.get_exelist()]),
              cross_args=' '.join(self.get_cross_info_lang_args(compiler.language, is_cross)),
              output_args=' '.join(compiler.get_output_args('$out')),
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Compiling LLVM IR object $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
          self.created_llvm_ir_rule = True
  
      def get_cross_info_lang_args(self, lang, is_cross):
          if is_cross:
              try:
                  return self.environment.cross_info.config['properties'][lang + '_args']
              except KeyError:
                  pass
          return []
  
      def generate_compile_rule_for(self, langname, compiler, is_cross, outfile):
          if langname == 'java':
              if not is_cross:
                  self.generate_java_compile_rule(compiler, outfile)
              return
          if langname == 'cs':
              if not is_cross:
                  self.generate_cs_compile_rule(compiler, outfile)
              return
          if langname == 'vala':
              if not is_cross:
                  self.generate_vala_compile_rules(compiler, outfile)
              return
          if langname == 'rust':
              self.generate_rust_compile_rules(compiler, outfile, is_cross)
              return
          if langname == 'swift':
              if not is_cross:
                  self.generate_swift_compile_rules(compiler, outfile)
              return
          if langname == 'fortran':
              self.generate_fortran_dep_hack(outfile)
          if is_cross:
              crstr = '_CROSS'
          else:
              crstr = ''
          rule = 'rule %s%s_COMPILER\n' % (langname, crstr)
          depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
          quoted_depargs = []
          for d in depargs:
              if d != '$out' and d != '$in':
                  d = quote_func(d)
              quoted_depargs.append(d)
          cross_args = self.get_cross_info_lang_args(langname, is_cross)
          if mesonlib.is_windows():
              command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in
  '''
          else:
              command_template = ' command = {executable} {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in\n'
          command = command_template.format(
              executable=' '.join([ninja_quote(i) for i in compiler.get_exelist()]),
              cross_args=' '.join(cross_args),
              dep_args=' '.join(quoted_depargs),
              output_args=' '.join(compiler.get_output_args('$out')),
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Compiling %s object $out.\n' % compiler.get_display_language()
          if compiler.get_id() == 'msvc':
              deps = ' deps = msvc\n'
          else:
              deps = ' deps = gcc\n'
              deps += ' depfile = $DEPFILE\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(deps)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_pch_rule_for(self, langname, compiler, is_cross, outfile):
          if langname != 'c' and langname != 'cpp':
              return
          if is_cross:
              crstr = '_CROSS'
          else:
              crstr = ''
          rule = 'rule %s%s_PCH\n' % (langname, crstr)
          depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
          cross_args = []
          if is_cross:
              try:
                  cross_args = self.environment.cross_info.config['properties'][langname + '_args']
              except KeyError:
                  pass
  
          quoted_depargs = []
          for d in depargs:
              if d != '$out' and d != '$in':
                  d = quote_func(d)
              quoted_depargs.append(d)
          if compiler.get_id() == 'msvc':
              output = ''
          else:
              output = ' '.join(compiler.get_output_args('$out'))
          command = " command = {executable} {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in\n".format(
              executable=' '.join(compiler.get_exelist()),
              cross_args=' '.join(cross_args),
              dep_args=' '.join(quoted_depargs),
              output_args=output,
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Precompiling header %s.\n' % '$in'
          if compiler.get_id() == 'msvc':
              deps = ' deps = msvc\n'
          else:
              deps = ' deps = gcc\n'
              deps += ' depfile = $DEPFILE\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(deps)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_compile_rules(self, outfile):
          for langname, compiler in self.build.compilers.items():
              if compiler.get_id() == 'clang':
                  self.generate_llvm_ir_compile_rule(compiler, False, outfile)
              self.generate_compile_rule_for(langname, compiler, False, outfile)
              self.generate_pch_rule_for(langname, compiler, False, outfile)
          if self.environment.is_cross_build():
              # In case we are going a target-only build, make the native compilers
              # masquerade as cross compilers.
              if self.environment.cross_info.need_cross_compiler():
                  cclist = self.build.cross_compilers
              else:
                  cclist = self.build.compilers
              for langname, compiler in cclist.items():
                  if compiler.get_id() == 'clang':
                      self.generate_llvm_ir_compile_rule(compiler, True, outfile)
                  self.generate_compile_rule_for(langname, compiler, True, outfile)
                  self.generate_pch_rule_for(langname, compiler, True, outfile)
          outfile.write('\n')
  
      def generate_generator_list_rules(self, target, outfile):
          # CustomTargets have already written their rules and
          # CustomTargetIndexes don't actually get generated, so write rules for
          # GeneratedLists here
          for genlist in target.get_generated_sources():
              if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              self.generate_genlist_for_target(genlist, target, outfile)
  
      def replace_paths(self, target, args, override_subdir=None):
          if override_subdir:
              source_target_dir = os.path.join(self.build_to_src, override_subdir)
          else:
              source_target_dir = self.get_target_source_dir(target)
          relout = self.get_target_private_dir(target)
          args = [x.replace("@SOURCE_DIR@", self.build_to_src).replace("@BUILD_DIR@", relout)
                  for x in args]
          args = [x.replace("@CURRENT_SOURCE_DIR@", source_target_dir) for x in args]
          args = [x.replace("@SOURCE_ROOT@", self.build_to_src).replace("@BUILD_ROOT@", '.')
                  for x in args]
          args = [x.replace('\\', '/') for x in args]
          return args
  
      def generate_genlist_for_target(self, genlist, target, outfile):
          generator = genlist.get_generator()
          subdir = genlist.subdir
          exe = generator.get_exe()
          exe_arr = self.exe_object_to_cmd_array(exe)
          infilelist = genlist.get_inputs()
          outfilelist = genlist.get_outputs()
          extra_dependencies = [os.path.join(self.build_to_src, i) for i in genlist.extra_depends]
          for i in range(len(infilelist)):
              if len(generator.outputs) == 1:
                  sole_output = os.path.join(self.get_target_private_dir(target), outfilelist[i])
              else:
                  sole_output = ''
              curfile = infilelist[i]
              infilename = curfile.rel_to_builddir(self.build_to_src)
              base_args = generator.get_arglist(infilename)
              outfiles = genlist.get_outputs_for(curfile)
              outfiles = [os.path.join(self.get_target_private_dir(target), of) for of in outfiles]
              if generator.depfile is None:
                  rulename = 'CUSTOM_COMMAND'
                  args = base_args
              else:
                  rulename = 'CUSTOM_COMMAND_DEP'
                  depfilename = generator.get_dep_outname(infilename)
                  depfile = os.path.join(self.get_target_private_dir(target), depfilename)
                  args = [x.replace('@DEPFILE@', depfile) for x in base_args]
              args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output)
                      for x in args]
              args = self.replace_outputs(args, self.get_target_private_dir(target), outfilelist)
              # We have consumed output files, so drop them from the list of remaining outputs.
              if sole_output == '':
                  outfilelist = outfilelist[len(generator.outputs):]
              args = self.replace_paths(target, args, override_subdir=subdir)
              cmdlist = exe_arr + self.replace_extra_args(args, genlist)
              if generator.capture:
                  exe_data = self.serialize_executable(
                      cmdlist[0],
                      cmdlist[1:],
                      self.environment.get_build_dir(),
                      capture=outfiles[0]
                  )
                  cmd = self.environment.get_build_command() + ['--internal', 'exe', exe_data]
                  abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
                  os.makedirs(abs_pdir, exist_ok=True)
              else:
                  cmd = cmdlist
  
              elem = NinjaBuildElement(self.all_outputs, outfiles, rulename, infilename)
              if generator.depfile is not None:
                  elem.add_item('DEPFILE', depfile)
              if len(extra_dependencies) > 0:
                  elem.add_dep(extra_dependencies)
              elem.add_item('DESC', 'Generating {!r}.'.format(sole_output))
              if isinstance(exe, build.BuildTarget):
                  elem.add_dep(self.get_target_filename(exe))
              elem.add_item('COMMAND', cmd)
              elem.write(outfile)
  
      def scan_fortran_module_outputs(self, target):
          compiler = None
          for lang, c in self.build.compilers.items():
              if lang == 'fortran':
                  compiler = c
                  break
          if compiler is None:
              self.fortran_deps[target.get_basename()] = {}
              return
          modre = re.compile(r"\s*module\s+(\w+)", re.IGNORECASE)
          module_files = {}
          for s in target.get_sources():
              # FIXME, does not work for Fortran sources generated by
              # custom_target() and generator() as those are run after
              # the configuration (configure_file() is OK)
              if not compiler.can_compile(s):
                  continue
              filename = s.absolute_path(self.environment.get_source_dir(),
                                         self.environment.get_build_dir())
              # Some Fortran editors save in weird encodings,
              # but all the parts we care about are in ASCII.
              with open(filename, errors='ignore') as f:
                  for line in f:
                      modmatch = modre.match(line)
                      if modmatch is not None:
                          modname = modmatch.group(1).lower()
                          if modname == 'procedure':
                              # MODULE PROCEDURE construct
                              continue
                          if modname in module_files:
                              raise InvalidArguments(
                                  'Namespace collision: module %s defined in '
                                  'two files %s and %s.' %
                                  (modname, module_files[modname], s))
                          module_files[modname] = s
          self.fortran_deps[target.get_basename()] = module_files
  
      def get_fortran_deps(self, compiler, src, target):
          mod_files = []
          usere = re.compile(r"\s*use\s+(\w+)", re.IGNORECASE)
          dirname = self.get_target_private_dir(target)
          tdeps = self.fortran_deps[target.get_basename()]
          with open(src) as f:
              for line in f:
                  usematch = usere.match(line)
                  if usematch is not None:
                      usename = usematch.group(1).lower()
                      if usename not in tdeps:
                          # The module is not provided by any source file. This
                          # is due to:
                          #   a) missing file/typo/etc
                          #   b) using a module provided by the compiler, such as
                          #      OpenMP
                          # There's no easy way to tell which is which (that I
                          # know of) so just ignore this and go on. Ideally we
                          # would print a warning message to the user but this is
                          # a common occurrence, which would lead to lots of
                          # distracting noise.
                          continue
                      mod_source_file = tdeps[usename]
                      # Check if a source uses a module it exports itself.
                      # Potential bug if multiple targets have a file with
                      # the same name.
                      if mod_source_file.fname == os.path.basename(src):
                          continue
                      mod_name = compiler.module_name_to_filename(
                          usematch.group(1))
                      mod_files.append(os.path.join(dirname, mod_name))
          return mod_files
  
      def get_cross_stdlib_args(self, target, compiler):
          if not target.is_cross:
              return []
          if not self.environment.cross_info.has_stdlib(compiler.language):
              return []
          return compiler.get_no_stdinc_args()
  
      def get_compile_debugfile_args(self, compiler, target, objfile):
          if compiler.id != 'msvc':
              return []
          # The way MSVC uses PDB files is documented exactly nowhere so
          # the following is what we have been able to decipher via
          # reverse engineering.
          #
          # Each object file gets the path of its PDB file written
          # inside it.  This can be either the final PDB (for, say,
          # foo.exe) or an object pdb (for foo.obj). If the former, then
          # each compilation step locks the pdb file for writing, which
          # is a bottleneck and object files from one target can not be
          # used in a different target. The latter seems to be the
          # sensible one (and what Unix does) but there is a catch.  If
          # you try to use precompiled headers MSVC will error out
          # because both source and pch pdbs go in the same file and
          # they must be the same.
          #
          # This means:
          #
          # - pch files must be compiled anew for every object file (negating
          #   the entire point of having them in the first place)
          # - when using pch, output must go to the target pdb
          #
          # Since both of these are broken in some way, use the one that
          # works for each target. This unfortunately means that you
          # can't combine pch and object extraction in a single target.
          #
          # PDB files also lead to filename collisions. A target foo.exe
          # has a corresponding foo.pdb. A shared library foo.dll _also_
          # has pdb file called foo.pdb. So will a static library
          # foo.lib, which clobbers both foo.pdb _and_ the dll file's
          # export library called foo.lib (by default, currently we name
          # them libfoo.a to avoidt this issue). You can give the files
          # unique names such as foo_exe.pdb but VC also generates a
          # bunch of other files which take their names from the target
          # basename (i.e. "foo") and stomp on each other.
          #
          # CMake solves this problem by doing two things. First of all
          # static libraries do not generate pdb files at
          # all. Presumably you don't need them and VC is smart enough
          # to look up the original data when linking (speculation, not
          # tested). The second solution is that you can only have
          # target named "foo" as an exe, shared lib _or_ static
          # lib. This makes filename collisions not happen. The downside
          # is that you can't have an executable foo that uses a shared
          # library libfoo.so, which is a common idiom on Unix.
          #
          # If you feel that the above is completely wrong and all of
          # this is actually doable, please send patches.
  
          if target.has_pch():
              tfilename = self.get_target_filename_abs(target)
              return compiler.get_compile_debugfile_args(tfilename, pch=True)
          else:
              return compiler.get_compile_debugfile_args(objfile, pch=False)
  
      def get_link_debugfile_args(self, linker, target, outname):
          return linker.get_link_debugfile_args(outname)
  
      def generate_llvm_ir_compile(self, target, outfile, src):
          compiler = get_compiler_for_source(target.compilers.values(), src)
          commands = CompilerArgs(compiler)
          # Compiler args for compiling this target
          commands += compilers.get_base_compile_args(self.environment.coredata.base_options,
                                                      compiler)
          if isinstance(src, File):
              if src.is_built:
                  src_filename = os.path.join(src.subdir, src.fname)
              else:
                  src_filename = src.fname
          elif os.path.isabs(src):
              src_filename = os.path.basename(src)
          else:
              src_filename = src
          obj_basename = src_filename.replace('/', '_').replace('\\', '_')
          rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
          rel_obj += '.' + self.environment.get_object_suffix()
          commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
          if isinstance(src, File) and src.is_built:
              rel_src = src.fname
          elif isinstance(src, File):
              rel_src = src.rel_to_builddir(self.build_to_src)
          else:
              raise InvalidArguments('Invalid source type: {!r}'.format(src))
          # Write the Ninja build command
          compiler_name = 'llvm_ir{}_COMPILER'.format('_CROSS' if target.is_cross else '')
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          element.add_item('ARGS', commands)
          element.write(outfile)
          return rel_obj
  
      def get_source_dir_include_args(self, target, compiler):
          curdir = target.get_subdir()
          tmppath = os.path.normpath(os.path.join(self.build_to_src, curdir))
          return compiler.get_include_args(tmppath, False)
  
      def get_build_dir_include_args(self, target, compiler):
          curdir = target.get_subdir()
          if curdir == '':
              curdir = '.'
          return compiler.get_include_args(curdir, False)
  
      def get_custom_target_dir_include_args(self, target, compiler):
          custom_target_include_dirs = []
          for i in target.get_generated_sources():
              # Generator output goes into the target private dir which is
              # already in the include paths list. Only custom targets have their
              # own target build dir.
              if not isinstance(i, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              idir = self.get_target_dir(i)
              if idir not in custom_target_include_dirs:
                  custom_target_include_dirs.append(idir)
          incs = []
          for i in custom_target_include_dirs:
              incs += compiler.get_include_args(i, False)
          return incs
  
      def _generate_single_compile(self, target, compiler, is_generated=False):
          base_proxy = self.get_base_options_for_target(target)
          # Create an empty commands list, and start adding arguments from
          # various sources in the order in which they must override each other
          commands = CompilerArgs(compiler)
          # Add compiler args for compiling this target derived from 'base' build
          # options passed on the command-line, in default_options, etc.
          # These have the lowest priority.
          commands += compilers.get_base_compile_args(base_proxy,
                                                      compiler)
          # The code generated by valac is usually crap and has tons of unused
          # variables and such, so disable warnings for Vala C sources.
          no_warn_args = (is_generated == 'vala')
          # Add compiler args and include paths from several sources; defaults,
          # build options, external dependencies, etc.
          commands += self.generate_basic_compiler_args(target, compiler, no_warn_args)
          # Add custom target dirs as includes automatically, but before
          # target-specific include directories.
          # XXX: Not sure if anyone actually uses this? It can cause problems in
          # situations which increase the likelihood for a header name collision,
          # such as in subprojects.
          commands += self.get_custom_target_dir_include_args(target, compiler)
          # Add include dirs from the `include_directories:` kwarg on the target
          # and from `include_directories:` of internal deps of the target.
          #
          # Target include dirs should override internal deps include dirs.
          # This is handled in BuildTarget.process_kwargs()
          #
          # Include dirs from internal deps should override include dirs from
          # external deps and must maintain the order in which they are specified.
          # Hence, we must reverse the list so that the order is preserved.
          for i in reversed(target.get_include_dirs()):
              basedir = i.get_curdir()
              for d in i.get_incdirs():
                  # Avoid superfluous '/.' at the end of paths when d is '.'
                  if d not in ('', '.'):
                      expdir = os.path.join(basedir, d)
                  else:
                      expdir = basedir
                  srctreedir = os.path.join(self.build_to_src, expdir)
                  # Add source subdir first so that the build subdir overrides it
                  sargs = compiler.get_include_args(srctreedir, i.is_system)
                  commands += sargs
                  # There may be include dirs where a build directory has not been
                  # created for some source dir. For example if someone does this:
                  #
                  # inc = include_directories('foo/bar/baz')
                  #
                  # But never subdir()s into the actual dir.
                  if os.path.isdir(os.path.join(self.environment.get_build_dir(), expdir)):
                      bargs = compiler.get_include_args(expdir, i.is_system)
                  else:
                      bargs = []
                  commands += bargs
              for d in i.get_extra_build_dirs():
                  commands += compiler.get_include_args(d, i.is_system)
          # Add per-target compile args, f.ex, `c_args : ['-DFOO']`. We set these
          # near the end since these are supposed to override everything else.
          commands += self.escape_extra_args(compiler,
                                             target.get_extra_args(compiler.get_language()))
          # Add source dir and build dir. Project-specific and target-specific
          # include paths must override per-target compile args, include paths
          # from external dependencies, internal dependencies, and from
          # per-target `include_directories:`
          #
          # We prefer headers in the build dir over the source dir since, for
          # instance, the user might have an srcdir == builddir Autotools build
          # in their source tree. Many projects that are moving to Meson have
          # both Meson and Autotools in parallel as part of the transition.
          if target.implicit_include_directories:
              commands += self.get_source_dir_include_args(target, compiler)
          if target.implicit_include_directories:
              commands += self.get_build_dir_include_args(target, compiler)
          # Finally add the private dir for the target to the include path. This
          # must override everything else and must be the final path added.
          commands += compiler.get_include_args(self.get_target_private_dir(target), False)
          return commands
  
      def generate_single_compile(self, target, outfile, src, is_generated=False, header_deps=[], order_deps=[]):
          """
          Compiles C/C++, ObjC/ObjC++, Fortran, and D sources
          """
          if isinstance(src, str) and src.endswith('.h'):
              raise AssertionError('BUG: sources should not contain headers {!r}'.format(src))
  
          compiler = get_compiler_for_source(target.compilers.values(), src)
          key = (target, compiler, is_generated)
          if key in self.target_arg_cache:
              commands = self.target_arg_cache[key]
          else:
              commands = self._generate_single_compile(target, compiler, is_generated)
              self.target_arg_cache[key] = commands
          commands = CompilerArgs(commands.compiler, commands)
  
          build_dir = self.environment.get_build_dir()
          if isinstance(src, File):
              rel_src = src.rel_to_builddir(self.build_to_src)
              if os.path.isabs(rel_src):
                  # Source files may not be from the source directory if they originate in source-only libraries,
                  # so we can't assert that the absolute path is anywhere in particular.
                  if src.is_built:
                      assert rel_src.startswith(build_dir)
                      rel_src = rel_src[len(build_dir) + 1:]
          elif is_generated:
              raise AssertionError('BUG: broken generated source file handling for {!r}'.format(src))
          else:
              raise InvalidArguments('Invalid source type: {!r}'.format(src))
          obj_basename = self.object_filename_from_source(target, src, self.is_unity(target))
          rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
          dep_file = compiler.depfile_for_object(rel_obj)
  
          # Add MSVC debug file generation compile flags: /Fd /FS
          commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
  
          # PCH handling
          if self.environment.coredata.base_options.get('b_pch', False):
              commands += self.get_pch_include_args(compiler, target)
              pchlist = target.get_pch(compiler.language)
          else:
              pchlist = []
          if not pchlist:
              pch_dep = []
          elif compiler.id == 'intel':
              pch_dep = []
          else:
              arr = []
              i = os.path.join(self.get_target_private_dir(target), compiler.get_pch_name(pchlist[0]))
              arr.append(i)
              pch_dep = arr
  
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          compiler_name = '%s%s_COMPILER' % (compiler.get_language(), crstr)
          extra_deps = []
          if compiler.get_language() == 'fortran':
              # Can't read source file to scan for deps if it's generated later
              # at build-time. Skip scanning for deps, and just set the module
              # outdir argument instead.
              # https://github.com/mesonbuild/meson/issues/1348
              if not is_generated:
                  abs_src = os.path.join(build_dir, rel_src)
                  extra_deps += self.get_fortran_deps(compiler, abs_src, target)
              # Dependency hack. Remove once multiple outputs in Ninja is fixed:
              # https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
              for modname, srcfile in self.fortran_deps[target.get_basename()].items():
                  modfile = os.path.join(self.get_target_private_dir(target),
                                         compiler.module_name_to_filename(modname))
                  if srcfile == src:
                      depelem = NinjaBuildElement(self.all_outputs, modfile, 'FORTRAN_DEP_HACK', rel_obj)
                      depelem.write(outfile)
              commands += compiler.get_module_outdir_args(self.get_target_private_dir(target))
  
          if compiler.language == 'd':
              commands += compiler.get_feature_args(target.d_features, self.build_to_src)
  
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
          for d in header_deps:
              if isinstance(d, File):
                  d = d.rel_to_builddir(self.build_to_src)
              elif not self.has_dir_part(d):
                  d = os.path.join(self.get_target_private_dir(target), d)
              element.add_dep(d)
          for d in extra_deps:
              element.add_dep(d)
          for d in order_deps:
              if isinstance(d, File):
                  d = d.rel_to_builddir(self.build_to_src)
              elif not self.has_dir_part(d):
                  d = os.path.join(self.get_target_private_dir(target), d)
              element.add_orderdep(d)
          element.add_orderdep(pch_dep)
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          for i in self.get_fortran_orderdeps(target, compiler):
              element.add_orderdep(i)
          element.add_item('DEPFILE', dep_file)
          element.add_item('ARGS', commands)
          element.write(outfile)
          return rel_obj
  
      def has_dir_part(self, fname):
          # FIXME FIXME: The usage of this is a terrible and unreliable hack
          if isinstance(fname, File):
              return fname.subdir != ''
          return has_path_sep(fname)
  
      # Fortran is a bit weird (again). When you link against a library, just compiling a source file
      # requires the mod files that are output when single files are built. To do this right we would need to
      # scan all inputs and write out explicit deps for each file. That is stoo slow and too much effort so
      # instead just have an ordered dependency on the library. This ensures all required mod files are created.
      # The real deps are then detected via dep file generation from the compiler. This breaks on compilers that
      # produce incorrect dep files but such is life.
      def get_fortran_orderdeps(self, target, compiler):
          if compiler.language != 'fortran':
              return []
          return [os.path.join(self.get_target_dir(lt), lt.get_filename()) for lt in target.link_targets]
  
      def generate_msvc_pch_command(self, target, compiler, pch):
          if len(pch) != 2:
              raise MesonException('MSVC requires one header and one source to produce precompiled headers.')
          header = pch[0]
          source = pch[1]
          pchname = compiler.get_pch_name(header)
          dst = os.path.join(self.get_target_private_dir(target), pchname)
  
          commands = []
          commands += self.generate_basic_compiler_args(target, compiler)
          just_name = os.path.basename(header)
          (objname, pch_args) = compiler.gen_pch_args(just_name, source, dst)
          commands += pch_args
          commands += self.get_compile_debugfile_args(compiler, target, objname)
          dep = dst + '.' + compiler.get_depfile_suffix()
          return commands, dep, dst, [objname]
  
      def generate_gcc_pch_command(self, target, compiler, pch):
          commands = self._generate_single_compile(target, compiler)
          dst = os.path.join(self.get_target_private_dir(target),
                             os.path.basename(pch) + '.' + compiler.get_pch_suffix())
          dep = dst + '.' + compiler.get_depfile_suffix()
          return commands, dep, dst, []  # Gcc does not create an object file during pch generation.
  
      def generate_pch(self, target, outfile):
          cstr = ''
          pch_objects = []
          if target.is_cross:
              cstr = '_CROSS'
          for lang in ['c', 'cpp']:
              pch = target.get_pch(lang)
              if not pch:
                  continue
              if not has_path_sep(pch[0]) or not has_path_sep(pch[-1]):
                  msg = 'Precompiled header of {!r} must not be in the same ' \
                        'directory as source, please put it in a subdirectory.' \
                        ''.format(target.get_basename())
                  raise InvalidArguments(msg)
              compiler = target.compilers[lang]
              if compiler.id == 'msvc':
                  src = os.path.join(self.build_to_src, target.get_source_subdir(), pch[-1])
                  (commands, dep, dst, objs) = self.generate_msvc_pch_command(target, compiler, pch)
                  extradep = os.path.join(self.build_to_src, target.get_source_subdir(), pch[0])
              elif compiler.id == 'intel':
                  # Intel generates on target generation
                  continue
              else:
                  src = os.path.join(self.build_to_src, target.get_source_subdir(), pch[0])
                  (commands, dep, dst, objs) = self.generate_gcc_pch_command(target, compiler, pch[0])
                  extradep = None
              pch_objects += objs
              rulename = compiler.get_language() + cstr + '_PCH'
              elem = NinjaBuildElement(self.all_outputs, dst, rulename, src)
              if extradep is not None:
                  elem.add_dep(extradep)
              elem.add_item('ARGS', commands)
              elem.add_item('DEPFILE', dep)
              elem.write(outfile)
          return pch_objects
  
      def generate_shsym(self, outfile, target):
          target_name = self.get_target_filename(target)
          targetdir = self.get_target_private_dir(target)
          symname = os.path.join(targetdir, target_name + '.symbols')
          elem = NinjaBuildElement(self.all_outputs, symname, 'SHSYM', target_name)
          if self.environment.is_cross_build() and self.environment.cross_info.need_cross_compiler():
              elem.add_item('CROSS', '--cross-host=' + self.environment.cross_info.config['host_machine']['system'])
          elem.write(outfile)
  
      def get_cross_stdlib_link_args(self, target, linker):
          if isinstance(target, build.StaticLibrary) or not target.is_cross:
              return []
          if not self.environment.cross_info.has_stdlib(linker.language):
              return []
          return linker.get_no_stdlib_link_args()
  
      def get_target_type_link_args(self, target, linker):
          abspath = os.path.join(self.environment.get_build_dir(), target.subdir)
          commands = []
          if isinstance(target, build.Executable):
              # Currently only used with the Swift compiler to add '-emit-executable'
              commands += linker.get_std_exe_link_args()
              # If gui_app, and that's significant on this platform
              if target.gui_app and hasattr(linker, 'get_gui_app_args'):
                  commands += linker.get_gui_app_args()
              # If export_dynamic, add the appropriate linker arguments
              if target.export_dynamic:
                  commands += linker.gen_export_dynamic_link_args(self.environment)
              # If implib, and that's significant on this platform (i.e. Windows using either GCC or Visual Studio)
              if target.import_filename:
                  commands += linker.gen_import_library_args(os.path.join(self.get_target_dir(target), target.import_filename))
          elif isinstance(target, build.SharedLibrary):
              if isinstance(target, build.SharedModule):
                  commands += linker.get_std_shared_module_link_args()
              else:
                  commands += linker.get_std_shared_lib_link_args()
              # All shared libraries are PIC
              commands += linker.get_pic_args()
              # Add -Wl,-soname arguments on Linux, -install_name on OS X
              commands += linker.get_soname_args(target.prefix, target.name, target.suffix,
                                                 abspath, target.soversion,
                                                 isinstance(target, build.SharedModule))
              # This is only visited when building for Windows using either GCC or Visual Studio
              if target.vs_module_defs and hasattr(linker, 'gen_vs_module_defs_args'):
                  commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src))
              # This is only visited when building for Windows using either GCC or Visual Studio
              if target.import_filename:
                  commands += linker.gen_import_library_args(os.path.join(self.get_target_dir(target), target.import_filename))
          elif isinstance(target, build.StaticLibrary):
              commands += linker.get_std_link_args()
          else:
              raise RuntimeError('Unknown build target type.')
          return commands
  
      def get_link_whole_args(self, linker, target):
          target_args = self.build_target_link_arguments(linker, target.link_whole_targets)
          return linker.get_link_whole_for(target_args) if len(target_args) else []
  
      def generate_link(self, target, outfile, outname, obj_list, linker, extra_args=[]):
          if isinstance(target, build.StaticLibrary):
              linker_base = 'STATIC'
          else:
              linker_base = linker.get_language() # Fixme.
          if isinstance(target, build.SharedLibrary):
              self.generate_shsym(outfile, target)
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          linker_rule = linker_base + crstr + '_LINKER'
  
          # Create an empty commands list, and start adding link arguments from
          # various sources in the order in which they must override each other
          # starting from hard-coded defaults followed by build options and so on.
          #
          # Once all the linker options have been passed, we will start passing
          # libraries and library paths from internal and external sources.
          commands = CompilerArgs(linker)
          # First, the trivial ones that are impossible to override.
          #
          # Add linker args for linking this target derived from 'base' build
          # options passed on the command-line, in default_options, etc.
          # These have the lowest priority.
          if not isinstance(target, build.StaticLibrary):
              commands += compilers.get_base_link_args(self.environment.coredata.base_options,
                                                       linker,
                                                       isinstance(target, build.SharedModule))
          # Add -nostdlib if needed; can't be overridden
          commands += self.get_cross_stdlib_link_args(target, linker)
          # Add things like /NOLOGO; usually can't be overridden
          commands += linker.get_linker_always_args()
          # Add buildtype linker args: optimization level, etc.
          commands += linker.get_buildtype_linker_args(self.get_option_for_target('buildtype', target))
          # Add /DEBUG and the pdb filename when using MSVC
          commands += self.get_link_debugfile_args(linker, target, outname)
          # Add link args specific to this BuildTarget type, such as soname args,
          # PIC, import library generation, etc.
          commands += self.get_target_type_link_args(target, linker)
          # Archives that are copied wholesale in the result. Must be before any
          # other link targets so missing symbols from whole archives are found in those.
          if not isinstance(target, build.StaticLibrary):
              commands += self.get_link_whole_args(linker, target)
  
          if not isinstance(target, build.StaticLibrary):
              # Add link args added using add_project_link_arguments()
              commands += self.build.get_project_link_args(linker, target.subproject)
              # Add link args added using add_global_link_arguments()
              # These override per-project link arguments
              commands += self.build.get_global_link_args(linker)
              if not target.is_cross:
                  # Link args added from the env: LDFLAGS. We want these to
                  # override all the defaults but not the per-target link args.
                  commands += self.environment.coredata.external_link_args[linker.get_language()]
  
          # Now we will add libraries and library paths from various sources
  
          # Add link args to link to all internal libraries (link_with:) and
          # internal dependencies needed by this target.
          if linker_base == 'STATIC':
              # Link arguments of static libraries are not put in the command
              # line of the library. They are instead appended to the command
              # line where the static library is used.
              dependencies = []
          else:
              dependencies = target.get_dependencies()
          commands += self.build_target_link_arguments(linker, dependencies)
          # For 'automagic' deps: Boost and GTest. Also dependency('threads').
          # pkg-config puts the thread flags itself via `Cflags:`
          for d in target.external_deps:
              if d.need_threads():
                  commands += linker.thread_link_flags(self.environment)
          # Only non-static built targets need link args and link dependencies
          if not isinstance(target, build.StaticLibrary):
              commands += target.link_args
              # External deps must be last because target link libraries may depend on them.
              for dep in target.get_external_deps():
                  # Extend without reordering or de-dup to preserve `-L -l` sets
                  # https://github.com/mesonbuild/meson/issues/1718
                  commands.extend_direct(dep.get_link_args())
              for d in target.get_dependencies():
                  if isinstance(d, build.StaticLibrary):
                      for dep in d.get_external_deps():
                          commands.extend_direct(dep.get_link_args())
          # Add link args for c_* or cpp_* build options. Currently this only
          # adds c_winlibs and cpp_winlibs when building for Windows. This needs
          # to be after all internal and external libraries so that unresolved
          # symbols from those can be found here. This is needed when the
          # *_winlibs that we want to link to are static mingw64 libraries.
          commands += linker.get_option_link_args(self.environment.coredata.compiler_options)
          # Set runtime-paths so we can run executables without needing to set
          # LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows.
          if has_path_sep(target.name):
              # Target names really should not have slashes in them, but
              # unfortunately we did not check for that and some downstream projects
              # now have them. Once slashes are forbidden, remove this bit.
              target_slashname_workaround_dir = os.path.join(
                  os.path.dirname(target.name),
                  self.get_target_dir(target))
          else:
              target_slashname_workaround_dir = self.get_target_dir(target)
          commands += linker.build_rpath_args(self.environment.get_build_dir(),
                                              target_slashname_workaround_dir,
                                              self.determine_rpath_dirs(target),
                                              target.build_rpath,
                                              target.install_rpath)
          # Add libraries generated by custom targets
          custom_target_libraries = self.get_custom_target_provided_libraries(target)
          commands += extra_args
          commands += custom_target_libraries
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          dep_targets = [self.get_dependency_filename(t) for t in dependencies]
          dep_targets.extend([self.get_dependency_filename(t)
                              for t in target.link_depends])
          elem = NinjaBuildElement(self.all_outputs, outname, linker_rule, obj_list)
          elem.add_dep(dep_targets + custom_target_libraries)
          elem.add_item('LINK_ARGS', commands)
          return elem
  
      def get_dependency_filename(self, t):
          if isinstance(t, build.SharedLibrary):
              return os.path.join(self.get_target_private_dir(t), self.get_target_filename(t) + '.symbols')
          elif isinstance(t, mesonlib.File):
              if t.is_built:
                  return t.relative_name()
              else:
                  return t.absolute_path(self.environment.get_source_dir(),
                                         self.environment.get_build_dir())
          return self.get_target_filename(t)
  
      def generate_shlib_aliases(self, target, outdir):
          aliases = target.get_aliases()
          for alias, to in aliases.items():
              aliasfile = os.path.join(self.environment.get_build_dir(), outdir, alias)
              try:
                  os.remove(aliasfile)
              except Exception:
                  pass
              try:
                  os.symlink(to, aliasfile)
              except NotImplementedError:
                  mlog.debug("Library versioning disabled because symlinks are not supported.")
              except OSError:
                  mlog.debug("Library versioning disabled because we do not have symlink creation privileges.")
  
      def generate_custom_target_clean(self, outfile, trees):
          e = NinjaBuildElement(self.all_outputs, 'meson-clean-ctlist', 'CUSTOM_COMMAND', 'PHONY')
          d = CleanTrees(self.environment.get_build_dir(), trees)
          d_file = os.path.join(self.environment.get_scratch_dir(), 'cleantrees.dat')
          e.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'cleantrees', d_file])
          e.add_item('description', 'Cleaning custom target directories.')
          e.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-ctlist', outfile)
          # Write out the data file passed to the script
          with open(d_file, 'wb') as ofile:
              pickle.dump(d, ofile)
          return 'clean-ctlist'
  
      def generate_gcov_clean(self, outfile):
          gcno_elem = NinjaBuildElement(self.all_outputs, 'meson-clean-gcno', 'CUSTOM_COMMAND', 'PHONY')
          script_root = self.environment.get_script_dir()
          clean_script = os.path.join(script_root, 'delwithsuffix.py')
          gcno_elem.add_item('COMMAND', mesonlib.python_command + [clean_script, '.', 'gcno'])
          gcno_elem.add_item('description', 'Deleting gcno files.')
          gcno_elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-gcno', outfile)
  
          gcda_elem = NinjaBuildElement(self.all_outputs, 'meson-clean-gcda', 'CUSTOM_COMMAND', 'PHONY')
          script_root = self.environment.get_script_dir()
          clean_script = os.path.join(script_root, 'delwithsuffix.py')
          gcda_elem.add_item('COMMAND', mesonlib.python_command + [clean_script, '.', 'gcda'])
          gcda_elem.add_item('description', 'Deleting gcda files.')
          gcda_elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-gcda', outfile)
  
      def get_user_option_args(self):
          cmds = []
          for (k, v) in self.environment.coredata.user_options.items():
              cmds.append('-D' + k + '=' + (v.value if isinstance(v.value, str) else str(v.value).lower()))
          # The order of these arguments must be the same between runs of Meson
          # to ensure reproducible output. The order we pass them shouldn't
          # affect behavior in any other way.
          return sorted(cmds)
  
      def generate_dist(self, outfile):
          elem = NinjaBuildElement(self.all_outputs, 'meson-dist', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('DESC', 'Creating source packages')
          elem.add_item('COMMAND', self.environment.get_build_command() + [
              '--internal', 'dist',
              self.environment.source_dir,
              self.environment.build_dir,
          ] + self.environment.get_build_command())
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-dist', outfile)
  
      # For things like scan-build and other helper tools we might have.
      def generate_utils(self, outfile):
          cmd = self.environment.get_build_command() + \
              ['--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir] + \
              self.environment.get_build_command() + self.get_user_option_args()
          elem = NinjaBuildElement(self.all_outputs, 'meson-scan-build', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-scan-build', outfile)
          cmd = self.environment.get_build_command() + ['--internal', 'uninstall']
          elem = NinjaBuildElement(self.all_outputs, 'meson-uninstall', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-uninstall', outfile)
  
      def generate_ending(self, outfile):
          targetlist = []
          for t in self.get_build_by_default_targets().values():
              # Add the first output of each target to the 'all' target so that
              # they are all built
              targetlist.append(os.path.join(self.get_target_dir(t), t.get_outputs()[0]))
  
          elem = NinjaBuildElement(self.all_outputs, 'all', 'phony', targetlist)
          elem.write(outfile)
  
          default = 'default all\n\n'
          outfile.write(default)
  
          elem = NinjaBuildElement(self.all_outputs, 'meson-clean', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', [self.ninja_command, '-t', 'clean'])
          elem.add_item('description', 'Cleaning.')
          # Alias that runs the above-defined meson-clean target
          self.create_target_alias('meson-clean', outfile)
  
          # If we have custom targets in this project, add all their outputs to
          # the list that is passed to the `cleantrees.py` script. The script
          # will manually delete all custom_target outputs that are directories
          # instead of files. This is needed because on platforms other than
          # Windows, Ninja only deletes directories while cleaning if they are
          # empty. https://github.com/mesonbuild/meson/issues/1220
          ctlist = []
          for t in self.build.get_targets().values():
              if isinstance(t, build.CustomTarget):
                  # Create a list of all custom target outputs
                  for o in t.get_outputs():
                      ctlist.append(os.path.join(self.get_target_dir(t), o))
          if ctlist:
              elem.add_dep(self.generate_custom_target_clean(outfile, ctlist))
  
          if 'b_coverage' in self.environment.coredata.base_options and \
             self.environment.coredata.base_options['b_coverage'].value:
              self.generate_gcov_clean(outfile)
              elem.add_dep('clean-gcda')
              elem.add_dep('clean-gcno')
          elem.write(outfile)
  
          deps = self.get_regen_filelist()
          elem = NinjaBuildElement(self.all_outputs, 'build.ninja', 'REGENERATE_BUILD', deps)
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
          elem = NinjaBuildElement(self.all_outputs, 'reconfigure', 'REGENERATE_BUILD', 'PHONY')
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
          elem = NinjaBuildElement(self.all_outputs, deps, 'phony', '')
          elem.write(outfile)
  
  def load(build_dir):
      filename = os.path.join(build_dir, 'meson-private', 'install.dat')
      with open(filename, 'rb') as f:
          obj = pickle.load(f)
      return obj
  
files: mesonbuild/backend/ninjabackend.py
files: # Copyright 2012-2017 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.
  
  import os, pickle, re, shlex, subprocess
  from collections import OrderedDict
  import itertools
  from pathlib import PurePath
  
  from . import backends
  from .. import modules
  from .. import environment, mesonlib
  from .. import build
  from .. import mlog
  from .. import dependencies
  from .. import compilers
  from ..compilers import CompilerArgs
  from ..linkers import ArLinker
  from ..mesonlib import File, MesonException, OrderedSet
  from ..mesonlib import get_compiler_for_source, has_path_sep
  from .backends import CleanTrees, InstallData
  from ..build import InvalidArguments
  
  if mesonlib.is_windows():
      quote_func = lambda s: '"{}"'.format(s)
      execute_wrapper = 'cmd /c'
      rmfile_prefix = 'del /f /s /q {} &&'
  else:
      quote_func = shlex.quote
      execute_wrapper = ''
      rmfile_prefix = 'rm -f {} &&'
  
  def ninja_quote(text, is_build_line=False):
      if is_build_line:
          qcs = ('$', ' ', ':')
      else:
          qcs = ('$', ' ')
      for char in qcs:
          text = text.replace(char, '$' + char)
      if '\n' in text:
          errmsg = '''Ninja does not support newlines in rules. The content was:
  
  %s
  
  Please report this error with a test case to the Meson bug tracker.''' % text
          raise MesonException(errmsg)
      return text
  
  
  class NinjaBuildElement:
      def __init__(self, all_outputs, outfilenames, rule, infilenames):
          if isinstance(outfilenames, str):
              self.outfilenames = [outfilenames]
          else:
              self.outfilenames = outfilenames
          assert(isinstance(rule, str))
          self.rule = rule
          if isinstance(infilenames, str):
              self.infilenames = [infilenames]
          else:
              self.infilenames = infilenames
          self.deps = set()
          self.orderdeps = set()
          self.elems = []
          self.all_outputs = all_outputs
  
      def add_dep(self, dep):
          if isinstance(dep, list):
              self.deps.update(dep)
          else:
              self.deps.add(dep)
  
      def add_orderdep(self, dep):
          if isinstance(dep, list):
              self.orderdeps.update(dep)
          else:
              self.orderdeps.add(dep)
  
      def add_item(self, name, elems):
          if isinstance(elems, str):
              elems = [elems]
          self.elems.append((name, elems))
  
      def write(self, outfile):
          self.check_outputs()
          line = 'build %s: %s %s' % (' '.join([ninja_quote(i, True) for i in self.outfilenames]),
                                      self.rule,
                                      ' '.join([ninja_quote(i, True) for i in self.infilenames]))
          if len(self.deps) > 0:
              line += ' | ' + ' '.join([ninja_quote(x, True) for x in self.deps])
          if len(self.orderdeps) > 0:
              line += ' || ' + ' '.join([ninja_quote(x, True) for x in self.orderdeps])
          line += '\n'
          # This is the only way I could find to make this work on all
          # platforms including Windows command shell. Slash is a dir separator
          # on Windows, too, so all characters are unambiguous and, more importantly,
          # do not require quoting, unless explicitely specified, which is necessary for
          # the csc compiler.
          line = line.replace('\\', '/')
          outfile.write(line)
  
          # All the entries that should remain unquoted
          raw_names = {'DEPFILE', 'DESC', 'pool', 'description'}
  
          for e in self.elems:
              (name, elems) = e
              should_quote = name not in raw_names
              line = ' %s = ' % name
              newelems = []
              for i in elems:
                  if not should_quote or i == '&&': # Hackety hack hack
                      quoter = ninja_quote
                  else:
                      quoter = lambda x: ninja_quote(quote_func(x))
                  i = i.replace('\\', '\\\\')
                  if quote_func('') == '""':
                      i = i.replace('"', '\\"')
                  newelems.append(quoter(i))
              line += ' '.join(newelems)
              line += '\n'
              outfile.write(line)
          outfile.write('\n')
  
      def check_outputs(self):
          for n in self.outfilenames:
              if n in self.all_outputs:
                  raise MesonException('Multiple producers for Ninja target "%s". Please rename your targets.' % n)
              self.all_outputs[n] = True
  
  class NinjaBackend(backends.Backend):
  
      def __init__(self, build):
          super().__init__(build)
          self.name = 'ninja'
          self.ninja_filename = 'build.ninja'
          self.target_arg_cache = {}
          self.fortran_deps = {}
          self.all_outputs = {}
  
      def create_target_alias(self, to_target, outfile):
          # We need to use aliases for targets that might be used as directory
          # names to workaround a Ninja bug that breaks `ninja -t clean`.
          # This is used for 'reserved' targets such as 'test', 'install',
          # 'benchmark', etc, and also for RunTargets.
          # https://github.com/mesonbuild/meson/issues/1644
          if not to_target.startswith('meson-'):
              m = 'Invalid usage of create_target_alias with {!r}'
              raise AssertionError(m.format(to_target))
          from_target = to_target[len('meson-'):]
          elem = NinjaBuildElement(self.all_outputs, from_target, 'phony', to_target)
          elem.write(outfile)
  
      def detect_vs_dep_prefix(self, tempfilename):
          '''VS writes its dependency in a locale dependent format.
          Detect the search prefix to use.'''
          for compiler in self.build.compilers.values():
              # Have to detect the dependency format
              if compiler.id == 'msvc':
                  break
          else:
              # None of our compilers are MSVC, we're done.
              return open(tempfilename, 'a')
          filename = os.path.join(self.environment.get_scratch_dir(),
                                  'incdetect.c')
          with open(filename, 'w') as f:
              f.write('''#include<stdio.h>
  int dummy;
  ''')
  
          # The output of cl dependency information is language
          # and locale dependent. Any attempt at converting it to
          # Python strings leads to failure. We _must_ do this detection
          # in raw byte mode and write the result in raw bytes.
          pc = subprocess.Popen(['cl', '/showIncludes', '/c', 'incdetect.c'],
                                cwd=self.environment.get_scratch_dir(),
                                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
          (stdo, _) = pc.communicate()
  
          # We want to match 'Note: including file: ' in the line
          # 'Note: including file: d:\MyDir\include\stdio.h', however
          # different locales have different messages with a different
          # number of colons. Match up to the the drive name 'd:\'.
          matchre = re.compile(rb"^(.*\s)[a-zA-Z]:\\.*stdio.h$")
          for line in stdo.split(b'\r\n'):
              match = matchre.match(line)
              if match:
                  with open(tempfilename, 'ab') as binfile:
                      binfile.write(b'msvc_deps_prefix = ' + match.group(1) + b'\n')
                  return open(tempfilename, 'a')
          raise MesonException('Could not determine vs dep dependency prefix string.')
  
      def generate(self, interp):
          self.interpreter = interp
          self.ninja_command = environment.detect_ninja(log=True)
          if self.ninja_command is None:
              raise MesonException('Could not detect Ninja v1.5 or newer')
          outfilename = os.path.join(self.environment.get_build_dir(), self.ninja_filename)
          tempfilename = outfilename + '~'
          with open(tempfilename, 'w') as outfile:
              outfile.write('# This is the build file for project "%s"\n' %
                            self.build.get_project())
              outfile.write('# It is autogenerated by the Meson build system.\n')
              outfile.write('# Do not edit by hand.\n\n')
              outfile.write('ninja_required_version = 1.5.1\n\n')
          with self.detect_vs_dep_prefix(tempfilename) as outfile:
              self.generate_rules(outfile)
              self.generate_phony(outfile)
              outfile.write('# Build rules for targets\n\n')
              for t in self.build.get_targets().values():
                  self.generate_target(t, outfile)
              outfile.write('# Test rules\n\n')
              self.generate_tests(outfile)
              outfile.write('# Install rules\n\n')
              self.generate_install(outfile)
              self.generate_dist(outfile)
              if 'b_coverage' in self.environment.coredata.base_options and \
                      self.environment.coredata.base_options['b_coverage'].value:
                  outfile.write('# Coverage rules\n\n')
                  self.generate_coverage_rules(outfile)
              outfile.write('# Suffix\n\n')
              self.generate_utils(outfile)
              self.generate_ending(outfile)
          # Only overwrite the old build file after the new one has been
          # fully created.
          os.replace(tempfilename, outfilename)
          self.generate_compdb()
  
      # http://clang.llvm.org/docs/JSONCompilationDatabase.html
      def generate_compdb(self):
          pch_compilers = ['%s_PCH' % i for i in self.build.compilers]
          native_compilers = ['%s_COMPILER' % i for i in self.build.compilers]
          cross_compilers = ['%s_CROSS_COMPILER' % i for i in self.build.cross_compilers]
          ninja_compdb = [self.ninja_command, '-t', 'compdb'] + pch_compilers + native_compilers + cross_compilers
          builddir = self.environment.get_build_dir()
          try:
              jsondb = subprocess.check_output(ninja_compdb, cwd=builddir)
              with open(os.path.join(builddir, 'compile_commands.json'), 'wb') as f:
                  f.write(jsondb)
          except Exception:
              mlog.warning('Could not create compilation database.')
  
      # Get all generated headers. Any source file might need them so
      # we need to add an order dependency to them.
      def get_generated_headers(self, target):
          header_deps = []
          # XXX: Why don't we add deps to CustomTarget headers here?
          for genlist in target.get_generated_sources():
              if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              for src in genlist.get_outputs():
                  if self.environment.is_header(src):
                      header_deps.append(self.get_target_generated_dir(target, genlist, src))
          if 'vala' in target.compilers and not isinstance(target, build.Executable):
              vala_header = File.from_built_file(self.get_target_dir(target), target.vala_header)
              header_deps.append(vala_header)
          # Recurse and find generated headers
          for dep in itertools.chain(target.link_targets, target.link_whole_targets):
              if isinstance(dep, (build.StaticLibrary, build.SharedLibrary)):
                  header_deps += self.get_generated_headers(dep)
          return header_deps
  
      def get_target_generated_sources(self, target):
          """
          Returns a dictionary with the keys being the path to the file
          (relative to the build directory) of that type and the value
          being the GeneratorList or CustomTarget that generated it.
          """
          srcs = OrderedDict()
          for gensrc in target.get_generated_sources():
              for s in gensrc.get_outputs():
                  f = self.get_target_generated_dir(target, gensrc, s)
                  srcs[f] = s
          return srcs
  
      def get_target_sources(self, target):
          srcs = OrderedDict()
          for s in target.get_sources():
              # BuildTarget sources are always mesonlib.File files which are
              # either in the source root, or generated with configure_file and
              # in the build root
              if not isinstance(s, File):
                  raise InvalidArguments('All sources in target {!r} must be of type mesonlib.File'.format(s))
              f = s.rel_to_builddir(self.build_to_src)
              srcs[f] = s
          return srcs
  
      # Languages that can mix with C or C++ but don't support unity builds yet
      # because the syntax we use for unity builds is specific to C/++/ObjC/++.
      # Assembly files cannot be unitified and neither can LLVM IR files
      langs_cant_unity = ('d', 'fortran')
  
      def get_target_source_can_unity(self, target, source):
          if isinstance(source, File):
              source = source.fname
          if self.environment.is_llvm_ir(source) or \
             self.environment.is_assembly(source):
              return False
          suffix = os.path.splitext(source)[1][1:]
          for lang in self.langs_cant_unity:
              if lang not in target.compilers:
                  continue
              if suffix in target.compilers[lang].file_suffixes:
                  return False
          return True
  
      def generate_target(self, target, outfile):
          if isinstance(target, build.CustomTarget):
              self.generate_custom_target(target, outfile)
          if isinstance(target, build.RunTarget):
              self.generate_run_target(target, outfile)
          name = target.get_id()
          if name in self.processed_targets:
              return
          self.processed_targets[name] = True
          # Generate rules for all dependency targets
          self.process_target_dependencies(target, outfile)
          # If target uses a language that cannot link to C objects,
          # just generate for that language and return.
          if isinstance(target, build.Jar):
              self.generate_jar_target(target, outfile)
              return
          if 'rust' in target.compilers:
              self.generate_rust_target(target, outfile)
              return
          if 'cs' in target.compilers:
              self.generate_cs_target(target, outfile)
              return
          if 'swift' in target.compilers:
              self.generate_swift_target(target, outfile)
              return
  
          # Now we handle the following languages:
          # ObjC++, ObjC, C++, C, D, Fortran, Vala
  
          # target_sources:
          #   Pre-existing target C/C++ sources to be built; dict of full path to
          #   source relative to build root and the original File object.
          # generated_sources:
          #   GeneratedList and CustomTarget sources to be built; dict of the full
          #   path to source relative to build root and the generating target/list
          # vala_generated_sources:
          #   Array of sources generated by valac that have to be compiled
          if 'vala' in target.compilers:
              # Sources consumed by valac are filtered out. These only contain
              # C/C++ sources, objects, generated libs, and unknown sources now.
              target_sources, generated_sources, \
                  vala_generated_sources = self.generate_vala_compile(target, outfile)
          else:
              target_sources = self.get_target_sources(target)
              generated_sources = self.get_target_generated_sources(target)
              vala_generated_sources = []
          self.scan_fortran_module_outputs(target)
          # Generate rules for GeneratedLists
          self.generate_generator_list_rules(target, outfile)
  
          # Generate rules for building the remaining source files in this target
          outname = self.get_target_filename(target)
          obj_list = []
          use_pch = self.environment.coredata.base_options.get('b_pch', False)
          is_unity = self.is_unity(target)
          if use_pch and target.has_pch():
              pch_objects = self.generate_pch(target, outfile)
          else:
              pch_objects = []
          header_deps = []
          unity_src = []
          unity_deps = [] # Generated sources that must be built before compiling a Unity target.
          header_deps += self.get_generated_headers(target)
  
          if is_unity:
              # Warn about incompatible sources if a unity build is enabled
              langs = set(target.compilers.keys())
              langs_cant = langs.intersection(self.langs_cant_unity)
              if langs_cant:
                  langs_are = langs = ', '.join(langs_cant).upper()
                  langs_are += ' are' if len(langs_cant) > 1 else ' is'
                  msg = '{} not supported in Unity builds yet, so {} ' \
                        'sources in the {!r} target will be compiled normally' \
                        ''.format(langs_are, langs, target.name)
                  mlog.log(mlog.red('FIXME'), msg)
  
          # Get a list of all generated headers that will be needed while building
          # this target's sources (generated sources and pre-existing sources).
          # This will be set as dependencies of all the target's sources. At the
          # same time, also deal with generated sources that need to be compiled.
          generated_source_files = []
          for rel_src, gensrc in generated_sources.items():
              dirpart, fnamepart = os.path.split(rel_src)
              raw_src = File(True, dirpart, fnamepart)
              if self.environment.is_source(rel_src) and not self.environment.is_header(rel_src):
                  if is_unity and self.get_target_source_can_unity(target, rel_src):
                      unity_deps.append(raw_src)
                      abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
                      unity_src.append(abs_src)
                  else:
                      generated_source_files.append(raw_src)
              elif self.environment.is_object(rel_src):
                  obj_list.append(rel_src)
              elif self.environment.is_library(rel_src):
                  pass
              else:
                  # Assume anything not specifically a source file is a header. This is because
                  # people generate files with weird suffixes (.inc, .fh) that they then include
                  # in their source files.
                  header_deps.append(raw_src)
          # These are the generated source files that need to be built for use by
          # this target. We create the Ninja build file elements for this here
          # because we need `header_deps` to be fully generated in the above loop.
          for src in generated_source_files:
              if self.environment.is_llvm_ir(src):
                  o = self.generate_llvm_ir_compile(target, outfile, src)
              else:
                  o = self.generate_single_compile(target, outfile, src, True,
                                                   header_deps=header_deps)
              obj_list.append(o)
  
          # Generate compilation targets for C sources generated from Vala
          # sources. This can be extended to other $LANG->C compilers later if
          # necessary. This needs to be separate for at least Vala
          vala_generated_source_files = []
          for src in vala_generated_sources:
              dirpart, fnamepart = os.path.split(src)
              raw_src = File(True, dirpart, fnamepart)
              if is_unity:
                  unity_src.append(os.path.join(self.environment.get_build_dir(), src))
                  header_deps.append(raw_src)
              else:
                  # Generated targets are ordered deps because the must exist
                  # before the sources compiling them are used. After the first
                  # compile we get precise dependency info from dep files.
                  # This should work in all cases. If it does not, then just
                  # move them from orderdeps to proper deps.
                  if self.environment.is_header(src):
                      header_deps.append(raw_src)
                  else:
                      # We gather all these and generate compile rules below
                      # after `header_deps` (above) is fully generated
                      vala_generated_source_files.append(raw_src)
          for src in vala_generated_source_files:
              # Passing 'vala' here signifies that we want the compile
              # arguments to be specialized for C code generated by
              # valac. For instance, no warnings should be emitted.
              obj_list.append(self.generate_single_compile(target, outfile, src, 'vala', [], header_deps))
  
          # Generate compile targets for all the pre-existing sources for this target
          for f, src in target_sources.items():
              if not self.environment.is_header(src):
                  if self.environment.is_llvm_ir(src):
                      obj_list.append(self.generate_llvm_ir_compile(target, outfile, src))
                  elif is_unity and self.get_target_source_can_unity(target, src):
                      abs_src = os.path.join(self.environment.get_build_dir(),
                                             src.rel_to_builddir(self.build_to_src))
                      unity_src.append(abs_src)
                  else:
                      obj_list.append(self.generate_single_compile(target, outfile, src, False, [], header_deps))
          obj_list += self.flatten_object_list(target)
          if is_unity:
              for src in self.generate_unity_files(target, unity_src):
                  obj_list.append(self.generate_single_compile(target, outfile, src, True, unity_deps + header_deps))
          linker = self.determine_linker(target)
          elem = self.generate_link(target, outfile, outname, obj_list, linker, pch_objects)
          self.generate_shlib_aliases(target, self.get_target_dir(target))
          elem.write(outfile)
  
      def process_target_dependencies(self, target, outfile):
          for t in target.get_dependencies():
              if t.get_id() not in self.processed_targets:
                  self.generate_target(t, outfile)
  
      def custom_target_generator_inputs(self, target, outfile):
          for s in target.sources:
              if hasattr(s, 'held_object'):
                  s = s.held_object
              if isinstance(s, build.GeneratedList):
                  self.generate_genlist_for_target(s, target, outfile)
  
      def unwrap_dep_list(self, target):
          deps = []
          for i in target.get_dependencies():
              # FIXME, should not grab element at zero but rather expand all.
              if isinstance(i, list):
                  i = i[0]
              # Add a dependency on all the outputs of this target
              for output in i.get_outputs():
                  deps.append(os.path.join(self.get_target_dir(i), output))
          return deps
  
      def generate_custom_target(self, target, outfile):
          self.custom_target_generator_inputs(target, outfile)
          (srcs, ofilenames, cmd) = self.eval_custom_target_command(target)
          deps = self.unwrap_dep_list(target)
          deps += self.get_custom_target_depend_files(target)
          desc = 'Generating {0} with a {1} command.'
          if target.build_always:
              deps.append('PHONY')
          if target.depfile is None:
              rulename = 'CUSTOM_COMMAND'
          else:
              rulename = 'CUSTOM_COMMAND_DEP'
          elem = NinjaBuildElement(self.all_outputs, ofilenames, rulename, srcs)
          elem.add_dep(deps)
          for d in target.extra_depends:
              # Add a dependency on all the outputs of this target
              for output in d.get_outputs():
                  elem.add_dep(os.path.join(self.get_target_dir(d), output))
          serialize = False
          extra_paths = []
          # If the target requires capturing stdout, then use the serialized
          # executable wrapper to capture that output and save it to a file.
          if target.capture:
              serialize = True
          # If the command line requires a newline, also use the wrapper, as
          # ninja does not support them in its build rule syntax.
          if any('\n' in c for c in cmd):
              serialize = True
          # Windows doesn't have -rpath, so for EXEs that need DLLs built within
          # the project, we need to set PATH so the DLLs are found. We use
          # a serialized executable wrapper for that and check if the
          # CustomTarget command needs extra paths first.
          if mesonlib.is_windows() or mesonlib.is_cygwin():
              extra_bdeps = target.get_transitive_build_target_deps()
              extra_paths = self.determine_windows_extra_paths(target.command[0], extra_bdeps)
              if extra_paths:
                  serialize = True
          if serialize:
              exe_data = self.serialize_executable(target.command[0], cmd[1:],
                                                   # All targets are built from the build dir
                                                   self.environment.get_build_dir(),
                                                   extra_paths=extra_paths,
                                                   capture=ofilenames[0] if target.capture else None)
              cmd = self.environment.get_build_command() + ['--internal', 'exe', exe_data]
              cmd_type = 'meson_exe.py custom'
          else:
              cmd_type = 'custom'
          if target.depfile is not None:
              rel_dfile = os.path.join(self.get_target_dir(target), target.depfile)
              abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
              os.makedirs(abs_pdir, exist_ok=True)
              elem.add_item('DEPFILE', rel_dfile)
          cmd = self.replace_paths(target, cmd)
          elem.add_item('COMMAND', cmd)
          elem.add_item('description', desc.format(target.name, cmd_type))
          elem.write(outfile)
          self.processed_targets[target.get_id()] = True
  
      def generate_run_target(self, target, outfile):
          cmd = self.environment.get_build_command() + ['--internal', 'commandrunner']
          deps = self.unwrap_dep_list(target)
          arg_strings = []
          for i in target.args:
              if isinstance(i, str):
                  arg_strings.append(i)
              elif isinstance(i, (build.BuildTarget, build.CustomTarget)):
                  relfname = self.get_target_filename(i)
                  arg_strings.append(os.path.join(self.environment.get_build_dir(), relfname))
                  deps.append(relfname)
              elif isinstance(i, mesonlib.File):
                  relfname = i.rel_to_builddir(self.build_to_src)
                  arg_strings.append(os.path.join(self.environment.get_build_dir(), relfname))
              else:
                  raise AssertionError('Unreachable code in generate_run_target: ' + str(i))
          if target.subproject != '':
              subproject_prefix = '{}@@'.format(target.subproject)
          else:
              subproject_prefix = ''
          target_name = 'meson-{}{}'.format(subproject_prefix, target.name)
          elem = NinjaBuildElement(self.all_outputs, target_name, 'CUSTOM_COMMAND', [])
          cmd += [self.environment.get_source_dir(),
                  self.environment.get_build_dir(),
                  target.subdir] + self.environment.get_build_command()
          texe = target.command
          try:
              texe = texe.held_object
          except AttributeError:
              pass
          if isinstance(texe, build.Executable):
              abs_exe = os.path.join(self.environment.get_build_dir(), self.get_target_filename(texe))
              deps.append(self.get_target_filename(texe))
              if self.environment.is_cross_build() and \
                 self.environment.cross_info.need_exe_wrapper():
                  exe_wrap = self.environment.cross_info.config['binaries'].get('exe_wrapper', None)
                  if exe_wrap is not None:
                      cmd += [exe_wrap]
              cmd.append(abs_exe)
          elif isinstance(texe, dependencies.ExternalProgram):
              cmd += texe.get_command()
          elif isinstance(texe, build.CustomTarget):
              deps.append(self.get_target_filename(texe))
              cmd += [os.path.join(self.environment.get_build_dir(), self.get_target_filename(texe))]
          elif isinstance(texe, mesonlib.File):
              cmd.append(texe.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir()))
          else:
              cmd.append(target.command)
          cmd += arg_strings
  
          elem.add_dep(deps)
          cmd = self.replace_paths(target, cmd)
          elem.add_item('COMMAND', cmd)
          elem.add_item('description', 'Running external command %s.' % target.name)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above with the name the user specified
          self.create_target_alias(target_name, outfile)
          self.processed_targets[target.get_id()] = True
  
      def generate_coverage_rules(self, outfile):
          e = NinjaBuildElement(self.all_outputs, 'meson-coverage', 'CUSTOM_COMMAND', 'PHONY')
          e.add_item('COMMAND', self.environment.get_build_command() +
                     ['--internal', 'coverage',
                      self.environment.get_source_dir(),
                      self.environment.get_build_dir(),
                      self.environment.get_log_dir()])
          e.add_item('description', 'Generates coverage reports.')
          e.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-coverage', outfile)
          self.generate_coverage_legacy_rules(outfile)
  
      def generate_coverage_legacy_rules(self, outfile):
          (gcovr_exe, gcovr_new_rootdir, lcov_exe, genhtml_exe) = environment.find_coverage_tools()
          added_rule = False
          if gcovr_exe:
              # gcovr >= 3.1 interprets rootdir differently
              if gcovr_new_rootdir:
                  rootdir = self.environment.get_build_dir()
              else:
                  rootdir = self.environment.get_source_dir(),
              added_rule = True
              elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-xml', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-x', '-r', rootdir,
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.xml')])
              elem.add_item('DESC', 'Generating XML coverage report.')
              elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-xml', outfile)
              elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-text', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-r', rootdir,
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.txt')])
              elem.add_item('DESC', 'Generating text coverage report.')
              elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-text', outfile)
          if lcov_exe and genhtml_exe:
              added_rule = True
              htmloutdir = os.path.join(self.environment.get_log_dir(), 'coveragereport')
              covinfo = os.path.join(self.environment.get_log_dir(), 'coverage.info')
              phony_elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-html', outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
  
              subproject_dir = self.build.get_subproject_dir()
              command = [lcov_exe,
                         '--directory', self.environment.get_build_dir(),
                         '--capture',
                         '--output-file', covinfo,
                         '--no-checksum',
                         '&&', lcov_exe,
                         '--extract',
                         covinfo,
                         os.path.join(self.environment.get_source_dir(), '*'),
                         '--output-file', covinfo,
                         '&&', lcov_exe,
                         '--remove',
                         covinfo,
                         os.path.join(self.environment.get_source_dir(), subproject_dir, '*'),
                         '--output-file', covinfo,
                         '&&', genhtml_exe,
                         '--prefix', self.environment.get_build_dir(),
                         '--output-directory', htmloutdir,
                         '--title', 'Code coverage',
                         '--legend',
                         '--show-details',
                         covinfo]
              elem.add_item('COMMAND', command)
              elem.add_item('DESC', 'Generating HTML coverage report.')
              elem.write(outfile)
          elif gcovr_exe and gcovr_new_rootdir:
              added_rule = True
              htmloutdir = os.path.join(self.environment.get_log_dir(), 'coveragereport')
              phony_elem = NinjaBuildElement(self.all_outputs, 'meson-coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              # Alias that runs the target defined above
              self.create_target_alias('meson-coverage-html', outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
              command = [gcovr_exe, '--html', '--html-details', '-r', self.environment.get_build_dir(),
                         '-o', os.path.join(htmloutdir, 'index.html')]
              elem.add_item('COMMAND', command)
              elem.add_item('DESC', 'Generating HTML coverage report.')
              elem.write(outfile)
          if not added_rule:
              mlog.warning('coverage requested but neither gcovr nor lcov/genhtml found.')
  
      def generate_install(self, outfile):
          install_data_file = os.path.join(self.environment.get_scratch_dir(), 'install.dat')
          if self.environment.is_cross_build():
              bins = self.environment.cross_info.config['binaries']
              if 'strip' not in bins:
                  mlog.warning('Cross file does not specify strip binary, result will not be stripped.')
                  strip_bin = None
              else:
                  strip_bin = mesonlib.stringlistify(bins['strip'])
          else:
              strip_bin = self.environment.native_strip_bin
          d = InstallData(self.environment.get_source_dir(),
                          self.environment.get_build_dir(),
                          self.environment.get_prefix(),
                          strip_bin, self.environment.get_build_command() + ['introspect'])
          elem = NinjaBuildElement(self.all_outputs, 'meson-install', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_dep('all')
          elem.add_item('DESC', 'Installing files.')
          elem.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'install', install_data_file])
          elem.add_item('pool', 'console')
          self.generate_depmf_install(d)
          self.generate_target_install(d)
          self.generate_header_install(d)
          self.generate_man_install(d)
          self.generate_data_install(d)
          self.generate_custom_install_script(d)
          self.generate_subdir_install(d)
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-install', outfile)
  
          with open(install_data_file, 'wb') as ofile:
              pickle.dump(d, ofile)
  
      def generate_target_install(self, d):
          for t in self.build.get_targets().values():
              if not t.should_install():
                  continue
              # Find the installation directory.
              outdirs = t.get_custom_install_dir()
              custom_install_dir = False
              if outdirs[0] is not None and outdirs[0] is not True:
                  # Either the value is set, or is set to False which means
                  # we want this specific output out of many outputs to not
                  # be installed.
                  custom_install_dir = True
              elif isinstance(t, build.SharedModule):
                  outdirs[0] = self.environment.get_shared_module_dir()
              elif isinstance(t, build.SharedLibrary):
                  outdirs[0] = self.environment.get_shared_lib_dir()
              elif isinstance(t, build.StaticLibrary):
                  outdirs[0] = self.environment.get_static_lib_dir()
              elif isinstance(t, build.Executable):
                  outdirs[0] = self.environment.get_bindir()
              else:
                  assert(isinstance(t, build.BuildTarget))
                  # XXX: Add BuildTarget-specific install dir cases here
                  outdirs[0] = self.environment.get_libdir()
              # Sanity-check the outputs and install_dirs
              num_outdirs, num_out = len(outdirs), len(t.get_outputs())
              if num_outdirs != 1 and num_outdirs != num_out:
                  m = 'Target {!r} has {} outputs: {!r}, but only {} "install_dir"s were found.\n' \
                      "Pass 'false' for outputs that should not be installed and 'true' for\n" \
                      'using the default installation directory for an output.'
                  raise MesonException(m.format(t.name, num_out, t.get_outputs(), num_outdirs))
              # Install the target output(s)
              if isinstance(t, build.BuildTarget):
                  should_strip = self.get_option_for_target('strip', t)
                  # Install primary build output (library/executable/jar, etc)
                  # Done separately because of strip/aliases/rpath
                  if outdirs[0] is not False:
                      i = [self.get_target_filename(t), outdirs[0],
                           t.get_aliases(), should_strip, t.install_rpath]
                      d.targets.append(i)
                      # On toolchains/platforms that use an import library for
                      # linking (separate from the shared library with all the
                      # code), we need to install that too (dll.a/.lib).
                      if (isinstance(t, build.SharedLibrary) or isinstance(t, build.Executable)) and t.get_import_filename():
                          if custom_install_dir:
                              # If the DLL is installed into a custom directory,
                              # install the import library into the same place so
                              # it doesn't go into a surprising place
                              implib_install_dir = outdirs[0]
                          else:
                              implib_install_dir = self.environment.get_import_lib_dir()
                          # Install the import library.
                          i = [self.get_target_filename_for_linking(t),
                               implib_install_dir,
                               # It has no aliases, should not be stripped, and
                               # doesn't have an install_rpath
                               {}, False, '']
                          d.targets.append(i)
                  # Install secondary outputs. Only used for Vala right now.
                  if num_outdirs > 1:
                      for output, outdir in zip(t.get_outputs()[1:], outdirs[1:]):
                          # User requested that we not install this output
                          if outdir is False:
                              continue
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdir, {}, False, None])
              elif isinstance(t, build.CustomTarget):
                  # If only one install_dir is specified, assume that all
                  # outputs will be installed into it. This is for
                  # backwards-compatibility and because it makes sense to
                  # avoid repetition since this is a common use-case.
                  #
                  # To selectively install only some outputs, pass `false` as
                  # the install_dir for the corresponding output by index
                  if num_outdirs == 1 and num_out > 1:
                      for output in t.get_outputs():
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdirs[0], {}, False, None])
                  else:
                      for output, outdir in zip(t.get_outputs(), outdirs):
                          # User requested that we not install this output
                          if outdir is False:
                              continue
                          f = os.path.join(self.get_target_dir(t), output)
                          d.targets.append([f, outdir, {}, False, None])
  
      def generate_custom_install_script(self, d):
          result = []
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for i in self.build.install_scripts:
              exe = i['exe']
              args = i['args']
              fixed_args = []
              for a in args:
                  a = a.replace('@SOURCE_ROOT@', srcdir)
                  a = a.replace('@BUILD_ROOT@', builddir)
                  fixed_args.append(a)
              result.append(build.RunScript(exe, fixed_args))
          d.install_scripts = result
  
      def generate_header_install(self, d):
          incroot = self.environment.get_includedir()
          headers = self.build.get_headers()
  
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for h in headers:
              outdir = h.get_custom_install_dir()
              if outdir is None:
                  outdir = os.path.join(incroot, h.get_install_subdir())
              for f in h.get_sources():
                  if not isinstance(f, File):
                      msg = 'Invalid header type {!r} can\'t be installed'
                      raise MesonException(msg.format(f))
                  abspath = f.absolute_path(srcdir, builddir)
                  i = [abspath, outdir]
                  d.headers.append(i)
  
      def generate_man_install(self, d):
          manroot = self.environment.get_mandir()
          man = self.build.get_man()
          for m in man:
              for f in m.get_sources():
                  num = f.split('.')[-1]
                  subdir = m.get_custom_install_dir()
                  if subdir is None:
                      subdir = os.path.join(manroot, 'man' + num)
                  srcabs = f.absolute_path(self.environment.get_source_dir(), self.environment.get_build_dir())
                  dstabs = os.path.join(subdir, os.path.basename(f.fname) + '.gz')
                  i = [srcabs, dstabs]
                  d.man.append(i)
  
      def generate_data_install(self, d):
          data = self.build.get_data()
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          for de in data:
              assert(isinstance(de, build.Data))
              subdir = de.install_dir
              if not subdir:
                  subdir = os.path.join(self.environment.get_datadir(), self.interpreter.build.project_name)
              for src_file, dst_name in zip(de.sources, de.rename):
                  assert(isinstance(src_file, mesonlib.File))
                  dst_abs = os.path.join(subdir, dst_name)
                  i = [src_file.absolute_path(srcdir, builddir), dst_abs, de.install_mode]
                  d.data.append(i)
  
      def generate_subdir_install(self, d):
          for sd in self.build.get_install_subdirs():
              src_dir = os.path.join(self.environment.get_source_dir(),
                                     sd.source_subdir,
                                     sd.installable_subdir).rstrip('/')
              dst_dir = os.path.join(self.environment.get_prefix(),
                                     sd.install_dir)
              if not sd.strip_directory:
                  dst_dir = os.path.join(dst_dir, os.path.basename(src_dir))
              d.install_subdirs.append([src_dir, dst_dir, sd.install_mode,
                                        sd.exclude])
  
      def generate_tests(self, outfile):
          self.serialize_tests()
          cmd = self.environment.get_build_command(True) + ['test', '--no-rebuild']
          if not self.environment.coredata.get_builtin_option('stdsplit'):
              cmd += ['--no-stdsplit']
          if self.environment.coredata.get_builtin_option('errorlogs'):
              cmd += ['--print-errorlogs']
          elem = NinjaBuildElement(self.all_outputs, 'meson-test', 'CUSTOM_COMMAND', ['all', 'PHONY'])
          elem.add_item('COMMAND', cmd)
          elem.add_item('DESC', 'Running all tests.')
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the above-defined meson-test target
          self.create_target_alias('meson-test', outfile)
  
          # And then benchmarks.
          cmd = self.environment.get_build_command(True) + [
              'test', '--benchmark', '--logbase',
              'benchmarklog', '--num-processes=1', '--no-rebuild']
          elem = NinjaBuildElement(self.all_outputs, 'meson-benchmark', 'CUSTOM_COMMAND', ['all', 'PHONY'])
          elem.add_item('COMMAND', cmd)
          elem.add_item('DESC', 'Running benchmark suite.')
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the above-defined meson-benchmark target
          self.create_target_alias('meson-benchmark', outfile)
  
      def generate_rules(self, outfile):
          outfile.write('# Rules for compiling.\n\n')
          self.generate_compile_rules(outfile)
          outfile.write('# Rules for linking.\n\n')
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          if num_pools > 0:
              outfile.write('''pool link_pool
    depth = %d
  
  ''' % num_pools)
          if self.environment.is_cross_build():
              self.generate_static_link_rules(True, outfile)
          self.generate_static_link_rules(False, outfile)
          self.generate_dynamic_link_rules(outfile)
          outfile.write('# Other rules\n\n')
          outfile.write('rule CUSTOM_COMMAND\n')
          outfile.write(' command = $COMMAND\n')
          outfile.write(' description = $DESC\n')
          outfile.write(' restat = 1\n\n')
          # Ninja errors out if you have deps = gcc but no depfile, so we must
          # have two rules for custom commands.
          outfile.write('rule CUSTOM_COMMAND_DEP\n')
          outfile.write(' command = $COMMAND\n')
          outfile.write(' description = $DESC\n')
          outfile.write(' deps = gcc\n')
          outfile.write(' depfile = $DEPFILE\n')
          outfile.write(' restat = 1\n\n')
          outfile.write('rule REGENERATE_BUILD\n')
          c = [ninja_quote(quote_func(x)) for x in self.environment.get_build_command()] + \
              ['--internal',
               'regenerate',
               ninja_quote(quote_func(self.environment.get_source_dir())),
               ninja_quote(quote_func(self.environment.get_build_dir()))]
          outfile.write(" command = " + ' '.join(c) + ' --backend ninja\n')
          outfile.write(' description = Regenerating build files.\n')
          outfile.write(' generator = 1\n\n')
          outfile.write('\n')
  
      def generate_phony(self, outfile):
          outfile.write('# Phony build target, always out of date\n')
          outfile.write('build PHONY: phony\n')
          outfile.write('\n')
  
      def generate_jar_target(self, target, outfile):
          fname = target.get_filename()
          outname_rel = os.path.join(self.get_target_dir(target), fname)
          src_list = target.get_sources()
          class_list = []
          compiler = target.compilers['java']
          c = 'c'
          m = ''
          e = ''
          f = 'f'
          main_class = target.get_main_class()
          if main_class != '':
              e = 'e'
          for src in src_list:
              plain_class_path = self.generate_single_java_compile(src, target, compiler, outfile)
              class_list.append(plain_class_path)
          class_dep_list = [os.path.join(self.get_target_private_dir(target), i) for i in class_list]
          jar_rule = 'java_LINKER'
          commands = [c + m + e + f]
          if e != '':
              commands.append(main_class)
          commands.append(self.get_target_filename(target))
          # Java compilation can produce an arbitrary number of output
          # class files for a single source file. Thus tell jar to just
          # grab everything in the final package.
          commands += ['-C', self.get_target_private_dir(target), '.']
          elem = NinjaBuildElement(self.all_outputs, outname_rel, jar_rule, [])
          elem.add_dep(class_dep_list)
          elem.add_item('ARGS', commands)
          elem.write(outfile)
  
      def generate_cs_resource_tasks(self, target, outfile):
          args = []
          deps = []
          for r in target.resources:
              rel_sourcefile = os.path.join(self.build_to_src, target.subdir, r)
              if r.endswith('.resources'):
                  a = '-resource:' + rel_sourcefile
              elif r.endswith('.txt') or r.endswith('.resx'):
                  ofilebase = os.path.splitext(os.path.basename(r))[0] + '.resources'
                  ofilename = os.path.join(self.get_target_private_dir(target), ofilebase)
                  elem = NinjaBuildElement(self.all_outputs, ofilename, "CUSTOM_COMMAND", rel_sourcefile)
                  elem.add_item('COMMAND', ['resgen', rel_sourcefile, ofilename])
                  elem.add_item('DESC', 'Compiling resource %s.' % rel_sourcefile)
                  elem.write(outfile)
                  deps.append(ofilename)
                  a = '-resource:' + ofilename
              else:
                  raise InvalidArguments('Unknown resource file %s.' % r)
              args.append(a)
          return args, deps
  
      def generate_cs_target(self, target, outfile):
          buildtype = self.get_option_for_target('buildtype', target)
          fname = target.get_filename()
          outname_rel = os.path.join(self.get_target_dir(target), fname)
          src_list = target.get_sources()
          compiler = target.compilers['cs']
          rel_srcs = [os.path.normpath(s.rel_to_builddir(self.build_to_src)) for s in src_list]
          deps = []
          commands = CompilerArgs(compiler, target.extra_args.get('cs', []))
          commands += compiler.get_buildtype_args(buildtype)
          if isinstance(target, build.Executable):
              commands.append('-target:exe')
          elif isinstance(target, build.SharedLibrary):
              commands.append('-target:library')
          else:
              raise MesonException('Unknown C# target type.')
          (resource_args, resource_deps) = self.generate_cs_resource_tasks(target, outfile)
          commands += resource_args
          deps += resource_deps
          commands += compiler.get_output_args(outname_rel)
          for l in target.link_targets:
              lname = os.path.join(self.get_target_dir(l), l.get_filename())
              commands += compiler.get_link_args(lname)
              deps.append(lname)
          if '-g' in commands:
              outputs = [outname_rel, outname_rel + '.mdb']
          else:
              outputs = [outname_rel]
          generated_sources = self.get_target_generated_sources(target)
          for rel_src in generated_sources.keys():
              dirpart, fnamepart = os.path.split(rel_src)
              if rel_src.lower().endswith('.cs'):
                  rel_srcs.append(os.path.normpath(rel_src))
              deps.append(os.path.normpath(rel_src))
  
          for dep in target.get_external_deps():
              commands.extend_direct(dep.get_link_args())
          commands += self.build.get_project_args(compiler, target.subproject)
          commands += self.build.get_global_args(compiler)
  
          elem = NinjaBuildElement(self.all_outputs, outputs, 'cs_COMPILER', rel_srcs)
          elem.add_dep(deps)
          elem.add_item('ARGS', commands)
          elem.write(outfile)
  
          self.generate_generator_list_rules(target, outfile)
  
      def generate_single_java_compile(self, src, target, compiler, outfile):
          args = []
          args += compiler.get_buildtype_args(self.get_option_for_target('buildtype', target))
          args += self.build.get_global_args(compiler)
          args += self.build.get_project_args(compiler, target.subproject)
          args += target.get_java_args()
          args += compiler.get_output_args(self.get_target_private_dir(target))
          for i in target.include_dirs:
              for idir in i.get_incdirs():
                  args += ['-sourcepath', os.path.join(self.build_to_src, i.curdir, idir)]
          rel_src = src.rel_to_builddir(self.build_to_src)
          plain_class_path = src.fname[:-4] + 'class'
          rel_obj = os.path.join(self.get_target_private_dir(target), plain_class_path)
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler.get_language() + '_COMPILER', rel_src)
          element.add_item('ARGS', args)
          element.write(outfile)
          return plain_class_path
  
      def generate_java_link(self, outfile):
          rule = 'rule java_LINKER\n'
          command = ' command = jar $ARGS\n'
          description = ' description = Creating JAR $out.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def determine_dep_vapis(self, target):
          """
          Peek into the sources of BuildTargets we're linking with, and if any of
          them was built with Vala, assume that it also generated a .vapi file of
          the same name as the BuildTarget and return the path to it relative to
          the build directory.
          """
          result = OrderedSet()
          for dep in itertools.chain(target.link_targets, target.link_whole_targets):
              for i in dep.sources:
                  if hasattr(i, 'fname'):
                      i = i.fname
                  if i.endswith('vala'):
                      vapiname = dep.vala_vapi
                      fullname = os.path.join(self.get_target_dir(dep), vapiname)
                      result.add(fullname)
                      break
          return list(result)
  
      def split_vala_sources(self, t):
          """
          Splits the target's sources into .vala, .gs, .vapi, and other sources.
          Handles both pre-existing and generated sources.
  
          Returns a tuple (vala, vapi, others) each of which is a dictionary with
          the keys being the path to the file (relative to the build directory)
          and the value being the object that generated or represents the file.
          """
          vala = OrderedDict()
          vapi = OrderedDict()
          others = OrderedDict()
          othersgen = OrderedDict()
          # Split pre-existing sources
          for s in t.get_sources():
              # BuildTarget sources are always mesonlib.File files which are
              # either in the source root, or generated with configure_file and
              # in the build root
              if not isinstance(s, File):
                  msg = 'All sources in target {!r} must be of type ' \
                        'mesonlib.File, not {!r}'.format(t, s)
                  raise InvalidArguments(msg)
              f = s.rel_to_builddir(self.build_to_src)
              if s.endswith(('.vala', '.gs')):
                  srctype = vala
              elif s.endswith('.vapi'):
                  srctype = vapi
              else:
                  srctype = others
              srctype[f] = s
          # Split generated sources
          for gensrc in t.get_generated_sources():
              for s in gensrc.get_outputs():
                  f = self.get_target_generated_dir(t, gensrc, s)
                  if s.endswith(('.vala', '.gs')):
                      srctype = vala
                  elif s.endswith('.vapi'):
                      srctype = vapi
                  # Generated non-Vala (C/C++) sources. Won't be used for
                  # generating the Vala compile rule below.
                  else:
                      srctype = othersgen
                  # Duplicate outputs are disastrous
                  if f in srctype and srctype[f] is not gensrc:
                      msg = 'Duplicate output {0!r} from {1!r} {2!r}; ' \
                            'conflicts with {0!r} from {4!r} {3!r}' \
                            ''.format(f, type(gensrc).__name__, gensrc.name,
                                      srctype[f].name, type(srctype[f]).__name__)
                      raise InvalidArguments(msg)
                  # Store 'somefile.vala': GeneratedList (or CustomTarget)
                  srctype[f] = gensrc
          return vala, vapi, (others, othersgen)
  
      def generate_vala_compile(self, target, outfile):
          """Vala is compiled into C. Set up all necessary build steps here."""
          (vala_src, vapi_src, other_src) = self.split_vala_sources(target)
          extra_dep_files = []
          if not vala_src:
              msg = 'Vala library {!r} has no Vala or Genie source files.'
              raise InvalidArguments(msg.format(target.name))
  
          valac = target.compilers['vala']
          c_out_dir = self.get_target_private_dir(target)
          # C files generated by valac
          vala_c_src = []
          # Files generated by valac
          valac_outputs = []
          # All sources that are passed to valac on the commandline
          all_files = list(vapi_src.keys())
          # Passed as --basedir
          srcbasedir = os.path.join(self.build_to_src, target.get_subdir())
          for (vala_file, gensrc) in vala_src.items():
              all_files.append(vala_file)
              # Figure out where the Vala compiler will write the compiled C file
              #
              # If the Vala file is in a subdir of the build dir (in our case
              # because it was generated/built by something else), and is also
              # a subdir of --basedir (because the builddir is in the source
              # tree, and the target subdir is the source root), the subdir
              # components from the source root till the private builddir will be
              # duplicated inside the private builddir. Otherwise, just the
              # basename will be used.
              #
              # If the Vala file is outside the build directory, the paths from
              # the --basedir till the subdir will be duplicated inside the
              # private builddir.
              if isinstance(gensrc, (build.CustomTarget, build.GeneratedList)) or gensrc.is_built:
                  vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
                  # Check if the vala file is in a subdir of --basedir
                  abs_srcbasedir = os.path.join(self.environment.get_source_dir(), target.get_subdir())
                  abs_vala_file = os.path.join(self.environment.get_build_dir(), vala_file)
                  if PurePath(os.path.commonpath((abs_srcbasedir, abs_vala_file))) == PurePath(abs_srcbasedir):
                      vala_c_subdir = PurePath(abs_vala_file).parent.relative_to(abs_srcbasedir)
                      vala_c_file = os.path.join(vala_c_subdir, vala_c_file)
              else:
                  path_to_target = os.path.join(self.build_to_src, target.get_subdir())
                  if vala_file.startswith(path_to_target):
                      vala_c_file = os.path.splitext(os.path.relpath(vala_file, path_to_target))[0] + '.c'
                  else:
                      vala_c_file = os.path.splitext(os.path.basename(vala_file))[0] + '.c'
              # All this will be placed inside the c_out_dir
              vala_c_file = os.path.join(c_out_dir, vala_c_file)
              vala_c_src.append(vala_c_file)
              valac_outputs.append(vala_c_file)
  
          args = self.generate_basic_compiler_args(target, valac)
          args += valac.get_colorout_args(self.environment.coredata.base_options.get('b_colorout').value)
          # Tell Valac to output everything in our private directory. Sadly this
          # means it will also preserve the directory components of Vala sources
          # found inside the build tree (generated sources).
          args += ['--directory', c_out_dir]
          args += ['--basedir', srcbasedir]
          if not isinstance(target, build.Executable):
              # Library name
              args += ['--library', target.name]
              # Outputted header
              hname = os.path.join(self.get_target_dir(target), target.vala_header)
              args += ['--header', hname]
              if self.is_unity(target):
                  # Without this the declarations will get duplicated in the .c
                  # files and cause a build failure when all of them are
                  # #include-d in one .c file.
                  # https://github.com/mesonbuild/meson/issues/1969
                  args += ['--use-header']
              valac_outputs.append(hname)
              # Outputted vapi file
              vapiname = os.path.join(self.get_target_dir(target), target.vala_vapi)
              # Force valac to write the vapi and gir files in the target build dir.
              # Without this, it will write it inside c_out_dir
              args += ['--vapi', os.path.join('..', target.vala_vapi)]
              valac_outputs.append(vapiname)
              target.outputs += [target.vala_header, target.vala_vapi]
              # Install header and vapi to default locations if user requests this
              if len(target.install_dir) > 1 and target.install_dir[1] is True:
                  target.install_dir[1] = self.environment.get_includedir()
              if len(target.install_dir) > 2 and target.install_dir[2] is True:
                  target.install_dir[2] = os.path.join(self.environment.get_datadir(), 'vala', 'vapi')
              # Generate GIR if requested
              if isinstance(target.vala_gir, str):
                  girname = os.path.join(self.get_target_dir(target), target.vala_gir)
                  args += ['--gir', os.path.join('..', target.vala_gir)]
                  valac_outputs.append(girname)
                  target.outputs.append(target.vala_gir)
                  # Install GIR to default location if requested by user
                  if len(target.install_dir) > 3 and target.install_dir[3] is True:
                      target.install_dir[3] = os.path.join(self.environment.get_datadir(), 'gir-1.0')
          # Detect gresources and add --gresources arguments for each
          for (gres, gensrc) in other_src[1].items():
              if isinstance(gensrc, modules.GResourceTarget):
                  gres_xml, = self.get_custom_target_sources(gensrc)
                  args += ['--gresources=' + gres_xml]
          extra_args = []
  
          for a in target.extra_args.get('vala', []):
              if isinstance(a, File):
                  relname = a.rel_to_builddir(self.build_to_src)
                  extra_dep_files.append(relname)
                  extra_args.append(relname)
              else:
                  extra_args.append(a)
          dependency_vapis = self.determine_dep_vapis(target)
          extra_dep_files += dependency_vapis
          args += extra_args
          element = NinjaBuildElement(self.all_outputs, valac_outputs,
                                      valac.get_language() + '_COMPILER',
                                      all_files + dependency_vapis)
          element.add_item('ARGS', args)
          element.add_dep(extra_dep_files)
          element.write(outfile)
          return other_src[0], other_src[1], vala_c_src
  
      def generate_rust_target(self, target, outfile):
          rustc = target.compilers['rust']
          relsrc = []
          for i in target.get_sources():
              if not rustc.can_compile(i):
                  raise InvalidArguments('Rust target %s contains a non-rust source file.' % target.get_basename())
              relsrc.append(i.rel_to_builddir(self.build_to_src))
          target_name = os.path.join(target.subdir, target.get_filename())
          args = ['--crate-type']
          if isinstance(target, build.Executable):
              cratetype = 'bin'
          elif hasattr(target, 'rust_crate_type'):
              cratetype = target.rust_crate_type
          elif isinstance(target, build.SharedLibrary):
              cratetype = 'dylib'
          elif isinstance(target, build.StaticLibrary):
              cratetype = 'rlib'
          else:
              raise InvalidArguments('Unknown target type for rustc.')
          args.append(cratetype)
          args += ['--crate-name', target.name]
          args += rustc.get_buildtype_args(self.get_option_for_target('buildtype', target))
          depfile = os.path.join(target.subdir, target.name + '.d')
          args += ['--emit', 'dep-info={}'.format(depfile), '--emit', 'link']
          args += target.get_extra_args('rust')
          args += ['-o', os.path.join(target.subdir, target.get_filename())]
          orderdeps = [os.path.join(t.subdir, t.get_filename()) for t in target.link_targets]
          linkdirs = OrderedDict()
          for d in target.link_targets:
              linkdirs[d.subdir] = True
              # specify `extern CRATE_NAME=OUTPUT_FILE` for each Rust
              # dependency, so that collisions with libraries in rustc's
              # sysroot don't cause ambiguity
              args += ['--extern', '{}={}'.format(d.name, os.path.join(d.subdir, d.filename))]
          for d in linkdirs.keys():
              if d == '':
                  d = '.'
              args += ['-L', d]
          has_shared_deps = False
          for dep in target.get_dependencies():
              if isinstance(dep, build.SharedLibrary):
                  has_shared_deps = True
          if isinstance(target, build.SharedLibrary) or has_shared_deps:
              # add prefer-dynamic if any of the Rust libraries we link
              # against are dynamic, otherwise we'll end up with
              # multiple implementations of crates
              args += ['-C', 'prefer-dynamic']
  
              # build the usual rpath arguments as well...
  
              # Set runtime-paths so we can run executables without needing to set
              # LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows.
              if has_path_sep(target.name):
                  # Target names really should not have slashes in them, but
                  # unfortunately we did not check for that and some downstream projects
                  # now have them. Once slashes are forbidden, remove this bit.
                  target_slashname_workaround_dir = os.path.join(os.path.dirname(target.name),
                                                                 self.get_target_dir(target))
              else:
                  target_slashname_workaround_dir = self.get_target_dir(target)
              rpath_args = rustc.build_rpath_args(self.environment.get_build_dir(),
                                                  target_slashname_workaround_dir,
                                                  self.determine_rpath_dirs(target),
                                                  target.build_rpath,
                                                  target.install_rpath)
              # ... but then add rustc's sysroot to account for rustup
              # installations
              for rpath_arg in rpath_args:
                  args += ['-C', 'link-arg=' + rpath_arg + ':' + os.path.join(rustc.get_sysroot(), 'lib')]
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          compiler_name = 'rust%s_COMPILER' % crstr
          element = NinjaBuildElement(self.all_outputs, target_name, compiler_name, relsrc)
          if len(orderdeps) > 0:
              element.add_orderdep(orderdeps)
          element.add_item('ARGS', args)
          element.add_item('targetdep', depfile)
          element.add_item('cratetype', cratetype)
          element.write(outfile)
          if isinstance(target, build.SharedLibrary):
              self.generate_shsym(outfile, target)
  
      def swift_module_file_name(self, target):
          return os.path.join(self.get_target_private_dir(target),
                              self.target_swift_modulename(target) + '.swiftmodule')
  
      def target_swift_modulename(self, target):
          return target.name
  
      def is_swift_target(self, target):
          for s in target.sources:
              if s.endswith('swift'):
                  return True
          return False
  
      def determine_swift_dep_modules(self, target):
          result = []
          for l in target.link_targets:
              if self.is_swift_target(l):
                  result.append(self.swift_module_file_name(l))
          return result
  
      def determine_swift_dep_dirs(self, target):
          result = []
          for l in target.link_targets:
              result.append(self.get_target_private_dir_abs(l))
          return result
  
      def get_swift_link_deps(self, target):
          result = []
          for l in target.link_targets:
              result.append(self.get_target_filename(l))
          return result
  
      def split_swift_generated_sources(self, target):
          all_srcs = self.get_target_generated_sources(target)
          srcs = []
          others = []
          for i in all_srcs:
              if i.endswith('.swift'):
                  srcs.append(i)
              else:
                  others.append(i)
          return srcs, others
  
      def generate_swift_target(self, target, outfile):
          module_name = self.target_swift_modulename(target)
          swiftc = target.compilers['swift']
          abssrc = []
          abs_headers = []
          header_imports = []
          for i in target.get_sources():
              if swiftc.can_compile(i):
                  relsrc = i.rel_to_builddir(self.build_to_src)
                  abss = os.path.normpath(os.path.join(self.environment.get_build_dir(), relsrc))
                  abssrc.append(abss)
              elif self.environment.is_header(i):
                  relh = i.rel_to_builddir(self.build_to_src)
                  absh = os.path.normpath(os.path.join(self.environment.get_build_dir(), relh))
                  abs_headers.append(absh)
                  header_imports += swiftc.get_header_import_args(absh)
              else:
                  raise InvalidArguments('Swift target %s contains a non-swift source file.' % target.get_basename())
          os.makedirs(self.get_target_private_dir_abs(target), exist_ok=True)
          compile_args = swiftc.get_compile_only_args()
          compile_args += swiftc.get_module_args(module_name)
          compile_args += self.build.get_project_args(swiftc, target.subproject)
          compile_args += self.build.get_global_args(swiftc)
          for i in reversed(target.get_include_dirs()):
              basedir = i.get_curdir()
              for d in i.get_incdirs():
                  if d not in ('', '.'):
                      expdir = os.path.join(basedir, d)
                  else:
                      expdir = basedir
                  srctreedir = os.path.normpath(os.path.join(self.environment.get_build_dir(), self.build_to_src, expdir))
                  sargs = swiftc.get_include_args(srctreedir)
                  compile_args += sargs
          link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target)))
          link_args += self.build.get_project_link_args(swiftc, target.subproject)
          link_args += self.build.get_global_link_args(swiftc)
          rundir = self.get_target_private_dir(target)
          out_module_name = self.swift_module_file_name(target)
          in_module_files = self.determine_swift_dep_modules(target)
          abs_module_dirs = self.determine_swift_dep_dirs(target)
          module_includes = []
          for x in abs_module_dirs:
              module_includes += swiftc.get_include_args(x)
          link_deps = self.get_swift_link_deps(target)
          abs_link_deps = [os.path.join(self.environment.get_build_dir(), x) for x in link_deps]
          for d in target.link_targets:
              reldir = self.get_target_dir(d)
              if reldir == '':
                  reldir = '.'
              link_args += ['-L', os.path.normpath(os.path.join(self.environment.get_build_dir(), reldir))]
          (rel_generated, _) = self.split_swift_generated_sources(target)
          abs_generated = [os.path.join(self.environment.get_build_dir(), x) for x in rel_generated]
          # We need absolute paths because swiftc needs to be invoked in a subdir
          # and this is the easiest way about it.
          objects = [] # Relative to swift invocation dir
          rel_objects = [] # Relative to build.ninja
          for i in abssrc + abs_generated:
              base = os.path.basename(i)
              oname = os.path.splitext(base)[0] + '.o'
              objects.append(oname)
              rel_objects.append(os.path.join(self.get_target_private_dir(target), oname))
  
          # Swiftc does not seem to be able to emit objects and module files in one go.
          elem = NinjaBuildElement(self.all_outputs, rel_objects,
                                   'swift_COMPILER',
                                   abssrc)
          elem.add_dep(in_module_files + rel_generated)
          elem.add_dep(abs_headers)
          elem.add_item('ARGS', compile_args + header_imports + abs_generated + module_includes)
          elem.add_item('RUNDIR', rundir)
          elem.write(outfile)
          elem = NinjaBuildElement(self.all_outputs, out_module_name,
                                   'swift_COMPILER',
                                   abssrc)
          elem.add_dep(in_module_files + rel_generated)
          elem.add_item('ARGS', compile_args + abs_generated + module_includes + swiftc.get_mod_gen_args())
          elem.add_item('RUNDIR', rundir)
          elem.write(outfile)
          if isinstance(target, build.StaticLibrary):
              elem = self.generate_link(target, outfile, self.get_target_filename(target),
                                        rel_objects, self.build.static_linker)
              elem.write(outfile)
          elif isinstance(target, build.Executable):
              elem = NinjaBuildElement(self.all_outputs, self.get_target_filename(target), 'swift_COMPILER', [])
              elem.add_dep(rel_objects)
              elem.add_dep(link_deps)
              elem.add_item('ARGS', link_args + swiftc.get_std_exe_link_args() + objects + abs_link_deps)
              elem.add_item('RUNDIR', rundir)
              elem.write(outfile)
          else:
              raise MesonException('Swift supports only executable and static library targets.')
  
      def generate_static_link_rules(self, is_cross, outfile):
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          if 'java' in self.build.compilers:
              if not is_cross:
                  self.generate_java_link(outfile)
          if is_cross:
              if self.environment.cross_info.need_cross_compiler():
                  static_linker = self.build.static_cross_linker
              else:
                  static_linker = self.build.static_linker
              crstr = '_CROSS'
          else:
              static_linker = self.build.static_linker
              crstr = ''
          if static_linker is None:
              return
          rule = 'rule STATIC%s_LINKER\n' % crstr
          # We don't use @file.rsp on Windows with ArLinker because llvm-ar and
          # gcc-ar blindly pass the --plugin argument to `ar` and you cannot pass
          # options as arguments while using the @file.rsp syntax.
          # See: https://github.com/mesonbuild/meson/issues/1646
          if mesonlib.is_windows() and not isinstance(static_linker, ArLinker):
              command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = $LINK_ARGS {output_args} $in
  '''
          else:
              command_template = ' command = {executable} $LINK_ARGS {output_args} $in\n'
          cmdlist = []
          # FIXME: Must normalize file names with pathlib.Path before writing
          #        them out to fix this properly on Windows. See:
          # https://github.com/mesonbuild/meson/issues/1517
          # https://github.com/mesonbuild/meson/issues/1526
          if isinstance(static_linker, ArLinker) and not mesonlib.is_windows():
              # `ar` has no options to overwrite archives. It always appends,
              # which is never what we want. Delete an existing library first if
              # it exists. https://github.com/mesonbuild/meson/issues/1355
              cmdlist = [execute_wrapper, rmfile_prefix.format('$out')]
          cmdlist += static_linker.get_exelist()
          command = command_template.format(
              executable=' '.join(cmdlist),
              output_args=' '.join(static_linker.get_output_args('$out')))
          description = ' description = Linking static target $out.\n\n'
          outfile.write(rule)
          outfile.write(command)
          if num_pools > 0:
              outfile.write(' pool = link_pool\n')
          outfile.write(description)
  
      def generate_dynamic_link_rules(self, outfile):
          num_pools = self.environment.coredata.backend_options['backend_max_links'].value
          ctypes = [(self.build.compilers, False)]
          if self.environment.is_cross_build():
              if self.environment.cross_info.need_cross_compiler():
                  ctypes.append((self.build.cross_compilers, True))
              else:
                  # Native compiler masquerades as the cross compiler.
                  ctypes.append((self.build.compilers, True))
          else:
              ctypes.append((self.build.cross_compilers, True))
          for (complist, is_cross) in ctypes:
              for langname, compiler in complist.items():
                  if langname == 'java' \
                          or langname == 'vala' \
                          or langname == 'rust' \
                          or langname == 'cs':
                      continue
                  crstr = ''
                  cross_args = []
                  if is_cross:
                      crstr = '_CROSS'
                      try:
                          cross_args = self.environment.cross_info.config['properties'][langname + '_link_args']
                      except KeyError:
                          pass
                  rule = 'rule %s%s_LINKER\n' % (langname, crstr)
                  if mesonlib.is_windows():
                      command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = $ARGS  {output_args} $in $LINK_ARGS {cross_args} $aliasing
  '''
                  else:
                      command_template = ' command = {executable} $ARGS {output_args} $in $LINK_ARGS {cross_args} $aliasing\n'
                  command = command_template.format(
                      executable=' '.join(compiler.get_linker_exelist()),
                      cross_args=' '.join(cross_args),
                      output_args=' '.join(compiler.get_linker_output_args('$out'))
                  )
                  description = ' description = Linking target $out.\n'
                  outfile.write(rule)
                  outfile.write(command)
                  if num_pools > 0:
                      outfile.write(' pool = link_pool\n')
                  outfile.write(description)
                  outfile.write('\n')
          outfile.write('\n')
          args = [ninja_quote(quote_func(x)) for x in self.environment.get_build_command()] + \
              ['--internal',
               'symbolextractor',
               '$in',
               '$out']
          symrule = 'rule SHSYM\n'
          symcmd = ' command = ' + ' '.join(args) + ' $CROSS\n'
          synstat = ' restat = 1\n'
          syndesc = ' description = Generating symbol file $out.\n'
          outfile.write(symrule)
          outfile.write(symcmd)
          outfile.write(synstat)
          outfile.write(syndesc)
          outfile.write('\n')
  
      def generate_java_compile_rule(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Java object $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_cs_compile_rule(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
  
          if mesonlib.is_windows():
              command = ''' command = {executable}  @$out.rsp
   rspfile = $out.rsp
   rspfile_content =  $ARGS  $in
  '''.format(executable=invoc)
          else:
              command = ' command = %s $ARGS $in\n' % invoc
  
          description = ' description = Compiling C Sharp target $out.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_vala_compile_rules(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Vala source $in.\n'
          restat = ' restat = 1\n' # ValaC does this always to take advantage of it.
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write(restat)
          outfile.write('\n')
  
      def generate_rust_compile_rules(self, compiler, outfile, is_cross):
          crstr = ''
          if is_cross:
              crstr = '_CROSS'
          rule = 'rule %s%s_COMPILER\n' % (compiler.get_language(), crstr)
          invoc = ' '.join([ninja_quote(i) for i in compiler.get_exelist()])
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Rust source $in.\n'
          depfile = ' depfile = $targetdep\n'
  
          depstyle = ' deps = gcc\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write(depfile)
          outfile.write(depstyle)
          outfile.write('\n')
  
      def generate_swift_compile_rules(self, compiler, outfile):
          rule = 'rule %s_COMPILER\n' % compiler.get_language()
          full_exe = [ninja_quote(x) for x in self.environment.get_build_command()] + [
              '--internal',
              'dirchanger',
              '$RUNDIR',
          ]
          invoc = (' '.join(full_exe) + ' ' +
                   ' '.join(ninja_quote(i) for i in compiler.get_exelist()))
          command = ' command = %s $ARGS $in\n' % invoc
          description = ' description = Compiling Swift source $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_fortran_dep_hack(self, outfile):
          if mesonlib.is_windows():
              cmd = 'cmd /C ""'
          else:
              cmd = 'true'
          template = '''# Workaround for these issues:
  # https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
  # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=47485
  rule FORTRAN_DEP_HACK
   command = %s
   description = Dep hack
   restat = 1
  
  '''
          outfile.write(template % cmd)
  
      def generate_llvm_ir_compile_rule(self, compiler, is_cross, outfile):
          if getattr(self, 'created_llvm_ir_rule', False):
              return
          rule = 'rule llvm_ir{}_COMPILER\n'.format('_CROSS' if is_cross else '')
          if mesonlib.is_windows():
              command_template = ' command = {executable} @$out.rsp\n' \
                                 ' rspfile = $out.rsp\n' \
                                 ' rspfile_content = {cross_args} $ARGS {output_args} {compile_only_args} $in\n'
          else:
              command_template = ' command = {executable} {cross_args} $ARGS {output_args} {compile_only_args} $in\n'
          command = command_template.format(
              executable=' '.join([ninja_quote(i) for i in compiler.get_exelist()]),
              cross_args=' '.join(self.get_cross_info_lang_args(compiler.language, is_cross)),
              output_args=' '.join(compiler.get_output_args('$out')),
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Compiling LLVM IR object $in.\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(description)
          outfile.write('\n')
          self.created_llvm_ir_rule = True
  
      def get_cross_info_lang_args(self, lang, is_cross):
          if is_cross:
              try:
                  return self.environment.cross_info.config['properties'][lang + '_args']
              except KeyError:
                  pass
          return []
  
      def generate_compile_rule_for(self, langname, compiler, is_cross, outfile):
          if langname == 'java':
              if not is_cross:
                  self.generate_java_compile_rule(compiler, outfile)
              return
          if langname == 'cs':
              if not is_cross:
                  self.generate_cs_compile_rule(compiler, outfile)
              return
          if langname == 'vala':
              if not is_cross:
                  self.generate_vala_compile_rules(compiler, outfile)
              return
          if langname == 'rust':
              self.generate_rust_compile_rules(compiler, outfile, is_cross)
              return
          if langname == 'swift':
              if not is_cross:
                  self.generate_swift_compile_rules(compiler, outfile)
              return
          if langname == 'fortran':
              self.generate_fortran_dep_hack(outfile)
          if is_cross:
              crstr = '_CROSS'
          else:
              crstr = ''
          rule = 'rule %s%s_COMPILER\n' % (langname, crstr)
          depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
          quoted_depargs = []
          for d in depargs:
              if d != '$out' and d != '$in':
                  d = quote_func(d)
              quoted_depargs.append(d)
          cross_args = self.get_cross_info_lang_args(langname, is_cross)
          if mesonlib.is_windows():
              command_template = ''' command = {executable} @$out.rsp
   rspfile = $out.rsp
   rspfile_content = {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in
  '''
          else:
              command_template = ' command = {executable} {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in\n'
          command = command_template.format(
              executable=' '.join([ninja_quote(i) for i in compiler.get_exelist()]),
              cross_args=' '.join(cross_args),
              dep_args=' '.join(quoted_depargs),
              output_args=' '.join(compiler.get_output_args('$out')),
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Compiling %s object $out.\n' % compiler.get_display_language()
          if compiler.get_id() == 'msvc':
              deps = ' deps = msvc\n'
          else:
              deps = ' deps = gcc\n'
              deps += ' depfile = $DEPFILE\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(deps)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_pch_rule_for(self, langname, compiler, is_cross, outfile):
          if langname != 'c' and langname != 'cpp':
              return
          if is_cross:
              crstr = '_CROSS'
          else:
              crstr = ''
          rule = 'rule %s%s_PCH\n' % (langname, crstr)
          depargs = compiler.get_dependency_gen_args('$out', '$DEPFILE')
          cross_args = []
          if is_cross:
              try:
                  cross_args = self.environment.cross_info.config['properties'][langname + '_args']
              except KeyError:
                  pass
  
          quoted_depargs = []
          for d in depargs:
              if d != '$out' and d != '$in':
                  d = quote_func(d)
              quoted_depargs.append(d)
          if compiler.get_id() == 'msvc':
              output = ''
          else:
              output = ' '.join(compiler.get_output_args('$out'))
          command = " command = {executable} {cross_args} $ARGS {dep_args} {output_args} {compile_only_args} $in\n".format(
              executable=' '.join(compiler.get_exelist()),
              cross_args=' '.join(cross_args),
              dep_args=' '.join(quoted_depargs),
              output_args=output,
              compile_only_args=' '.join(compiler.get_compile_only_args())
          )
          description = ' description = Precompiling header %s.\n' % '$in'
          if compiler.get_id() == 'msvc':
              deps = ' deps = msvc\n'
          else:
              deps = ' deps = gcc\n'
              deps += ' depfile = $DEPFILE\n'
          outfile.write(rule)
          outfile.write(command)
          outfile.write(deps)
          outfile.write(description)
          outfile.write('\n')
  
      def generate_compile_rules(self, outfile):
          for langname, compiler in self.build.compilers.items():
              if compiler.get_id() == 'clang':
                  self.generate_llvm_ir_compile_rule(compiler, False, outfile)
              self.generate_compile_rule_for(langname, compiler, False, outfile)
              self.generate_pch_rule_for(langname, compiler, False, outfile)
          if self.environment.is_cross_build():
              # In case we are going a target-only build, make the native compilers
              # masquerade as cross compilers.
              if self.environment.cross_info.need_cross_compiler():
                  cclist = self.build.cross_compilers
              else:
                  cclist = self.build.compilers
              for langname, compiler in cclist.items():
                  if compiler.get_id() == 'clang':
                      self.generate_llvm_ir_compile_rule(compiler, True, outfile)
                  self.generate_compile_rule_for(langname, compiler, True, outfile)
                  self.generate_pch_rule_for(langname, compiler, True, outfile)
          outfile.write('\n')
  
      def generate_generator_list_rules(self, target, outfile):
          # CustomTargets have already written their rules and
          # CustomTargetIndexes don't actually get generated, so write rules for
          # GeneratedLists here
          for genlist in target.get_generated_sources():
              if isinstance(genlist, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              self.generate_genlist_for_target(genlist, target, outfile)
  
      def replace_paths(self, target, args, override_subdir=None):
          if override_subdir:
              source_target_dir = os.path.join(self.build_to_src, override_subdir)
          else:
              source_target_dir = self.get_target_source_dir(target)
          relout = self.get_target_private_dir(target)
          args = [x.replace("@SOURCE_DIR@", self.build_to_src).replace("@BUILD_DIR@", relout)
                  for x in args]
          args = [x.replace("@CURRENT_SOURCE_DIR@", source_target_dir) for x in args]
          args = [x.replace("@SOURCE_ROOT@", self.build_to_src).replace("@BUILD_ROOT@", '.')
                  for x in args]
          args = [x.replace('\\', '/') for x in args]
          return args
  
      def generate_genlist_for_target(self, genlist, target, outfile):
          generator = genlist.get_generator()
          subdir = genlist.subdir
          exe = generator.get_exe()
          exe_arr = self.exe_object_to_cmd_array(exe)
          infilelist = genlist.get_inputs()
          outfilelist = genlist.get_outputs()
          extra_dependencies = [os.path.join(self.build_to_src, i) for i in genlist.extra_depends]
          for i in range(len(infilelist)):
              if len(generator.outputs) == 1:
                  sole_output = os.path.join(self.get_target_private_dir(target), outfilelist[i])
              else:
                  sole_output = ''
              curfile = infilelist[i]
              infilename = curfile.rel_to_builddir(self.build_to_src)
              base_args = generator.get_arglist(infilename)
              outfiles = genlist.get_outputs_for(curfile)
              outfiles = [os.path.join(self.get_target_private_dir(target), of) for of in outfiles]
              if generator.depfile is None:
                  rulename = 'CUSTOM_COMMAND'
                  args = base_args
              else:
                  rulename = 'CUSTOM_COMMAND_DEP'
                  depfilename = generator.get_dep_outname(infilename)
                  depfile = os.path.join(self.get_target_private_dir(target), depfilename)
                  args = [x.replace('@DEPFILE@', depfile) for x in base_args]
              args = [x.replace("@INPUT@", infilename).replace('@OUTPUT@', sole_output)
                      for x in args]
              args = self.replace_outputs(args, self.get_target_private_dir(target), outfilelist)
              # We have consumed output files, so drop them from the list of remaining outputs.
              if sole_output == '':
                  outfilelist = outfilelist[len(generator.outputs):]
              args = self.replace_paths(target, args, override_subdir=subdir)
              cmdlist = exe_arr + self.replace_extra_args(args, genlist)
              if generator.capture:
                  exe_data = self.serialize_executable(
                      cmdlist[0],
                      cmdlist[1:],
                      self.environment.get_build_dir(),
                      capture=outfiles[0]
                  )
                  cmd = self.environment.get_build_command() + ['--internal', 'exe', exe_data]
                  abs_pdir = os.path.join(self.environment.get_build_dir(), self.get_target_dir(target))
                  os.makedirs(abs_pdir, exist_ok=True)
              else:
                  cmd = cmdlist
  
              elem = NinjaBuildElement(self.all_outputs, outfiles, rulename, infilename)
              if generator.depfile is not None:
                  elem.add_item('DEPFILE', depfile)
              if len(extra_dependencies) > 0:
                  elem.add_dep(extra_dependencies)
              elem.add_item('DESC', 'Generating {!r}.'.format(sole_output))
              if isinstance(exe, build.BuildTarget):
                  elem.add_dep(self.get_target_filename(exe))
              elem.add_item('COMMAND', cmd)
              elem.write(outfile)
  
      def scan_fortran_module_outputs(self, target):
          compiler = None
          for lang, c in self.build.compilers.items():
              if lang == 'fortran':
                  compiler = c
                  break
          if compiler is None:
              self.fortran_deps[target.get_basename()] = {}
              return
          modre = re.compile(r"\s*module\s+(\w+)", re.IGNORECASE)
          module_files = {}
          for s in target.get_sources():
              # FIXME, does not work for Fortran sources generated by
              # custom_target() and generator() as those are run after
              # the configuration (configure_file() is OK)
              if not compiler.can_compile(s):
                  continue
              filename = s.absolute_path(self.environment.get_source_dir(),
                                         self.environment.get_build_dir())
              # Some Fortran editors save in weird encodings,
              # but all the parts we care about are in ASCII.
              with open(filename, errors='ignore') as f:
                  for line in f:
                      modmatch = modre.match(line)
                      if modmatch is not None:
                          modname = modmatch.group(1).lower()
                          if modname == 'procedure':
                              # MODULE PROCEDURE construct
                              continue
                          if modname in module_files:
                              raise InvalidArguments(
                                  'Namespace collision: module %s defined in '
                                  'two files %s and %s.' %
                                  (modname, module_files[modname], s))
                          module_files[modname] = s
          self.fortran_deps[target.get_basename()] = module_files
  
      def get_fortran_deps(self, compiler, src, target):
          mod_files = []
          usere = re.compile(r"\s*use\s+(\w+)", re.IGNORECASE)
          dirname = self.get_target_private_dir(target)
          tdeps = self.fortran_deps[target.get_basename()]
          with open(src) as f:
              for line in f:
                  usematch = usere.match(line)
                  if usematch is not None:
                      usename = usematch.group(1).lower()
                      if usename not in tdeps:
                          # The module is not provided by any source file. This
                          # is due to:
                          #   a) missing file/typo/etc
                          #   b) using a module provided by the compiler, such as
                          #      OpenMP
                          # There's no easy way to tell which is which (that I
                          # know of) so just ignore this and go on. Ideally we
                          # would print a warning message to the user but this is
                          # a common occurrence, which would lead to lots of
                          # distracting noise.
                          continue
                      mod_source_file = tdeps[usename]
                      # Check if a source uses a module it exports itself.
                      # Potential bug if multiple targets have a file with
                      # the same name.
                      if mod_source_file.fname == os.path.basename(src):
                          continue
                      mod_name = compiler.module_name_to_filename(
                          usematch.group(1))
                      mod_files.append(os.path.join(dirname, mod_name))
          return mod_files
  
      def get_cross_stdlib_args(self, target, compiler):
          if not target.is_cross:
              return []
          if not self.environment.cross_info.has_stdlib(compiler.language):
              return []
          return compiler.get_no_stdinc_args()
  
      def get_compile_debugfile_args(self, compiler, target, objfile):
          if compiler.id != 'msvc':
              return []
          # The way MSVC uses PDB files is documented exactly nowhere so
          # the following is what we have been able to decipher via
          # reverse engineering.
          #
          # Each object file gets the path of its PDB file written
          # inside it.  This can be either the final PDB (for, say,
          # foo.exe) or an object pdb (for foo.obj). If the former, then
          # each compilation step locks the pdb file for writing, which
          # is a bottleneck and object files from one target can not be
          # used in a different target. The latter seems to be the
          # sensible one (and what Unix does) but there is a catch.  If
          # you try to use precompiled headers MSVC will error out
          # because both source and pch pdbs go in the same file and
          # they must be the same.
          #
          # This means:
          #
          # - pch files must be compiled anew for every object file (negating
          #   the entire point of having them in the first place)
          # - when using pch, output must go to the target pdb
          #
          # Since both of these are broken in some way, use the one that
          # works for each target. This unfortunately means that you
          # can't combine pch and object extraction in a single target.
          #
          # PDB files also lead to filename collisions. A target foo.exe
          # has a corresponding foo.pdb. A shared library foo.dll _also_
          # has pdb file called foo.pdb. So will a static library
          # foo.lib, which clobbers both foo.pdb _and_ the dll file's
          # export library called foo.lib (by default, currently we name
          # them libfoo.a to avoidt this issue). You can give the files
          # unique names such as foo_exe.pdb but VC also generates a
          # bunch of other files which take their names from the target
          # basename (i.e. "foo") and stomp on each other.
          #
          # CMake solves this problem by doing two things. First of all
          # static libraries do not generate pdb files at
          # all. Presumably you don't need them and VC is smart enough
          # to look up the original data when linking (speculation, not
          # tested). The second solution is that you can only have
          # target named "foo" as an exe, shared lib _or_ static
          # lib. This makes filename collisions not happen. The downside
          # is that you can't have an executable foo that uses a shared
          # library libfoo.so, which is a common idiom on Unix.
          #
          # If you feel that the above is completely wrong and all of
          # this is actually doable, please send patches.
  
          if target.has_pch():
              tfilename = self.get_target_filename_abs(target)
              return compiler.get_compile_debugfile_args(tfilename, pch=True)
          else:
              return compiler.get_compile_debugfile_args(objfile, pch=False)
  
      def get_link_debugfile_args(self, linker, target, outname):
          return linker.get_link_debugfile_args(outname)
  
      def generate_llvm_ir_compile(self, target, outfile, src):
          compiler = get_compiler_for_source(target.compilers.values(), src)
          commands = CompilerArgs(compiler)
          # Compiler args for compiling this target
          commands += compilers.get_base_compile_args(self.environment.coredata.base_options,
                                                      compiler)
          if isinstance(src, File):
              if src.is_built:
                  src_filename = os.path.join(src.subdir, src.fname)
              else:
                  src_filename = src.fname
          elif os.path.isabs(src):
              src_filename = os.path.basename(src)
          else:
              src_filename = src
          obj_basename = src_filename.replace('/', '_').replace('\\', '_')
          rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
          rel_obj += '.' + self.environment.get_object_suffix()
          commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
          if isinstance(src, File) and src.is_built:
              rel_src = src.fname
          elif isinstance(src, File):
              rel_src = src.rel_to_builddir(self.build_to_src)
          else:
              raise InvalidArguments('Invalid source type: {!r}'.format(src))
          # Write the Ninja build command
          compiler_name = 'llvm_ir{}_COMPILER'.format('_CROSS' if target.is_cross else '')
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          element.add_item('ARGS', commands)
          element.write(outfile)
          return rel_obj
  
      def get_source_dir_include_args(self, target, compiler):
          curdir = target.get_subdir()
          tmppath = os.path.normpath(os.path.join(self.build_to_src, curdir))
          return compiler.get_include_args(tmppath, False)
  
      def get_build_dir_include_args(self, target, compiler):
          curdir = target.get_subdir()
          if curdir == '':
              curdir = '.'
          return compiler.get_include_args(curdir, False)
  
      def get_custom_target_dir_include_args(self, target, compiler):
          custom_target_include_dirs = []
          for i in target.get_generated_sources():
              # Generator output goes into the target private dir which is
              # already in the include paths list. Only custom targets have their
              # own target build dir.
              if not isinstance(i, (build.CustomTarget, build.CustomTargetIndex)):
                  continue
              idir = self.get_target_dir(i)
              if idir not in custom_target_include_dirs:
                  custom_target_include_dirs.append(idir)
          incs = []
          for i in custom_target_include_dirs:
              incs += compiler.get_include_args(i, False)
          return incs
  
      def _generate_single_compile(self, target, compiler, is_generated=False):
          base_proxy = backends.OptionOverrideProxy(target.option_overrides,
                                                    self.environment.coredata.base_options)
          # Create an empty commands list, and start adding arguments from
          # various sources in the order in which they must override each other
          commands = CompilerArgs(compiler)
          # Add compiler args for compiling this target derived from 'base' build
          # options passed on the command-line, in default_options, etc.
          # These have the lowest priority.
          commands += compilers.get_base_compile_args(base_proxy,
                                                      compiler)
          # The code generated by valac is usually crap and has tons of unused
          # variables and such, so disable warnings for Vala C sources.
          no_warn_args = (is_generated == 'vala')
          # Add compiler args and include paths from several sources; defaults,
          # build options, external dependencies, etc.
          commands += self.generate_basic_compiler_args(target, compiler, no_warn_args)
          # Add custom target dirs as includes automatically, but before
          # target-specific include directories.
          # XXX: Not sure if anyone actually uses this? It can cause problems in
          # situations which increase the likelihood for a header name collision,
          # such as in subprojects.
          commands += self.get_custom_target_dir_include_args(target, compiler)
          # Add include dirs from the `include_directories:` kwarg on the target
          # and from `include_directories:` of internal deps of the target.
          #
          # Target include dirs should override internal deps include dirs.
          # This is handled in BuildTarget.process_kwargs()
          #
          # Include dirs from internal deps should override include dirs from
          # external deps and must maintain the order in which they are specified.
          # Hence, we must reverse the list so that the order is preserved.
          for i in reversed(target.get_include_dirs()):
              basedir = i.get_curdir()
              for d in i.get_incdirs():
                  # Avoid superfluous '/.' at the end of paths when d is '.'
                  if d not in ('', '.'):
                      expdir = os.path.join(basedir, d)
                  else:
                      expdir = basedir
                  srctreedir = os.path.join(self.build_to_src, expdir)
                  # Add source subdir first so that the build subdir overrides it
                  sargs = compiler.get_include_args(srctreedir, i.is_system)
                  commands += sargs
                  # There may be include dirs where a build directory has not been
                  # created for some source dir. For example if someone does this:
                  #
                  # inc = include_directories('foo/bar/baz')
                  #
                  # But never subdir()s into the actual dir.
                  if os.path.isdir(os.path.join(self.environment.get_build_dir(), expdir)):
                      bargs = compiler.get_include_args(expdir, i.is_system)
                  else:
                      bargs = []
                  commands += bargs
              for d in i.get_extra_build_dirs():
                  commands += compiler.get_include_args(d, i.is_system)
          # Add per-target compile args, f.ex, `c_args : ['-DFOO']`. We set these
          # near the end since these are supposed to override everything else.
          commands += self.escape_extra_args(compiler,
                                             target.get_extra_args(compiler.get_language()))
          # Add source dir and build dir. Project-specific and target-specific
          # include paths must override per-target compile args, include paths
          # from external dependencies, internal dependencies, and from
          # per-target `include_directories:`
          #
          # We prefer headers in the build dir over the source dir since, for
          # instance, the user might have an srcdir == builddir Autotools build
          # in their source tree. Many projects that are moving to Meson have
          # both Meson and Autotools in parallel as part of the transition.
          if target.implicit_include_directories:
              commands += self.get_source_dir_include_args(target, compiler)
          if target.implicit_include_directories:
              commands += self.get_build_dir_include_args(target, compiler)
          # Finally add the private dir for the target to the include path. This
          # must override everything else and must be the final path added.
          commands += compiler.get_include_args(self.get_target_private_dir(target), False)
          return commands
  
      def generate_single_compile(self, target, outfile, src, is_generated=False, header_deps=[], order_deps=[]):
          """
          Compiles C/C++, ObjC/ObjC++, Fortran, and D sources
          """
          if isinstance(src, str) and src.endswith('.h'):
              raise AssertionError('BUG: sources should not contain headers {!r}'.format(src))
  
          compiler = get_compiler_for_source(target.compilers.values(), src)
          key = (target, compiler, is_generated)
          if key in self.target_arg_cache:
              commands = self.target_arg_cache[key]
          else:
              commands = self._generate_single_compile(target, compiler, is_generated)
              self.target_arg_cache[key] = commands
          commands = CompilerArgs(commands.compiler, commands)
  
          build_dir = self.environment.get_build_dir()
          if isinstance(src, File):
              rel_src = src.rel_to_builddir(self.build_to_src)
              if os.path.isabs(rel_src):
                  # Source files may not be from the source directory if they originate in source-only libraries,
                  # so we can't assert that the absolute path is anywhere in particular.
                  if src.is_built:
                      assert rel_src.startswith(build_dir)
                      rel_src = rel_src[len(build_dir) + 1:]
          elif is_generated:
              raise AssertionError('BUG: broken generated source file handling for {!r}'.format(src))
          else:
              raise InvalidArguments('Invalid source type: {!r}'.format(src))
          obj_basename = self.object_filename_from_source(target, src, self.is_unity(target))
          rel_obj = os.path.join(self.get_target_private_dir(target), obj_basename)
          dep_file = compiler.depfile_for_object(rel_obj)
  
          # Add MSVC debug file generation compile flags: /Fd /FS
          commands += self.get_compile_debugfile_args(compiler, target, rel_obj)
  
          # PCH handling
          if self.environment.coredata.base_options.get('b_pch', False):
              commands += self.get_pch_include_args(compiler, target)
              pchlist = target.get_pch(compiler.language)
          else:
              pchlist = []
          if not pchlist:
              pch_dep = []
          elif compiler.id == 'intel':
              pch_dep = []
          else:
              arr = []
              i = os.path.join(self.get_target_private_dir(target), compiler.get_pch_name(pchlist[0]))
              arr.append(i)
              pch_dep = arr
  
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          compiler_name = '%s%s_COMPILER' % (compiler.get_language(), crstr)
          extra_deps = []
          if compiler.get_language() == 'fortran':
              # Can't read source file to scan for deps if it's generated later
              # at build-time. Skip scanning for deps, and just set the module
              # outdir argument instead.
              # https://github.com/mesonbuild/meson/issues/1348
              if not is_generated:
                  abs_src = os.path.join(build_dir, rel_src)
                  extra_deps += self.get_fortran_deps(compiler, abs_src, target)
              # Dependency hack. Remove once multiple outputs in Ninja is fixed:
              # https://groups.google.com/forum/#!topic/ninja-build/j-2RfBIOd_8
              for modname, srcfile in self.fortran_deps[target.get_basename()].items():
                  modfile = os.path.join(self.get_target_private_dir(target),
                                         compiler.module_name_to_filename(modname))
                  if srcfile == src:
                      depelem = NinjaBuildElement(self.all_outputs, modfile, 'FORTRAN_DEP_HACK', rel_obj)
                      depelem.write(outfile)
              commands += compiler.get_module_outdir_args(self.get_target_private_dir(target))
  
          if compiler.language == 'd':
              commands += compiler.get_feature_args(target.d_features, self.build_to_src)
  
          element = NinjaBuildElement(self.all_outputs, rel_obj, compiler_name, rel_src)
          for d in header_deps:
              if isinstance(d, File):
                  d = d.rel_to_builddir(self.build_to_src)
              elif not self.has_dir_part(d):
                  d = os.path.join(self.get_target_private_dir(target), d)
              element.add_dep(d)
          for d in extra_deps:
              element.add_dep(d)
          for d in order_deps:
              if isinstance(d, File):
                  d = d.rel_to_builddir(self.build_to_src)
              elif not self.has_dir_part(d):
                  d = os.path.join(self.get_target_private_dir(target), d)
              element.add_orderdep(d)
          element.add_orderdep(pch_dep)
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          for i in self.get_fortran_orderdeps(target, compiler):
              element.add_orderdep(i)
          element.add_item('DEPFILE', dep_file)
          element.add_item('ARGS', commands)
          element.write(outfile)
          return rel_obj
  
      def has_dir_part(self, fname):
          # FIXME FIXME: The usage of this is a terrible and unreliable hack
          if isinstance(fname, File):
              return fname.subdir != ''
          return has_path_sep(fname)
  
      # Fortran is a bit weird (again). When you link against a library, just compiling a source file
      # requires the mod files that are output when single files are built. To do this right we would need to
      # scan all inputs and write out explicit deps for each file. That is stoo slow and too much effort so
      # instead just have an ordered dependency on the library. This ensures all required mod files are created.
      # The real deps are then detected via dep file generation from the compiler. This breaks on compilers that
      # produce incorrect dep files but such is life.
      def get_fortran_orderdeps(self, target, compiler):
          if compiler.language != 'fortran':
              return []
          return [os.path.join(self.get_target_dir(lt), lt.get_filename()) for lt in target.link_targets]
  
      def generate_msvc_pch_command(self, target, compiler, pch):
          if len(pch) != 2:
              raise MesonException('MSVC requires one header and one source to produce precompiled headers.')
          header = pch[0]
          source = pch[1]
          pchname = compiler.get_pch_name(header)
          dst = os.path.join(self.get_target_private_dir(target), pchname)
  
          commands = []
          commands += self.generate_basic_compiler_args(target, compiler)
          just_name = os.path.basename(header)
          (objname, pch_args) = compiler.gen_pch_args(just_name, source, dst)
          commands += pch_args
          commands += self.get_compile_debugfile_args(compiler, target, objname)
          dep = dst + '.' + compiler.get_depfile_suffix()
          return commands, dep, dst, [objname]
  
      def generate_gcc_pch_command(self, target, compiler, pch):
          commands = self._generate_single_compile(target, compiler)
          dst = os.path.join(self.get_target_private_dir(target),
                             os.path.basename(pch) + '.' + compiler.get_pch_suffix())
          dep = dst + '.' + compiler.get_depfile_suffix()
          return commands, dep, dst, []  # Gcc does not create an object file during pch generation.
  
      def generate_pch(self, target, outfile):
          cstr = ''
          pch_objects = []
          if target.is_cross:
              cstr = '_CROSS'
          for lang in ['c', 'cpp']:
              pch = target.get_pch(lang)
              if not pch:
                  continue
              if not has_path_sep(pch[0]) or not has_path_sep(pch[-1]):
                  msg = 'Precompiled header of {!r} must not be in the same ' \
                        'directory as source, please put it in a subdirectory.' \
                        ''.format(target.get_basename())
                  raise InvalidArguments(msg)
              compiler = target.compilers[lang]
              if compiler.id == 'msvc':
                  src = os.path.join(self.build_to_src, target.get_source_subdir(), pch[-1])
                  (commands, dep, dst, objs) = self.generate_msvc_pch_command(target, compiler, pch)
                  extradep = os.path.join(self.build_to_src, target.get_source_subdir(), pch[0])
              elif compiler.id == 'intel':
                  # Intel generates on target generation
                  continue
              else:
                  src = os.path.join(self.build_to_src, target.get_source_subdir(), pch[0])
                  (commands, dep, dst, objs) = self.generate_gcc_pch_command(target, compiler, pch[0])
                  extradep = None
              pch_objects += objs
              rulename = compiler.get_language() + cstr + '_PCH'
              elem = NinjaBuildElement(self.all_outputs, dst, rulename, src)
              if extradep is not None:
                  elem.add_dep(extradep)
              elem.add_item('ARGS', commands)
              elem.add_item('DEPFILE', dep)
              elem.write(outfile)
          return pch_objects
  
      def generate_shsym(self, outfile, target):
          target_name = self.get_target_filename(target)
          targetdir = self.get_target_private_dir(target)
          symname = os.path.join(targetdir, target_name + '.symbols')
          elem = NinjaBuildElement(self.all_outputs, symname, 'SHSYM', target_name)
          if self.environment.is_cross_build() and self.environment.cross_info.need_cross_compiler():
              elem.add_item('CROSS', '--cross-host=' + self.environment.cross_info.config['host_machine']['system'])
          elem.write(outfile)
  
      def get_cross_stdlib_link_args(self, target, linker):
          if isinstance(target, build.StaticLibrary) or not target.is_cross:
              return []
          if not self.environment.cross_info.has_stdlib(linker.language):
              return []
          return linker.get_no_stdlib_link_args()
  
      def get_target_type_link_args(self, target, linker):
          abspath = os.path.join(self.environment.get_build_dir(), target.subdir)
          commands = []
          if isinstance(target, build.Executable):
              # Currently only used with the Swift compiler to add '-emit-executable'
              commands += linker.get_std_exe_link_args()
              # If gui_app, and that's significant on this platform
              if target.gui_app and hasattr(linker, 'get_gui_app_args'):
                  commands += linker.get_gui_app_args()
              # If export_dynamic, add the appropriate linker arguments
              if target.export_dynamic:
                  commands += linker.gen_export_dynamic_link_args(self.environment)
              # If implib, and that's significant on this platform (i.e. Windows using either GCC or Visual Studio)
              if target.import_filename:
                  commands += linker.gen_import_library_args(os.path.join(self.get_target_dir(target), target.import_filename))
          elif isinstance(target, build.SharedLibrary):
              if isinstance(target, build.SharedModule):
                  commands += linker.get_std_shared_module_link_args()
              else:
                  commands += linker.get_std_shared_lib_link_args()
              # All shared libraries are PIC
              commands += linker.get_pic_args()
              # Add -Wl,-soname arguments on Linux, -install_name on OS X
              commands += linker.get_soname_args(target.prefix, target.name, target.suffix,
                                                 abspath, target.soversion,
                                                 isinstance(target, build.SharedModule))
              # This is only visited when building for Windows using either GCC or Visual Studio
              if target.vs_module_defs and hasattr(linker, 'gen_vs_module_defs_args'):
                  commands += linker.gen_vs_module_defs_args(target.vs_module_defs.rel_to_builddir(self.build_to_src))
              # This is only visited when building for Windows using either GCC or Visual Studio
              if target.import_filename:
                  commands += linker.gen_import_library_args(os.path.join(self.get_target_dir(target), target.import_filename))
          elif isinstance(target, build.StaticLibrary):
              commands += linker.get_std_link_args()
          else:
              raise RuntimeError('Unknown build target type.')
          return commands
  
      def get_link_whole_args(self, linker, target):
          target_args = self.build_target_link_arguments(linker, target.link_whole_targets)
          return linker.get_link_whole_for(target_args) if len(target_args) else []
  
      def generate_link(self, target, outfile, outname, obj_list, linker, extra_args=[]):
          if isinstance(target, build.StaticLibrary):
              linker_base = 'STATIC'
          else:
              linker_base = linker.get_language() # Fixme.
          if isinstance(target, build.SharedLibrary):
              self.generate_shsym(outfile, target)
          crstr = ''
          if target.is_cross:
              crstr = '_CROSS'
          linker_rule = linker_base + crstr + '_LINKER'
  
          # Create an empty commands list, and start adding link arguments from
          # various sources in the order in which they must override each other
          # starting from hard-coded defaults followed by build options and so on.
          #
          # Once all the linker options have been passed, we will start passing
          # libraries and library paths from internal and external sources.
          commands = CompilerArgs(linker)
          # First, the trivial ones that are impossible to override.
          #
          # Add linker args for linking this target derived from 'base' build
          # options passed on the command-line, in default_options, etc.
          # These have the lowest priority.
          if not isinstance(target, build.StaticLibrary):
              commands += compilers.get_base_link_args(self.environment.coredata.base_options,
                                                       linker,
                                                       isinstance(target, build.SharedModule))
          # Add -nostdlib if needed; can't be overridden
          commands += self.get_cross_stdlib_link_args(target, linker)
          # Add things like /NOLOGO; usually can't be overridden
          commands += linker.get_linker_always_args()
          # Add buildtype linker args: optimization level, etc.
          commands += linker.get_buildtype_linker_args(self.get_option_for_target('buildtype', target))
          # Add /DEBUG and the pdb filename when using MSVC
          commands += self.get_link_debugfile_args(linker, target, outname)
          # Add link args specific to this BuildTarget type, such as soname args,
          # PIC, import library generation, etc.
          commands += self.get_target_type_link_args(target, linker)
          # Archives that are copied wholesale in the result. Must be before any
          # other link targets so missing symbols from whole archives are found in those.
          if not isinstance(target, build.StaticLibrary):
              commands += self.get_link_whole_args(linker, target)
  
          if not isinstance(target, build.StaticLibrary):
              # Add link args added using add_project_link_arguments()
              commands += self.build.get_project_link_args(linker, target.subproject)
              # Add link args added using add_global_link_arguments()
              # These override per-project link arguments
              commands += self.build.get_global_link_args(linker)
              if not target.is_cross:
                  # Link args added from the env: LDFLAGS. We want these to
                  # override all the defaults but not the per-target link args.
                  commands += self.environment.coredata.external_link_args[linker.get_language()]
  
          # Now we will add libraries and library paths from various sources
  
          # Add link args to link to all internal libraries (link_with:) and
          # internal dependencies needed by this target.
          if linker_base == 'STATIC':
              # Link arguments of static libraries are not put in the command
              # line of the library. They are instead appended to the command
              # line where the static library is used.
              dependencies = []
          else:
              dependencies = target.get_dependencies()
          commands += self.build_target_link_arguments(linker, dependencies)
          # For 'automagic' deps: Boost and GTest. Also dependency('threads').
          # pkg-config puts the thread flags itself via `Cflags:`
          for d in target.external_deps:
              if d.need_threads():
                  commands += linker.thread_link_flags(self.environment)
          # Only non-static built targets need link args and link dependencies
          if not isinstance(target, build.StaticLibrary):
              commands += target.link_args
              # External deps must be last because target link libraries may depend on them.
              for dep in target.get_external_deps():
                  # Extend without reordering or de-dup to preserve `-L -l` sets
                  # https://github.com/mesonbuild/meson/issues/1718
                  commands.extend_direct(dep.get_link_args())
              for d in target.get_dependencies():
                  if isinstance(d, build.StaticLibrary):
                      for dep in d.get_external_deps():
                          commands.extend_direct(dep.get_link_args())
          # Add link args for c_* or cpp_* build options. Currently this only
          # adds c_winlibs and cpp_winlibs when building for Windows. This needs
          # to be after all internal and external libraries so that unresolved
          # symbols from those can be found here. This is needed when the
          # *_winlibs that we want to link to are static mingw64 libraries.
          commands += linker.get_option_link_args(self.environment.coredata.compiler_options)
          # Set runtime-paths so we can run executables without needing to set
          # LD_LIBRARY_PATH, etc in the environment. Doesn't work on Windows.
          if has_path_sep(target.name):
              # Target names really should not have slashes in them, but
              # unfortunately we did not check for that and some downstream projects
              # now have them. Once slashes are forbidden, remove this bit.
              target_slashname_workaround_dir = os.path.join(
                  os.path.dirname(target.name),
                  self.get_target_dir(target))
          else:
              target_slashname_workaround_dir = self.get_target_dir(target)
          commands += linker.build_rpath_args(self.environment.get_build_dir(),
                                              target_slashname_workaround_dir,
                                              self.determine_rpath_dirs(target),
                                              target.build_rpath,
                                              target.install_rpath)
          # Add libraries generated by custom targets
          custom_target_libraries = self.get_custom_target_provided_libraries(target)
          commands += extra_args
          commands += custom_target_libraries
          # Convert from GCC-style link argument naming to the naming used by the
          # current compiler.
          commands = commands.to_native()
          dep_targets = [self.get_dependency_filename(t) for t in dependencies]
          dep_targets.extend([self.get_dependency_filename(t)
                              for t in target.link_depends])
          elem = NinjaBuildElement(self.all_outputs, outname, linker_rule, obj_list)
          elem.add_dep(dep_targets + custom_target_libraries)
          elem.add_item('LINK_ARGS', commands)
          return elem
  
      def get_dependency_filename(self, t):
          if isinstance(t, build.SharedLibrary):
              return os.path.join(self.get_target_private_dir(t), self.get_target_filename(t) + '.symbols')
          elif isinstance(t, mesonlib.File):
              if t.is_built:
                  return t.relative_name()
              else:
                  return t.absolute_path(self.environment.get_source_dir(),
                                         self.environment.get_build_dir())
          return self.get_target_filename(t)
  
      def generate_shlib_aliases(self, target, outdir):
          aliases = target.get_aliases()
          for alias, to in aliases.items():
              aliasfile = os.path.join(self.environment.get_build_dir(), outdir, alias)
              try:
                  os.remove(aliasfile)
              except Exception:
                  pass
              try:
                  os.symlink(to, aliasfile)
              except NotImplementedError:
                  mlog.debug("Library versioning disabled because symlinks are not supported.")
              except OSError:
                  mlog.debug("Library versioning disabled because we do not have symlink creation privileges.")
  
      def generate_custom_target_clean(self, outfile, trees):
          e = NinjaBuildElement(self.all_outputs, 'meson-clean-ctlist', 'CUSTOM_COMMAND', 'PHONY')
          d = CleanTrees(self.environment.get_build_dir(), trees)
          d_file = os.path.join(self.environment.get_scratch_dir(), 'cleantrees.dat')
          e.add_item('COMMAND', self.environment.get_build_command() + ['--internal', 'cleantrees', d_file])
          e.add_item('description', 'Cleaning custom target directories.')
          e.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-ctlist', outfile)
          # Write out the data file passed to the script
          with open(d_file, 'wb') as ofile:
              pickle.dump(d, ofile)
          return 'clean-ctlist'
  
      def generate_gcov_clean(self, outfile):
          gcno_elem = NinjaBuildElement(self.all_outputs, 'meson-clean-gcno', 'CUSTOM_COMMAND', 'PHONY')
          script_root = self.environment.get_script_dir()
          clean_script = os.path.join(script_root, 'delwithsuffix.py')
          gcno_elem.add_item('COMMAND', mesonlib.python_command + [clean_script, '.', 'gcno'])
          gcno_elem.add_item('description', 'Deleting gcno files.')
          gcno_elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-gcno', outfile)
  
          gcda_elem = NinjaBuildElement(self.all_outputs, 'meson-clean-gcda', 'CUSTOM_COMMAND', 'PHONY')
          script_root = self.environment.get_script_dir()
          clean_script = os.path.join(script_root, 'delwithsuffix.py')
          gcda_elem.add_item('COMMAND', mesonlib.python_command + [clean_script, '.', 'gcda'])
          gcda_elem.add_item('description', 'Deleting gcda files.')
          gcda_elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-clean-gcda', outfile)
  
      def get_user_option_args(self):
          cmds = []
          for (k, v) in self.environment.coredata.user_options.items():
              cmds.append('-D' + k + '=' + (v.value if isinstance(v.value, str) else str(v.value).lower()))
          # The order of these arguments must be the same between runs of Meson
          # to ensure reproducible output. The order we pass them shouldn't
          # affect behavior in any other way.
          return sorted(cmds)
  
      def generate_dist(self, outfile):
          elem = NinjaBuildElement(self.all_outputs, 'meson-dist', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('DESC', 'Creating source packages')
          elem.add_item('COMMAND', self.environment.get_build_command() + [
              '--internal', 'dist',
              self.environment.source_dir,
              self.environment.build_dir,
          ] + self.environment.get_build_command())
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-dist', outfile)
  
      # For things like scan-build and other helper tools we might have.
      def generate_utils(self, outfile):
          cmd = self.environment.get_build_command() + \
              ['--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir] + \
              self.environment.get_build_command() + self.get_user_option_args()
          elem = NinjaBuildElement(self.all_outputs, 'meson-scan-build', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-scan-build', outfile)
          cmd = self.environment.get_build_command() + ['--internal', 'uninstall']
          elem = NinjaBuildElement(self.all_outputs, 'meson-uninstall', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          # Alias that runs the target defined above
          self.create_target_alias('meson-uninstall', outfile)
  
      def generate_ending(self, outfile):
          targetlist = []
          for t in self.get_build_by_default_targets().values():
              # Add the first output of each target to the 'all' target so that
              # they are all built
              targetlist.append(os.path.join(self.get_target_dir(t), t.get_outputs()[0]))
  
          elem = NinjaBuildElement(self.all_outputs, 'all', 'phony', targetlist)
          elem.write(outfile)
  
          default = 'default all\n\n'
          outfile.write(default)
  
          elem = NinjaBuildElement(self.all_outputs, 'meson-clean', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', [self.ninja_command, '-t', 'clean'])
          elem.add_item('description', 'Cleaning.')
          # Alias that runs the above-defined meson-clean target
          self.create_target_alias('meson-clean', outfile)
  
          # If we have custom targets in this project, add all their outputs to
          # the list that is passed to the `cleantrees.py` script. The script
          # will manually delete all custom_target outputs that are directories
          # instead of files. This is needed because on platforms other than
          # Windows, Ninja only deletes directories while cleaning if they are
          # empty. https://github.com/mesonbuild/meson/issues/1220
          ctlist = []
          for t in self.build.get_targets().values():
              if isinstance(t, build.CustomTarget):
                  # Create a list of all custom target outputs
                  for o in t.get_outputs():
                      ctlist.append(os.path.join(self.get_target_dir(t), o))
          if ctlist:
              elem.add_dep(self.generate_custom_target_clean(outfile, ctlist))
  
          if 'b_coverage' in self.environment.coredata.base_options and \
             self.environment.coredata.base_options['b_coverage'].value:
              self.generate_gcov_clean(outfile)
              elem.add_dep('clean-gcda')
              elem.add_dep('clean-gcno')
          elem.write(outfile)
  
          deps = self.get_regen_filelist()
          elem = NinjaBuildElement(self.all_outputs, 'build.ninja', 'REGENERATE_BUILD', deps)
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
          elem = NinjaBuildElement(self.all_outputs, 'reconfigure', 'REGENERATE_BUILD', 'PHONY')
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
          elem = NinjaBuildElement(self.all_outputs, deps, 'phony', '')
          elem.write(outfile)
  
  def load(build_dir):
      filename = os.path.join(build_dir, 'meson-private', 'install.dat')
      with open(filename, 'rb') as f:
          obj = pickle.load(f)
      return obj
  
files: mesonbuild/backend/ninjabackend.py
files: # Copyright 2012-2017 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.
  
  import contextlib, os.path, re, tempfile
  import subprocess
  
  from ..linkers import StaticLinker
  from .. import coredata
  from .. import mlog
  from .. import mesonlib
  from ..mesonlib import EnvironmentException, MesonException, version_compare, Popen_safe
  
  """This file contains the data files of all compilers Meson knows
  about. To support a new compiler, add its information below.
  Also add corresponding autodetection code in environment.py."""
  
  header_suffixes = ('h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di')
  obj_suffixes = ('o', 'obj', 'res')
  lib_suffixes = ('a', 'lib', 'dll', 'dylib', 'so')
  # Mapping of language to suffixes of files that should always be in that language
  # This means we can't include .h headers here since they could be C, C++, ObjC, etc.
  lang_suffixes = {
      'c': ('c',),
      'cpp': ('cpp', 'cc', 'cxx', 'c++', 'hh', 'hpp', 'ipp', 'hxx'),
      # f90, f95, f03, f08 are for free-form fortran ('f90' recommended)
      # f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended)
      'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'),
      'd': ('d', 'di'),
      'objc': ('m',),
      'objcpp': ('mm',),
      'rust': ('rs',),
      'vala': ('vala', 'vapi', 'gs'),
      'cs': ('cs',),
      'swift': ('swift',),
      'java': ('java',),
  }
  cpp_suffixes = lang_suffixes['cpp'] + ('h',)
  c_suffixes = lang_suffixes['c'] + ('h',)
  # List of languages that can be linked with C code directly by the linker
  # used in build.py:process_compilers() and build.py:get_dynamic_linker()
  clike_langs = ('d', 'objcpp', 'cpp', 'objc', 'c', 'fortran',)
  clike_suffixes = ()
  for _l in clike_langs:
      clike_suffixes += lang_suffixes[_l]
  clike_suffixes += ('h', 'll', 's')
  
  # XXX: Use this in is_library()?
  soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  
  # All these are only for C-like languages; see `clike_langs` above.
  
  def sort_clike(lang):
      '''
      Sorting function to sort the list of languages according to
      reversed(compilers.clike_langs) and append the unknown langs in the end.
      The purpose is to prefer C over C++ for files that can be compiled by
      both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc.
      '''
      if lang not in clike_langs:
          return 1
      return -clike_langs.index(lang)
  
  def is_header(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in header_suffixes
  
  def is_source(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1].lower()
      return suffix in clike_suffixes
  
  def is_assembly(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      return fname.split('.')[-1].lower() == 's'
  
  def is_llvm_ir(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      return fname.split('.')[-1] == 'll'
  
  def is_object(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in obj_suffixes
  
  def is_library(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in lib_suffixes
  
  gnulike_buildtype_args = {'plain': [],
                            # -O0 is passed for improved debugging information with gcc
                            # See https://github.com/mesonbuild/meson/pull/509
                            'debug': ['-O0', '-g'],
                            'debugoptimized': ['-O2', '-g'],
                            'release': ['-O3'],
                            'minsize': ['-Os', '-g']}
  
  msvc_buildtype_args = {'plain': [],
                         'debug': ["/MDd", "/ZI", "/Ob0", "/Od", "/RTC1"],
                         'debugoptimized': ["/MD", "/Zi", "/O2", "/Ob1"],
                         'release': ["/MD", "/O2", "/Ob2"],
                         'minsize': ["/MD", "/Zi", "/Os", "/Ob1"],
                         }
  
  apple_buildtype_linker_args = {'plain': [],
                                 'debug': [],
                                 'debugoptimized': [],
                                 'release': [],
                                 'minsize': [],
                                 }
  
  gnulike_buildtype_linker_args = {'plain': [],
                                   'debug': [],
                                   'debugoptimized': [],
                                   'release': ['-Wl,-O1'],
                                   'minsize': [],
                                   }
  
  msvc_buildtype_linker_args = {'plain': [],
                                'debug': [],
                                'debugoptimized': [],
                                # The otherwise implicit REF and ICF linker
                                # optimisations are disabled by /DEBUG.
                                # REF implies ICF.
                                'release': ['/OPT:REF'],
                                'minsize': ['/INCREMENTAL:NO', '/OPT:REF'],
                                }
  
  java_buildtype_args = {'plain': [],
                         'debug': ['-g'],
                         'debugoptimized': ['-g'],
                         'release': [],
                         'minsize': [],
                         }
  
  rust_buildtype_args = {'plain': [],
                         'debug': ['-C', 'debuginfo=2'],
                         'debugoptimized': ['-C', 'debuginfo=2', '-C', 'opt-level=2'],
                         'release': ['-C', 'opt-level=3'],
                         'minsize': [], # In a future release: ['-C', 'opt-level=s'],
                         }
  
  d_gdc_buildtype_args = {'plain': [],
                          'debug': ['-g', '-O0'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O3', '-frelease'],
                          'minsize': [],
                          }
  
  d_ldc_buildtype_args = {'plain': [],
                          'debug': ['-g', '-O0'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O3', '-release'],
                          'minsize': [],
                          }
  
  d_dmd_buildtype_args = {'plain': [],
                          'debug': ['-g'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O', '-release'],
                          'minsize': [],
                          }
  
  mono_buildtype_args = {'plain': [],
                         'debug': ['-debug'],
                         'debugoptimized': ['-debug', '-optimize+'],
                         'release': ['-optimize+'],
                         'minsize': [],
                         }
  
  swift_buildtype_args = {'plain': [],
                          'debug': ['-g'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O'],
                          'minsize': [],
                          }
  
  gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32',
                 '-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32']
  
  msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib',
                  'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib',
                  'uuid.lib', 'comdlg32.lib', 'advapi32.lib']
  
  gnu_color_args = {'auto': ['-fdiagnostics-color=auto'],
                    'always': ['-fdiagnostics-color=always'],
                    'never': ['-fdiagnostics-color=never'],
                    }
  
  clang_color_args = {'auto': ['-Xclang', '-fcolor-diagnostics'],
                      'always': ['-Xclang', '-fcolor-diagnostics'],
                      'never': ['-Xclang', '-fno-color-diagnostics'],
                      }
  
  base_options = {'b_pch': coredata.UserBooleanOption('b_pch', 'Use precompiled headers', True),
                  'b_lto': coredata.UserBooleanOption('b_lto', 'Use link time optimization', False),
                  'b_sanitize': coredata.UserComboOption('b_sanitize',
                                                         'Code sanitizer to use',
                                                         ['none', 'address', 'thread', 'undefined', 'memory', 'address,undefined'],
                                                         'none'),
                  'b_lundef': coredata.UserBooleanOption('b_lundef', 'Use -Wl,--no-undefined when linking', True),
                  'b_asneeded': coredata.UserBooleanOption('b_asneeded', 'Use -Wl,--as-needed when linking', True),
                  'b_pgo': coredata.UserComboOption('b_pgo', 'Use profile guided optimization',
                                                    ['off', 'generate', 'use'],
                                                    'off'),
                  'b_coverage': coredata.UserBooleanOption('b_coverage',
                                                           'Enable coverage tracking.',
                                                           False),
                  'b_colorout': coredata.UserComboOption('b_colorout', 'Use colored output',
                                                         ['auto', 'always', 'never'],
                                                         'always'),
                  'b_ndebug': coredata.UserComboOption('b_ndebug', 'Disable asserts',
                                                       ['true', 'false', 'if-release'], 'false'),
                  'b_staticpic': coredata.UserBooleanOption('b_staticpic',
                                                            'Build static libraries as position independent',
                                                            True),
                  }
  
  gnulike_instruction_set_args = {'mmx': ['-mmmx'],
                                  'sse': ['-msse'],
                                  'sse2': ['-msse2'],
                                  'sse3': ['-msse3'],
                                  'ssse3': ['-mssse3'],
                                  'sse41': ['-msse4.1'],
                                  'sse42': ['-msse4.2'],
                                  'avx': ['-mavx'],
                                  'avx2': ['-mavx2'],
                                  'neon': ['-mfpu=neon'],
                                  }
  
  vs32_instruction_set_args = {'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMX
                               'sse': ['/arch:SSE'],
                               'sse2': ['/arch:SSE2'],
                               'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.
                               'sse41': ['/arch:AVX'],
                               'sse42': ['/arch:AVX'],
                               'avx': ['/arch:AVX'],
                               'avx2': ['/arch:AVX2'],
                               'neon': None,
                               }
  
  # The 64 bit compiler defaults to /arch:avx.
  vs64_instruction_set_args = {'mmx': ['/arch:AVX'],
                               'sse': ['/arch:AVX'],
                               'sse2': ['/arch:AVX'],
                               'sse3': ['/arch:AVX'],
                               'ssse3': ['/arch:AVX'],
                               'sse41': ['/arch:AVX'],
                               'sse42': ['/arch:AVX'],
                               'avx': ['/arch:AVX'],
                               'avx2': ['/arch:AVX2'],
                               'neon': None,
                               }
  
  
  def sanitizer_compile_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      if 'address' in value: # For -fsanitize=address,undefined
          args.append('-fno-omit-frame-pointer')
      return args
  
  def sanitizer_link_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      return args
  
  def get_base_compile_args(options, compiler):
      args = []
      # FIXME, gcc/clang specific.
      try:
          if options['b_lto'].value:
              args.append('-flto')
      except KeyError:
          pass
      try:
          args += compiler.get_colorout_args(options['b_colorout'].value)
      except KeyError:
          pass
      try:
          args += sanitizer_compile_args(options['b_sanitize'].value)
      except KeyError:
          pass
      try:
          pgo_val = options['b_pgo'].value
          if pgo_val == 'generate':
              args.append('-fprofile-generate')
          elif pgo_val == 'use':
              args.append('-fprofile-use')
      except KeyError:
          pass
      try:
          if options['b_coverage'].value:
              args += compiler.get_coverage_args()
      except KeyError:
          pass
      try:
          if (options['b_ndebug'].value == 'true' or
                  (options['b_ndebug'].value == 'if-release' and
                   options['buildtype'].value == 'release')):
              args += ['-DNDEBUG']
      except KeyError:
          pass
      return args
  
  def get_base_link_args(options, linker, is_shared_module):
      args = []
      # FIXME, gcc/clang specific.
      try:
          if options['b_lto'].value:
              args.append('-flto')
      except KeyError:
          pass
      try:
          args += sanitizer_link_args(options['b_sanitize'].value)
      except KeyError:
          pass
      try:
          pgo_val = options['b_pgo'].value
          if pgo_val == 'generate':
              args.append('-fprofile-generate')
          elif pgo_val == 'use':
              args.append('-fprofile-use')
      except KeyError:
          pass
      try:
          if not is_shared_module and 'b_lundef' in linker.base_options and options['b_lundef'].value:
              args.append('-Wl,--no-undefined')
      except KeyError:
          pass
      try:
          if 'b_asneeded' in linker.base_options and options['b_asneeded'].value:
              args.append(linker.get_asneeded_args())
      except KeyError:
          pass
      try:
          if options['b_coverage'].value:
              args += linker.get_coverage_link_args()
      except KeyError:
          pass
      return args
  
  class CrossNoRunException(MesonException):
      pass
  
  class RunResult:
      def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'):
          self.compiled = compiled
          self.returncode = returncode
          self.stdout = stdout
          self.stderr = stderr
  
  class CompilerArgs(list):
      '''
      Class derived from list() that manages a list of compiler arguments. Should
      be used while constructing compiler arguments from various sources. Can be
      operated with ordinary lists, so this does not need to be used everywhere.
  
      All arguments must be inserted and stored in GCC-style (-lfoo, -Idir, etc)
      and can converted to the native type of each compiler by using the
      .to_native() method to which you must pass an instance of the compiler or
      the compiler class.
  
      New arguments added to this class (either with .append(), .extend(), or +=)
      are added in a way that ensures that they override previous arguments.
      For example:
  
      >>> a = ['-Lfoo', '-lbar']
      >>> a += ['-Lpho', '-lbaz']
      >>> print(a)
      ['-Lpho', '-Lfoo', '-lbar', '-lbaz']
  
      Arguments will also be de-duped if they can be de-duped safely.
  
      Note that because of all this, this class is not commutative and does not
      preserve the order of arguments if it is safe to not. For example:
      >>> ['-Ifoo', '-Ibar'] + ['-Ifez', '-Ibaz', '-Werror']
      ['-Ifez', '-Ibaz', '-Ifoo', '-Ibar', '-Werror']
      >>> ['-Ifez', '-Ibaz', '-Werror'] + ['-Ifoo', '-Ibar']
      ['-Ifoo', '-Ibar', '-Ifez', '-Ibaz', '-Werror']
  
      '''
      # NOTE: currently this class is only for C-like compilers, but it can be
      # extended to other languages easily. Just move the following to the
      # compiler class and initialize when self.compiler is set.
  
      # Arg prefixes that override by prepending instead of appending
      prepend_prefixes = ('-I', '-L')
      # Arg prefixes and args that must be de-duped by returning 2
      dedup2_prefixes = ('-I', '-L', '-D', '-U')
      dedup2_suffixes = ()
      dedup2_args = ()
      # Arg prefixes and args that must be de-duped by returning 1
      dedup1_prefixes = ('-l',)
      dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a')
      # Match a .so of the form path/to/libfoo.so.0.1.0
      # Only UNIX shared libraries require this. Others have a fixed extension.
      dedup1_regex = re.compile(r'([\/\\]|\A)lib.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
      dedup1_args = ('-c', '-S', '-E', '-pipe', '-pthread')
      compiler = None
  
      def _check_args(self, args):
          cargs = []
          if len(args) > 2:
              raise TypeError("CompilerArgs() only accepts at most 2 arguments: "
                              "The compiler, and optionally an initial list")
          elif not args:
              return cargs
          elif len(args) == 1:
              if isinstance(args[0], (Compiler, StaticLinker)):
                  self.compiler = args[0]
              else:
                  raise TypeError("you must pass a Compiler instance as one of "
                                  "the arguments")
          elif len(args) == 2:
              if isinstance(args[0], (Compiler, StaticLinker)):
                  self.compiler = args[0]
                  cargs = args[1]
              elif isinstance(args[1], (Compiler, StaticLinker)):
                  cargs = args[0]
                  self.compiler = args[1]
              else:
                  raise TypeError("you must pass a Compiler instance as one of "
                                  "the two arguments")
          else:
              raise AssertionError('Not reached')
          return cargs
  
      def __init__(self, *args):
          super().__init__(self._check_args(args))
  
      @classmethod
      def _can_dedup(cls, arg):
          '''
          Returns whether the argument can be safely de-duped. This is dependent
          on three things:
  
          a) Whether an argument can be 'overridden' by a later argument.  For
             example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
             can safely remove the previous occurrence and add a new one. The same
             is true for include paths and library paths with -I and -L. For
             these we return `2`. See `dedup2_prefixes` and `dedup2_args`.
          b) Arguments that once specified cannot be undone, such as `-c` or
             `-pipe`. New instances of these can be completely skipped. For these
             we return `1`. See `dedup1_prefixes` and `dedup1_args`.
          c) Whether it matters where or how many times on the command-line
             a particular argument is present. This can matter for symbol
             resolution in static or shared libraries, so we cannot de-dup or
             reorder them. For these we return `0`. This is the default.
  
          In addition to these, we handle library arguments specially.
          With GNU ld, we surround library arguments with -Wl,--start/end-group
          to recursively search for symbols in the libraries. This is not needed
          with other linkers.
          '''
  
          # A standalone argument must never be deduplicated because it is
          # defined by what comes _after_ it. Thus dedupping this:
          # -D FOO -D BAR
          # would yield either
          # -D FOO BAR
          # or
          # FOO -D BAR
          # both of which are invalid.
          if arg in cls.dedup2_prefixes:
              return 0
          if arg in cls.dedup2_args or \
             arg.startswith(cls.dedup2_prefixes) or \
             arg.endswith(cls.dedup2_suffixes):
              return 2
          if arg in cls.dedup1_args or \
             arg.startswith(cls.dedup1_prefixes) or \
             arg.endswith(cls.dedup1_suffixes) or \
             re.search(cls.dedup1_regex, arg):
              return 1
          return 0
  
      @classmethod
      def _should_prepend(cls, arg):
          if arg.startswith(cls.prepend_prefixes):
              return True
          return False
  
      def to_native(self):
          # Check if we need to add --start/end-group for circular dependencies
          # between static libraries, and for recursively searching for symbols
          # needed by static libraries that are provided by object files or
          # shared libraries.
          if get_compiler_uses_gnuld(self.compiler):
              global soregex
              group_start = -1
              for each in self:
                  if not each.startswith('-l') and not each.endswith('.a') and \
                     not soregex.match(each):
                      continue
                  i = self.index(each)
                  if group_start < 0:
                      # First occurrence of a library
                      group_start = i
              if group_start >= 0:
                  # Last occurrence of a library
                  self.insert(i + 1, '-Wl,--end-group')
                  self.insert(group_start, '-Wl,--start-group')
          return self.compiler.unix_args_to_native(self)
  
      def append_direct(self, arg):
          '''
          Append the specified argument without any reordering or de-dup
          '''
          super().append(arg)
  
      def extend_direct(self, iterable):
          '''
          Extend using the elements in the specified iterable without any
          reordering or de-dup
          '''
          super().extend(iterable)
  
      def __add__(self, args):
          new = CompilerArgs(self, self.compiler)
          new += args
          return new
  
      def __iadd__(self, args):
          '''
          Add two CompilerArgs while taking into account overriding of arguments
          and while preserving the order of arguments as much as possible
          '''
          pre = []
          post = []
          if not isinstance(args, list):
              raise TypeError('can only concatenate list (not "{}") to list'.format(args))
          for arg in args:
              # If the argument can be de-duped, do it either by removing the
              # previous occurrence of it and adding a new one, or not adding the
              # new occurrence.
              dedup = self._can_dedup(arg)
              if dedup == 1:
                  # Argument already exists and adding a new instance is useless
                  if arg in self or arg in pre or arg in post:
                      continue
              if dedup == 2:
                  # Remove all previous occurrences of the arg and add it anew
                  if arg in self:
                      self.remove(arg)
                  if arg in pre:
                      pre.remove(arg)
                  if arg in post:
                      post.remove(arg)
              if self._should_prepend(arg):
                  pre.append(arg)
              else:
                  post.append(arg)
          # Insert at the beginning
          self[:0] = pre
          # Append to the end
          super().__iadd__(post)
          return self
  
      def __radd__(self, args):
          new = CompilerArgs(args, self.compiler)
          new += self
          return new
  
      def __mul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def __imul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def __rmul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def append(self, arg):
          self.__iadd__([arg])
  
      def extend(self, args):
          self.__iadd__(args)
  
  class Compiler:
      # Libraries to ignore in find_library() since they are provided by the
      # compiler or the C library. Currently only used for MSVC.
      ignore_libs = ()
  
      def __init__(self, exelist, version, **kwargs):
          if isinstance(exelist, str):
              self.exelist = [exelist]
          elif isinstance(exelist, list):
              self.exelist = exelist
          else:
              raise TypeError('Unknown argument to Compiler')
          # In case it's been overridden by a child class already
          if not hasattr(self, 'file_suffixes'):
              self.file_suffixes = lang_suffixes[self.language]
          if not hasattr(self, 'can_compile_suffixes'):
              self.can_compile_suffixes = set(self.file_suffixes)
          self.default_suffix = self.file_suffixes[0]
          self.version = version
          if 'full_version' in kwargs:
              self.full_version = kwargs['full_version']
          else:
              self.full_version = None
          self.base_options = []
  
      def __repr__(self):
          repr_str = "<{0}: v{1} `{2}`>"
          return repr_str.format(self.__class__.__name__, self.version,
                                 ' '.join(self.exelist))
  
      def can_compile(self, src):
          if hasattr(src, 'fname'):
              src = src.fname
          suffix = os.path.splitext(src)[1].lower()
          if suffix and suffix[1:] in self.can_compile_suffixes:
              return True
          return False
  
      def get_id(self):
          return self.id
  
      def get_language(self):
          return self.language
  
      def get_display_language(self):
          return self.language.capitalize()
  
      def get_default_suffix(self):
          return self.default_suffix
  
      def get_exelist(self):
          return self.exelist[:]
  
      def get_builtin_define(self, *args, **kwargs):
          raise EnvironmentException('%s does not support get_builtin_define.' % self.id)
  
      def has_builtin_define(self, *args, **kwargs):
          raise EnvironmentException('%s does not support has_builtin_define.' % self.id)
  
      def get_always_args(self):
          return []
  
      def get_linker_always_args(self):
          return []
  
      def gen_import_library_args(self, implibname):
          """
          Used only on Windows for libraries that need an import library.
          This currently means C, C++, Fortran.
          """
          return []
  
      def get_options(self):
          return {} # build afresh every time
  
      def get_option_compile_args(self, options):
          return []
  
      def get_option_link_args(self, options):
          return []
  
      def has_header(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
  
      def has_header_symbol(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language())
  
      def compiles(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support compile checks.' % self.get_display_language())
  
      def links(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support link checks.' % self.get_display_language())
  
      def run(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support run checks.' % self.get_display_language())
  
      def sizeof(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language())
  
      def alignment(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language())
  
      def has_function(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language())
  
      @classmethod
      def unix_args_to_native(cls, args):
          "Always returns a copy that can be independently mutated"
          return args[:]
  
      def find_library(self, *args, **kwargs):
          raise EnvironmentException('Language {} does not support library finding.'.format(self.get_display_language()))
  
      def get_library_dirs(self):
          return []
  
      def has_argument(self, arg, env):
          return self.has_multi_arguments([arg], env)
  
      def has_multi_arguments(self, args, env):
          raise EnvironmentException(
              'Language {} does not support has_multi_arguments.'.format(
                  self.get_display_language()))
  
      def get_supported_arguments(self, args, env):
          supported_args = []
          for arg in args:
              if self.has_argument(arg, env):
                  supported_args.append(arg)
          return supported_args
  
      def get_cross_extra_flags(self, environment, link):
          extra_flags = []
          if self.is_cross and environment:
              if 'properties' in environment.cross_info.config:
                  props = environment.cross_info.config['properties']
                  lang_args_key = self.language + '_args'
                  extra_flags += props.get(lang_args_key, [])
                  lang_link_args_key = self.language + '_link_args'
                  if link:
                      extra_flags += props.get(lang_link_args_key, [])
          return extra_flags
  
      def _get_compile_output(self, dirname, mode):
          # In pre-processor mode, the output is sent to stdout and discarded
          if mode == 'preprocess':
              return None
          # Extension only matters if running results; '.exe' is
          # guaranteed to be executable on every platform.
          if mode == 'link':
              suffix = 'exe'
          else:
              suffix = 'obj'
          return os.path.join(dirname, 'output.' + suffix)
  
      @contextlib.contextmanager
      def compile(self, code, extra_args=None, mode='link'):
          if extra_args is None:
              extra_args = []
          try:
              with tempfile.TemporaryDirectory() as tmpdirname:
                  if isinstance(code, str):
                      srcname = os.path.join(tmpdirname,
                                             'testfile.' + self.default_suffix)
                      with open(srcname, 'w') as ofile:
                          ofile.write(code)
                  elif isinstance(code, mesonlib.File):
                      srcname = code.fname
                  output = self._get_compile_output(tmpdirname, mode)
  
                  # Construct the compiler command-line
                  commands = CompilerArgs(self)
                  commands.append(srcname)
                  commands += extra_args
                  commands += self.get_always_args()
                  if mode == 'compile':
                      commands += self.get_compile_only_args()
                  # Preprocess mode outputs to stdout, so no output args
                  if mode == 'preprocess':
                      commands += self.get_preprocess_only_args()
                  else:
                      commands += self.get_output_args(output)
                  # Generate full command-line with the exelist
                  commands = self.get_exelist() + commands.to_native()
                  mlog.debug('Running compile:')
                  mlog.debug('Working directory: ', tmpdirname)
                  mlog.debug('Command line: ', ' '.join(commands), '\n')
                  mlog.debug('Code:\n', code)
                  p, p.stdo, p.stde = Popen_safe(commands, cwd=tmpdirname)
                  mlog.debug('Compiler stdout:\n', p.stdo)
                  mlog.debug('Compiler stderr:\n', p.stde)
                  p.input_name = srcname
                  p.output_name = output
                  yield p
          except (PermissionError, OSError):
              # On Windows antivirus programs and the like hold on to files so
              # they can't be deleted. There's not much to do in this case. Also,
              # catch OSError because the directory is then no longer empty.
              pass
  
      def get_colorout_args(self, colortype):
          return []
  
      # Some compilers (msvc) write debug info to a separate file.
      # These args specify where it should be written.
      def get_compile_debugfile_args(self, rel_obj, **kwargs):
          return []
  
      def get_link_debugfile_args(self, rel_obj):
          return []
  
      def get_std_shared_lib_link_args(self):
          return []
  
      def get_std_shared_module_link_args(self):
          return self.get_std_shared_lib_link_args()
  
      def get_link_whole_for(self, args):
          if isinstance(args, list) and not args:
              return []
          raise EnvironmentException('Language %s does not support linking whole archives.' % self.get_display_language())
  
      # Compiler arguments needed to enable the given instruction set.
      # May be [] meaning nothing needed or None meaning the given set
      # is not supported.
      def get_instruction_set_args(self, instruction_set):
          return None
  
      def build_osx_rpath_args(self, build_dir, rpath_paths, build_rpath):
          if not rpath_paths and not build_rpath:
              return []
          # On OSX, rpaths must be absolute.
          abs_rpaths = [os.path.join(build_dir, p) for p in rpath_paths]
          if build_rpath != '':
              abs_rpaths.append(build_rpath)
          args = ['-Wl,-rpath,' + rp for rp in abs_rpaths]
          return args
  
      def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
          if not rpath_paths and not install_rpath and not build_rpath:
              return []
          # The rpaths we write must be relative, because otherwise
          # they have different length depending on the build
          # directory. This breaks reproducible builds.
          rel_rpaths = []
          for p in rpath_paths:
              if p == from_dir:
                  relative = '' # relpath errors out in this case
              else:
                  relative = os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
              rel_rpaths.append(relative)
          paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
          # Build_rpath is used as-is (it is usually absolute).
          if build_rpath != '':
              if paths != '':
                  paths += ':'
              paths += build_rpath
          if len(paths) < len(install_rpath):
              padding = 'X' * (len(install_rpath) - len(paths))
              if not paths:
                  paths = padding
              else:
                  paths = paths + ':' + padding
          args = []
          if mesonlib.is_dragonflybsd():
              # This argument instructs the compiler to record the value of
              # ORIGIN in the .dynamic section of the elf. On Linux this is done
              # by default, but is not on dragonfly for some reason. Without this
              # $ORIGIN in the runtime path will be undefined and any binaries
              # linked against local libraries will fail to resolve them.
              args.append('-Wl,-z,origin')
          args.append('-Wl,-rpath,' + paths)
          if get_compiler_is_linuxlike(self):
              # Rpaths to use while linking must be absolute. These are not
              # written to the binary. Needed only with GNU ld:
              # https://sourceware.org/bugzilla/show_bug.cgi?id=16936
              # Not needed on Windows or other platforms that don't use RPATH
              # https://github.com/mesonbuild/meson/issues/1897
              lpaths = ':'.join([os.path.join(build_dir, p) for p in rpath_paths])
  
              # clang expands '-Wl,rpath-link,' to ['-rpath-link'] instead of ['-rpath-link','']
              # This eats the next argument, which happens to be 'ldstdc++', causing link failures.
              # We can dodge this problem by not adding any rpath_paths if the argument is empty.
              if lpaths.strip() != '':
                  args += ['-Wl,-rpath-link,' + lpaths]
          return args
  
      def thread_flags(self, env):
          return []
  
  
  GCC_STANDARD = 0
  GCC_OSX = 1
  GCC_MINGW = 2
  GCC_CYGWIN = 3
  
  CLANG_STANDARD = 0
  CLANG_OSX = 1
  CLANG_WIN = 2
  # Possibly clang-cl?
  
  ICC_STANDARD = 0
  ICC_OSX = 1
  ICC_WIN = 2
  
  # GNU ld cannot be installed on macOS
  # https://github.com/Homebrew/homebrew-core/issues/17794#issuecomment-328174395
  # Hence, we don't need to differentiate between OS and ld
  # for the sake of adding as-needed support
  GNU_LD_AS_NEEDED = '-Wl,--as-needed'
  APPLE_LD_AS_NEEDED = '-Wl,-dead_strip_dylibs'
  
  def get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module):
      if soversion is None:
          sostr = ''
      else:
          sostr = '.' + soversion
      if gcc_type in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN):
          # Might not be correct for mingw but seems to work.
          return ['-Wl,-soname,%s%s.%s%s' % (prefix, shlib_name, suffix, sostr)]
      elif gcc_type == GCC_OSX:
          if is_shared_module:
              return []
          install_name = prefix + shlib_name
          if soversion is not None:
              install_name += '.' + soversion
          install_name += '.dylib'
          return ['-install_name', os.path.join('@rpath', install_name)]
      else:
          raise RuntimeError('Not implemented yet.')
  
  def get_compiler_is_linuxlike(compiler):
      if (getattr(compiler, 'gcc_type', None) == GCC_STANDARD) or \
         (getattr(compiler, 'clang_type', None) == CLANG_STANDARD) or \
         (getattr(compiler, 'icc_type', None) == ICC_STANDARD):
          return True
      return False
  
  def get_compiler_uses_gnuld(c):
      # FIXME: Perhaps we should detect the linker in the environment?
      # FIXME: Assumes that *BSD use GNU ld, but they might start using lld soon
      if (getattr(c, 'gcc_type', None) in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN)) or \
         (getattr(c, 'clang_type', None) in (CLANG_STANDARD, CLANG_WIN)) or \
         (getattr(c, 'icc_type', None) in (ICC_STANDARD, ICC_WIN)):
          return True
      return False
  
  def get_largefile_args(compiler):
      '''
      Enable transparent large-file-support for 32-bit UNIX systems
      '''
      if get_compiler_is_linuxlike(compiler):
          # Enable large-file support unconditionally on all platforms other
          # than macOS and Windows. macOS is now 64-bit-only so it doesn't
          # need anything special, and Windows doesn't have automatic LFS.
          # You must use the 64-bit counterparts explicitly.
          # glibc, musl, and uclibc, and all BSD libcs support this. On Android,
          # support for transparent LFS is available depending on the version of
          # Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs
          # https://code.google.com/p/android/issues/detail?id=64613
          #
          # If this breaks your code, fix it! It's been 20+ years!
          return ['-D_FILE_OFFSET_BITS=64']
          # We don't enable -D_LARGEFILE64_SOURCE since that enables
          # transitionary features and must be enabled by programs that use
          # those features explicitly.
      return []
  
  # TODO: The result from calling compiler should be cached. So that calling this
  # function multiple times don't add latency.
  def gnulike_default_include_dirs(compiler, lang):
      if lang == 'cpp':
          lang = 'c++'
      env = os.environ.copy()
      env["LC_ALL"] = 'C'
      cmd = compiler + ['-x{}'.format(lang), '-E', '-v', '-']
      p = subprocess.Popen(
          cmd,
          stdin=subprocess.DEVNULL,
          stderr=subprocess.PIPE,
          stdout=subprocess.PIPE,
          env=env
      )
      stderr = p.stderr.read().decode('utf-8')
      parse_state = 0
      paths = []
      for line in stderr.split('\n'):
          if parse_state == 0:
              if line == '#include "..." search starts here:':
                  parse_state = 1
          elif parse_state == 1:
              if line == '#include <...> search starts here:':
                  parse_state = 2
              else:
                  paths.append(line[1:])
          elif parse_state == 2:
              if line == 'End of search list.':
                  break
              else:
                  paths.append(line[1:])
      if len(paths) == 0:
          mlog.warning('No include directory found parsing "{cmd}" output'.format(cmd=" ".join(cmd)))
      return paths
  
  class GnuCompiler:
      # Functionality that is common to all GNU family compilers.
      def __init__(self, gcc_type, defines):
          self.id = 'gcc'
          self.gcc_type = gcc_type
          self.defines = defines or {}
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_colorout', 'b_ndebug', 'b_staticpic']
          if self.gcc_type != GCC_OSX:
              self.base_options.append('b_lundef')
          self.base_options.append('b_asneeded')
          # All GCC backends can do assembly
          self.can_compile_suffixes.add('s')
  
      # TODO: centralise this policy more globally, instead
      # of fragmenting it into GnuCompiler and ClangCompiler
      def get_asneeded_args(self):
          if self.gcc_type == GCC_OSX:
              return APPLE_LD_AS_NEEDED
          else:
              return GNU_LD_AS_NEEDED
  
      def get_colorout_args(self, colortype):
          if mesonlib.version_compare(self.version, '>=4.9.0'):
              return gnu_color_args[colortype][:]
          return []
  
      def get_warn_args(self, level):
          args = super().get_warn_args(level)
          if mesonlib.version_compare(self.version, '<4.8.0') and '-Wpedantic' in args:
              # -Wpedantic was added in 4.8.0
              # https://gcc.gnu.org/gcc-4.8/changes.html
              args[args.index('-Wpedantic')] = '-pedantic'
          return args
  
      def has_builtin_define(self, define):
          return define in self.defines
  
      def get_builtin_define(self, define):
          if define in self.defines:
              return self.defines[define]
  
      def get_pic_args(self):
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW, GCC_OSX):
              return [] # On Window and OS X, pic is always on.
          return ['-fPIC']
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          if self.gcc_type == GCC_OSX:
              return apple_buildtype_linker_args[buildtype]
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'gch'
  
      def split_shlib_to_parts(self, fname):
          return os.path.dirname(fname), fname
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def get_link_whole_for(self, args):
          return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  
      def gen_vs_module_defs_args(self, defsfile):
          if not isinstance(defsfile, str):
              raise RuntimeError('Module definitions file should be str')
          # On Windows targets, .def files may be specified on the linker command
          # line like an object file.
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
              return [defsfile]
          # For other targets, discard the .def file.
          return []
  
      def get_gui_app_args(self):
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
              return ['-mwindows']
          return []
  
      def get_instruction_set_args(self, instruction_set):
          return gnulike_instruction_set_args.get(instruction_set, None)
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
  
  class ClangCompiler:
      def __init__(self, clang_type):
          self.id = 'clang'
          self.clang_type = clang_type
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_ndebug', 'b_staticpic', 'b_colorout']
          if self.clang_type != CLANG_OSX:
              self.base_options.append('b_lundef')
          self.base_options.append('b_asneeded')
          # All Clang backends can do assembly and LLVM IR
          self.can_compile_suffixes.update(['ll', 's'])
  
      # TODO: centralise this policy more globally, instead
      # of fragmenting it into GnuCompiler and ClangCompiler
      def get_asneeded_args(self):
          if self.clang_type == CLANG_OSX:
              return APPLE_LD_AS_NEEDED
          else:
              return GNU_LD_AS_NEEDED
  
      def get_pic_args(self):
          if self.clang_type in (CLANG_WIN, CLANG_OSX):
              return [] # On Window and OS X, pic is always on.
          return ['-fPIC']
  
      def get_colorout_args(self, colortype):
          return clang_color_args[colortype][:]
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          if self.clang_type == CLANG_OSX:
              return apple_buildtype_linker_args[buildtype]
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pch'
  
      def get_pch_use_args(self, pch_dir, header):
          # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
          # This flag is internal to Clang (or at least not documented on the man page)
          # so it might change semantics at any time.
          return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          if self.clang_type == CLANG_STANDARD:
              gcc_type = GCC_STANDARD
          elif self.clang_type == CLANG_OSX:
              gcc_type = GCC_OSX
          elif self.clang_type == CLANG_WIN:
              gcc_type = GCC_MINGW
          else:
              raise MesonException('Unreachable code when converting clang type to gcc type.')
          return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def has_multi_arguments(self, args, env):
          myargs = ['-Werror=unknown-warning-option', '-Werror=unused-command-line-argument']
          if mesonlib.version_compare(self.version, '>=3.6.0'):
              myargs.append('-Werror=ignored-optimization-argument')
          return super().has_multi_arguments(
              myargs + args,
              env)
  
      def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          # Starting with XCode 8, we need to pass this to force linker
          # visibility to obey OS X and iOS minimum version targets with
          # -mmacosx-version-min, -miphoneos-version-min, etc.
          # https://github.com/Homebrew/homebrew-core/issues/3727
          if self.clang_type == CLANG_OSX and version_compare(self.version, '>=8.0'):
              extra_args.append('-Wl,-no_weak_imports')
          return super().has_function(funcname, prefix, env, extra_args, dependencies)
  
      def get_std_shared_module_link_args(self):
          if self.clang_type == CLANG_OSX:
              return ['-bundle', '-Wl,-undefined,dynamic_lookup']
          return ['-shared']
  
      def get_link_whole_for(self, args):
          if self.clang_type == CLANG_OSX:
              result = []
              for a in args:
                  result += ['-Wl,-force_load', a]
              return result
          return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  
      def get_instruction_set_args(self, instruction_set):
          return gnulike_instruction_set_args.get(instruction_set, None)
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
  
  # Tested on linux for ICC 14.0.3, 15.0.6, 16.0.4, 17.0.1
  class IntelCompiler:
      def __init__(self, icc_type):
          self.id = 'intel'
          self.icc_type = icc_type
          self.lang_header = 'none'
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_colorout', 'b_ndebug', 'b_staticpic', 'b_lundef', 'b_asneeded']
          # Assembly
          self.can_compile_suffixes.add('s')
  
      def get_pic_args(self):
          return ['-fPIC']
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pchi'
  
      def get_pch_use_args(self, pch_dir, header):
          return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x',
                  self.lang_header, '-include', header, '-x', 'none']
  
      def get_pch_name(self, header_name):
          return os.path.basename(header_name) + '.' + self.get_pch_suffix()
  
      def split_shlib_to_parts(self, fname):
          return os.path.dirname(fname), fname
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          if self.icc_type == ICC_STANDARD:
              gcc_type = GCC_STANDARD
          elif self.icc_type == ICC_OSX:
              gcc_type = GCC_OSX
          elif self.icc_type == ICC_WIN:
              gcc_type = GCC_MINGW
          else:
              raise MesonException('Unreachable code when converting icc type to gcc type.')
          return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def get_std_shared_lib_link_args(self):
          # FIXME: Don't know how icc works on OSX
          # if self.icc_type == ICC_OSX:
          #     return ['-bundle']
          return ['-shared']
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
files: mesonbuild/compilers/compilers.py
files: # Copyright 2012-2017 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.
  
  import contextlib, os.path, re, tempfile
  import subprocess
  
  from ..linkers import StaticLinker
  from .. import coredata
  from .. import mlog
  from .. import mesonlib
  from ..mesonlib import EnvironmentException, MesonException, version_compare, Popen_safe
  
  """This file contains the data files of all compilers Meson knows
  about. To support a new compiler, add its information below.
  Also add corresponding autodetection code in environment.py."""
  
  header_suffixes = ('h', 'hh', 'hpp', 'hxx', 'H', 'ipp', 'moc', 'vapi', 'di')
  obj_suffixes = ('o', 'obj', 'res')
  lib_suffixes = ('a', 'lib', 'dll', 'dylib', 'so')
  # Mapping of language to suffixes of files that should always be in that language
  # This means we can't include .h headers here since they could be C, C++, ObjC, etc.
  lang_suffixes = {
      'c': ('c',),
      'cpp': ('cpp', 'cc', 'cxx', 'c++', 'hh', 'hpp', 'ipp', 'hxx'),
      # f90, f95, f03, f08 are for free-form fortran ('f90' recommended)
      # f, for, ftn, fpp are for fixed-form fortran ('f' or 'for' recommended)
      'fortran': ('f90', 'f95', 'f03', 'f08', 'f', 'for', 'ftn', 'fpp'),
      'd': ('d', 'di'),
      'objc': ('m',),
      'objcpp': ('mm',),
      'rust': ('rs',),
      'vala': ('vala', 'vapi', 'gs'),
      'cs': ('cs',),
      'swift': ('swift',),
      'java': ('java',),
  }
  cpp_suffixes = lang_suffixes['cpp'] + ('h',)
  c_suffixes = lang_suffixes['c'] + ('h',)
  # List of languages that can be linked with C code directly by the linker
  # used in build.py:process_compilers() and build.py:get_dynamic_linker()
  clike_langs = ('d', 'objcpp', 'cpp', 'objc', 'c', 'fortran',)
  clike_suffixes = ()
  for _l in clike_langs:
      clike_suffixes += lang_suffixes[_l]
  clike_suffixes += ('h', 'll', 's')
  
  # XXX: Use this in is_library()?
  soregex = re.compile(r'.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
  
  # All these are only for C-like languages; see `clike_langs` above.
  
  def sort_clike(lang):
      '''
      Sorting function to sort the list of languages according to
      reversed(compilers.clike_langs) and append the unknown langs in the end.
      The purpose is to prefer C over C++ for files that can be compiled by
      both such as assembly, C, etc. Also applies to ObjC, ObjC++, etc.
      '''
      if lang not in clike_langs:
          return 1
      return -clike_langs.index(lang)
  
  def is_header(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in header_suffixes
  
  def is_source(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1].lower()
      return suffix in clike_suffixes
  
  def is_assembly(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      return fname.split('.')[-1].lower() == 's'
  
  def is_llvm_ir(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      return fname.split('.')[-1] == 'll'
  
  def is_object(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in obj_suffixes
  
  def is_library(fname):
      if hasattr(fname, 'fname'):
          fname = fname.fname
      suffix = fname.split('.')[-1]
      return suffix in lib_suffixes
  
  gnulike_buildtype_args = {'plain': [],
                            # -O0 is passed for improved debugging information with gcc
                            # See https://github.com/mesonbuild/meson/pull/509
                            'debug': ['-O0', '-g'],
                            'debugoptimized': ['-O2', '-g'],
                            'release': ['-O3'],
                            'minsize': ['-Os', '-g']}
  
  msvc_buildtype_args = {'plain': [],
                         'debug': ["/MDd", "/ZI", "/Ob0", "/Od", "/RTC1"],
                         'debugoptimized': ["/MD", "/Zi", "/O2", "/Ob1"],
                         'release': ["/MD", "/O2", "/Ob2"],
                         'minsize': ["/MD", "/Zi", "/Os", "/Ob1"],
                         }
  
  apple_buildtype_linker_args = {'plain': [],
                                 'debug': [],
                                 'debugoptimized': [],
                                 'release': [],
                                 'minsize': [],
                                 }
  
  gnulike_buildtype_linker_args = {'plain': [],
                                   'debug': [],
                                   'debugoptimized': [],
                                   'release': ['-Wl,-O1'],
                                   'minsize': [],
                                   }
  
  msvc_buildtype_linker_args = {'plain': [],
                                'debug': [],
                                'debugoptimized': [],
                                # The otherwise implicit REF and ICF linker
                                # optimisations are disabled by /DEBUG.
                                # REF implies ICF.
                                'release': ['/OPT:REF'],
                                'minsize': ['/INCREMENTAL:NO', '/OPT:REF'],
                                }
  
  java_buildtype_args = {'plain': [],
                         'debug': ['-g'],
                         'debugoptimized': ['-g'],
                         'release': [],
                         'minsize': [],
                         }
  
  rust_buildtype_args = {'plain': [],
                         'debug': ['-C', 'debuginfo=2'],
                         'debugoptimized': ['-C', 'debuginfo=2', '-C', 'opt-level=2'],
                         'release': ['-C', 'opt-level=3'],
                         'minsize': [], # In a future release: ['-C', 'opt-level=s'],
                         }
  
  d_gdc_buildtype_args = {'plain': [],
                          'debug': ['-g', '-O0'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O3', '-frelease'],
                          'minsize': [],
                          }
  
  d_ldc_buildtype_args = {'plain': [],
                          'debug': ['-g', '-O0'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O3', '-release'],
                          'minsize': [],
                          }
  
  d_dmd_buildtype_args = {'plain': [],
                          'debug': ['-g'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O', '-release'],
                          'minsize': [],
                          }
  
  mono_buildtype_args = {'plain': [],
                         'debug': ['-debug'],
                         'debugoptimized': ['-debug', '-optimize+'],
                         'release': ['-optimize+'],
                         'minsize': [],
                         }
  
  swift_buildtype_args = {'plain': [],
                          'debug': ['-g'],
                          'debugoptimized': ['-g', '-O'],
                          'release': ['-O'],
                          'minsize': [],
                          }
  
  gnu_winlibs = ['-lkernel32', '-luser32', '-lgdi32', '-lwinspool', '-lshell32',
                 '-lole32', '-loleaut32', '-luuid', '-lcomdlg32', '-ladvapi32']
  
  msvc_winlibs = ['kernel32.lib', 'user32.lib', 'gdi32.lib',
                  'winspool.lib', 'shell32.lib', 'ole32.lib', 'oleaut32.lib',
                  'uuid.lib', 'comdlg32.lib', 'advapi32.lib']
  
  gnu_color_args = {'auto': ['-fdiagnostics-color=auto'],
                    'always': ['-fdiagnostics-color=always'],
                    'never': ['-fdiagnostics-color=never'],
                    }
  
  clang_color_args = {'auto': ['-Xclang', '-fcolor-diagnostics'],
                      'always': ['-Xclang', '-fcolor-diagnostics'],
                      'never': ['-Xclang', '-fno-color-diagnostics'],
                      }
  
  base_options = {'b_pch': coredata.UserBooleanOption('b_pch', 'Use precompiled headers', True),
                  'b_lto': coredata.UserBooleanOption('b_lto', 'Use link time optimization', False),
                  'b_sanitize': coredata.UserComboOption('b_sanitize',
                                                         'Code sanitizer to use',
                                                         ['none', 'address', 'thread', 'undefined', 'memory', 'address,undefined'],
                                                         'none'),
                  'b_lundef': coredata.UserBooleanOption('b_lundef', 'Use -Wl,--no-undefined when linking', True),
                  'b_asneeded': coredata.UserBooleanOption('b_asneeded', 'Use -Wl,--as-needed when linking', True),
                  'b_pgo': coredata.UserComboOption('b_pgo', 'Use profile guided optimization',
                                                    ['off', 'generate', 'use'],
                                                    'off'),
                  'b_coverage': coredata.UserBooleanOption('b_coverage',
                                                           'Enable coverage tracking.',
                                                           False),
                  'b_colorout': coredata.UserComboOption('b_colorout', 'Use colored output',
                                                         ['auto', 'always', 'never'],
                                                         'always'),
                  'b_ndebug': coredata.UserComboOption('b_ndebug', 'Disable asserts',
                                                       ['true', 'false', 'if-release'], 'false'),
                  'b_staticpic': coredata.UserBooleanOption('b_staticpic',
                                                            'Build static libraries as position independent',
                                                            True),
                  }
  
  gnulike_instruction_set_args = {'mmx': ['-mmmx'],
                                  'sse': ['-msse'],
                                  'sse2': ['-msse2'],
                                  'sse3': ['-msse3'],
                                  'ssse3': ['-mssse3'],
                                  'sse41': ['-msse4.1'],
                                  'sse42': ['-msse4.2'],
                                  'avx': ['-mavx'],
                                  'avx2': ['-mavx2'],
                                  'neon': ['-mfpu=neon'],
                                  }
  
  vs32_instruction_set_args = {'mmx': ['/arch:SSE'], # There does not seem to be a flag just for MMX
                               'sse': ['/arch:SSE'],
                               'sse2': ['/arch:SSE2'],
                               'sse3': ['/arch:AVX'], # VS leaped from SSE2 directly to AVX.
                               'sse41': ['/arch:AVX'],
                               'sse42': ['/arch:AVX'],
                               'avx': ['/arch:AVX'],
                               'avx2': ['/arch:AVX2'],
                               'neon': None,
                               }
  
  # The 64 bit compiler defaults to /arch:avx.
  vs64_instruction_set_args = {'mmx': ['/arch:AVX'],
                               'sse': ['/arch:AVX'],
                               'sse2': ['/arch:AVX'],
                               'sse3': ['/arch:AVX'],
                               'ssse3': ['/arch:AVX'],
                               'sse41': ['/arch:AVX'],
                               'sse42': ['/arch:AVX'],
                               'avx': ['/arch:AVX'],
                               'avx2': ['/arch:AVX2'],
                               'neon': None,
                               }
  
  
  def sanitizer_compile_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      if 'address' in value: # For -fsanitize=address,undefined
          args.append('-fno-omit-frame-pointer')
      return args
  
  def sanitizer_link_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      return args
  
  def get_base_compile_args(options, compiler):
      args = []
      # FIXME, gcc/clang specific.
      try:
          if options['b_lto'].value:
              args.append('-flto')
      except KeyError:
          pass
      try:
          args += compiler.get_colorout_args(options['b_colorout'].value)
      except KeyError:
          pass
      try:
          args += sanitizer_compile_args(options['b_sanitize'].value)
      except KeyError:
          pass
      try:
          pgo_val = options['b_pgo'].value
          if pgo_val == 'generate':
              args.append('-fprofile-generate')
          elif pgo_val == 'use':
              args.append('-fprofile-use')
      except KeyError:
          pass
      try:
          if options['b_coverage'].value:
              args += compiler.get_coverage_args()
      except KeyError:
          pass
      try:
          if options['b_ndebug'].value == 'true' or (options['b_ndebug'].value == 'if-release' and options['buildtype'] == 'release'):
              args += ['-DNDEBUG']
      except KeyError:
          pass
      return args
  
  def get_base_link_args(options, linker, is_shared_module):
      args = []
      # FIXME, gcc/clang specific.
      try:
          if options['b_lto'].value:
              args.append('-flto')
      except KeyError:
          pass
      try:
          args += sanitizer_link_args(options['b_sanitize'].value)
      except KeyError:
          pass
      try:
          pgo_val = options['b_pgo'].value
          if pgo_val == 'generate':
              args.append('-fprofile-generate')
          elif pgo_val == 'use':
              args.append('-fprofile-use')
      except KeyError:
          pass
      try:
          if not is_shared_module and 'b_lundef' in linker.base_options and options['b_lundef'].value:
              args.append('-Wl,--no-undefined')
      except KeyError:
          pass
      try:
          if 'b_asneeded' in linker.base_options and options['b_asneeded'].value:
              args.append(linker.get_asneeded_args())
      except KeyError:
          pass
      try:
          if options['b_coverage'].value:
              args += linker.get_coverage_link_args()
      except KeyError:
          pass
      return args
  
  class CrossNoRunException(MesonException):
      pass
  
  class RunResult:
      def __init__(self, compiled, returncode=999, stdout='UNDEFINED', stderr='UNDEFINED'):
          self.compiled = compiled
          self.returncode = returncode
          self.stdout = stdout
          self.stderr = stderr
  
  class CompilerArgs(list):
      '''
      Class derived from list() that manages a list of compiler arguments. Should
      be used while constructing compiler arguments from various sources. Can be
      operated with ordinary lists, so this does not need to be used everywhere.
  
      All arguments must be inserted and stored in GCC-style (-lfoo, -Idir, etc)
      and can converted to the native type of each compiler by using the
      .to_native() method to which you must pass an instance of the compiler or
      the compiler class.
  
      New arguments added to this class (either with .append(), .extend(), or +=)
      are added in a way that ensures that they override previous arguments.
      For example:
  
      >>> a = ['-Lfoo', '-lbar']
      >>> a += ['-Lpho', '-lbaz']
      >>> print(a)
      ['-Lpho', '-Lfoo', '-lbar', '-lbaz']
  
      Arguments will also be de-duped if they can be de-duped safely.
  
      Note that because of all this, this class is not commutative and does not
      preserve the order of arguments if it is safe to not. For example:
      >>> ['-Ifoo', '-Ibar'] + ['-Ifez', '-Ibaz', '-Werror']
      ['-Ifez', '-Ibaz', '-Ifoo', '-Ibar', '-Werror']
      >>> ['-Ifez', '-Ibaz', '-Werror'] + ['-Ifoo', '-Ibar']
      ['-Ifoo', '-Ibar', '-Ifez', '-Ibaz', '-Werror']
  
      '''
      # NOTE: currently this class is only for C-like compilers, but it can be
      # extended to other languages easily. Just move the following to the
      # compiler class and initialize when self.compiler is set.
  
      # Arg prefixes that override by prepending instead of appending
      prepend_prefixes = ('-I', '-L')
      # Arg prefixes and args that must be de-duped by returning 2
      dedup2_prefixes = ('-I', '-L', '-D', '-U')
      dedup2_suffixes = ()
      dedup2_args = ()
      # Arg prefixes and args that must be de-duped by returning 1
      dedup1_prefixes = ('-l',)
      dedup1_suffixes = ('.lib', '.dll', '.so', '.dylib', '.a')
      # Match a .so of the form path/to/libfoo.so.0.1.0
      # Only UNIX shared libraries require this. Others have a fixed extension.
      dedup1_regex = re.compile(r'([\/\\]|\A)lib.*\.so(\.[0-9]+)?(\.[0-9]+)?(\.[0-9]+)?$')
      dedup1_args = ('-c', '-S', '-E', '-pipe', '-pthread')
      compiler = None
  
      def _check_args(self, args):
          cargs = []
          if len(args) > 2:
              raise TypeError("CompilerArgs() only accepts at most 2 arguments: "
                              "The compiler, and optionally an initial list")
          elif not args:
              return cargs
          elif len(args) == 1:
              if isinstance(args[0], (Compiler, StaticLinker)):
                  self.compiler = args[0]
              else:
                  raise TypeError("you must pass a Compiler instance as one of "
                                  "the arguments")
          elif len(args) == 2:
              if isinstance(args[0], (Compiler, StaticLinker)):
                  self.compiler = args[0]
                  cargs = args[1]
              elif isinstance(args[1], (Compiler, StaticLinker)):
                  cargs = args[0]
                  self.compiler = args[1]
              else:
                  raise TypeError("you must pass a Compiler instance as one of "
                                  "the two arguments")
          else:
              raise AssertionError('Not reached')
          return cargs
  
      def __init__(self, *args):
          super().__init__(self._check_args(args))
  
      @classmethod
      def _can_dedup(cls, arg):
          '''
          Returns whether the argument can be safely de-duped. This is dependent
          on three things:
  
          a) Whether an argument can be 'overridden' by a later argument.  For
             example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
             can safely remove the previous occurrence and add a new one. The same
             is true for include paths and library paths with -I and -L. For
             these we return `2`. See `dedup2_prefixes` and `dedup2_args`.
          b) Arguments that once specified cannot be undone, such as `-c` or
             `-pipe`. New instances of these can be completely skipped. For these
             we return `1`. See `dedup1_prefixes` and `dedup1_args`.
          c) Whether it matters where or how many times on the command-line
             a particular argument is present. This can matter for symbol
             resolution in static or shared libraries, so we cannot de-dup or
             reorder them. For these we return `0`. This is the default.
  
          In addition to these, we handle library arguments specially.
          With GNU ld, we surround library arguments with -Wl,--start/end-group
          to recursively search for symbols in the libraries. This is not needed
          with other linkers.
          '''
  
          # A standalone argument must never be deduplicated because it is
          # defined by what comes _after_ it. Thus dedupping this:
          # -D FOO -D BAR
          # would yield either
          # -D FOO BAR
          # or
          # FOO -D BAR
          # both of which are invalid.
          if arg in cls.dedup2_prefixes:
              return 0
          if arg in cls.dedup2_args or \
             arg.startswith(cls.dedup2_prefixes) or \
             arg.endswith(cls.dedup2_suffixes):
              return 2
          if arg in cls.dedup1_args or \
             arg.startswith(cls.dedup1_prefixes) or \
             arg.endswith(cls.dedup1_suffixes) or \
             re.search(cls.dedup1_regex, arg):
              return 1
          return 0
  
      @classmethod
      def _should_prepend(cls, arg):
          if arg.startswith(cls.prepend_prefixes):
              return True
          return False
  
      def to_native(self):
          # Check if we need to add --start/end-group for circular dependencies
          # between static libraries, and for recursively searching for symbols
          # needed by static libraries that are provided by object files or
          # shared libraries.
          if get_compiler_uses_gnuld(self.compiler):
              global soregex
              group_start = -1
              for each in self:
                  if not each.startswith('-l') and not each.endswith('.a') and \
                     not soregex.match(each):
                      continue
                  i = self.index(each)
                  if group_start < 0:
                      # First occurrence of a library
                      group_start = i
              if group_start >= 0:
                  # Last occurrence of a library
                  self.insert(i + 1, '-Wl,--end-group')
                  self.insert(group_start, '-Wl,--start-group')
          return self.compiler.unix_args_to_native(self)
  
      def append_direct(self, arg):
          '''
          Append the specified argument without any reordering or de-dup
          '''
          super().append(arg)
  
      def extend_direct(self, iterable):
          '''
          Extend using the elements in the specified iterable without any
          reordering or de-dup
          '''
          super().extend(iterable)
  
      def __add__(self, args):
          new = CompilerArgs(self, self.compiler)
          new += args
          return new
  
      def __iadd__(self, args):
          '''
          Add two CompilerArgs while taking into account overriding of arguments
          and while preserving the order of arguments as much as possible
          '''
          pre = []
          post = []
          if not isinstance(args, list):
              raise TypeError('can only concatenate list (not "{}") to list'.format(args))
          for arg in args:
              # If the argument can be de-duped, do it either by removing the
              # previous occurrence of it and adding a new one, or not adding the
              # new occurrence.
              dedup = self._can_dedup(arg)
              if dedup == 1:
                  # Argument already exists and adding a new instance is useless
                  if arg in self or arg in pre or arg in post:
                      continue
              if dedup == 2:
                  # Remove all previous occurrences of the arg and add it anew
                  if arg in self:
                      self.remove(arg)
                  if arg in pre:
                      pre.remove(arg)
                  if arg in post:
                      post.remove(arg)
              if self._should_prepend(arg):
                  pre.append(arg)
              else:
                  post.append(arg)
          # Insert at the beginning
          self[:0] = pre
          # Append to the end
          super().__iadd__(post)
          return self
  
      def __radd__(self, args):
          new = CompilerArgs(args, self.compiler)
          new += self
          return new
  
      def __mul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def __imul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def __rmul__(self, args):
          raise TypeError("can't multiply compiler arguments")
  
      def append(self, arg):
          self.__iadd__([arg])
  
      def extend(self, args):
          self.__iadd__(args)
  
  class Compiler:
      # Libraries to ignore in find_library() since they are provided by the
      # compiler or the C library. Currently only used for MSVC.
      ignore_libs = ()
  
      def __init__(self, exelist, version, **kwargs):
          if isinstance(exelist, str):
              self.exelist = [exelist]
          elif isinstance(exelist, list):
              self.exelist = exelist
          else:
              raise TypeError('Unknown argument to Compiler')
          # In case it's been overridden by a child class already
          if not hasattr(self, 'file_suffixes'):
              self.file_suffixes = lang_suffixes[self.language]
          if not hasattr(self, 'can_compile_suffixes'):
              self.can_compile_suffixes = set(self.file_suffixes)
          self.default_suffix = self.file_suffixes[0]
          self.version = version
          if 'full_version' in kwargs:
              self.full_version = kwargs['full_version']
          else:
              self.full_version = None
          self.base_options = []
  
      def __repr__(self):
          repr_str = "<{0}: v{1} `{2}`>"
          return repr_str.format(self.__class__.__name__, self.version,
                                 ' '.join(self.exelist))
  
      def can_compile(self, src):
          if hasattr(src, 'fname'):
              src = src.fname
          suffix = os.path.splitext(src)[1].lower()
          if suffix and suffix[1:] in self.can_compile_suffixes:
              return True
          return False
  
      def get_id(self):
          return self.id
  
      def get_language(self):
          return self.language
  
      def get_display_language(self):
          return self.language.capitalize()
  
      def get_default_suffix(self):
          return self.default_suffix
  
      def get_exelist(self):
          return self.exelist[:]
  
      def get_builtin_define(self, *args, **kwargs):
          raise EnvironmentException('%s does not support get_builtin_define.' % self.id)
  
      def has_builtin_define(self, *args, **kwargs):
          raise EnvironmentException('%s does not support has_builtin_define.' % self.id)
  
      def get_always_args(self):
          return []
  
      def get_linker_always_args(self):
          return []
  
      def gen_import_library_args(self, implibname):
          """
          Used only on Windows for libraries that need an import library.
          This currently means C, C++, Fortran.
          """
          return []
  
      def get_options(self):
          return {} # build afresh every time
  
      def get_option_compile_args(self, options):
          return []
  
      def get_option_link_args(self, options):
          return []
  
      def has_header(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header checks.' % self.get_display_language())
  
      def has_header_symbol(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header symbol checks.' % self.get_display_language())
  
      def compiles(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support compile checks.' % self.get_display_language())
  
      def links(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support link checks.' % self.get_display_language())
  
      def run(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support run checks.' % self.get_display_language())
  
      def sizeof(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support sizeof checks.' % self.get_display_language())
  
      def alignment(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support alignment checks.' % self.get_display_language())
  
      def has_function(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support function checks.' % self.get_display_language())
  
      @classmethod
      def unix_args_to_native(cls, args):
          "Always returns a copy that can be independently mutated"
          return args[:]
  
      def find_library(self, *args, **kwargs):
          raise EnvironmentException('Language {} does not support library finding.'.format(self.get_display_language()))
  
      def get_library_dirs(self):
          return []
  
      def has_argument(self, arg, env):
          return self.has_multi_arguments([arg], env)
  
      def has_multi_arguments(self, args, env):
          raise EnvironmentException(
              'Language {} does not support has_multi_arguments.'.format(
                  self.get_display_language()))
  
      def get_supported_arguments(self, args, env):
          supported_args = []
          for arg in args:
              if self.has_argument(arg, env):
                  supported_args.append(arg)
          return supported_args
  
      def get_cross_extra_flags(self, environment, link):
          extra_flags = []
          if self.is_cross and environment:
              if 'properties' in environment.cross_info.config:
                  props = environment.cross_info.config['properties']
                  lang_args_key = self.language + '_args'
                  extra_flags += props.get(lang_args_key, [])
                  lang_link_args_key = self.language + '_link_args'
                  if link:
                      extra_flags += props.get(lang_link_args_key, [])
          return extra_flags
  
      def _get_compile_output(self, dirname, mode):
          # In pre-processor mode, the output is sent to stdout and discarded
          if mode == 'preprocess':
              return None
          # Extension only matters if running results; '.exe' is
          # guaranteed to be executable on every platform.
          if mode == 'link':
              suffix = 'exe'
          else:
              suffix = 'obj'
          return os.path.join(dirname, 'output.' + suffix)
  
      @contextlib.contextmanager
      def compile(self, code, extra_args=None, mode='link'):
          if extra_args is None:
              extra_args = []
          try:
              with tempfile.TemporaryDirectory() as tmpdirname:
                  if isinstance(code, str):
                      srcname = os.path.join(tmpdirname,
                                             'testfile.' + self.default_suffix)
                      with open(srcname, 'w') as ofile:
                          ofile.write(code)
                  elif isinstance(code, mesonlib.File):
                      srcname = code.fname
                  output = self._get_compile_output(tmpdirname, mode)
  
                  # Construct the compiler command-line
                  commands = CompilerArgs(self)
                  commands.append(srcname)
                  commands += extra_args
                  commands += self.get_always_args()
                  if mode == 'compile':
                      commands += self.get_compile_only_args()
                  # Preprocess mode outputs to stdout, so no output args
                  if mode == 'preprocess':
                      commands += self.get_preprocess_only_args()
                  else:
                      commands += self.get_output_args(output)
                  # Generate full command-line with the exelist
                  commands = self.get_exelist() + commands.to_native()
                  mlog.debug('Running compile:')
                  mlog.debug('Working directory: ', tmpdirname)
                  mlog.debug('Command line: ', ' '.join(commands), '\n')
                  mlog.debug('Code:\n', code)
                  p, p.stdo, p.stde = Popen_safe(commands, cwd=tmpdirname)
                  mlog.debug('Compiler stdout:\n', p.stdo)
                  mlog.debug('Compiler stderr:\n', p.stde)
                  p.input_name = srcname
                  p.output_name = output
                  yield p
          except (PermissionError, OSError):
              # On Windows antivirus programs and the like hold on to files so
              # they can't be deleted. There's not much to do in this case. Also,
              # catch OSError because the directory is then no longer empty.
              pass
  
      def get_colorout_args(self, colortype):
          return []
  
      # Some compilers (msvc) write debug info to a separate file.
      # These args specify where it should be written.
      def get_compile_debugfile_args(self, rel_obj, **kwargs):
          return []
  
      def get_link_debugfile_args(self, rel_obj):
          return []
  
      def get_std_shared_lib_link_args(self):
          return []
  
      def get_std_shared_module_link_args(self):
          return self.get_std_shared_lib_link_args()
  
      def get_link_whole_for(self, args):
          if isinstance(args, list) and not args:
              return []
          raise EnvironmentException('Language %s does not support linking whole archives.' % self.get_display_language())
  
      # Compiler arguments needed to enable the given instruction set.
      # May be [] meaning nothing needed or None meaning the given set
      # is not supported.
      def get_instruction_set_args(self, instruction_set):
          return None
  
      def build_osx_rpath_args(self, build_dir, rpath_paths, build_rpath):
          if not rpath_paths and not build_rpath:
              return []
          # On OSX, rpaths must be absolute.
          abs_rpaths = [os.path.join(build_dir, p) for p in rpath_paths]
          if build_rpath != '':
              abs_rpaths.append(build_rpath)
          args = ['-Wl,-rpath,' + rp for rp in abs_rpaths]
          return args
  
      def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, build_rpath, install_rpath):
          if not rpath_paths and not install_rpath and not build_rpath:
              return []
          # The rpaths we write must be relative, because otherwise
          # they have different length depending on the build
          # directory. This breaks reproducible builds.
          rel_rpaths = []
          for p in rpath_paths:
              if p == from_dir:
                  relative = '' # relpath errors out in this case
              else:
                  relative = os.path.relpath(os.path.join(build_dir, p), os.path.join(build_dir, from_dir))
              rel_rpaths.append(relative)
          paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
          # Build_rpath is used as-is (it is usually absolute).
          if build_rpath != '':
              if paths != '':
                  paths += ':'
              paths += build_rpath
          if len(paths) < len(install_rpath):
              padding = 'X' * (len(install_rpath) - len(paths))
              if not paths:
                  paths = padding
              else:
                  paths = paths + ':' + padding
          args = []
          if mesonlib.is_dragonflybsd():
              # This argument instructs the compiler to record the value of
              # ORIGIN in the .dynamic section of the elf. On Linux this is done
              # by default, but is not on dragonfly for some reason. Without this
              # $ORIGIN in the runtime path will be undefined and any binaries
              # linked against local libraries will fail to resolve them.
              args.append('-Wl,-z,origin')
          args.append('-Wl,-rpath,' + paths)
          if get_compiler_is_linuxlike(self):
              # Rpaths to use while linking must be absolute. These are not
              # written to the binary. Needed only with GNU ld:
              # https://sourceware.org/bugzilla/show_bug.cgi?id=16936
              # Not needed on Windows or other platforms that don't use RPATH
              # https://github.com/mesonbuild/meson/issues/1897
              lpaths = ':'.join([os.path.join(build_dir, p) for p in rpath_paths])
  
              # clang expands '-Wl,rpath-link,' to ['-rpath-link'] instead of ['-rpath-link','']
              # This eats the next argument, which happens to be 'ldstdc++', causing link failures.
              # We can dodge this problem by not adding any rpath_paths if the argument is empty.
              if lpaths.strip() != '':
                  args += ['-Wl,-rpath-link,' + lpaths]
          return args
  
      def thread_flags(self, env):
          return []
  
  
  GCC_STANDARD = 0
  GCC_OSX = 1
  GCC_MINGW = 2
  GCC_CYGWIN = 3
  
  CLANG_STANDARD = 0
  CLANG_OSX = 1
  CLANG_WIN = 2
  # Possibly clang-cl?
  
  ICC_STANDARD = 0
  ICC_OSX = 1
  ICC_WIN = 2
  
  # GNU ld cannot be installed on macOS
  # https://github.com/Homebrew/homebrew-core/issues/17794#issuecomment-328174395
  # Hence, we don't need to differentiate between OS and ld
  # for the sake of adding as-needed support
  GNU_LD_AS_NEEDED = '-Wl,--as-needed'
  APPLE_LD_AS_NEEDED = '-Wl,-dead_strip_dylibs'
  
  def get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module):
      if soversion is None:
          sostr = ''
      else:
          sostr = '.' + soversion
      if gcc_type in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN):
          # Might not be correct for mingw but seems to work.
          return ['-Wl,-soname,%s%s.%s%s' % (prefix, shlib_name, suffix, sostr)]
      elif gcc_type == GCC_OSX:
          if is_shared_module:
              return []
          install_name = prefix + shlib_name
          if soversion is not None:
              install_name += '.' + soversion
          install_name += '.dylib'
          return ['-install_name', os.path.join('@rpath', install_name)]
      else:
          raise RuntimeError('Not implemented yet.')
  
  def get_compiler_is_linuxlike(compiler):
      if (getattr(compiler, 'gcc_type', None) == GCC_STANDARD) or \
         (getattr(compiler, 'clang_type', None) == CLANG_STANDARD) or \
         (getattr(compiler, 'icc_type', None) == ICC_STANDARD):
          return True
      return False
  
  def get_compiler_uses_gnuld(c):
      # FIXME: Perhaps we should detect the linker in the environment?
      # FIXME: Assumes that *BSD use GNU ld, but they might start using lld soon
      if (getattr(c, 'gcc_type', None) in (GCC_STANDARD, GCC_MINGW, GCC_CYGWIN)) or \
         (getattr(c, 'clang_type', None) in (CLANG_STANDARD, CLANG_WIN)) or \
         (getattr(c, 'icc_type', None) in (ICC_STANDARD, ICC_WIN)):
          return True
      return False
  
  def get_largefile_args(compiler):
      '''
      Enable transparent large-file-support for 32-bit UNIX systems
      '''
      if get_compiler_is_linuxlike(compiler):
          # Enable large-file support unconditionally on all platforms other
          # than macOS and Windows. macOS is now 64-bit-only so it doesn't
          # need anything special, and Windows doesn't have automatic LFS.
          # You must use the 64-bit counterparts explicitly.
          # glibc, musl, and uclibc, and all BSD libcs support this. On Android,
          # support for transparent LFS is available depending on the version of
          # Bionic: https://github.com/android/platform_bionic#32-bit-abi-bugs
          # https://code.google.com/p/android/issues/detail?id=64613
          #
          # If this breaks your code, fix it! It's been 20+ years!
          return ['-D_FILE_OFFSET_BITS=64']
          # We don't enable -D_LARGEFILE64_SOURCE since that enables
          # transitionary features and must be enabled by programs that use
          # those features explicitly.
      return []
  
  # TODO: The result from calling compiler should be cached. So that calling this
  # function multiple times don't add latency.
  def gnulike_default_include_dirs(compiler, lang):
      if lang == 'cpp':
          lang = 'c++'
      env = os.environ.copy()
      env["LC_ALL"] = 'C'
      cmd = compiler + ['-x{}'.format(lang), '-E', '-v', '-']
      p = subprocess.Popen(
          cmd,
          stdin=subprocess.DEVNULL,
          stderr=subprocess.PIPE,
          stdout=subprocess.PIPE,
          env=env
      )
      stderr = p.stderr.read().decode('utf-8')
      parse_state = 0
      paths = []
      for line in stderr.split('\n'):
          if parse_state == 0:
              if line == '#include "..." search starts here:':
                  parse_state = 1
          elif parse_state == 1:
              if line == '#include <...> search starts here:':
                  parse_state = 2
              else:
                  paths.append(line[1:])
          elif parse_state == 2:
              if line == 'End of search list.':
                  break
              else:
                  paths.append(line[1:])
      if len(paths) == 0:
          mlog.warning('No include directory found parsing "{cmd}" output'.format(cmd=" ".join(cmd)))
      return paths
  
  class GnuCompiler:
      # Functionality that is common to all GNU family compilers.
      def __init__(self, gcc_type, defines):
          self.id = 'gcc'
          self.gcc_type = gcc_type
          self.defines = defines or {}
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_colorout', 'b_ndebug', 'b_staticpic']
          if self.gcc_type != GCC_OSX:
              self.base_options.append('b_lundef')
          self.base_options.append('b_asneeded')
          # All GCC backends can do assembly
          self.can_compile_suffixes.add('s')
  
      # TODO: centralise this policy more globally, instead
      # of fragmenting it into GnuCompiler and ClangCompiler
      def get_asneeded_args(self):
          if self.gcc_type == GCC_OSX:
              return APPLE_LD_AS_NEEDED
          else:
              return GNU_LD_AS_NEEDED
  
      def get_colorout_args(self, colortype):
          if mesonlib.version_compare(self.version, '>=4.9.0'):
              return gnu_color_args[colortype][:]
          return []
  
      def get_warn_args(self, level):
          args = super().get_warn_args(level)
          if mesonlib.version_compare(self.version, '<4.8.0') and '-Wpedantic' in args:
              # -Wpedantic was added in 4.8.0
              # https://gcc.gnu.org/gcc-4.8/changes.html
              args[args.index('-Wpedantic')] = '-pedantic'
          return args
  
      def has_builtin_define(self, define):
          return define in self.defines
  
      def get_builtin_define(self, define):
          if define in self.defines:
              return self.defines[define]
  
      def get_pic_args(self):
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW, GCC_OSX):
              return [] # On Window and OS X, pic is always on.
          return ['-fPIC']
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          if self.gcc_type == GCC_OSX:
              return apple_buildtype_linker_args[buildtype]
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'gch'
  
      def split_shlib_to_parts(self, fname):
          return os.path.dirname(fname), fname
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return get_gcc_soname_args(self.gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def get_link_whole_for(self, args):
          return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  
      def gen_vs_module_defs_args(self, defsfile):
          if not isinstance(defsfile, str):
              raise RuntimeError('Module definitions file should be str')
          # On Windows targets, .def files may be specified on the linker command
          # line like an object file.
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
              return [defsfile]
          # For other targets, discard the .def file.
          return []
  
      def get_gui_app_args(self):
          if self.gcc_type in (GCC_CYGWIN, GCC_MINGW):
              return ['-mwindows']
          return []
  
      def get_instruction_set_args(self, instruction_set):
          return gnulike_instruction_set_args.get(instruction_set, None)
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
  
  class ClangCompiler:
      def __init__(self, clang_type):
          self.id = 'clang'
          self.clang_type = clang_type
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_ndebug', 'b_staticpic', 'b_colorout']
          if self.clang_type != CLANG_OSX:
              self.base_options.append('b_lundef')
          self.base_options.append('b_asneeded')
          # All Clang backends can do assembly and LLVM IR
          self.can_compile_suffixes.update(['ll', 's'])
  
      # TODO: centralise this policy more globally, instead
      # of fragmenting it into GnuCompiler and ClangCompiler
      def get_asneeded_args(self):
          if self.clang_type == CLANG_OSX:
              return APPLE_LD_AS_NEEDED
          else:
              return GNU_LD_AS_NEEDED
  
      def get_pic_args(self):
          if self.clang_type in (CLANG_WIN, CLANG_OSX):
              return [] # On Window and OS X, pic is always on.
          return ['-fPIC']
  
      def get_colorout_args(self, colortype):
          return clang_color_args[colortype][:]
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          if self.clang_type == CLANG_OSX:
              return apple_buildtype_linker_args[buildtype]
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pch'
  
      def get_pch_use_args(self, pch_dir, header):
          # Workaround for Clang bug http://llvm.org/bugs/show_bug.cgi?id=15136
          # This flag is internal to Clang (or at least not documented on the man page)
          # so it might change semantics at any time.
          return ['-include-pch', os.path.join(pch_dir, self.get_pch_name(header))]
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          if self.clang_type == CLANG_STANDARD:
              gcc_type = GCC_STANDARD
          elif self.clang_type == CLANG_OSX:
              gcc_type = GCC_OSX
          elif self.clang_type == CLANG_WIN:
              gcc_type = GCC_MINGW
          else:
              raise MesonException('Unreachable code when converting clang type to gcc type.')
          return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def has_multi_arguments(self, args, env):
          myargs = ['-Werror=unknown-warning-option', '-Werror=unused-command-line-argument']
          if mesonlib.version_compare(self.version, '>=3.6.0'):
              myargs.append('-Werror=ignored-optimization-argument')
          return super().has_multi_arguments(
              myargs + args,
              env)
  
      def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          # Starting with XCode 8, we need to pass this to force linker
          # visibility to obey OS X and iOS minimum version targets with
          # -mmacosx-version-min, -miphoneos-version-min, etc.
          # https://github.com/Homebrew/homebrew-core/issues/3727
          if self.clang_type == CLANG_OSX and version_compare(self.version, '>=8.0'):
              extra_args.append('-Wl,-no_weak_imports')
          return super().has_function(funcname, prefix, env, extra_args, dependencies)
  
      def get_std_shared_module_link_args(self):
          if self.clang_type == CLANG_OSX:
              return ['-bundle', '-Wl,-undefined,dynamic_lookup']
          return ['-shared']
  
      def get_link_whole_for(self, args):
          if self.clang_type == CLANG_OSX:
              result = []
              for a in args:
                  result += ['-Wl,-force_load', a]
              return result
          return ['-Wl,--whole-archive'] + args + ['-Wl,--no-whole-archive']
  
      def get_instruction_set_args(self, instruction_set):
          return gnulike_instruction_set_args.get(instruction_set, None)
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
  
  # Tested on linux for ICC 14.0.3, 15.0.6, 16.0.4, 17.0.1
  class IntelCompiler:
      def __init__(self, icc_type):
          self.id = 'intel'
          self.icc_type = icc_type
          self.lang_header = 'none'
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage',
                               'b_colorout', 'b_ndebug', 'b_staticpic', 'b_lundef', 'b_asneeded']
          # Assembly
          self.can_compile_suffixes.add('s')
  
      def get_pic_args(self):
          return ['-fPIC']
  
      def get_buildtype_args(self, buildtype):
          return gnulike_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          return gnulike_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pchi'
  
      def get_pch_use_args(self, pch_dir, header):
          return ['-pch', '-pch_dir', os.path.join(pch_dir), '-x',
                  self.lang_header, '-include', header, '-x', 'none']
  
      def get_pch_name(self, header_name):
          return os.path.basename(header_name) + '.' + self.get_pch_suffix()
  
      def split_shlib_to_parts(self, fname):
          return os.path.dirname(fname), fname
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          if self.icc_type == ICC_STANDARD:
              gcc_type = GCC_STANDARD
          elif self.icc_type == ICC_OSX:
              gcc_type = GCC_OSX
          elif self.icc_type == ICC_WIN:
              gcc_type = GCC_MINGW
          else:
              raise MesonException('Unreachable code when converting icc type to gcc type.')
          return get_gcc_soname_args(gcc_type, prefix, shlib_name, suffix, path, soversion, is_shared_module)
  
      def get_std_shared_lib_link_args(self):
          # FIXME: Don't know how icc works on OSX
          # if self.icc_type == ICC_OSX:
          #     return ['-bundle']
          return ['-shared']
  
      def get_default_include_dirs(self):
          return gnulike_default_include_dirs(self.exelist, self.language)
  
files: mesonbuild/compilers/compilers.py