aboutsummaryrefslogtreecommitdiff
path: root/libcxx/test/selftest/dsl/dsl.sh.py
blob: 6d4406b7858e698ac697da3bd2ac85db19008873 (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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# ===----------------------------------------------------------------------===##
#
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# ===----------------------------------------------------------------------===##

# With picolibc, test_program_stderr_is_not_conflated_with_stdout fails
# because stdout & stderr are treated as the same.
# XFAIL: LIBCXX-PICOLIBC-FIXME

# Note: We prepend arguments with 'x' to avoid thinking there are too few
#       arguments in case an argument is an empty string.
# RUN: %{python} %s x%S x%T x%{substitutions}

import base64
import copy
import os
import pickle
import platform
import subprocess
import sys
import unittest
from os.path import dirname

# Allow importing 'lit' and the 'libcxx' module. Make sure we put the lit
# path first so we don't find any system-installed version.
monorepoRoot = dirname(dirname(dirname(dirname(dirname(__file__)))))
sys.path = [
    os.path.join(monorepoRoot, "libcxx", "utils"),
    os.path.join(monorepoRoot, "llvm", "utils", "lit"),
] + sys.path
import libcxx.test.dsl as dsl
import lit.LitConfig
import lit.util

# Steal some parameters from the config running this test so that we can
# bootstrap our own TestingConfig.
args = list(map(lambda s: s[1:], sys.argv[1:8]))  # Remove the leading 'x'
SOURCE_ROOT, EXEC_PATH, SUBSTITUTIONS = args
sys.argv[1:8] = []

# Decode the substitutions.
SUBSTITUTIONS = pickle.loads(base64.b64decode(SUBSTITUTIONS))
for s, sub in SUBSTITUTIONS:
    print("Substitution '{}' is '{}'".format(s, sub))


class SetupConfigs(unittest.TestCase):
    """
    Base class for the tests below -- it creates a fake TestingConfig.
    """

    def setUp(self):
        """
        Create a fake TestingConfig that can be populated however we wish for
        the purpose of running unit tests below. We pre-populate it with the
        minimum required substitutions.
        """
        self.litConfig = lit.LitConfig.LitConfig(
            progname="lit",
            path=[],
            quiet=False,
            useValgrind=False,
            valgrindLeakCheck=False,
            valgrindArgs=[],
            noExecute=False,
            debug=False,
            isWindows=platform.system() == "Windows",
            order="smart",
            params={},
        )

        self.config = lit.TestingConfig.TestingConfig.fromdefaults(self.litConfig)
        self.config.environment = dict(os.environ)
        self.config.test_source_root = SOURCE_ROOT
        self.config.test_exec_root = EXEC_PATH
        self.config.recursiveExpansionLimit = 10
        self.config.substitutions = copy.deepcopy(SUBSTITUTIONS)

    def getSubstitution(self, substitution):
        """
        Return a given substitution from the TestingConfig. It is an error if
        there is no such substitution.
        """
        found = [x for (s, x) in self.config.substitutions if s == substitution]
        assert len(found) == 1
        return found[0]


def findIndex(list, pred):
    """Finds the index of the first element satisfying 'pred' in a list, or
    'len(list)' if there is no such element."""
    index = 0
    for x in list:
        if pred(x):
            break
        else:
            index += 1
    return index


class TestHasCompileFlag(SetupConfigs):
    """
    Tests for libcxx.test.dsl.hasCompileFlag
    """

    def test_no_flag_should_work(self):
        self.assertTrue(dsl.hasCompileFlag(self.config, ""))

    def test_flag_exists(self):
        self.assertTrue(dsl.hasCompileFlag(self.config, "-O1"))

    def test_nonexistent_flag(self):
        self.assertFalse(
            dsl.hasCompileFlag(self.config, "-this_is_not_a_flag_any_compiler_has")
        )

    def test_multiple_flags(self):
        self.assertTrue(dsl.hasCompileFlag(self.config, "-O1 -Dhello"))


class TestSourceBuilds(SetupConfigs):
    """
    Tests for libcxx.test.dsl.sourceBuilds
    """

    def test_valid_program_builds(self):
        source = """int main(int, char**) { return 0; }"""
        self.assertTrue(dsl.sourceBuilds(self.config, source))

    def test_compilation_error_fails(self):
        source = """int main(int, char**) { this does not compile }"""
        self.assertFalse(dsl.sourceBuilds(self.config, source))

    def test_link_error_fails(self):
        source = """extern void this_isnt_defined_anywhere();
                    int main(int, char**) { this_isnt_defined_anywhere(); return 0; }"""
        self.assertFalse(dsl.sourceBuilds(self.config, source))


class TestProgramOutput(SetupConfigs):
    """
    Tests for libcxx.test.dsl.programOutput
    """

    def test_valid_program_returns_output(self):
        source = """
        #include <cstdio>
        int main(int, char**) { std::printf("FOOBAR"); return 0; }
        """
        self.assertEqual(dsl.programOutput(self.config, source), "FOOBAR")

    def test_valid_program_returns_output_newline_handling(self):
        source = """
        #include <cstdio>
        int main(int, char**) { std::printf("FOOBAR\\n"); return 0; }
        """
        self.assertEqual(dsl.programOutput(self.config, source), "FOOBAR\n")

    def test_valid_program_returns_no_output(self):
        source = """
        int main(int, char**) { return 0; }
        """
        self.assertEqual(dsl.programOutput(self.config, source), "")

    def test_program_that_fails_to_run_raises_runtime_error(self):
        # The program compiles, but exits with an error
        source = """
        int main(int, char**) { return 1; }
        """
        self.assertRaises(
            dsl.ConfigurationRuntimeError,
            lambda: dsl.programOutput(self.config, source),
        )

    def test_program_that_fails_to_compile_raises_compilation_error(self):
        # The program doesn't compile
        source = """
        int main(int, char**) { this doesnt compile }
        """
        self.assertRaises(
            dsl.ConfigurationCompilationError,
            lambda: dsl.programOutput(self.config, source),
        )

    def test_pass_arguments_to_program(self):
        source = """
        #include <cassert>
        #include <string>
        int main(int argc, char** argv) {
            assert(argc == 3);
            assert(argv[1] == std::string("first-argument"));
            assert(argv[2] == std::string("second-argument"));
            return 0;
        }
        """
        args = ["first-argument", "second-argument"]
        self.assertEqual(dsl.programOutput(self.config, source, args=args), "")

    def test_caching_is_not_too_aggressive(self):
        # Run a program, then change the substitutions and run it again.
        # Make sure the program is run the second time and the right result
        # is given, to ensure we're not incorrectly caching the result of the
        # first program run.
        source = """
        #include <cstdio>
        int main(int, char**) {
            std::printf("MACRO=%u\\n", MACRO);
            return 0;
        }
        """
        compileFlagsIndex = findIndex(
            self.config.substitutions, lambda x: x[0] == "%{compile_flags}"
        )
        compileFlags = self.config.substitutions[compileFlagsIndex][1]

        self.config.substitutions[compileFlagsIndex] = (
            "%{compile_flags}",
            compileFlags + " -DMACRO=1",
        )
        output1 = dsl.programOutput(self.config, source)
        self.assertEqual(output1, "MACRO=1\n")

        self.config.substitutions[compileFlagsIndex] = (
            "%{compile_flags}",
            compileFlags + " -DMACRO=2",
        )
        output2 = dsl.programOutput(self.config, source)
        self.assertEqual(output2, "MACRO=2\n")

    def test_program_stderr_is_not_conflated_with_stdout(self):
        # Run a program that produces stdout output and stderr output too, making
        # sure the stderr output does not pollute the stdout output.
        source = """
        #include <cstdio>
        int main(int, char**) {
            std::fprintf(stdout, "STDOUT-OUTPUT");
            std::fprintf(stderr, "STDERR-OUTPUT");
            return 0;
        }
        """
        self.assertEqual(dsl.programOutput(self.config, source), "STDOUT-OUTPUT")


class TestProgramSucceeds(SetupConfigs):
    """
    Tests for libcxx.test.dsl.programSucceeds
    """

    def test_success(self):
        source = """
        int main(int, char**) { return 0; }
        """
        self.assertTrue(dsl.programSucceeds(self.config, source))

    def test_failure(self):
        source = """
        int main(int, char**) { return 1; }
        """
        self.assertFalse(dsl.programSucceeds(self.config, source))

    def test_compile_failure(self):
        source = """
        this does not compile
        """
        self.assertRaises(
            dsl.ConfigurationCompilationError,
            lambda: dsl.programSucceeds(self.config, source),
        )


class TestHasLocale(SetupConfigs):
    """
    Tests for libcxx.test.dsl.hasLocale
    """

    def test_doesnt_explode(self):
        # It's really hard to test that a system has a given locale, so at least
        # make sure we don't explode when we try to check it.
        try:
            dsl.hasAnyLocale(self.config, ["en_US.UTF-8"])
        except subprocess.CalledProcessError:
            self.fail("checking for hasLocale should not explode")

    def test_nonexistent_locale(self):
        self.assertFalse(
            dsl.hasAnyLocale(self.config, ["forsurethisisnotanexistinglocale"])
        )

    def test_localization_program_doesnt_compile(self):
        compilerIndex = findIndex(self.config.substitutions, lambda x: x[0] == "%{cxx}")
        self.config.substitutions[compilerIndex] = (
            "%{cxx}",
            "this-is-certainly-not-a-valid-compiler!!",
        )
        self.assertRaises(
            dsl.ConfigurationCompilationError,
            lambda: dsl.hasAnyLocale(self.config, ["en_US.UTF-8"]),
        )


class TestCompilerMacros(SetupConfigs):
    """
    Tests for libcxx.test.dsl.compilerMacros
    """

    def test_basic(self):
        macros = dsl.compilerMacros(self.config)
        self.assertIsInstance(macros, dict)
        self.assertGreater(len(macros), 0)
        for (k, v) in macros.items():
            self.assertIsInstance(k, str)
            self.assertIsInstance(v, str)

    def test_no_flag(self):
        macros = dsl.compilerMacros(self.config)
        self.assertIn("__cplusplus", macros.keys())

    def test_empty_flag(self):
        macros = dsl.compilerMacros(self.config, "")
        self.assertIn("__cplusplus", macros.keys())

    def test_with_flag(self):
        macros = dsl.compilerMacros(self.config, "-DFOO=3")
        self.assertIn("__cplusplus", macros.keys())
        self.assertEqual(macros["FOO"], "3")

    def test_with_flags(self):
        macros = dsl.compilerMacros(self.config, "-DFOO=3 -DBAR=hello")
        self.assertIn("__cplusplus", macros.keys())
        self.assertEqual(macros["FOO"], "3")
        self.assertEqual(macros["BAR"], "hello")


class TestFeatureTestMacros(SetupConfigs):
    """
    Tests for libcxx.test.dsl.featureTestMacros
    """

    def test_basic(self):
        macros = dsl.featureTestMacros(self.config)
        self.assertIsInstance(macros, dict)
        self.assertGreater(len(macros), 0)
        for (k, v) in macros.items():
            self.assertIsInstance(k, str)
            self.assertIsInstance(v, int)


class TestFeature(SetupConfigs):
    """
    Tests for libcxx.test.dsl.Feature
    """

    def test_trivial(self):
        feature = dsl.Feature(name="name")
        origSubstitutions = copy.deepcopy(self.config.substitutions)
        actions = feature.getActions(self.config)
        self.assertTrue(len(actions) == 1)
        for a in actions:
            a.applyTo(self.config)
        self.assertEqual(origSubstitutions, self.config.substitutions)
        self.assertIn("name", self.config.available_features)

    def test_name_can_be_a_callable(self):
        feature = dsl.Feature(name=lambda cfg: "name")
        for a in feature.getActions(self.config):
            a.applyTo(self.config)
        self.assertIn("name", self.config.available_features)

    def test_name_is_not_a_string_1(self):
        feature = dsl.Feature(name=None)
        self.assertRaises(ValueError, lambda: feature.getActions(self.config))
        self.assertRaises(ValueError, lambda: feature.pretty(self.config))

    def test_name_is_not_a_string_2(self):
        feature = dsl.Feature(name=lambda cfg: None)
        self.assertRaises(ValueError, lambda: feature.getActions(self.config))
        self.assertRaises(ValueError, lambda: feature.pretty(self.config))

    def test_adding_action(self):
        feature = dsl.Feature(name="name", actions=[dsl.AddCompileFlag("-std=c++03")])
        origLinkFlags = copy.deepcopy(self.getSubstitution("%{link_flags}"))
        for a in feature.getActions(self.config):
            a.applyTo(self.config)
        self.assertIn("name", self.config.available_features)
        self.assertIn("-std=c++03", self.getSubstitution("%{compile_flags}"))
        self.assertEqual(origLinkFlags, self.getSubstitution("%{link_flags}"))

    def test_actions_can_be_a_callable(self):
        feature = dsl.Feature(
            name="name",
            actions=lambda cfg: (
                self.assertIs(self.config, cfg),
                [dsl.AddCompileFlag("-std=c++03")],
            )[1],
        )
        for a in feature.getActions(self.config):
            a.applyTo(self.config)
        self.assertIn("-std=c++03", self.getSubstitution("%{compile_flags}"))

    def test_unsupported_feature(self):
        feature = dsl.Feature(name="name", when=lambda _: False)
        self.assertEqual(feature.getActions(self.config), [])

    def test_is_supported_gets_passed_the_config(self):
        feature = dsl.Feature(
            name="name", when=lambda cfg: (self.assertIs(self.config, cfg), True)[1]
        )
        self.assertEqual(len(feature.getActions(self.config)), 1)


def _throw():
    raise ValueError()


class TestParameter(SetupConfigs):
    """
    Tests for libcxx.test.dsl.Parameter
    """

    def test_empty_name_should_blow_up(self):
        self.assertRaises(
            ValueError,
            lambda: dsl.Parameter(
                name="", choices=["c++03"], type=str, help="", actions=lambda _: []
            ),
        )

    def test_empty_choices_should_blow_up(self):
        self.assertRaises(
            ValueError,
            lambda: dsl.Parameter(
                name="std", choices=[], type=str, help="", actions=lambda _: []
            ),
        )

    def test_no_choices_is_ok(self):
        param = dsl.Parameter(name="triple", type=str, help="", actions=lambda _: [])
        self.assertEqual(param.name, "triple")

    def test_name_is_set_correctly(self):
        param = dsl.Parameter(
            name="std", choices=["c++03"], type=str, help="", actions=lambda _: []
        )
        self.assertEqual(param.name, "std")

    def test_no_value_provided_and_no_default_value(self):
        param = dsl.Parameter(
            name="std", choices=["c++03"], type=str, help="", actions=lambda _: []
        )
        self.assertRaises(
            ValueError, lambda: param.getActions(self.config, self.litConfig.params)
        )

    def test_no_value_provided_and_default_value(self):
        param = dsl.Parameter(
            name="std",
            choices=["c++03"],
            type=str,
            help="",
            default="c++03",
            actions=lambda std: [dsl.AddFeature(std)],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("c++03", self.config.available_features)

    def test_value_provided_on_command_line_and_no_default_value(self):
        self.litConfig.params["std"] = "c++03"
        param = dsl.Parameter(
            name="std",
            choices=["c++03"],
            type=str,
            help="",
            actions=lambda std: [dsl.AddFeature(std)],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("c++03", self.config.available_features)

    def test_value_provided_on_command_line_and_default_value(self):
        """The value provided on the command line should override the default value"""
        self.litConfig.params["std"] = "c++11"
        param = dsl.Parameter(
            name="std",
            choices=["c++03", "c++11"],
            type=str,
            default="c++03",
            help="",
            actions=lambda std: [dsl.AddFeature(std)],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("c++11", self.config.available_features)
        self.assertNotIn("c++03", self.config.available_features)

    def test_value_provided_in_config_and_default_value(self):
        """The value provided in the config should override the default value"""
        self.config.std = "c++11"
        param = dsl.Parameter(
            name="std",
            choices=["c++03", "c++11"],
            type=str,
            default="c++03",
            help="",
            actions=lambda std: [dsl.AddFeature(std)],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("c++11", self.config.available_features)
        self.assertNotIn("c++03", self.config.available_features)

    def test_value_provided_in_config_and_on_command_line(self):
        """The value on the command line should override the one in the config"""
        self.config.std = "c++11"
        self.litConfig.params["std"] = "c++03"
        param = dsl.Parameter(
            name="std",
            choices=["c++03", "c++11"],
            type=str,
            help="",
            actions=lambda std: [dsl.AddFeature(std)],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("c++03", self.config.available_features)
        self.assertNotIn("c++11", self.config.available_features)

    def test_no_actions(self):
        self.litConfig.params["std"] = "c++03"
        param = dsl.Parameter(
            name="std", choices=["c++03"], type=str, help="", actions=lambda _: []
        )
        actions = param.getActions(self.config, self.litConfig.params)
        self.assertEqual(actions, [])

    def test_boolean_value_parsed_from_trueish_string_parameter(self):
        self.litConfig.params["enable_exceptions"] = "True"
        param = dsl.Parameter(
            name="enable_exceptions",
            choices=[True, False],
            type=bool,
            help="",
            actions=lambda exceptions: [] if exceptions else _throw(),
        )
        self.assertEqual(param.getActions(self.config, self.litConfig.params), [])

    def test_boolean_value_from_true_boolean_parameter(self):
        self.litConfig.params["enable_exceptions"] = True
        param = dsl.Parameter(
            name="enable_exceptions",
            choices=[True, False],
            type=bool,
            help="",
            actions=lambda exceptions: [] if exceptions else _throw(),
        )
        self.assertEqual(param.getActions(self.config, self.litConfig.params), [])

    def test_boolean_value_parsed_from_falseish_string_parameter(self):
        self.litConfig.params["enable_exceptions"] = "False"
        param = dsl.Parameter(
            name="enable_exceptions",
            choices=[True, False],
            type=bool,
            help="",
            actions=lambda exceptions: []
            if exceptions
            else [dsl.AddFeature("-fno-exceptions")],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("-fno-exceptions", self.config.available_features)

    def test_boolean_value_from_false_boolean_parameter(self):
        self.litConfig.params["enable_exceptions"] = False
        param = dsl.Parameter(
            name="enable_exceptions",
            choices=[True, False],
            type=bool,
            help="",
            actions=lambda exceptions: []
            if exceptions
            else [dsl.AddFeature("-fno-exceptions")],
        )
        for a in param.getActions(self.config, self.litConfig.params):
            a.applyTo(self.config)
        self.assertIn("-fno-exceptions", self.config.available_features)

    def test_list_parsed_from_comma_delimited_string_empty(self):
        self.litConfig.params["additional_features"] = ""
        param = dsl.Parameter(
            name="additional_features", type=list, help="", actions=lambda f: f
        )
        self.assertEqual(param.getActions(self.config, self.litConfig.params), [])

    def test_list_parsed_from_comma_delimited_string_1(self):
        self.litConfig.params["additional_features"] = "feature1"
        param = dsl.Parameter(
            name="additional_features", type=list, help="", actions=lambda f: f
        )
        self.assertEqual(
            param.getActions(self.config, self.litConfig.params), ["feature1"]
        )

    def test_list_parsed_from_comma_delimited_string_2(self):
        self.litConfig.params["additional_features"] = "feature1,feature2"
        param = dsl.Parameter(
            name="additional_features", type=list, help="", actions=lambda f: f
        )
        self.assertEqual(
            param.getActions(self.config, self.litConfig.params),
            ["feature1", "feature2"],
        )

    def test_list_parsed_from_comma_delimited_string_3(self):
        self.litConfig.params["additional_features"] = "feature1,feature2, feature3"
        param = dsl.Parameter(
            name="additional_features", type=list, help="", actions=lambda f: f
        )
        self.assertEqual(
            param.getActions(self.config, self.litConfig.params),
            ["feature1", "feature2", "feature3"],
        )


if __name__ == "__main__":
    unittest.main(verbosity=2)