This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
forked from dxx-rebirth/dxx-rebirth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSConstruct
5730 lines (5486 loc) · 223 KB
/
SConstruct
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#SConstruct
# vim: set fenc=utf-8 sw=4 ts=4 :
# $Format:%H$
# needed imports
from collections import (defaultdict, Counter as collections_counter)
import collections.abc
from dataclasses import dataclass
import base64
import binascii
import errno
import itertools
import shlex
import subprocess
import sys
import typing
import os
import SCons.Util
import SCons.Script
# Disable injecting tools into default namespace
SCons.Defaults.DefaultEnvironment(tools = [])
def message(program, msg: str):
print(f'{program.program_message_prefix}: {msg}')
def get_Werror_sequence(active_cxxflags: list[str], warning_flags: collections.abc.Sequence[str]) -> list[str]:
# The leading -W is passed in each element in warning_flags so that if
# -Werror is already set, the warning_flags can be returned as-is. This
# also means that the warning flag is written in the caller as it will be
# on the command line, so users who grep for `-Wfoo` will find where
# `-Wfoo` is set. If the `-W` were composed in this function and the
# caller passed `foo`, then a search for `-Wfoo` would find nothing.
if active_cxxflags and '-Werror' in active_cxxflags:
# Make both paths return a Python list.
return list(warning_flags)
# When an option is converted to `-Werror=foo` form, the leading `-W` from
# the caller must be stripped off to avoid producing `-Werror=-Wfoo`.
return [f'-Werror={warning[2:]}' for warning in warning_flags]
class StaticSubprocess:
# This class contains utility functions for calling subprocesses
# that are expected to return the same output for every call. The
# output is cached after the first call, so that callers can request
# the output again later without causing the program to be run again.
#
# Suitable programs are not required to depend solely on the
# parameters, but are assumed to depend only on state that is
# unlikely to change in the brief time that SConstruct runs. For
# example, a tool might be upgraded by the system administrator,
# changing its version string. However, we assume nobody upgrades
# their tools in the middle of an SConstruct run. Results are not
# cached to persistent storage, so an upgrade performed after one
# SConstruct run, but before the next, will not cause any
# inconsistencies.
shlex_split = shlex.split
@dataclass(eq=False)
class CachedCall:
out: bytes
err: bytes
returncode: int
@dataclass(eq=False)
class CachedVersionCall:
version_head: str
def __init__(self, out: bytes, err: bytes, returncode: int):
oe = out or err
self.version_head = oe.splitlines()[0].decode() if not returncode and oe else None
# @staticmethod delayed so that default arguments pick up the
# undecorated form.
def pcall(args: list[bytes | str], stderr=None, CachedCall=CachedCall, _call_cache: dict[str, CachedCall]={}) -> CachedCall:
# Use repr since callers may construct the same argument
# list independently.
## >>> a = ['git', '--version']
## >>> b = ['git', '--version']
## >>> a is b
## False
## >>> id(a) == id(b)
## False
## >>> a == b
## True
## >>> repr(a) == repr(b)
## True
a = repr(args)
c = _call_cache.get(a)
if c is not None:
return c
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr)
(o, e) = p.communicate()
_call_cache[a] = c = CachedCall(o, e, p.wait())
return c
def qcall(args: str, stderr=None, _pcall=pcall, _shlex_split=shlex_split) -> CachedCall:
return _pcall(_shlex_split(args),stderr)
@classmethod
def get_version_head(cls, cmd: bytes | str, _pcall=pcall, _shlex_split=shlex_split) -> str:
# If cmd is bytes, then it is output from a program and should
# not be reparsed.
return _pcall(([cmd] if isinstance(cmd, bytes) else _shlex_split(cmd)) + ['--version'], stderr=subprocess.PIPE, CachedCall=cls.CachedVersionCall).version_head
pcall = staticmethod(pcall)
qcall = staticmethod(qcall)
shlex_split = staticmethod(shlex_split)
class ToolchainInformation(StaticSubprocess):
@staticmethod
def get_tool_path(env: SCons.Environment, tool: str, _qcall=StaticSubprocess.qcall):
# Include $LINKFLAGS since -fuse-ld=gold influences the path
# printed for the linker.
tool = env.subst(f'$CXX $CXXFLAGS $LINKFLAGS -print-prog-name={tool}')
return tool, _qcall(tool).out.strip()
@staticmethod
def show_partial_environ(env: SCons.Environment, user_settings, f: collections.abc.Callable[[str], None], msgprefix: str, append_newline='\n'):
f(f'{msgprefix}: CHOST: {(user_settings.CHOST)!r}{append_newline}')
for v in (
'CXX',
'CPPDEFINES',
'CPPPATH',
'CPPFLAGS',
'CXXFLAGS',
'LIBS',
'LINKFLAGS',
) + (
(
'RC',
'RCFLAGS',
) if user_settings.host_platform == 'win32' else (
'FRAMEWORKPATH',
'FRAMEWORKS',
) if user_settings.host_platform == 'darwin' else (
)
):
f(f'{msgprefix}: {v}: {(env.get(v, None))!r}{append_newline}')
penv = env['ENV']
for v in (
'CCACHE_PREFIX',
'DISTCC_HOSTS',
):
f(f'{msgprefix}: ${v}: {(penv.get(v, None))!r}{append_newline}')
class Git(StaticSubprocess):
@dataclass(eq=False)
class ComputedExtraVersion:
describe: str
status: str
diffstat_HEAD: str
revparse_HEAD: str
__slots__ = ('describe', 'status', 'diffstat_HEAD', 'revparse_HEAD')
UnknownExtraVersion = (
# If the string is alphanumeric, then `git archive` has rewritten the
# string to be a commit ID. Use that commit ID as a guessed default
# when Git is not available to resolve a current commit ID.
ComputedExtraVersion('$Format:%(describe:tags,abbrev=12)$', None, None, 'archive_$Format:%H$') if '$Format:%H$'.isalnum() else
# Otherwise, assume that this is a checked-in copy.
ComputedExtraVersion(None, None, None, None)
)
# None until computed, then ComputedExtraVersion once cached.
__computed_extra_version: typing.ClassVar[None | ComputedExtraVersion] = None
__path_git: typing.ClassVar[None | list[str]] = None
# `__pcall_missing_git`, `__pcall_found_git`, and `pcall` must have
# compatible signatures. In any given run, there will be at most
# one call to `pcall`, which then patches itself out of the call
# chain. A run will call either __pcall_missing_git or
# __pcall_found_git (depending on whether $GIT is blank), but never
# both in the same run.
@classmethod
def __pcall_missing_git(cls,args,stderr=None,_missing_git=StaticSubprocess.CachedCall(None, None, 1)):
return _missing_git
@classmethod
def __pcall_found_git(cls,args,stderr=None,_pcall=StaticSubprocess.pcall):
return _pcall(cls.__path_git + args, stderr=stderr)
@classmethod
def pcall(cls,args,stderr=None):
git = cls.__path_git
if git is None:
cls.__path_git = git = cls.shlex_split(os.environ.get('GIT', 'git'))
cls.pcall = f = cls.__pcall_found_git if git else cls.__pcall_missing_git
return f(args, stderr)
def spcall(cls,args,stderr=None):
g = cls.pcall(args, stderr)
if g.returncode:
return None
return g.out
@classmethod
def compute_extra_version(cls, _spcall=spcall) -> ComputedExtraVersion:
c = cls.__computed_extra_version
if c is None:
v = cls.__compute_extra_version()
cls.__computed_extra_version = c = cls.ComputedExtraVersion(
v,
_spcall(cls, ['status', '--short', '--branch']).decode(),
_spcall(cls, ['diff', '--stat', 'HEAD']).decode(),
_spcall(cls, ['rev-parse', 'HEAD']).rstrip().decode(),
) if v is not None else cls.UnknownExtraVersion
return c
# Run `git describe --tags --abbrev=12`.
# On failure, return None.
# On success, return a string containing:
# first line of output of describe
# '*' if there are unstaged changes else ''
# '+' if there are staged changes else ''
@classmethod
def __compute_extra_version(cls) -> None | str:
try:
g = cls.pcall(['describe', '--tags', '--abbrev=12'], stderr=subprocess.PIPE)
except OSError as e:
if e.errno == errno.ENOENT:
return None
raise
if g.returncode:
return None
_pcall = cls.pcall
return (g.out.splitlines()[0] + \
(b'*' if _pcall(['diff', '--quiet']).returncode else b'') + \
(b'+' if _pcall(['diff', '--quiet', '--cached']).returncode else b'')
).decode()
class _ConfigureTests:
@dataclass(eq=False)
class Collector:
record: collections.abc.Callable[['ConfigureTest'], None]
@dataclass(eq=False, slots=True)
class RecordedTest:
name: str
desc: str
# predicate is a sequence of zero-or-more functions that take a
# UserSettings object as the only argument. A recorded test is
# only passed to the SConf logic if at most zero predicates return
# a false-like value.
#
# Callers use this to exclude from execution tests which make no
# sense in the current environment, such as a Windows-specific test
# when building for a Linux target.
predicate: tuple[collections.abc.Callable[['UserSettings'], bool]] = ()
def __call__(self, f: collections.abc.Callable) -> collections.abc.Callable:
desc = None
doc = getattr(f, '__doc__', None)
if doc is not None:
doc = doc.rstrip().splitlines()
if doc and doc[-1].startswith("help:"):
desc = doc[-1][5:]
self.record(self.RecordedTest(f.__name__, desc))
return f
class ConfigureTests(_ConfigureTests):
class Collector(_ConfigureTests.Collector):
def __init__(self):
# An unguarded collector maintains a list of tests, and adds
# to the list as the decorator is called on individual
# functions.
self.tests = tests = []
super().__init__(tests.append)
class GuardedCollector(_ConfigureTests.Collector):
def __init__(self,collector,guard):
# A guarded collector delegates to the list maintained by
# the input collector, instead of keeping a list of its own.
super().__init__(collector.record)
# `guard` is a single function, but the predicate handling
# expects a sequence of functions, so store a single-element
# tuple.
self.__guard = guard,
self.__RecordedTest = collector.RecordedTest
def RecordedTest(self, name, desc, predicate=()):
# Record a test with both the guard of this GuardedCollector
# and any guards from the input collector objects, which may
# in turn be instances of GuardedCollector with predicates
# of their own.
return self.__RecordedTest(name, desc, self.__guard + predicate)
class CxxRequiredFeature:
__slots__ = ('main', 'name', 'text')
def __init__(self, name: str, text: str, main: str = ''):
self.name = name
# Avoid generating consecutive underscores if the input
# string has multiple adjacent unacceptable characters.
# Pass alphanumeric characters through as-is. Escape
# non-alphanumeric by converting them to the hexadecimal
# representation of their ordinal value.
name = {'N' : f'test_{"".join(c if c.isalnum() else f"_{(ord(c)):x}" for c in name)}'}
self.text = text % name
self.main = f'{{{(main % name)}}}\n' if main else ''
class Cxx11RequiredFeature(CxxRequiredFeature):
std = 11
class Cxx14RequiredFeature(CxxRequiredFeature):
std = 14
class Cxx17RequiredFeature(CxxRequiredFeature):
std = 17
class Cxx20RequiredFeature(CxxRequiredFeature):
std = 20
class CxxRequiredFeatures:
__slots__ = ('features', 'main', 'text')
def __init__(self, features: list['CxxRequiredFeature']):
self.features = features
s = '/* C++{} {} */\n{}'.format
self.main = '\n'.join((s(f.std, f.name, f.main) for f in features if f.main))
self.text = '\n'.join((s(f.std, f.name, f.text) for f in features if f.text))
class PCHAction:
def __init__(self,context):
self._context = context
def __call__(self,text,ext):
# Ignore caller-supplied text, since _Test always includes a
# definition of main(). Using the caller-supplied text
# would provide one main() in the PCH and another in the
# test which includes the PCH.
env = self._context.env
s = env['OBJSUFFIX']
env['OBJSUFFIX'] = '.h.gch'
result = self._context.TryCompile('''
/* Define this here. Use it in the file which includes the PCH. If the
* compiler skips including the PCH, and does not fail for that reason
* alone, then it will fail when the symbol is used in the later test,
* since the only definition comes from the PCH.
*/
#define dxx_compiler_supports_pch
''', ext)
env['OBJSUFFIX'] = s
return result
class PreservedEnvironment:
# One empty list for all the defaults. The comprehension
# creates copies, so it is safe for the default value to be
# shared.
def __init__(self, env: SCons.Environment, keyviews, _l=[]):
self.flags = {k: env.get(k, _l).copy() for k in itertools.chain.from_iterable(keyviews)}
def restore(self, env: SCons.Environment):
env.Replace(**self.flags)
def __getitem__(self, name: str):
return self.flags.__getitem__(name)
class ForceVerboseLog(PreservedEnvironment):
def __init__(self, env: SCons.Environment):
# Force verbose output to sconf.log
self.flags = {}
for k in (
'CXXCOMSTR',
'LINKCOMSTR',
):
try:
# env is like a dict, but does not have .pop(), so
# emulate it with a lookup + delete.
self.flags[k] = env[k]
del env[k]
except KeyError:
pass
class pkgconfig:
def _get_pkg_config_exec_path(context,msgprefix,pkgconfig):
Display = context.Display
if not pkgconfig:
Display(f'{msgprefix}: pkg-config disabled by user settings\n')
return pkgconfig
if os.sep in pkgconfig:
# Split early, so that the user can pass a command with
# arguments. Convert to tuple so that the value is not
# modified later.
pkgconfig = tuple(StaticSubprocess.shlex_split(pkgconfig))
Display(f'{msgprefix}: using pkg-config at user specified path {pkgconfig!r}\n')
return pkgconfig
join = os.path.join
# No path specified, search in $PATH
for p in os.environ.get('PATH', '').split(os.pathsep):
fp = join(p, pkgconfig)
try:
os.close(os.open(fp, os.O_RDONLY))
except OSError as e:
# Ignore on permission errors. If pkg-config is
# runnable but not readable, the user must
# specify its path.
if e.errno == errno.ENOENT or e.errno == errno.EACCES:
continue
raise
Display(f'{msgprefix}: using pkg-config at discovered path {fp}\n')
return (fp,)
Display(f'{msgprefix}: no usable pkg-config {pkgconfig!r} found in $PATH\n')
def __get_pkg_config_path(context,message,user_settings,display_name,
_get_pkg_config_exec_path=_get_pkg_config_exec_path,
_cache={}):
pkgconfig = user_settings.PKG_CONFIG
if pkgconfig is None:
CHOST = user_settings.CHOST
pkgconfig = f'{CHOST}-pkg-config' if CHOST else 'pkg-config'
if sys.platform == 'win32':
pkgconfig += '.exe'
path = _cache.get(pkgconfig, _cache)
if path is _cache:
_cache[pkgconfig] = path = _get_pkg_config_exec_path(context, message, pkgconfig)
return path
@staticmethod
def merge(context,message,user_settings,pkgconfig_name,display_name,
guess_flags,
__get_pkg_config_path=__get_pkg_config_path,
_cache={}):
Display = context.Display
Display(f'{message}: checking {display_name} pkg-config {pkgconfig_name}\n')
pkgconfig = __get_pkg_config_path(context, message, user_settings, display_name)
if not pkgconfig:
Display(f'{message}: skipping {display_name} pkg-config; using default flags {guess_flags!r}\n')
return guess_flags
cmd = pkgconfig + ('--cflags', '--libs', pkgconfig_name)
flags = _cache.get(cmd, None)
if flags is not None:
Display(f'{message}: reusing {display_name} settings from `{shlex.join(cmd)}`: {flags!r}\n')
return flags
mv_cmd = pkgconfig + ('--modversion', pkgconfig_name)
try:
Display(f'{message}: reading {pkgconfig_name} version from `{shlex.join(mv_cmd)}`\n')
v = StaticSubprocess.pcall(mv_cmd, stderr=subprocess.PIPE)
if v.err:
for l in v.err.splitlines():
Display(f'{message}: pkg-config error: {display_name}: {l.decode()}\n')
if v.returncode:
Display(f'{message}: pkg-config failed: {display_name}: {v.returncode}; using default flags {guess_flags!r}\n')
return guess_flags
if v.out:
displayed_version = v.out.splitlines()[0]
try:
displayed_version = displayed_version.decode()
except UnicodeDecodeError:
pass
Display(f'{message}: {display_name} version: {displayed_version!r}\n')
except OSError as o:
Display(f'''{message}: failed with error {repr(o.message) if o.errno is None else f'{o.errno} ("{o.strerror}")'}; using default flags for {pkgconfig_name!r}: {guess_flags!r}\n''')
flags = guess_flags
else:
Display(f'{message}: reading {display_name} settings from `{shlex.join(cmd)}`\n')
try:
v = StaticSubprocess.pcall(cmd, stderr=subprocess.PIPE)
if v.err:
for l in v.err.splitlines():
Display(f'{message}: pkg-config error: {display_name}: {l.decode()}\n')
if v.returncode:
Display(f'{message}: pkg-config failed: {display_name}: {v.returncode}; using default flags {guess_flags!r}\n')
return guess_flags
out = v.out
flags = {
k:v for k,v in context.env.ParseFlags(' ' + out.decode()).items()
if v and (k[0] in 'CL')
}
Display(f'{message}: {display_name} settings: {flags!r}\n')
# Write the full output to the SCons log for later review.
# Omit it from `Display` since it is rarely necessary to
# see it during the build.
context.Log(f'{message}: {display_name} settings full output: {out!r}\n')
except OSError as o:
Display(f'''{message}: failed with error {repr(o.message) if o.errno is None else f'{o.errno} ("{o.strerror}")'}; using default flags for {pkgconfig_name!r}: {guess_flags!r}\n''')
flags = guess_flags
_cache[cmd] = flags
return flags
# Force test to report failure
sconf_force_failure = 'force-failure'
# Force test to report success, and modify flags like it
# succeeded
sconf_force_success = 'force-success'
# Force test to report success, do not modify flags
sconf_assume_success = 'assume-success'
expect_sconf_success = 'success'
expect_sconf_failure = 'failure'
_implicit_test = Collector()
_custom_test = Collector()
_guarded_test_windows = GuardedCollector(_custom_test, lambda user_settings: user_settings.host_platform == 'win32')
_guarded_test_darwin = GuardedCollector(_custom_test, lambda user_settings: user_settings.host_platform == 'darwin')
implicit_tests = _implicit_test.tests
custom_tests = _custom_test.tests
comment_not_supported = '/* not supported */'
__python_import_struct = None
_cxx_conformance_cxx20 = 20
__cxx_std_required_features = CxxRequiredFeatures([
# As of this writing, <gcc-12 is already unsupported, but some
# platforms, such as Ubuntu 22.04, still try to use gcc-11 by default.
# Use this test both to verify that Class Template Argument Deduction
# is generally supported, since it is used in the game, and to exclude
# an unsupported compiler that does not accept CTAD in one of the
# contexts the game uses.
Cxx20RequiredFeature('class template argument deduction', '''
struct Outer_%(N)s
{
template <typename byte_type>
struct Inner
{
constexpr Inner(byte_type &)
{
}
};
/* <gcc-12 does not allow declaring a deduction guide in the immediately
* enclosing scope:
```
error: deduction guide 'Outer_test_class_20template_20argument
_20deduction::Inner(byte_type&) -> Outer_test_class_20template_20argument_20deduction::Inner<byte_type>' must be declared at namespace scope
```
*/
template <typename byte_type>
Inner(byte_type &) -> Inner<byte_type>;
};
'''),
Cxx20RequiredFeature('explicitly defaulted operator==', '''
struct A_%(N)s
{
int a;
constexpr bool operator==(const A_%(N)s &) const = default;
};
''',
'''
constexpr A_%(N)s a1{0};
constexpr A_%(N)s a2{0};
static_assert(a1 == a2);
static_assert(!(a1 != a2));
'''),
Cxx20RequiredFeature('requires clause', '''
template <typename T>
requires(sizeof(T) >= 1)
void f_%(N)s(T)
{
}
''',
'''
f_%(N)s('a');
'''),
Cxx20RequiredFeature('std::span', '''
#include <span>
void sd_%(N)s(std::span<const char>);
void ss_%(N)s(std::span<const char, 2>);
void sd_%(N)s(std::span<const char>)
{
}
void ss_%(N)s(std::span<const char, 2>)
{
}
''',
'''
sd_%(N)s("ab");
ss_%(N)s("a");
'''),
Cxx17RequiredFeature('constexpr if', '''
template <bool b>
int f_%(N)s()
{
if constexpr (b)
return 1;
else
return 0;
}
''',
'''
f_%(N)s<false>();
'''),
Cxx17RequiredFeature('fold expressions', '''
static inline void g_%(N)s(int) {}
template <int... i>
void f_%(N)s()
{
(g_%(N)s(i), ...);
(g_%(N)s(i), ..., (void)0);
((void)0, ..., g_%(N)s(i));
}
''',
'''
f_%(N)s<0, 1, 2, 3>();
'''),
Cxx17RequiredFeature('structured binding declarations', '',
'''
int a_%(N)s[2] = {0, 1};
auto &&[b_%(N)s, c_%(N)s] = a_%(N)s;
(void)b_%(N)s;
(void)c_%(N)s;
'''),
Cxx17RequiredFeature('attribute [[fallthrough]]', '''
static inline void f_%(N)s() {}
''',
'''
switch (argc)
{
case 1:
f_%(N)s();
[[fallthrough]];
case 2:
f_%(N)s();
break;
}
'''),
Cxx17RequiredFeature('attribute [[nodiscard]]', '''
[[nodiscard]]
static int f_%(N)s()
{
return 0;
}
''',
'''
auto i_%(N)s = f_%(N)s();
(void)i_%(N)s;
'''),
Cxx14RequiredFeature('template variables', '''
template <unsigned U_%(N)s>
int a_%(N)s = U_%(N)s + 1;
''', ''),
Cxx14RequiredFeature('std::exchange', '''
#include <utility>
''', '''
argc |= std::exchange(argc, 5);
'''),
Cxx14RequiredFeature('std::index_sequence', '''
#include <utility>
''', '''
std::integer_sequence<int, 0> integer_%(N)s = std::make_integer_sequence<int, 1>();
(void)integer_%(N)s;
std::index_sequence<0> index_%(N)s = std::make_index_sequence<1>();
(void)index_%(N)s;
'''),
Cxx14RequiredFeature('std::make_unique', '''
#include <memory>
''', '''
std::make_unique<int>(0);
std::make_unique<int[]>(1);
'''),
Cxx11RequiredFeature('std::addressof', '''
#include <memory>
''', '''
struct A_%(N)s
{
void operator&() = delete;
};
A_%(N)s i_%(N)s;
(void)std::addressof(i_%(N)s);
'''),
Cxx11RequiredFeature('constexpr', '''
struct %(N)s {};
static constexpr %(N)s get_%(N)s(){return {};}
''', '''
get_%(N)s();
'''),
Cxx11RequiredFeature('nullptr', '''
#include <cstddef>
std::nullptr_t %(N)s1 = nullptr;
int *%(N)s2 = nullptr;
''', '''
%(N)s2 = %(N)s1;
'''),
Cxx11RequiredFeature('explicit operator bool', '''
struct %(N)s {
explicit operator bool();
};
'''),
Cxx11RequiredFeature('explicitly deleted functions', '''
void b_%(N)s(int c) = delete;
''', '''
struct A_%(N)s
{
void a(int b) = delete;
};
A_%(N)s i_%(N)s;
(void)i_%(N)s;
'''),
Cxx11RequiredFeature('template aliases', '''
using %(N)s_typedef = int;
template <typename>
struct %(N)s_struct;
template <typename T>
using %(N)s_alias = %(N)s_struct<T>;
''', '''
%(N)s_struct<int> *a = nullptr;
%(N)s_alias<int> *b = a;
%(N)s_typedef *c = nullptr;
(void)b;
(void)c;
'''),
Cxx11RequiredFeature('trailing function return type', '''
auto %(N)s()->int;
'''),
Cxx11RequiredFeature('class scope static constexpr assignment', '''
struct %(N)s_instance {
};
struct %(N)s_container {
static constexpr %(N)s_instance a = {};
};
'''),
Cxx11RequiredFeature('braced base class initialization', '''
struct %(N)s_base {
int a;
};
struct %(N)s_derived : %(N)s_base {
%(N)s_derived(int e) : %(N)s_base{e} {}
};
'''),
Cxx11RequiredFeature('std::array', '''
#include <array>
''', '''
std::array<int,2>b;
b[0]=1;
'''
),
Cxx11RequiredFeature('std::begin(), std::end()', '''
#include <array>
''', f'''
char ac[1];
std::array<char, 1> as;
{(''.join([f""" {{
auto s = std::{f}({a});
(void)s;
}}
""" for f in ('begin', 'end') for a in ('ac', 'as')]
)
)}
'''),
Cxx11RequiredFeature('range-based for', '''
#include "compiler-range_for.h"
''', '''
int b[2];
range_for(int&c,b)c=0;
'''
),
Cxx11RequiredFeature('<type_traits>', '''
#include <type_traits>
''', '''
typename std::conditional<sizeof(argc) == sizeof(int),int,long>::type a = 0;
typename std::conditional<sizeof(argc) != sizeof(int),int,long>::type b = 0;
(void)a;
(void)b;
'''
),
Cxx11RequiredFeature('std::unordered_map::emplace', '''
#include <unordered_map>
''', '''
std::unordered_map<int,int> m;
m.emplace(0, 0);
'''
),
Cxx11RequiredFeature('reference qualified methods', '''
struct %(N)s {
int a()const &{return 1;}
int a()const &&{return 2;}
};
''', '''
%(N)s a;
auto b = a.a() != %(N)s().a();
(void)b;
'''
),
Cxx11RequiredFeature('inheriting constructors', '''
/* Test for bug where clang + libc++ + constructor inheritance causes a
* compilation failure when returning nullptr.
*
* Works: gcc
* Works: clang + gcc libstdc++
* Works: old clang + old libc++ (cutoff date unknown).
* Works: new clang + new libc++ + unique_ptr<T>
* Fails: new clang + new libc++ + unique_ptr<T[]> (v3.6.0 confirmed broken).
memory:2676:32: error: no type named 'type' in 'std::__1::enable_if<false, std::__1::unique_ptr<int [], std::__1::default_delete<int []> >::__nat>'; 'enable_if' cannot be used to disable this declaration
typename enable_if<__same_or_less_cv_qualified<_Pp, pointer>::value, __nat>::type = __nat()) _NOEXCEPT
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.sconf_temp/conftest_43.cpp:26:11: note: in instantiation of member function 'std::__1::unique_ptr<int [], std::__1::default_delete<int []> >::unique_ptr' requested here
using B::B;
^
.sconf_temp/conftest_43.cpp:30:2: note: while substituting deduced template arguments into function template 'I' [with _Pp = I]
return nullptr;
^
*/
#include <memory>
class I%(N)s : std::unique_ptr<int[]>
{
public:
typedef std::unique_ptr<int[]> b%(N)s;
using b%(N)s::b%(N)s;
};
I%(N)s a%(N)s();
I%(N)s a%(N)s()
{
return nullptr;
}
''', '''
I%(N)s i = a%(N)s();
(void)i;
'''
),
])
def __init__(self,msgprefix,user_settings,platform_settings):
self.msgprefix = msgprefix
self.user_settings = user_settings
self.platform_settings = platform_settings
self.successful_flags = defaultdict(list)
self._sconf_results = []
self.__tool_versions = []
self.__defined_macros = ''
# Some tests check the functionality of the compiler's
# optimizer.
#
# When LTO is used, the optimizer is deferred to link time.
# Force all tests to be Link tests when LTO is enabled.
self.Compile = self.Link if user_settings.lto else self._Compile
self.custom_tests = [t for t in self.custom_tests if all(predicate(user_settings) for predicate in t.predicate)]
def _quote_macro_value(v):
return v.strip().replace('\n', ' \\\n')
def _check_sconf_forced(self,calling_function):
return self._check_forced(calling_function), self._check_expected(calling_function)
@staticmethod
def _find_calling_sconf_function():
try:
1//0
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back.f_back
while frame is not None:
co_name = frame.f_code.co_name
if co_name[:6] == 'check_':
return co_name[6:]
frame = frame.f_back
# This assertion is hit if a test is asked to deduce its caller
# (calling_function=None), but no function in the call stack appears to
# be a checking function.
assert False, "SConf caller not specified and no acceptable caller in stack."
def _check_forced(self,name):
# This getattr will raise AttributeError if called for a function which
# is not a registered test. Tests must be registered as an implicit
# test (in implicit_tests, usually by applying the @_implicit_test
# decorator) or a custom test (in custom_tests, usually by applying the
# @_custom_test decorator).
#
# Unregistered tests are never documented and cannot be overridden by
# the user.
return getattr(self.user_settings, f'sconf_{name}')
def _check_expected(self,name):
# The remarks for _check_forced apply here too.
r = getattr(self.user_settings, f'expect_sconf_{name}')
if r is not None:
if r == self.expect_sconf_success:
return 1
if r == self.expect_sconf_failure:
return 0
return r
def _check_macro(self,context,macro_name,macro_value,test,_comment_not_supported=comment_not_supported,**kwargs):
r = self.Compile(context, text=f'''
#define {macro_name} {macro_value}
{test}
''', **kwargs)
if not r:
macro_value = _comment_not_supported
self._define_macro(context, macro_name, macro_value)
def _define_macro(self,context,macro_name,macro_value):
context.sconf.Define(macro_name, macro_value)
self.__defined_macros += f'#define {macro_name} {macro_value}\n'
implicit_tests.append(_implicit_test.RecordedTest('check_ccache_distcc_ld_works', "assume ccache, distcc, C++ compiler, and C++ linker work"))
implicit_tests.append(_implicit_test.RecordedTest('check_ccache_ld_works', "assume ccache, C++ compiler, and C++ linker work"))
implicit_tests.append(_implicit_test.RecordedTest('check_distcc_ld_works', "assume distcc, C++ compiler, and C++ linker work"))
implicit_tests.append(_implicit_test.RecordedTest('check_ld_works', "assume C++ compiler and linker work"))
implicit_tests.append(_implicit_test.RecordedTest('check_ld_blank_libs_works', "assume C++ compiler and linker work with empty $LIBS"))
implicit_tests.append(_implicit_test.RecordedTest('check_ld_blank_libs_ldflags_works', "assume C++ compiler and linker work with empty $LIBS and empty $LDFLAGS"))
implicit_tests.append(_implicit_test.RecordedTest('check_cxx_blank_cxxflags_works', "assume C++ compiler works with empty $CXXFLAGS"))
# This must be the first custom test. This test verifies the compiler
# works and disables any use of ccache/distcc for the duration of the
# configure run.
#
# SCons caches configuration results and tests are usually very small, so
# ccache will provide limited benefit.
#
# Some tests are expected to raise a compiler error. If distcc is used
# and DISTCC_FALLBACK prevents local retries, then distcc interprets a
# compiler error as an indication that the volunteer which served that
# compile is broken and should be blacklisted. Suppress use of distcc for
# all tests to avoid spurious blacklist entries.
#
# During the main build, compiling remotely can allow more jobs to run in
# parallel. Tests are serialized by SCons, so distcc is helpful during
# testing only if compiling remotely is faster than compiling locally.
# This may be true for embedded systems that distcc to desktops, but will
# not be true for desktops or laptops that distcc to similar sized
# machines.
@_custom_test
def check_cxx_works(self,context):
"""
help:assume C++ compiler works
"""
# Use !r to print the tuple in an unambiguous form.
context.Log(f'scons: dxx: version: {(Git.compute_extra_version(),)!r}\n')
cenv = context.env
penv = cenv['ENV']
self.__cxx_com_prefix = cenv['CXXCOM']
# Require ccache to run the next stage, but allow it to write the
# result to cache. This lets the test validate that ccache fails for
# an unusable CCACHE_DIR and also validate that the next stage handles
# the input correctly. Without this, a cached result may hide that
# the next stage compiler (or wrapper) worked when a prior run
# performed the test, but is now broken.
CCACHE_RECACHE = penv.get('CCACHE_RECACHE', None)
penv['CCACHE_RECACHE'] = '1'
most_recent_error = self._check_cxx_works(context)
if most_recent_error is not None:
raise SCons.Errors.StopError(most_recent_error)
if CCACHE_RECACHE is None:
del penv['CCACHE_RECACHE']
else:
penv['CCACHE_RECACHE'] = CCACHE_RECACHE
# If ccache/distcc are in use, disable them during testing.
# This assignment is also done in _check_cxx_works, but only on an
# error path. Repeat it here so that it is effective on the success
# path. It cannot be moved above the call to _check_cxx_works because
# some tests in _check_cxx_works rely on its original value.
cenv['CXXCOM'] = cenv._dxx_cxxcom_no_prefix
self._check_cxx_conformance_level(context)
def _show_tool_version(self,context,tool,desc,save_tool_version=True):
# These version results are not used for anything, but are
# collected here so that users who post only a build log will
# still supply at least some useful information.
#
# This is split into two lines so that the first line is printed
# before the function call required to format the string for the
# second line.
Display = context.Display
Display(f'{self.msgprefix}: checking version of {desc} {tool!r} ... ')
try:
v = StaticSubprocess.get_version_head(tool)
except OSError as e:
if e.errno == errno.ENOENT or e.errno == errno.EACCES:
Display(f'error: {e.strerror}\n')
raise SCons.Errors.StopError(f'Failed to run {tool!r}.')
raise
if save_tool_version:
self.__tool_versions.append((tool, v))
Display(f'{v!r}\n')
def _show_indirect_tool_version(self,context,CXX,tool,desc):
Display = context.Display
Display(f'{self.msgprefix}: checking path to {desc} ... ')
tool, name = ToolchainInformation.get_tool_path(context.env, tool)
self.__tool_versions.append((tool, name))
if not name:
# Strange, but not fatal for this to fail.
Display(f'! {name!r}\n')
return
Display(f'{name!r}\n')
self._show_tool_version(context,name,desc)
def _check_cxx_works(self,context,_crc32=binascii.crc32):
# Test whether the compiler+linker+optional wrapper(s) work. If
# anything fails, a StopError is guaranteed on return. However, to
# help the user, this function pushes through all the combinations and
# reports the StopError for the least complicated issue. If both the
# compiler and the linker fail, the compiler will be reported, since
# the linker might work once the compiler is fixed.
#
# If a test fails, then the pending StopError allows this function to
# safely modify the construction environment and process environment
# without reverting its changes.
most_recent_error = None
Link = self.Link
cenv = context.env
user_settings = self.user_settings
use_distcc = user_settings.distcc
use_ccache = user_settings.ccache
text = '''
/* When compiling using gcc, defining a virtual function requires linking to a
* symbol from gcc libstdc++. If the linker is `gcc`, rather than `g++`, (which
* can happen if the user sets `CXX=gcc`), then libstdc++ is not linked, and the
* build fails with an error like:
```
undefined reference to `vtable for __cxxabiv1::__class_type_info'
```
* Test for that combination here, so that the test will report that the C++
* linker does not work, rather than waiting for the user to get a link
* failure in the game binary at the end of the build.
*/
struct test_virtual_function_supported
{
virtual void a();
};
void test_virtual_function_supported::a() {}
'''
if user_settings.show_tool_version:
CXX = cenv['CXX']
self._show_tool_version(context, CXX, 'C++ compiler')
if user_settings.show_assembler_version:
self._show_indirect_tool_version(context, CXX, 'as', 'assembler')
if user_settings.show_linker_version:
self._show_indirect_tool_version(context, CXX, 'ld', 'linker')
if use_distcc:
self._show_tool_version(context, use_distcc, 'distcc', False)
if use_ccache:
self._show_tool_version(context, use_ccache, 'ccache', False)
# Use C++ single line comment so that it is guaranteed to extend
# to the end of the line. repr ensures that embedded newlines
# will be escaped and that the final character will not be a
# backslash.
self.__commented_tool_versions = s = ''.join(f'// {tool!r} => {value!r}\n' for tool, value in self.__tool_versions)
self.__tool_versions = f'''
/* This test is always false. Use a non-trivial condition to
* discourage external text scanners from recognizing that the block
* is never compiled. This is intended to encourage SCons to generate a new
* test if any of the tools have changed their version identifier.
*/
#if 1 < -1
{_crc32(s.encode()):08x}
{s}
#endif
'''
ToolchainInformation.show_partial_environ(cenv, user_settings, context.Display, self.msgprefix)
if use_ccache:
if use_distcc:
if Link(context, text=text, msg='whether ccache, distcc, C++ compiler, and linker work', calling_function='ccache_distcc_ld_works'):