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

Issue:
ERROR: <ExternalLibrary libcrypto: True> is not a target.
**Describe the bug**

I get the error `ERROR: <ExternalLibrary libcrypto: True> is not a target.` when trying to setup the build directory for this simple project.

**To Reproduce**

meson.build
```
project('p', 'cpp')
compiler = meson.get_compiler('cpp')
libcrypto_dep = declare_dependency(
  include_directories: ['C:\Qt\Tools\OpenSSL\Win_x64\include'],
  link_with: compiler.find_library('libcrypto', dirs: 'C:\Qt\Tools\OpenSSL\Win_x64\lib'))
executable('app', 'main.cpp', dependencies: [libcrypto_dep])
```

main.cpp contains only an empty main() function.

**Expected behavior**

I think this should setup just fine, but maybe I am misunderstanding the declare_dependency() documentation or the error message?!

**system parameters**
* Native
* Windows inside MSYS2
* Python: 3.10.6
* Meson: 0.63.1
* Ninja: 1.11.1



Discussion:
the output of `compiler.find_library()` is a dependency, not a target. so you want to replace `link_with` with `dependencies`, like so:
```meson
project('p', 'cpp')
compiler = meson.get_compiler('cpp')
libcrypto_dep = declare_dependency(
  include_directories: ['C:\Qt\Tools\OpenSSL\Win_x64\include'],
  dependencies: compiler.find_library('libcrypto', dirs: 'C:\Qt\Tools\OpenSSL\Win_x64\lib'))
executable('app', 'main.cpp', dependencies: [libcrypto_dep])
```
Thank you so much, that solved the problem nicely! :)

I guess, `link_with` can only be used for libraries built with `library()` within the current project?

I like to think I could have found that solution myself, but for the fact, that the error message came from line 6. So I was trying to fix something in the `executable()` call. Shouldn't the error message apply to line 5? Or maybe line 3 for the start of the `declare_dependency()` call? As far as I can see in the documentation, the types of `dependencies` is `list[dep]` whereas the type of `link_with` is `list[lib]`. Would it be possible to catch that error, where it's initiated, not where it is used?

Resolving patch:
diff --git a/mesonbuild/interpreter/type_checking.py b/mesonbuild/interpreter/type_checking.py
--- a/mesonbuild/interpreter/type_checking.py
+++ b/mesonbuild/interpreter/type_checking.py
@@ -409,7 +409,7 @@ def _output_validator(outputs: T.List[str]) -> T.Optional[str]:
     ContainerTypeInfo(list, (BothLibraries, SharedLibrary, StaticLibrary, CustomTarget, CustomTargetIndex, Jar, Executable, Dependency)),
     listify=True,
     default=[],
-    validator=lambda x: _link_with_error if isinstance(x, Dependency) else None,
+    validator=lambda x: _link_with_error if any(isinstance(i, Dependency) for i in x) else None,
 )
 
 def link_whole_validator(values: T.List[T.Union[StaticLibrary, CustomTarget, CustomTargetIndex, Dependency]]) -> T.Optional[str]:


Test patch:
Repository: mesonbuild/meson

Issue:
Feature request: meson test: Add --fail-fast or --stop-after-failures
When enough tests fail it often isn't useful to continue running - something fairly fundamental may be broken. Sometimes that may even mean that every test segfaults and produces core files. Especially for CI it'd be useful to abort meson test after a few failures.

I can probably prototype something, but I thought I'd collect some input first.


Discussion:
I'm actually surprised that we don't have this functionality yet. I'm not sure about the actual name, but it should definitely define the number of failures tolerated. Maybe `--stop-after-failures=5` and if the value is negative or zero then behave as currently.
> I'm not sure about the actual name

For the record, pytest has:
```
  -x, --exitfirst       exit instantly on first error or failed test.
  --maxfail=num         exit after first num failures or errors.
```
@anarazel PR more than welcome ;D
Of these `--maxfail` is my favourite. It is short and unambiguous.

Resolving patch:
diff --git a/mesonbuild/mtest.py b/mesonbuild/mtest.py
--- a/mesonbuild/mtest.py
+++ b/mesonbuild/mtest.py
@@ -94,6 +94,9 @@ def determine_worker_count() -> int:
     return num_workers
 
 def add_arguments(parser: argparse.ArgumentParser) -> None:
+    parser.add_argument('--maxfail', default=0, type=int,
+                        help='Number of failing tests before aborting the '
+                        'test run. (default: 0, to disable aborting on failure)')
     parser.add_argument('--repeat', default=1, dest='repeat', type=int,
                         help='Number of times to run the tests.')
     parser.add_argument('--no-rebuild', default=False, action='store_true',
@@ -1912,6 +1915,9 @@ async def run_test(test: SingleTestRunner) -> None:
                     return
                 res = await test.run(self)
                 self.process_test_result(res)
+                maxfail = self.options.maxfail
+                if maxfail and self.fail_count >= maxfail and res.res.is_bad():
+                    cancel_all_tests()
 
         def test_done(f: asyncio.Future) -> None:
             if not f.cancelled():


Test patch:
Repository: mesonbuild/meson

Issue:
docs: compiler.find_library: discourage lib prefix
I continue seeing it in the wild.


Discussion:
CI failure is very relevant.
I do not want you to use unicode in the docs, NACK to the first commit. :)
unicode is already used in the docs, for instance in the reference tables. No idea why we aren't just using `^1` there instead of superscript 1
Idk about that, but I do know that frivolously using ~~"typographically correct"~~ "annoying" quotes is... annoying. And it's also frivolous.

So anything that catches them and makes them error out is good in my book. Now if only we could remove them from the Unicode standard...

I think in general if your documentation relies on Unicode then you need to do some deep introspection on why you think you need it and whether that's in fact true. It probably isn't.
![image](https://user-images.githubusercontent.com/11936772/191818421-0511ee95-0871-4d8a-87b2-6939cc75c2a9.png)

I also hate unicode quotes, but I don't think automatic detection is a reason to forbid all of unicode. That is just a reason to force use of regular quotes

Resolving patch:
diff --git a/mesonbuild/compilers/mixins/clike.py b/mesonbuild/compilers/mixins/clike.py
--- a/mesonbuild/compilers/mixins/clike.py
+++ b/mesonbuild/compilers/mixins/clike.py
@@ -1158,6 +1158,8 @@ def _find_library_real(self, libname: str, env: 'Environment', extra_dirs: T.Lis
                 trial = self._get_file_from_list(env, trials)
                 if not trial:
                     continue
+                if libname.startswith('lib') and trial.name.startswith(libname):
+                    mlog.warning(f'find_library({libname!r}) starting in "lib" only works by accident and is not portable')
                 return [trial.as_posix()]
         return None
 


Test patch:
Repository: mesonbuild/meson

Issue:
JNI system dependency does not include FreeBSD
**Describe the bug**

When trying to use the JNI system dependency on FreeBSD, the following error appears: `Could not find a JDK platform include directory for your OS, please open an issue or provide a pull request.`

This is related to the following list being limited to only Windows, Linux, Darwin and Solaris: https://github.com/mesonbuild/meson/blob/master/mesonbuild/dependencies/dev.py#L606-L622

**To Reproduce**

As per code examination, merely trying to pull in the JNI system dependency should be a sufficient reproduction.

**Expected behavior**

Detecting the platform-dependent include directory on FreeBSD, whose name is  `freebsd`.

**system parameters**

* FreeBSD 13.1
* Python 3.9.14
* Meson 0.62.2


Discussion:
@tristan957 

Resolving patch:
diff --git a/mesonbuild/dependencies/dev.py b/mesonbuild/dependencies/dev.py
--- a/mesonbuild/dependencies/dev.py
+++ b/mesonbuild/dependencies/dev.py
@@ -607,7 +607,7 @@ def __machine_info_to_platform_include_dir(m: 'MachineInfo') -> T.Optional[str]:
         """Translates the machine information to the platform-dependent include directory
 
         When inspecting a JDK release tarball or $JAVA_HOME, inside the `include/` directory is a
-        platform dependent folder that must be on the target's include path in addition to the
+        platform-dependent directory that must be on the target's include path in addition to the
         parent `include/` directory.
         """
         if m.is_linux():
@@ -618,6 +618,14 @@ def __machine_info_to_platform_include_dir(m: 'MachineInfo') -> T.Optional[str]:
             return 'darwin'
         elif m.is_sunos():
             return 'solaris'
+        elif m.is_freebsd():
+            return 'freebsd'
+        elif m.is_netbsd():
+            return 'netbsd'
+        elif m.is_openbsd():
+            return 'openbsd'
+        elif m.is_dragonflybsd():
+            return 'dragonfly'
 
         return None
 


Test patch:
Repository: mesonbuild/meson

Issue:
override_options cpp_std does not work for vs backend
**Describe the bug**
override_options cpp_std is broken with the vs backend while it is ok with the ninja backend. It fails to override 

**To Reproduce**
main.cpp:
```c++
#include <any>

int main(int, char *[]) {
    std::any ret = 0;
    return std::any_cast<int>(ret);
}
```
meson.build :
```
project('vsbackend-override-options', 'cpp',
    version : '1.0',
    default_options : ['cpp_std=c++11',])

executable('override-options', 'main.cpp', override_options: 'cpp_std=c++17')
```

```shell
meson --vsenv --backend=vs2017 builddir
meson compile -C builddir
```

**Expected behavior**
Compiles with vs2017 (and others) backend.

**system parameters**
* plain native build
* Windows 10
* Python 3.10.3
* Meson 0.62.1



Discussion:
Came here to report this. Also happens for the `c_std` option.
Actually, it's worse than that, it turns out:

In C++ this causes MSVC to emit a harmess-but-annoying message, e.g.:
```
cl : command line  warning D9025: overriding '/std:c++20' with '/std:c++14'
```

But their C frontend handles this scenario differently, instead stopping at a hard error:
```
cl : command line  error D8016: '/std:c11' and '/std:c17' command-line options are incompatible
```

Meaning that testing scenarios like "test that my library's public API is consumable in all these versions of C" are now much more difficult/complicated since they require multiple invocations `meson setup`.

@eli-schwartz Any chance a fix for this can make 0.64.0?

Resolving patch:
diff --git a/mesonbuild/backend/vs2010backend.py b/mesonbuild/backend/vs2010backend.py
--- a/mesonbuild/backend/vs2010backend.py
+++ b/mesonbuild/backend/vs2010backend.py
@@ -1029,7 +1029,7 @@ def gen_vcxproj(self, target, ofname, guid):
                 file_args[l] += compilers.get_base_compile_args(
                     target.get_options(), comp)
                 file_args[l] += comp.get_option_compile_args(
-                    self.environment.coredata.options)
+                    target.get_options())
 
         # Add compile args added using add_project_arguments()
         for l, args in self.build.projects_args[target.for_machine].get(target.subproject, {}).items():


Test patch:
Repository: mesonbuild/meson

Issue:
Qt compile_resources stumbles on empty <file> element
**Describe the bug**

If a Qt resources file (.qrc) contains an empty <file> element, meson exits with an exception.

```
  ...
  File "/home/user/.local/lib/python3.10/site-packages/mesonbuild/modules/qt.py", line 241, in _parse_qrc_deps
    if os.path.isabs(resource_path):
  File "/usr/lib/python3.10/posixpath.py", line 62, in isabs
    s = os.fspath(s)
TypeError: expected str, bytes or os.PathLike object, not NoneType
```

**To Reproduce**

meson.build
```
project('bug', 'cpp')
qt = import('qt6')
source = qt.compile_resources(sources: 'resource.qrc')
executable('app', sources: source)
```

resource.qrc
```
<!DOCTYPE RCC>

<RCC version="1.0">
	<qresource>
		<file></file>
	</qresource>
</RCC>
```

**Expected behavior**

An error message about the empty <file> element. This probably doesn't happen for static resources files like this, but for dynamic resource files going through `configure_file()` with some paths to generated files. And if any of those configuration_data fields is not set, the <file> element remains empty. In that case, a two page stacktrace doesn't really help.

**system parameters**

* Native build.
* Ubuntu jammy
* Python: 3.10.6
* Meson: 0.64.0
* Ninja: 1.10.1



Discussion:

Resolving patch:
diff --git a/mesonbuild/modules/qt.py b/mesonbuild/modules/qt.py
--- a/mesonbuild/modules/qt.py
+++ b/mesonbuild/modules/qt.py
@@ -198,12 +198,11 @@ def _qrc_nodes(state: 'ModuleState', rcc_file: 'FileOrString') -> T.Tuple[str, T
         abspath: str
         if isinstance(rcc_file, str):
             abspath = os.path.join(state.environment.source_dir, state.subdir, rcc_file)
-            rcc_dirname = os.path.dirname(abspath)
         else:
             abspath = rcc_file.absolute_path(state.environment.source_dir, state.environment.build_dir)
-            rcc_dirname = os.path.dirname(abspath)
+        rcc_dirname = os.path.dirname(abspath)
 
-        # FIXME: what error are we actually trying to check here?
+        # FIXME: what error are we actually trying to check here? (probably parse errors?)
         try:
             tree = ET.parse(abspath)
             root = tree.getroot()
@@ -212,10 +211,14 @@ def _qrc_nodes(state: 'ModuleState', rcc_file: 'FileOrString') -> T.Tuple[str, T
                 if child.tag != 'file':
                     mlog.warning("malformed rcc file: ", os.path.join(state.subdir, str(rcc_file)))
                     break
+                elif child.text is None:
+                    raise MesonException(f'<file> element without a path in {os.path.join(state.subdir, str(rcc_file))}')
                 else:
                     result.append(child.text)
 
             return rcc_dirname, result
+        except MesonException:
+            raise
         except Exception:
             raise MesonException(f'Unable to parse resource file {abspath}')
 


Test patch:
Repository: mesonbuild/meson

Issue:
NASM language fails when threads dependency added to library
**Describe the bug**
I want to play around with the new nasm language so I've modified one of my projects that uses nasm in combination with a meson generator to compile .asm files. Instead of using the generator I added the .asm files as sources to the static_library object that is being build. Unfortunately nasm borks because meson adds an -pthread argument due to the library having a threads dependency added. 

**To Reproduce**
Toy attached
[asm_pthread_toy.tar.gz](https://github.com/mesonbuild/meson/files/10001810/asm_pthread_toy.tar.gz)

**Expected behavior**
Some arguments would need to be sanitized, in this example: nasm should be run without -pthread





Discussion:
Some extra info: for nasm according to it's man -p is intended to signal files that are to be pre-included. I'm fairly certain it would be best to sanitize away any arguments starting with -p that are not explicitly added by the user.

Resolving patch:
diff --git a/mesonbuild/compilers/asm.py b/mesonbuild/compilers/asm.py
--- a/mesonbuild/compilers/asm.py
+++ b/mesonbuild/compilers/asm.py
@@ -47,6 +47,14 @@ def get_werror_args(self) -> T.List[str]:
     def get_output_args(self, outputname: str) -> T.List[str]:
         return ['-o', outputname]
 
+    def unix_args_to_native(self, args: T.List[str]) -> T.List[str]:
+        outargs = []
+        for arg in args:
+            if arg == '-pthread':
+                continue
+            outargs.append(arg)
+        return outargs
+
     def get_optimization_args(self, optimization_level: str) -> T.List[str]:
         return nasm_optimization_args[optimization_level]
 


Test patch:
diff --git a/test cases/nasm/2 asm language/meson.build b/test cases/nasm/2 asm language/meson.build
--- a/test cases/nasm/2 asm language/meson.build	
+++ b/test cases/nasm/2 asm language/meson.build	
@@ -43,3 +43,15 @@ exe = executable('hello', 'hello.asm',
   link_args: link_args,
 )
 test('hello', exe)
+
+#Test whether pthread dependency gets filtered out
+threads = dependency('threads')
+
+exe2 = executable('hello_w_threads', 'hello.asm',
+  config_file,
+  nasm_args: '-DFOO',
+  link_args: link_args,
+  dependencies: [threads]
+)
+
+test('hello_w_threads', exe2)
Repository: mesonbuild/meson

Issue:
D: -D flag gets ignored with ldc2
**Describe the bug**

When building with ldc2, `-D`, `-Dd`, or `-Df` flags are not parsed (these flags are related to documentation). It seems to be introduced by [this PR](https://github.com/mesonbuild/meson/commit/efea48788ab29c45a83f6a50d39fd7d0689f5f0e) that ignores every `-D*` flag.

**To Reproduce**

Use ldc2 compiler with `-D` as global argument.

**Expected behavior**

Documentation is generated as well as binaries.

**system parameters**
* `python3 --version` --> ` Python 3.9.2`
* what `meson --version` --> `0.62.99`




Discussion:

Resolving patch:
diff --git a/mesonbuild/compilers/d.py b/mesonbuild/compilers/d.py
--- a/mesonbuild/compilers/d.py
+++ b/mesonbuild/compilers/d.py
@@ -314,7 +314,9 @@ def _translate_args_to_nongnu(cls, args: T.List[str], info: MachineInfo, link_id
                 continue
             if arg.startswith('-fstack-protector'):
                 continue
-            if arg.startswith('-D'):
+            if arg.startswith('-D') and not (arg == '-D' or arg.startswith(('-Dd', '-Df'))):
+                # ignore all '-D*' flags (like '-D_THREAD_SAFE')
+                # unless they are related to documentation
                 continue
             if arg.startswith('-Wl,'):
                 # Translate linker arguments here.


Test patch:
Repository: mesonbuild/meson

Issue:
dependency not_found_message prints multiple times
```
Run-time dependency gpgme found: NO (tried pkgconfig and config-tool)
Message: gpgme >=1.3.0 is needed for GPG signature support
Message: gpgme >=1.3.0 is needed for GPG signature support
```

I can get it to print only once, if I add `methods:` to the dependency() call, it seems to be printing once per method it tries.

Even if it doesn't try them due to being disabled, in this case it ignores `methods:`:

```
Dependency gpgme skipped: feature gpgme disabled
Message: gpgme >=1.3.0 is needed for GPG signature support
Message: gpgme >=1.3.0 is needed for GPG signature support
```


Discussion:
Also I realize now it would be nice if this were elevated to error() not message() when it is required but not found.

Resolving patch:
diff --git a/mesonbuild/interpreter/interpreter.py b/mesonbuild/interpreter/interpreter.py
--- a/mesonbuild/interpreter/interpreter.py
+++ b/mesonbuild/interpreter/interpreter.py
@@ -1706,7 +1706,6 @@ def func_dependency(self, node: mparser.BaseNode, args: T.Tuple[T.List[str]], kw
         assert isinstance(d, Dependency)
         if not d.found() and not_found_message:
             self.message_impl([not_found_message])
-            self.message_impl([not_found_message])
         # Ensure the correct include type
         if 'include_type' in kwargs:
             wanted = kwargs['include_type']


Test patch:
Repository: mesonbuild/meson

Issue:
meson setup fails to report relevant pkgconfig error
**Describe the bug**
When dependency `d1` is found by pkgconfig but its transitive dependency `d2` isn't, meson displays output as if `d1` is missing with no mention to `d2` anywhere.

**To Reproduce**

Below example is for building `fontconfig` (where `d1` is `freetype2` and `d2` is `zlib`)

Setup command `PKG_CONFIG_PATH=<freetype_path> meson setup --wrap-mode=nofallback <fontconfig_src>` outputs:

```
[...]
Run-time dependency freetype2 found: NO (tried pkgconfig)
[...]
../fontconfig-2.14.1/meson.build:32:2: ERROR: Dependency 'freetype' is required but not found.

A full log can be found at meson-logs/meson-log.txt
```

and relevant bits from `meson-log.txt`:

```
[...]
Called `/usr/bin/pkg-config --modversion freetype2` -> 1

Run-time dependency freetype2 found: NO (tried pkgconfig)
[...]
../fontconfig-2.14.1/meson.build:32:2: ERROR: Dependency 'freetype' is required but not found.
```

Now if you run the command printed on `meson-log.txt` you will see the actual error:

```
$ PKG_CONFIG_PATH=<freetype_path> /usr/bin/pkg-config --modversion freetype2
Package zlib was not found in the pkg-config search path.
Perhaps you should add the directory containing `zlib.pc'
to the PKG_CONFIG_PATH environment variable
Package 'zlib', required by 'freetype2', not found
```


**Expected behavior**
Output should include failed pkg-config command output. Actual missing package in this example is `zlib` but it is not present in either `meson setup` output or `meson-log.txt`. Debugging this requires recreating the build environment and executing a pkg-config command just to see an error message that meson could have displayed instead of omitting.

**system parameters**
`meson --version` is `0.64.0` (latest)



Discussion:
Turns out the issue depends on pkg-config version, I've sent a PR which documents the issue on the test file

Resolving patch:
diff --git a/mesonbuild/dependencies/pkgconfig.py b/mesonbuild/dependencies/pkgconfig.py
--- a/mesonbuild/dependencies/pkgconfig.py
+++ b/mesonbuild/dependencies/pkgconfig.py
@@ -124,7 +124,11 @@ def _call_pkgbin_real(self, args: T.List[str], env: T.Dict[str, str]) -> T.Tuple
         p, out, err = Popen_safe(cmd, env=env)
         rc, out, err = p.returncode, out.strip(), err.strip()
         call = ' '.join(cmd)
-        mlog.debug(f"Called `{call}` -> {rc}\n{out}")
+        mlog.debug(f"Called `{call}` -> {rc}")
+        if out:
+            mlog.debug(f'stdout:\n{out}\n-----------')
+        if err:
+            mlog.debug(f'stderr:\n{err}\n-----------')
         return rc, out, err
 
     @staticmethod


Test patch:
Repository: mesonbuild/meson

Issue:
meson init --name xyz --build doesn't work on Windows - doesn't follow its own advice
Pardon the screenshot-as-a-bug-report, I was working on this in a VM as I don't generally use Windows.

![image](https://user-images.githubusercontent.com/38919842/210435090-4612cfdc-305a-4fda-9d06-07e5d644ded0.png)

It seems when passing the --build flag to meson init, it runs ninja directly rather than the meson compile wrapper, which leads to a failed build as it does not automatically activate the visual studio environment (which is an *excellent* feature, by the way!).

Running meson compile -C build works fine, as shown

This is on Windows 10, meson 0.64.1, installed with the MSI installer. Native build.


Discussion:

Resolving patch:
diff --git a/mesonbuild/minit.py b/mesonbuild/minit.py
--- a/mesonbuild/minit.py
+++ b/mesonbuild/minit.py
@@ -22,7 +22,7 @@
 import os
 import re
 from glob import glob
-from mesonbuild import mesonlib
+from mesonbuild import build, mesonlib, mlog
 from mesonbuild.coredata import FORBIDDEN_TARGET_NAMES
 from mesonbuild.environment import detect_ninja
 from mesonbuild.templates.samplefactory import sameple_generator
@@ -180,10 +180,16 @@ def run(options: 'argparse.Namespace') -> int:
             print('Build directory already exists, deleting it.')
             shutil.rmtree(options.builddir)
         print('Building...')
-        cmd = mesonlib.get_meson_command() + [options.builddir]
+        cmd = mesonlib.get_meson_command() + ['setup', options.builddir]
         ret = subprocess.run(cmd)
         if ret.returncode:
             raise SystemExit
+
+        b = build.load(options.builddir)
+        vsenv_active = mesonlib.setup_vsenv(b.need_vsenv)
+        if vsenv_active:
+            mlog.log(mlog.green('INFO:'), 'automatically activated MSVC compiler environment')
+
         cmd = detect_ninja() + ['-C', options.builddir]
         ret = subprocess.run(cmd)
         if ret.returncode:


Test patch: