internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: mesonbuild/meson

Issue:
meson_exe: Don't assert that we need an exe_wrapper when we say we do…
…n't need one

Fixes cross compiling mesa from x86_64 -> x86 on an x86_64 system.

Fixes #5567


Discussion:

Resolving patch:
diff --git a/mesonbuild/dependencies/dev.py b/mesonbuild/dependencies/dev.py
--- a/mesonbuild/dependencies/dev.py
+++ b/mesonbuild/dependencies/dev.py
@@ -460,12 +460,12 @@ def _factory(cls, env, kwargs):
         methods = cls._process_method_kw(kwargs)
         candidates = []
 
-        if DependencyMethods.CMAKE in methods:
-            candidates.append(functools.partial(LLVMDependencyCMake, env, kwargs))
-
         if DependencyMethods.CONFIG_TOOL in methods:
             candidates.append(functools.partial(LLVMDependencyConfigTool, env, kwargs))
 
+        if DependencyMethods.CMAKE in methods:
+            candidates.append(functools.partial(LLVMDependencyCMake, env, kwargs))
+
         return candidates
 
     @staticmethod


Test patch:
diff --git a/test cases/frameworks/15 llvm/meson.build b/test cases/frameworks/15 llvm/meson.build
--- a/test cases/frameworks/15 llvm/meson.build	
+++ b/test cases/frameworks/15 llvm/meson.build	
@@ -31,25 +31,29 @@ if not dep_tinfo.found()
   dep_tinfo = cpp.find_library('tinfo', required: false)
 endif
 
-foreach static : [true, false]
-  llvm_dep = dependency(
-    'llvm',
-    modules : ['bitwriter', 'asmprinter', 'executionengine', 'target',
-               'mcjit', 'nativecodegen', 'amdgpu'],
-    required : false,
-    static : static,
-  )
-  if llvm_dep.found()
-    name = static ? 'static' : 'dynamic'
-    executable(
-      'sum-@0@'.format(name),
-      'sum.c',
-      dependencies : [
-        llvm_dep, dep_tinfo,
-        # zlib will be statically linked on windows
-        dependency('zlib', required : host_machine.system() != 'windows'),
-        meson.get_compiler('c').find_library('dl', required : false),
-      ]
+foreach method : ['config-tool', 'cmake']
+  foreach static : [true, false]
+    message('Trying method @0@ for @1@ link'.format(method, static ? 'static' : 'dynamic'))
+    llvm_dep = dependency(
+      'llvm',
+      modules : ['bitwriter', 'asmprinter', 'executionengine', 'target',
+                'mcjit', 'nativecodegen', 'amdgpu'],
+      required : false,
+      static : static,
+      method : method,
     )
-  endif
+    if llvm_dep.found()
+      name = static ? 'static' : 'dynamic'
+      executable(
+        'sum-@0@-@1@'.format(name, method),
+        'sum.c',
+        dependencies : [
+          llvm_dep, dep_tinfo,
+          # zlib will be statically linked on windows
+          dependency('zlib', required : host_machine.system() != 'windows'),
+          meson.get_compiler('c').find_library('dl', required : false),
+        ]
+      )
+    endif
+  endforeach
 endforeach
Repository: mesonbuild/meson

Issue:
windres module doesn't flatten arguments
```meson
import('windows').compile_resources('file.rc', args : [[-DFOO'], '-DBAR])
```
results in
```
ERROR: List item must be one of <class 'str'>
```


Discussion:

Resolving patch:
diff --git a/mesonbuild/modules/windows.py b/mesonbuild/modules/windows.py
--- a/mesonbuild/modules/windows.py
+++ b/mesonbuild/modules/windows.py
@@ -23,7 +23,7 @@
 from . import ModuleReturnValue
 from . import ExtensionModule
 from ..interpreter import CustomTargetHolder
-from ..interpreterbase import permittedKwargs, FeatureNewKwargs
+from ..interpreterbase import permittedKwargs, FeatureNewKwargs, flatten
 from ..dependencies import ExternalProgram
 
 class ResourceCompilerType(enum.Enum):
@@ -78,7 +78,7 @@ def _find_resource_compiler(self, state):
     @FeatureNewKwargs('windows.compile_resources', '0.47.0', ['depend_files', 'depends'])
     @permittedKwargs({'args', 'include_directories', 'depend_files', 'depends'})
     def compile_resources(self, state, args, kwargs):
-        extra_args = mesonlib.stringlistify(kwargs.get('args', []))
+        extra_args = mesonlib.stringlistify(flatten(kwargs.get('args', [])))
         wrc_depend_files = extract_as_list(kwargs, 'depend_files', pop = True)
         wrc_depends = extract_as_list(kwargs, 'depends', pop = True)
         for d in wrc_depends:


Test patch:
diff --git a/test cases/windows/5 resources/res/meson.build b/test cases/windows/5 resources/res/meson.build
--- a/test cases/windows/5 resources/res/meson.build	
+++ b/test cases/windows/5 resources/res/meson.build	
@@ -2,7 +2,8 @@ win = import('windows')
 
 res = win.compile_resources('myres.rc',
   depend_files: 'sample.ico',
-  include_directories : inc)
+  include_directories : inc,
+  args : [['-DFOO'], '-DBAR'])
 
 # test that with MSVC tools, LIB/LINK invokes CVTRES with correct /MACHINE
 static_library('reslib', res, 'dummy.c')
Repository: mesonbuild/meson

Issue:
D: strip unsupported -D (and -f) flags for ldc2
Building [tilix](https://github.com/gnunn1/tilix) on FreeBSD, where the x11 pkgconf file contains a define flag:

```
% cat /usr/local/libdata/pkgconfig/x11.pc
[…]
Cflags: -I${includedir} -D_THREAD_SAFE
```

```
[1/63] ldc2 -I=tilix@exe -I=. -I=.. -I=../source/ -I=data -I/usr/local/include/d/gtkd-3/ -I/usr/local/include -enable-color -wi -release -enable-inlining -Hkeep-all-bodies -O3 -D_THREAD_SAFE -vcolumns -d-version=StdLoggerDisableTrace  -of='tilix@exe/source_secretc_secret.d.o' -c ../source/secretc/secret.d
FAILED: tilix@exe/source_secretc_secret.d.o
ldc2 -I=tilix@exe -I=. -I=.. -I=../source/ -I=data -I/usr/local/include/d/gtkd-3/ -I/usr/local/include -enable-color -wi -release -enable-inlining -Hkeep-all-bodies -O3 -D_THREAD_SAFE -vcolumns -d-version=StdLoggerDisableTrace  -of='tilix@exe/source_secretc_secret.d.o' -c ../source/secretc/secret.d
ldc2: Unknown command line argument '-D_THREAD_SAFE'.  Try: 'ldc2 -help'
ldc2: Did you mean '-pre-RA-sched'?
```

I guess such flags should be just removed…

Also, FreeBSD Ports sets up `LDFLAGS` for C/C++, and meson ends up passing unsupported flags to ldc2 here as well:

```
ldc2: Unknown command line argument '-fstack-protector-strong'.  Try: 'ldc2 -help'
ldc2: Did you mean '-stack-symbol-ordering'?
```


Discussion:
ping

Resolving patch:
diff --git a/mesonbuild/compilers/d.py b/mesonbuild/compilers/d.py
--- a/mesonbuild/compilers/d.py
+++ b/mesonbuild/compilers/d.py
@@ -356,6 +356,10 @@ def translate_args_to_nongnu(cls, args):
             # Translate common D arguments here.
             if arg == '-pthread':
                 continue
+            if arg.startswith('-fstack-protector'):
+                continue
+            if arg.startswith('-D'):
+                continue
             if arg.startswith('-Wl,'):
                 # Translate linker arguments here.
                 linkargs = arg[arg.index(',') + 1:].split(',')


Test patch:
Repository: mesonbuild/meson

Issue:
Disabler in nested arrays not working fine
See #5658


Discussion:

Resolving patch:
diff --git a/mesonbuild/interpreterbase.py b/mesonbuild/interpreterbase.py
--- a/mesonbuild/interpreterbase.py
+++ b/mesonbuild/interpreterbase.py
@@ -337,20 +337,25 @@ def __init__(self):
     def found_method(self, args, kwargs):
         return False
 
-def is_disabler(i):
+def is_disabler(i) -> bool:
     return isinstance(i, Disabler)
 
-def is_disabled(args, kwargs):
+def is_arg_disabled(arg) -> bool:
+    if is_disabler(arg):
+        return True
+    if isinstance(arg, list):
+        for i in arg:
+            if is_arg_disabled(i):
+                return True
+    return False
+
+def is_disabled(args, kwargs) -> bool:
     for i in args:
-        if isinstance(i, Disabler):
+        if is_arg_disabled(i):
             return True
     for i in kwargs.values():
-        if isinstance(i, Disabler):
+        if is_arg_disabled(i):
             return True
-        if isinstance(i, list):
-            for j in i:
-                if isinstance(j, Disabler):
-                    return True
     return False
 
 class InterpreterBase:


Test patch:
diff --git a/test cases/common/164 disabler/meson.build b/test cases/common/164 disabler/meson.build
--- a/test cases/common/164 disabler/meson.build	
+++ b/test cases/common/164 disabler/meson.build	
@@ -33,6 +33,7 @@ assert(number == 2, 'If found handled incorrectly, value should be 2 but is @0@'
 
 dep = dependency('notfounddep', required : false, disabler : true)
 app = executable('myapp', 'notfound.c', dependencies : [dep])
+app = executable('myapp', 'notfound.c', dependencies : [[dep]])
 
 cc = meson.get_compiler('c')
 dep = cc.find_library('notfounddep', required : false, disabler : true)
Repository: mesonbuild/meson

Issue:
Extra return line in environment.py
Just a little error. :cat2: 

There's an extra return in:

https://github.com/mesonbuild/meson/blob/5d9a1558c2e1041b1149fca6b2bceba447b6823e/mesonbuild/environment.py#L761-L766

Which is a duplicate of the return in the if block directly above:

https://github.com/mesonbuild/meson/blob/5d9a1558c2e1041b1149fca6b2bceba447b6823e/mesonbuild/environment.py#L752-L760


Discussion:
Could you please open a pull request for this? It's definitely worth fixing :)

I'm surprised our linter didn't catch this already.
From what I can see, flake8 doesn't catch `W0101 Unreachable code`. I didn't immediately see any flake8 plugins that do this. Pylint does catch this error.

Meson `sideci.yml` config appears to only use flake8 at the moment.

Example (unreachable.py)

```python
def foo():
    return 1
    return 2


foo()
```

```sh
$ flake8   # no output

$ pylint unreachable.py

...
unreachable.py:3:4: W0101: Unreachable code (unreachable)
```
Here is what catches this error (complete output given below):

```sh
$ pylint mesonbuild --disable=all --enable=W0101

************* Module mesonbuild.environment
mesonbuild\environment.py:766:16: W0101: Unreachable code (unreachable)
************* Module mesonbuild.scripts.depfixer
mesonbuild\scripts\depfixer.py:418:8: W0101: Unreachable code (unreachable)
```

@nirbheek I think pylint for W0101 unreachable code would be worthwhile to add. Do you have a preference how to add this to CI e.g. Sider?
...and thank you so much @LynnKirby for raising this issue. I had blindly assumed that flake8 would catch these!

Resolving patch:
diff --git a/mesonbuild/environment.py b/mesonbuild/environment.py
--- a/mesonbuild/environment.py
+++ b/mesonbuild/environment.py
@@ -763,7 +763,6 @@ def sanitize(p):
                 target = 'x86' if 'IA-32' in err else 'x86_64'
                 cls = IntelClCCompiler if lang == 'c' else IntelClCPPCompiler
                 return cls(compiler, version, for_machine, is_cross, exe_wrap, target)
-                return cls(ccache + compiler, version, compiler_type, for_machine, is_cross, exe_wrap, full_version=full_version)
             if 'Microsoft' in out or 'Microsoft' in err:
                 # Latest versions of Visual Studio print version
                 # number to stderr but earlier ones print version
diff --git a/mesonbuild/scripts/depfixer.py b/mesonbuild/scripts/depfixer.py
--- a/mesonbuild/scripts/depfixer.py
+++ b/mesonbuild/scripts/depfixer.py
@@ -413,9 +413,8 @@ def fix_darwin(fname, new_rpath, final_path, install_name_mappings):
             subprocess.check_call(['install_name_tool', fname] + args,
                                   stdout=subprocess.DEVNULL,
                                   stderr=subprocess.DEVNULL)
-    except Exception:
-        raise
-        sys.exit(0)
+    except Exception as err:
+        raise SystemExit(err)
 
 def fix_jar(fname):
     subprocess.check_call(['jar', 'xfv', fname, 'META-INF/MANIFEST.MF'])


Test patch:
Repository: mesonbuild/meson

Issue:
Changes to files outside source dir do not trigger reconfigure
In my Meson script, I read some configuration files that affect the build. If the config file is in the source dir, all is fine. However, if I'm reading a config file that is in the build dir, weird things happen. When the build dir is inside the source dir (I tested in `build` subdirectory), meson generates dependencies as expected and when config files change Meson is re-run automatically. However, when build dir is a sibling of the source dir, those same dependencies are _not_ generated and `ninja` ignores changes to those files.

Here is a short test example:
```meson
project(
    'meson test',
    [ 'c', 'cpp' ],
)

conf_file = files(meson.build_root() / '_testcfg')

run_command('cat', conf_file)
```


Discussion:
After a second thought, it is quite obvious that Meson decides whether the dependency should be included based on whether the file is in source dir or not. IMHO that is unexpected and should be considered a bug.
I found a workaround for this. If I use `configure_file(copy: true)` as an intermediate step, it works as expected.

Resolving patch:
diff --git a/mesonbuild/interpreter.py b/mesonbuild/interpreter.py
--- a/mesonbuild/interpreter.py
+++ b/mesonbuild/interpreter.py
@@ -2412,14 +2412,15 @@ def run_command_impl(self, node, args, kwargs, in_builddir=False):
                 expanded_args.append(a.held_object.get_path())
             else:
                 raise InterpreterException('Arguments ' + m.format(a))
+        # If any file that was used as an argument to the command
+        # changes, we must re-run the configuration step.
         for a in expanded_args:
             if not os.path.isabs(a):
                 a = os.path.join(builddir if in_builddir else srcdir, self.subdir, a)
             if os.path.isfile(a):
                 a = mesonlib.relpath(a, start=srcdir)
-                if not a.startswith('..'):
-                    if a not in self.build_def_files:
-                        self.build_def_files.append(a)
+                if a not in self.build_def_files:
+                    self.build_def_files.append(a)
         return RunProcess(cmd, expanded_args, env, srcdir, builddir, self.subdir,
                           self.environment.get_build_command() + ['introspect'],
                           in_builddir=in_builddir, check=check, capture=capture)


Test patch:
Repository: mesonbuild/meson

Issue:
AttributeError: module 'typing' has no attribute 'NoReturn'
>  def get_search_args(self, dirname: str) -> typing.NoReturn:
> 
> AttributeError: module 'typing' has no attribute 'NoReturn'

According to:
https://github.com/marshmallow-code/webargs/issues/366#issuecomment-459991329

it was fixed in python 3.5.4rc1. They replaced the typing expression with a string. 


Discussion:

Resolving patch:
diff --git a/mesonbuild/linkers.py b/mesonbuild/linkers.py
--- a/mesonbuild/linkers.py
+++ b/mesonbuild/linkers.py
@@ -664,7 +664,7 @@ def get_std_shared_lib_args(self) -> typing.List[str]:
     def get_output_args(self, outputname: str) -> typing.List[str]:
         return ['-output=%s' % outputname]
 
-    def get_search_args(self, dirname: str) -> typing.NoReturn:
+    def get_search_args(self, dirname: str) -> 'typing.NoReturn':
         raise EnvironmentError('rlink.exe does not have a search dir argument')
 
     def get_allow_undefined_args(self) -> typing.List[str]:
@@ -688,7 +688,7 @@ def __init__(self, for_machine: mesonlib.MachineChoice,
     def get_accepts_rsp(self) -> bool:
         return False
 
-    def get_std_shared_lib_args(self) -> typing.NoReturn:
+    def get_std_shared_lib_args(self) -> 'typing.NoReturn':
         raise mesonlib.MesonException('The Arm Linkers do not support shared libraries')
 
     def get_allow_undefined_args(self) -> typing.List[str]:


Test patch:
Repository: mesonbuild/meson

Issue:
Commit 1ea3ddc6 breaks the compile command
Prior to commit 1ea3ddc6 the *compile_commands.json* output from the config phase looks like this:

```
"command": "cc -Isrc/lib/libast/e416224@@ast@sta -Isrc/lib/libast -I../src/lib/libast -I. -I../
```

I've omitted the subsequent args because they aren't relevant.  With commit 1ea3ddc6 that same command looks like this:

```
"command": "cc -Isrc/lib/libast/e416224@@ast@sta -Isrc/lib/libast -I../src/lib/libast -I -I../
```

**Notice that `-I.` has become `-I`**

This breaks our build because a dynamically constructed header placed in the build root dir is no longer found.


Discussion:
This should be fixed by #5832.
Confirmed. PR #5832 fixes this for me.
Closing since there is a fix in the pipeline.

Resolving patch:
diff --git a/mesonbuild/compilers/mixins/gnu.py b/mesonbuild/compilers/mixins/gnu.py
--- a/mesonbuild/compilers/mixins/gnu.py
+++ b/mesonbuild/compilers/mixins/gnu.py
@@ -286,6 +286,8 @@ def get_compile_only_args(self) -> typing.List[str]:
         return ['-c']
 
     def get_include_args(self, path: str, is_system: bool) -> typing.List[str]:
+        if not path:
+            path = '.'
         if is_system:
             return ['-isystem' + path]
         return ['-I' + path]


Test patch:
diff --git a/test cases/common/225 include_dir dot/meson.build b/test cases/common/225 include_dir dot/meson.build
new file mode 100644
--- /dev/null
+++ b/test cases/common/225 include_dir dot/meson.build	
@@ -0,0 +1,8 @@
+project('Include Here', 'c')
+
+# The layout with the .h file in . and the .c files in src/ is critical to
+# tickle the bug #5847
+
+inc = include_directories('.')
+
+subdir('src')
\ No newline at end of file
diff --git a/test cases/common/225 include_dir dot/rone.h b/test cases/common/225 include_dir dot/rone.h
new file mode 100644
--- /dev/null
+++ b/test cases/common/225 include_dir dot/rone.h	
@@ -0,0 +1 @@
+int rOne(void);
\ No newline at end of file
diff --git a/test cases/common/225 include_dir dot/src/main.c b/test cases/common/225 include_dir dot/src/main.c
new file mode 100644
--- /dev/null
+++ b/test cases/common/225 include_dir dot/src/main.c	
@@ -0,0 +1,5 @@
+#include "rone.h"
+
+int main() {
+    return rOne();
+}
\ No newline at end of file
diff --git a/test cases/common/225 include_dir dot/src/meson.build b/test cases/common/225 include_dir dot/src/meson.build
new file mode 100644
--- /dev/null
+++ b/test cases/common/225 include_dir dot/src/meson.build	
@@ -0,0 +1,6 @@
+t = executable(
+  'main',
+  ['main.c', 'rone.c'],
+  include_directories : inc,
+  implicit_include_directories : false,
+)
\ No newline at end of file
diff --git a/test cases/common/225 include_dir dot/src/rone.c b/test cases/common/225 include_dir dot/src/rone.c
new file mode 100644
--- /dev/null
+++ b/test cases/common/225 include_dir dot/src/rone.c	
@@ -0,0 +1,3 @@
+int rOne(void) {
+    return 1;
+}
\ No newline at end of file
Repository: mesonbuild/meson

Issue:
objc freestanding sanitycheck failed
Header stdio.h isn't available on the freestanding environment,

https://github.com/mesonbuild/meson/blob/7b9c348102792030859ed0001a51416506a0a092/mesonbuild/compilers/objc.py#L44

https://en.cppreference.com/w/cpp/freestanding


Discussion:

Resolving patch:
diff --git a/mesonbuild/compilers/objc.py b/mesonbuild/compilers/objc.py
--- a/mesonbuild/compilers/objc.py
+++ b/mesonbuild/compilers/objc.py
@@ -41,7 +41,7 @@ def sanity_check(self, work_dir, environment):
         else:
             extra_flags += environment.coredata.get_external_link_args(self.for_machine, self.language)
         with open(source_name, 'w') as ofile:
-            ofile.write('#import<stdio.h>\n'
+            ofile.write('#import<stddef.h>\n'
                         'int main() { return 0; }\n')
         pc = subprocess.Popen(self.exelist + extra_flags + [source_name, '-o', binary_name])
         pc.wait()


Test patch:
Repository: mesonbuild/meson

Issue:
cmake config generator doesn't support `check_and_set`
According to https://cmake.org/cmake/help/v3.2/module/CMakePackageConfigHelpers.html?highlight=set_and_check, it's a best practice to use `set_and_check` instead of plain `set`. `set_and_check` is of course not normally defined, but is generated as part of the replacement of @PACKAGE_INIT@.

I would like to share a single .in file between a legacy cmake build system and a new meson build system, without giving up cmake best practice in the mean time.


Discussion:
Is this related to [configure_package_config_file](https://mesonbuild.com/CMake-module.html#cmakeconfigure_package_config_file), CMake subprojects, or the CMake dependency backend?

Also, do you have a public repo with this problem?
the Cmake module, so `configure_package_config_file`. The repo in question is [here](https://gitlab.freedesktop.org/mesa/waffle), there's a pull request to add the cmake file to the meson build.

Resolving patch:
diff --git a/mesonbuild/modules/cmake.py b/mesonbuild/modules/cmake.py
--- a/mesonbuild/modules/cmake.py
+++ b/mesonbuild/modules/cmake.py
@@ -29,6 +29,7 @@
 ####### Expanded from \\@PACKAGE_INIT\\@ by configure_package_config_file() #######
 ####### Any changes to this file will be overwritten by the next CMake run ####
 ####### The input file was @inputFileName@ ########
+
 get_filename_component(PACKAGE_PREFIX_DIR "${CMAKE_CURRENT_LIST_DIR}/@PACKAGE_RELATIVE_PATH@" ABSOLUTE)
 '''
 PACKAGE_INIT_EXT = '''
@@ -42,6 +43,16 @@
 unset(_realOrig)
 unset(_realCurr)
 '''
+PACKAGE_INIT_SET_AND_CHECK = '''
+macro(set_and_check _var _file)
+  set(${_var} "${_file}")
+  if(NOT EXISTS "${_file}")
+    message(FATAL_ERROR "File or directory ${_file} referenced by variable ${_var} does not exist !")
+  endif()
+endmacro()
+
+####################################################################################
+'''
 
 class CMakeSubprojectHolder(InterpreterObject, ObjectHolder):
     def __init__(self, subp, pv):
@@ -184,6 +195,7 @@ def create_package_file(self, infile, outfile, PACKAGE_RELATIVE_PATH, extra, con
         package_init = PACKAGE_INIT_BASE.replace('@PACKAGE_RELATIVE_PATH@', PACKAGE_RELATIVE_PATH)
         package_init = package_init.replace('@inputFileName@', infile)
         package_init += extra
+        package_init += PACKAGE_INIT_SET_AND_CHECK
 
         try:
             with open(infile, "r") as fin:


Test patch:
Repository: mesonbuild/meson

Issue:
Missing `libselinux` dependency on Arch
swaywm/wlroots#1477 provides more context


Discussion:
The problem is `restore_selinux_contexts()` in minstall.py does `subprocess.check_call(['selinuxenabled'])` but `selinuxenabled` is not installed. Meson catch the FileNotFoundError exception but for some reason your python 3.7 seems to raise NotADirectoryError that we don't catch.

It is weird that python 3.7 changed that exception, but I guess we should catch it too.

Resolving patch:
diff --git a/mesonbuild/minstall.py b/mesonbuild/minstall.py
--- a/mesonbuild/minstall.py
+++ b/mesonbuild/minstall.py
@@ -157,7 +157,7 @@ def restore_selinux_contexts():
     '''
     try:
         subprocess.check_call(['selinuxenabled'])
-    except (FileNotFoundError, PermissionError, subprocess.CalledProcessError):
+    except (FileNotFoundError, NotADirectoryError, PermissionError, subprocess.CalledProcessError):
         # If we don't have selinux or selinuxenabled returned 1, failure
         # is ignored quietly.
         return


Test patch: