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, shutil, subprocess, sys
  from collections import OrderedDict
  
  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_meson_script, get_compiler_for_source
  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):
      for char in ('$', ' ', ':'):
          text = text.replace(char, '$' + char)
      if '\n' in text:
          raise MesonException('Ninja does not support newlines in rules. '
                               'Please report this error with a test case to the Meson bug tracker.')
      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) for i in self.outfilenames]),
              self.rule,
              ' '.join([ninja_quote(i) for i in self.infilenames]))
          if len(self.deps) > 0:
              line += ' | ' + ' '.join([ninja_quote(x) for x in self.deps])
          if len(self.orderdeps) > 0:
              line += ' || ' + ' '.join([ninja_quote(x) 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.
          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
              noq_templ = "%s"
              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 detect_vs_dep_prefix(self, tempfilename):
          '''VS writes its dependency in a locale dependent format.
          Detect the search prefix to use.'''
          # Of course there is another program called 'cl' on
          # some platforms. Let's just require that on Windows
          # cl points to msvc.
          if not mesonlib.is_windows() or shutil.which('cl') is None:
              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
          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 ovewrite 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):
          ninja_exe = environment.detect_ninja()
          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 = [ninja_exe, '-t', 'compdb'] + 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):
                  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 target.link_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():
              tname = t.get_basename() + t.type_suffix()
              if tname 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))
          # If the target requires capturing stdout, then use the serialized
          # executable wrapper to capture that output and save it to a file.
          #
          # If the command line requires a newline, also use the wrapper, as
          # ninja does not support them in its build rule syntax.
          #
          # 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 (target.capture or any('\n' in c for c in cmd) or
                  ((mesonlib.is_windows() or mesonlib.is_cygwin()) and
                   self.determine_windows_extra_paths(target.command[0]))):
              exe_data = self.serialize_executable(target.command[0], cmd[1:],
                                                   # All targets are built from the build dir
                                                   self.environment.get_build_dir(),
                                                   capture=ofilenames[0] if target.capture else None)
              cmd = [sys.executable, 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.name + target.type_suffix()] = True
  
      def generate_run_target(self, target, outfile):
          cmd = [sys.executable, 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))
          elem = NinjaBuildElement(self.all_outputs, target.name, 'CUSTOM_COMMAND', [])
          cmd += [self.environment.get_source_dir(),
                  self.environment.get_build_dir(),
                  target.subdir,
                  get_meson_script(self.environment, 'mesonintrospect')]
          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))]
          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)
          self.processed_targets[target.name + target.type_suffix()] = True
  
      def generate_coverage_rules(self, outfile):
          e = NinjaBuildElement(self.all_outputs, 'coverage', 'CUSTOM_COMMAND', 'PHONY')
          e.add_item('COMMAND', [sys.executable,
                                 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)
          self.generate_coverage_legacy_rules(outfile)
  
      def generate_coverage_legacy_rules(self, outfile):
          (gcovr_exe, lcov_exe, genhtml_exe) = environment.find_coverage_tools()
          added_rule = False
          if gcovr_exe:
              added_rule = True
              elem = NinjaBuildElement(self.all_outputs, 'coverage-xml', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-x', '-r', self.environment.get_source_dir(),
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.xml')])
              elem.add_item('DESC', 'Generating XML coverage report.')
              elem.write(outfile)
              elem = NinjaBuildElement(self.all_outputs, 'coverage-text', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-r', self.environment.get_source_dir(),
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.txt')])
              elem.add_item('DESC', 'Generating text coverage report.')
              elem.write(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, 'coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
              command = [lcov_exe, '--directory', self.environment.get_build_dir(),
                         '--capture', '--output-file', covinfo, '--no-checksum',
                         '&&', 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)
          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,
                          get_meson_script(self.environment, 'mesonintrospect'))
          elem = NinjaBuildElement(self.all_outputs, 'install', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_dep('all')
          elem.add_item('DESC', 'Installing files.')
          elem.add_item('COMMAND', [sys.executable, 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)
  
          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) 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 = os.path.join(self.environment.get_source_dir(), m.get_source_subdir(), f)
                  dstabs = os.path.join(subdir, os.path.split(f)[1] + '.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
              for f in de.sources:
                  assert(isinstance(f, mesonlib.File))
                  plain_f = os.path.split(f.fname)[1]
                  dstabs = os.path.join(subdir, plain_f)
                  i = [f.absolute_path(srcdir, builddir), dstabs, de.install_mode]
                  d.data.append(i)
  
      def generate_subdir_install(self, d):
          for sd in self.build.get_install_subdirs():
              inst_subdir = sd.installable_subdir.rstrip('/')
              idir_parts = inst_subdir.split('/')
              if len(idir_parts) > 1:
                  subdir = os.path.join(sd.source_subdir, '/'.join(idir_parts[:-1]))
                  inst_dir = idir_parts[-1]
              else:
                  subdir = sd.source_subdir
                  inst_dir = sd.installable_subdir
              src_dir = os.path.join(self.environment.get_source_dir(), subdir)
              dst_dir = os.path.join(self.environment.get_prefix(), sd.install_dir)
              d.install_subdirs.append([src_dir, inst_dir, dst_dir, sd.install_mode])
  
      def generate_tests(self, outfile):
          self.serialize_tests()
          test_exe = get_meson_script(self.environment, 'mesontest')
          cmd = [sys.executable, '-u', test_exe, '--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, '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)
  
          # And then benchmarks.
          cmd = [sys.executable, '-u', test_exe, '--benchmark', '--logbase',
                 'benchmarklog', '--num-processes=1', '--no-rebuild']
          elem = NinjaBuildElement(self.all_outputs, '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)
  
      def generate_rules(self, outfile):
          outfile.write('# Rules for compiling.\n\n')
          self.generate_compile_rules(outfile)
          outfile.write('# Rules for linking.\n\n')
          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(sys.executable)),
               ninja_quote(quote_func(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 = %s %s %s %s %s %s --backend ninja\n" % c)
          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 = [s.rel_to_builddir(self.build_to_src) for s in src_list]
          deps = []
          commands = 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]
          elem = NinjaBuildElement(self.all_outputs, outputs, 'cs_COMPILER', rel_srcs)
          elem.add_dep(deps)
          elem.add_item('ARGS', commands)
          elem.write(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 target.link_targets:
              for i in dep.sources:
                  if hasattr(i, 'fname'):
                      i = i.fname
                  if i.endswith('vala'):
                      vapiname = dep.name + '.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, .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'):
                  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'):
                      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 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())
          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), the subdir path
              # components will be preserved in the output path. But if the Vala
              # file is outside the build directory, the path components will be
              # stripped and just the basename will be used.
              if isinstance(gensrc, (build.CustomTarget, build.GeneratedList)) or gensrc.is_built:
                  vala_c_file = os.path.splitext(vala_file)[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)
          # 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 += ['-d', c_out_dir]
          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 += ['-H', 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 += 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
          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 '/' in target.name or '\\' in 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.split(target.name)[0],
                                                                 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.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')]
          element = NinjaBuildElement(self.all_outputs, target_name, 'rust_COMPILER', 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)
          link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target)))
          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]
          (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.split(i)[1]
              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):
          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)
          outfile.write(description)
  
      def generate_dynamic_link_rules(self, outfile):
          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.'
                  outfile.write(rule)
                  outfile.write(command)
                  outfile.write(description)
                  outfile.write('\n')
          outfile.write('\n')
          symrule = 'rule SHSYM\n'
          symcmd = ' command = "%s" "%s" %s %s %s %s $CROSS\n' % (ninja_quote(sys.executable),
                                                                  self.environment.get_build_command(),
                                                                  '--internal',
                                                                  'symbolextractor',
                                                                  '$in',
                                                                  '$out')
          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()])
          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):
          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 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(sys.executable),
                      ninja_quote(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':
              if not is_cross:
                  self.generate_rust_compile_rules(compiler, outfile)
              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,
          # so write rules for GeneratedLists here
          for genlist in target.get_generated_sources():
              if isinstance(genlist, build.CustomTarget):
                  continue
              self.generate_genlist_for_target(genlist, target, outfile)
  
      def replace_paths(self, target, args):
          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]
          return args
  
      def generate_genlist_for_target(self, genlist, target, outfile):
          generator = genlist.get_generator()
          exe = generator.get_exe()
          exe_arr = self.exe_object_to_cmd_array(exe)
          infilelist = genlist.get_inputs()
          outfilelist = genlist.get_outputs()
          base_args = generator.get_arglist()
          extra_dependencies = [os.path.join(self.build_to_src, i) for i in genlist.extra_depends]
          source_target_dir = self.get_target_source_dir(target)
          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)
              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):]
              relout = self.get_target_private_dir(target)
              args = self.replace_paths(target, args)
              cmdlist = exe_arr + self.replace_extra_args(args, genlist)
              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 $out')
              if isinstance(exe, build.BuildTarget):
                  elem.add_dep(self.get_target_filename(exe))
              elem.add_item('COMMAND', cmdlist)
              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())
              with open(filename) 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.split(src)[1]:
                          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):
                  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 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 and the custom target 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.
          commands += self.get_source_dir_include_args(target, compiler)
          commands += self.get_custom_target_dir_include_args(target, compiler)
          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)
  
          if isinstance(src, mesonlib.File) and src.is_built:
              rel_src = os.path.join(src.subdir, src.fname)
              if os.path.isabs(rel_src):
                  assert(rel_src.startswith(self.environment.get_build_dir()))
                  rel_src = rel_src[len(self.environment.get_build_dir()) + 1:]
              abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
          elif isinstance(src, mesonlib.File):
              rel_src = src.rel_to_builddir(self.build_to_src)
              abs_src = src.absolute_path(self.environment.get_source_dir(),
                                          self.environment.get_build_dir())
          elif is_generated:
              raise AssertionError('BUG: broken generated source file handling for {!r}'.format(src))
          else:
              if isinstance(src, File):
                  rel_src = src.rel_to_builddir(self.build_to_src)
              else:
                  raise InvalidArguments('Invalid source type: {!r}'.format(src))
              abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
          if isinstance(src, File):
              if src.is_built:
                  src_filename = os.path.join(src.subdir, src.fname)
                  if os.path.isabs(src_filename):
                      assert(src_filename.startswith(self.environment.get_build_dir()))
                      src_filename = src_filename[len(self.environment.get_build_dir()) + 1:]
              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()
          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:
                  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))
  
          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 '/' in fname or '\\' in 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 dependendy 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 RuntimeError('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.split(header)[1]
          (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 = []
          commands += self.generate_basic_compiler_args(target, compiler)
          dst = os.path.join(self.get_target_private_dir(target),
                             os.path.split(pch)[-1] + '.' + 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 in pch[0] or '/' not in 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()
          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(target.subdir, 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 overriden
          commands += self.get_cross_stdlib_link_args(target, linker)
          # Add things like /NOLOGO; usually can't be overriden
          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()
          # 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 '/' in target.name or '\\' in 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.split(target.name)[0],
                  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.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, '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', [sys.executable,
                                 self.environment.get_build_command(),
                                 '--internal', 'cleantrees', d_file])
          e.add_item('description', 'Cleaning custom target directories.')
          e.write(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, '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', [sys.executable, clean_script, '.', 'gcno'])
              gcno_elem.add_item('description', 'Deleting gcno files.')
              gcno_elem.write(outfile)
  
              gcda_elem = NinjaBuildElement(self.all_outputs, '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', [sys.executable, clean_script, '.', 'gcda'])
              gcda_elem.add_item('description', 'Deleting gcda files.')
              gcda_elem.write(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, 'dist', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('DESC', 'Creating source packages')
          elem.add_item('COMMAND', [sys.executable,
                                    self.environment.get_build_command(),
                                    '--internal', 'dist',
                                    self.environment.source_dir,
                                    self.environment.build_dir,
                                    sys.executable,
                                    self.environment.get_build_command()])
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
      # For things like scan-build and other helper tools we might have.
      def generate_utils(self, outfile):
          cmd = [sys.executable, self.environment.get_build_command(),
                 '--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir,
                 sys.executable, self.environment.get_build_command()] + self.get_user_option_args()
          elem = NinjaBuildElement(self.all_outputs, 'scan-build', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          cmd = [sys.executable, self.environment.get_build_command(),
                 '--internal', 'uninstall']
          elem = NinjaBuildElement(self.all_outputs, 'uninstall', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(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)
  
          ninja_command = environment.detect_ninja()
          if ninja_command is None:
              raise MesonException('Could not detect Ninja v1.6 or newer')
          elem = NinjaBuildElement(self.all_outputs, 'clean', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', [ninja_command, '-t', 'clean'])
          elem.add_item('description', 'Cleaning.')
  
          # 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)
  
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, shutil, subprocess, sys
  from collections import OrderedDict
  
  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_meson_script, get_compiler_for_source
  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):
      for char in ('$', ' ', ':'):
          text = text.replace(char, '$' + char)
      if '\n' in text:
          raise MesonException('Ninja does not support newlines in rules. '
                               'Please report this error with a test case to the Meson bug tracker.')
      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) for i in self.outfilenames]),
              self.rule,
              ' '.join([ninja_quote(i) for i in self.infilenames]))
          if len(self.deps) > 0:
              line += ' | ' + ' '.join([ninja_quote(x) for x in self.deps])
          if len(self.orderdeps) > 0:
              line += ' || ' + ' '.join([ninja_quote(x) 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.
          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
              noq_templ = "%s"
              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 detect_vs_dep_prefix(self, tempfilename):
          '''VS writes its dependency in a locale dependent format.
          Detect the search prefix to use.'''
          # Of course there is another program called 'cl' on
          # some platforms. Let's just require that on Windows
          # cl points to msvc.
          if not mesonlib.is_windows() or shutil.which('cl') is None:
              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
          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 ovewrite 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):
          ninja_exe = environment.detect_ninja()
          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 = [ninja_exe, '-t', 'compdb'] + 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):
                  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 target.link_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():
              tname = t.get_basename() + t.type_suffix()
              if tname 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))
          # If the target requires capturing stdout, then use the serialized
          # executable wrapper to capture that output and save it to a file.
          #
          # If the command line requires a newline, also use the wrapper, as
          # ninja does not support them in its build rule syntax.
          #
          # 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 (target.capture or any('\n' in c for c in cmd) or
                  ((mesonlib.is_windows() or mesonlib.is_cygwin()) and
                   self.determine_windows_extra_paths(target.command[0]))):
              exe_data = self.serialize_executable(target.command[0], cmd[1:],
                                                   # All targets are built from the build dir
                                                   self.environment.get_build_dir(),
                                                   capture=ofilenames[0] if target.capture else None)
              cmd = [sys.executable, 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.name + target.type_suffix()] = True
  
      def generate_run_target(self, target, outfile):
          cmd = [sys.executable, 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))
          elem = NinjaBuildElement(self.all_outputs, target.name, 'CUSTOM_COMMAND', [])
          cmd += [self.environment.get_source_dir(),
                  self.environment.get_build_dir(),
                  target.subdir,
                  get_meson_script(self.environment, 'mesonintrospect')]
          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))]
          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)
          self.processed_targets[target.name + target.type_suffix()] = True
  
      def generate_coverage_rules(self, outfile):
          e = NinjaBuildElement(self.all_outputs, 'coverage', 'CUSTOM_COMMAND', 'PHONY')
          e.add_item('COMMAND', [sys.executable,
                                 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)
          self.generate_coverage_legacy_rules(outfile)
  
      def generate_coverage_legacy_rules(self, outfile):
          (gcovr_exe, lcov_exe, genhtml_exe) = environment.find_coverage_tools()
          added_rule = False
          if gcovr_exe:
              added_rule = True
              elem = NinjaBuildElement(self.all_outputs, 'coverage-xml', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-x', '-r', self.environment.get_source_dir(),
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.xml')])
              elem.add_item('DESC', 'Generating XML coverage report.')
              elem.write(outfile)
              elem = NinjaBuildElement(self.all_outputs, 'coverage-text', 'CUSTOM_COMMAND', '')
              elem.add_item('COMMAND', [gcovr_exe, '-r', self.environment.get_source_dir(),
                                        '-o', os.path.join(self.environment.get_log_dir(), 'coverage.txt')])
              elem.add_item('DESC', 'Generating text coverage report.')
              elem.write(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, 'coverage-html', 'phony', os.path.join(htmloutdir, 'index.html'))
              phony_elem.write(outfile)
              elem = NinjaBuildElement(self.all_outputs, os.path.join(htmloutdir, 'index.html'), 'CUSTOM_COMMAND', '')
              command = [lcov_exe, '--directory', self.environment.get_build_dir(),
                         '--capture', '--output-file', covinfo, '--no-checksum',
                         '&&', 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)
          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,
                          get_meson_script(self.environment, 'mesonintrospect'))
          elem = NinjaBuildElement(self.all_outputs, 'install', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_dep('all')
          elem.add_item('DESC', 'Installing files.')
          elem.add_item('COMMAND', [sys.executable, 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)
  
          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) 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 = os.path.join(self.environment.get_source_dir(), m.get_source_subdir(), f)
                  dstabs = os.path.join(subdir, os.path.split(f)[1] + '.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
              for f in de.sources:
                  assert(isinstance(f, mesonlib.File))
                  plain_f = os.path.split(f.fname)[1]
                  dstabs = os.path.join(subdir, plain_f)
                  i = [f.absolute_path(srcdir, builddir), dstabs, de.install_mode]
                  d.data.append(i)
  
      def generate_subdir_install(self, d):
          for sd in self.build.get_install_subdirs():
              inst_subdir = sd.installable_subdir.rstrip('/')
              idir_parts = inst_subdir.split('/')
              if len(idir_parts) > 1:
                  subdir = os.path.join(sd.source_subdir, '/'.join(idir_parts[:-1]))
                  inst_dir = idir_parts[-1]
              else:
                  subdir = sd.source_subdir
                  inst_dir = sd.installable_subdir
              src_dir = os.path.join(self.environment.get_source_dir(), subdir)
              dst_dir = os.path.join(self.environment.get_prefix(), sd.install_dir)
              d.install_subdirs.append([src_dir, inst_dir, dst_dir, sd.install_mode])
  
      def generate_tests(self, outfile):
          self.serialize_tests()
          test_exe = get_meson_script(self.environment, 'mesontest')
          cmd = [sys.executable, '-u', test_exe, '--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, '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)
  
          # And then benchmarks.
          cmd = [sys.executable, '-u', test_exe, '--benchmark', '--logbase',
                 'benchmarklog', '--num-processes=1', '--no-rebuild']
          elem = NinjaBuildElement(self.all_outputs, '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)
  
      def generate_rules(self, outfile):
          outfile.write('# Rules for compiling.\n\n')
          self.generate_compile_rules(outfile)
          outfile.write('# Rules for linking.\n\n')
          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(sys.executable)),
               ninja_quote(quote_func(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 = %s %s %s %s %s %s --backend ninja\n" % c)
          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 = [s.rel_to_builddir(self.build_to_src) for s in src_list]
          deps = []
          commands = 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]
          elem = NinjaBuildElement(self.all_outputs, outputs, 'cs_COMPILER', rel_srcs)
          elem.add_dep(deps)
          elem.add_item('ARGS', commands)
          elem.write(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 target.link_targets:
              for i in dep.sources:
                  if hasattr(i, 'fname'):
                      i = i.fname
                  if i.endswith('vala'):
                      vapiname = dep.name + '.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, .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'):
                  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'):
                      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 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())
          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), the subdir path
              # components will be preserved in the output path. But if the Vala
              # file is outside the build directory, the path components will be
              # stripped and just the basename will be used.
              if isinstance(gensrc, (build.CustomTarget, build.GeneratedList)) or gensrc.is_built:
                  vala_c_file = os.path.splitext(vala_file)[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)
          # 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 += ['-d', c_out_dir]
          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 += ['-H', 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 += 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
          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 '/' in target.name or '\\' in 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.split(target.name)[0],
                                                                 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.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')]
          element = NinjaBuildElement(self.all_outputs, target_name, 'rust_COMPILER', 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)
          link_args = swiftc.get_output_args(os.path.join(self.environment.get_build_dir(), self.get_target_filename(target)))
          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]
          (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.split(i)[1]
              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):
          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)
          outfile.write(description)
  
      def generate_dynamic_link_rules(self, outfile):
          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.'
                  outfile.write(rule)
                  outfile.write(command)
                  outfile.write(description)
                  outfile.write('\n')
          outfile.write('\n')
          symrule = 'rule SHSYM\n'
          symcmd = ' command = "%s" "%s" %s %s %s %s $CROSS\n' % (ninja_quote(sys.executable),
                                                                  self.environment.get_build_command(),
                                                                  '--internal',
                                                                  'symbolextractor',
                                                                  '$in',
                                                                  '$out')
          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()])
          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):
          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 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(sys.executable),
                      ninja_quote(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':
              if not is_cross:
                  self.generate_rust_compile_rules(compiler, outfile)
              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' % langname.title()
          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,
          # so write rules for GeneratedLists here
          for genlist in target.get_generated_sources():
              if isinstance(genlist, build.CustomTarget):
                  continue
              self.generate_genlist_for_target(genlist, target, outfile)
  
      def replace_paths(self, target, args):
          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]
          return args
  
      def generate_genlist_for_target(self, genlist, target, outfile):
          generator = genlist.get_generator()
          exe = generator.get_exe()
          exe_arr = self.exe_object_to_cmd_array(exe)
          infilelist = genlist.get_inputs()
          outfilelist = genlist.get_outputs()
          base_args = generator.get_arglist()
          extra_dependencies = [os.path.join(self.build_to_src, i) for i in genlist.extra_depends]
          source_target_dir = self.get_target_source_dir(target)
          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)
              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):]
              relout = self.get_target_private_dir(target)
              args = self.replace_paths(target, args)
              cmdlist = exe_arr + self.replace_extra_args(args, genlist)
              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 $out')
              if isinstance(exe, build.BuildTarget):
                  elem.add_dep(self.get_target_filename(exe))
              elem.add_item('COMMAND', cmdlist)
              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())
              with open(filename) 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.split(src)[1]:
                          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):
                  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 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 and the custom target 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.
          commands += self.get_source_dir_include_args(target, compiler)
          commands += self.get_custom_target_dir_include_args(target, compiler)
          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)
  
          if isinstance(src, mesonlib.File) and src.is_built:
              rel_src = os.path.join(src.subdir, src.fname)
              if os.path.isabs(rel_src):
                  assert(rel_src.startswith(self.environment.get_build_dir()))
                  rel_src = rel_src[len(self.environment.get_build_dir()) + 1:]
              abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
          elif isinstance(src, mesonlib.File):
              rel_src = src.rel_to_builddir(self.build_to_src)
              abs_src = src.absolute_path(self.environment.get_source_dir(),
                                          self.environment.get_build_dir())
          elif is_generated:
              raise AssertionError('BUG: broken generated source file handling for {!r}'.format(src))
          else:
              if isinstance(src, File):
                  rel_src = src.rel_to_builddir(self.build_to_src)
              else:
                  raise InvalidArguments('Invalid source type: {!r}'.format(src))
              abs_src = os.path.join(self.environment.get_build_dir(), rel_src)
          if isinstance(src, File):
              if src.is_built:
                  src_filename = os.path.join(src.subdir, src.fname)
                  if os.path.isabs(src_filename):
                      assert(src_filename.startswith(self.environment.get_build_dir()))
                      src_filename = src_filename[len(self.environment.get_build_dir()) + 1:]
              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()
          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:
                  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))
  
          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 '/' in fname or '\\' in 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 dependendy 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 RuntimeError('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.split(header)[1]
          (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 = []
          commands += self.generate_basic_compiler_args(target, compiler)
          dst = os.path.join(self.get_target_private_dir(target),
                             os.path.split(pch)[-1] + '.' + 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 in pch[0] or '/' not in 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()
          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(target.subdir, 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 overriden
          commands += self.get_cross_stdlib_link_args(target, linker)
          # Add things like /NOLOGO; usually can't be overriden
          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()
          # 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 '/' in target.name or '\\' in 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.split(target.name)[0],
                  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.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, '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', [sys.executable,
                                 self.environment.get_build_command(),
                                 '--internal', 'cleantrees', d_file])
          e.add_item('description', 'Cleaning custom target directories.')
          e.write(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, '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', [sys.executable, clean_script, '.', 'gcno'])
              gcno_elem.add_item('description', 'Deleting gcno files.')
              gcno_elem.write(outfile)
  
              gcda_elem = NinjaBuildElement(self.all_outputs, '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', [sys.executable, clean_script, '.', 'gcda'])
              gcda_elem.add_item('description', 'Deleting gcda files.')
              gcda_elem.write(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, 'dist', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('DESC', 'Creating source packages')
          elem.add_item('COMMAND', [sys.executable,
                                    self.environment.get_build_command(),
                                    '--internal', 'dist',
                                    self.environment.source_dir,
                                    self.environment.build_dir,
                                    sys.executable,
                                    self.environment.get_build_command()])
          elem.add_item('pool', 'console')
          elem.write(outfile)
  
      # For things like scan-build and other helper tools we might have.
      def generate_utils(self, outfile):
          cmd = [sys.executable, self.environment.get_build_command(),
                 '--internal', 'scanbuild', self.environment.source_dir, self.environment.build_dir,
                 sys.executable, self.environment.get_build_command()] + self.get_user_option_args()
          elem = NinjaBuildElement(self.all_outputs, 'scan-build', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(outfile)
          cmd = [sys.executable, self.environment.get_build_command(),
                 '--internal', 'uninstall']
          elem = NinjaBuildElement(self.all_outputs, 'uninstall', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', cmd)
          elem.add_item('pool', 'console')
          elem.write(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)
  
          ninja_command = environment.detect_ninja()
          if ninja_command is None:
              raise MesonException('Could not detect Ninja v1.6 or newer')
          elem = NinjaBuildElement(self.all_outputs, 'clean', 'CUSTOM_COMMAND', 'PHONY')
          elem.add_item('COMMAND', [ninja_command, '-t', 'clean'])
          elem.add_item('description', 'Cleaning.')
  
          # 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)
  
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 subprocess, os.path, tempfile
  
  from .. import mlog
  from .. import coredata
  from ..mesonlib import EnvironmentException, version_compare, Popen_safe
  
  from .compilers import (
      GCC_MINGW,
      get_largefile_args,
      gnu_winlibs,
      msvc_buildtype_args,
      msvc_buildtype_linker_args,
      msvc_winlibs,
      ClangCompiler,
      Compiler,
      CompilerArgs,
      CrossNoRunException,
      GnuCompiler,
      IntelCompiler,
      RunResult,
  )
  
  
  class CCompiler(Compiler):
      def __init__(self, exelist, version, is_cross, exe_wrapper=None):
          # If a child ObjC or CPP class has already set it, don't set it ourselves
          if not hasattr(self, 'language'):
              self.language = 'c'
          super().__init__(exelist, version)
          self.id = 'unknown'
          self.is_cross = is_cross
          self.can_compile_suffixes.add('h')
          if isinstance(exe_wrapper, str):
              self.exe_wrapper = [exe_wrapper]
          else:
              self.exe_wrapper = exe_wrapper
  
      def needs_static_linker(self):
          return True # When compiling static libraries, so yes.
  
      def get_always_args(self):
          '''
          Args that are always-on for all C compilers other than MSVC
          '''
          return ['-pipe'] + get_largefile_args(self)
  
      def get_linker_debug_crt_args(self):
          """
          Arguments needed to select a debug crt for the linker
          This is only needed for MSVC
          """
          return []
  
      def get_no_stdinc_args(self):
          return ['-nostdinc']
  
      def get_no_stdlib_link_args(self):
          return ['-nostdlib']
  
      def get_warn_args(self, level):
          return self.warn_args[level]
  
      def get_no_warn_args(self):
          # Almost every compiler uses this for disabling warnings
          return ['-w']
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return []
  
      def split_shlib_to_parts(self, fname):
          return None, fname
  
      # The default behavior is this, override in MSVC
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return self.build_unix_rpath_args(build_dir, from_dir, rpath_paths, install_rpath)
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return ['-MMD', '-MQ', outtarget, '-MF', outfile]
  
      def depfile_for_object(self, objfile):
          return objfile + '.' + self.get_depfile_suffix()
  
      def get_depfile_suffix(self):
          return 'd'
  
      def get_exelist(self):
          return self.exelist[:]
  
      def get_linker_exelist(self):
          return self.exelist[:]
  
      def get_preprocess_only_args(self):
          return ['-E', '-P']
  
      def get_compile_only_args(self):
          return ['-c']
  
      def get_no_optimization_args(self):
          return ['-O0']
  
      def get_compiler_check_args(self):
          '''
          Get arguments useful for compiler checks such as being permissive in
          the code quality and not doing any optimization.
          '''
          return self.get_no_optimization_args()
  
      def get_output_args(self, target):
          return ['-o', target]
  
      def get_linker_output_args(self, outputname):
          return ['-o', outputname]
  
      def get_coverage_args(self):
          return ['--coverage']
  
      def get_coverage_link_args(self):
          return ['--coverage']
  
      def get_werror_args(self):
          return ['-Werror']
  
      def get_std_exe_link_args(self):
          return []
  
      def get_include_args(self, path, is_system):
          if path == '':
              path = '.'
          if is_system:
              return ['-isystem', path]
          return ['-I' + path]
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def get_library_dirs(self):
          stdo = Popen_safe(self.exelist + ['--print-search-dirs'])[1]
          for line in stdo.split('\n'):
              if line.startswith('libraries:'):
                  libstr = line.split('=', 1)[1]
                  return libstr.split(':')
          return []
  
      def get_pic_args(self):
          return ['-fPIC']
  
      def name_string(self):
          return ' '.join(self.exelist)
  
      def get_pch_use_args(self, pch_dir, header):
          return ['-include', os.path.split(header)[-1]]
  
      def get_pch_name(self, header_name):
          return os.path.split(header_name)[-1] + '.' + self.get_pch_suffix()
  
      def get_linker_search_args(self, dirname):
          return ['-L' + dirname]
  
      def gen_import_library_args(self, implibname):
          """
          The name of the outputted import library
  
          This implementation is used only on Windows by compilers that use GNU ld
          """
          return ['-Wl,--out-implib=' + implibname]
  
      def sanity_check_impl(self, work_dir, environment, sname, code):
          mlog.debug('Sanity testing ' + self.get_display_language() + ' compiler:', ' '.join(self.exelist))
          mlog.debug('Is cross compiler: %s.' % str(self.is_cross))
  
          extra_flags = []
          source_name = os.path.join(work_dir, sname)
          binname = sname.rsplit('.', 1)[0]
          if self.is_cross:
              binname += '_cross'
              if self.exe_wrapper is None:
                  # Linking cross built apps is painful. You can't really
                  # tell if you should use -nostdlib or not and for example
                  # on OSX the compiler binary is the same but you need
                  # a ton of compiler flags to differentiate between
                  # arm and x86_64. So just compile.
                  extra_flags += self.get_cross_extra_flags(environment, link=False)
                  extra_flags += self.get_compile_only_args()
              else:
                  extra_flags += self.get_cross_extra_flags(environment, link=True)
          # Is a valid executable output for all toolchains and platforms
          binname += '.exe'
          # Write binary check source
          binary_name = os.path.join(work_dir, binname)
          with open(source_name, 'w') as ofile:
              ofile.write(code)
          # Compile sanity check
          cmdlist = self.exelist + extra_flags + [source_name] + self.get_output_args(binary_name)
          pc, stdo, stde = Popen_safe(cmdlist, cwd=work_dir)
          mlog.debug('Sanity check compiler command line:', ' '.join(cmdlist))
          mlog.debug('Sanity check compile stdout:')
          mlog.debug(stdo)
          mlog.debug('-----\nSanity check compile stderr:')
          mlog.debug(stde)
          mlog.debug('-----')
          if pc.returncode != 0:
              raise EnvironmentException('Compiler {0} can not compile programs.'.format(self.name_string()))
          # Run sanity check
          if self.is_cross:
              if self.exe_wrapper is None:
                  # Can't check if the binaries run so we have to assume they do
                  return
              cmdlist = self.exe_wrapper + [binary_name]
          else:
              cmdlist = [binary_name]
          mlog.debug('Running test binary command: ' + ' '.join(cmdlist))
          pe = subprocess.Popen(cmdlist)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by {0} compiler {1} are not runnable.'.format(self.language, self.name_string()))
  
      def sanity_check(self, work_dir, environment):
          code = 'int main(int argc, char **argv) { int class=0; return class; }\n'
          return self.sanity_check_impl(work_dir, environment, 'sanitycheckc.c', code)
  
      def has_header(self, hname, prefix, env, extra_args=None, dependencies=None):
          fargs = {'prefix': prefix, 'header': hname}
          code = '''{prefix}
          #ifdef __has_include
           #if !__has_include("{header}")
            #error "Header '{header}' could not be found"
           #endif
          #else
           #include <{header}>
          #endif'''
          return self.compiles(code.format(**fargs), env, extra_args,
                               dependencies, 'preprocess')
  
      def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):
          fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
          t = '''{prefix}
          #include <{header}>
          int main () {{
              /* If it's not defined as a macro, try to use as a symbol */
              #ifndef {symbol}
                  {symbol};
              #endif
          }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def _get_compiler_check_args(self, env, extra_args, dependencies, mode='compile'):
          if extra_args is None:
              extra_args = []
          elif isinstance(extra_args, str):
              extra_args = [extra_args]
          if dependencies is None:
              dependencies = []
          elif not isinstance(dependencies, list):
              dependencies = [dependencies]
          # Collect compiler arguments
          args = CompilerArgs(self)
          for d in dependencies:
              # Add compile flags needed by dependencies
              args += d.get_compile_args()
              if mode == 'link':
                  # Add link flags needed to find dependencies
                  args += d.get_link_args()
          # Select a CRT if needed since we're linking
          if mode == 'link':
              args += self.get_linker_debug_crt_args()
          # Read c_args/cpp_args/etc from the cross-info file (if needed)
          args += self.get_cross_extra_flags(env, link=(mode == 'link'))
          if not self.is_cross:
              if mode == 'preprocess':
                  # Add CPPFLAGS from the env.
                  args += env.coredata.external_preprocess_args[self.language]
              elif mode == 'compile':
                  # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS from the env
                  args += env.coredata.external_args[self.language]
              elif mode == 'link':
                  # Add LDFLAGS from the env
                  args += env.coredata.external_link_args[self.language]
          args += self.get_compiler_check_args()
          # extra_args must override all other arguments, so we add them last
          args += extra_args
          return args
  
      def compiles(self, code, env, extra_args=None, dependencies=None, mode='compile'):
          args = self._get_compiler_check_args(env, extra_args, dependencies, mode)
          # We only want to compile; not link
          with self.compile(code, args.to_native(), mode) as p:
              return p.returncode == 0
  
      def _links_wrapper(self, code, env, extra_args, dependencies):
          "Shares common code between self.links and self.run"
          args = self._get_compiler_check_args(env, extra_args, dependencies, mode='link')
          return self.compile(code, args)
  
      def links(self, code, env, extra_args=None, dependencies=None):
          with self._links_wrapper(code, env, extra_args, dependencies) as p:
              return p.returncode == 0
  
      def run(self, code, env, extra_args=None, dependencies=None):
          if self.is_cross and self.exe_wrapper is None:
              raise CrossNoRunException('Can not run test applications in this cross environment.')
          with self._links_wrapper(code, env, extra_args, dependencies) as p:
              if p.returncode != 0:
                  mlog.debug('Could not compile test file %s: %d\n' % (
                      p.input_name,
                      p.returncode))
                  return RunResult(False)
              if self.is_cross:
                  cmdlist = self.exe_wrapper + [p.output_name]
              else:
                  cmdlist = p.output_name
              try:
                  pe, so, se = Popen_safe(cmdlist)
              except Exception as e:
                  mlog.debug('Could not run: %s (error: %s)\n' % (cmdlist, e))
                  return RunResult(False)
  
          mlog.debug('Program stdout:\n')
          mlog.debug(so)
          mlog.debug('Program stderr:\n')
          mlog.debug(se)
          return RunResult(True, pe.returncode, so, se)
  
      def _compile_int(self, expression, prefix, env, extra_args, dependencies):
          fargs = {'prefix': prefix, 'expression': expression}
          t = '''#include <stdio.h>
          {prefix}
          int main() {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def cross_compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies):
          if isinstance(guess, int):
              if self._compile_int('%s == %d' % (expression, guess), prefix, env, extra_args, dependencies):
                  return guess
  
          cur = low
          while low < high:
              cur = int((low + high) / 2)
              if cur == low:
                  break
  
              if self._compile_int('%s >= %d' % (expression, cur), prefix, env, extra_args, dependencies):
                  low = cur
              else:
                  high = cur
  
          if self._compile_int('%s == %d' % (expression, cur), prefix, env, extra_args, dependencies):
              return cur
          raise EnvironmentException('Cross-compile check overflowed')
  
      def compute_int(self, expression, low, high, guess, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          if self.is_cross:
              return self.cross_compute_int(expression, low, high, guess, prefix, env, extra_args, dependencies)
          fargs = {'prefix': prefix, 'expression': expression}
          t = '''#include<stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              printf("%ld\\n", (long)({expression}));
              return 0;
          }};'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              return -1
          if res.returncode != 0:
              raise EnvironmentException('Could not run compute_int test binary.')
          return int(res.stdout)
  
      def cross_sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              {type} something;
          }}'''
          if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
              return -1
          return self.cross_compute_int('sizeof(%s)' % typename, 1, 128, None, prefix, env, extra_args, dependencies)
  
      def sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          if self.is_cross:
              return self.cross_sizeof(typename, prefix, env, extra_args, dependencies)
          t = '''#include<stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              printf("%ld\\n", (long)(sizeof({type})));
              return 0;
          }};'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              return -1
          if res.returncode != 0:
              raise EnvironmentException('Could not run sizeof test binary.')
          return int(res.stdout)
  
      def cross_alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              {type} something;
          }}'''
          if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
              return -1
          t = '''#include <stddef.h>
          {prefix}
          struct tmp {{
              char c;
              {type} target;
          }};'''
          return self.cross_compute_int('offsetof(struct tmp, target)', 1, 1024, None, t.format(**fargs), env, extra_args, dependencies)
  
      def alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          if self.is_cross:
              return self.cross_alignment(typename, prefix, env, extra_args, dependencies)
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          #include <stddef.h>
          {prefix}
          struct tmp {{
              char c;
              {type} target;
          }};
          int main(int argc, char **argv) {{
              printf("%d", (int)offsetof(struct tmp, target));
              return 0;
          }}'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              raise EnvironmentException('Could not compile alignment test.')
          if res.returncode != 0:
              raise EnvironmentException('Could not run alignment test binary.')
          align = int(res.stdout)
          if align == 0:
              raise EnvironmentException('Could not determine alignment of %s. Sorry. You might want to file a bug.' % typename)
          return align
  
      def get_define(self, dname, prefix, env, extra_args, dependencies):
          delim = '"MESON_GET_DEFINE_DELIMITER"'
          fargs = {'prefix': prefix, 'define': dname, 'delim': delim}
          code = '''
          {prefix}
          #ifndef {define}
          # define {define}
          #endif
          {delim}\n{define}'''
          args = self._get_compiler_check_args(env, extra_args, dependencies,
                                               mode='preprocess').to_native()
          with self.compile(code.format(**fargs), args, 'preprocess') as p:
              if p.returncode != 0:
                  raise EnvironmentException('Could not get define {!r}'.format(dname))
          # Get the preprocessed value after the delimiter,
          # minus the extra newline at the end
          return p.stdo.split(delim + '\n')[-1][:-1]
  
      @staticmethod
      def _no_prototype_templ():
          """
          Try to find the function without a prototype from a header by defining
          our own dummy prototype and trying to link with the C library (and
          whatever else the compiler links in by default). This is very similar
          to the check performed by Autoconf for AC_CHECK_FUNCS.
          """
          # Define the symbol to something else since it is defined by the
          # includes or defines listed by the user or by the compiler. This may
          # include, for instance _GNU_SOURCE which must be defined before
          # limits.h, which includes features.h
          # Then, undef the symbol to get rid of it completely.
          head = '''
          #define {func} meson_disable_define_of_{func}
          {prefix}
          #include <limits.h>
          #undef {func}
          '''
          # Override any GCC internal prototype and declare our own definition for
          # the symbol. Use char because that's unlikely to be an actual return
          # value for a function which ensures that we override the definition.
          head += '''
          #ifdef __cplusplus
          extern "C"
          #endif
          char {func} ();
          '''
          # The actual function call
          main = '''
          int main () {{
            return {func} ();
          }}'''
          return head, main
  
      @staticmethod
      def _have_prototype_templ():
          """
          Returns a head-er and main() call that uses the headers listed by the
          user for the function prototype while checking if a function exists.
          """
          # Add the 'prefix', aka defines, includes, etc that the user provides
          # This may include, for instance _GNU_SOURCE which must be defined
          # before limits.h, which includes features.h
          head = '{prefix}\n#include <limits.h>\n'
          # We don't know what the function takes or returns, so return it as an int.
          # Just taking the address or comparing it to void is not enough because
          # compilers are smart enough to optimize it away. The resulting binary
          # is not run so we don't care what the return value is.
          main = '''\nint main() {{
              void *a = (void*) &{func};
              long b = (long) a;
              return (int) b;
          }}'''
          return head, main
  
      def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
          """
          First, this function looks for the symbol in the default libraries
          provided by the compiler (stdlib + a few others usually). If that
          fails, it checks if any of the headers specified in the prefix provide
          an implementation of the function, and if that fails, it checks if it's
          implemented as a compiler-builtin.
          """
          if extra_args is None:
              extra_args = []
  
          # Short-circuit if the check is already provided by the cross-info file
          varname = 'has function ' + funcname
          varname = varname.replace(' ', '_')
          if self.is_cross:
              val = env.cross_info.config['properties'].get(varname, None)
              if val is not None:
                  if isinstance(val, bool):
                      return val
                  raise EnvironmentException('Cross variable {0} is not a boolean.'.format(varname))
  
          fargs = {'prefix': prefix, 'func': funcname}
  
          # glibc defines functions that are not available on Linux as stubs that
          # fail with ENOSYS (such as e.g. lchmod). In this case we want to fail
          # instead of detecting the stub as a valid symbol.
          # We already included limits.h earlier to ensure that these are defined
          # for stub functions.
          stubs_fail = '''
          #if defined __stub_{func} || defined __stub___{func}
          fail fail fail this function is not going to work
          #endif
          '''
  
          # If we have any includes in the prefix supplied by the user, assume
          # that the user wants us to use the symbol prototype defined in those
          # includes. If not, then try to do the Autoconf-style check with
          # a dummy prototype definition of our own.
          # This is needed when the linker determines symbol availability from an
          # SDK based on the prototype in the header provided by the SDK.
          # Ignoring this prototype would result in the symbol always being
          # marked as available.
          if '#include' in prefix:
              head, main = self._have_prototype_templ()
          else:
              head, main = self._no_prototype_templ()
          templ = head + stubs_fail + main
  
          if self.links(templ.format(**fargs), env, extra_args, dependencies):
              return True
  
          # MSVC does not have compiler __builtin_-s.
          if self.get_id() == 'msvc':
              return False
  
          # Detect function as a built-in
          #
          # Some functions like alloca() are defined as compiler built-ins which
          # are inlined by the compiler and you can't take their address, so we
          # need to look for them differently. On nice compilers like clang, we
          # can just directly use the __has_builtin() macro.
          fargs['no_includes'] = '#include' not in prefix
          t = '''{prefix}
          int main() {{
          #ifdef __has_builtin
              #if !__has_builtin(__builtin_{func})
                  #error "__builtin_{func} not found"
              #endif
          #elif ! defined({func})
              /* Check for __builtin_{func} only if no includes were added to the
               * prefix above, which means no definition of {func} can be found.
               * We would always check for this, but we get false positives on
               * MSYS2 if we do. Their toolchain is broken, but we can at least
               * give them a workaround. */
              #if {no_includes:d}
                  __builtin_{func};
              #else
                  #error "No definition for __builtin_{func} found in the prefix"
              #endif
          #endif
          }}'''
          return self.links(t.format(**fargs), env, extra_args, dependencies)
  
      def has_members(self, typename, membernames, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename, 'name': 'foo'}
          # Create code that accesses all members
          members = ''
          for member in membernames:
              members += '{}.{};\n'.format(fargs['name'], member)
          fargs['members'] = members
          t = '''{prefix}
          void bar() {{
              {type} {name};
              {members}
          }};'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def has_type(self, typename, prefix, env, extra_args, dependencies=None):
          fargs = {'prefix': prefix, 'type': typename}
          t = '''{prefix}
          void bar() {{
              sizeof({type});
          }};'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def symbols_have_underscore_prefix(self, env):
          '''
          Check if the compiler prefixes an underscore to global C symbols
          '''
          symbol_name = b'meson_uscore_prefix'
          code = '''#ifdef __cplusplus
          extern "C" {
          #endif
          void ''' + symbol_name.decode() + ''' () {}
          #ifdef __cplusplus
          }
          #endif
          '''
          args = self.get_cross_extra_flags(env, link=False)
          args += self.get_compiler_check_args()
          n = 'symbols_have_underscore_prefix'
          with self.compile(code, args, 'compile') as p:
              if p.returncode != 0:
                  m = 'BUG: Unable to compile {!r} check: {}'
                  raise RuntimeError(m.format(n, p.stdo))
              if not os.path.isfile(p.output_name):
                  m = 'BUG: Can\'t find compiled test code for {!r} check'
                  raise RuntimeError(m.format(n))
              with open(p.output_name, 'rb') as o:
                  for line in o:
                      # Check if the underscore form of the symbol is somewhere
                      # in the output file.
                      if b'_' + symbol_name in line:
                          return True
                      # Else, check if the non-underscored form is present
                      elif symbol_name in line:
                          return False
          raise RuntimeError('BUG: {!r} check failed unexpectedly'.format(n))
  
      def find_library(self, libname, env, extra_dirs):
          # First try if we can just add the library as -l.
          code = '''int main(int argc, char **argv) {
      return 0;
  }
          '''
          if extra_dirs and isinstance(extra_dirs, str):
              extra_dirs = [extra_dirs]
          # Gcc + co seem to prefer builtin lib dirs to -L dirs.
          # Only try to find std libs if no extra dirs specified.
          if not extra_dirs:
              args = ['-l' + libname]
              if self.links(code, env, extra_args=args):
                  return args
          # Not found? Try to find the library file itself.
          extra_dirs += self.get_library_dirs()
          suffixes = ['so', 'dylib', 'lib', 'dll', 'a']
          for d in extra_dirs:
              for suffix in suffixes:
                  trial = os.path.join(d, 'lib' + libname + '.' + suffix)
                  if os.path.isfile(trial):
                      return [trial]
                  trial2 = os.path.join(d, libname + '.' + suffix)
                  if os.path.isfile(trial2):
                      return [trial2]
          return None
  
      def thread_flags(self):
          return ['-pthread']
  
      def thread_link_flags(self):
          return ['-pthread']
  
      def has_multi_arguments(self, args, env):
          return self.compiles('int i;\n', env, extra_args=args)
  
  
  class ClangCCompiler(ClangCompiler, CCompiler):
      def __init__(self, exelist, version, clang_type, is_cross, exe_wrapper=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, clang_type)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          return {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none', 'c89', 'c99', 'c11',
                                                     'gnu89', 'gnu99', 'gnu11'],
                                                    'none')}
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return []
  
  
  class GnuCCompiler(GnuCompiler, CCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          opts = {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none', 'c89', 'c99', 'c11',
                                                     'gnu89', 'gnu99', 'gnu11'],
                                                    'none')}
          if self.gcc_type == GCC_MINGW:
              opts.update({
                  'c_winlibs': coredata.UserStringArrayOption('c_winlibs', 'Standard Win libraries to link against',
                                                              gnu_winlibs), })
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          if self.gcc_type == GCC_MINGW:
              return options['c_winlibs'].value[:]
          return []
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
  
  class IntelCCompiler(IntelCompiler, CCompiler):
      def __init__(self, exelist, version, icc_type, is_cross, exe_wrapper=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          IntelCompiler.__init__(self, icc_type)
          self.lang_header = 'c-header'
          default_warn_args = ['-Wall', '-w3', '-diag-disable:remark', '-Wpch-messages']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          c_stds = ['c89', 'c99']
          g_stds = ['gnu89', 'gnu99']
          if version_compare(self.version, '>=16.0.0'):
              c_stds += ['c11']
          opts = {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none'] + c_stds + g_stds,
                                                    'none')}
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def has_multi_arguments(self, args, env):
          return super().has_multi_arguments(args + ['-diag-error', '10006'], env)
  
  
  class VisualStudioCCompiler(CCompiler):
      std_warn_args = ['/W3']
      std_opt_args = ['/O2']
  
      def __init__(self, exelist, version, is_cross, exe_wrap):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          self.id = 'msvc'
          # /showIncludes is needed for build dependency tracking in Ninja
          # See: https://ninja-build.org/manual.html#_deps
          self.always_args = ['/nologo', '/showIncludes']
          self.warn_args = {'1': ['/W2'],
                            '2': ['/W3'],
                            '3': ['/W4']}
          self.base_options = ['b_pch'] # FIXME add lto, pgo and the like
  
      # Override CCompiler.get_always_args
      def get_always_args(self):
          return self.always_args
  
      def get_linker_debug_crt_args(self):
          """
          Arguments needed to select a debug crt for the linker
  
          Sometimes we need to manually select the CRT (C runtime) to use with
          MSVC. One example is when trying to link with static libraries since
          MSVC won't auto-select a CRT for us in that case and will error out
          asking us to select one.
          """
          return ['/MDd']
  
      def get_buildtype_args(self, buildtype):
          return msvc_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          return msvc_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pch'
  
      def get_pch_name(self, header):
          chopped = os.path.split(header)[-1].split('.')[:-1]
          chopped.append(self.get_pch_suffix())
          pchname = '.'.join(chopped)
          return pchname
  
      def get_pch_use_args(self, pch_dir, header):
          base = os.path.split(header)[-1]
          pchname = self.get_pch_name(header)
          return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]
  
      def get_preprocess_only_args(self):
          return ['/EP']
  
      def get_compile_only_args(self):
          return ['/c']
  
      def get_no_optimization_args(self):
          return ['/Od']
  
      def get_output_args(self, target):
          if target.endswith('.exe'):
              return ['/Fe' + target]
          return ['/Fo' + target]
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return []
  
      def get_linker_exelist(self):
          return ['link'] # FIXME, should have same path as compiler.
  
      def get_linker_always_args(self):
          return ['/nologo']
  
      def get_linker_output_args(self, outputname):
          return ['/OUT:' + outputname]
  
      def get_linker_search_args(self, dirname):
          return ['/LIBPATH:' + dirname]
  
      def get_pic_args(self):
          return [] # PIC is handled by the loader on Windows
  
      def get_std_shared_lib_link_args(self):
          return ['/DLL']
  
      def gen_vs_module_defs_args(self, defsfile):
          if not isinstance(defsfile, str):
              raise RuntimeError('Module definitions file should be str')
          # With MSVC, DLLs only export symbols that are explicitly exported,
          # so if a module defs file is specified, we use that to export symbols
          return ['/DEF:' + defsfile]
  
      def gen_pch_args(self, header, source, pchname):
          objname = os.path.splitext(pchname)[0] + '.obj'
          return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]
  
      def gen_import_library_args(self, implibname):
          "The name of the outputted import library"
          return ['/IMPLIB:' + implibname]
  
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return []
  
      # FIXME, no idea what these should be.
      def thread_flags(self):
          return []
  
      def thread_link_flags(self):
          return []
  
      def get_options(self):
          return {'c_winlibs': coredata.UserStringArrayOption('c_winlibs',
                                                              'Windows libs to link against.',
                                                              msvc_winlibs)
                  }
  
      def get_option_link_args(self, options):
          return options['c_winlibs'].value[:]
  
      @classmethod
      def unix_args_to_native(cls, args):
          result = []
          for i in args:
              # -mms-bitfields is specific to MinGW-GCC
              # -pthread is only valid for GCC
              if i in ('-mms-bitfields', '-pthread'):
                  continue
              if i.startswith('-L'):
                  i = '/LIBPATH:' + i[2:]
              # Translate GNU-style -lfoo library name to the import library
              elif i.startswith('-l'):
                  name = i[2:]
                  if name in ('m', 'c', 'pthread'):
                      # With MSVC, these are provided by the C runtime which is
                      # linked in by default
                      continue
                  else:
                      i = name + '.lib'
              # -pthread in link flags is only used on Linux
              elif i == '-pthread':
                  continue
              result.append(i)
          return result
  
      def get_werror_args(self):
          return ['/WX']
  
      def get_include_args(self, path, is_system):
          if path == '':
              path = '.'
          # msvc does not have a concept of system header dirs.
          return ['-I' + path]
  
      # Visual Studio is special. It ignores some arguments it does not
      # understand and you can't tell it to error out on those.
      # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t
      def has_multi_arguments(self, args, env):
          warning_text = '9002'
          code = 'int i;\n'
          (fd, srcname) = tempfile.mkstemp(suffix='.' + self.default_suffix)
          os.close(fd)
          with open(srcname, 'w') as ofile:
              ofile.write(code)
          # Read c_args/cpp_args/etc from the cross-info file (if needed)
          extra_args = self.get_cross_extra_flags(env, link=False)
          extra_args += self.get_compile_only_args()
          commands = self.exelist + args + extra_args + [srcname]
          mlog.debug('Running VS compile:')
          mlog.debug('Command line: ', ' '.join(commands))
          mlog.debug('Code:\n', code)
          p, stdo, stde = Popen_safe(commands, cwd=os.path.split(srcname)[0])
          if p.returncode != 0:
              return False
          return not(warning_text in stde or warning_text in stdo)
  
      def get_compile_debugfile_args(self, rel_obj, pch=False):
          pdbarr = rel_obj.split('.')[:-1]
          pdbarr += ['pdb']
          args = ['/Fd' + '.'.join(pdbarr)]
          # When generating a PDB file with PCH, all compile commands write
          # to the same PDB file. Hence, we need to serialize the PDB
          # writes using /FS since we do parallel builds. This slows down the
          # build obviously, which is why we only do this when PCH is on.
          # This was added in Visual Studio 2013 (MSVC 18.0). Before that it was
          # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspx
          if pch and version_compare(self.version, '>=18.0'):
              args = ['/FS'] + args
          return args
  
      def get_link_debugfile_args(self, targetfile):
          pdbarr = targetfile.split('.')[:-1]
          pdbarr += ['pdb']
          return ['/DEBUG', '/PDB:' + '.'.join(pdbarr)]
  
      def get_link_whole_for(self, args):
          # Only since VS2015
          if not isinstance(args, list):
              args = [args]
          return ['/WHOLEARCHIVE:' + x for x in args]
  
files: mesonbuild/compilers/c.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 subprocess, os.path, tempfile
  
  from .. import mlog
  from .. import coredata
  from ..mesonlib import EnvironmentException, version_compare, Popen_safe
  
  from .compilers import (
      GCC_MINGW,
      get_largefile_args,
      gnu_winlibs,
      msvc_buildtype_args,
      msvc_buildtype_linker_args,
      msvc_winlibs,
      ClangCompiler,
      Compiler,
      CompilerArgs,
      CrossNoRunException,
      GnuCompiler,
      IntelCompiler,
      RunResult,
  )
  
  
  class CCompiler(Compiler):
      def __init__(self, exelist, version, is_cross, exe_wrapper=None):
          # If a child ObjC or CPP class has already set it, don't set it ourselves
          if not hasattr(self, 'language'):
              self.language = 'c'
          super().__init__(exelist, version)
          self.id = 'unknown'
          self.is_cross = is_cross
          self.can_compile_suffixes.add('h')
          if isinstance(exe_wrapper, str):
              self.exe_wrapper = [exe_wrapper]
          else:
              self.exe_wrapper = exe_wrapper
  
      def needs_static_linker(self):
          return True # When compiling static libraries, so yes.
  
      def get_always_args(self):
          '''
          Args that are always-on for all C compilers other than MSVC
          '''
          return ['-pipe'] + get_largefile_args(self)
  
      def get_linker_debug_crt_args(self):
          """
          Arguments needed to select a debug crt for the linker
          This is only needed for MSVC
          """
          return []
  
      def get_no_stdinc_args(self):
          return ['-nostdinc']
  
      def get_no_stdlib_link_args(self):
          return ['-nostdlib']
  
      def get_warn_args(self, level):
          return self.warn_args[level]
  
      def get_no_warn_args(self):
          # Almost every compiler uses this for disabling warnings
          return ['-w']
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return []
  
      def split_shlib_to_parts(self, fname):
          return None, fname
  
      # The default behavior is this, override in MSVC
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return self.build_unix_rpath_args(build_dir, from_dir, rpath_paths, install_rpath)
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return ['-MMD', '-MQ', outtarget, '-MF', outfile]
  
      def depfile_for_object(self, objfile):
          return objfile + '.' + self.get_depfile_suffix()
  
      def get_depfile_suffix(self):
          return 'd'
  
      def get_exelist(self):
          return self.exelist[:]
  
      def get_linker_exelist(self):
          return self.exelist[:]
  
      def get_preprocess_only_args(self):
          return ['-E', '-P']
  
      def get_compile_only_args(self):
          return ['-c']
  
      def get_no_optimization_args(self):
          return ['-O0']
  
      def get_compiler_check_args(self):
          '''
          Get arguments useful for compiler checks such as being permissive in
          the code quality and not doing any optimization.
          '''
          return self.get_no_optimization_args()
  
      def get_output_args(self, target):
          return ['-o', target]
  
      def get_linker_output_args(self, outputname):
          return ['-o', outputname]
  
      def get_coverage_args(self):
          return ['--coverage']
  
      def get_coverage_link_args(self):
          return ['--coverage']
  
      def get_werror_args(self):
          return ['-Werror']
  
      def get_std_exe_link_args(self):
          return []
  
      def get_include_args(self, path, is_system):
          if path == '':
              path = '.'
          if is_system:
              return ['-isystem', path]
          return ['-I' + path]
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def get_library_dirs(self):
          stdo = Popen_safe(self.exelist + ['--print-search-dirs'])[1]
          for line in stdo.split('\n'):
              if line.startswith('libraries:'):
                  libstr = line.split('=', 1)[1]
                  return libstr.split(':')
          return []
  
      def get_pic_args(self):
          return ['-fPIC']
  
      def name_string(self):
          return ' '.join(self.exelist)
  
      def get_pch_use_args(self, pch_dir, header):
          return ['-include', os.path.split(header)[-1]]
  
      def get_pch_name(self, header_name):
          return os.path.split(header_name)[-1] + '.' + self.get_pch_suffix()
  
      def get_linker_search_args(self, dirname):
          return ['-L' + dirname]
  
      def gen_import_library_args(self, implibname):
          """
          The name of the outputted import library
  
          This implementation is used only on Windows by compilers that use GNU ld
          """
          return ['-Wl,--out-implib=' + implibname]
  
      def sanity_check_impl(self, work_dir, environment, sname, code):
          mlog.debug('Sanity testing ' + self.language + ' compiler:', ' '.join(self.exelist))
          mlog.debug('Is cross compiler: %s.' % str(self.is_cross))
  
          extra_flags = []
          source_name = os.path.join(work_dir, sname)
          binname = sname.rsplit('.', 1)[0]
          if self.is_cross:
              binname += '_cross'
              if self.exe_wrapper is None:
                  # Linking cross built apps is painful. You can't really
                  # tell if you should use -nostdlib or not and for example
                  # on OSX the compiler binary is the same but you need
                  # a ton of compiler flags to differentiate between
                  # arm and x86_64. So just compile.
                  extra_flags += self.get_cross_extra_flags(environment, link=False)
                  extra_flags += self.get_compile_only_args()
              else:
                  extra_flags += self.get_cross_extra_flags(environment, link=True)
          # Is a valid executable output for all toolchains and platforms
          binname += '.exe'
          # Write binary check source
          binary_name = os.path.join(work_dir, binname)
          with open(source_name, 'w') as ofile:
              ofile.write(code)
          # Compile sanity check
          cmdlist = self.exelist + extra_flags + [source_name] + self.get_output_args(binary_name)
          pc, stdo, stde = Popen_safe(cmdlist, cwd=work_dir)
          mlog.debug('Sanity check compiler command line:', ' '.join(cmdlist))
          mlog.debug('Sanity check compile stdout:')
          mlog.debug(stdo)
          mlog.debug('-----\nSanity check compile stderr:')
          mlog.debug(stde)
          mlog.debug('-----')
          if pc.returncode != 0:
              raise EnvironmentException('Compiler {0} can not compile programs.'.format(self.name_string()))
          # Run sanity check
          if self.is_cross:
              if self.exe_wrapper is None:
                  # Can't check if the binaries run so we have to assume they do
                  return
              cmdlist = self.exe_wrapper + [binary_name]
          else:
              cmdlist = [binary_name]
          mlog.debug('Running test binary command: ' + ' '.join(cmdlist))
          pe = subprocess.Popen(cmdlist)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by {0} compiler {1} are not runnable.'.format(self.language, self.name_string()))
  
      def sanity_check(self, work_dir, environment):
          code = 'int main(int argc, char **argv) { int class=0; return class; }\n'
          return self.sanity_check_impl(work_dir, environment, 'sanitycheckc.c', code)
  
      def has_header(self, hname, prefix, env, extra_args=None, dependencies=None):
          fargs = {'prefix': prefix, 'header': hname}
          code = '''{prefix}
          #ifdef __has_include
           #if !__has_include("{header}")
            #error "Header '{header}' could not be found"
           #endif
          #else
           #include <{header}>
          #endif'''
          return self.compiles(code.format(**fargs), env, extra_args,
                               dependencies, 'preprocess')
  
      def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):
          fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
          t = '''{prefix}
          #include <{header}>
          int main () {{
              /* If it's not defined as a macro, try to use as a symbol */
              #ifndef {symbol}
                  {symbol};
              #endif
          }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def _get_compiler_check_args(self, env, extra_args, dependencies, mode='compile'):
          if extra_args is None:
              extra_args = []
          elif isinstance(extra_args, str):
              extra_args = [extra_args]
          if dependencies is None:
              dependencies = []
          elif not isinstance(dependencies, list):
              dependencies = [dependencies]
          # Collect compiler arguments
          args = CompilerArgs(self)
          for d in dependencies:
              # Add compile flags needed by dependencies
              args += d.get_compile_args()
              if mode == 'link':
                  # Add link flags needed to find dependencies
                  args += d.get_link_args()
          # Select a CRT if needed since we're linking
          if mode == 'link':
              args += self.get_linker_debug_crt_args()
          # Read c_args/cpp_args/etc from the cross-info file (if needed)
          args += self.get_cross_extra_flags(env, link=(mode == 'link'))
          if not self.is_cross:
              if mode == 'preprocess':
                  # Add CPPFLAGS from the env.
                  args += env.coredata.external_preprocess_args[self.language]
              elif mode == 'compile':
                  # Add CFLAGS/CXXFLAGS/OBJCFLAGS/OBJCXXFLAGS from the env
                  args += env.coredata.external_args[self.language]
              elif mode == 'link':
                  # Add LDFLAGS from the env
                  args += env.coredata.external_link_args[self.language]
          args += self.get_compiler_check_args()
          # extra_args must override all other arguments, so we add them last
          args += extra_args
          return args
  
      def compiles(self, code, env, extra_args=None, dependencies=None, mode='compile'):
          args = self._get_compiler_check_args(env, extra_args, dependencies, mode)
          # We only want to compile; not link
          with self.compile(code, args.to_native(), mode) as p:
              return p.returncode == 0
  
      def _links_wrapper(self, code, env, extra_args, dependencies):
          "Shares common code between self.links and self.run"
          args = self._get_compiler_check_args(env, extra_args, dependencies, mode='link')
          return self.compile(code, args)
  
      def links(self, code, env, extra_args=None, dependencies=None):
          with self._links_wrapper(code, env, extra_args, dependencies) as p:
              return p.returncode == 0
  
      def run(self, code, env, extra_args=None, dependencies=None):
          if self.is_cross and self.exe_wrapper is None:
              raise CrossNoRunException('Can not run test applications in this cross environment.')
          with self._links_wrapper(code, env, extra_args, dependencies) as p:
              if p.returncode != 0:
                  mlog.debug('Could not compile test file %s: %d\n' % (
                      p.input_name,
                      p.returncode))
                  return RunResult(False)
              if self.is_cross:
                  cmdlist = self.exe_wrapper + [p.output_name]
              else:
                  cmdlist = p.output_name
              try:
                  pe, so, se = Popen_safe(cmdlist)
              except Exception as e:
                  mlog.debug('Could not run: %s (error: %s)\n' % (cmdlist, e))
                  return RunResult(False)
  
          mlog.debug('Program stdout:\n')
          mlog.debug(so)
          mlog.debug('Program stderr:\n')
          mlog.debug(se)
          return RunResult(True, pe.returncode, so, se)
  
      def _compile_int(self, expression, prefix, env, extra_args, dependencies):
          fargs = {'prefix': prefix, 'expression': expression}
          t = '''#include <stdio.h>
          {prefix}
          int main() {{ static int a[1-2*!({expression})]; a[0]=0; return 0; }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def cross_compute_int(self, expression, low, high, guess, prefix, env, extra_args, dependencies):
          if isinstance(guess, int):
              if self._compile_int('%s == %d' % (expression, guess), prefix, env, extra_args, dependencies):
                  return guess
  
          cur = low
          while low < high:
              cur = int((low + high) / 2)
              if cur == low:
                  break
  
              if self._compile_int('%s >= %d' % (expression, cur), prefix, env, extra_args, dependencies):
                  low = cur
              else:
                  high = cur
  
          if self._compile_int('%s == %d' % (expression, cur), prefix, env, extra_args, dependencies):
              return cur
          raise EnvironmentException('Cross-compile check overflowed')
  
      def compute_int(self, expression, low, high, guess, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          if self.is_cross:
              return self.cross_compute_int(expression, low, high, guess, prefix, env, extra_args, dependencies)
          fargs = {'prefix': prefix, 'expression': expression}
          t = '''#include<stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              printf("%ld\\n", (long)({expression}));
              return 0;
          }};'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              return -1
          if res.returncode != 0:
              raise EnvironmentException('Could not run compute_int test binary.')
          return int(res.stdout)
  
      def cross_sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              {type} something;
          }}'''
          if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
              return -1
          return self.cross_compute_int('sizeof(%s)' % typename, 1, 128, None, prefix, env, extra_args, dependencies)
  
      def sizeof(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          if self.is_cross:
              return self.cross_sizeof(typename, prefix, env, extra_args, dependencies)
          t = '''#include<stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              printf("%ld\\n", (long)(sizeof({type})));
              return 0;
          }};'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              return -1
          if res.returncode != 0:
              raise EnvironmentException('Could not run sizeof test binary.')
          return int(res.stdout)
  
      def cross_alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          {prefix}
          int main(int argc, char **argv) {{
              {type} something;
          }}'''
          if not self.compiles(t.format(**fargs), env, extra_args, dependencies):
              return -1
          t = '''#include <stddef.h>
          {prefix}
          struct tmp {{
              char c;
              {type} target;
          }};'''
          return self.cross_compute_int('offsetof(struct tmp, target)', 1, 1024, None, t.format(**fargs), env, extra_args, dependencies)
  
      def alignment(self, typename, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          if self.is_cross:
              return self.cross_alignment(typename, prefix, env, extra_args, dependencies)
          fargs = {'prefix': prefix, 'type': typename}
          t = '''#include <stdio.h>
          #include <stddef.h>
          {prefix}
          struct tmp {{
              char c;
              {type} target;
          }};
          int main(int argc, char **argv) {{
              printf("%d", (int)offsetof(struct tmp, target));
              return 0;
          }}'''
          res = self.run(t.format(**fargs), env, extra_args, dependencies)
          if not res.compiled:
              raise EnvironmentException('Could not compile alignment test.')
          if res.returncode != 0:
              raise EnvironmentException('Could not run alignment test binary.')
          align = int(res.stdout)
          if align == 0:
              raise EnvironmentException('Could not determine alignment of %s. Sorry. You might want to file a bug.' % typename)
          return align
  
      def get_define(self, dname, prefix, env, extra_args, dependencies):
          delim = '"MESON_GET_DEFINE_DELIMITER"'
          fargs = {'prefix': prefix, 'define': dname, 'delim': delim}
          code = '''
          {prefix}
          #ifndef {define}
          # define {define}
          #endif
          {delim}\n{define}'''
          args = self._get_compiler_check_args(env, extra_args, dependencies,
                                               mode='preprocess').to_native()
          with self.compile(code.format(**fargs), args, 'preprocess') as p:
              if p.returncode != 0:
                  raise EnvironmentException('Could not get define {!r}'.format(dname))
          # Get the preprocessed value after the delimiter,
          # minus the extra newline at the end
          return p.stdo.split(delim + '\n')[-1][:-1]
  
      @staticmethod
      def _no_prototype_templ():
          """
          Try to find the function without a prototype from a header by defining
          our own dummy prototype and trying to link with the C library (and
          whatever else the compiler links in by default). This is very similar
          to the check performed by Autoconf for AC_CHECK_FUNCS.
          """
          # Define the symbol to something else since it is defined by the
          # includes or defines listed by the user or by the compiler. This may
          # include, for instance _GNU_SOURCE which must be defined before
          # limits.h, which includes features.h
          # Then, undef the symbol to get rid of it completely.
          head = '''
          #define {func} meson_disable_define_of_{func}
          {prefix}
          #include <limits.h>
          #undef {func}
          '''
          # Override any GCC internal prototype and declare our own definition for
          # the symbol. Use char because that's unlikely to be an actual return
          # value for a function which ensures that we override the definition.
          head += '''
          #ifdef __cplusplus
          extern "C"
          #endif
          char {func} ();
          '''
          # The actual function call
          main = '''
          int main () {{
            return {func} ();
          }}'''
          return head, main
  
      @staticmethod
      def _have_prototype_templ():
          """
          Returns a head-er and main() call that uses the headers listed by the
          user for the function prototype while checking if a function exists.
          """
          # Add the 'prefix', aka defines, includes, etc that the user provides
          # This may include, for instance _GNU_SOURCE which must be defined
          # before limits.h, which includes features.h
          head = '{prefix}\n#include <limits.h>\n'
          # We don't know what the function takes or returns, so return it as an int.
          # Just taking the address or comparing it to void is not enough because
          # compilers are smart enough to optimize it away. The resulting binary
          # is not run so we don't care what the return value is.
          main = '''\nint main() {{
              void *a = (void*) &{func};
              long b = (long) a;
              return (int) b;
          }}'''
          return head, main
  
      def has_function(self, funcname, prefix, env, extra_args=None, dependencies=None):
          """
          First, this function looks for the symbol in the default libraries
          provided by the compiler (stdlib + a few others usually). If that
          fails, it checks if any of the headers specified in the prefix provide
          an implementation of the function, and if that fails, it checks if it's
          implemented as a compiler-builtin.
          """
          if extra_args is None:
              extra_args = []
  
          # Short-circuit if the check is already provided by the cross-info file
          varname = 'has function ' + funcname
          varname = varname.replace(' ', '_')
          if self.is_cross:
              val = env.cross_info.config['properties'].get(varname, None)
              if val is not None:
                  if isinstance(val, bool):
                      return val
                  raise EnvironmentException('Cross variable {0} is not a boolean.'.format(varname))
  
          fargs = {'prefix': prefix, 'func': funcname}
  
          # glibc defines functions that are not available on Linux as stubs that
          # fail with ENOSYS (such as e.g. lchmod). In this case we want to fail
          # instead of detecting the stub as a valid symbol.
          # We already included limits.h earlier to ensure that these are defined
          # for stub functions.
          stubs_fail = '''
          #if defined __stub_{func} || defined __stub___{func}
          fail fail fail this function is not going to work
          #endif
          '''
  
          # If we have any includes in the prefix supplied by the user, assume
          # that the user wants us to use the symbol prototype defined in those
          # includes. If not, then try to do the Autoconf-style check with
          # a dummy prototype definition of our own.
          # This is needed when the linker determines symbol availability from an
          # SDK based on the prototype in the header provided by the SDK.
          # Ignoring this prototype would result in the symbol always being
          # marked as available.
          if '#include' in prefix:
              head, main = self._have_prototype_templ()
          else:
              head, main = self._no_prototype_templ()
          templ = head + stubs_fail + main
  
          if self.links(templ.format(**fargs), env, extra_args, dependencies):
              return True
  
          # MSVC does not have compiler __builtin_-s.
          if self.get_id() == 'msvc':
              return False
  
          # Detect function as a built-in
          #
          # Some functions like alloca() are defined as compiler built-ins which
          # are inlined by the compiler and you can't take their address, so we
          # need to look for them differently. On nice compilers like clang, we
          # can just directly use the __has_builtin() macro.
          fargs['no_includes'] = '#include' not in prefix
          t = '''{prefix}
          int main() {{
          #ifdef __has_builtin
              #if !__has_builtin(__builtin_{func})
                  #error "__builtin_{func} not found"
              #endif
          #elif ! defined({func})
              /* Check for __builtin_{func} only if no includes were added to the
               * prefix above, which means no definition of {func} can be found.
               * We would always check for this, but we get false positives on
               * MSYS2 if we do. Their toolchain is broken, but we can at least
               * give them a workaround. */
              #if {no_includes:d}
                  __builtin_{func};
              #else
                  #error "No definition for __builtin_{func} found in the prefix"
              #endif
          #endif
          }}'''
          return self.links(t.format(**fargs), env, extra_args, dependencies)
  
      def has_members(self, typename, membernames, prefix, env, extra_args=None, dependencies=None):
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'type': typename, 'name': 'foo'}
          # Create code that accesses all members
          members = ''
          for member in membernames:
              members += '{}.{};\n'.format(fargs['name'], member)
          fargs['members'] = members
          t = '''{prefix}
          void bar() {{
              {type} {name};
              {members}
          }};'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def has_type(self, typename, prefix, env, extra_args, dependencies=None):
          fargs = {'prefix': prefix, 'type': typename}
          t = '''{prefix}
          void bar() {{
              sizeof({type});
          }};'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
      def symbols_have_underscore_prefix(self, env):
          '''
          Check if the compiler prefixes an underscore to global C symbols
          '''
          symbol_name = b'meson_uscore_prefix'
          code = '''#ifdef __cplusplus
          extern "C" {
          #endif
          void ''' + symbol_name.decode() + ''' () {}
          #ifdef __cplusplus
          }
          #endif
          '''
          args = self.get_cross_extra_flags(env, link=False)
          args += self.get_compiler_check_args()
          n = 'symbols_have_underscore_prefix'
          with self.compile(code, args, 'compile') as p:
              if p.returncode != 0:
                  m = 'BUG: Unable to compile {!r} check: {}'
                  raise RuntimeError(m.format(n, p.stdo))
              if not os.path.isfile(p.output_name):
                  m = 'BUG: Can\'t find compiled test code for {!r} check'
                  raise RuntimeError(m.format(n))
              with open(p.output_name, 'rb') as o:
                  for line in o:
                      # Check if the underscore form of the symbol is somewhere
                      # in the output file.
                      if b'_' + symbol_name in line:
                          return True
                      # Else, check if the non-underscored form is present
                      elif symbol_name in line:
                          return False
          raise RuntimeError('BUG: {!r} check failed unexpectedly'.format(n))
  
      def find_library(self, libname, env, extra_dirs):
          # First try if we can just add the library as -l.
          code = '''int main(int argc, char **argv) {
      return 0;
  }
          '''
          if extra_dirs and isinstance(extra_dirs, str):
              extra_dirs = [extra_dirs]
          # Gcc + co seem to prefer builtin lib dirs to -L dirs.
          # Only try to find std libs if no extra dirs specified.
          if not extra_dirs:
              args = ['-l' + libname]
              if self.links(code, env, extra_args=args):
                  return args
          # Not found? Try to find the library file itself.
          extra_dirs += self.get_library_dirs()
          suffixes = ['so', 'dylib', 'lib', 'dll', 'a']
          for d in extra_dirs:
              for suffix in suffixes:
                  trial = os.path.join(d, 'lib' + libname + '.' + suffix)
                  if os.path.isfile(trial):
                      return [trial]
                  trial2 = os.path.join(d, libname + '.' + suffix)
                  if os.path.isfile(trial2):
                      return [trial2]
          return None
  
      def thread_flags(self):
          return ['-pthread']
  
      def thread_link_flags(self):
          return ['-pthread']
  
      def has_multi_arguments(self, args, env):
          return self.compiles('int i;\n', env, extra_args=args)
  
  
  class ClangCCompiler(ClangCompiler, CCompiler):
      def __init__(self, exelist, version, clang_type, is_cross, exe_wrapper=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, clang_type)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          return {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none', 'c89', 'c99', 'c11',
                                                     'gnu89', 'gnu99', 'gnu11'],
                                                    'none')}
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return []
  
  
  class GnuCCompiler(GnuCompiler, CCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          opts = {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none', 'c89', 'c99', 'c11',
                                                     'gnu89', 'gnu99', 'gnu11'],
                                                    'none')}
          if self.gcc_type == GCC_MINGW:
              opts.update({
                  'c_winlibs': coredata.UserStringArrayOption('c_winlibs', 'Standard Win libraries to link against',
                                                              gnu_winlibs), })
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          if self.gcc_type == GCC_MINGW:
              return options['c_winlibs'].value[:]
          return []
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
  
  class IntelCCompiler(IntelCompiler, CCompiler):
      def __init__(self, exelist, version, icc_type, is_cross, exe_wrapper=None):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          IntelCompiler.__init__(self, icc_type)
          self.lang_header = 'c-header'
          default_warn_args = ['-Wall', '-w3', '-diag-disable:remark', '-Wpch-messages']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          c_stds = ['c89', 'c99']
          g_stds = ['gnu89', 'gnu99']
          if version_compare(self.version, '>=16.0.0'):
              c_stds += ['c11']
          opts = {'c_std': coredata.UserComboOption('c_std', 'C language standard to use',
                                                    ['none'] + c_stds + g_stds,
                                                    'none')}
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['c_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_std_shared_lib_link_args(self):
          return ['-shared']
  
      def has_multi_arguments(self, args, env):
          return super().has_multi_arguments(args + ['-diag-error', '10006'], env)
  
  
  class VisualStudioCCompiler(CCompiler):
      std_warn_args = ['/W3']
      std_opt_args = ['/O2']
  
      def __init__(self, exelist, version, is_cross, exe_wrap):
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          self.id = 'msvc'
          # /showIncludes is needed for build dependency tracking in Ninja
          # See: https://ninja-build.org/manual.html#_deps
          self.always_args = ['/nologo', '/showIncludes']
          self.warn_args = {'1': ['/W2'],
                            '2': ['/W3'],
                            '3': ['/W4']}
          self.base_options = ['b_pch'] # FIXME add lto, pgo and the like
  
      # Override CCompiler.get_always_args
      def get_always_args(self):
          return self.always_args
  
      def get_linker_debug_crt_args(self):
          """
          Arguments needed to select a debug crt for the linker
  
          Sometimes we need to manually select the CRT (C runtime) to use with
          MSVC. One example is when trying to link with static libraries since
          MSVC won't auto-select a CRT for us in that case and will error out
          asking us to select one.
          """
          return ['/MDd']
  
      def get_buildtype_args(self, buildtype):
          return msvc_buildtype_args[buildtype]
  
      def get_buildtype_linker_args(self, buildtype):
          return msvc_buildtype_linker_args[buildtype]
  
      def get_pch_suffix(self):
          return 'pch'
  
      def get_pch_name(self, header):
          chopped = os.path.split(header)[-1].split('.')[:-1]
          chopped.append(self.get_pch_suffix())
          pchname = '.'.join(chopped)
          return pchname
  
      def get_pch_use_args(self, pch_dir, header):
          base = os.path.split(header)[-1]
          pchname = self.get_pch_name(header)
          return ['/FI' + base, '/Yu' + base, '/Fp' + os.path.join(pch_dir, pchname)]
  
      def get_preprocess_only_args(self):
          return ['/EP']
  
      def get_compile_only_args(self):
          return ['/c']
  
      def get_no_optimization_args(self):
          return ['/Od']
  
      def get_output_args(self, target):
          if target.endswith('.exe'):
              return ['/Fe' + target]
          return ['/Fo' + target]
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return []
  
      def get_linker_exelist(self):
          return ['link'] # FIXME, should have same path as compiler.
  
      def get_linker_always_args(self):
          return ['/nologo']
  
      def get_linker_output_args(self, outputname):
          return ['/OUT:' + outputname]
  
      def get_linker_search_args(self, dirname):
          return ['/LIBPATH:' + dirname]
  
      def get_pic_args(self):
          return [] # PIC is handled by the loader on Windows
  
      def get_std_shared_lib_link_args(self):
          return ['/DLL']
  
      def gen_vs_module_defs_args(self, defsfile):
          if not isinstance(defsfile, str):
              raise RuntimeError('Module definitions file should be str')
          # With MSVC, DLLs only export symbols that are explicitly exported,
          # so if a module defs file is specified, we use that to export symbols
          return ['/DEF:' + defsfile]
  
      def gen_pch_args(self, header, source, pchname):
          objname = os.path.splitext(pchname)[0] + '.obj'
          return objname, ['/Yc' + header, '/Fp' + pchname, '/Fo' + objname]
  
      def gen_import_library_args(self, implibname):
          "The name of the outputted import library"
          return ['/IMPLIB:' + implibname]
  
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return []
  
      # FIXME, no idea what these should be.
      def thread_flags(self):
          return []
  
      def thread_link_flags(self):
          return []
  
      def get_options(self):
          return {'c_winlibs': coredata.UserStringArrayOption('c_winlibs',
                                                              'Windows libs to link against.',
                                                              msvc_winlibs)
                  }
  
      def get_option_link_args(self, options):
          return options['c_winlibs'].value[:]
  
      @classmethod
      def unix_args_to_native(cls, args):
          result = []
          for i in args:
              # -mms-bitfields is specific to MinGW-GCC
              # -pthread is only valid for GCC
              if i in ('-mms-bitfields', '-pthread'):
                  continue
              if i.startswith('-L'):
                  i = '/LIBPATH:' + i[2:]
              # Translate GNU-style -lfoo library name to the import library
              elif i.startswith('-l'):
                  name = i[2:]
                  if name in ('m', 'c', 'pthread'):
                      # With MSVC, these are provided by the C runtime which is
                      # linked in by default
                      continue
                  else:
                      i = name + '.lib'
              # -pthread in link flags is only used on Linux
              elif i == '-pthread':
                  continue
              result.append(i)
          return result
  
      def get_werror_args(self):
          return ['/WX']
  
      def get_include_args(self, path, is_system):
          if path == '':
              path = '.'
          # msvc does not have a concept of system header dirs.
          return ['-I' + path]
  
      # Visual Studio is special. It ignores some arguments it does not
      # understand and you can't tell it to error out on those.
      # http://stackoverflow.com/questions/15259720/how-can-i-make-the-microsoft-c-compiler-treat-unknown-flags-as-errors-rather-t
      def has_multi_arguments(self, args, env):
          warning_text = '9002'
          code = 'int i;\n'
          (fd, srcname) = tempfile.mkstemp(suffix='.' + self.default_suffix)
          os.close(fd)
          with open(srcname, 'w') as ofile:
              ofile.write(code)
          # Read c_args/cpp_args/etc from the cross-info file (if needed)
          extra_args = self.get_cross_extra_flags(env, link=False)
          extra_args += self.get_compile_only_args()
          commands = self.exelist + args + extra_args + [srcname]
          mlog.debug('Running VS compile:')
          mlog.debug('Command line: ', ' '.join(commands))
          mlog.debug('Code:\n', code)
          p, stdo, stde = Popen_safe(commands, cwd=os.path.split(srcname)[0])
          if p.returncode != 0:
              return False
          return not(warning_text in stde or warning_text in stdo)
  
      def get_compile_debugfile_args(self, rel_obj, pch=False):
          pdbarr = rel_obj.split('.')[:-1]
          pdbarr += ['pdb']
          args = ['/Fd' + '.'.join(pdbarr)]
          # When generating a PDB file with PCH, all compile commands write
          # to the same PDB file. Hence, we need to serialize the PDB
          # writes using /FS since we do parallel builds. This slows down the
          # build obviously, which is why we only do this when PCH is on.
          # This was added in Visual Studio 2013 (MSVC 18.0). Before that it was
          # always on: https://msdn.microsoft.com/en-us/library/dn502518.aspx
          if pch and version_compare(self.version, '>=18.0'):
              args = ['/FS'] + args
          return args
  
      def get_link_debugfile_args(self, targetfile):
          pdbarr = targetfile.split('.')[:-1]
          pdbarr += ['pdb']
          return ['/DEBUG', '/PDB:' + '.'.join(pdbarr)]
  
      def get_link_whole_for(self, args):
          # Only since VS2015
          if not isinstance(args, list):
              args = [args]
          return ['/WHOLEARCHIVE:' + x for x in args]
  
files: mesonbuild/compilers/c.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
  
  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'),
      '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 = ('objcpp', 'objc', 'd', 'cpp', 'c', 'fortran',)
  clike_suffixes = ()
  for _l in clike_langs:
      clike_suffixes += lang_suffixes[_l]
  clike_suffixes += ('h', 'll', 's')
  
  # 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': [],
                                'release': [],
                                'minsize': ['/INCREMENTAL:NO'],
                                }
  
  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'],
                                                         '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 guide 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.UserBooleanOption('b_ndebug',
                                                         'Disable asserts',
                                                         False),
                  'b_staticpic': coredata.UserBooleanOption('b_staticpic',
                                                            'Build static libraries as position independent',
                                                            True),
                  }
  
  def sanitizer_compile_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      if value == 'address':
          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:
              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('-Wl,--as-needed')
      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 'overriden' by a later argument.  For
             example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
             can safely remove the previous occurance 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.
          if get_compiler_uses_gnuld(self.compiler):
              group_started = False
              for each in self:
                  if not each.startswith('-l') and not each.endswith('.a'):
                      continue
                  i = self.index(each)
                  if not group_started:
                      # First occurance of a library
                      self.insert(i, '-Wl,--start-group')
                      group_started = True
              # Last occurance of a library
              if group_started:
                  self.insert(i + 1, '-Wl,--end-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 occurance of it and adding a new one, or not adding the
              # new occurance.
              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 occurances 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:
      def __init__(self, exelist, version):
          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 overriden 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
          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.language)
  
      def has_header_symbol(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header symbol checks.' % self.language)
  
      def compiles(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support compile checks.' % self.language)
  
      def links(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support link checks.' % self.language)
  
      def run(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support run checks.' % self.language)
  
      def sizeof(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support sizeof checks.' % self.language)
  
      def alignment(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support alignment checks.' % self.language)
  
      def has_function(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support function checks.' % self.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.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.language))
  
      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.language)
  
      def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          if not rpath_paths and not install_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(p, from_dir)
              rel_rpaths.append(relative)
          paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
          if len(paths) < len(install_rpath):
              padding = 'X' * (len(install_rpath) - len(paths))
              if not paths:
                  paths = padding
              else:
                  paths = paths + ':' + padding
          args = ['-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])
              args += ['-Wl,-rpath-link,' + lpaths]
          return args
  
  
  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
  
  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 []
          return ['-install_name', os.path.join(path, 'lib' + shlib_name + '.dylib')]
      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 []
  
  
  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')
  
      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.split(fname)[0], 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):
          if self.gcc_type == GCC_OSX:
              return ['-bundle']
          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 []
  
  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'])
  
      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):
          return super().has_multi_arguments(
              ['-Werror=unknown-warning-option'] + 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']
  
  
  # 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.split(header_name)[-1] + '.' + self.get_pch_suffix()
  
      def split_shlib_to_parts(self, fname):
          return os.path.split(fname)[0], 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']
  
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
  
  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'),
      '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 = ('objcpp', 'objc', 'd', 'cpp', 'c', 'fortran',)
  clike_suffixes = ()
  for _l in clike_langs:
      clike_suffixes += lang_suffixes[_l]
  clike_suffixes += ('h', 'll', 's')
  
  # 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': [],
                                'release': [],
                                'minsize': ['/INCREMENTAL:NO'],
                                }
  
  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'],
                                                         '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 guide 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.UserBooleanOption('b_ndebug',
                                                         'Disable asserts',
                                                         False),
                  'b_staticpic': coredata.UserBooleanOption('b_staticpic',
                                                            'Build static libraries as position independent',
                                                            True),
                  }
  
  def sanitizer_compile_args(value):
      if value == 'none':
          return []
      args = ['-fsanitize=' + value]
      if value == 'address':
          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:
              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('-Wl,--as-needed')
      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 'overriden' by a later argument.  For
             example, -DFOO defines FOO and -UFOO undefines FOO. In this case, we
             can safely remove the previous occurance 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.
          if get_compiler_uses_gnuld(self.compiler):
              group_started = False
              for each in self:
                  if not each.startswith('-l') and not each.endswith('.a'):
                      continue
                  i = self.index(each)
                  if not group_started:
                      # First occurance of a library
                      self.insert(i, '-Wl,--start-group')
                      group_started = True
              # Last occurance of a library
              if group_started:
                  self.insert(i + 1, '-Wl,--end-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 occurance of it and adding a new one, or not adding the
              # new occurance.
              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 occurances 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:
      def __init__(self, exelist, version):
          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 overriden 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
          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_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.language)
  
      def has_header_symbol(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support header symbol checks.' % self.language)
  
      def compiles(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support compile checks.' % self.language)
  
      def links(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support link checks.' % self.language)
  
      def run(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support run checks.' % self.language)
  
      def sizeof(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support sizeof checks.' % self.language)
  
      def alignment(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support alignment checks.' % self.language)
  
      def has_function(self, *args, **kwargs):
          raise EnvironmentException('Language %s does not support function checks.' % self.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.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.language))
  
      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.language)
  
      def build_unix_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          if not rpath_paths and not install_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(p, from_dir)
              rel_rpaths.append(relative)
          paths = ':'.join([os.path.join('$ORIGIN', p) for p in rel_rpaths])
          if len(paths) < len(install_rpath):
              padding = 'X' * (len(install_rpath) - len(paths))
              if not paths:
                  paths = padding
              else:
                  paths = paths + ':' + padding
          args = ['-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])
              args += ['-Wl,-rpath-link,' + lpaths]
          return args
  
  
  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
  
  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 []
          return ['-install_name', os.path.join(path, 'lib' + shlib_name + '.dylib')]
      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 []
  
  
  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')
  
      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.split(fname)[0], 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):
          if self.gcc_type == GCC_OSX:
              return ['-bundle']
          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 []
  
  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'])
  
      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):
          return super().has_multi_arguments(
              ['-Werror=unknown-warning-option'] + 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']
  
  
  # 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.split(header_name)[-1] + '.' + self.get_pch_suffix()
  
      def split_shlib_to_parts(self, fname):
          return os.path.split(fname)[0], 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']
  
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.
  
  from .. import coredata
  from ..mesonlib import version_compare
  
  from .c import CCompiler, VisualStudioCCompiler
  from .compilers import (
      GCC_MINGW,
      gnu_winlibs,
      msvc_winlibs,
      ClangCompiler,
      GnuCompiler,
      IntelCompiler,
  )
  
  class CPPCompiler(CCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          # If a child ObjCPP class has already set it, don't set it ourselves
          if not hasattr(self, 'language'):
              self.language = 'cpp'
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def get_display_language(self):
          return 'C++'
  
      def get_no_stdinc_args(self):
          return ['-nostdinc++']
  
      def sanity_check(self, work_dir, environment):
          code = 'class breakCCompiler;int main(int argc, char **argv) { return 0; }\n'
          return self.sanity_check_impl(work_dir, environment, 'sanitycheckcpp.cc', code)
  
      def get_compiler_check_args(self):
          # -fpermissive allows non-conforming code to compile which is necessary
          # for many C++ checks. Particularly, the has_header_symbol check is
          # too strict without this and always fails.
          return super().get_compiler_check_args() + ['-fpermissive']
  
      def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):
          # Check if it's a C-like symbol
          if super().has_header_symbol(hname, symbol, prefix, env, extra_args, dependencies):
              return True
          # Check if it's a class or a template
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
          t = '''{prefix}
          #include <{header}>
          using {symbol};
          int main () {{ return 0; }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
  
  class ClangCPPCompiler(ClangCompiler, CPPCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          return {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none', 'c++03', 'c++11', 'c++14', 'c++1z',
                                                       'gnu++11', 'gnu++14', 'gnu++1z'],
                                                      'none')}
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return []
  
  
  class GnuCPPCompiler(GnuCompiler, CPPCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrap, defines):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none', 'c++03', 'c++11', 'c++14', 'c++1z',
                                                       'gnu++03', 'gnu++11', 'gnu++14', 'gnu++1z'],
                                                      'none'),
                  'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',
                                                             'STL debug mode',
                                                             False)}
          if self.gcc_type == GCC_MINGW:
              opts.update({
                  'cpp_winlibs': coredata.UserStringArrayOption('cpp_winlibs', 'Standard Win libraries to link against',
                                                                gnu_winlibs), })
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          if options['cpp_debugstl'].value:
              args.append('-D_GLIBCXX_DEBUG=1')
          return args
  
      def get_option_link_args(self, options):
          if self.gcc_type == GCC_MINGW:
              return options['cpp_winlibs'].value[:]
          return []
  
  
  class IntelCPPCompiler(IntelCompiler, CPPCompiler):
      def __init__(self, exelist, version, icc_type, is_cross, exe_wrap):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          IntelCompiler.__init__(self, icc_type)
          self.lang_header = 'c++-header'
          default_warn_args = ['-Wall', '-w3', '-diag-disable:remark',
                               '-Wpch-messages', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          c_stds = []
          g_stds = ['gnu++98']
          if version_compare(self.version, '>=15.0.0'):
              c_stds += ['c++11', 'c++14']
              g_stds += ['gnu++11']
          if version_compare(self.version, '>=16.0.0'):
              c_stds += ['c++17']
          if version_compare(self.version, '>=17.0.0'):
              g_stds += ['gnu++14']
          opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none'] + c_stds + g_stds,
                                                      'none'),
                  'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',
                                                             'STL debug mode',
                                                             False)}
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          if options['cpp_debugstl'].value:
              args.append('-D_GLIBCXX_DEBUG=1')
          return args
  
      def get_option_link_args(self, options):
          return []
  
      def has_multi_arguments(self, args, env):
          return super().has_multi_arguments(args + ['-diag-error', '10006'], env)
  
  
  class VisualStudioCPPCompiler(VisualStudioCCompiler, CPPCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'cpp'
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          VisualStudioCCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          self.base_options = ['b_pch'] # FIXME add lto, pgo and the like
  
      def get_options(self):
          return {'cpp_eh': coredata.UserComboOption('cpp_eh',
                                                     'C++ exception handling type.',
                                                     ['none', 'a', 's', 'sc'],
                                                     'sc'),
                  'cpp_winlibs': coredata.UserStringArrayOption('cpp_winlibs',
                                                                'Windows libs to link against.',
                                                                msvc_winlibs)
                  }
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_eh']
          if std.value != 'none':
              args.append('/EH' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return options['cpp_winlibs'].value[:]
  
      def get_compiler_check_args(self):
          # Visual Studio C++ compiler doesn't support -fpermissive,
          # so just use the plain C args.
          return super(VisualStudioCCompiler, self).get_compiler_check_args()
  
files: mesonbuild/compilers/cpp.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.
  
  from .. import coredata
  from ..mesonlib import version_compare
  
  from .c import CCompiler, VisualStudioCCompiler
  from .compilers import (
      GCC_MINGW,
      gnu_winlibs,
      msvc_winlibs,
      ClangCompiler,
      GnuCompiler,
      IntelCompiler,
  )
  
  class CPPCompiler(CCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          # If a child ObjCPP class has already set it, don't set it ourselves
          if not hasattr(self, 'language'):
              self.language = 'cpp'
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def get_no_stdinc_args(self):
          return ['-nostdinc++']
  
      def sanity_check(self, work_dir, environment):
          code = 'class breakCCompiler;int main(int argc, char **argv) { return 0; }\n'
          return self.sanity_check_impl(work_dir, environment, 'sanitycheckcpp.cc', code)
  
      def get_compiler_check_args(self):
          # -fpermissive allows non-conforming code to compile which is necessary
          # for many C++ checks. Particularly, the has_header_symbol check is
          # too strict without this and always fails.
          return super().get_compiler_check_args() + ['-fpermissive']
  
      def has_header_symbol(self, hname, symbol, prefix, env, extra_args=None, dependencies=None):
          # Check if it's a C-like symbol
          if super().has_header_symbol(hname, symbol, prefix, env, extra_args, dependencies):
              return True
          # Check if it's a class or a template
          if extra_args is None:
              extra_args = []
          fargs = {'prefix': prefix, 'header': hname, 'symbol': symbol}
          t = '''{prefix}
          #include <{header}>
          using {symbol};
          int main () {{ return 0; }}'''
          return self.compiles(t.format(**fargs), env, extra_args, dependencies)
  
  
  class ClangCPPCompiler(ClangCompiler, CPPCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          return {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none', 'c++03', 'c++11', 'c++14', 'c++1z',
                                                       'gnu++11', 'gnu++14', 'gnu++1z'],
                                                      'none')}
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return []
  
  
  class GnuCPPCompiler(GnuCompiler, CPPCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrap, defines):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none', 'c++03', 'c++11', 'c++14', 'c++1z',
                                                       'gnu++03', 'gnu++11', 'gnu++14', 'gnu++1z'],
                                                      'none'),
                  'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',
                                                             'STL debug mode',
                                                             False)}
          if self.gcc_type == GCC_MINGW:
              opts.update({
                  'cpp_winlibs': coredata.UserStringArrayOption('cpp_winlibs', 'Standard Win libraries to link against',
                                                                gnu_winlibs), })
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          if options['cpp_debugstl'].value:
              args.append('-D_GLIBCXX_DEBUG=1')
          return args
  
      def get_option_link_args(self, options):
          if self.gcc_type == GCC_MINGW:
              return options['cpp_winlibs'].value[:]
          return []
  
  
  class IntelCPPCompiler(IntelCompiler, CPPCompiler):
      def __init__(self, exelist, version, icc_type, is_cross, exe_wrap):
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          IntelCompiler.__init__(self, icc_type)
          self.lang_header = 'c++-header'
          default_warn_args = ['-Wall', '-w3', '-diag-disable:remark',
                               '-Wpch-messages', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
      def get_options(self):
          c_stds = []
          g_stds = ['gnu++98']
          if version_compare(self.version, '>=15.0.0'):
              c_stds += ['c++11', 'c++14']
              g_stds += ['gnu++11']
          if version_compare(self.version, '>=16.0.0'):
              c_stds += ['c++17']
          if version_compare(self.version, '>=17.0.0'):
              g_stds += ['gnu++14']
          opts = {'cpp_std': coredata.UserComboOption('cpp_std', 'C++ language standard to use',
                                                      ['none'] + c_stds + g_stds,
                                                      'none'),
                  'cpp_debugstl': coredata.UserBooleanOption('cpp_debugstl',
                                                             'STL debug mode',
                                                             False)}
          return opts
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_std']
          if std.value != 'none':
              args.append('-std=' + std.value)
          if options['cpp_debugstl'].value:
              args.append('-D_GLIBCXX_DEBUG=1')
          return args
  
      def get_option_link_args(self, options):
          return []
  
      def has_multi_arguments(self, args, env):
          return super().has_multi_arguments(args + ['-diag-error', '10006'], env)
  
  
  class VisualStudioCPPCompiler(VisualStudioCCompiler, CPPCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'cpp'
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          VisualStudioCCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
          self.base_options = ['b_pch'] # FIXME add lto, pgo and the like
  
      def get_options(self):
          return {'cpp_eh': coredata.UserComboOption('cpp_eh',
                                                     'C++ exception handling type.',
                                                     ['none', 'a', 's', 'sc'],
                                                     'sc'),
                  'cpp_winlibs': coredata.UserStringArrayOption('cpp_winlibs',
                                                                'Windows libs to link against.',
                                                                msvc_winlibs)
                  }
  
      def get_option_compile_args(self, options):
          args = []
          std = options['cpp_eh']
          if std.value != 'none':
              args.append('/EH' + std.value)
          return args
  
      def get_option_link_args(self, options):
          return options['cpp_winlibs'].value[:]
  
      def get_compiler_check_args(self):
          # Visual Studio C++ compiler doesn't support -fpermissive,
          # so just use the plain C args.
          return super(VisualStudioCCompiler, self).get_compiler_check_args()
  
files: mesonbuild/compilers/cpp.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .compilers import Compiler, mono_buildtype_args
  
  class MonoCompiler(Compiler):
      def __init__(self, exelist, version):
          self.language = 'cs'
          super().__init__(exelist, version)
          self.id = 'mono'
          self.monorunner = 'mono'
  
      def get_display_language(self):
          return 'C#'
  
      def get_output_args(self, fname):
          return ['-out:' + fname]
  
      def get_link_args(self, fname):
          return ['-r:' + fname]
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return []
  
      def get_werror_args(self):
          return ['-warnaserror']
  
      def split_shlib_to_parts(self, fname):
          return None, fname
  
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return []
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return []
  
      def get_linker_exelist(self):
          return self.exelist[:]
  
      def get_compile_only_args(self):
          return []
  
      def get_linker_output_args(self, outputname):
          return []
  
      def get_coverage_args(self):
          return []
  
      def get_coverage_link_args(self):
          return []
  
      def get_std_exe_link_args(self):
          return []
  
      def get_include_args(self, path):
          return []
  
      def get_pic_args(self):
          return []
  
      def name_string(self):
          return ' '.join(self.exelist)
  
      def get_pch_use_args(self, pch_dir, header):
          return []
  
      def get_pch_name(self, header_name):
          return ''
  
      def sanity_check(self, work_dir, environment):
          src = 'sanity.cs'
          obj = 'sanity.exe'
          source_name = os.path.join(work_dir, src)
          with open(source_name, 'w') as ofile:
              ofile.write('''public class Sanity {
      static public void Main () {
      }
  }
  ''')
          pc = subprocess.Popen(self.exelist + [src], cwd=work_dir)
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('Mono compiler %s can not compile programs.' % self.name_string())
          cmdlist = [self.monorunner, obj]
          pe = subprocess.Popen(cmdlist, cwd=work_dir)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by Mono compiler %s are not runnable.' % self.name_string())
  
      def needs_static_linker(self):
          return False
  
      def get_buildtype_args(self, buildtype):
          return mono_buildtype_args[buildtype]
  
files: mesonbuild/compilers/cs.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .compilers import Compiler, mono_buildtype_args
  
  class MonoCompiler(Compiler):
      def __init__(self, exelist, version):
          self.language = 'cs'
          super().__init__(exelist, version)
          self.id = 'mono'
          self.monorunner = 'mono'
  
      def get_output_args(self, fname):
          return ['-out:' + fname]
  
      def get_link_args(self, fname):
          return ['-r:' + fname]
  
      def get_soname_args(self, prefix, shlib_name, suffix, path, soversion, is_shared_module):
          return []
  
      def get_werror_args(self):
          return ['-warnaserror']
  
      def split_shlib_to_parts(self, fname):
          return None, fname
  
      def build_rpath_args(self, build_dir, from_dir, rpath_paths, install_rpath):
          return []
  
      def get_dependency_gen_args(self, outtarget, outfile):
          return []
  
      def get_linker_exelist(self):
          return self.exelist[:]
  
      def get_compile_only_args(self):
          return []
  
      def get_linker_output_args(self, outputname):
          return []
  
      def get_coverage_args(self):
          return []
  
      def get_coverage_link_args(self):
          return []
  
      def get_std_exe_link_args(self):
          return []
  
      def get_include_args(self, path):
          return []
  
      def get_pic_args(self):
          return []
  
      def name_string(self):
          return ' '.join(self.exelist)
  
      def get_pch_use_args(self, pch_dir, header):
          return []
  
      def get_pch_name(self, header_name):
          return ''
  
      def sanity_check(self, work_dir, environment):
          src = 'sanity.cs'
          obj = 'sanity.exe'
          source_name = os.path.join(work_dir, src)
          with open(source_name, 'w') as ofile:
              ofile.write('''public class Sanity {
      static public void Main () {
      }
  }
  ''')
          pc = subprocess.Popen(self.exelist + [src], cwd=work_dir)
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('Mono compiler %s can not compile programs.' % self.name_string())
          cmdlist = [self.monorunner, obj]
          pe = subprocess.Popen(cmdlist, cwd=work_dir)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by Mono compiler %s are not runnable.' % self.name_string())
  
      def needs_static_linker(self):
          return False
  
      def get_buildtype_args(self, buildtype):
          return mono_buildtype_args[buildtype]
  
files: mesonbuild/compilers/cs.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .c import CCompiler
  from .compilers import ClangCompiler, GnuCompiler
  
  class ObjCCompiler(CCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'objc'
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def get_display_language(self):
          return 'Objective-C'
  
      def sanity_check(self, work_dir, environment):
          # TODO try to use sanity_check_impl instead of duplicated code
          source_name = os.path.join(work_dir, 'sanitycheckobjc.m')
          binary_name = os.path.join(work_dir, 'sanitycheckobjc')
          extra_flags = self.get_cross_extra_flags(environment, link=False)
          if self.is_cross:
              extra_flags += self.get_compile_only_args()
          with open(source_name, 'w') as ofile:
              ofile.write('#import<stdio.h>\n'
                          'int main(int argc, char **argv) { return 0; }\n')
          pc = subprocess.Popen(self.exelist + extra_flags + [source_name, '-o', binary_name])
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('ObjC compiler %s can not compile programs.' % self.name_string())
          if self.is_cross:
              # Can't check if the binaries run so we have to assume they do
              return
          pe = subprocess.Popen(binary_name)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by ObjC compiler %s are not runnable.' % self.name_string())
  
  
  class GnuObjCCompiler(GnuCompiler, ObjCCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          ObjCCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
  
  class ClangObjCCompiler(ClangCompiler, GnuObjCCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          GnuObjCCompiler.__init__(self, exelist, version, cltype, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage']
  
files: mesonbuild/compilers/objc.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .c import CCompiler
  from .compilers import ClangCompiler, GnuCompiler
  
  class ObjCCompiler(CCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'objc'
          CCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def sanity_check(self, work_dir, environment):
          # TODO try to use sanity_check_impl instead of duplicated code
          source_name = os.path.join(work_dir, 'sanitycheckobjc.m')
          binary_name = os.path.join(work_dir, 'sanitycheckobjc')
          extra_flags = self.get_cross_extra_flags(environment, link=False)
          if self.is_cross:
              extra_flags += self.get_compile_only_args()
          with open(source_name, 'w') as ofile:
              ofile.write('#import<stdio.h>\n'
                          'int main(int argc, char **argv) { return 0; }\n')
          pc = subprocess.Popen(self.exelist + extra_flags + [source_name, '-o', binary_name])
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('ObjC compiler %s can not compile programs.' % self.name_string())
          if self.is_cross:
              # Can't check if the binaries run so we have to assume they do
              return
          pe = subprocess.Popen(binary_name)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by ObjC compiler %s are not runnable.' % self.name_string())
  
  
  class GnuObjCCompiler(GnuCompiler, ObjCCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          ObjCCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
  
  class ClangObjCCompiler(ClangCompiler, GnuObjCCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          GnuObjCCompiler.__init__(self, exelist, version, cltype, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage']
  
files: mesonbuild/compilers/objc.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .cpp import CPPCompiler
  from .compilers import ClangCompiler, GnuCompiler
  
  class ObjCPPCompiler(CPPCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'objcpp'
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def get_display_language(self):
          return 'Objective-C++'
  
      def sanity_check(self, work_dir, environment):
          # TODO try to use sanity_check_impl instead of duplicated code
          source_name = os.path.join(work_dir, 'sanitycheckobjcpp.mm')
          binary_name = os.path.join(work_dir, 'sanitycheckobjcpp')
          extra_flags = self.get_cross_extra_flags(environment, link=False)
          if self.is_cross:
              extra_flags += self.get_compile_only_args()
          with open(source_name, 'w') as ofile:
              ofile.write('#import<stdio.h>\n'
                          'class MyClass;'
                          'int main(int argc, char **argv) { return 0; }\n')
          pc = subprocess.Popen(self.exelist + extra_flags + [source_name, '-o', binary_name])
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('ObjC++ compiler %s can not compile programs.' % self.name_string())
          if self.is_cross:
              # Can't check if the binaries run so we have to assume they do
              return
          pe = subprocess.Popen(binary_name)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by ObjC++ compiler %s are not runnable.' % self.name_string())
  
  
  class GnuObjCPPCompiler(GnuCompiler, ObjCPPCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          ObjCPPCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
  
  class ClangObjCPPCompiler(ClangCompiler, GnuObjCPPCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          GnuObjCPPCompiler.__init__(self, exelist, version, cltype, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage']
  
files: mesonbuild/compilers/objcpp.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.path, subprocess
  
  from ..mesonlib import EnvironmentException
  
  from .cpp import CPPCompiler
  from .compilers import ClangCompiler, GnuCompiler
  
  class ObjCPPCompiler(CPPCompiler):
      def __init__(self, exelist, version, is_cross, exe_wrap):
          self.language = 'objcpp'
          CPPCompiler.__init__(self, exelist, version, is_cross, exe_wrap)
  
      def sanity_check(self, work_dir, environment):
          # TODO try to use sanity_check_impl instead of duplicated code
          source_name = os.path.join(work_dir, 'sanitycheckobjcpp.mm')
          binary_name = os.path.join(work_dir, 'sanitycheckobjcpp')
          extra_flags = self.get_cross_extra_flags(environment, link=False)
          if self.is_cross:
              extra_flags += self.get_compile_only_args()
          with open(source_name, 'w') as ofile:
              ofile.write('#import<stdio.h>\n'
                          'class MyClass;'
                          'int main(int argc, char **argv) { return 0; }\n')
          pc = subprocess.Popen(self.exelist + extra_flags + [source_name, '-o', binary_name])
          pc.wait()
          if pc.returncode != 0:
              raise EnvironmentException('ObjC++ compiler %s can not compile programs.' % self.name_string())
          if self.is_cross:
              # Can't check if the binaries run so we have to assume they do
              return
          pe = subprocess.Popen(binary_name)
          pe.wait()
          if pe.returncode != 0:
              raise EnvironmentException('Executables created by ObjC++ compiler %s are not runnable.' % self.name_string())
  
  
  class GnuObjCPPCompiler(GnuCompiler, ObjCPPCompiler):
      def __init__(self, exelist, version, gcc_type, is_cross, exe_wrapper=None, defines=None):
          ObjCPPCompiler.__init__(self, exelist, version, is_cross, exe_wrapper)
          GnuCompiler.__init__(self, gcc_type, defines)
          default_warn_args = ['-Wall', '-Winvalid-pch', '-Wnon-virtual-dtor']
          self.warn_args = {'1': default_warn_args,
                            '2': default_warn_args + ['-Wextra'],
                            '3': default_warn_args + ['-Wextra', '-Wpedantic']}
  
  
  class ClangObjCPPCompiler(ClangCompiler, GnuObjCPPCompiler):
      def __init__(self, exelist, version, cltype, is_cross, exe_wrapper=None):
          GnuObjCPPCompiler.__init__(self, exelist, version, cltype, is_cross, exe_wrapper)
          ClangCompiler.__init__(self, cltype)
          self.base_options = ['b_pch', 'b_lto', 'b_pgo', 'b_sanitize', 'b_coverage']
  
files: mesonbuild/compilers/objcpp.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.
  
  from . import mparser
  from . import environment
  from . import coredata
  from . import dependencies
  from . import mlog
  from . import build
  from . import optinterpreter
  from . import compilers
  from .wrap import wrap, WrapMode
  from . import mesonlib
  from .mesonlib import FileMode, Popen_safe, get_meson_script
  from .dependencies import ExternalProgram
  from .dependencies import InternalDependency, Dependency, DependencyException
  from .interpreterbase import InterpreterBase
  from .interpreterbase import check_stringlist, noPosargs, noKwargs, stringArgs
  from .interpreterbase import InterpreterException, InvalidArguments, InvalidCode
  from .interpreterbase import InterpreterObject, MutableInterpreterObject
  from .modules import ModuleReturnValue
  
  import os, sys, shutil, uuid
  import re
  from collections import namedtuple
  
  import importlib
  
  run_depr_printed = False
  
  def stringifyUserArguments(args):
      if isinstance(args, list):
          return '[%s]' % ', '.join([stringifyUserArguments(x) for x in args])
      elif isinstance(args, int):
          return str(args)
      elif isinstance(args, str):
          return "'%s'" % args
      raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
  
  class TryRunResultHolder(InterpreterObject):
      def __init__(self, res):
          super().__init__()
          self.res = res
          self.methods.update({'returncode': self.returncode_method,
                               'compiled': self.compiled_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def returncode_method(self, args, kwargs):
          return self.res.returncode
  
      def compiled_method(self, args, kwargs):
          return self.res.compiled
  
      def stdout_method(self, args, kwargs):
          return self.res.stdout
  
      def stderr_method(self, args, kwargs):
          return self.res.stderr
  
  class RunProcess(InterpreterObject):
  
      def __init__(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir=False):
          super().__init__()
          if not isinstance(cmd, ExternalProgram):
              raise AssertionError('BUG: RunProcess must be passed an ExternalProgram')
          pc, self.stdout, self.stderr = self.run_command(cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir)
          self.returncode = pc.returncode
          self.methods.update({'returncode': self.returncode_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def run_command(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir):
          command_array = cmd.get_command() + args
          env = {'MESON_SOURCE_ROOT': source_dir,
                 'MESON_BUILD_ROOT': build_dir,
                 'MESON_SUBDIR': subdir,
                 'MESONINTROSPECT': mesonintrospect}
          if in_builddir:
              cwd = os.path.join(build_dir, subdir)
          else:
              cwd = os.path.join(source_dir, subdir)
          child_env = os.environ.copy()
          child_env.update(env)
          mlog.debug('Running command:', ' '.join(command_array))
          try:
              return Popen_safe(command_array, env=child_env, cwd=cwd)
          except FileNotFoundError:
              raise InterpreterException('Could not execute command "%s".' % ' '.join(command_array))
  
      def returncode_method(self, args, kwargs):
          return self.returncode
  
      def stdout_method(self, args, kwargs):
          return self.stdout
  
      def stderr_method(self, args, kwargs):
          return self.stderr
  
  class ConfigureFileHolder(InterpreterObject):
  
      def __init__(self, subdir, sourcename, targetname, configuration_data):
          InterpreterObject.__init__(self)
          self.held_object = build.ConfigureFile(subdir, sourcename, targetname, configuration_data)
  
  
  class EnvironmentVariablesHolder(MutableInterpreterObject):
      def __init__(self):
          super().__init__()
          self.held_object = build.EnvironmentVariables()
          self.methods.update({'set': self.set_method,
                               'append': self.append_method,
                               'prepend': self.prepend_method,
                               })
  
      def __repr__(self):
          repr_str = "<{0}: {1}>"
          return repr_str.format(self.__class__.__name__, self.held_object.envvars)
  
      @stringArgs
      def add_var(self, method, args, kwargs):
          if not isinstance(kwargs.get("separator", ""), str):
              raise InterpreterException("EnvironmentVariablesHolder methods 'separator'"
                                         " argument needs to be a string.")
          if len(args) < 2:
              raise InterpreterException("EnvironmentVariablesHolder methods require at least"
                                         "2 arguments, first is the name of the variable and"
                                         " following one are values")
          self.held_object.envvars.append((method, args[0], args[1:], kwargs))
  
      def set_method(self, args, kwargs):
          self.add_var(self.held_object.set, args, kwargs)
  
      def append_method(self, args, kwargs):
          self.add_var(self.held_object.append, args, kwargs)
  
      def prepend_method(self, args, kwargs):
          self.add_var(self.held_object.prepend, args, kwargs)
  
  
  class ConfigurationDataHolder(MutableInterpreterObject):
      def __init__(self):
          super().__init__()
          self.used = False # These objects become immutable after use in configure_file.
          self.held_object = build.ConfigurationData()
          self.methods.update({'set': self.set_method,
                               'set10': self.set10_method,
                               'set_quoted': self.set_quoted_method,
                               'has': self.has_method,
                               'get': self.get_method,
                               })
  
      def is_used(self):
          return self.used
  
      def mark_used(self):
          self.used = True
  
      def validate_args(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException("Configuration set requires 2 arguments.")
          if self.used:
              raise InterpreterException("Can not set values on configuration object that has been used.")
          name = args[0]
          val = args[1]
          desc = kwargs.get('description', None)
          if not isinstance(name, str):
              raise InterpreterException("First argument to set must be a string.")
          if desc is not None and not isinstance(desc, str):
              raise InterpreterException('Description must be a string.')
  
          return name, val, desc
  
      def set_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          self.held_object.values[name] = (val, desc)
  
      def set_quoted_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if not isinstance(val, str):
              raise InterpreterException("Second argument to set_quoted must be a string.")
          escaped_val = '\\"'.join(val.split('"'))
          self.held_object.values[name] = ('"' + escaped_val + '"', desc)
  
      def set10_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if val:
              self.held_object.values[name] = (1, desc)
          else:
              self.held_object.values[name] = (0, desc)
  
      def has_method(self, args, kwargs):
          return args[0] in self.held_object.values
  
      def get_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              return self.held_object.get(name)[0]
          if len(args) > 1:
              return args[1]
          raise InterpreterException('Entry %s not in configuration data.' % name)
  
      def get(self, name):
          return self.held_object.values[name]     # (val, desc)
  
      def keys(self):
          return self.held_object.values.keys()
  
  # Interpreter objects can not be pickled so we must have
  # these wrappers.
  
  class DependencyHolder(InterpreterObject):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          self.held_object = dep
          self.methods.update({'found': self.found_method,
                               'type_name': self.type_name_method,
                               'version': self.version_method,
                               'get_pkgconfig_variable': self.pkgconfig_method,
                               })
  
      def type_name_method(self, args, kwargs):
          return self.held_object.type_name
  
      def found_method(self, args, kwargs):
          if self.held_object.type_name == 'internal':
              return True
          return self.held_object.found()
  
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      def pkgconfig_method(self, args, kwargs):
          if not isinstance(args, list):
              args = [args]
          if len(args) != 1:
              raise InterpreterException('get_pkgconfig_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_pkgconfig_variable(varname)
  
  class InternalDependencyHolder(InterpreterObject):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          self.held_object = dep
          self.methods.update({'found': self.found_method,
                               'version': self.version_method,
                               })
  
      def found_method(self, args, kwargs):
          return True
  
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
  class ExternalProgramHolder(InterpreterObject):
      def __init__(self, ep):
          InterpreterObject.__init__(self)
          self.held_object = ep
          self.methods.update({'found': self.found_method,
                               'path': self.path_method})
  
      def found_method(self, args, kwargs):
          return self.found()
  
      def path_method(self, args, kwargs):
          return self.held_object.get_path()
  
      def found(self):
          return self.held_object.found()
  
      def get_command(self):
          return self.held_object.get_command()
  
      def get_name(self):
          return self.held_object.get_name()
  
  class ExternalLibraryHolder(InterpreterObject):
      def __init__(self, el):
          InterpreterObject.__init__(self)
          self.held_object = el
          self.methods.update({'found': self.found_method})
  
      def found(self):
          return self.held_object.found()
  
      def found_method(self, args, kwargs):
          return self.found()
  
      def get_name(self):
          return self.held_object.name
  
      def get_compile_args(self):
          return self.held_object.get_compile_args()
  
      def get_link_args(self):
          return self.held_object.get_link_args()
  
      def get_exe_args(self):
          return self.held_object.get_exe_args()
  
  class GeneratorHolder(InterpreterObject):
      def __init__(self, interpreter, args, kwargs):
          super().__init__()
          self.interpreter = interpreter
          self.held_object = build.Generator(args, kwargs)
          self.methods.update({'process': self.process_method})
  
      def process_method(self, args, kwargs):
          extras = mesonlib.stringlistify(kwargs.get('extra_args', []))
          gl = self.held_object.process_files('Generator', args, self.interpreter, extra_args=extras)
          return GeneratedListHolder(gl)
  
  
  class GeneratedListHolder(InterpreterObject):
      def __init__(self, arg1, extra_args=[]):
          super().__init__()
          if isinstance(arg1, GeneratorHolder):
              self.held_object = build.GeneratedList(arg1.held_object, extra_args)
          else:
              self.held_object = arg1
  
      def __repr__(self):
          r = '<{}: {!r}>'
          return r.format(self.__class__.__name__, self.held_object.get_outputs())
  
      def add_file(self, a):
          self.held_object.add_file(a)
  
  class BuildMachine(InterpreterObject):
      def __init__(self, compilers):
          self.compilers = compilers
          InterpreterObject.__init__(self)
          self.held_object = environment.MachineInfo(environment.detect_system(),
                                                     environment.detect_cpu_family(self.compilers),
                                                     environment.detect_cpu(self.compilers),
                                                     sys.byteorder)
          self.methods.update({'system': self.system_method,
                               'cpu_family': self.cpu_family_method,
                               'cpu': self.cpu_method,
                               'endian': self.endian_method,
                               })
  
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  # This class will provide both host_machine and
  # target_machine
  class CrossMachineInfo(InterpreterObject):
      def __init__(self, cross_info):
          InterpreterObject.__init__(self)
          minimum_cross_info = {'cpu', 'cpu_family', 'endian', 'system'}
          if set(cross_info) < minimum_cross_info:
              raise InterpreterException(
                  'Machine info is currently {}\n'.format(cross_info) +
                  'but is missing {}.'.format(minimum_cross_info - set(cross_info)))
          self.info = cross_info
          self.held_object = environment.MachineInfo(cross_info['system'],
                                                     cross_info['cpu_family'],
                                                     cross_info['cpu'],
                                                     cross_info['endian'])
          self.methods.update({'system': self.system_method,
                               'cpu': self.cpu_method,
                               'cpu_family': self.cpu_family_method,
                               'endian': self.endian_method,
                               })
  
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  class IncludeDirsHolder(InterpreterObject):
      def __init__(self, idobj):
          super().__init__()
          self.held_object = idobj
  
  class Headers(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.install_subdir = kwargs.get('subdir', '')
          self.custom_install_dir = kwargs.get('install_dir', None)
          if self.custom_install_dir is not None:
              if not isinstance(self.custom_install_dir, str):
                  raise InterpreterException('Custom_install_dir must be a string.')
  
      def set_install_subdir(self, subdir):
          self.install_subdir = subdir
  
      def get_install_subdir(self):
          return self.install_subdir
  
      def get_sources(self):
          return self.sources
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
  class DataHolder(InterpreterObject):
      def __init__(self, data):
          super().__init__()
          self.held_object = data
  
      def get_source_subdir(self):
          return self.held_object.source_subdir
  
      def get_sources(self):
          return self.held_object.sources
  
      def get_install_dir(self):
          return self.held_object.install_dir
  
  class InstallDir(InterpreterObject):
      def __init__(self, src_subdir, inst_subdir, install_dir, install_mode):
          InterpreterObject.__init__(self)
          self.source_subdir = src_subdir
          self.installable_subdir = inst_subdir
          self.install_dir = install_dir
          self.install_mode = install_mode
  
  class Man(InterpreterObject):
  
      def __init__(self, source_subdir, sources, kwargs):
          InterpreterObject.__init__(self)
          self.source_subdir = source_subdir
          self.sources = sources
          self.validate_sources()
          if len(kwargs) > 1:
              raise InvalidArguments('Man function takes at most one keyword arguments.')
          self.custom_install_dir = kwargs.get('install_dir', None)
          if self.custom_install_dir is not None and not isinstance(self.custom_install_dir, str):
              raise InterpreterException('Custom_install_dir must be a string.')
  
      def validate_sources(self):
          for s in self.sources:
              try:
                  num = int(s.split('.')[-1])
              except (IndexError, ValueError):
                  num = 0
              if num < 1 or num > 8:
                  raise InvalidArguments('Man file must have a file extension of a number between 1 and 8')
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_sources(self):
          return self.sources
  
      def get_source_subdir(self):
          return self.source_subdir
  
  class GeneratedObjectsHolder(InterpreterObject):
      def __init__(self, held_object):
          super().__init__()
          self.held_object = held_object
  
  class TargetHolder(InterpreterObject):
      def __init__(self):
          super().__init__()
  
  class BuildTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__()
          self.held_object = target
          self.interpreter = interp
          self.methods.update({'extract_objects': self.extract_objects_method,
                               'extract_all_objects': self.extract_all_objects_method,
                               'get_id': self.get_id_method,
                               'outdir': self.outdir_method,
                               'full_path': self.full_path_method,
                               'private_dir_include': self.private_dir_include_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.filename)
  
      def is_cross(self):
          return self.held_object.is_cross()
  
      def private_dir_include_method(self, args, kwargs):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [self.interpreter.backend.get_target_private_dir(self.held_object)]))
  
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      def outdir_method(self, args, kwargs):
          return self.interpreter.backend.get_target_dir(self.held_object)
  
      def extract_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_objects(args)
          return GeneratedObjectsHolder(gobjs)
  
      def extract_all_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_all_objects()
          return GeneratedObjectsHolder(gobjs)
  
      def get_id_method(self, args, kwargs):
          return self.held_object.get_id()
  
  class ExecutableHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class StaticLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedModuleHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class JarHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class CustomTargetHolder(TargetHolder):
      def __init__(self, object_to_hold, interp):
          super().__init__()
          self.held_object = object_to_hold
          self.interpreter = interp
          self.methods.update({'full_path': self.full_path_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
  class RunTargetHolder(InterpreterObject):
      def __init__(self, name, command, args, dependencies, subdir):
          super().__init__()
          self.held_object = build.RunTarget(name, command, args, dependencies, subdir)
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
  class Test(InterpreterObject):
      def __init__(self, name, suite, exe, is_parallel, cmd_args, env, should_fail, timeout, workdir):
          InterpreterObject.__init__(self)
          self.name = name
          self.suite = suite
          self.exe = exe
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
  
      def get_exe(self):
          return self.exe
  
      def get_name(self):
          return self.name
  
  class SubprojectHolder(InterpreterObject):
  
      def __init__(self, subinterpreter):
          super().__init__()
          self.held_object = subinterpreter
          self.methods.update({'get_variable': self.get_variable_method,
                               })
  
      def get_variable_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Get_variable takes one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Get_variable takes a string argument.')
          return self.held_object.variables[varname]
  
  class CompilerHolder(InterpreterObject):
      def __init__(self, compiler, env):
          InterpreterObject.__init__(self)
          self.compiler = compiler
          self.environment = env
          self.methods.update({'compiles': self.compiles_method,
                               'links': self.links_method,
                               'get_id': self.get_id_method,
                               'compute_int': self.compute_int_method,
                               'sizeof': self.sizeof_method,
                               'get_define': self.get_define_method,
                               'has_header': self.has_header_method,
                               'has_header_symbol': self.has_header_symbol_method,
                               'run': self.run_method,
                               'has_function': self.has_function_method,
                               'has_member': self.has_member_method,
                               'has_members': self.has_members_method,
                               'has_type': self.has_type_method,
                               'alignment': self.alignment_method,
                               'version': self.version_method,
                               'cmd_array': self.cmd_array_method,
                               'find_library': self.find_library_method,
                               'has_argument': self.has_argument_method,
                               'has_multi_arguments': self.has_multi_arguments_method,
                               'first_supported_argument': self.first_supported_argument_method,
                               'unittest_args': self.unittest_args_method,
                               'symbols_have_underscore_prefix': self.symbols_have_underscore_prefix_method,
                               })
  
      def version_method(self, args, kwargs):
          return self.compiler.version
  
      def cmd_array_method(self, args, kwargs):
          return self.compiler.exelist
  
      def determine_args(self, kwargs):
          nobuiltins = kwargs.get('no_builtin_args', False)
          if not isinstance(nobuiltins, bool):
              raise InterpreterException('Type of no_builtin_args not a boolean.')
          args = []
          incdirs = kwargs.get('include_directories', [])
          if not isinstance(incdirs, list):
              incdirs = [incdirs]
          for i in incdirs:
              if not isinstance(i, IncludeDirsHolder):
                  raise InterpreterException('Include directories argument must be an include_directories object.')
              for idir in i.held_object.get_incdirs():
                  idir = os.path.join(self.environment.get_source_dir(), idir)
                  args += self.compiler.get_include_args(idir, False)
          if not nobuiltins:
              opts = self.environment.coredata.compiler_options
              args += self.compiler.get_option_compile_args(opts)
              args += self.compiler.get_option_link_args(opts)
          args += mesonlib.stringlistify(kwargs.get('args', []))
          return args
  
      def determine_dependencies(self, kwargs):
          deps = kwargs.get('dependencies', None)
          if deps is not None:
              if not isinstance(deps, list):
                  deps = [deps]
              final_deps = []
              for d in deps:
                  try:
                      d = d.held_object
                  except Exception:
                      pass
                  if isinstance(d, InternalDependency) or not isinstance(d, Dependency):
                      raise InterpreterException('Dependencies must be external dependencies')
                  final_deps.append(d)
              deps = final_deps
          return deps
  
      def alignment_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Alignment method takes exactly one positional argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = mesonlib.stringlistify(kwargs.get('args', []))
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.alignment(typename, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for alignment of "', mlog.bold(typename), '": ', result, sep='')
          return result
  
      def run_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Run method takes exactly one positional argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.run(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if not result.compiled:
                  h = mlog.red('DID NOT COMPILE')
              elif result.returncode == 0:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO (%d)' % result.returncode)
              mlog.log('Checking if "', mlog.bold(testname), '" runs: ', h, sep='')
          return TryRunResultHolder(result)
  
      def get_id_method(self, args, kwargs):
          return self.compiler.get_id()
  
      def symbols_have_underscore_prefix_method(self, args, kwargs):
          '''
          Check if the compiler prefixes _ (underscore) to global C symbols
          See: https://en.wikipedia.org/wiki/Name_mangling#C
          '''
          return self.compiler.symbols_have_underscore_prefix(self.environment)
  
      def unittest_args_method(self, args, kwargs):
          # At time, only D compilers have this feature.
          if not hasattr(self.compiler, 'get_unittest_args'):
              raise InterpreterException('This {} compiler has no unittest arguments.'.format(self.compiler.get_display_language()))
          return self.compiler.get_unittest_args()
  
      def has_member_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Has_member takes exactly two arguments.')
          check_stringlist(args)
          typename = args[0]
          membername = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_member must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, [membername], prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has member "', mlog.bold(membername), '": ', hadtxt, sep='')
          return had
  
      def has_members_method(self, args, kwargs):
          check_stringlist(args)
          typename = args[0]
          membernames = args[1:]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_members must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, membernames, prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          members = mlog.bold(', '.join(['"{}"'.format(m) for m in membernames]))
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has members ', members, ': ', hadtxt, sep='')
          return had
  
      def has_function_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_function takes exactly one argument.')
          check_stringlist(args)
          funcname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_function must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_function(funcname, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for function "', mlog.bold(funcname), '": ', hadtxt, sep='')
          return had
  
      def has_type_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_type takes exactly one argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_type must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_type(typename, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for type "', mlog.bold(typename), '": ', hadtxt, sep='')
          return had
  
      def compute_int_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Compute_int takes exactly one argument.')
          check_stringlist(args)
          expression = args[0]
          prefix = kwargs.get('prefix', '')
          l = kwargs.get('low', -1024)
          h = kwargs.get('high', 1024)
          guess = kwargs.get('guess', None)
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of compute_int must be a string.')
          if not isinstance(l, int):
              raise InterpreterException('Low argument of compute_int must be an int.')
          if not isinstance(h, int):
              raise InterpreterException('High argument of compute_int must be an int.')
          if guess is not None and not isinstance(guess, int):
              raise InterpreterException('Guess argument of compute_int must be an int.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          res = self.compiler.compute_int(expression, l, h, guess, prefix, self.environment, extra_args, deps)
          mlog.log('Computing int of "%s": %d' % (expression, res))
          return res
  
      def sizeof_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Sizeof takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          esize = self.compiler.sizeof(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for size of "%s": %d' % (element, esize))
          return esize
  
      def get_define_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_define() takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of get_define() must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          value = self.compiler.get_define(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for value of define "%s": %s' % (element, value))
          return value
  
      def compiles_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('compiles method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.compiles(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" compiles: ', h, sep='')
          return result
  
      def links_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('links method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.links(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" links: ', h, sep='')
          return result
  
      def has_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('has_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Has header "%s":' % hname, h)
          return haz
  
      def has_header_symbol_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('has_header_symbol method takes exactly two arguments.')
          check_stringlist(args)
          hname = args[0]
          symbol = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header_symbol must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header_symbol(hname, symbol, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Header <{0}> has symbol "{1}":'.format(hname, symbol), h)
          return haz
  
      def find_library_method(self, args, kwargs):
          # TODO add dependencies support?
          if len(args) != 1:
              raise InterpreterException('find_library method takes one argument.')
          libname = args[0]
          if not isinstance(libname, str):
              raise InterpreterException('Library name not a string.')
          required = kwargs.get('required', True)
          if not isinstance(required, bool):
              raise InterpreterException('required must be boolean.')
          search_dirs = mesonlib.stringlistify(kwargs.get('dirs', []))
          for i in search_dirs:
              if not os.path.isabs(i):
                  raise InvalidCode('Search directory %s is not an absolute path.' % i)
          linkargs = self.compiler.find_library(libname, self.environment, search_dirs)
          if required and not linkargs:
              raise InterpreterException('{} library {!r} not found'.format(self.compiler.get_display_language(), libname))
          lib = dependencies.ExternalLibrary(libname, linkargs, self.environment,
                                             self.compiler.language)
          return ExternalLibraryHolder(lib)
  
      def has_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('Has_arg takes exactly one argument.')
          result = self.compiler.has_argument(args[0], self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Compiler for {} supports argument {}:'.format(self.compiler.get_display_language(), args[0]), h)
          return result
  
      def has_multi_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports arguments {}:'.format(
                  self.compiler.get_display_language(), ' '.join(args)),
              h)
          return result
  
      def first_supported_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.compiler.has_argument(i, self.environment):
                  mlog.log('First supported argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported argument:', mlog.red('None'))
          return []
  
  ModuleState = namedtuple('ModuleState', [
      'build_to_src', 'subdir', 'environment', 'project_name', 'project_version',
      'backend', 'compilers', 'targets', 'data', 'headers', 'man', 'global_args',
      'project_args', 'build_machine', 'host_machine', 'target_machine'])
  
  class ModuleHolder(InterpreterObject):
      def __init__(self, modname, module, interpreter):
          InterpreterObject.__init__(self)
          self.modname = modname
          self.held_object = module
          self.interpreter = interpreter
  
      def method_call(self, method_name, args, kwargs):
          try:
              fn = getattr(self.held_object, method_name)
          except AttributeError:
              raise InvalidArguments('Module %s does not have method %s.' % (self.modname, method_name))
          if method_name.startswith('_'):
              raise InvalidArguments('Function {!r} in module {!r} is private.'.format(method_name, self.modname))
          # This is not 100% reliable but we can't use hash()
          # because the Build object contains dicts and lists.
          num_targets = len(self.interpreter.build.targets)
          state = ModuleState(
              build_to_src=os.path.relpath(self.interpreter.environment.get_source_dir(),
                                           self.interpreter.environment.get_build_dir()),
              subdir=self.interpreter.subdir,
              environment=self.interpreter.environment,
              project_name=self.interpreter.build.project_name,
              project_version=self.interpreter.build.dep_manifest[self.interpreter.active_projectname],
              # The backend object is under-used right now, but we will need it:
              # https://github.com/mesonbuild/meson/issues/1419
              backend=self.interpreter.backend,
              compilers=self.interpreter.build.compilers,
              targets=self.interpreter.build.targets,
              data=self.interpreter.build.data,
              headers=self.interpreter.build.get_headers(),
              man=self.interpreter.build.get_man(),
              global_args=self.interpreter.build.global_args,
              project_args=self.interpreter.build.projects_args.get(self.interpreter.subproject, {}),
              build_machine=self.interpreter.builtin['build_machine'].held_object,
              host_machine=self.interpreter.builtin['host_machine'].held_object,
              target_machine=self.interpreter.builtin['target_machine'].held_object,
          )
          if self.held_object.is_snippet(method_name):
              value = fn(self.interpreter, state, args, kwargs)
              return self.interpreter.holderify(value)
          else:
              value = fn(state, args, kwargs)
              if num_targets != len(self.interpreter.build.targets):
                  raise InterpreterException('Extension module altered internal state illegally.')
              return self.interpreter.module_method_callback(value)
  
  class MesonMain(InterpreterObject):
      def __init__(self, build, interpreter):
          InterpreterObject.__init__(self)
          self.build = build
          self.interpreter = interpreter
          self._found_source_scripts = {}
          self.methods.update({'get_compiler': self.get_compiler_method,
                               'is_cross_build': self.is_cross_build_method,
                               'has_exe_wrapper': self.has_exe_wrapper_method,
                               'is_unity': self.is_unity_method,
                               'is_subproject': self.is_subproject_method,
                               'current_source_dir': self.current_source_dir_method,
                               'current_build_dir': self.current_build_dir_method,
                               'source_root': self.source_root_method,
                               'build_root': self.build_root_method,
                               'add_install_script': self.add_install_script_method,
                               'add_postconf_script': self.add_postconf_script_method,
                               'install_dependency_manifest': self.install_dependency_manifest_method,
                               'project_version': self.project_version_method,
                               'version': self.version_method,
                               'project_name': self.project_name_method,
                               'get_cross_property': self.get_cross_property_method,
                               'backend': self.backend_method,
                               })
  
      def _find_source_script(self, name, args):
          # Prefer scripts in the current source directory
          search_dir = os.path.join(self.interpreter.environment.source_dir,
                                    self.interpreter.subdir)
          key = (name, search_dir)
          if key in self._found_source_scripts:
              found = self._found_source_scripts[key]
          else:
              found = dependencies.ExternalProgram(name, search_dir=search_dir)
              if found.found():
                  self._found_source_scripts[key] = found
              else:
                  m = 'Script or command {!r} not found or not executable'
                  raise InterpreterException(m.format(name))
          return build.RunScript(found.get_command(), args)
  
      def add_install_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_install_script takes one or more arguments')
          check_stringlist(args, 'add_install_script args must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.install_scripts.append(script)
  
      def add_postconf_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_postconf_script takes one or more arguments')
          check_stringlist(args, 'add_postconf_script arguments must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.postconf_scripts.append(script)
  
      def current_source_dir_method(self, args, kwargs):
          src = self.interpreter.environment.source_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      def current_build_dir_method(self, args, kwargs):
          src = self.interpreter.environment.build_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      def backend_method(self, args, kwargs):
          return self.interpreter.backend.name
  
      def source_root_method(self, args, kwargs):
          return self.interpreter.environment.source_dir
  
      def build_root_method(self, args, kwargs):
          return self.interpreter.environment.build_dir
  
      def has_exe_wrapper_method(self, args, kwargs):
          if self.is_cross_build_method(None, None) and \
             'binaries' in self.build.environment.cross_info.config and \
             self.build.environment.cross_info.need_exe_wrapper():
              exe_wrap = self.build.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              if exe_wrap is None:
                  return False
          # We return True when exe_wrap is defined, when it's not needed, and
          # when we're compiling natively. The last two are semantically confusing.
          # Need to revisit this.
          return True
  
      def is_cross_build_method(self, args, kwargs):
          return self.build.environment.is_cross_build()
  
      def get_compiler_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_compiler_method must have one and only one argument.')
          cname = args[0]
          native = kwargs.get('native', None)
          if native is None:
              if self.build.environment.is_cross_build():
                  native = False
              else:
                  native = True
          if not isinstance(native, bool):
              raise InterpreterException('Type of "native" must be a boolean.')
          if native:
              clist = self.build.compilers
          else:
              clist = self.build.cross_compilers
          if cname in clist:
              return CompilerHolder(clist[cname], self.build.environment)
          raise InterpreterException('Tried to access compiler for unspecified language "%s".' % cname)
  
      def is_unity_method(self, args, kwargs):
          optval = self.interpreter.environment.coredata.get_builtin_option('unity')
          if optval == 'on' or (optval == 'subprojects' and self.interpreter.subproject != ''):
              return True
          return False
  
      def is_subproject_method(self, args, kwargs):
          return self.interpreter.is_subproject()
  
      def install_dependency_manifest_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Must specify manifest install file name')
          if not isinstance(args[0], str):
              raise InterpreterException('Argument must be a string.')
          self.build.dep_manifest_name = args[0]
  
      def project_version_method(self, args, kwargs):
          return self.build.dep_manifest[self.interpreter.active_projectname]['version']
  
      def version_method(self, args, kwargs):
          return coredata.version
  
      def project_name_method(self, args, kwargs):
          return self.interpreter.active_projectname
  
      def get_cross_property_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Must have one or two arguments.')
          propname = args[0]
          if not isinstance(propname, str):
              raise InterpreterException('Property name must be string.')
          try:
              props = self.interpreter.environment.cross_info.get_properties()
              return props[propname]
          except Exception:
              if len(args) == 2:
                  return args[1]
              raise InterpreterException('Unknown cross property: %s.' % propname)
  
  class Interpreter(InterpreterBase):
  
      def __init__(self, build, backend, subproject='', subdir='', subproject_dir='subprojects',
                   default_project_options=[]):
          super().__init__(build.environment.get_source_dir(), subdir)
          self.build = build
          self.environment = build.environment
          self.coredata = self.environment.get_coredata()
          self.backend = backend
          self.subproject = subproject
          self.subproject_dir = subproject_dir
          self.option_file = os.path.join(self.source_root, self.subdir, 'meson_options.txt')
          self.load_root_meson_file()
          self.sanity_check_ast()
          self.builtin.update({'meson': MesonMain(build, self)})
          self.generators = []
          self.visited_subdirs = {}
          self.project_args_frozen = False
          self.global_args_frozen = False  # implies self.project_args_frozen
          self.subprojects = {}
          self.subproject_stack = []
          self.default_project_options = default_project_options[:] # Passed from the outside, only used in subprojects.
          self.build_func_dict()
          self.parse_project()
          self.builtin['build_machine'] = BuildMachine(self.coredata.compilers)
          if not self.build.environment.is_cross_build():
              self.builtin['host_machine'] = self.builtin['build_machine']
              self.builtin['target_machine'] = self.builtin['build_machine']
          else:
              cross_info = self.build.environment.cross_info
              if cross_info.has_host():
                  self.builtin['host_machine'] = CrossMachineInfo(cross_info.config['host_machine'])
              else:
                  self.builtin['host_machine'] = self.builtin['build_machine']
              if cross_info.has_target():
                  self.builtin['target_machine'] = CrossMachineInfo(cross_info.config['target_machine'])
              else:
                  self.builtin['target_machine'] = self.builtin['host_machine']
          self.build_def_files = [os.path.join(self.subdir, environment.build_filename)]
  
      def build_func_dict(self):
          self.funcs.update({'project': self.func_project,
                             'message': self.func_message,
                             'error': self.func_error,
                             'executable': self.func_executable,
                             'dependency': self.func_dependency,
                             'static_library': self.func_static_lib,
                             'shared_library': self.func_shared_lib,
                             'shared_module': self.func_shared_module,
                             'library': self.func_library,
                             'jar': self.func_jar,
                             'build_target': self.func_build_target,
                             'custom_target': self.func_custom_target,
                             'run_target': self.func_run_target,
                             'generator': self.func_generator,
                             'test': self.func_test,
                             'benchmark': self.func_benchmark,
                             'install_headers': self.func_install_headers,
                             'install_man': self.func_install_man,
                             'subdir': self.func_subdir,
                             'install_data': self.func_install_data,
                             'install_subdir': self.func_install_subdir,
                             'configure_file': self.func_configure_file,
                             'include_directories': self.func_include_directories,
                             'add_global_arguments': self.func_add_global_arguments,
                             'add_project_arguments': self.func_add_project_arguments,
                             'add_global_link_arguments': self.func_add_global_link_arguments,
                             'add_project_link_arguments': self.func_add_project_link_arguments,
                             'add_test_setup': self.func_add_test_setup,
                             'add_languages': self.func_add_languages,
                             'find_program': self.func_find_program,
                             'find_library': self.func_find_library,
                             'configuration_data': self.func_configuration_data,
                             'run_command': self.func_run_command,
                             'gettext': self.func_gettext,
                             'option': self.func_option,
                             'get_option': self.func_get_option,
                             'subproject': self.func_subproject,
                             'vcs_tag': self.func_vcs_tag,
                             'set_variable': self.func_set_variable,
                             'is_variable': self.func_is_variable,
                             'get_variable': self.func_get_variable,
                             'import': self.func_import,
                             'files': self.func_files,
                             'declare_dependency': self.func_declare_dependency,
                             'assert': self.func_assert,
                             'environment': self.func_environment,
                             'join_paths': self.func_join_paths,
                             })
  
      def holderify(self, item):
          if isinstance(item, list):
              return [self.holderify(x) for x in item]
          if isinstance(item, build.CustomTarget):
              return CustomTargetHolder(item, self)
          elif isinstance(item, (int, str)) or item is None:
              return item
          elif isinstance(item, build.Executable):
              return ExecutableHolder(item, self)
          elif isinstance(item, build.GeneratedList):
              return GeneratedListHolder(item)
          elif isinstance(item, build.RunTarget):
              raise RuntimeError('This is not a pipe.')
          elif isinstance(item, build.RunScript):
              raise RuntimeError('Do not do this.')
          elif isinstance(item, build.Data):
              return DataHolder(item)
          elif isinstance(item, dependencies.InternalDependency):
              return InternalDependencyHolder(item)
          elif isinstance(item, dependencies.ExternalProgram):
              return ExternalProgramHolder(item)
          elif hasattr(item, 'held_object'):
              return item
          else:
              raise InterpreterException('Module returned a value of unknown type.')
  
      def process_new_values(self, invalues):
          if not isinstance(invalues, list):
              invalues = [invalues]
          for v in invalues:
              if isinstance(v, (build.BuildTarget, build.CustomTarget, build.RunTarget)):
                  self.add_target(v.name, v)
              elif isinstance(v, list):
                  self.module_method_callback(v)
              elif isinstance(v, build.GeneratedList):
                  pass
              elif isinstance(v, build.RunScript):
                  self.build.install_scripts.append(v)
              elif isinstance(v, build.Data):
                  self.build.data.append(v)
              elif isinstance(v, dependencies.ExternalProgram):
                  return ExternalProgramHolder(v)
              elif isinstance(v, dependencies.InternalDependency):
                  # FIXME: This is special cased and not ideal:
                  # The first source is our new VapiTarget, the rest are deps
                  self.process_new_values(v.sources[0])
              elif hasattr(v, 'held_object'):
                  pass
              else:
                  raise InterpreterException('Module returned a value of unknown type.')
  
      def module_method_callback(self, return_object):
          if not isinstance(return_object, ModuleReturnValue):
              raise InterpreterException('Bug in module, it returned an invalid object')
          invalues = return_object.new_objects
          self.process_new_values(invalues)
          return self.holderify(return_object.return_value)
  
      def get_build_def_files(self):
          return self.build_def_files
  
      def get_variables(self):
          return self.variables
  
      def check_cross_stdlibs(self):
          if self.build.environment.is_cross_build():
              cross_info = self.build.environment.cross_info
              for l, c in self.build.cross_compilers.items():
                  try:
                      di = mesonlib.stringlistify(cross_info.get_stdlib(l))
                      if len(di) != 2:
                          raise InterpreterException('Stdlib definition for %s should have exactly two elements.'
                                                     % l)
                      projname, depname = di
                      subproj = self.do_subproject(projname, {})
                      self.build.cross_stdlibs[l] = subproj.get_variable_method([depname], {})
                  except KeyError:
                      pass
  
      @stringArgs
      @noKwargs
      def func_import(self, node, args, kwargs):
          if len(args) != 1:
              raise InvalidCode('Import takes one argument.')
          modname = args[0]
          if modname not in self.environment.coredata.modules:
              try:
                  module = importlib.import_module('mesonbuild.modules.' + modname)
              except ImportError:
                  raise InvalidArguments('Module "%s" does not exist' % (modname, ))
              self.environment.coredata.modules[modname] = module.initialize()
          return ModuleHolder(modname, self.environment.coredata.modules[modname], self)
  
      @stringArgs
      @noKwargs
      def func_files(self, node, args, kwargs):
          return [mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, fname) for fname in args]
  
      @noPosargs
      def func_declare_dependency(self, node, args, kwargs):
          version = kwargs.get('version', self.project_version)
          if not isinstance(version, str):
              raise InterpreterException('Version must be a string.')
          incs = kwargs.get('include_directories', [])
          if not isinstance(incs, list):
              incs = [incs]
          libs = kwargs.get('link_with', [])
          if not isinstance(libs, list):
              libs = [libs]
          sources = kwargs.get('sources', [])
          if not isinstance(sources, list):
              sources = [sources]
          sources = self.source_strings_to_files(self.flatten(sources))
          deps = self.flatten(kwargs.get('dependencies', []))
          if not isinstance(deps, list):
              deps = [deps]
          compile_args = mesonlib.stringlistify(kwargs.get('compile_args', []))
          link_args = mesonlib.stringlistify(kwargs.get('link_args', []))
          final_deps = []
          for d in deps:
              try:
                  d = d.held_object
              except Exception:
                  pass
              if not isinstance(d, (dependencies.Dependency, dependencies.ExternalLibrary, dependencies.InternalDependency)):
                  raise InterpreterException('Dependencies must be external deps')
              final_deps.append(d)
          dep = dependencies.InternalDependency(version, incs, compile_args, link_args, libs, sources, final_deps)
          return DependencyHolder(dep)
  
      @noKwargs
      def func_assert(self, node, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Assert takes exactly two arguments')
          value, message = args
          if not isinstance(value, bool):
              raise InterpreterException('Assert value not bool.')
          if not isinstance(message, str):
              raise InterpreterException('Assert message not a string.')
          if not value:
              raise InterpreterException('Assert failed: ' + message)
  
      def validate_arguments(self, args, argcount, arg_types):
          if argcount is not None:
              if argcount != len(args):
                  raise InvalidArguments('Expected %d arguments, got %d.' %
                                         (argcount, len(args)))
          for i in range(min(len(args), len(arg_types))):
              wanted = arg_types[i]
              actual = args[i]
              if wanted is not None:
                  if not isinstance(actual, wanted):
                      raise InvalidArguments('Incorrect argument type.')
  
      def func_run_command(self, node, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('Not enough arguments')
          cmd = args[0]
          cargs = args[1:]
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          m = 'must be a string, or the output of find_program(), files(), or ' \
              'configure_file(); not {!r}'
          if isinstance(cmd, ExternalProgramHolder):
              cmd = cmd.held_object
          else:
              if isinstance(cmd, mesonlib.File):
                  cmd = cmd.absolute_path(srcdir, builddir)
              elif not isinstance(cmd, str):
                  raise InterpreterException('First argument ' + m.format(cmd))
              # Prefer scripts in the current source directory
              search_dir = os.path.join(srcdir, self.subdir)
              prog = ExternalProgram(cmd, silent=True, search_dir=search_dir)
              if not prog.found():
                  raise InterpreterException('Program or command {!r} not found'
                                             'or not executable'.format(cmd))
              cmd = prog
          expanded_args = []
          for a in mesonlib.flatten(cargs):
              if isinstance(a, str):
                  expanded_args.append(a)
              elif isinstance(a, mesonlib.File):
                  expanded_args.append(a.absolute_path(srcdir, builddir))
              elif isinstance(a, ExternalProgramHolder):
                  expanded_args.append(a.held_object.get_path())
              else:
                  raise InterpreterException('Arguments ' + m.format(a))
          in_builddir = kwargs.get('in_builddir', False)
          if not isinstance(in_builddir, bool):
              raise InterpreterException('in_builddir must be boolean.')
          return RunProcess(cmd, expanded_args, srcdir, builddir, self.subdir,
                            get_meson_script(self.environment, 'mesonintrospect'), in_builddir)
  
      @stringArgs
      def func_gettext(self, nodes, args, kwargs):
          raise InterpreterException('Gettext() function has been moved to module i18n. Import it and use i18n.gettext() instead')
  
      def func_option(self, nodes, args, kwargs):
          raise InterpreterException('Tried to call option() in build description file. All options must be in the option file.')
  
      @stringArgs
      def func_subproject(self, nodes, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Subproject takes exactly one argument')
          dirname = args[0]
          return self.do_subproject(dirname, kwargs)
  
      def do_subproject(self, dirname, kwargs):
          if dirname in self.subproject_stack:
              fullstack = self.subproject_stack + [dirname]
              incpath = ' => '.join(fullstack)
              raise InvalidCode('Recursive include of subprojects: %s.' % incpath)
          if dirname in self.subprojects:
              return self.subprojects[dirname]
          subproject_dir_abs = os.path.join(self.environment.get_source_dir(), self.subproject_dir)
          r = wrap.Resolver(subproject_dir_abs, self.coredata.wrap_mode)
          try:
              resolved = r.resolve(dirname)
          except RuntimeError as e:
              msg = 'Subproject directory {!r} does not exist and cannot be downloaded:\n{}'
              raise InterpreterException(msg.format(os.path.join(self.subproject_dir, dirname), e))
          subdir = os.path.join(self.subproject_dir, resolved)
          os.makedirs(os.path.join(self.build.environment.get_build_dir(), subdir), exist_ok=True)
          self.global_args_frozen = True
          mlog.log('\nExecuting subproject ', mlog.bold(dirname), '.\n', sep='')
          subi = Interpreter(self.build, self.backend, dirname, subdir, self.subproject_dir,
                             mesonlib.stringlistify(kwargs.get('default_options', [])))
          subi.subprojects = self.subprojects
  
          subi.subproject_stack = self.subproject_stack + [dirname]
          current_active = self.active_projectname
          subi.run()
          if 'version' in kwargs:
              pv = subi.project_version
              wanted = kwargs['version']
              if pv == 'undefined' or not mesonlib.version_compare(pv, wanted):
                  raise InterpreterException('Subproject %s version is %s but %s required.' % (dirname, pv, wanted))
          self.active_projectname = current_active
          mlog.log('\nSubproject', mlog.bold(dirname), 'finished.')
          self.build.subprojects[dirname] = subi.project_version
          self.subprojects.update(subi.subprojects)
          self.subprojects[dirname] = SubprojectHolder(subi)
          self.build_def_files += subi.build_def_files
          return self.subprojects[dirname]
  
      @stringArgs
      @noKwargs
      def func_get_option(self, nodes, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Argument required for get_option.')
          optname = args[0]
          try:
              return self.environment.get_coredata().get_builtin_option(optname)
          except RuntimeError:
              pass
          try:
              return self.environment.coredata.compiler_options[optname].value
          except KeyError:
              pass
          if not coredata.is_builtin_option(optname) and self.is_subproject():
              optname = self.subproject + ':' + optname
          try:
              return self.environment.coredata.user_options[optname].value
          except KeyError:
              pass
          if optname.endswith('_link_args'):
              try:
                  lang = optname[:-10]
                  return self.coredata.external_link_args[lang]
              except KeyError:
                  pass
          if optname.endswith('_args'):
              try:
                  lang = optname[:-5]
                  return self.coredata.external_args[lang]
              except KeyError:
                  pass
          raise InterpreterException('Tried to access unknown option "%s".' % optname)
  
      @noKwargs
      def func_configuration_data(self, node, args, kwargs):
          if args:
              raise InterpreterException('configuration_data takes no arguments')
          return ConfigurationDataHolder()
  
      def parse_default_options(self, default_options):
          if not isinstance(default_options, list):
              default_options = [default_options]
          for option in default_options:
              if not isinstance(option, str):
                  mlog.debug(option)
                  raise InterpreterException('Default options must be strings')
              if '=' not in option:
                  raise InterpreterException('All default options must be of type key=value.')
              key, value = option.split('=', 1)
              if coredata.is_builtin_option(key):
                  if self.subproject != '':
                      continue # Only the master project is allowed to set global options.
                  if not self.environment.had_argument_for(key):
                      self.coredata.set_builtin_option(key, value)
                  # If this was set on the command line, do not override.
              else:
                  # Option values set with subproject() default_options override those
                  # set in project() default_options.
                  pref = key + '='
                  for i in self.default_project_options:
                      if i.startswith(pref):
                          option = i
                          break
                  # If we are in a subproject, add the subproject prefix to option
                  # name.
                  if self.subproject != '':
                      option = self.subproject + ':' + option
                  newoptions = [option] + self.environment.cmd_line_options.projectoptions
                  self.environment.cmd_line_options.projectoptions = newoptions
          # Add options that are only in default_options.
          for defopt in self.default_project_options:
              key, value = defopt.split('=')
              pref = key + '='
              for i in default_options:
                  if i.startswith(pref):
                      break
              else:
                  defopt = self.subproject + ':' + defopt
                  newoptions = [defopt] + self.environment.cmd_line_options.projectoptions
                  self.environment.cmd_line_options.projectoptions = newoptions
  
      @stringArgs
      def func_project(self, node, args, kwargs):
          if len(args) < 1:
              raise InvalidArguments('Not enough arguments to project(). Needs at least the project name.')
          proj_name = args[0]
          proj_langs = args[1:]
          if ':' in proj_name:
              raise InvalidArguments("Project name {!r} must not contain ':'".format(proj_name))
          default_options = kwargs.get('default_options', [])
          if self.environment.first_invocation and (len(default_options) > 0 or
                                                    len(self.default_project_options) > 0):
              self.parse_default_options(default_options)
          if not self.is_subproject():
              self.build.project_name = proj_name
          if os.path.exists(self.option_file):
              oi = optinterpreter.OptionInterpreter(self.subproject,
                                                    self.build.environment.cmd_line_options.projectoptions,
                                                    )
              oi.process(self.option_file)
              self.build.environment.merge_options(oi.options)
          self.active_projectname = proj_name
          self.project_version = kwargs.get('version', 'undefined')
          if self.build.project_version is None:
              self.build.project_version = self.project_version
          proj_license = mesonlib.stringlistify(kwargs.get('license', 'unknown'))
          self.build.dep_manifest[proj_name] = {'version': self.project_version,
                                                'license': proj_license}
          if self.subproject in self.build.projects:
              raise InvalidCode('Second call to project().')
          if not self.is_subproject() and 'subproject_dir' in kwargs:
              self.subproject_dir = kwargs['subproject_dir']
  
          if 'meson_version' in kwargs:
              cv = coredata.version
              pv = kwargs['meson_version']
              if not mesonlib.version_compare(cv, pv):
                  raise InterpreterException('Meson version is %s but project requires %s.' % (cv, pv))
          self.build.projects[self.subproject] = proj_name
          mlog.log('Project name: ', mlog.bold(proj_name), sep='')
          self.add_languages(proj_langs, True)
          langs = self.coredata.compilers.keys()
          if 'vala' in langs:
              if 'c' not in langs:
                  raise InterpreterException('Compiling Vala requires C. Add C to your project languages and rerun Meson.')
          if not self.is_subproject():
              self.check_cross_stdlibs()
  
      @stringArgs
      def func_add_languages(self, node, args, kwargs):
          return self.add_languages(args, kwargs.get('required', True))
  
      @noKwargs
      def func_message(self, node, args, kwargs):
          # reduce arguments again to avoid flattening posargs
          (posargs, _) = self.reduce_arguments(node.args)
          if len(posargs) != 1:
              raise InvalidArguments('Expected 1 argument, got %d' % len(posargs))
  
          arg = posargs[0]
          if isinstance(arg, list):
              argstr = stringifyUserArguments(arg)
          elif isinstance(arg, str):
              argstr = arg
          elif isinstance(arg, int):
              argstr = str(arg)
          else:
              raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
          mlog.log(mlog.bold('Message:'), argstr)
  
      @noKwargs
      def func_error(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          raise InterpreterException('Error encountered: ' + args[0])
  
      def detect_compilers(self, lang, need_cross_compiler):
          cross_comp = None
          if lang == 'c':
              comp = self.environment.detect_c_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_c_compiler(True)
          elif lang == 'cpp':
              comp = self.environment.detect_cpp_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_cpp_compiler(True)
          elif lang == 'objc':
              comp = self.environment.detect_objc_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_objc_compiler(True)
          elif lang == 'objcpp':
              comp = self.environment.detect_objcpp_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_objcpp_compiler(True)
          elif lang == 'java':
              comp = self.environment.detect_java_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # Java is platform independent.
          elif lang == 'cs':
              comp = self.environment.detect_cs_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # C# is platform independent.
          elif lang == 'vala':
              comp = self.environment.detect_vala_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # Vala compiles to platform-independent C
          elif lang == 'd':
              comp = self.environment.detect_d_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_d_compiler(True)
          elif lang == 'rust':
              comp = self.environment.detect_rust_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # FIXME, not correct.
          elif lang == 'fortran':
              comp = self.environment.detect_fortran_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_fortran_compiler(True)
          elif lang == 'swift':
              comp = self.environment.detect_swift_compiler()
              if need_cross_compiler:
                  raise InterpreterException('Cross compilation with Swift is not working yet.')
                  # cross_comp = self.environment.detect_fortran_compiler(True)
          else:
              raise InvalidCode('Tried to use unknown language "%s".' % lang)
          comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
          self.coredata.compilers[lang] = comp
          # Native compiler always exist so always add its options.
          new_options = comp.get_options()
          if cross_comp is not None:
              cross_comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
              self.coredata.cross_compilers[lang] = cross_comp
              new_options.update(cross_comp.get_options())
          optprefix = lang + '_'
          for i in new_options:
              if not i.startswith(optprefix):
                  raise InterpreterException('Internal error, %s has incorrect prefix.' % i)
              cmd_prefix = i + '='
              for cmd_arg in self.environment.cmd_line_options.projectoptions:
                  if cmd_arg.startswith(cmd_prefix):
                      value = cmd_arg.split('=', 1)[1]
                      new_options[i].set_value(value)
          new_options.update(self.coredata.compiler_options)
          self.coredata.compiler_options = new_options
          return comp, cross_comp
  
      def add_languages(self, args, required):
          success = True
          need_cross_compiler = self.environment.is_cross_build() and self.environment.cross_info.need_cross_compiler()
          for lang in sorted(args, key=compilers.sort_clike):
              lang = lang.lower()
              if lang in self.coredata.compilers:
                  comp = self.coredata.compilers[lang]
                  cross_comp = self.coredata.cross_compilers.get(lang, None)
              else:
                  try:
                      (comp, cross_comp) = self.detect_compilers(lang, need_cross_compiler)
                  except Exception:
                      if not required:
                          mlog.log('Compiler for language', mlog.bold(lang), 'not found.')
                          success = False
                          continue
                      else:
                          raise
              mlog.log('Native %s compiler: ' % comp.get_display_language(), mlog.bold(' '.join(comp.get_exelist())), ' (%s %s)' % (comp.id, comp.version), sep='')
              if not comp.get_language() in self.coredata.external_args:
                  (preproc_args, compile_args, link_args) = environment.get_args_from_envvars(comp)
                  self.coredata.external_preprocess_args[comp.get_language()] = preproc_args
                  self.coredata.external_args[comp.get_language()] = compile_args
                  self.coredata.external_link_args[comp.get_language()] = link_args
              self.build.add_compiler(comp)
              if need_cross_compiler:
                  mlog.log('Cross %s compiler: ' % cross_comp.get_display_language(), mlog.bold(' '.join(cross_comp.get_exelist())), ' (%s %s)' % (cross_comp.id, cross_comp.version), sep='')
                  self.build.add_cross_compiler(cross_comp)
              if self.environment.is_cross_build() and not need_cross_compiler:
                  self.build.add_cross_compiler(comp)
              self.add_base_options(comp)
          return success
  
      def add_base_options(self, compiler):
          proj_opt = self.environment.cmd_line_options.projectoptions
          for optname in compiler.base_options:
              if optname in self.coredata.base_options:
                  continue
              oobj = compilers.base_options[optname]
              for po in proj_opt:
                  if po.startswith(optname + '='):
                      oobj.set_value(po.split('=', 1)[1])
                      break
              self.coredata.base_options[optname] = oobj
  
      def func_find_program(self, node, args, kwargs):
          if not args:
              raise InterpreterException('No program name specified.')
          required = kwargs.get('required', True)
          if not isinstance(required, bool):
              raise InvalidArguments('"required" argument must be a boolean.')
          # Search for scripts relative to current subdir.
          # Do not cache found programs because find_program('foobar')
          # might give different results when run from different source dirs.
          source_dir = os.path.join(self.environment.get_source_dir(), self.subdir)
          for exename in args:
              if isinstance(exename, mesonlib.File):
                  if exename.is_built:
                      search_dir = os.path.join(self.environment.get_build_dir(),
                                                exename.subdir)
                  else:
                      search_dir = os.path.join(self.environment.get_source_dir(),
                                                exename.subdir)
                  exename = exename.fname
              elif isinstance(exename, str):
                  search_dir = source_dir
              else:
                  raise InvalidArguments('find_program only accepts strings and '
                                         'files, not {!r}'.format(exename))
              extprog = dependencies.ExternalProgram(exename, search_dir=search_dir)
              progobj = ExternalProgramHolder(extprog)
              if progobj.found():
                  return progobj
          if required and not progobj.found():
              raise InvalidArguments('Program "%s" not found or not executable' % exename)
          return progobj
  
      def func_find_library(self, node, args, kwargs):
          mlog.log(mlog.red('DEPRECATION:'), 'find_library() is removed, use the corresponding method in compiler object instead.')
  
      def _find_cached_dep(self, name, kwargs):
          # Check if we want this as a cross-dep or a native-dep
          # FIXME: Not all dependencies support such a distinction right now,
          # and we repeat this check inside dependencies that do. We need to
          # consolidate this somehow.
          is_cross = self.environment.is_cross_build()
          if 'native' in kwargs and is_cross:
              want_cross = not kwargs['native']
          else:
              want_cross = is_cross
          identifier = dependencies.get_dep_identifier(name, kwargs, want_cross)
          cached_dep = None
          # Check if we've already searched for and found this dep
          if identifier in self.coredata.deps:
              cached_dep = self.coredata.deps[identifier]
          else:
              # Check if exactly the same dep with different version requirements
              # was found already.
              wanted = identifier[1]
              for trial, trial_dep in self.coredata.deps.items():
                  # trial[1], identifier[1] are the version requirements
                  if trial[0] != identifier[0] or trial[2:] != identifier[2:]:
                      continue
                  found = trial_dep.get_version()
                  if not wanted or mesonlib.version_compare_many(found, wanted)[0]:
                      # We either don't care about the version, or our
                      # version requirements matched the trial dep's version.
                      cached_dep = trial_dep
                      break
          return identifier, cached_dep
  
      def func_dependency(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          name = args[0]
          if '<' in name or '>' in name or '=' in name:
              raise InvalidArguments('Characters <, > and = are forbidden in dependency names. To specify'
                                     'version\n requirements use the \'version\' keyword argument instead.')
          identifier, cached_dep = self._find_cached_dep(name, kwargs)
  
          if cached_dep:
              if kwargs.get('required', True) and not cached_dep.found():
                  m = 'Dependency {!r} was already checked and was not found'
                  raise DependencyException(m.format(name))
              dep = cached_dep
          else:
              # We need to actually search for this dep
              exception = None
              dep = None
              # If the dependency has already been configured, possibly by
              # a higher level project, try to use it first.
              if 'fallback' in kwargs:
                  dirname, varname = self.get_subproject_infos(kwargs)
                  if dirname in self.subprojects:
                      subproject = self.subprojects[dirname]
                      try:
                          # Never add fallback deps to self.coredata.deps
                          return subproject.get_variable_method([varname], {})
                      except KeyError:
                          pass
  
              # Search for it outside the project
              if not dep:
                  try:
                      dep = dependencies.find_external_dependency(name, self.environment, kwargs)
                  except DependencyException as e:
                      exception = e
                      pass
  
              # Search inside the projects list
              if not dep or not dep.found():
                  if 'fallback' in kwargs:
                      fallback_dep = self.dependency_fallback(name, kwargs)
                      if fallback_dep:
                          # Never add fallback deps to self.coredata.deps since we
                          # cannot cache them. They must always be evaluated else
                          # we won't actually read all the build files.
                          return fallback_dep
                  if not dep:
                      raise exception
  
          # Only store found-deps in the cache
          if dep.found():
              self.coredata.deps[identifier] = dep
          return DependencyHolder(dep)
  
      def get_subproject_infos(self, kwargs):
          fbinfo = kwargs['fallback']
          check_stringlist(fbinfo)
          if len(fbinfo) != 2:
              raise InterpreterException('Fallback info must have exactly two items.')
          return fbinfo
  
      def dependency_fallback(self, name, kwargs):
          if self.coredata.wrap_mode in (WrapMode.nofallback, WrapMode.nodownload):
              mlog.log('Not looking for a fallback subproject for the dependency',
                       mlog.bold(name), 'because:\nAutomatic wrap-based fallback '
                       'dependency downloading is disabled.')
              return None
          dirname, varname = self.get_subproject_infos(kwargs)
          # Try to execute the subproject
          try:
              sp_kwargs = {}
              try:
                  sp_kwargs['default_options'] = kwargs['default_options']
              except KeyError:
                  pass
              self.do_subproject(dirname, sp_kwargs)
          # Invalid code is always an error
          except InvalidCode:
              raise
          # If the subproject execution failed in a non-fatal way, don't raise an
          # exception; let the caller handle things.
          except:
              mlog.log('Also couldn\'t find a fallback subproject in',
                       mlog.bold(os.path.join(self.subproject_dir, dirname)),
                       'for the dependency', mlog.bold(name))
              return None
          try:
              dep = self.subprojects[dirname].get_variable_method([varname], {})
          except KeyError:
              if kwargs.get('required', True):
                  m = 'Fallback variable {!r} in the subproject {!r} does not exist'
                  raise DependencyException(m.format(varname, dirname))
              # If the dependency is not required, don't raise an exception
              mlog.log('Also couldn\'t find the dependency', mlog.bold(name),
                       'in the fallback subproject',
                       mlog.bold(os.path.join(self.subproject_dir, dirname)))
              return None
          if not isinstance(dep, DependencyHolder):
              raise InvalidCode('Fallback variable {!r} in the subproject {!r} is '
                                'not a dependency object.'.format(varname, dirname))
          # Check if the version of the declared dependency matches what we want
          if 'version' in kwargs:
              wanted = kwargs['version']
              found = dep.version_method([], {})
              if found == 'undefined' or not mesonlib.version_compare(found, wanted):
                  mlog.log('Subproject', mlog.bold(dirname), 'dependency',
                           mlog.bold(varname), 'version is', mlog.bold(found),
                           'but', mlog.bold(wanted), 'is required.')
                  return None
          mlog.log('Found a', mlog.green('fallback'), 'subproject',
                   mlog.bold(os.path.join(self.subproject_dir, dirname)), 'for',
                   mlog.bold(name))
          return dep
  
      def func_executable(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, ExecutableHolder)
  
      def func_static_lib(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, StaticLibraryHolder)
  
      def func_shared_lib(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, SharedLibraryHolder)
  
      def func_shared_module(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, SharedModuleHolder)
  
      def func_library(self, node, args, kwargs):
          if self.coredata.get_builtin_option('default_library') == 'shared':
              return self.func_shared_lib(node, args, kwargs)
          return self.func_static_lib(node, args, kwargs)
  
      def func_jar(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, JarHolder)
  
      def func_build_target(self, node, args, kwargs):
          if 'target_type' not in kwargs:
              raise InterpreterException('Missing target_type keyword argument')
          target_type = kwargs.pop('target_type')
          if target_type == 'executable':
              return self.func_executable(node, args, kwargs)
          elif target_type == 'shared_library':
              return self.func_shared_lib(node, args, kwargs)
          elif target_type == 'static_library':
              return self.func_static_lib(node, args, kwargs)
          elif target_type == 'library':
              return self.func_library(node, args, kwargs)
          elif target_type == 'jar':
              return self.func_jar(node, args, kwargs)
          else:
              raise InterpreterException('Unknown target_type.')
  
      def func_vcs_tag(self, node, args, kwargs):
          if 'input' not in kwargs or 'output' not in kwargs:
              raise InterpreterException('Keyword arguments input and output must exist')
          fallback = kwargs.pop('fallback', self.project_version)
          if not isinstance(fallback, str):
              raise InterpreterException('Keyword argument fallback must be a string.')
          replace_string = kwargs.pop('replace_string', '@VCS_TAG@')
          regex_selector = '(.*)' # default regex selector for custom command: use complete output
          vcs_cmd = kwargs.get('command', None)
          if vcs_cmd and not isinstance(vcs_cmd, list):
              vcs_cmd = [vcs_cmd]
          source_dir = os.path.normpath(os.path.join(self.environment.get_source_dir(), self.subdir))
          if vcs_cmd:
              # Is the command an executable in path or maybe a script in the source tree?
              vcs_cmd[0] = shutil.which(vcs_cmd[0]) or os.path.join(source_dir, vcs_cmd[0])
          else:
              vcs = mesonlib.detect_vcs(source_dir)
              if vcs:
                  mlog.log('Found %s repository at %s' % (vcs['name'], vcs['wc_dir']))
                  vcs_cmd = vcs['get_rev'].split()
                  regex_selector = vcs['rev_regex']
              else:
                  vcs_cmd = [' '] # executing this cmd will fail in vcstagger.py and force to use the fallback string
          # vcstagger.py parameters: infile, outfile, fallback, source_dir, replace_string, regex_selector, command...
          kwargs['command'] = [sys.executable,
                               self.environment.get_build_command(),
                               '--internal',
                               'vcstagger',
                               '@INPUT0@',
                               '@OUTPUT0@',
                               fallback,
                               source_dir,
                               replace_string,
                               regex_selector] + vcs_cmd
          kwargs.setdefault('build_always', True)
          return self.func_custom_target(node, [kwargs['output']], kwargs)
  
      @stringArgs
      def func_custom_target(self, node, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('custom_target: Only one positional argument is allowed, and it must be a string name')
          name = args[0]
          tg = CustomTargetHolder(build.CustomTarget(name, self.subdir, kwargs), self)
          self.add_target(name, tg.held_object)
          return tg
  
      def func_run_target(self, node, args, kwargs):
          global run_depr_printed
          if len(args) > 1:
              if not run_depr_printed:
                  mlog.log(mlog.red('DEPRECATION'), 'positional version of run_target is deprecated, use the keyword version instead.')
                  run_depr_printed = True
              if 'command' in kwargs:
                  raise InterpreterException('Can not have command both in positional and keyword arguments.')
              all_args = args[1:]
              deps = []
          elif len(args) == 1:
              if 'command' not in kwargs:
                  raise InterpreterException('Missing "command" keyword argument')
              all_args = kwargs['command']
              if not isinstance(all_args, list):
                  all_args = [all_args]
              deps = kwargs.get('depends', [])
              if not isinstance(deps, list):
                  deps = [deps]
          else:
              raise InterpreterException('Run_target needs at least one positional argument.')
  
          cleaned_args = []
          for i in mesonlib.flatten(all_args):
              try:
                  i = i.held_object
              except AttributeError:
                  pass
              if not isinstance(i, (str, build.BuildTarget, build.CustomTarget, dependencies.ExternalProgram, mesonlib.File)):
                  mlog.debug('Wrong type:', str(i))
                  raise InterpreterException('Invalid argument to run_target.')
              cleaned_args.append(i)
          name = args[0]
          if not isinstance(name, str):
              raise InterpreterException('First argument must be a string.')
          cleaned_deps = []
          for d in deps:
              try:
                  d = d.held_object
              except AttributeError:
                  pass
              if not isinstance(d, (build.BuildTarget, build.CustomTarget)):
                  raise InterpreterException('Depends items must be build targets.')
              cleaned_deps.append(d)
          command = cleaned_args[0]
          cmd_args = cleaned_args[1:]
          tg = RunTargetHolder(name, command, cmd_args, cleaned_deps, self.subdir)
          self.add_target(name, tg.held_object)
          return tg
  
      def func_generator(self, node, args, kwargs):
          gen = GeneratorHolder(self, args, kwargs)
          self.generators.append(gen)
          return gen
  
      def func_benchmark(self, node, args, kwargs):
          self.add_test(node, args, kwargs, False)
  
      def func_test(self, node, args, kwargs):
          self.add_test(node, args, kwargs, True)
  
      def unpack_env_kwarg(self, kwargs):
          envlist = kwargs.get('env', EnvironmentVariablesHolder())
          if isinstance(envlist, EnvironmentVariablesHolder):
              env = envlist.held_object
          else:
              if not isinstance(envlist, list):
                  envlist = [envlist]
              env = {}
              for e in envlist:
                  if '=' not in e:
                      raise InterpreterException('Env var definition must be of type key=val.')
                  (k, val) = e.split('=', 1)
                  k = k.strip()
                  val = val.strip()
                  if ' ' in k:
                      raise InterpreterException('Env var key must not have spaces in it.')
                  env[k] = val
          return env
  
      def add_test(self, node, args, kwargs, is_base_test):
          if len(args) != 2:
              raise InterpreterException('Incorrect number of arguments')
          if not isinstance(args[0], str):
              raise InterpreterException('First argument of test must be a string.')
          if not isinstance(args[1], (ExecutableHolder, JarHolder, ExternalProgramHolder)):
              raise InterpreterException('Second argument must be executable.')
          par = kwargs.get('is_parallel', True)
          if not isinstance(par, bool):
              raise InterpreterException('Keyword argument is_parallel must be a boolean.')
          cmd_args = kwargs.get('args', [])
          if not isinstance(cmd_args, list):
              cmd_args = [cmd_args]
          for i in cmd_args:
              if not isinstance(i, (str, mesonlib.File, TargetHolder)):
                  raise InterpreterException('Command line arguments must be strings, files or targets.')
          env = self.unpack_env_kwarg(kwargs)
          should_fail = kwargs.get('should_fail', False)
          if not isinstance(should_fail, bool):
              raise InterpreterException('Keyword argument should_fail must be a boolean.')
          timeout = kwargs.get('timeout', 30)
          if 'workdir' in kwargs:
              workdir = kwargs['workdir']
              if not isinstance(workdir, str):
                  raise InterpreterException('Workdir keyword argument must be a string.')
              if not os.path.isabs(workdir):
                  raise InterpreterException('Workdir keyword argument must be an absolute path.')
          else:
              workdir = None
          if not isinstance(timeout, int):
              raise InterpreterException('Timeout must be an integer.')
          suite = []
          for s in mesonlib.stringlistify(kwargs.get('suite', '')):
              if len(s) > 0:
                  s = ':' + s
              if self.is_subproject():
                  suite.append(self.subproject.replace(' ', '_').replace(':', '_') + s)
              else:
                  suite.append(self.build.project_name.replace(' ', '_').replace(':', '_') + s)
          t = Test(args[0], suite, args[1].held_object, par, cmd_args, env, should_fail, timeout, workdir)
          if is_base_test:
              self.build.tests.append(t)
              mlog.debug('Adding test "', mlog.bold(args[0]), '".', sep='')
          else:
              self.build.benchmarks.append(t)
              mlog.debug('Adding benchmark "', mlog.bold(args[0]), '".', sep='')
  
      def func_install_headers(self, node, args, kwargs):
          source_files = self.source_strings_to_files(args)
          h = Headers(source_files, kwargs)
          self.build.headers.append(h)
          return h
  
      @stringArgs
      def func_install_man(self, node, args, kwargs):
          m = Man(self.subdir, args, kwargs)
          self.build.man.append(m)
          return m
  
      @noKwargs
      def func_subdir(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          if '..' in args[0]:
              raise InvalidArguments('Subdir contains ..')
          if self.subdir == '' and args[0] == self.subproject_dir:
              raise InvalidArguments('Must not go into subprojects dir with subdir(), use subproject() instead.')
          if self.subdir == '' and args[0].startswith('meson-'):
              raise InvalidArguments('The "meson-" prefix is reserved and cannot be used for top-level subdir().')
          prev_subdir = self.subdir
          subdir = os.path.join(prev_subdir, args[0])
          if os.path.isabs(subdir):
              raise InvalidArguments('Subdir argument must be a relative path.')
          absdir = os.path.join(self.environment.get_source_dir(), subdir)
          symlinkless_dir = os.path.realpath(absdir)
          if symlinkless_dir in self.visited_subdirs:
              raise InvalidArguments('Tried to enter directory "%s", which has already been visited.'
                                     % subdir)
          self.visited_subdirs[symlinkless_dir] = True
          self.subdir = subdir
          os.makedirs(os.path.join(self.environment.build_dir, subdir), exist_ok=True)
          buildfilename = os.path.join(self.subdir, environment.build_filename)
          self.build_def_files.append(buildfilename)
          absname = os.path.join(self.environment.get_source_dir(), buildfilename)
          if not os.path.isfile(absname):
              self.subdir = prev_subdir
              raise InterpreterException('Non-existent build file {!r}'.format(buildfilename))
          with open(absname, encoding='utf8') as f:
              code = f.read()
          assert(isinstance(code, str))
          try:
              codeblock = mparser.Parser(code, self.subdir).parse()
          except mesonlib.MesonException as me:
              me.file = buildfilename
              raise me
          self.evaluate_codeblock(codeblock)
          self.subdir = prev_subdir
  
      def _get_kwarg_install_mode(self, kwargs):
          if 'install_mode' not in kwargs:
              return None
          install_mode = []
          mode = mesonlib.typeslistify(kwargs.get('install_mode', []), (str, int))
          for m in mode:
              # We skip any arguments that are set to `false`
              if m is False:
                  m = None
              install_mode.append(m)
          if len(install_mode) > 3:
              raise InvalidArguments('Keyword argument install_mode takes at '
                                     'most 3 arguments.')
          if len(install_mode) > 0 and install_mode[0] is not None and \
             not isinstance(install_mode[0], str):
              raise InvalidArguments('Keyword argument install_mode requires the '
                                     'permissions arg to be a string or false')
          return FileMode(*install_mode)
  
      def func_install_data(self, node, args, kwargs):
          kwsource = mesonlib.stringlistify(kwargs.get('sources', []))
          raw_sources = args + kwsource
          sources = []
          source_strings = []
          for s in raw_sources:
              if isinstance(s, mesonlib.File):
                  sources.append(s)
              else:
                  source_strings.append(s)
          sources += self.source_strings_to_files(source_strings)
          install_dir = kwargs.get('install_dir', None)
          if not isinstance(install_dir, (str, type(None))):
              raise InvalidArguments('Keyword argument install_dir not a string.')
          install_mode = self._get_kwarg_install_mode(kwargs)
          data = DataHolder(build.Data(sources, install_dir, install_mode))
          self.build.data.append(data.held_object)
          return data
  
      @stringArgs
      def func_install_subdir(self, node, args, kwargs):
          if len(args) != 1:
              raise InvalidArguments('Install_subdir requires exactly one argument.')
          if 'install_dir' not in kwargs:
              raise InvalidArguments('Missing keyword argument install_dir')
          install_dir = kwargs['install_dir']
          if not isinstance(install_dir, str):
              raise InvalidArguments('Keyword argument install_dir not a string.')
          install_mode = self._get_kwarg_install_mode(kwargs)
          idir = InstallDir(self.subdir, args[0], install_dir, install_mode)
          self.build.install_dirs.append(idir)
          return idir
  
      def func_configure_file(self, node, args, kwargs):
          if len(args) > 0:
              raise InterpreterException("configure_file takes only keyword arguments.")
          if 'output' not in kwargs:
              raise InterpreterException('Required keyword argument "output" not defined.')
          if 'configuration' in kwargs and 'command' in kwargs:
              raise InterpreterException('Must not specify both "configuration" '
                                         'and "command" keyword arguments since '
                                         'they are mutually exclusive.')
          if 'capture' in kwargs:
              if not isinstance(kwargs['capture'], bool):
                  raise InterpreterException('"capture" keyword must be a boolean.')
              if 'command' not in kwargs:
                  raise InterpreterException('"capture" keyword requires "command" keyword.')
  
          # Validate input
          inputfile = None
          ifile_abs = None
          if 'input' in kwargs:
              inputfile = kwargs['input']
              if isinstance(inputfile, list):
                  if len(inputfile) != 1:
                      m = "Keyword argument 'input' requires exactly one file"
                      raise InterpreterException(m)
                  inputfile = inputfile[0]
              if not isinstance(inputfile, (str, mesonlib.File)):
                  raise InterpreterException('Input must be a string or a file')
              if isinstance(inputfile, str):
                  inputfile = os.path.join(self.subdir, inputfile)
                  ifile_abs = os.path.join(self.environment.source_dir, inputfile)
              else:
                  ifile_abs = inputfile.absolute_path(self.environment.source_dir,
                                                      self.environment.build_dir)
                  inputfile = inputfile.relative_name()
          elif 'command' in kwargs and '@INPUT@' in kwargs['command']:
              raise InterpreterException('@INPUT@ used as command argument, but no input file specified.')
          # Validate output
          output = kwargs['output']
          if not isinstance(output, str):
              raise InterpreterException('Output file name must be a string')
          if ifile_abs:
              values = mesonlib.get_filenames_templates_dict([ifile_abs], None)
              outputs = mesonlib.substitute_values([output], values)
              output = outputs[0]
          if os.path.split(output)[0] != '':
              raise InterpreterException('Output file name must not contain a subdirectory.')
          (ofile_path, ofile_fname) = os.path.split(os.path.join(self.subdir, output))
          ofile_abs = os.path.join(self.environment.build_dir, ofile_path, ofile_fname)
          if 'configuration' in kwargs:
              conf = kwargs['configuration']
              if not isinstance(conf, ConfigurationDataHolder):
                  raise InterpreterException('Argument "configuration" is not of type configuration_data')
              mlog.log('Configuring', mlog.bold(output), 'using configuration')
              if inputfile is not None:
                  # Normalize the path of the conffile to avoid duplicates
                  # This is especially important to convert '/' to '\' on Windows
                  conffile = os.path.normpath(inputfile)
                  if conffile not in self.build_def_files:
                      self.build_def_files.append(conffile)
                  os.makedirs(os.path.join(self.environment.build_dir, self.subdir), exist_ok=True)
                  mesonlib.do_conf_file(ifile_abs, ofile_abs, conf.held_object)
              else:
                  mesonlib.dump_conf_header(ofile_abs, conf.held_object)
              conf.mark_used()
          elif 'command' in kwargs:
              # We use absolute paths for input and output here because the cwd
              # that the command is run from is 'unspecified', so it could change.
              # Currently it's builddir/subdir for in_builddir else srcdir/subdir.
              if ifile_abs:
                  values = mesonlib.get_filenames_templates_dict([ifile_abs], [ofile_abs])
              else:
                  values = mesonlib.get_filenames_templates_dict(None, [ofile_abs])
              # Substitute @INPUT@, @OUTPUT@, etc here.
              cmd = mesonlib.substitute_values(kwargs['command'], values)
              mlog.log('Configuring', mlog.bold(output), 'with command')
              res = self.func_run_command(node, cmd, {'in_builddir': True})
              if res.returncode != 0:
                  raise InterpreterException('Running configure command failed.\n%s\n%s' %
                                             (res.stdout, res.stderr))
              if 'capture' in kwargs and kwargs['capture']:
                  dst_tmp = ofile_abs + '~'
                  with open(dst_tmp, 'w', encoding='utf-8') as f:
                      f.writelines(res.stdout)
                  if ifile_abs:
                      shutil.copymode(ifile_abs, dst_tmp)
                  mesonlib.replace_if_different(ofile_abs, dst_tmp)
          else:
              raise InterpreterException('Configure_file must have either "configuration" or "command".')
          idir = kwargs.get('install_dir', None)
          if isinstance(idir, str):
              cfile = mesonlib.File.from_built_file(ofile_path, ofile_fname)
              self.build.data.append(build.Data([cfile], idir))
          return mesonlib.File.from_built_file(self.subdir, output)
  
      @stringArgs
      def func_include_directories(self, node, args, kwargs):
          src_root = self.environment.get_source_dir()
          build_root = self.environment.get_build_dir()
          absbase_src = os.path.join(src_root, self.subdir)
          absbase_build = os.path.join(build_root, self.subdir)
  
          for a in args:
              if a.startswith(src_root):
                  raise InvalidArguments('''Tried to form an absolute path to a source dir. You should not do that but use
  relative paths instead.
  
  To get include path to any directory relative to the current dir do
  
  incdir = include_directories(dirname)
  
  After this incdir will contain both the current source dir as well as the
  corresponding build dir. It can then be used in any subdirectory and
  Meson will take care of all the busywork to make paths work.
  
  Dirname can even be '.' to mark the current directory. Though you should
  remember that the current source and build directories are always
  put in the include directories by default so you only need to do
  include_directories('.') if you intend to use the result in a
  different subdirectory.
  ''')
              absdir_src = os.path.join(absbase_src, a)
              absdir_build = os.path.join(absbase_build, a)
              if not os.path.isdir(absdir_src) and not os.path.isdir(absdir_build):
                  raise InvalidArguments('Include dir %s does not exist.' % a)
          is_system = kwargs.get('is_system', False)
          if not isinstance(is_system, bool):
              raise InvalidArguments('Is_system must be boolean.')
          i = IncludeDirsHolder(build.IncludeDirs(self.subdir, args, is_system))
          return i
  
      @stringArgs
      def func_add_test_setup(self, node, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Add_test_setup needs one argument for the setup name.')
          setup_name = args[0]
          if re.fullmatch('[_a-zA-Z][_0-9a-zA-Z]*', setup_name) is None:
              raise InterpreterException('Setup name may only contain alphanumeric characters.')
          try:
              inp = kwargs.get('exe_wrapper', [])
              if not isinstance(inp, list):
                  inp = [inp]
              exe_wrapper = []
              for i in inp:
                  if hasattr(i, 'held_object'):
                      i = i.held_object
                  if isinstance(i, str):
                      exe_wrapper.append(i)
                  elif isinstance(i, dependencies.ExternalProgram):
                      if not i.found():
                          raise InterpreterException('Tried to use non-found executable.')
                      exe_wrapper += i.get_command()
                  else:
                      raise InterpreterException('Exe wrapper can only contain strings or external binaries.')
          except KeyError:
              exe_wrapper = None
          gdb = kwargs.get('gdb', False)
          if not isinstance(gdb, bool):
              raise InterpreterException('Gdb option must be a boolean')
          timeout_multiplier = kwargs.get('timeout_multiplier', 1)
          if not isinstance(timeout_multiplier, int):
              raise InterpreterException('Timeout multiplier must be a number.')
          env = self.unpack_env_kwarg(kwargs)
          setupobj = build.TestSetup(exe_wrapper=exe_wrapper,
                                     gdb=gdb,
                                     timeout_multiplier=timeout_multiplier,
                                     env=env)
          if self.subproject == '':
              # Dunno what we should do with subprojects really. Let's start simple
              # and just use the master project ones.
              self.build.test_setups[setup_name] = setupobj
  
      @stringArgs
      def func_add_global_arguments(self, node, args, kwargs):
          self.add_global_arguments(node, self.build.global_args, args, kwargs)
  
      @stringArgs
      def func_add_global_link_arguments(self, node, args, kwargs):
          self.add_global_arguments(node, self.build.global_link_args, args, kwargs)
  
      @stringArgs
      def func_add_project_arguments(self, node, args, kwargs):
          self.add_project_arguments(node, self.build.projects_args, args, kwargs)
  
      @stringArgs
      def func_add_project_link_arguments(self, node, args, kwargs):
          self.add_project_arguments(node, self.build.projects_link_args, args, kwargs)
  
      def add_global_arguments(self, node, argsdict, args, kwargs):
          if self.subproject != '':
              msg = 'Function \'{}\' cannot be used in subprojects because ' \
                    'there is no way to make that reliable.\nPlease only call ' \
                    'this if is_subproject() returns false. Alternatively, ' \
                    'define a variable that\ncontains your language-specific ' \
                    'arguments and add it to the appropriate *_args kwarg ' \
                    'in each target.'.format(node.func_name)
              raise InvalidCode(msg)
          frozen = self.project_args_frozen or self.global_args_frozen
          self.add_arguments(node, argsdict, frozen, args, kwargs)
  
      def add_project_arguments(self, node, argsdict, args, kwargs):
          if self.subproject not in argsdict:
              argsdict[self.subproject] = {}
          self.add_arguments(node, argsdict[self.subproject],
                             self.project_args_frozen, args, kwargs)
  
      def add_arguments(self, node, argsdict, args_frozen, args, kwargs):
          if args_frozen:
              msg = 'Tried to use \'{}\' after a build target has been declared.\n' \
                    'This is not permitted. Please declare all ' \
                    'arguments before your targets.'.format(node.func_name)
              raise InvalidCode(msg)
  
          if 'language' not in kwargs:
              raise InvalidCode('Missing language definition in {}'.format(node.func_name))
  
          for lang in mesonlib.stringlistify(kwargs['language']):
              lang = lang.lower()
              argsdict[lang] = argsdict.get(lang, []) + args
  
      def func_environment(self, node, args, kwargs):
          return EnvironmentVariablesHolder()
  
      @stringArgs
      @noKwargs
      def func_join_paths(self, node, args, kwargs):
          return os.path.join(*args).replace('\\', '/')
  
      def run(self):
          super().run()
          mlog.log('Build targets in project:', mlog.bold(str(len(self.build.targets))))
  
      def source_strings_to_files(self, sources):
          results = []
          for s in sources:
              if isinstance(s, (mesonlib.File, GeneratedListHolder,
                                CustomTargetHolder)):
                  pass
              elif isinstance(s, str):
                  s = mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, s)
              else:
                  raise InterpreterException("Source item is not string or File-type object.")
              results.append(s)
          return results
  
      def add_target(self, name, tobj):
          if name == '':
              raise InterpreterException('Target name must not be empty.')
          if name in coredata.forbidden_target_names:
              raise InvalidArguments('Target name "%s" is reserved for Meson\'s internal use. Please rename.'
                                     % name)
          # To permit an executable and a shared library to have the
          # same name, such as "foo.exe" and "libfoo.a".
          idname = tobj.get_id()
          if idname in self.build.targets:
              raise InvalidCode('Tried to create target "%s", but a target of that name already exists.' % name)
          self.build.targets[idname] = tobj
          if idname not in self.coredata.target_guids:
              self.coredata.target_guids[idname] = str(uuid.uuid4()).upper()
  
      def build_target(self, node, args, kwargs, targetholder):
          if not args:
              raise InterpreterException('Target does not have a name.')
          name = args[0]
          sources = args[1:]
          if self.environment.is_cross_build():
              if kwargs.get('native', False):
                  is_cross = False
              else:
                  is_cross = True
          else:
              is_cross = False
          try:
              kw_src = self.flatten(kwargs['sources'])
              if not isinstance(kw_src, list):
                  kw_src = [kw_src]
          except KeyError:
              kw_src = []
          sources += kw_src
          sources = self.source_strings_to_files(sources)
          objs = self.flatten(kwargs.get('objects', []))
          kwargs['dependencies'] = self.flatten(kwargs.get('dependencies', []))
          if 'extra_files' in kwargs:
              ef = kwargs['extra_files']
              if not isinstance(ef, list):
                  ef = [ef]
              kwargs['extra_files'] = self.source_strings_to_files(ef)
          if not isinstance(objs, list):
              objs = [objs]
          self.check_sources_exist(os.path.join(self.source_root, self.subdir), sources)
          if targetholder is ExecutableHolder:
              targetclass = build.Executable
          elif targetholder is SharedLibraryHolder:
              targetclass = build.SharedLibrary
          elif targetholder is SharedModuleHolder:
              targetclass = build.SharedModule
          elif targetholder is StaticLibraryHolder:
              targetclass = build.StaticLibrary
          elif targetholder is JarHolder:
              targetclass = build.Jar
          else:
              mlog.debug('Unknown target type:', str(targetholder))
              raise RuntimeError('Unreachable code')
          target = targetclass(name, self.subdir, self.subproject, is_cross, sources, objs, self.environment, kwargs)
          if is_cross:
              self.add_cross_stdlib_info(target)
          l = targetholder(target, self)
          self.add_target(name, l.held_object)
          self.project_args_frozen = True
          return l
  
      def get_used_languages(self, target):
          result = {}
          for i in target.sources:
              for lang, c in self.build.compilers.items():
                  if c.can_compile(i):
                      result[lang] = True
                      break
          return result
  
      def add_cross_stdlib_info(self, target):
          for l in self.get_used_languages(target):
              if self.environment.cross_info.has_stdlib(l) \
                      and self.subproject != self.environment.cross_info.get_stdlib(l)[0]:
                  target.add_deps(self.build.cross_stdlibs[l])
  
      def check_sources_exist(self, subdir, sources):
          for s in sources:
              if not isinstance(s, str):
                  continue # This means a generated source and they always exist.
              fname = os.path.join(subdir, s)
              if not os.path.isfile(fname):
                  raise InterpreterException('Tried to add non-existing source file %s.' % s)
  
      def format_string(self, templ, args):
          if isinstance(args, mparser.ArgumentNode):
              args = args.arguments
          for (i, arg) in enumerate(args):
              arg = self.evaluate_statement(arg)
              if isinstance(arg, bool): # Python boolean is upper case.
                  arg = str(arg).lower()
              templ = templ.replace('@{}@'.format(i), str(arg))
          return templ
  
      # Only permit object extraction from the same subproject
      def validate_extraction(self, buildtarget):
          if not self.subdir.startswith(self.subproject_dir):
              if buildtarget.subdir.startswith(self.subproject_dir):
                  raise InterpreterException('Tried to extract objects from a subproject target.')
          else:
              if not buildtarget.subdir.startswith(self.subproject_dir):
                  raise InterpreterException('Tried to extract objects from the main project from a subproject.')
              if self.subdir.split('/')[1] != buildtarget.subdir.split('/')[1]:
                  raise InterpreterException('Tried to extract objects from a different subproject.')
  
      def check_contains(self, obj, args):
          if len(args) != 1:
              raise InterpreterException('Contains method takes exactly one argument.')
          item = args[0]
          for element in obj:
              if isinstance(element, list):
                  found = self.check_contains(element, args)
                  if found:
                      return True
              try:
                  if element == item:
                      return True
              except Exception:
                  pass
          return False
  
      def is_subproject(self):
          return self.subproject != ''
  
files: mesonbuild/interpreter.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.
  
  from . import mparser
  from . import environment
  from . import coredata
  from . import dependencies
  from . import mlog
  from . import build
  from . import optinterpreter
  from . import compilers
  from .wrap import wrap, WrapMode
  from . import mesonlib
  from .mesonlib import FileMode, Popen_safe, get_meson_script
  from .dependencies import ExternalProgram
  from .dependencies import InternalDependency, Dependency, DependencyException
  from .interpreterbase import InterpreterBase
  from .interpreterbase import check_stringlist, noPosargs, noKwargs, stringArgs
  from .interpreterbase import InterpreterException, InvalidArguments, InvalidCode
  from .interpreterbase import InterpreterObject, MutableInterpreterObject
  from .modules import ModuleReturnValue
  
  import os, sys, shutil, uuid
  import re
  from collections import namedtuple
  
  import importlib
  
  run_depr_printed = False
  
  def stringifyUserArguments(args):
      if isinstance(args, list):
          return '[%s]' % ', '.join([stringifyUserArguments(x) for x in args])
      elif isinstance(args, int):
          return str(args)
      elif isinstance(args, str):
          return "'%s'" % args
      raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
  
  class TryRunResultHolder(InterpreterObject):
      def __init__(self, res):
          super().__init__()
          self.res = res
          self.methods.update({'returncode': self.returncode_method,
                               'compiled': self.compiled_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def returncode_method(self, args, kwargs):
          return self.res.returncode
  
      def compiled_method(self, args, kwargs):
          return self.res.compiled
  
      def stdout_method(self, args, kwargs):
          return self.res.stdout
  
      def stderr_method(self, args, kwargs):
          return self.res.stderr
  
  class RunProcess(InterpreterObject):
  
      def __init__(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir=False):
          super().__init__()
          if not isinstance(cmd, ExternalProgram):
              raise AssertionError('BUG: RunProcess must be passed an ExternalProgram')
          pc, self.stdout, self.stderr = self.run_command(cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir)
          self.returncode = pc.returncode
          self.methods.update({'returncode': self.returncode_method,
                               'stdout': self.stdout_method,
                               'stderr': self.stderr_method,
                               })
  
      def run_command(self, cmd, args, source_dir, build_dir, subdir, mesonintrospect, in_builddir):
          command_array = cmd.get_command() + args
          env = {'MESON_SOURCE_ROOT': source_dir,
                 'MESON_BUILD_ROOT': build_dir,
                 'MESON_SUBDIR': subdir,
                 'MESONINTROSPECT': mesonintrospect}
          if in_builddir:
              cwd = os.path.join(build_dir, subdir)
          else:
              cwd = os.path.join(source_dir, subdir)
          child_env = os.environ.copy()
          child_env.update(env)
          mlog.debug('Running command:', ' '.join(command_array))
          try:
              return Popen_safe(command_array, env=child_env, cwd=cwd)
          except FileNotFoundError:
              raise InterpreterException('Could not execute command "%s".' % ' '.join(command_array))
  
      def returncode_method(self, args, kwargs):
          return self.returncode
  
      def stdout_method(self, args, kwargs):
          return self.stdout
  
      def stderr_method(self, args, kwargs):
          return self.stderr
  
  class ConfigureFileHolder(InterpreterObject):
  
      def __init__(self, subdir, sourcename, targetname, configuration_data):
          InterpreterObject.__init__(self)
          self.held_object = build.ConfigureFile(subdir, sourcename, targetname, configuration_data)
  
  
  class EnvironmentVariablesHolder(MutableInterpreterObject):
      def __init__(self):
          super().__init__()
          self.held_object = build.EnvironmentVariables()
          self.methods.update({'set': self.set_method,
                               'append': self.append_method,
                               'prepend': self.prepend_method,
                               })
  
      def __repr__(self):
          repr_str = "<{0}: {1}>"
          return repr_str.format(self.__class__.__name__, self.held_object.envvars)
  
      @stringArgs
      def add_var(self, method, args, kwargs):
          if not isinstance(kwargs.get("separator", ""), str):
              raise InterpreterException("EnvironmentVariablesHolder methods 'separator'"
                                         " argument needs to be a string.")
          if len(args) < 2:
              raise InterpreterException("EnvironmentVariablesHolder methods require at least"
                                         "2 arguments, first is the name of the variable and"
                                         " following one are values")
          self.held_object.envvars.append((method, args[0], args[1:], kwargs))
  
      def set_method(self, args, kwargs):
          self.add_var(self.held_object.set, args, kwargs)
  
      def append_method(self, args, kwargs):
          self.add_var(self.held_object.append, args, kwargs)
  
      def prepend_method(self, args, kwargs):
          self.add_var(self.held_object.prepend, args, kwargs)
  
  
  class ConfigurationDataHolder(MutableInterpreterObject):
      def __init__(self):
          super().__init__()
          self.used = False # These objects become immutable after use in configure_file.
          self.held_object = build.ConfigurationData()
          self.methods.update({'set': self.set_method,
                               'set10': self.set10_method,
                               'set_quoted': self.set_quoted_method,
                               'has': self.has_method,
                               'get': self.get_method,
                               })
  
      def is_used(self):
          return self.used
  
      def mark_used(self):
          self.used = True
  
      def validate_args(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException("Configuration set requires 2 arguments.")
          if self.used:
              raise InterpreterException("Can not set values on configuration object that has been used.")
          name = args[0]
          val = args[1]
          desc = kwargs.get('description', None)
          if not isinstance(name, str):
              raise InterpreterException("First argument to set must be a string.")
          if desc is not None and not isinstance(desc, str):
              raise InterpreterException('Description must be a string.')
  
          return name, val, desc
  
      def set_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          self.held_object.values[name] = (val, desc)
  
      def set_quoted_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if not isinstance(val, str):
              raise InterpreterException("Second argument to set_quoted must be a string.")
          escaped_val = '\\"'.join(val.split('"'))
          self.held_object.values[name] = ('"' + escaped_val + '"', desc)
  
      def set10_method(self, args, kwargs):
          (name, val, desc) = self.validate_args(args, kwargs)
          if val:
              self.held_object.values[name] = (1, desc)
          else:
              self.held_object.values[name] = (0, desc)
  
      def has_method(self, args, kwargs):
          return args[0] in self.held_object.values
  
      def get_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Get method takes one or two arguments.')
          name = args[0]
          if name in self.held_object:
              return self.held_object.get(name)[0]
          if len(args) > 1:
              return args[1]
          raise InterpreterException('Entry %s not in configuration data.' % name)
  
      def get(self, name):
          return self.held_object.values[name]     # (val, desc)
  
      def keys(self):
          return self.held_object.values.keys()
  
  # Interpreter objects can not be pickled so we must have
  # these wrappers.
  
  class DependencyHolder(InterpreterObject):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          self.held_object = dep
          self.methods.update({'found': self.found_method,
                               'type_name': self.type_name_method,
                               'version': self.version_method,
                               'get_pkgconfig_variable': self.pkgconfig_method,
                               })
  
      def type_name_method(self, args, kwargs):
          return self.held_object.type_name
  
      def found_method(self, args, kwargs):
          if self.held_object.type_name == 'internal':
              return True
          return self.held_object.found()
  
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
      def pkgconfig_method(self, args, kwargs):
          if not isinstance(args, list):
              args = [args]
          if len(args) != 1:
              raise InterpreterException('get_pkgconfig_variable takes exactly one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Variable name must be a string.')
          return self.held_object.get_pkgconfig_variable(varname)
  
  class InternalDependencyHolder(InterpreterObject):
      def __init__(self, dep):
          InterpreterObject.__init__(self)
          self.held_object = dep
          self.methods.update({'found': self.found_method,
                               'version': self.version_method,
                               })
  
      def found_method(self, args, kwargs):
          return True
  
      def version_method(self, args, kwargs):
          return self.held_object.get_version()
  
  class ExternalProgramHolder(InterpreterObject):
      def __init__(self, ep):
          InterpreterObject.__init__(self)
          self.held_object = ep
          self.methods.update({'found': self.found_method,
                               'path': self.path_method})
  
      def found_method(self, args, kwargs):
          return self.found()
  
      def path_method(self, args, kwargs):
          return self.held_object.get_path()
  
      def found(self):
          return self.held_object.found()
  
      def get_command(self):
          return self.held_object.get_command()
  
      def get_name(self):
          return self.held_object.get_name()
  
  class ExternalLibraryHolder(InterpreterObject):
      def __init__(self, el):
          InterpreterObject.__init__(self)
          self.held_object = el
          self.methods.update({'found': self.found_method})
  
      def found(self):
          return self.held_object.found()
  
      def found_method(self, args, kwargs):
          return self.found()
  
      def get_name(self):
          return self.held_object.name
  
      def get_compile_args(self):
          return self.held_object.get_compile_args()
  
      def get_link_args(self):
          return self.held_object.get_link_args()
  
      def get_exe_args(self):
          return self.held_object.get_exe_args()
  
  class GeneratorHolder(InterpreterObject):
      def __init__(self, interpreter, args, kwargs):
          super().__init__()
          self.interpreter = interpreter
          self.held_object = build.Generator(args, kwargs)
          self.methods.update({'process': self.process_method})
  
      def process_method(self, args, kwargs):
          extras = mesonlib.stringlistify(kwargs.get('extra_args', []))
          gl = self.held_object.process_files('Generator', args, self.interpreter, extra_args=extras)
          return GeneratedListHolder(gl)
  
  
  class GeneratedListHolder(InterpreterObject):
      def __init__(self, arg1, extra_args=[]):
          super().__init__()
          if isinstance(arg1, GeneratorHolder):
              self.held_object = build.GeneratedList(arg1.held_object, extra_args)
          else:
              self.held_object = arg1
  
      def __repr__(self):
          r = '<{}: {!r}>'
          return r.format(self.__class__.__name__, self.held_object.get_outputs())
  
      def add_file(self, a):
          self.held_object.add_file(a)
  
  class BuildMachine(InterpreterObject):
      def __init__(self, compilers):
          self.compilers = compilers
          InterpreterObject.__init__(self)
          self.held_object = environment.MachineInfo(environment.detect_system(),
                                                     environment.detect_cpu_family(self.compilers),
                                                     environment.detect_cpu(self.compilers),
                                                     sys.byteorder)
          self.methods.update({'system': self.system_method,
                               'cpu_family': self.cpu_family_method,
                               'cpu': self.cpu_method,
                               'endian': self.endian_method,
                               })
  
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  # This class will provide both host_machine and
  # target_machine
  class CrossMachineInfo(InterpreterObject):
      def __init__(self, cross_info):
          InterpreterObject.__init__(self)
          minimum_cross_info = {'cpu', 'cpu_family', 'endian', 'system'}
          if set(cross_info) < minimum_cross_info:
              raise InterpreterException(
                  'Machine info is currently {}\n'.format(cross_info) +
                  'but is missing {}.'.format(minimum_cross_info - set(cross_info)))
          self.info = cross_info
          self.held_object = environment.MachineInfo(cross_info['system'],
                                                     cross_info['cpu_family'],
                                                     cross_info['cpu'],
                                                     cross_info['endian'])
          self.methods.update({'system': self.system_method,
                               'cpu': self.cpu_method,
                               'cpu_family': self.cpu_family_method,
                               'endian': self.endian_method,
                               })
  
      def cpu_family_method(self, args, kwargs):
          return self.held_object.cpu_family
  
      def cpu_method(self, args, kwargs):
          return self.held_object.cpu
  
      def system_method(self, args, kwargs):
          return self.held_object.system
  
      def endian_method(self, args, kwargs):
          return self.held_object.endian
  
  class IncludeDirsHolder(InterpreterObject):
      def __init__(self, idobj):
          super().__init__()
          self.held_object = idobj
  
  class Headers(InterpreterObject):
  
      def __init__(self, sources, kwargs):
          InterpreterObject.__init__(self)
          self.sources = sources
          self.install_subdir = kwargs.get('subdir', '')
          self.custom_install_dir = kwargs.get('install_dir', None)
          if self.custom_install_dir is not None:
              if not isinstance(self.custom_install_dir, str):
                  raise InterpreterException('Custom_install_dir must be a string.')
  
      def set_install_subdir(self, subdir):
          self.install_subdir = subdir
  
      def get_install_subdir(self):
          return self.install_subdir
  
      def get_sources(self):
          return self.sources
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
  class DataHolder(InterpreterObject):
      def __init__(self, data):
          super().__init__()
          self.held_object = data
  
      def get_source_subdir(self):
          return self.held_object.source_subdir
  
      def get_sources(self):
          return self.held_object.sources
  
      def get_install_dir(self):
          return self.held_object.install_dir
  
  class InstallDir(InterpreterObject):
      def __init__(self, src_subdir, inst_subdir, install_dir, install_mode):
          InterpreterObject.__init__(self)
          self.source_subdir = src_subdir
          self.installable_subdir = inst_subdir
          self.install_dir = install_dir
          self.install_mode = install_mode
  
  class Man(InterpreterObject):
  
      def __init__(self, source_subdir, sources, kwargs):
          InterpreterObject.__init__(self)
          self.source_subdir = source_subdir
          self.sources = sources
          self.validate_sources()
          if len(kwargs) > 1:
              raise InvalidArguments('Man function takes at most one keyword arguments.')
          self.custom_install_dir = kwargs.get('install_dir', None)
          if self.custom_install_dir is not None and not isinstance(self.custom_install_dir, str):
              raise InterpreterException('Custom_install_dir must be a string.')
  
      def validate_sources(self):
          for s in self.sources:
              try:
                  num = int(s.split('.')[-1])
              except (IndexError, ValueError):
                  num = 0
              if num < 1 or num > 8:
                  raise InvalidArguments('Man file must have a file extension of a number between 1 and 8')
  
      def get_custom_install_dir(self):
          return self.custom_install_dir
  
      def get_sources(self):
          return self.sources
  
      def get_source_subdir(self):
          return self.source_subdir
  
  class GeneratedObjectsHolder(InterpreterObject):
      def __init__(self, held_object):
          super().__init__()
          self.held_object = held_object
  
  class TargetHolder(InterpreterObject):
      def __init__(self):
          super().__init__()
  
  class BuildTargetHolder(TargetHolder):
      def __init__(self, target, interp):
          super().__init__()
          self.held_object = target
          self.interpreter = interp
          self.methods.update({'extract_objects': self.extract_objects_method,
                               'extract_all_objects': self.extract_all_objects_method,
                               'get_id': self.get_id_method,
                               'outdir': self.outdir_method,
                               'full_path': self.full_path_method,
                               'private_dir_include': self.private_dir_include_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.filename)
  
      def is_cross(self):
          return self.held_object.is_cross()
  
      def private_dir_include_method(self, args, kwargs):
          return IncludeDirsHolder(build.IncludeDirs('', [], False,
                                                     [self.interpreter.backend.get_target_private_dir(self.held_object)]))
  
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
      def outdir_method(self, args, kwargs):
          return self.interpreter.backend.get_target_dir(self.held_object)
  
      def extract_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_objects(args)
          return GeneratedObjectsHolder(gobjs)
  
      def extract_all_objects_method(self, args, kwargs):
          gobjs = self.held_object.extract_all_objects()
          return GeneratedObjectsHolder(gobjs)
  
      def get_id_method(self, args, kwargs):
          return self.held_object.get_id()
  
  class ExecutableHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class StaticLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedLibraryHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class SharedModuleHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class JarHolder(BuildTargetHolder):
      def __init__(self, target, interp):
          super().__init__(target, interp)
  
  class CustomTargetHolder(TargetHolder):
      def __init__(self, object_to_hold, interp):
          super().__init__()
          self.held_object = object_to_hold
          self.interpreter = interp
          self.methods.update({'full_path': self.full_path_method,
                               })
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
      def full_path_method(self, args, kwargs):
          return self.interpreter.backend.get_target_filename_abs(self.held_object)
  
  class RunTargetHolder(InterpreterObject):
      def __init__(self, name, command, args, dependencies, subdir):
          super().__init__()
          self.held_object = build.RunTarget(name, command, args, dependencies, subdir)
  
      def __repr__(self):
          r = '<{} {}: {}>'
          h = self.held_object
          return r.format(self.__class__.__name__, h.get_id(), h.command)
  
  class Test(InterpreterObject):
      def __init__(self, name, suite, exe, is_parallel, cmd_args, env, should_fail, timeout, workdir):
          InterpreterObject.__init__(self)
          self.name = name
          self.suite = suite
          self.exe = exe
          self.is_parallel = is_parallel
          self.cmd_args = cmd_args
          self.env = env
          self.should_fail = should_fail
          self.timeout = timeout
          self.workdir = workdir
  
      def get_exe(self):
          return self.exe
  
      def get_name(self):
          return self.name
  
  class SubprojectHolder(InterpreterObject):
  
      def __init__(self, subinterpreter):
          super().__init__()
          self.held_object = subinterpreter
          self.methods.update({'get_variable': self.get_variable_method,
                               })
  
      def get_variable_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Get_variable takes one argument.')
          varname = args[0]
          if not isinstance(varname, str):
              raise InterpreterException('Get_variable takes a string argument.')
          return self.held_object.variables[varname]
  
  class CompilerHolder(InterpreterObject):
      def __init__(self, compiler, env):
          InterpreterObject.__init__(self)
          self.compiler = compiler
          self.environment = env
          self.methods.update({'compiles': self.compiles_method,
                               'links': self.links_method,
                               'get_id': self.get_id_method,
                               'compute_int': self.compute_int_method,
                               'sizeof': self.sizeof_method,
                               'get_define': self.get_define_method,
                               'has_header': self.has_header_method,
                               'has_header_symbol': self.has_header_symbol_method,
                               'run': self.run_method,
                               'has_function': self.has_function_method,
                               'has_member': self.has_member_method,
                               'has_members': self.has_members_method,
                               'has_type': self.has_type_method,
                               'alignment': self.alignment_method,
                               'version': self.version_method,
                               'cmd_array': self.cmd_array_method,
                               'find_library': self.find_library_method,
                               'has_argument': self.has_argument_method,
                               'has_multi_arguments': self.has_multi_arguments_method,
                               'first_supported_argument': self.first_supported_argument_method,
                               'unittest_args': self.unittest_args_method,
                               'symbols_have_underscore_prefix': self.symbols_have_underscore_prefix_method,
                               })
  
      def version_method(self, args, kwargs):
          return self.compiler.version
  
      def cmd_array_method(self, args, kwargs):
          return self.compiler.exelist
  
      def determine_args(self, kwargs):
          nobuiltins = kwargs.get('no_builtin_args', False)
          if not isinstance(nobuiltins, bool):
              raise InterpreterException('Type of no_builtin_args not a boolean.')
          args = []
          incdirs = kwargs.get('include_directories', [])
          if not isinstance(incdirs, list):
              incdirs = [incdirs]
          for i in incdirs:
              if not isinstance(i, IncludeDirsHolder):
                  raise InterpreterException('Include directories argument must be an include_directories object.')
              for idir in i.held_object.get_incdirs():
                  idir = os.path.join(self.environment.get_source_dir(), idir)
                  args += self.compiler.get_include_args(idir, False)
          if not nobuiltins:
              opts = self.environment.coredata.compiler_options
              args += self.compiler.get_option_compile_args(opts)
              args += self.compiler.get_option_link_args(opts)
          args += mesonlib.stringlistify(kwargs.get('args', []))
          return args
  
      def determine_dependencies(self, kwargs):
          deps = kwargs.get('dependencies', None)
          if deps is not None:
              if not isinstance(deps, list):
                  deps = [deps]
              final_deps = []
              for d in deps:
                  try:
                      d = d.held_object
                  except Exception:
                      pass
                  if isinstance(d, InternalDependency) or not isinstance(d, Dependency):
                      raise InterpreterException('Dependencies must be external dependencies')
                  final_deps.append(d)
              deps = final_deps
          return deps
  
      def alignment_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Alignment method takes exactly one positional argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = mesonlib.stringlistify(kwargs.get('args', []))
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.alignment(typename, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for alignment of "', mlog.bold(typename), '": ', result, sep='')
          return result
  
      def run_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Run method takes exactly one positional argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.run(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if not result.compiled:
                  h = mlog.red('DID NOT COMPILE')
              elif result.returncode == 0:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO (%d)' % result.returncode)
              mlog.log('Checking if "', mlog.bold(testname), '" runs: ', h, sep='')
          return TryRunResultHolder(result)
  
      def get_id_method(self, args, kwargs):
          return self.compiler.get_id()
  
      def symbols_have_underscore_prefix_method(self, args, kwargs):
          '''
          Check if the compiler prefixes _ (underscore) to global C symbols
          See: https://en.wikipedia.org/wiki/Name_mangling#C
          '''
          return self.compiler.symbols_have_underscore_prefix(self.environment)
  
      def unittest_args_method(self, args, kwargs):
          # At time, only D compilers have this feature.
          if not hasattr(self.compiler, 'get_unittest_args'):
              raise InterpreterException('This {} compiler has no unittest arguments.'.format(self.compiler.language))
          return self.compiler.get_unittest_args()
  
      def has_member_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Has_member takes exactly two arguments.')
          check_stringlist(args)
          typename = args[0]
          membername = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_member must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, [membername], prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has member "', mlog.bold(membername), '": ', hadtxt, sep='')
          return had
  
      def has_members_method(self, args, kwargs):
          check_stringlist(args)
          typename = args[0]
          membernames = args[1:]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_members must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_members(typename, membernames, prefix,
                                          self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          members = mlog.bold(', '.join(['"{}"'.format(m) for m in membernames]))
          mlog.log('Checking whether type "', mlog.bold(typename),
                   '" has members ', members, ': ', hadtxt, sep='')
          return had
  
      def has_function_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_function takes exactly one argument.')
          check_stringlist(args)
          funcname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_function must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_function(funcname, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for function "', mlog.bold(funcname), '": ', hadtxt, sep='')
          return had
  
      def has_type_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Has_type takes exactly one argument.')
          check_stringlist(args)
          typename = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_type must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          had = self.compiler.has_type(typename, prefix, self.environment, extra_args, deps)
          if had:
              hadtxt = mlog.green('YES')
          else:
              hadtxt = mlog.red('NO')
          mlog.log('Checking for type "', mlog.bold(typename), '": ', hadtxt, sep='')
          return had
  
      def compute_int_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Compute_int takes exactly one argument.')
          check_stringlist(args)
          expression = args[0]
          prefix = kwargs.get('prefix', '')
          l = kwargs.get('low', -1024)
          h = kwargs.get('high', 1024)
          guess = kwargs.get('guess', None)
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of compute_int must be a string.')
          if not isinstance(l, int):
              raise InterpreterException('Low argument of compute_int must be an int.')
          if not isinstance(h, int):
              raise InterpreterException('High argument of compute_int must be an int.')
          if guess is not None and not isinstance(guess, int):
              raise InterpreterException('Guess argument of compute_int must be an int.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          res = self.compiler.compute_int(expression, l, h, guess, prefix, self.environment, extra_args, deps)
          mlog.log('Computing int of "%s": %d' % (expression, res))
          return res
  
      def sizeof_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Sizeof takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of sizeof must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          esize = self.compiler.sizeof(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for size of "%s": %d' % (element, esize))
          return esize
  
      def get_define_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_define() takes exactly one argument.')
          check_stringlist(args)
          element = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of get_define() must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          value = self.compiler.get_define(element, prefix, self.environment, extra_args, deps)
          mlog.log('Checking for value of define "%s": %s' % (element, value))
          return value
  
      def compiles_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('compiles method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.compiles(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" compiles: ', h, sep='')
          return result
  
      def links_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('links method takes exactly one argument.')
          code = args[0]
          if isinstance(code, mesonlib.File):
              code = mesonlib.File.from_absolute_file(
                  code.rel_to_builddir(self.environment.source_dir))
          elif not isinstance(code, str):
              raise InvalidArguments('Argument must be string or file.')
          testname = kwargs.get('name', '')
          if not isinstance(testname, str):
              raise InterpreterException('Testname argument must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          result = self.compiler.links(code, self.environment, extra_args, deps)
          if len(testname) > 0:
              if result:
                  h = mlog.green('YES')
              else:
                  h = mlog.red('NO')
              mlog.log('Checking if "', mlog.bold(testname), '" links: ', h, sep='')
          return result
  
      def has_header_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('has_header method takes exactly one argument.')
          check_stringlist(args)
          hname = args[0]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header(hname, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Has header "%s":' % hname, h)
          return haz
  
      def has_header_symbol_method(self, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('has_header_symbol method takes exactly two arguments.')
          check_stringlist(args)
          hname = args[0]
          symbol = args[1]
          prefix = kwargs.get('prefix', '')
          if not isinstance(prefix, str):
              raise InterpreterException('Prefix argument of has_header_symbol must be a string.')
          extra_args = self.determine_args(kwargs)
          deps = self.determine_dependencies(kwargs)
          haz = self.compiler.has_header_symbol(hname, symbol, prefix, self.environment, extra_args, deps)
          if haz:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Header <{0}> has symbol "{1}":'.format(hname, symbol), h)
          return haz
  
      def find_library_method(self, args, kwargs):
          # TODO add dependencies support?
          if len(args) != 1:
              raise InterpreterException('find_library method takes one argument.')
          libname = args[0]
          if not isinstance(libname, str):
              raise InterpreterException('Library name not a string.')
          required = kwargs.get('required', True)
          if not isinstance(required, bool):
              raise InterpreterException('required must be boolean.')
          search_dirs = mesonlib.stringlistify(kwargs.get('dirs', []))
          for i in search_dirs:
              if not os.path.isabs(i):
                  raise InvalidCode('Search directory %s is not an absolute path.' % i)
          linkargs = self.compiler.find_library(libname, self.environment, search_dirs)
          if required and not linkargs:
              l = self.compiler.language.capitalize()
              raise InterpreterException('{} library {!r} not found'.format(l, libname))
          lib = dependencies.ExternalLibrary(libname, linkargs, self.environment,
                                             self.compiler.language)
          return ExternalLibraryHolder(lib)
  
      def has_argument_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          if len(args) != 1:
              raise InterpreterException('Has_arg takes exactly one argument.')
          result = self.compiler.has_argument(args[0], self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log('Compiler for {} supports argument {}:'.format(self.compiler.language, args[0]), h)
          return result
  
      def has_multi_arguments_method(self, args, kwargs):
          args = mesonlib.stringlistify(args)
          result = self.compiler.has_multi_arguments(args, self.environment)
          if result:
              h = mlog.green('YES')
          else:
              h = mlog.red('NO')
          mlog.log(
              'Compiler for {} supports arguments {}:'.format(
                  self.compiler.language, ' '.join(args)),
              h)
          return result
  
      def first_supported_argument_method(self, args, kwargs):
          for i in mesonlib.stringlistify(args):
              if self.compiler.has_argument(i, self.environment):
                  mlog.log('First supported argument:', mlog.bold(i))
                  return [i]
          mlog.log('First supported argument:', mlog.red('None'))
          return []
  
  ModuleState = namedtuple('ModuleState', [
      'build_to_src', 'subdir', 'environment', 'project_name', 'project_version',
      'backend', 'compilers', 'targets', 'data', 'headers', 'man', 'global_args',
      'project_args', 'build_machine', 'host_machine', 'target_machine'])
  
  class ModuleHolder(InterpreterObject):
      def __init__(self, modname, module, interpreter):
          InterpreterObject.__init__(self)
          self.modname = modname
          self.held_object = module
          self.interpreter = interpreter
  
      def method_call(self, method_name, args, kwargs):
          try:
              fn = getattr(self.held_object, method_name)
          except AttributeError:
              raise InvalidArguments('Module %s does not have method %s.' % (self.modname, method_name))
          if method_name.startswith('_'):
              raise InvalidArguments('Function {!r} in module {!r} is private.'.format(method_name, self.modname))
          # This is not 100% reliable but we can't use hash()
          # because the Build object contains dicts and lists.
          num_targets = len(self.interpreter.build.targets)
          state = ModuleState(
              build_to_src=os.path.relpath(self.interpreter.environment.get_source_dir(),
                                           self.interpreter.environment.get_build_dir()),
              subdir=self.interpreter.subdir,
              environment=self.interpreter.environment,
              project_name=self.interpreter.build.project_name,
              project_version=self.interpreter.build.dep_manifest[self.interpreter.active_projectname],
              # The backend object is under-used right now, but we will need it:
              # https://github.com/mesonbuild/meson/issues/1419
              backend=self.interpreter.backend,
              compilers=self.interpreter.build.compilers,
              targets=self.interpreter.build.targets,
              data=self.interpreter.build.data,
              headers=self.interpreter.build.get_headers(),
              man=self.interpreter.build.get_man(),
              global_args=self.interpreter.build.global_args,
              project_args=self.interpreter.build.projects_args.get(self.interpreter.subproject, {}),
              build_machine=self.interpreter.builtin['build_machine'].held_object,
              host_machine=self.interpreter.builtin['host_machine'].held_object,
              target_machine=self.interpreter.builtin['target_machine'].held_object,
          )
          if self.held_object.is_snippet(method_name):
              value = fn(self.interpreter, state, args, kwargs)
              return self.interpreter.holderify(value)
          else:
              value = fn(state, args, kwargs)
              if num_targets != len(self.interpreter.build.targets):
                  raise InterpreterException('Extension module altered internal state illegally.')
              return self.interpreter.module_method_callback(value)
  
  class MesonMain(InterpreterObject):
      def __init__(self, build, interpreter):
          InterpreterObject.__init__(self)
          self.build = build
          self.interpreter = interpreter
          self._found_source_scripts = {}
          self.methods.update({'get_compiler': self.get_compiler_method,
                               'is_cross_build': self.is_cross_build_method,
                               'has_exe_wrapper': self.has_exe_wrapper_method,
                               'is_unity': self.is_unity_method,
                               'is_subproject': self.is_subproject_method,
                               'current_source_dir': self.current_source_dir_method,
                               'current_build_dir': self.current_build_dir_method,
                               'source_root': self.source_root_method,
                               'build_root': self.build_root_method,
                               'add_install_script': self.add_install_script_method,
                               'add_postconf_script': self.add_postconf_script_method,
                               'install_dependency_manifest': self.install_dependency_manifest_method,
                               'project_version': self.project_version_method,
                               'version': self.version_method,
                               'project_name': self.project_name_method,
                               'get_cross_property': self.get_cross_property_method,
                               'backend': self.backend_method,
                               })
  
      def _find_source_script(self, name, args):
          # Prefer scripts in the current source directory
          search_dir = os.path.join(self.interpreter.environment.source_dir,
                                    self.interpreter.subdir)
          key = (name, search_dir)
          if key in self._found_source_scripts:
              found = self._found_source_scripts[key]
          else:
              found = dependencies.ExternalProgram(name, search_dir=search_dir)
              if found.found():
                  self._found_source_scripts[key] = found
              else:
                  m = 'Script or command {!r} not found or not executable'
                  raise InterpreterException(m.format(name))
          return build.RunScript(found.get_command(), args)
  
      def add_install_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_install_script takes one or more arguments')
          check_stringlist(args, 'add_install_script args must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.install_scripts.append(script)
  
      def add_postconf_script_method(self, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('add_postconf_script takes one or more arguments')
          check_stringlist(args, 'add_postconf_script arguments must be strings')
          script = self._find_source_script(args[0], args[1:])
          self.build.postconf_scripts.append(script)
  
      def current_source_dir_method(self, args, kwargs):
          src = self.interpreter.environment.source_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      def current_build_dir_method(self, args, kwargs):
          src = self.interpreter.environment.build_dir
          sub = self.interpreter.subdir
          if sub == '':
              return src
          return os.path.join(src, sub)
  
      def backend_method(self, args, kwargs):
          return self.interpreter.backend.name
  
      def source_root_method(self, args, kwargs):
          return self.interpreter.environment.source_dir
  
      def build_root_method(self, args, kwargs):
          return self.interpreter.environment.build_dir
  
      def has_exe_wrapper_method(self, args, kwargs):
          if self.is_cross_build_method(None, None) and \
             'binaries' in self.build.environment.cross_info.config and \
             self.build.environment.cross_info.need_exe_wrapper():
              exe_wrap = self.build.environment.cross_info.config['binaries'].get('exe_wrapper', None)
              if exe_wrap is None:
                  return False
          # We return True when exe_wrap is defined, when it's not needed, and
          # when we're compiling natively. The last two are semantically confusing.
          # Need to revisit this.
          return True
  
      def is_cross_build_method(self, args, kwargs):
          return self.build.environment.is_cross_build()
  
      def get_compiler_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('get_compiler_method must have one and only one argument.')
          cname = args[0]
          native = kwargs.get('native', None)
          if native is None:
              if self.build.environment.is_cross_build():
                  native = False
              else:
                  native = True
          if not isinstance(native, bool):
              raise InterpreterException('Type of "native" must be a boolean.')
          if native:
              clist = self.build.compilers
          else:
              clist = self.build.cross_compilers
          if cname in clist:
              return CompilerHolder(clist[cname], self.build.environment)
          raise InterpreterException('Tried to access compiler for unspecified language "%s".' % cname)
  
      def is_unity_method(self, args, kwargs):
          optval = self.interpreter.environment.coredata.get_builtin_option('unity')
          if optval == 'on' or (optval == 'subprojects' and self.interpreter.subproject != ''):
              return True
          return False
  
      def is_subproject_method(self, args, kwargs):
          return self.interpreter.is_subproject()
  
      def install_dependency_manifest_method(self, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Must specify manifest install file name')
          if not isinstance(args[0], str):
              raise InterpreterException('Argument must be a string.')
          self.build.dep_manifest_name = args[0]
  
      def project_version_method(self, args, kwargs):
          return self.build.dep_manifest[self.interpreter.active_projectname]['version']
  
      def version_method(self, args, kwargs):
          return coredata.version
  
      def project_name_method(self, args, kwargs):
          return self.interpreter.active_projectname
  
      def get_cross_property_method(self, args, kwargs):
          if len(args) < 1 or len(args) > 2:
              raise InterpreterException('Must have one or two arguments.')
          propname = args[0]
          if not isinstance(propname, str):
              raise InterpreterException('Property name must be string.')
          try:
              props = self.interpreter.environment.cross_info.get_properties()
              return props[propname]
          except Exception:
              if len(args) == 2:
                  return args[1]
              raise InterpreterException('Unknown cross property: %s.' % propname)
  
  class Interpreter(InterpreterBase):
  
      def __init__(self, build, backend, subproject='', subdir='', subproject_dir='subprojects',
                   default_project_options=[]):
          super().__init__(build.environment.get_source_dir(), subdir)
          self.build = build
          self.environment = build.environment
          self.coredata = self.environment.get_coredata()
          self.backend = backend
          self.subproject = subproject
          self.subproject_dir = subproject_dir
          self.option_file = os.path.join(self.source_root, self.subdir, 'meson_options.txt')
          self.load_root_meson_file()
          self.sanity_check_ast()
          self.builtin.update({'meson': MesonMain(build, self)})
          self.generators = []
          self.visited_subdirs = {}
          self.project_args_frozen = False
          self.global_args_frozen = False  # implies self.project_args_frozen
          self.subprojects = {}
          self.subproject_stack = []
          self.default_project_options = default_project_options[:] # Passed from the outside, only used in subprojects.
          self.build_func_dict()
          self.parse_project()
          self.builtin['build_machine'] = BuildMachine(self.coredata.compilers)
          if not self.build.environment.is_cross_build():
              self.builtin['host_machine'] = self.builtin['build_machine']
              self.builtin['target_machine'] = self.builtin['build_machine']
          else:
              cross_info = self.build.environment.cross_info
              if cross_info.has_host():
                  self.builtin['host_machine'] = CrossMachineInfo(cross_info.config['host_machine'])
              else:
                  self.builtin['host_machine'] = self.builtin['build_machine']
              if cross_info.has_target():
                  self.builtin['target_machine'] = CrossMachineInfo(cross_info.config['target_machine'])
              else:
                  self.builtin['target_machine'] = self.builtin['host_machine']
          self.build_def_files = [os.path.join(self.subdir, environment.build_filename)]
  
      def build_func_dict(self):
          self.funcs.update({'project': self.func_project,
                             'message': self.func_message,
                             'error': self.func_error,
                             'executable': self.func_executable,
                             'dependency': self.func_dependency,
                             'static_library': self.func_static_lib,
                             'shared_library': self.func_shared_lib,
                             'shared_module': self.func_shared_module,
                             'library': self.func_library,
                             'jar': self.func_jar,
                             'build_target': self.func_build_target,
                             'custom_target': self.func_custom_target,
                             'run_target': self.func_run_target,
                             'generator': self.func_generator,
                             'test': self.func_test,
                             'benchmark': self.func_benchmark,
                             'install_headers': self.func_install_headers,
                             'install_man': self.func_install_man,
                             'subdir': self.func_subdir,
                             'install_data': self.func_install_data,
                             'install_subdir': self.func_install_subdir,
                             'configure_file': self.func_configure_file,
                             'include_directories': self.func_include_directories,
                             'add_global_arguments': self.func_add_global_arguments,
                             'add_project_arguments': self.func_add_project_arguments,
                             'add_global_link_arguments': self.func_add_global_link_arguments,
                             'add_project_link_arguments': self.func_add_project_link_arguments,
                             'add_test_setup': self.func_add_test_setup,
                             'add_languages': self.func_add_languages,
                             'find_program': self.func_find_program,
                             'find_library': self.func_find_library,
                             'configuration_data': self.func_configuration_data,
                             'run_command': self.func_run_command,
                             'gettext': self.func_gettext,
                             'option': self.func_option,
                             'get_option': self.func_get_option,
                             'subproject': self.func_subproject,
                             'vcs_tag': self.func_vcs_tag,
                             'set_variable': self.func_set_variable,
                             'is_variable': self.func_is_variable,
                             'get_variable': self.func_get_variable,
                             'import': self.func_import,
                             'files': self.func_files,
                             'declare_dependency': self.func_declare_dependency,
                             'assert': self.func_assert,
                             'environment': self.func_environment,
                             'join_paths': self.func_join_paths,
                             })
  
      def holderify(self, item):
          if isinstance(item, list):
              return [self.holderify(x) for x in item]
          if isinstance(item, build.CustomTarget):
              return CustomTargetHolder(item, self)
          elif isinstance(item, (int, str)) or item is None:
              return item
          elif isinstance(item, build.Executable):
              return ExecutableHolder(item, self)
          elif isinstance(item, build.GeneratedList):
              return GeneratedListHolder(item)
          elif isinstance(item, build.RunTarget):
              raise RuntimeError('This is not a pipe.')
          elif isinstance(item, build.RunScript):
              raise RuntimeError('Do not do this.')
          elif isinstance(item, build.Data):
              return DataHolder(item)
          elif isinstance(item, dependencies.InternalDependency):
              return InternalDependencyHolder(item)
          elif isinstance(item, dependencies.ExternalProgram):
              return ExternalProgramHolder(item)
          elif hasattr(item, 'held_object'):
              return item
          else:
              raise InterpreterException('Module returned a value of unknown type.')
  
      def process_new_values(self, invalues):
          if not isinstance(invalues, list):
              invalues = [invalues]
          for v in invalues:
              if isinstance(v, (build.BuildTarget, build.CustomTarget, build.RunTarget)):
                  self.add_target(v.name, v)
              elif isinstance(v, list):
                  self.module_method_callback(v)
              elif isinstance(v, build.GeneratedList):
                  pass
              elif isinstance(v, build.RunScript):
                  self.build.install_scripts.append(v)
              elif isinstance(v, build.Data):
                  self.build.data.append(v)
              elif isinstance(v, dependencies.ExternalProgram):
                  return ExternalProgramHolder(v)
              elif isinstance(v, dependencies.InternalDependency):
                  # FIXME: This is special cased and not ideal:
                  # The first source is our new VapiTarget, the rest are deps
                  self.process_new_values(v.sources[0])
              elif hasattr(v, 'held_object'):
                  pass
              else:
                  raise InterpreterException('Module returned a value of unknown type.')
  
      def module_method_callback(self, return_object):
          if not isinstance(return_object, ModuleReturnValue):
              raise InterpreterException('Bug in module, it returned an invalid object')
          invalues = return_object.new_objects
          self.process_new_values(invalues)
          return self.holderify(return_object.return_value)
  
      def get_build_def_files(self):
          return self.build_def_files
  
      def get_variables(self):
          return self.variables
  
      def check_cross_stdlibs(self):
          if self.build.environment.is_cross_build():
              cross_info = self.build.environment.cross_info
              for l, c in self.build.cross_compilers.items():
                  try:
                      di = mesonlib.stringlistify(cross_info.get_stdlib(l))
                      if len(di) != 2:
                          raise InterpreterException('Stdlib definition for %s should have exactly two elements.'
                                                     % l)
                      projname, depname = di
                      subproj = self.do_subproject(projname, {})
                      self.build.cross_stdlibs[l] = subproj.get_variable_method([depname], {})
                  except KeyError:
                      pass
  
      @stringArgs
      @noKwargs
      def func_import(self, node, args, kwargs):
          if len(args) != 1:
              raise InvalidCode('Import takes one argument.')
          modname = args[0]
          if modname not in self.environment.coredata.modules:
              try:
                  module = importlib.import_module('mesonbuild.modules.' + modname)
              except ImportError:
                  raise InvalidArguments('Module "%s" does not exist' % (modname, ))
              self.environment.coredata.modules[modname] = module.initialize()
          return ModuleHolder(modname, self.environment.coredata.modules[modname], self)
  
      @stringArgs
      @noKwargs
      def func_files(self, node, args, kwargs):
          return [mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, fname) for fname in args]
  
      @noPosargs
      def func_declare_dependency(self, node, args, kwargs):
          version = kwargs.get('version', self.project_version)
          if not isinstance(version, str):
              raise InterpreterException('Version must be a string.')
          incs = kwargs.get('include_directories', [])
          if not isinstance(incs, list):
              incs = [incs]
          libs = kwargs.get('link_with', [])
          if not isinstance(libs, list):
              libs = [libs]
          sources = kwargs.get('sources', [])
          if not isinstance(sources, list):
              sources = [sources]
          sources = self.source_strings_to_files(self.flatten(sources))
          deps = self.flatten(kwargs.get('dependencies', []))
          if not isinstance(deps, list):
              deps = [deps]
          compile_args = mesonlib.stringlistify(kwargs.get('compile_args', []))
          link_args = mesonlib.stringlistify(kwargs.get('link_args', []))
          final_deps = []
          for d in deps:
              try:
                  d = d.held_object
              except Exception:
                  pass
              if not isinstance(d, (dependencies.Dependency, dependencies.ExternalLibrary, dependencies.InternalDependency)):
                  raise InterpreterException('Dependencies must be external deps')
              final_deps.append(d)
          dep = dependencies.InternalDependency(version, incs, compile_args, link_args, libs, sources, final_deps)
          return DependencyHolder(dep)
  
      @noKwargs
      def func_assert(self, node, args, kwargs):
          if len(args) != 2:
              raise InterpreterException('Assert takes exactly two arguments')
          value, message = args
          if not isinstance(value, bool):
              raise InterpreterException('Assert value not bool.')
          if not isinstance(message, str):
              raise InterpreterException('Assert message not a string.')
          if not value:
              raise InterpreterException('Assert failed: ' + message)
  
      def validate_arguments(self, args, argcount, arg_types):
          if argcount is not None:
              if argcount != len(args):
                  raise InvalidArguments('Expected %d arguments, got %d.' %
                                         (argcount, len(args)))
          for i in range(min(len(args), len(arg_types))):
              wanted = arg_types[i]
              actual = args[i]
              if wanted is not None:
                  if not isinstance(actual, wanted):
                      raise InvalidArguments('Incorrect argument type.')
  
      def func_run_command(self, node, args, kwargs):
          if len(args) < 1:
              raise InterpreterException('Not enough arguments')
          cmd = args[0]
          cargs = args[1:]
          srcdir = self.environment.get_source_dir()
          builddir = self.environment.get_build_dir()
          m = 'must be a string, or the output of find_program(), files(), or ' \
              'configure_file(); not {!r}'
          if isinstance(cmd, ExternalProgramHolder):
              cmd = cmd.held_object
          else:
              if isinstance(cmd, mesonlib.File):
                  cmd = cmd.absolute_path(srcdir, builddir)
              elif not isinstance(cmd, str):
                  raise InterpreterException('First argument ' + m.format(cmd))
              # Prefer scripts in the current source directory
              search_dir = os.path.join(srcdir, self.subdir)
              prog = ExternalProgram(cmd, silent=True, search_dir=search_dir)
              if not prog.found():
                  raise InterpreterException('Program or command {!r} not found'
                                             'or not executable'.format(cmd))
              cmd = prog
          expanded_args = []
          for a in mesonlib.flatten(cargs):
              if isinstance(a, str):
                  expanded_args.append(a)
              elif isinstance(a, mesonlib.File):
                  expanded_args.append(a.absolute_path(srcdir, builddir))
              elif isinstance(a, ExternalProgramHolder):
                  expanded_args.append(a.held_object.get_path())
              else:
                  raise InterpreterException('Arguments ' + m.format(a))
          in_builddir = kwargs.get('in_builddir', False)
          if not isinstance(in_builddir, bool):
              raise InterpreterException('in_builddir must be boolean.')
          return RunProcess(cmd, expanded_args, srcdir, builddir, self.subdir,
                            get_meson_script(self.environment, 'mesonintrospect'), in_builddir)
  
      @stringArgs
      def func_gettext(self, nodes, args, kwargs):
          raise InterpreterException('Gettext() function has been moved to module i18n. Import it and use i18n.gettext() instead')
  
      def func_option(self, nodes, args, kwargs):
          raise InterpreterException('Tried to call option() in build description file. All options must be in the option file.')
  
      @stringArgs
      def func_subproject(self, nodes, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Subproject takes exactly one argument')
          dirname = args[0]
          return self.do_subproject(dirname, kwargs)
  
      def do_subproject(self, dirname, kwargs):
          if dirname in self.subproject_stack:
              fullstack = self.subproject_stack + [dirname]
              incpath = ' => '.join(fullstack)
              raise InvalidCode('Recursive include of subprojects: %s.' % incpath)
          if dirname in self.subprojects:
              return self.subprojects[dirname]
          subproject_dir_abs = os.path.join(self.environment.get_source_dir(), self.subproject_dir)
          r = wrap.Resolver(subproject_dir_abs, self.coredata.wrap_mode)
          try:
              resolved = r.resolve(dirname)
          except RuntimeError as e:
              msg = 'Subproject directory {!r} does not exist and cannot be downloaded:\n{}'
              raise InterpreterException(msg.format(os.path.join(self.subproject_dir, dirname), e))
          subdir = os.path.join(self.subproject_dir, resolved)
          os.makedirs(os.path.join(self.build.environment.get_build_dir(), subdir), exist_ok=True)
          self.global_args_frozen = True
          mlog.log('\nExecuting subproject ', mlog.bold(dirname), '.\n', sep='')
          subi = Interpreter(self.build, self.backend, dirname, subdir, self.subproject_dir,
                             mesonlib.stringlistify(kwargs.get('default_options', [])))
          subi.subprojects = self.subprojects
  
          subi.subproject_stack = self.subproject_stack + [dirname]
          current_active = self.active_projectname
          subi.run()
          if 'version' in kwargs:
              pv = subi.project_version
              wanted = kwargs['version']
              if pv == 'undefined' or not mesonlib.version_compare(pv, wanted):
                  raise InterpreterException('Subproject %s version is %s but %s required.' % (dirname, pv, wanted))
          self.active_projectname = current_active
          mlog.log('\nSubproject', mlog.bold(dirname), 'finished.')
          self.build.subprojects[dirname] = subi.project_version
          self.subprojects.update(subi.subprojects)
          self.subprojects[dirname] = SubprojectHolder(subi)
          self.build_def_files += subi.build_def_files
          return self.subprojects[dirname]
  
      @stringArgs
      @noKwargs
      def func_get_option(self, nodes, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Argument required for get_option.')
          optname = args[0]
          try:
              return self.environment.get_coredata().get_builtin_option(optname)
          except RuntimeError:
              pass
          try:
              return self.environment.coredata.compiler_options[optname].value
          except KeyError:
              pass
          if not coredata.is_builtin_option(optname) and self.is_subproject():
              optname = self.subproject + ':' + optname
          try:
              return self.environment.coredata.user_options[optname].value
          except KeyError:
              pass
          if optname.endswith('_link_args'):
              try:
                  lang = optname[:-10]
                  return self.coredata.external_link_args[lang]
              except KeyError:
                  pass
          if optname.endswith('_args'):
              try:
                  lang = optname[:-5]
                  return self.coredata.external_args[lang]
              except KeyError:
                  pass
          raise InterpreterException('Tried to access unknown option "%s".' % optname)
  
      @noKwargs
      def func_configuration_data(self, node, args, kwargs):
          if args:
              raise InterpreterException('configuration_data takes no arguments')
          return ConfigurationDataHolder()
  
      def parse_default_options(self, default_options):
          if not isinstance(default_options, list):
              default_options = [default_options]
          for option in default_options:
              if not isinstance(option, str):
                  mlog.debug(option)
                  raise InterpreterException('Default options must be strings')
              if '=' not in option:
                  raise InterpreterException('All default options must be of type key=value.')
              key, value = option.split('=', 1)
              if coredata.is_builtin_option(key):
                  if self.subproject != '':
                      continue # Only the master project is allowed to set global options.
                  if not self.environment.had_argument_for(key):
                      self.coredata.set_builtin_option(key, value)
                  # If this was set on the command line, do not override.
              else:
                  # Option values set with subproject() default_options override those
                  # set in project() default_options.
                  pref = key + '='
                  for i in self.default_project_options:
                      if i.startswith(pref):
                          option = i
                          break
                  # If we are in a subproject, add the subproject prefix to option
                  # name.
                  if self.subproject != '':
                      option = self.subproject + ':' + option
                  newoptions = [option] + self.environment.cmd_line_options.projectoptions
                  self.environment.cmd_line_options.projectoptions = newoptions
          # Add options that are only in default_options.
          for defopt in self.default_project_options:
              key, value = defopt.split('=')
              pref = key + '='
              for i in default_options:
                  if i.startswith(pref):
                      break
              else:
                  defopt = self.subproject + ':' + defopt
                  newoptions = [defopt] + self.environment.cmd_line_options.projectoptions
                  self.environment.cmd_line_options.projectoptions = newoptions
  
      @stringArgs
      def func_project(self, node, args, kwargs):
          if len(args) < 1:
              raise InvalidArguments('Not enough arguments to project(). Needs at least the project name.')
          proj_name = args[0]
          proj_langs = args[1:]
          if ':' in proj_name:
              raise InvalidArguments("Project name {!r} must not contain ':'".format(proj_name))
          default_options = kwargs.get('default_options', [])
          if self.environment.first_invocation and (len(default_options) > 0 or
                                                    len(self.default_project_options) > 0):
              self.parse_default_options(default_options)
          if not self.is_subproject():
              self.build.project_name = proj_name
          if os.path.exists(self.option_file):
              oi = optinterpreter.OptionInterpreter(self.subproject,
                                                    self.build.environment.cmd_line_options.projectoptions,
                                                    )
              oi.process(self.option_file)
              self.build.environment.merge_options(oi.options)
          self.active_projectname = proj_name
          self.project_version = kwargs.get('version', 'undefined')
          if self.build.project_version is None:
              self.build.project_version = self.project_version
          proj_license = mesonlib.stringlistify(kwargs.get('license', 'unknown'))
          self.build.dep_manifest[proj_name] = {'version': self.project_version,
                                                'license': proj_license}
          if self.subproject in self.build.projects:
              raise InvalidCode('Second call to project().')
          if not self.is_subproject() and 'subproject_dir' in kwargs:
              self.subproject_dir = kwargs['subproject_dir']
  
          if 'meson_version' in kwargs:
              cv = coredata.version
              pv = kwargs['meson_version']
              if not mesonlib.version_compare(cv, pv):
                  raise InterpreterException('Meson version is %s but project requires %s.' % (cv, pv))
          self.build.projects[self.subproject] = proj_name
          mlog.log('Project name: ', mlog.bold(proj_name), sep='')
          self.add_languages(proj_langs, True)
          langs = self.coredata.compilers.keys()
          if 'vala' in langs:
              if 'c' not in langs:
                  raise InterpreterException('Compiling Vala requires C. Add C to your project languages and rerun Meson.')
          if not self.is_subproject():
              self.check_cross_stdlibs()
  
      @stringArgs
      def func_add_languages(self, node, args, kwargs):
          return self.add_languages(args, kwargs.get('required', True))
  
      @noKwargs
      def func_message(self, node, args, kwargs):
          # reduce arguments again to avoid flattening posargs
          (posargs, _) = self.reduce_arguments(node.args)
          if len(posargs) != 1:
              raise InvalidArguments('Expected 1 argument, got %d' % len(posargs))
  
          arg = posargs[0]
          if isinstance(arg, list):
              argstr = stringifyUserArguments(arg)
          elif isinstance(arg, str):
              argstr = arg
          elif isinstance(arg, int):
              argstr = str(arg)
          else:
              raise InvalidArguments('Function accepts only strings, integers, lists and lists thereof.')
  
          mlog.log(mlog.bold('Message:'), argstr)
  
      @noKwargs
      def func_error(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          raise InterpreterException('Error encountered: ' + args[0])
  
      def detect_compilers(self, lang, need_cross_compiler):
          cross_comp = None
          if lang == 'c':
              comp = self.environment.detect_c_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_c_compiler(True)
          elif lang == 'cpp':
              comp = self.environment.detect_cpp_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_cpp_compiler(True)
          elif lang == 'objc':
              comp = self.environment.detect_objc_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_objc_compiler(True)
          elif lang == 'objcpp':
              comp = self.environment.detect_objcpp_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_objcpp_compiler(True)
          elif lang == 'java':
              comp = self.environment.detect_java_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # Java is platform independent.
          elif lang == 'cs':
              comp = self.environment.detect_cs_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # C# is platform independent.
          elif lang == 'vala':
              comp = self.environment.detect_vala_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # Vala compiles to platform-independent C
          elif lang == 'd':
              comp = self.environment.detect_d_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_d_compiler(True)
          elif lang == 'rust':
              comp = self.environment.detect_rust_compiler()
              if need_cross_compiler:
                  cross_comp = comp  # FIXME, not correct.
          elif lang == 'fortran':
              comp = self.environment.detect_fortran_compiler(False)
              if need_cross_compiler:
                  cross_comp = self.environment.detect_fortran_compiler(True)
          elif lang == 'swift':
              comp = self.environment.detect_swift_compiler()
              if need_cross_compiler:
                  raise InterpreterException('Cross compilation with Swift is not working yet.')
                  # cross_comp = self.environment.detect_fortran_compiler(True)
          else:
              raise InvalidCode('Tried to use unknown language "%s".' % lang)
          comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
          self.coredata.compilers[lang] = comp
          # Native compiler always exist so always add its options.
          new_options = comp.get_options()
          if cross_comp is not None:
              cross_comp.sanity_check(self.environment.get_scratch_dir(), self.environment)
              self.coredata.cross_compilers[lang] = cross_comp
              new_options.update(cross_comp.get_options())
          optprefix = lang + '_'
          for i in new_options:
              if not i.startswith(optprefix):
                  raise InterpreterException('Internal error, %s has incorrect prefix.' % i)
              cmd_prefix = i + '='
              for cmd_arg in self.environment.cmd_line_options.projectoptions:
                  if cmd_arg.startswith(cmd_prefix):
                      value = cmd_arg.split('=', 1)[1]
                      new_options[i].set_value(value)
          new_options.update(self.coredata.compiler_options)
          self.coredata.compiler_options = new_options
          return comp, cross_comp
  
      def add_languages(self, args, required):
          success = True
          need_cross_compiler = self.environment.is_cross_build() and self.environment.cross_info.need_cross_compiler()
          for lang in sorted(args, key=compilers.sort_clike):
              lang = lang.lower()
              if lang in self.coredata.compilers:
                  comp = self.coredata.compilers[lang]
                  cross_comp = self.coredata.cross_compilers.get(lang, None)
              else:
                  try:
                      (comp, cross_comp) = self.detect_compilers(lang, need_cross_compiler)
                  except Exception:
                      if not required:
                          mlog.log('Compiler for language', mlog.bold(lang), 'not found.')
                          success = False
                          continue
                      else:
                          raise
              mlog.log('Native %s compiler: ' % lang, mlog.bold(' '.join(comp.get_exelist())), ' (%s %s)' % (comp.id, comp.version), sep='')
              if not comp.get_language() in self.coredata.external_args:
                  (preproc_args, compile_args, link_args) = environment.get_args_from_envvars(comp)
                  self.coredata.external_preprocess_args[comp.get_language()] = preproc_args
                  self.coredata.external_args[comp.get_language()] = compile_args
                  self.coredata.external_link_args[comp.get_language()] = link_args
              self.build.add_compiler(comp)
              if need_cross_compiler:
                  mlog.log('Cross %s compiler: ' % lang, mlog.bold(' '.join(cross_comp.get_exelist())), ' (%s %s)' % (cross_comp.id, cross_comp.version), sep='')
                  self.build.add_cross_compiler(cross_comp)
              if self.environment.is_cross_build() and not need_cross_compiler:
                  self.build.add_cross_compiler(comp)
              self.add_base_options(comp)
          return success
  
      def add_base_options(self, compiler):
          proj_opt = self.environment.cmd_line_options.projectoptions
          for optname in compiler.base_options:
              if optname in self.coredata.base_options:
                  continue
              oobj = compilers.base_options[optname]
              for po in proj_opt:
                  if po.startswith(optname + '='):
                      oobj.set_value(po.split('=', 1)[1])
                      break
              self.coredata.base_options[optname] = oobj
  
      def func_find_program(self, node, args, kwargs):
          if not args:
              raise InterpreterException('No program name specified.')
          required = kwargs.get('required', True)
          if not isinstance(required, bool):
              raise InvalidArguments('"required" argument must be a boolean.')
          # Search for scripts relative to current subdir.
          # Do not cache found programs because find_program('foobar')
          # might give different results when run from different source dirs.
          source_dir = os.path.join(self.environment.get_source_dir(), self.subdir)
          for exename in args:
              if isinstance(exename, mesonlib.File):
                  if exename.is_built:
                      search_dir = os.path.join(self.environment.get_build_dir(),
                                                exename.subdir)
                  else:
                      search_dir = os.path.join(self.environment.get_source_dir(),
                                                exename.subdir)
                  exename = exename.fname
              elif isinstance(exename, str):
                  search_dir = source_dir
              else:
                  raise InvalidArguments('find_program only accepts strings and '
                                         'files, not {!r}'.format(exename))
              extprog = dependencies.ExternalProgram(exename, search_dir=search_dir)
              progobj = ExternalProgramHolder(extprog)
              if progobj.found():
                  return progobj
          if required and not progobj.found():
              raise InvalidArguments('Program "%s" not found or not executable' % exename)
          return progobj
  
      def func_find_library(self, node, args, kwargs):
          mlog.log(mlog.red('DEPRECATION:'), 'find_library() is removed, use the corresponding method in compiler object instead.')
  
      def _find_cached_dep(self, name, kwargs):
          # Check if we want this as a cross-dep or a native-dep
          # FIXME: Not all dependencies support such a distinction right now,
          # and we repeat this check inside dependencies that do. We need to
          # consolidate this somehow.
          is_cross = self.environment.is_cross_build()
          if 'native' in kwargs and is_cross:
              want_cross = not kwargs['native']
          else:
              want_cross = is_cross
          identifier = dependencies.get_dep_identifier(name, kwargs, want_cross)
          cached_dep = None
          # Check if we've already searched for and found this dep
          if identifier in self.coredata.deps:
              cached_dep = self.coredata.deps[identifier]
          else:
              # Check if exactly the same dep with different version requirements
              # was found already.
              wanted = identifier[1]
              for trial, trial_dep in self.coredata.deps.items():
                  # trial[1], identifier[1] are the version requirements
                  if trial[0] != identifier[0] or trial[2:] != identifier[2:]:
                      continue
                  found = trial_dep.get_version()
                  if not wanted or mesonlib.version_compare_many(found, wanted)[0]:
                      # We either don't care about the version, or our
                      # version requirements matched the trial dep's version.
                      cached_dep = trial_dep
                      break
          return identifier, cached_dep
  
      def func_dependency(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          name = args[0]
          if '<' in name or '>' in name or '=' in name:
              raise InvalidArguments('Characters <, > and = are forbidden in dependency names. To specify'
                                     'version\n requirements use the \'version\' keyword argument instead.')
          identifier, cached_dep = self._find_cached_dep(name, kwargs)
  
          if cached_dep:
              if kwargs.get('required', True) and not cached_dep.found():
                  m = 'Dependency {!r} was already checked and was not found'
                  raise DependencyException(m.format(name))
              dep = cached_dep
          else:
              # We need to actually search for this dep
              exception = None
              dep = None
              # If the dependency has already been configured, possibly by
              # a higher level project, try to use it first.
              if 'fallback' in kwargs:
                  dirname, varname = self.get_subproject_infos(kwargs)
                  if dirname in self.subprojects:
                      subproject = self.subprojects[dirname]
                      try:
                          # Never add fallback deps to self.coredata.deps
                          return subproject.get_variable_method([varname], {})
                      except KeyError:
                          pass
  
              # Search for it outside the project
              if not dep:
                  try:
                      dep = dependencies.find_external_dependency(name, self.environment, kwargs)
                  except DependencyException as e:
                      exception = e
                      pass
  
              # Search inside the projects list
              if not dep or not dep.found():
                  if 'fallback' in kwargs:
                      fallback_dep = self.dependency_fallback(name, kwargs)
                      if fallback_dep:
                          # Never add fallback deps to self.coredata.deps since we
                          # cannot cache them. They must always be evaluated else
                          # we won't actually read all the build files.
                          return fallback_dep
                  if not dep:
                      raise exception
  
          # Only store found-deps in the cache
          if dep.found():
              self.coredata.deps[identifier] = dep
          return DependencyHolder(dep)
  
      def get_subproject_infos(self, kwargs):
          fbinfo = kwargs['fallback']
          check_stringlist(fbinfo)
          if len(fbinfo) != 2:
              raise InterpreterException('Fallback info must have exactly two items.')
          return fbinfo
  
      def dependency_fallback(self, name, kwargs):
          if self.coredata.wrap_mode in (WrapMode.nofallback, WrapMode.nodownload):
              mlog.log('Not looking for a fallback subproject for the dependency',
                       mlog.bold(name), 'because:\nAutomatic wrap-based fallback '
                       'dependency downloading is disabled.')
              return None
          dirname, varname = self.get_subproject_infos(kwargs)
          # Try to execute the subproject
          try:
              sp_kwargs = {}
              try:
                  sp_kwargs['default_options'] = kwargs['default_options']
              except KeyError:
                  pass
              self.do_subproject(dirname, sp_kwargs)
          # Invalid code is always an error
          except InvalidCode:
              raise
          # If the subproject execution failed in a non-fatal way, don't raise an
          # exception; let the caller handle things.
          except:
              mlog.log('Also couldn\'t find a fallback subproject in',
                       mlog.bold(os.path.join(self.subproject_dir, dirname)),
                       'for the dependency', mlog.bold(name))
              return None
          try:
              dep = self.subprojects[dirname].get_variable_method([varname], {})
          except KeyError:
              if kwargs.get('required', True):
                  m = 'Fallback variable {!r} in the subproject {!r} does not exist'
                  raise DependencyException(m.format(varname, dirname))
              # If the dependency is not required, don't raise an exception
              mlog.log('Also couldn\'t find the dependency', mlog.bold(name),
                       'in the fallback subproject',
                       mlog.bold(os.path.join(self.subproject_dir, dirname)))
              return None
          if not isinstance(dep, DependencyHolder):
              raise InvalidCode('Fallback variable {!r} in the subproject {!r} is '
                                'not a dependency object.'.format(varname, dirname))
          # Check if the version of the declared dependency matches what we want
          if 'version' in kwargs:
              wanted = kwargs['version']
              found = dep.version_method([], {})
              if found == 'undefined' or not mesonlib.version_compare(found, wanted):
                  mlog.log('Subproject', mlog.bold(dirname), 'dependency',
                           mlog.bold(varname), 'version is', mlog.bold(found),
                           'but', mlog.bold(wanted), 'is required.')
                  return None
          mlog.log('Found a', mlog.green('fallback'), 'subproject',
                   mlog.bold(os.path.join(self.subproject_dir, dirname)), 'for',
                   mlog.bold(name))
          return dep
  
      def func_executable(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, ExecutableHolder)
  
      def func_static_lib(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, StaticLibraryHolder)
  
      def func_shared_lib(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, SharedLibraryHolder)
  
      def func_shared_module(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, SharedModuleHolder)
  
      def func_library(self, node, args, kwargs):
          if self.coredata.get_builtin_option('default_library') == 'shared':
              return self.func_shared_lib(node, args, kwargs)
          return self.func_static_lib(node, args, kwargs)
  
      def func_jar(self, node, args, kwargs):
          return self.build_target(node, args, kwargs, JarHolder)
  
      def func_build_target(self, node, args, kwargs):
          if 'target_type' not in kwargs:
              raise InterpreterException('Missing target_type keyword argument')
          target_type = kwargs.pop('target_type')
          if target_type == 'executable':
              return self.func_executable(node, args, kwargs)
          elif target_type == 'shared_library':
              return self.func_shared_lib(node, args, kwargs)
          elif target_type == 'static_library':
              return self.func_static_lib(node, args, kwargs)
          elif target_type == 'library':
              return self.func_library(node, args, kwargs)
          elif target_type == 'jar':
              return self.func_jar(node, args, kwargs)
          else:
              raise InterpreterException('Unknown target_type.')
  
      def func_vcs_tag(self, node, args, kwargs):
          if 'input' not in kwargs or 'output' not in kwargs:
              raise InterpreterException('Keyword arguments input and output must exist')
          fallback = kwargs.pop('fallback', self.project_version)
          if not isinstance(fallback, str):
              raise InterpreterException('Keyword argument fallback must be a string.')
          replace_string = kwargs.pop('replace_string', '@VCS_TAG@')
          regex_selector = '(.*)' # default regex selector for custom command: use complete output
          vcs_cmd = kwargs.get('command', None)
          if vcs_cmd and not isinstance(vcs_cmd, list):
              vcs_cmd = [vcs_cmd]
          source_dir = os.path.normpath(os.path.join(self.environment.get_source_dir(), self.subdir))
          if vcs_cmd:
              # Is the command an executable in path or maybe a script in the source tree?
              vcs_cmd[0] = shutil.which(vcs_cmd[0]) or os.path.join(source_dir, vcs_cmd[0])
          else:
              vcs = mesonlib.detect_vcs(source_dir)
              if vcs:
                  mlog.log('Found %s repository at %s' % (vcs['name'], vcs['wc_dir']))
                  vcs_cmd = vcs['get_rev'].split()
                  regex_selector = vcs['rev_regex']
              else:
                  vcs_cmd = [' '] # executing this cmd will fail in vcstagger.py and force to use the fallback string
          # vcstagger.py parameters: infile, outfile, fallback, source_dir, replace_string, regex_selector, command...
          kwargs['command'] = [sys.executable,
                               self.environment.get_build_command(),
                               '--internal',
                               'vcstagger',
                               '@INPUT0@',
                               '@OUTPUT0@',
                               fallback,
                               source_dir,
                               replace_string,
                               regex_selector] + vcs_cmd
          kwargs.setdefault('build_always', True)
          return self.func_custom_target(node, [kwargs['output']], kwargs)
  
      @stringArgs
      def func_custom_target(self, node, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('custom_target: Only one positional argument is allowed, and it must be a string name')
          name = args[0]
          tg = CustomTargetHolder(build.CustomTarget(name, self.subdir, kwargs), self)
          self.add_target(name, tg.held_object)
          return tg
  
      def func_run_target(self, node, args, kwargs):
          global run_depr_printed
          if len(args) > 1:
              if not run_depr_printed:
                  mlog.log(mlog.red('DEPRECATION'), 'positional version of run_target is deprecated, use the keyword version instead.')
                  run_depr_printed = True
              if 'command' in kwargs:
                  raise InterpreterException('Can not have command both in positional and keyword arguments.')
              all_args = args[1:]
              deps = []
          elif len(args) == 1:
              if 'command' not in kwargs:
                  raise InterpreterException('Missing "command" keyword argument')
              all_args = kwargs['command']
              if not isinstance(all_args, list):
                  all_args = [all_args]
              deps = kwargs.get('depends', [])
              if not isinstance(deps, list):
                  deps = [deps]
          else:
              raise InterpreterException('Run_target needs at least one positional argument.')
  
          cleaned_args = []
          for i in mesonlib.flatten(all_args):
              try:
                  i = i.held_object
              except AttributeError:
                  pass
              if not isinstance(i, (str, build.BuildTarget, build.CustomTarget, dependencies.ExternalProgram, mesonlib.File)):
                  mlog.debug('Wrong type:', str(i))
                  raise InterpreterException('Invalid argument to run_target.')
              cleaned_args.append(i)
          name = args[0]
          if not isinstance(name, str):
              raise InterpreterException('First argument must be a string.')
          cleaned_deps = []
          for d in deps:
              try:
                  d = d.held_object
              except AttributeError:
                  pass
              if not isinstance(d, (build.BuildTarget, build.CustomTarget)):
                  raise InterpreterException('Depends items must be build targets.')
              cleaned_deps.append(d)
          command = cleaned_args[0]
          cmd_args = cleaned_args[1:]
          tg = RunTargetHolder(name, command, cmd_args, cleaned_deps, self.subdir)
          self.add_target(name, tg.held_object)
          return tg
  
      def func_generator(self, node, args, kwargs):
          gen = GeneratorHolder(self, args, kwargs)
          self.generators.append(gen)
          return gen
  
      def func_benchmark(self, node, args, kwargs):
          self.add_test(node, args, kwargs, False)
  
      def func_test(self, node, args, kwargs):
          self.add_test(node, args, kwargs, True)
  
      def unpack_env_kwarg(self, kwargs):
          envlist = kwargs.get('env', EnvironmentVariablesHolder())
          if isinstance(envlist, EnvironmentVariablesHolder):
              env = envlist.held_object
          else:
              if not isinstance(envlist, list):
                  envlist = [envlist]
              env = {}
              for e in envlist:
                  if '=' not in e:
                      raise InterpreterException('Env var definition must be of type key=val.')
                  (k, val) = e.split('=', 1)
                  k = k.strip()
                  val = val.strip()
                  if ' ' in k:
                      raise InterpreterException('Env var key must not have spaces in it.')
                  env[k] = val
          return env
  
      def add_test(self, node, args, kwargs, is_base_test):
          if len(args) != 2:
              raise InterpreterException('Incorrect number of arguments')
          if not isinstance(args[0], str):
              raise InterpreterException('First argument of test must be a string.')
          if not isinstance(args[1], (ExecutableHolder, JarHolder, ExternalProgramHolder)):
              raise InterpreterException('Second argument must be executable.')
          par = kwargs.get('is_parallel', True)
          if not isinstance(par, bool):
              raise InterpreterException('Keyword argument is_parallel must be a boolean.')
          cmd_args = kwargs.get('args', [])
          if not isinstance(cmd_args, list):
              cmd_args = [cmd_args]
          for i in cmd_args:
              if not isinstance(i, (str, mesonlib.File, TargetHolder)):
                  raise InterpreterException('Command line arguments must be strings, files or targets.')
          env = self.unpack_env_kwarg(kwargs)
          should_fail = kwargs.get('should_fail', False)
          if not isinstance(should_fail, bool):
              raise InterpreterException('Keyword argument should_fail must be a boolean.')
          timeout = kwargs.get('timeout', 30)
          if 'workdir' in kwargs:
              workdir = kwargs['workdir']
              if not isinstance(workdir, str):
                  raise InterpreterException('Workdir keyword argument must be a string.')
              if not os.path.isabs(workdir):
                  raise InterpreterException('Workdir keyword argument must be an absolute path.')
          else:
              workdir = None
          if not isinstance(timeout, int):
              raise InterpreterException('Timeout must be an integer.')
          suite = []
          for s in mesonlib.stringlistify(kwargs.get('suite', '')):
              if len(s) > 0:
                  s = ':' + s
              if self.is_subproject():
                  suite.append(self.subproject.replace(' ', '_').replace(':', '_') + s)
              else:
                  suite.append(self.build.project_name.replace(' ', '_').replace(':', '_') + s)
          t = Test(args[0], suite, args[1].held_object, par, cmd_args, env, should_fail, timeout, workdir)
          if is_base_test:
              self.build.tests.append(t)
              mlog.debug('Adding test "', mlog.bold(args[0]), '".', sep='')
          else:
              self.build.benchmarks.append(t)
              mlog.debug('Adding benchmark "', mlog.bold(args[0]), '".', sep='')
  
      def func_install_headers(self, node, args, kwargs):
          source_files = self.source_strings_to_files(args)
          h = Headers(source_files, kwargs)
          self.build.headers.append(h)
          return h
  
      @stringArgs
      def func_install_man(self, node, args, kwargs):
          m = Man(self.subdir, args, kwargs)
          self.build.man.append(m)
          return m
  
      @noKwargs
      def func_subdir(self, node, args, kwargs):
          self.validate_arguments(args, 1, [str])
          if '..' in args[0]:
              raise InvalidArguments('Subdir contains ..')
          if self.subdir == '' and args[0] == self.subproject_dir:
              raise InvalidArguments('Must not go into subprojects dir with subdir(), use subproject() instead.')
          if self.subdir == '' and args[0].startswith('meson-'):
              raise InvalidArguments('The "meson-" prefix is reserved and cannot be used for top-level subdir().')
          prev_subdir = self.subdir
          subdir = os.path.join(prev_subdir, args[0])
          if os.path.isabs(subdir):
              raise InvalidArguments('Subdir argument must be a relative path.')
          absdir = os.path.join(self.environment.get_source_dir(), subdir)
          symlinkless_dir = os.path.realpath(absdir)
          if symlinkless_dir in self.visited_subdirs:
              raise InvalidArguments('Tried to enter directory "%s", which has already been visited.'
                                     % subdir)
          self.visited_subdirs[symlinkless_dir] = True
          self.subdir = subdir
          os.makedirs(os.path.join(self.environment.build_dir, subdir), exist_ok=True)
          buildfilename = os.path.join(self.subdir, environment.build_filename)
          self.build_def_files.append(buildfilename)
          absname = os.path.join(self.environment.get_source_dir(), buildfilename)
          if not os.path.isfile(absname):
              self.subdir = prev_subdir
              raise InterpreterException('Non-existent build file {!r}'.format(buildfilename))
          with open(absname, encoding='utf8') as f:
              code = f.read()
          assert(isinstance(code, str))
          try:
              codeblock = mparser.Parser(code, self.subdir).parse()
          except mesonlib.MesonException as me:
              me.file = buildfilename
              raise me
          self.evaluate_codeblock(codeblock)
          self.subdir = prev_subdir
  
      def _get_kwarg_install_mode(self, kwargs):
          if 'install_mode' not in kwargs:
              return None
          install_mode = []
          mode = mesonlib.typeslistify(kwargs.get('install_mode', []), (str, int))
          for m in mode:
              # We skip any arguments that are set to `false`
              if m is False:
                  m = None
              install_mode.append(m)
          if len(install_mode) > 3:
              raise InvalidArguments('Keyword argument install_mode takes at '
                                     'most 3 arguments.')
          if len(install_mode) > 0 and install_mode[0] is not None and \
             not isinstance(install_mode[0], str):
              raise InvalidArguments('Keyword argument install_mode requires the '
                                     'permissions arg to be a string or false')
          return FileMode(*install_mode)
  
      def func_install_data(self, node, args, kwargs):
          kwsource = mesonlib.stringlistify(kwargs.get('sources', []))
          raw_sources = args + kwsource
          sources = []
          source_strings = []
          for s in raw_sources:
              if isinstance(s, mesonlib.File):
                  sources.append(s)
              else:
                  source_strings.append(s)
          sources += self.source_strings_to_files(source_strings)
          install_dir = kwargs.get('install_dir', None)
          if not isinstance(install_dir, (str, type(None))):
              raise InvalidArguments('Keyword argument install_dir not a string.')
          install_mode = self._get_kwarg_install_mode(kwargs)
          data = DataHolder(build.Data(sources, install_dir, install_mode))
          self.build.data.append(data.held_object)
          return data
  
      @stringArgs
      def func_install_subdir(self, node, args, kwargs):
          if len(args) != 1:
              raise InvalidArguments('Install_subdir requires exactly one argument.')
          if 'install_dir' not in kwargs:
              raise InvalidArguments('Missing keyword argument install_dir')
          install_dir = kwargs['install_dir']
          if not isinstance(install_dir, str):
              raise InvalidArguments('Keyword argument install_dir not a string.')
          install_mode = self._get_kwarg_install_mode(kwargs)
          idir = InstallDir(self.subdir, args[0], install_dir, install_mode)
          self.build.install_dirs.append(idir)
          return idir
  
      def func_configure_file(self, node, args, kwargs):
          if len(args) > 0:
              raise InterpreterException("configure_file takes only keyword arguments.")
          if 'output' not in kwargs:
              raise InterpreterException('Required keyword argument "output" not defined.')
          if 'configuration' in kwargs and 'command' in kwargs:
              raise InterpreterException('Must not specify both "configuration" '
                                         'and "command" keyword arguments since '
                                         'they are mutually exclusive.')
          if 'capture' in kwargs:
              if not isinstance(kwargs['capture'], bool):
                  raise InterpreterException('"capture" keyword must be a boolean.')
              if 'command' not in kwargs:
                  raise InterpreterException('"capture" keyword requires "command" keyword.')
  
          # Validate input
          inputfile = None
          ifile_abs = None
          if 'input' in kwargs:
              inputfile = kwargs['input']
              if isinstance(inputfile, list):
                  if len(inputfile) != 1:
                      m = "Keyword argument 'input' requires exactly one file"
                      raise InterpreterException(m)
                  inputfile = inputfile[0]
              if not isinstance(inputfile, (str, mesonlib.File)):
                  raise InterpreterException('Input must be a string or a file')
              if isinstance(inputfile, str):
                  inputfile = os.path.join(self.subdir, inputfile)
                  ifile_abs = os.path.join(self.environment.source_dir, inputfile)
              else:
                  ifile_abs = inputfile.absolute_path(self.environment.source_dir,
                                                      self.environment.build_dir)
                  inputfile = inputfile.relative_name()
          elif 'command' in kwargs and '@INPUT@' in kwargs['command']:
              raise InterpreterException('@INPUT@ used as command argument, but no input file specified.')
          # Validate output
          output = kwargs['output']
          if not isinstance(output, str):
              raise InterpreterException('Output file name must be a string')
          if ifile_abs:
              values = mesonlib.get_filenames_templates_dict([ifile_abs], None)
              outputs = mesonlib.substitute_values([output], values)
              output = outputs[0]
          if os.path.split(output)[0] != '':
              raise InterpreterException('Output file name must not contain a subdirectory.')
          (ofile_path, ofile_fname) = os.path.split(os.path.join(self.subdir, output))
          ofile_abs = os.path.join(self.environment.build_dir, ofile_path, ofile_fname)
          if 'configuration' in kwargs:
              conf = kwargs['configuration']
              if not isinstance(conf, ConfigurationDataHolder):
                  raise InterpreterException('Argument "configuration" is not of type configuration_data')
              mlog.log('Configuring', mlog.bold(output), 'using configuration')
              if inputfile is not None:
                  # Normalize the path of the conffile to avoid duplicates
                  # This is especially important to convert '/' to '\' on Windows
                  conffile = os.path.normpath(inputfile)
                  if conffile not in self.build_def_files:
                      self.build_def_files.append(conffile)
                  os.makedirs(os.path.join(self.environment.build_dir, self.subdir), exist_ok=True)
                  mesonlib.do_conf_file(ifile_abs, ofile_abs, conf.held_object)
              else:
                  mesonlib.dump_conf_header(ofile_abs, conf.held_object)
              conf.mark_used()
          elif 'command' in kwargs:
              # We use absolute paths for input and output here because the cwd
              # that the command is run from is 'unspecified', so it could change.
              # Currently it's builddir/subdir for in_builddir else srcdir/subdir.
              if ifile_abs:
                  values = mesonlib.get_filenames_templates_dict([ifile_abs], [ofile_abs])
              else:
                  values = mesonlib.get_filenames_templates_dict(None, [ofile_abs])
              # Substitute @INPUT@, @OUTPUT@, etc here.
              cmd = mesonlib.substitute_values(kwargs['command'], values)
              mlog.log('Configuring', mlog.bold(output), 'with command')
              res = self.func_run_command(node, cmd, {'in_builddir': True})
              if res.returncode != 0:
                  raise InterpreterException('Running configure command failed.\n%s\n%s' %
                                             (res.stdout, res.stderr))
              if 'capture' in kwargs and kwargs['capture']:
                  dst_tmp = ofile_abs + '~'
                  with open(dst_tmp, 'w', encoding='utf-8') as f:
                      f.writelines(res.stdout)
                  if ifile_abs:
                      shutil.copymode(ifile_abs, dst_tmp)
                  mesonlib.replace_if_different(ofile_abs, dst_tmp)
          else:
              raise InterpreterException('Configure_file must have either "configuration" or "command".')
          idir = kwargs.get('install_dir', None)
          if isinstance(idir, str):
              cfile = mesonlib.File.from_built_file(ofile_path, ofile_fname)
              self.build.data.append(build.Data([cfile], idir))
          return mesonlib.File.from_built_file(self.subdir, output)
  
      @stringArgs
      def func_include_directories(self, node, args, kwargs):
          src_root = self.environment.get_source_dir()
          build_root = self.environment.get_build_dir()
          absbase_src = os.path.join(src_root, self.subdir)
          absbase_build = os.path.join(build_root, self.subdir)
  
          for a in args:
              if a.startswith(src_root):
                  raise InvalidArguments('''Tried to form an absolute path to a source dir. You should not do that but use
  relative paths instead.
  
  To get include path to any directory relative to the current dir do
  
  incdir = include_directories(dirname)
  
  After this incdir will contain both the current source dir as well as the
  corresponding build dir. It can then be used in any subdirectory and
  Meson will take care of all the busywork to make paths work.
  
  Dirname can even be '.' to mark the current directory. Though you should
  remember that the current source and build directories are always
  put in the include directories by default so you only need to do
  include_directories('.') if you intend to use the result in a
  different subdirectory.
  ''')
              absdir_src = os.path.join(absbase_src, a)
              absdir_build = os.path.join(absbase_build, a)
              if not os.path.isdir(absdir_src) and not os.path.isdir(absdir_build):
                  raise InvalidArguments('Include dir %s does not exist.' % a)
          is_system = kwargs.get('is_system', False)
          if not isinstance(is_system, bool):
              raise InvalidArguments('Is_system must be boolean.')
          i = IncludeDirsHolder(build.IncludeDirs(self.subdir, args, is_system))
          return i
  
      @stringArgs
      def func_add_test_setup(self, node, args, kwargs):
          if len(args) != 1:
              raise InterpreterException('Add_test_setup needs one argument for the setup name.')
          setup_name = args[0]
          if re.fullmatch('[_a-zA-Z][_0-9a-zA-Z]*', setup_name) is None:
              raise InterpreterException('Setup name may only contain alphanumeric characters.')
          try:
              inp = kwargs.get('exe_wrapper', [])
              if not isinstance(inp, list):
                  inp = [inp]
              exe_wrapper = []
              for i in inp:
                  if hasattr(i, 'held_object'):
                      i = i.held_object
                  if isinstance(i, str):
                      exe_wrapper.append(i)
                  elif isinstance(i, dependencies.ExternalProgram):
                      if not i.found():
                          raise InterpreterException('Tried to use non-found executable.')
                      exe_wrapper += i.get_command()
                  else:
                      raise InterpreterException('Exe wrapper can only contain strings or external binaries.')
          except KeyError:
              exe_wrapper = None
          gdb = kwargs.get('gdb', False)
          if not isinstance(gdb, bool):
              raise InterpreterException('Gdb option must be a boolean')
          timeout_multiplier = kwargs.get('timeout_multiplier', 1)
          if not isinstance(timeout_multiplier, int):
              raise InterpreterException('Timeout multiplier must be a number.')
          env = self.unpack_env_kwarg(kwargs)
          setupobj = build.TestSetup(exe_wrapper=exe_wrapper,
                                     gdb=gdb,
                                     timeout_multiplier=timeout_multiplier,
                                     env=env)
          if self.subproject == '':
              # Dunno what we should do with subprojects really. Let's start simple
              # and just use the master project ones.
              self.build.test_setups[setup_name] = setupobj
  
      @stringArgs
      def func_add_global_arguments(self, node, args, kwargs):
          self.add_global_arguments(node, self.build.global_args, args, kwargs)
  
      @stringArgs
      def func_add_global_link_arguments(self, node, args, kwargs):
          self.add_global_arguments(node, self.build.global_link_args, args, kwargs)
  
      @stringArgs
      def func_add_project_arguments(self, node, args, kwargs):
          self.add_project_arguments(node, self.build.projects_args, args, kwargs)
  
      @stringArgs
      def func_add_project_link_arguments(self, node, args, kwargs):
          self.add_project_arguments(node, self.build.projects_link_args, args, kwargs)
  
      def add_global_arguments(self, node, argsdict, args, kwargs):
          if self.subproject != '':
              msg = 'Function \'{}\' cannot be used in subprojects because ' \
                    'there is no way to make that reliable.\nPlease only call ' \
                    'this if is_subproject() returns false. Alternatively, ' \
                    'define a variable that\ncontains your language-specific ' \
                    'arguments and add it to the appropriate *_args kwarg ' \
                    'in each target.'.format(node.func_name)
              raise InvalidCode(msg)
          frozen = self.project_args_frozen or self.global_args_frozen
          self.add_arguments(node, argsdict, frozen, args, kwargs)
  
      def add_project_arguments(self, node, argsdict, args, kwargs):
          if self.subproject not in argsdict:
              argsdict[self.subproject] = {}
          self.add_arguments(node, argsdict[self.subproject],
                             self.project_args_frozen, args, kwargs)
  
      def add_arguments(self, node, argsdict, args_frozen, args, kwargs):
          if args_frozen:
              msg = 'Tried to use \'{}\' after a build target has been declared.\n' \
                    'This is not permitted. Please declare all ' \
                    'arguments before your targets.'.format(node.func_name)
              raise InvalidCode(msg)
  
          if 'language' not in kwargs:
              raise InvalidCode('Missing language definition in {}'.format(node.func_name))
  
          for lang in mesonlib.stringlistify(kwargs['language']):
              lang = lang.lower()
              argsdict[lang] = argsdict.get(lang, []) + args
  
      def func_environment(self, node, args, kwargs):
          return EnvironmentVariablesHolder()
  
      @stringArgs
      @noKwargs
      def func_join_paths(self, node, args, kwargs):
          return os.path.join(*args).replace('\\', '/')
  
      def run(self):
          super().run()
          mlog.log('Build targets in project:', mlog.bold(str(len(self.build.targets))))
  
      def source_strings_to_files(self, sources):
          results = []
          for s in sources:
              if isinstance(s, (mesonlib.File, GeneratedListHolder,
                                CustomTargetHolder)):
                  pass
              elif isinstance(s, str):
                  s = mesonlib.File.from_source_file(self.environment.source_dir, self.subdir, s)
              else:
                  raise InterpreterException("Source item is not string or File-type object.")
              results.append(s)
          return results
  
      def add_target(self, name, tobj):
          if name == '':
              raise InterpreterException('Target name must not be empty.')
          if name in coredata.forbidden_target_names:
              raise InvalidArguments('Target name "%s" is reserved for Meson\'s internal use. Please rename.'
                                     % name)
          # To permit an executable and a shared library to have the
          # same name, such as "foo.exe" and "libfoo.a".
          idname = tobj.get_id()
          if idname in self.build.targets:
              raise InvalidCode('Tried to create target "%s", but a target of that name already exists.' % name)
          self.build.targets[idname] = tobj
          if idname not in self.coredata.target_guids:
              self.coredata.target_guids[idname] = str(uuid.uuid4()).upper()
  
      def build_target(self, node, args, kwargs, targetholder):
          if not args:
              raise InterpreterException('Target does not have a name.')
          name = args[0]
          sources = args[1:]
          if self.environment.is_cross_build():
              if kwargs.get('native', False):
                  is_cross = False
              else:
                  is_cross = True
          else:
              is_cross = False
          try:
              kw_src = self.flatten(kwargs['sources'])
              if not isinstance(kw_src, list):
                  kw_src = [kw_src]
          except KeyError:
              kw_src = []
          sources += kw_src
          sources = self.source_strings_to_files(sources)
          objs = self.flatten(kwargs.get('objects', []))
          kwargs['dependencies'] = self.flatten(kwargs.get('dependencies', []))
          if 'extra_files' in kwargs:
              ef = kwargs['extra_files']
              if not isinstance(ef, list):
                  ef = [ef]
              kwargs['extra_files'] = self.source_strings_to_files(ef)
          if not isinstance(objs, list):
              objs = [objs]
          self.check_sources_exist(os.path.join(self.source_root, self.subdir), sources)
          if targetholder is ExecutableHolder:
              targetclass = build.Executable
          elif targetholder is SharedLibraryHolder:
              targetclass = build.SharedLibrary
          elif targetholder is SharedModuleHolder:
              targetclass = build.SharedModule
          elif targetholder is StaticLibraryHolder:
              targetclass = build.StaticLibrary
          elif targetholder is JarHolder:
              targetclass = build.Jar
          else:
              mlog.debug('Unknown target type:', str(targetholder))
              raise RuntimeError('Unreachable code')
          target = targetclass(name, self.subdir, self.subproject, is_cross, sources, objs, self.environment, kwargs)
          if is_cross:
              self.add_cross_stdlib_info(target)
          l = targetholder(target, self)
          self.add_target(name, l.held_object)
          self.project_args_frozen = True
          return l
  
      def get_used_languages(self, target):
          result = {}
          for i in target.sources:
              for lang, c in self.build.compilers.items():
                  if c.can_compile(i):
                      result[lang] = True
                      break
          return result
  
      def add_cross_stdlib_info(self, target):
          for l in self.get_used_languages(target):
              if self.environment.cross_info.has_stdlib(l) \
                      and self.subproject != self.environment.cross_info.get_stdlib(l)[0]:
                  target.add_deps(self.build.cross_stdlibs[l])
  
      def check_sources_exist(self, subdir, sources):
          for s in sources:
              if not isinstance(s, str):
                  continue # This means a generated source and they always exist.
              fname = os.path.join(subdir, s)
              if not os.path.isfile(fname):
                  raise InterpreterException('Tried to add non-existing source file %s.' % s)
  
      def format_string(self, templ, args):
          if isinstance(args, mparser.ArgumentNode):
              args = args.arguments
          for (i, arg) in enumerate(args):
              arg = self.evaluate_statement(arg)
              if isinstance(arg, bool): # Python boolean is upper case.
                  arg = str(arg).lower()
              templ = templ.replace('@{}@'.format(i), str(arg))
          return templ
  
      # Only permit object extraction from the same subproject
      def validate_extraction(self, buildtarget):
          if not self.subdir.startswith(self.subproject_dir):
              if buildtarget.subdir.startswith(self.subproject_dir):
                  raise InterpreterException('Tried to extract objects from a subproject target.')
          else:
              if not buildtarget.subdir.startswith(self.subproject_dir):
                  raise InterpreterException('Tried to extract objects from the main project from a subproject.')
              if self.subdir.split('/')[1] != buildtarget.subdir.split('/')[1]:
                  raise InterpreterException('Tried to extract objects from a different subproject.')
  
      def check_contains(self, obj, args):
          if len(args) != 1:
              raise InterpreterException('Contains method takes exactly one argument.')
          item = args[0]
          for element in obj:
              if isinstance(element, list):
                  found = self.check_contains(element, args)
                  if found:
                      return True
              try:
                  if element == item:
                      return True
              except Exception:
                  pass
          return False
  
      def is_subproject(self):
          return self.subproject != ''
  
files: mesonbuild/interpreter.py