aboutsummaryrefslogtreecommitdiff
path: root/mesonbuild/compilers/c.py
blob: 1bc9e849981f913f96fd41c0f142c624747efee7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
# 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
import typing as T

from .. import coredata
from ..mesonlib import MachineChoice, MesonException, mlog, version_compare
from ..linkers import LinkerEnvVarsMixin
from .c_function_attributes import C_FUNC_ATTRIBUTES
from .mixins.clike import CLikeCompiler
from .mixins.ccrx import CcrxCompiler
from .mixins.xc16 import Xc16Compiler
from .mixins.c2000 import C2000Compiler
from .mixins.arm import ArmCompiler, ArmclangCompiler
from .mixins.visualstudio import MSVCCompiler, ClangClCompiler
from .mixins.gnu import GnuCompiler
from .mixins.intel import IntelGnuLikeCompiler, IntelVisualStudioLikeCompiler
from .mixins.clang import ClangCompiler
from .mixins.elbrus import ElbrusCompiler
from .mixins.pgi import PGICompiler
from .mixins.emscripten import EmscriptenMixin
from .compilers import (
    gnu_winlibs,
    msvc_winlibs,
    Compiler,
)

if T.TYPE_CHECKING:
    from ..envconfig import MachineInfo


class CCompiler(CLikeCompiler, Compiler):

    @staticmethod
    def attribute_check_func(name):
        try:
            return C_FUNC_ATTRIBUTES[name]
        except KeyError:
            raise MesonException('Unknown function attribute "{}"'.format(name))

    language = 'c'

    def __init__(self, exelist, version, for_machine: MachineChoice, is_cross: bool,
                 info: 'MachineInfo', exe_wrapper: T.Optional[str] = None, **kwargs):
        # If a child ObjC or CPP class has already set it, don't set it ourselves
        Compiler.__init__(self, exelist, version, for_machine, info, **kwargs)
        CLikeCompiler.__init__(self, is_cross, exe_wrapper)

    def get_no_stdinc_args(self):
        return ['-nostdinc']

    def sanity_check(self, work_dir, environment):
        code = 'int main(void) { int class=0; return class; }\n'
        return self.sanity_check_impl(work_dir, environment, 'sanitycheckc.c', code)

    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(void) {{
            /* If it's not defined as a macro, try to use as a symbol */
            #ifndef {symbol}
                {symbol};
            #endif
            return 0;
        }}'''
        return self.compiles(t.format(**fargs), env, extra_args=extra_args,
                             dependencies=dependencies)


class ClangCCompiler(ClangCompiler, CCompiler):

    _C17_VERSION = '>=6.0.0'
    _C18_VERSION = '>=8.0.0'

    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross, info, exe_wrapper, **kwargs)
        ClangCompiler.__init__(self)
        default_warn_args = ['-Wall', '-Winvalid-pch']
        self.warn_args = {'0': [],
                          '1': default_warn_args,
                          '2': default_warn_args + ['-Wextra'],
                          '3': default_warn_args + ['-Wextra', '-Wpedantic']}

    def get_options(self):
        opts = CCompiler.get_options(self)
        c_stds = ['c89', 'c99', 'c11']
        g_stds = ['gnu89', 'gnu99', 'gnu11']
        # https://releases.llvm.org/6.0.0/tools/clang/docs/ReleaseNotes.html
        # https://en.wikipedia.org/wiki/Xcode#Latest_versions
        if version_compare(self.version, self._C17_VERSION):
            c_stds += ['c17']
            g_stds += ['gnu17']
        if version_compare(self.version, self._C18_VERSION):
            c_stds += ['c18']
            g_stds += ['gnu18']
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none'] + c_stds + g_stds,
                'none',
            ),
        })
        if self.info.is_windows() or self.info.is_cygwin():
            opts.update({
                'winlibs': coredata.UserArrayOption(
                    'Standard Win libraries to link against',
                    gnu_winlibs,
                ),
            })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value != 'none':
            args.append('-std=' + std.value)
        return args

    def get_option_link_args(self, options):
        if self.info.is_windows() or self.info.is_cygwin():
            return options['winlibs'].value[:]
        return []


class AppleClangCCompiler(ClangCCompiler):

    """Handle the differences between Apple Clang and Vanilla Clang.

    Right now this just handles the differences between the versions that new
    C standards were added.
    """

    _C17_VERSION = '>=10.0.0'
    _C18_VERSION = '>=11.0.0'


class EmscriptenCCompiler(EmscriptenMixin, LinkerEnvVarsMixin, ClangCCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross: bool, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        if not is_cross:
            raise MesonException('Emscripten compiler can only be used for cross compilation.')
        ClangCCompiler.__init__(self, exelist=exelist, version=version,
                                for_machine=for_machine, is_cross=is_cross,
                                info=info, exe_wrapper=exe_wrapper, **kwargs)
        self.id = 'emscripten'


class ArmclangCCompiler(ArmclangCompiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        ArmclangCompiler.__init__(self)
        default_warn_args = ['-Wall', '-Winvalid-pch']
        self.warn_args = {'0': [],
                          '1': default_warn_args,
                          '2': default_warn_args + ['-Wextra'],
                          '3': default_warn_args + ['-Wextra', '-Wpedantic']}

    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none', 'c90', 'c99', 'c11', 'gnu90', 'gnu99', 'gnu11'],
                'none',
            ),
        })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['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, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None,
                 defines=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        GnuCompiler.__init__(self, defines)
        default_warn_args = ['-Wall', '-Winvalid-pch']
        self.warn_args = {'0': [],
                          '1': default_warn_args,
                          '2': default_warn_args + ['-Wextra'],
                          '3': default_warn_args + ['-Wextra', '-Wpedantic']}

    def get_options(self):
        opts = CCompiler.get_options(self)
        c_stds = ['c89', 'c99', 'c11']
        g_stds = ['gnu89', 'gnu99', 'gnu11']
        v = '>=8.0.0'
        if version_compare(self.version, v):
            c_stds += ['c17', 'c18']
            g_stds += ['gnu17', 'gnu18']
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none'] + c_stds + g_stds,
                'none',
            ),
        })
        if self.info.is_windows() or self.info.is_cygwin():
            opts.update({
                'winlibs': coredata.UserArrayOption(
                    'Standard Win libraries to link against',
                    gnu_winlibs,
                ),
            })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value != 'none':
            args.append('-std=' + std.value)
        return args

    def get_option_link_args(self, options):
        if self.info.is_windows() or self.info.is_cygwin():
            return options['winlibs'].value[:]
        return []

    def get_pch_use_args(self, pch_dir, header):
        return ['-fpch-preprocess', '-include', os.path.basename(header)]


class PGICCompiler(PGICompiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        PGICompiler.__init__(self)


class ElbrusCCompiler(GnuCCompiler, ElbrusCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None,
                 defines=None, **kwargs):
        GnuCCompiler.__init__(self, exelist, version, for_machine, is_cross,
                              info, exe_wrapper, defines, **kwargs)
        ElbrusCompiler.__init__(self)

    # It does support some various ISO standards and c/gnu 90, 9x, 1x in addition to those which GNU CC supports.
    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                [
                    'none', 'c89', 'c90', 'c9x', 'c99', 'c1x', 'c11',
                    'gnu89', 'gnu90', 'gnu9x', 'gnu99', 'gnu1x', 'gnu11',
                    'iso9899:2011', 'iso9899:1990', 'iso9899:199409', 'iso9899:1999',
                ],
                'none',
            ),
        })
        return opts

    # Elbrus C compiler does not have lchmod, but there is only linker warning, not compiler error.
    # So we should explicitly fail at this case.
    def has_function(self, funcname, prefix, env, *, extra_args=None, dependencies=None):
        if funcname == 'lchmod':
            return False, False
        else:
            return super().has_function(funcname, prefix, env,
                                        extra_args=extra_args,
                                        dependencies=dependencies)


class IntelCCompiler(IntelGnuLikeCompiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        IntelGnuLikeCompiler.__init__(self)
        self.lang_header = 'c-header'
        default_warn_args = ['-Wall', '-w3', '-diag-disable:remark']
        self.warn_args = {'0': [],
                          '1': default_warn_args,
                          '2': default_warn_args + ['-Wextra'],
                          '3': default_warn_args + ['-Wextra']}

    def get_options(self):
        opts = CCompiler.get_options(self)
        c_stds = ['c89', 'c99']
        g_stds = ['gnu89', 'gnu99']
        if version_compare(self.version, '>=16.0.0'):
            c_stds += ['c11']
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none'] + c_stds + g_stds,
                'none',
            ),
        })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value != 'none':
            args.append('-std=' + std.value)
        return args


class VisualStudioLikeCCompilerMixin:

    """Shared methods that apply to MSVC-like C compilers."""

    def get_options(self):
        opts = super().get_options()
        opts.update({
            'winlibs': coredata.UserArrayOption(
                'Windows libs to link against.',
                msvc_winlibs,
            ),
        })
        return opts

    def get_option_link_args(self, options):
        return options['winlibs'].value[:]


class VisualStudioCCompiler(MSVCCompiler, VisualStudioLikeCCompilerMixin, CCompiler):

    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrap, target: str,
                 **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrap, **kwargs)
        MSVCCompiler.__init__(self, target)


class ClangClCCompiler(ClangClCompiler, VisualStudioLikeCCompilerMixin, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrap, target, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrap, **kwargs)
        ClangClCompiler.__init__(self, target)


class IntelClCCompiler(IntelVisualStudioLikeCompiler, VisualStudioLikeCCompilerMixin, CCompiler):

    """Intel "ICL" compiler abstraction."""

    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrap, target, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrap, **kwargs)
        IntelVisualStudioLikeCompiler.__init__(self, target)

    def get_options(self):
        opts = super().get_options()
        c_stds = ['none', 'c89', 'c99', 'c11']
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                c_stds,
                'none',
            ),
        })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value == 'c89':
            mlog.warning("ICL doesn't explicitly implement c89, setting the standard to 'none', which is close.", once=True)
        elif std.value != 'none':
            args.append('/Qstd:' + std.value)
        return args


class ArmCCompiler(ArmCompiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        ArmCompiler.__init__(self)

    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none', 'c90', 'c99'],
                'none',
            ),
        })
        return opts

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value != 'none':
            args.append('--' + std.value)
        return args


class CcrxCCompiler(CcrxCompiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        CcrxCompiler.__init__(self)

    # Override CCompiler.get_always_args
    def get_always_args(self):
        return ['-nologo']

    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({
            'std': coredata.UserComboOption(
                'C language standard to use',
                ['none', 'c89', 'c99'],
                'none',
            ),
        })
        return opts

    def get_no_stdinc_args(self):
        return []

    def get_option_compile_args(self, options):
        args = []
        std = options['std']
        if std.value == 'c89':
            args.append('-lang=c')
        elif std.value == 'c99':
            args.append('-lang=c99')
        return args

    def get_compile_only_args(self):
        return []

    def get_no_optimization_args(self):
        return ['-optimize=0']

    def get_output_args(self, target):
        return ['-output=obj=%s' % target]

    def get_werror_args(self):
        return ['-change_message=error']

    def get_include_args(self, path, is_system):
        if path == '':
            path = '.'
        return ['-include=' + path]


class Xc16CCompiler(Xc16Compiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        Xc16Compiler.__init__(self)

    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({'c_std': coredata.UserComboOption('C language standard to use',
                                                       ['none', 'c89', 'c99', 'gnu89', 'gnu99'],
                                                       'none')})
        return opts

    def get_no_stdinc_args(self):
        return []

    def get_option_compile_args(self, options):
        args = []
        std = options['c_std']
        if std.value != 'none':
            args.append('-ansi')
            args.append('-std=' + std.value)
        return args

    def get_compile_only_args(self):
        return []

    def get_no_optimization_args(self):
        return ['-O0']

    def get_output_args(self, target):
        return ['-o%s' % target]

    def get_werror_args(self):
        return ['-change_message=error']

    def get_include_args(self, path, is_system):
        if path == '':
            path = '.'
        return ['-I' + path]


class C2000CCompiler(C2000Compiler, CCompiler):
    def __init__(self, exelist, version, for_machine: MachineChoice,
                 is_cross, info: 'MachineInfo', exe_wrapper=None, **kwargs):
        CCompiler.__init__(self, exelist, version, for_machine, is_cross,
                           info, exe_wrapper, **kwargs)
        C2000Compiler.__init__(self)

    # Override CCompiler.get_always_args
    def get_always_args(self):
        return []

    def get_options(self):
        opts = CCompiler.get_options(self)
        opts.update({'c_std': coredata.UserComboOption('C language standard to use',
                                                       ['none', 'c89', 'c99', 'c11'],
                                                       'none')})
        return opts

    def get_no_stdinc_args(self):
        return []

    def get_option_compile_args(self, options):
        args = []
        std = options['c_std']
        if std.value != 'none':
            args.append('--' + std.value)
        return args

    def get_compile_only_args(self):
        return []

    def get_no_optimization_args(self):
        return ['-Ooff']

    def get_output_args(self, target):
        return ['--output_file=%s' % target]

    def get_werror_args(self):
        return ['-change_message=error']

    def get_include_args(self, path, is_system):
        if path == '':
            path = '.'
        return ['--include_path=' + path]
span class="hl opt">('---rwx---'), stat.S_IRWXG) self.assertEqual(modefunc('------rwx'), stat.S_IRWXO) # We could keep listing combinations exhaustively but that seems # tedious and pointless. Just test a few more. self.assertEqual(modefunc('rwxr-xr-x'), stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) self.assertEqual(modefunc('rw-r--r--'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) self.assertEqual(modefunc('rwsr-x---'), stat.S_IRWXU | stat.S_ISUID | stat.S_IRGRP | stat.S_IXGRP) def test_compiler_args_class_none_flush(self): cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, False, mock.Mock()) a = cc.compiler_args(['-I.']) #first we are checking if the tree construction deduplicates the correct -I argument a += ['-I..'] a += ['-I./tests/'] a += ['-I./tests2/'] #think this here as assertion, we cannot apply it, otherwise the CompilerArgs would already flush the changes: # assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..', '-I.']) a += ['-I.'] a += ['-I.', '-I./tests/'] self.assertEqual(a, ['-I.', '-I./tests/', '-I./tests2/', '-I..']) #then we are checking that when CompilerArgs already have a build container list, that the deduplication is taking the correct one a += ['-I.', '-I./tests2/'] self.assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..']) def test_compiler_args_class_d(self): d = DmdDCompiler([], 'fake', MachineChoice.HOST, 'info', 'arch') # check include order is kept when deduplicating a = d.compiler_args(['-Ifirst', '-Isecond', '-Ithird']) a += ['-Ifirst'] self.assertEqual(a, ['-Ifirst', '-Isecond', '-Ithird']) def test_compiler_args_class_clike(self): cc = ClangCCompiler([], [], 'fake', MachineChoice.HOST, False, mock.Mock()) # Test that empty initialization works a = cc.compiler_args() self.assertEqual(a, []) # Test that list initialization works a = cc.compiler_args(['-I.', '-I..']) self.assertEqual(a, ['-I.', '-I..']) # Test that there is no de-dup on initialization self.assertEqual(cc.compiler_args(['-I.', '-I.']), ['-I.', '-I.']) ## Test that appending works a.append('-I..') self.assertEqual(a, ['-I..', '-I.']) a.append('-O3') self.assertEqual(a, ['-I..', '-I.', '-O3']) ## Test that in-place addition works a += ['-O2', '-O2'] self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2', '-O2']) # Test that removal works a.remove('-O2') self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2']) # Test that de-dup happens on addition a += ['-Ifoo', '-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) # .extend() is just +=, so we don't test it ## Test that addition works # Test that adding a list with just one old arg works and yields the same array a = a + ['-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) # Test that adding a list with one arg new and one old works a = a + ['-Ifoo', '-Ibaz'] self.assertEqual(a, ['-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2']) # Test that adding args that must be prepended and appended works a = a + ['-Ibar', '-Wall'] self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) ## Test that reflected addition works # Test that adding to a list with just one old arg works and yields the same array a = ['-Ifoo'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) # Test that adding to a list with just one new arg that is not pre-pended works a = ['-Werror'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Werror', '-O3', '-O2', '-Wall']) # Test that adding to a list with two new args preserves the order a = ['-Ldir', '-Lbah'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) # Test that adding to a list with old args does nothing a = ['-Ibar', '-Ibaz', '-Ifoo'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) ## Test that adding libraries works l = cc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) # Adding a library and a libpath appends both correctly l += ['-Lbardir', '-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) # Adding the same library again does nothing l += ['-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) ## Test that 'direct' append and extend works l = cc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) # Direct-adding a library and a libpath appends both correctly l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar']) # Direct-adding the same library again still adds it l.append_direct('-lbar') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar']) # Direct-adding with absolute path deduplicates l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) # Adding libbaz again does nothing l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) def test_compiler_args_class_visualstudio(self): linker = linkers.MSVCDynamicLinker(MachineChoice.HOST, []) # Version just needs to be > 19.0.0 cc = VisualStudioCPPCompiler([], [], '20.00', MachineChoice.HOST, False, mock.Mock(), 'x64', linker=linker) a = cc.compiler_args(cc.get_always_args()) self.assertEqual(a.to_native(copy=True), ['/nologo', '/showIncludes', '/utf-8', '/Zc:__cplusplus']) # Ensure /source-charset: removes /utf-8 a.append('/source-charset:utf-8') self.assertEqual(a.to_native(copy=True), ['/nologo', '/showIncludes', '/Zc:__cplusplus', '/source-charset:utf-8']) # Ensure /execution-charset: removes /utf-8 a = cc.compiler_args(cc.get_always_args() + ['/execution-charset:utf-8']) self.assertEqual(a.to_native(copy=True), ['/nologo', '/showIncludes', '/Zc:__cplusplus', '/execution-charset:utf-8']) # Ensure /validate-charset- removes /utf-8 a = cc.compiler_args(cc.get_always_args() + ['/validate-charset-']) self.assertEqual(a.to_native(copy=True), ['/nologo', '/showIncludes', '/Zc:__cplusplus', '/validate-charset-']) def test_compiler_args_class_gnuld(self): ## Test --start/end-group linker = linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = GnuCCompiler([], [], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) ## Ensure that the fake compiler is never called by overriding the relevant function gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include'] ## Test that 'direct' append and extend works l = gcc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo']) # Direct-adding a library and a libpath appends both correctly l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-Wl,--end-group']) # Direct-adding the same library again still adds it l.append_direct('-lbar') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '-Wl,--end-group']) # Direct-adding with absolute path deduplicates l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) # Adding libbaz again does nothing l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) # Adding a non-library argument doesn't include it in the group l += ['-Lfoo', '-Wl,--export-dynamic'] self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group', '-Wl,--export-dynamic']) # -Wl,-lfoo is detected as a library and gets added to the group l.append('-Wl,-ldl') self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--export-dynamic', '-Wl,-ldl', '-Wl,--end-group']) def test_compiler_args_remove_system(self): ## Test --start/end-group linker = linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = GnuCCompiler([], [], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) ## Ensure that the fake compiler is never called by overriding the relevant function gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include'] ## Test that 'direct' append and extend works l = gcc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo']) ## Test that to_native removes all system includes l += ['-isystem/usr/include', '-isystem=/usr/share/include', '-DSOMETHING_IMPORTANT=1', '-isystem', '/usr/local/include'] self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-lfoo', '-DSOMETHING_IMPORTANT=1']) def test_string_templates_substitution(self): dictfunc = mesonbuild.mesonlib.get_filenames_templates_dict substfunc = mesonbuild.mesonlib.substitute_values ME = mesonbuild.mesonlib.MesonException # Identity self.assertEqual(dictfunc([], []), {}) # One input, no outputs inputs = ['bar/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + [d['@PLAINNAME@'] + '.ok'] + cmd[2:]) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) # One input, one output inputs = ['bar/foo.c.in'] outputs = ['out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': '.'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', '@OUTPUT@', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + outputs + cmd[2:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', '@OUTPUT0@'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', d['@PLAINNAME@'] + '.ok'] + outputs) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) # One input, one output with a subdir outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME0@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Two inputs, no outputs inputs = ['bar/foo.c.in', 'baz/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[1:]) cmd = ['@INPUT0@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) cmd = ['@INPUT0@', '@INPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[2:]) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Too many inputs cmd = ['@PLAINNAME@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@BASENAME@'] self.assertRaises(ME, substfunc, cmd, d) # No outputs cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT0@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTDIR@'] self.assertRaises(ME, substfunc, cmd, d) # Two inputs, one output outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out'] + cmd[1:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough outputs cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Two inputs, two outputs outputs = ['dir/out.c', 'dir/out2.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@PLAINNAME0@': 'foo.c.in', '@PLAINNAME1@': 'foo.c.in', '@BASENAME0@': 'foo.c', '@BASENAME1@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTPUT1@': outputs[1], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT0@', '@OUTPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[2:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', '@OUTDIR@'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir']) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough outputs cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Many outputs, can't use @OUTPUT@ like this cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) def test_needs_exe_wrapper_override(self): config = ConfigParser() config['binaries'] = { 'c': '\'/usr/bin/gcc\'', } config['host_machine'] = { 'system': '\'linux\'', 'cpu_family': '\'arm\'', 'cpu': '\'armv7\'', 'endian': '\'little\'', } # Can not be used as context manager because we need to # open it a second time and this is not possible on # Windows. configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8') configfilename = configfile.name config.write(configfile) configfile.flush() configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) detected_value = env.need_exe_wrapper() os.unlink(configfilename) desired_value = not detected_value config['properties'] = { 'needs_exe_wrapper': 'true' if desired_value else 'false' } configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8') configfilename = configfile.name config.write(configfile) configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) forced_value = env.need_exe_wrapper() os.unlink(configfilename) self.assertEqual(forced_value, desired_value) def test_listify(self): listify = mesonbuild.mesonlib.listify # Test sanity self.assertEqual([1], listify(1)) self.assertEqual([], listify([])) self.assertEqual([1], listify([1])) # Test flattening self.assertEqual([1, 2, 3], listify([1, [2, 3]])) self.assertEqual([1, 2, 3], listify([1, [2, [3]]])) self.assertEqual([1, [2, [3]]], listify([1, [2, [3]]], flatten=False)) # Test flattening and unholdering class TestHeldObj(mesonbuild.mesonlib.HoldableObject): def __init__(self, val: int) -> None: self._val = val class MockInterpreter: def __init__(self) -> None: self.subproject = '' self.environment = None heldObj1 = TestHeldObj(1) holder1 = ObjectHolder(heldObj1, MockInterpreter()) self.assertEqual([holder1], listify(holder1)) self.assertEqual([holder1], listify([holder1])) self.assertEqual([holder1, 2], listify([holder1, 2])) self.assertEqual([holder1, 2, 3], listify([holder1, 2, [3]])) def test_extract_as_list(self): extract = mesonbuild.mesonlib.extract_as_list # Test sanity kwargs = {'sources': [1, 2, 3]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) self.assertEqual(kwargs, {'sources': [1, 2, 3]}) self.assertEqual([1, 2, 3], extract(kwargs, 'sources', pop=True)) self.assertEqual(kwargs, {}) class TestHeldObj(mesonbuild.mesonlib.HoldableObject): pass class MockInterpreter: def __init__(self) -> None: self.subproject = '' self.environment = None heldObj = TestHeldObj() # Test unholding holder3 = ObjectHolder(heldObj, MockInterpreter()) kwargs = {'sources': [1, 2, holder3]} self.assertEqual(kwargs, {'sources': [1, 2, holder3]}) # flatten nested lists kwargs = {'sources': [1, [2, [3]]]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) def _test_all_naming(self, cc, env, patterns, platform): shr = patterns[platform]['shared'] stc = patterns[platform]['static'] shrstc = shr + tuple(x for x in stc if x not in shr) stcshr = stc + tuple(x for x in shr if x not in stc) p = cc.get_library_naming(env, LibType.SHARED) self.assertEqual(p, shr) p = cc.get_library_naming(env, LibType.STATIC) self.assertEqual(p, stc) p = cc.get_library_naming(env, LibType.PREFER_STATIC) self.assertEqual(p, stcshr) p = cc.get_library_naming(env, LibType.PREFER_SHARED) self.assertEqual(p, shrstc) # Test find library by mocking up openbsd if platform != 'openbsd': return with tempfile.TemporaryDirectory() as tmpdir: for i in ['libfoo.so.6.0', 'libfoo.so.5.0', 'libfoo.so.54.0', 'libfoo.so.66a.0b', 'libfoo.so.70.0.so.1', 'libbar.so.7.10', 'libbar.so.7.9', 'libbar.so.7.9.3']: libpath = Path(tmpdir) / i libpath.write_text('', encoding='utf-8') found = cc._find_library_real('foo', env, [tmpdir], '', LibType.PREFER_SHARED, lib_prefix_warning=True) self.assertEqual(os.path.basename(found[0]), 'libfoo.so.54.0') found = cc._find_library_real('bar', env, [tmpdir], '', LibType.PREFER_SHARED, lib_prefix_warning=True) self.assertEqual(os.path.basename(found[0]), 'libbar.so.7.10') def test_find_library_patterns(self): ''' Unit test for the library search patterns used by find_library() ''' unix_static = ('lib{}.a', '{}.a') msvc_static = ('lib{}.a', 'lib{}.lib', '{}.a', '{}.lib') # This is the priority list of pattern matching for library searching patterns = {'openbsd': {'shared': ('lib{}.so', '{}.so', 'lib{}.so.[0-9]*.[0-9]*', '{}.so.[0-9]*.[0-9]*'), 'static': unix_static}, 'linux': {'shared': ('lib{}.so', '{}.so'), 'static': unix_static}, 'darwin': {'shared': ('lib{}.dylib', 'lib{}.so', '{}.dylib', '{}.so'), 'static': unix_static}, 'cygwin': {'shared': ('cyg{}.dll', 'cyg{}.dll.a', 'lib{}.dll', 'lib{}.dll.a', '{}.dll', '{}.dll.a'), 'static': ('cyg{}.a',) + unix_static}, 'windows-msvc': {'shared': ('lib{}.lib', '{}.lib'), 'static': msvc_static}, 'windows-mingw': {'shared': ('lib{}.dll.a', 'lib{}.lib', 'lib{}.dll', '{}.dll.a', '{}.lib', '{}.dll'), 'static': msvc_static}} env = get_fake_env() cc = detect_c_compiler(env, MachineChoice.HOST) if is_osx(): self._test_all_naming(cc, env, patterns, 'darwin') elif is_cygwin(): self._test_all_naming(cc, env, patterns, 'cygwin') elif is_windows(): if cc.get_argument_syntax() == 'msvc': self._test_all_naming(cc, env, patterns, 'windows-msvc') else: self._test_all_naming(cc, env, patterns, 'windows-mingw') elif is_openbsd(): self._test_all_naming(cc, env, patterns, 'openbsd') else: self._test_all_naming(cc, env, patterns, 'linux') env.machines.host.system = 'openbsd' self._test_all_naming(cc, env, patterns, 'openbsd') env.machines.host.system = 'darwin' self._test_all_naming(cc, env, patterns, 'darwin') env.machines.host.system = 'cygwin' self._test_all_naming(cc, env, patterns, 'cygwin') env.machines.host.system = 'windows' self._test_all_naming(cc, env, patterns, 'windows-mingw') @skipIfNoPkgconfig def test_pkgconfig_parse_libs(self): ''' Unit test for parsing of pkg-config output to search for libraries https://github.com/mesonbuild/meson/issues/3951 ''' def create_static_lib(name): if not is_osx(): name.open('w', encoding='utf-8').close() return src = name.with_suffix('.c') out = name.with_suffix('.o') with src.open('w', encoding='utf-8') as f: f.write('int meson_foobar (void) { return 0; }') # use of x86_64 is hardcoded in run_tests.py:get_fake_env() subprocess.check_call(['clang', '-c', str(src), '-o', str(out), '-arch', 'x86_64']) subprocess.check_call(['ar', 'csr', str(name), str(out)]) with tempfile.TemporaryDirectory() as tmpdir: pkgbin = ExternalProgram('pkg-config', command=['pkg-config'], silent=True) env = get_fake_env() compiler = detect_c_compiler(env, MachineChoice.HOST) env.coredata.compilers.host = {'c': compiler} env.coredata.optstore.set_value_object(OptionKey('c_link_args'), FakeCompilerOptions()) p1 = Path(tmpdir) / '1' p2 = Path(tmpdir) / '2' p1.mkdir() p2.mkdir() # libfoo.a is in one prefix create_static_lib(p1 / 'libfoo.a') # libbar.a is in both prefixes create_static_lib(p1 / 'libbar.a') create_static_lib(p2 / 'libbar.a') # Ensure that we never statically link to these create_static_lib(p1 / 'libpthread.a') create_static_lib(p1 / 'libm.a') create_static_lib(p1 / 'libc.a') create_static_lib(p1 / 'libdl.a') create_static_lib(p1 / 'librt.a') class FakeInstance(PkgConfigCLI): def _call_pkgbin(self, args, env=None): if '--libs' not in args: return 0, '', '' if args[-1] == 'foo': return 0, f'-L{p2.as_posix()} -lfoo -L{p1.as_posix()} -lbar', '' if args[-1] == 'bar': return 0, f'-L{p2.as_posix()} -lbar', '' if args[-1] == 'internal': return 0, f'-L{p1.as_posix()} -lpthread -lm -lc -lrt -ldl', '' with mock.patch.object(PkgConfigInterface, 'instance') as instance_method: instance_method.return_value = FakeInstance(env, MachineChoice.HOST, silent=True) kwargs = {'required': True, 'silent': True} foo_dep = PkgConfigDependency('foo', env, kwargs) self.assertEqual(foo_dep.get_link_args(), [(p1 / 'libfoo.a').as_posix(), (p2 / 'libbar.a').as_posix()]) bar_dep = PkgConfigDependency('bar', env, kwargs) self.assertEqual(bar_dep.get_link_args(), [(p2 / 'libbar.a').as_posix()]) internal_dep = PkgConfigDependency('internal', env, kwargs) if compiler.get_argument_syntax() == 'msvc': self.assertEqual(internal_dep.get_link_args(), []) else: link_args = internal_dep.get_link_args() for link_arg in link_args: for lib in ('pthread', 'm', 'c', 'dl', 'rt'): self.assertNotIn(f'lib{lib}.a', link_arg, msg=link_args) def test_program_version(self): with tempfile.TemporaryDirectory() as tmpdir: script_path = Path(tmpdir) / 'script.py' script_path.write_text('import sys\nprint(sys.argv[1])\n', encoding='utf-8') script_path.chmod(0o755) for output, expected in { '': None, '1': None, '1.2.4': '1.2.4', '1 1.2.4': '1.2.4', 'foo version 1.2.4': '1.2.4', 'foo 1.2.4.': '1.2.4', 'foo 1.2.4': '1.2.4', 'foo 1.2.4 bar': '1.2.4', 'foo 10.0.0': '10.0.0', '50 5.4.0': '5.4.0', 'This is perl 5, version 40, subversion 0 (v5.40.0)': '5.40.0', 'git version 2.48.0.rc1': '2.48.0', }.items(): prog = ExternalProgram('script', command=[python_command, str(script_path), output], silent=True) if expected is None: with self.assertRaisesRegex(MesonException, 'Could not find a version number'): prog.get_version() else: self.assertEqual(prog.get_version(), expected) def test_version_compare(self): comparefunc = mesonbuild.mesonlib.version_compare_many for (a, b, result) in [ ('0.99.beta19', '>= 0.99.beta14', True), ]: self.assertEqual(comparefunc(a, b)[0], result) for (a, b, op) in [ # examples from https://fedoraproject.org/wiki/Archive:Tools/RPM/VersionComparison ("1.0010", "1.9", operator.gt), ("1.05", "1.5", operator.eq), ("1.0", "1", operator.gt), ("2.50", "2.5", operator.gt), ("fc4", "fc.4", operator.eq), ("FC5", "fc4", operator.lt), ("2a", "2.0", operator.lt), ("1.0", "1.fc4", operator.gt), ("3.0.0_fc", "3.0.0.fc", operator.eq), # from RPM tests ("1.0", "1.0", operator.eq), ("1.0", "2.0", operator.lt), ("2.0", "1.0", operator.gt), ("2.0.1", "2.0.1", operator.eq), ("2.0", "2.0.1", operator.lt), ("2.0.1", "2.0", operator.gt), ("2.0.1a", "2.0.1a", operator.eq), ("2.0.1a", "2.0.1", operator.gt), ("2.0.1", "2.0.1a", operator.lt), ("5.5p1", "5.5p1", operator.eq), ("5.5p1", "5.5p2", operator.lt), ("5.5p2", "5.5p1", operator.gt), ("5.5p10", "5.5p10", operator.eq), ("5.5p1", "5.5p10", operator.lt), ("5.5p10", "5.5p1", operator.gt), ("10xyz", "10.1xyz", operator.lt), ("10.1xyz", "10xyz", operator.gt), ("xyz10", "xyz10", operator.eq), ("xyz10", "xyz10.1", operator.lt), ("xyz10.1", "xyz10", operator.gt), ("xyz.4", "xyz.4", operator.eq), ("xyz.4", "8", operator.lt), ("8", "xyz.4", operator.gt), ("xyz.4", "2", operator.lt), ("2", "xyz.4", operator.gt), ("5.5p2", "5.6p1", operator.lt), ("5.6p1", "5.5p2", operator.gt), ("5.6p1", "6.5p1", operator.lt), ("6.5p1", "5.6p1", operator.gt), ("6.0.rc1", "6.0", operator.gt), ("6.0", "6.0.rc1", operator.lt), ("10b2", "10a1", operator.gt), ("10a2", "10b2", operator.lt), ("1.0aa", "1.0aa", operator.eq), ("1.0a", "1.0aa", operator.lt), ("1.0aa", "1.0a", operator.gt), ("10.0001", "10.0001", operator.eq), ("10.0001", "10.1", operator.eq), ("10.1", "10.0001", operator.eq), ("10.0001", "10.0039", operator.lt), ("10.0039", "10.0001", operator.gt), ("4.999.9", "5.0", operator.lt), ("5.0", "4.999.9", operator.gt), ("20101121", "20101121", operator.eq), ("20101121", "20101122", operator.lt), ("20101122", "20101121", operator.gt), ("2_0", "2_0", operator.eq), ("2.0", "2_0", operator.eq), ("2_0", "2.0", operator.eq), ("a", "a", operator.eq), ("a+", "a+", operator.eq), ("a+", "a_", operator.eq), ("a_", "a+", operator.eq), ("+a", "+a", operator.eq), ("+a", "_a", operator.eq), ("_a", "+a", operator.eq), ("+_", "+_", operator.eq), ("_+", "+_", operator.eq), ("_+", "_+", operator.eq), ("+", "_", operator.eq), ("_", "+", operator.eq), # other tests ('0.99.beta19', '0.99.beta14', operator.gt), ("1.0.0", "2.0.0", operator.lt), (".0.0", "2.0.0", operator.lt), ("alpha", "beta", operator.lt), ("1.0", "1.0.0", operator.lt), ("2.456", "2.1000", operator.lt), ("2.1000", "3.111", operator.lt), ("2.001", "2.1", operator.eq), ("2.34", "2.34", operator.eq), ("6.1.2", "6.3.8", operator.lt), ("1.7.3.0", "2.0.0", operator.lt), ("2.24.51", "2.25", operator.lt), ("2.1.5+20120813+gitdcbe778", "2.1.5", operator.gt), ("3.4.1", "3.4b1", operator.gt), ("041206", "200090325", operator.lt), ("0.6.2+git20130413", "0.6.2", operator.gt), ("2.6.0+bzr6602", "2.6.0", operator.gt), ("2.6.0", "2.6b2", operator.gt), ("2.6.0+bzr6602", "2.6b2x", operator.gt), ("0.6.7+20150214+git3a710f9", "0.6.7", operator.gt), ("15.8b", "15.8.0.1", operator.lt), ("1.2rc1", "1.2.0", operator.lt), ]: ver_a = Version(a) ver_b = Version(b) if op is operator.eq: for o, name in [(op, 'eq'), (operator.ge, 'ge'), (operator.le, 'le')]: self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}') if op is operator.lt: for o, name in [(op, 'lt'), (operator.le, 'le'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}') for o, name in [(operator.gt, 'gt'), (operator.ge, 'ge'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}') if op is operator.gt: for o, name in [(op, 'gt'), (operator.ge, 'ge'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}') for o, name in [(operator.lt, 'lt'), (operator.le, 'le'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), f'{ver_a} {name} {ver_b}') def test_msvc_toolset_version(self): ''' Ensure that the toolset version returns the correct value for this MSVC ''' env = get_fake_env() cc = detect_c_compiler(env, MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') toolset_ver = cc.get_toolset_version() self.assertIsNotNone(toolset_ver) # Visual Studio 2015 and older versions do not define VCToolsVersion # TODO: ICL doesn't set this in the VSC2015 profile either if cc.id == 'msvc' and int(''.join(cc.version.split('.')[0:2])) < 1910: return if 'VCToolsVersion' in os.environ: vctools_ver = os.environ['VCToolsVersion'] else: self.assertIn('VCINSTALLDIR', os.environ) # See https://devblogs.microsoft.com/cppblog/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ vctools_ver = (Path(os.environ['VCINSTALLDIR']) / 'Auxiliary' / 'Build' / 'Microsoft.VCToolsVersion.default.txt').read_text(encoding='utf-8') self.assertTrue(vctools_ver.startswith(toolset_ver), msg=f'{vctools_ver!r} does not start with {toolset_ver!r}') def test_split_args(self): split_args = mesonbuild.mesonlib.split_args join_args = mesonbuild.mesonlib.join_args if is_windows(): test_data = [ # examples from https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments (r'"a b c" d e', ['a b c', 'd', 'e'], True), (r'"ab\"c" "\\" d', ['ab"c', '\\', 'd'], False), (r'a\\\b d"e f"g h', [r'a\\\b', 'de fg', 'h'], False), (r'a\\\"b c d', [r'a\"b', 'c', 'd'], False), (r'a\\\\"b c" d e', [r'a\\b c', 'd', 'e'], False), # other basics (r'""', [''], True), (r'a b c d "" e', ['a', 'b', 'c', 'd', '', 'e'], True), (r"'a b c' d e", ["'a", 'b', "c'", 'd', 'e'], True), (r"'a&b&c' d e", ["'a&b&c'", 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], True), (r"'a & b & c d e'", ["'a", '&', 'b', '&', 'c', 'd', "e'"], True), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), # more illustrative tests (r'cl test.cpp /O1 /Fe:test.exe', ['cl', 'test.cpp', '/O1', '/Fe:test.exe'], True), (r'cl "test.cpp /O1 /Fe:test.exe"', ['cl', 'test.cpp /O1 /Fe:test.exe'], True), (r'cl /DNAME=\"Bob\" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob\"" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], True), (r'cl /DNAME=\"Bob, Alice\" test.cpp', ['cl', '/DNAME="Bob,', 'Alice"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob, Alice\"" test.cpp', ['cl', '/DNAME="Bob, Alice"', 'test.cpp'], True), (r'cl C:\path\with\backslashes.cpp', ['cl', r'C:\path\with\backslashes.cpp'], True), (r'cl C:\\path\\with\\double\\backslashes.cpp', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], True), (r'cl "C:\\path\\with\\double\\backslashes.cpp"', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], False), (r'cl C:\path with spaces\test.cpp', ['cl', r'C:\path', 'with', r'spaces\test.cpp'], False), (r'cl "C:\path with spaces\test.cpp"', ['cl', r'C:\path with spaces\test.cpp'], True), (r'cl /DPATH="C:\path\with\backslashes test.cpp', ['cl', r'/DPATH=C:\path\with\backslashes test.cpp'], False), (r'cl /DPATH=\"C:\\ends\\with\\backslashes\\\" test.cpp', ['cl', r'/DPATH="C:\\ends\\with\\backslashes\"', 'test.cpp'], False), (r'cl /DPATH="C:\\ends\\with\\backslashes\\" test.cpp', ['cl', '/DPATH=C:\\\\ends\\\\with\\\\backslashes\\', 'test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\"', 'test.cpp'], True), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\ test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\"', 'test.cpp'], True), ] else: test_data = [ (r"'a b c' d e", ['a b c', 'd', 'e'], True), (r"a/b/c d e", ['a/b/c', 'd', 'e'], True), (r"a\b\c d e", [r'abc', 'd', 'e'], False), (r"a\\b\\c d e", [r'a\b\c', 'd', 'e'], False), (r'"a b c" d e', ['a b c', 'd', 'e'], False), (r'"a\\b\\c\\" d e', ['a\\b\\c\\', 'd', 'e'], False), (r"'a\b\c\' d e", ['a\\b\\c\\', 'd', 'e'], True), (r"'a&b&c' d e", ['a&b&c', 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], False), (r"'a & b & c d e'", ['a & b & c d e'], True), (r"abd'e f'g h", [r'abde fg', 'h'], False), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), ('g++ -DNAME="Bob" test.cpp', ['g++', '-DNAME=Bob', 'test.cpp'], False), ("g++ '-DNAME=\"Bob\"' test.cpp", ['g++', '-DNAME="Bob"', 'test.cpp'], True), ('g++ -DNAME="Bob, Alice" test.cpp', ['g++', '-DNAME=Bob, Alice', 'test.cpp'], False), ("g++ '-DNAME=\"Bob, Alice\"' test.cpp", ['g++', '-DNAME="Bob, Alice"', 'test.cpp'], True), ] for (cmd, expected, roundtrip) in test_data: self.assertEqual(split_args(cmd), expected) if roundtrip: self.assertEqual(join_args(expected), cmd) def test_quote_arg(self): split_args = mesonbuild.mesonlib.split_args quote_arg = mesonbuild.mesonlib.quote_arg if is_windows(): test_data = [ ('', '""'), ('arg1', 'arg1'), ('/option1', '/option1'), ('/Ovalue', '/Ovalue'), ('/OBob&Alice', '/OBob&Alice'), ('/Ovalue with spaces', r'"/Ovalue with spaces"'), (r'/O"value with spaces"', r'"/O\"value with spaces\""'), (r'/OC:\path with spaces\test.exe', r'"/OC:\path with spaces\test.exe"'), ('/LIBPATH:C:\\path with spaces\\ends\\with\\backslashes\\', r'"/LIBPATH:C:\path with spaces\ends\with\backslashes\\"'), ('/LIBPATH:"C:\\path with spaces\\ends\\with\\backslashes\\\\"', r'"/LIBPATH:\"C:\path with spaces\ends\with\backslashes\\\\\""'), (r'/DMSG="Alice said: \"Let\'s go\""', r'"/DMSG=\"Alice said: \\\"Let\'s go\\\"\""'), ] else: test_data = [ ('arg1', 'arg1'), ('--option1', '--option1'), ('-O=value', '-O=value'), ('-O=Bob&Alice', "'-O=Bob&Alice'"), ('-O=value with spaces', "'-O=value with spaces'"), ('-O="value with spaces"', '\'-O=\"value with spaces\"\''), ('-O=/path with spaces/test', '\'-O=/path with spaces/test\''), ('-DMSG="Alice said: \\"Let\'s go\\""', "'-DMSG=\"Alice said: \\\"Let'\"'\"'s go\\\"\"'"), ] for (arg, expected) in test_data: self.assertEqual(quote_arg(arg), expected) self.assertEqual(split_args(expected)[0], arg) def test_depfile(self): for (f, target, expdeps) in [ # empty, unknown target ([''], 'unknown', set()), # simple target & deps (['meson/foo.o : foo.c foo.h'], 'meson/foo.o', set({'foo.c', 'foo.h'})), (['meson/foo.o: foo.c foo.h'], 'foo.c', set()), # get all deps (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'meson/foo.o', set({'foo.c', 'foo.h', 'gen.py'})), (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'foo.c', set({'gen.py'})), # linue continuation, multiple targets (['foo.o \\', 'foo.h: bar'], 'foo.h', set({'bar'})), (['foo.o \\', 'foo.h: bar'], 'foo.o', set({'bar'})), # \\ handling (['foo: Program\\ F\\iles\\\\X'], 'foo', set({'Program Files\\X'})), # $ handling (['f$o.o: c/b'], 'f$o.o', set({'c/b'})), (['f$$o.o: c/b'], 'f$o.o', set({'c/b'})), # cycles (['a: b', 'b: a'], 'a', set({'a', 'b'})), (['a: b', 'b: a'], 'b', set({'a', 'b'})), ]: d = mesonbuild.depfile.DepFile(f) deps = d.get_all_dependencies(target) self.assertEqual(sorted(deps), sorted(expdeps)) def test_log_once(self): f = io.StringIO() with mock.patch('mesonbuild.mlog._logger.log_file', f), \ mock.patch('mesonbuild.mlog._logger.logged_once', set()): mesonbuild.mlog.log('foo', once=True) mesonbuild.mlog.log('foo', once=True) actual = f.getvalue().strip() self.assertEqual(actual, 'foo', actual) def test_log_once_ansi(self): f = io.StringIO() with mock.patch('mesonbuild.mlog._logger.log_file', f), \ mock.patch('mesonbuild.mlog._logger.logged_once', set()): mesonbuild.mlog.log(mesonbuild.mlog.bold('foo'), once=True) mesonbuild.mlog.log(mesonbuild.mlog.bold('foo'), once=True) actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) mesonbuild.mlog.log('foo', once=True) actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) f.truncate() mesonbuild.mlog.warning('bar', once=True) mesonbuild.mlog.warning('bar', once=True) actual = f.getvalue().strip() self.assertEqual(actual.count('bar'), 1, actual) def test_sort_libpaths(self): sort_libpaths = mesonbuild.dependencies.base.sort_libpaths self.assertEqual(sort_libpaths( ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/local/lib', '/home/mesonuser/.local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/libdata/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) def test_dependency_factory_order(self): b = mesonbuild.dependencies.base F = mesonbuild.dependencies.factory with tempfile.TemporaryDirectory() as tmpdir: with chdir(tmpdir): env = get_fake_env() env.scratch_dir = tmpdir f = F.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake']) f = F.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig']) def test_validate_json(self) -> None: """Validate the json schema for the test cases.""" try: from fastjsonschema import compile, JsonSchemaValueException as JsonSchemaFailure fast = True except ImportError: try: from jsonschema import validate, ValidationError as JsonSchemaFailure fast = False except: if is_ci(): raise raise unittest.SkipTest('neither Python fastjsonschema nor jsonschema module not found.') with open('data/test.schema.json', 'r', encoding='utf-8') as f: data = json.loads(f.read()) if fast: schema_validator = compile(data) else: schema_validator = lambda x: validate(x, schema=data) errors: T.List[T.Tuple[Path, Exception]] = [] for p in Path('test cases').glob('**/test.json'): try: schema_validator(json.loads(p.read_text(encoding='utf-8'))) except JsonSchemaFailure as e: errors.append((p.resolve(), e)) for f, e in errors: print(f'Failed to validate: "{f}"') print(str(e)) self.assertFalse(errors) def test_typed_pos_args_types(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], int) self.assertIsInstance(args[2], bool) _(None, mock.Mock(), ['string', 1, False], None) def test_typed_pos_args_types_invalid(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1.0, False], None) self.assertEqual(str(cm.exception), 'foo argument 2 was of type "float" but should have been "int"') def test_typed_pos_args_types_wrong_number(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 2.') with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1, True, True], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 4.') def test_typed_pos_args_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_varargs_not_given(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertEqual(args[1], []) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_varargs_invalid(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been "str"') def test_typed_pos_args_varargs_invalid_multiple_types(self) -> None: @typed_pos_args('foo', str, varargs=(str, list)) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been one of: "str", "list"') def test_typed_pos_args_max_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=5) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=1) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args'], None) self.assertEqual(str(cm.exception), 'foo takes between 1 and 2 arguments, but got 3.') def test_typed_pos_args_min_varargs(self) -> None: @typed_pos_args('foo', varargs=str, max_varargs=2, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], list) self.assertIsInstance(args[0][0], str) self.assertIsInstance(args[0][1], str) _(None, mock.Mock(), ['string', 'var'], None) def test_typed_pos_args_min_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_and_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 'bar'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 4.') def test_typed_pos_args_min_and_max_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 1.') def test_typed_pos_args_variadic_and_optional(self) -> None: @typed_pos_args('foo', str, optargs=[str], varargs=str, min_varargs=0) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(AssertionError) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual( str(cm.exception), 'varargs and optargs not supported together as this would be ambiguous') def test_typed_pos_args_min_optargs_not_met(self) -> None: @typed_pos_args('foo', str, str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_optargs_max_exceeded(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', '1', '2'], None) self.assertEqual(str(cm.exception), 'foo takes at most 2 arguments, but got 3.') def test_typed_pos_args_optargs_not_given(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertEqual(len(args), 2) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsNone(args[1]) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_optargs_some_given(self) -> None: