forked from dxx-rebirth/dxx-rebirth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SConstruct
5468 lines (5253 loc) · 213 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 base64
import binascii
import errno
import itertools
import subprocess
import sys
import os
import SCons.Util
# Disable injecting tools into default namespace
SCons.Defaults.DefaultEnvironment(tools = [])
try:
# Test whether the old Python 2 names exist.
# If the names are found, use the old Python 2 names, which return
# views on the data. If the names are not found, an exception is
# raised.
get_dictionary_key_view = dict.iterkeys
get_dictionary_item_view = dict.iteritems
get_dictionary_value_view = dict.itervalues
except AttributeError:
# Name not found. Use the new Python 3 names, which return views
# (at least until the Python maintainers decide to redefine the
# interface again).
get_dictionary_key_view = dict.keys
get_dictionary_item_view = dict.items
get_dictionary_value_view = dict.values
def message(program,msg):
print("%s: %s" % (program.program_message_prefix, msg))
def get_Werror_string(l):
if l and '-Werror' in l:
return '-W'
return '-Werror='
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.
from shlex import split as shlex_split
class CachedCall:
def __init__(self,out,err,returncode):
self.out = out
self.err = err
self.returncode = returncode
# @staticmethod delayed so that default arguments pick up the
# undecorated form.
def pcall(args,stderr=None,_call_cache={},_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,stderr=None,_pcall=pcall,_shlex_split=shlex_split):
return _pcall(_shlex_split(args),stderr)
@staticmethod
def get_version_head(cmd,_pcall=pcall,_shlex_split=shlex_split):
# If cmd is bytes, then it is output from a program and should
# not be reparsed.
v = _pcall(([cmd] if isinstance(cmd, bytes) else _shlex_split(cmd)) + ['--version'], stderr=subprocess.PIPE)
try:
return v.__version_head
except AttributeError:
v.__version_head = r = (v.out or v.err).splitlines()[0].decode() if not v.returncode and (v.out or v.err) else None
return r
pcall = staticmethod(pcall)
qcall = staticmethod(qcall)
shlex_split = staticmethod(shlex_split)
class ToolchainInformation(StaticSubprocess):
@staticmethod
def get_tool_path(env,tool,_qcall=StaticSubprocess.qcall):
# Include $LINKFLAGS since -fuse-ld=gold influences the path
# printed for the linker.
tool = env.subst('$CXX $CXXFLAGS $LINKFLAGS -print-prog-name=%s' % tool)
return tool, _qcall(tool).out.strip()
@staticmethod
def show_partial_environ(env, user_settings, f):
f("CHOST: %r" % (user_settings.CHOST,))
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("%s: %r" % (v, env.get(v, None)))
penv = env['ENV']
for v in (
'CCACHE_PREFIX',
'DISTCC_HOSTS',
):
f("$%s: %r" % (v, penv.get(v, None)))
class Git(StaticSubprocess):
__git_archive_export_commit = '$Format:%H$'
if len(__git_archive_export_commit) == 40:
# If the length is 40, 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.
__git_archive_export_commit = 'archive_{}'.format(__git_archive_export_commit)
else:
# Otherwise, assume that this is a checked-in copy.
__git_archive_export_commit = None
class ComputedExtraVersion(object):
__slots__ = ('describe', 'status', 'diffstat_HEAD', 'revparse_HEAD')
def __init__(self,describe,status,diffstat_HEAD,revparse_HEAD):
self.describe = describe
self.status = status
self.diffstat_HEAD = diffstat_HEAD
self.revparse_HEAD = revparse_HEAD
def __repr__(self):
return 'ComputedExtraVersion(%r,%r,%r,%r)' % (self.describe, self.status, self.diffstat_HEAD, self.revparse_HEAD)
UnknownExtraVersion = ComputedExtraVersion(None, None, None, __git_archive_export_commit)
# None when unset. Instance of ComputedExtraVersion once cached.
__computed_extra_version = None
__path_git = 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):
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):
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:
class Collector(object):
class RecordedTest(object):
__slots__ = ('desc', 'name', 'predicate')
def __init__(self,name,desc,predicate=None):
self.name = name
self.desc = desc
self.predicate = predicate
def __repr__(self):
return '_ConfigureTests.Collector.RecordedTest(%r, %r, %r)' % (self.name, self.desc, self.predicate)
def __init__(self,record):
self.record = record
def __call__(self,f):
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):
self.tests = tests = []
_ConfigureTests.Collector.__init__(self, tests.append)
class GuardedCollector(_ConfigureTests.Collector):
__RecordedTest = _ConfigureTests.Collector.RecordedTest
def __init__(self,collector,guard):
_ConfigureTests.Collector.__init__(self, collector.record)
self.__guard = guard
def RecordedTest(self,name,desc):
return self.__RecordedTest(name, desc, self.__guard)
class CxxRequiredFeature(object):
__slots__ = ('main', 'name', 'text')
def __init__(self,name,text,main=''):
self.name = name
name = {'N' : 'test_' + ''.join([c if c.isalnum() else '_' for c in name])}
self.text = text % name
self.main = ('{' + (main % name) + '}\n') if main else ''
class Cxx11RequiredFeature(CxxRequiredFeature):
std = 11
class Cxx14RequiredFeature(CxxRequiredFeature):
std = 14
class Cxx17RequiredFeature(CxxRequiredFeature):
std = 17
class CxxRequiredFeatures(object):
__slots__ = ('features', 'main', 'text')
def __init__(self,features):
self.features = features
s = '/* C++{} {} */\n{}'.format
self.main = '\n'.join((s(f.std, f.name, f.main) for f in features))
self.text = '\n'.join((s(f.std, f.name, f.text) for f in features))
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,keyviews,_l=[]):
self.flags = {k: env.get(k, _l)[:] for k in itertools.chain.from_iterable(keyviews)}
def restore(self,env):
env.Replace(**self.flags)
def __getitem__(self,name):
return self.flags.__getitem__(name)
class ForceVerboseLog(PreservedEnvironment):
def __init__(self,env):
# 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("%s: pkg-config disabled by user settings\n" % msgprefix)
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("%s: using pkg-config at user specified path %s\n" % (msgprefix, pkgconfig))
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("%s: using pkg-config at discovered path %s\n" % (msgprefix, fp))
return (fp,)
Display("%s: no usable pkg-config %r found in $PATH\n" % (msgprefix, pkgconfig))
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 = ('%s-pkg-config' % CHOST) 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("%s: checking %s pkg-config %s\n" % (message, display_name, pkgconfig_name))
pkgconfig = __get_pkg_config_path(context, message, user_settings, display_name)
if not pkgconfig:
Display("%s: skipping %s pkg-config; using default flags %r\n" % (message, display_name, guess_flags))
return guess_flags
cmd = pkgconfig + ('--cflags', '--libs', pkgconfig_name)
flags = _cache.get(cmd, None)
if flags is not None:
Display("%s: reusing %s settings from %s: %r\n" % (message, display_name, cmd, flags))
return flags
mv_cmd = pkgconfig + ('--modversion', pkgconfig_name)
try:
Display("%s: reading %s version from %s\n" % (message, pkgconfig_name, mv_cmd))
v = StaticSubprocess.pcall(mv_cmd)
if v.out:
Display("%s: %s version: %r\n" % (message, display_name, v.out.splitlines()[0]))
except OSError as o:
Display("%s: failed with error %s; using default flags for '%s': %r\n" % (message, repr(o.message) if o.errno is None else ('%u ("%s")' % (o.errno, o.strerror)), pkgconfig_name, guess_flags))
flags = guess_flags
else:
Display("%s: reading %s settings from %s\n" % (message, display_name, cmd))
try:
flags = {
k:v for k,v in get_dictionary_item_view(context.env.ParseFlags(' ' + StaticSubprocess.pcall(cmd).out.decode()))
if v and (k[0] in 'CL')
}
Display("%s: %s settings: %r\n" % (message, display_name, flags))
except OSError as o:
Display("%s: failed with error %s; using default flags for '%s': %r\n" % (message, repr(o.message) if o.errno is None else ('%u ("%s")' % (o.errno, o.strerror)), pkgconfig_name, guess_flags))
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')
implicit_tests = _implicit_test.tests
custom_tests = _custom_test.tests
comment_not_supported = '/* not supported */'
__python_import_struct = None
_cxx_conformance_cxx17 = 17
__cxx_std_required_features = CxxRequiredFeatures([
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;
'''),
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('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>
''', '''
char ac[1];
std::array<char, 1> as;
%s
''' % (''.join(['''
auto %(i)s = std::%(f)s(%(a)s);
(void)%(i)s;
''' % {'i' : 'i%s%s' % (f, a), 'f' : f, 'a' : a} 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;
'''
),
])
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 t.predicate is None or t.predicate(user_settings)]
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, 'sconf_%s' % name)
def _check_expected(self,name):
# The remarks for _check_forced apply here too.
r = getattr(self.user_settings, 'expect_sconf_%s' % 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="""
#define {macro_name} {macro_value}
{test}
""".format(macro_name=macro_name, macro_value=macro_value, test=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 += '#define %s %s\n' % (macro_name, macro_value)
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('scons: dxx: version: %r\n' % (Git.compute_extra_version(),))
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('%s: checking version of %s %r ... ' % (self.msgprefix, desc, tool))
try:
v = StaticSubprocess.get_version_head(tool)
except OSError as e:
if e.errno == errno.ENOENT or e.errno == errno.EACCES:
Display('error: %s\n' % e.strerror)
raise SCons.Errors.StopError('Failed to run %r.' % tool)
raise
if save_tool_version:
self.__tool_versions.append((tool, v))
Display('%r\n' % v)
def _show_indirect_tool_version(self,context,CXX,tool,desc):
Display = context.Display
Display('%s: checking path to %s ... ' % (self.msgprefix, 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('! %r\n' % name)
return
Display('%r\n' % name)
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
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('// %r => %r\n' % (v[0], v[1]) for v in self.__tool_versions)
self.__tool_versions = '''
/* This test is always false. Use a non-trivial condition to
* discourage external text scanners from recognizing that the block
* is never compiled.
*/
#if 1 < -1
%.8x
%s
#endif
''' % (_crc32(s.encode()), s)
ToolchainInformation.show_partial_environ(cenv, user_settings, lambda s, _Display=context.Display, _msgprefix=self.msgprefix: _Display("%s:\t%s\n" % (_msgprefix, s)))
if use_ccache:
if use_distcc:
if Link(context, text='', msg='whether ccache, distcc, C++ compiler, and linker work', calling_function='ccache_distcc_ld_works'):
return
most_recent_error = 'ccache and C++ linker work, but distcc does not work.'
# Disable distcc so that the next call to self.Link tests only
# ccache+linker.
del cenv['ENV']['CCACHE_PREFIX']
if Link(context, text='', msg='whether ccache, C++ compiler, and linker work', calling_function='ccache_ld_works'):
return most_recent_error
most_recent_error = 'C++ linker works, but ccache does not work.'
elif use_distcc:
if Link(context, text='', msg='whether distcc, C++ compiler, and linker work', calling_function='distcc_ld_works'):
return
most_recent_error = 'C++ linker works, but distcc does not work.'
else:
# This assertion fails if the environment's $CXXCOM was modified
# to use a prefix, but both user_settings.ccache and
# user_settings.distcc evaluate to false.
assert cenv._dxx_cxxcom_no_prefix is cenv['CXXCOM'], "Unexpected prefix in $CXXCOM."
# If ccache/distcc are in use, then testing with one or both of them
# failed. Disable them so that the next test can check whether the
# local linker works.
#
# If they are not in use, this assignment is a no-op.
cenv['CXXCOM'] = cenv._dxx_cxxcom_no_prefix
if Link(context, text='', msg='whether C++ compiler and linker work', calling_function='ld_works'):
# If ccache or distcc are in use, this block is only reached
# when one or both of them failed. `most_recent_error` will
# be a description of the failure. If neither are in use,
# `most_recent_error` will be None.
return most_recent_error
# Force only compile, even if LTO is enabled.
elif self._Compile(context, text='', msg='whether C++ compiler works', calling_function='cxx_works'):
specified_LIBS = 'or ' if cenv.get('LIBS') else ''
if specified_LIBS:
cenv['LIBS'] = []
if Link(context, text='', msg='whether C++ compiler and linker work with blank $LIBS', calling_function='ld_blank_libs_works'):
# Using $LIBS="" allowed the test to succeed. $LIBS
# specifies one or more unusable libraries. Usually
# this is because it specifies a library which does
# not exist or is an incompatible architecture.
return 'C++ compiler works. C++ linker works with blank $LIBS. C++ linker does not work with specified $LIBS.'
if cenv['LINKFLAGS']:
cenv['LINKFLAGS'] = []
if Link(context, text='', msg='whether C++ compiler and linker work with blank $LIBS and blank $LDFLAGS', calling_function='ld_blank_libs_ldflags_works'):
# Using LINKFLAGS="" allowed the test to succeed.
# To avoid bloat, there is no further test to see
# whether the link will work with user-specified
# LIBS after LINKFLAGS is cleared. The user must
# fix at least one problem anyway. If the user is
# unlucky, fixing LINKFLAGS will result in a
# different error on the next run. If the user is
# lucky, fixing LINKFLAGS will allow the build to
# run.
return 'C++ compiler works. C++ linker works with blank $LIBS and blank $LDFLAGS. C++ linker does not work with blank $LIBS and specified $LDFLAGS.'
return 'C++ compiler works. C++ linker does not work with specified %(LIBS)sblank $LIBS and specified $LINKFLAGS. C++ linker does not work with blank $LIBS and blank $LINKFLAGS.' % {
'LIBS' : specified_LIBS,
}
else:
if cenv['CXXFLAGS']:
cenv['CXXFLAGS'] = []
if self._Compile(context, text='', msg='whether C++ compiler works with blank $CXXFLAGS', calling_function='cxx_blank_cxxflags_works'):
return 'C++ compiler works with blank $CXXFLAGS. C++ compiler does not work with specified $CXXFLAGS.'
return 'C++ compiler does not work.'
implicit_tests.append(_implicit_test.RecordedTest('check_cxx17', "assume C++ compiler supports C++17"))
__cxx_conformance_CXXFLAGS = [None]
def _check_cxx_conformance_level(self,context,_levels=(
# List standards in descending order of preference.
#
# C++17 is required, so list it last.
_cxx_conformance_cxx17,
), _CXXFLAGS=__cxx_conformance_CXXFLAGS,
_successflags={'CXXFLAGS' : __cxx_conformance_CXXFLAGS}
):
# Testing the compiler option parser only needs Compile, even when LTO
# is enabled.
Compile = self._Compile
# Accepted options by version:
#
# gcc-7 -std=gnu++1y
# gcc-7 -std=gnu++14
# gcc-7 -std=gnu++1z
# gcc-7 -std=gnu++17
#
# gcc-8 -std=gnu++1y
# gcc-8 -std=gnu++14
# gcc-8 -std=gnu++1z
# gcc-8 -std=gnu++17
# gcc-8 -std=gnu++2a
#
# gcc-9 -std=gnu++1y
# gcc-9 -std=gnu++14
# gcc-9 -std=gnu++1z
# gcc-9 -std=gnu++17
# gcc-9 -std=gnu++2a
for level in _levels:
opt = '-std=gnu++%u' % level
_CXXFLAGS[0] = opt
if Compile(context, text='', msg='whether C++ compiler accepts {opt}'.format(opt=opt), successflags=_successflags, calling_function='cxx%s' % level):
return
raise SCons.Errors.StopError('C++ compiler does not accept any supported C++ -std option.')
def _Test(self,context,text,msg,action,main='',ext='.cpp',testflags={},successflags={},skipped=None,successmsg=None,failuremsg=None,expect_failure=False,calling_function=None,__flags_Werror = {'CXXFLAGS' : ['-Werror']}):
if calling_function is None:
calling_function = self._find_calling_sconf_function()
context.Message('%s: checking %s...' % (self.msgprefix, msg))
if skipped is not None:
context.Result('(skipped){skipped}'.format(skipped=skipped))
if self.user_settings.record_sconf_results:
self._sconf_results.append((calling_function, 'skipped'))
return
env_flags = self.PreservedEnvironment(context.env, (get_dictionary_key_view(successflags), get_dictionary_key_view(testflags), get_dictionary_key_view(__flags_Werror), ('CPPDEFINES',)))
context.env.MergeFlags(successflags)
forced, expected = self._check_sconf_forced(calling_function)
caller_modified_env_flags = self.PreservedEnvironment(context.env, (get_dictionary_key_view(testflags), get_dictionary_key_view(__flags_Werror)))
# Always pass -Werror to configure tests.
context.env.Append(**__flags_Werror)
context.env.Append(**testflags)
# If forced is None, run the test. Otherwise, skip the test and
# take an action determined by the value of forced.
if forced is None:
r = action('''
{tools}
{macros}
{text}
#undef main /* avoid -Dmain=SDL_main from libSDL (and, on some platforms, from libSDL2) */
{main}
'''.format(
tools=self.__tool_versions,
macros=self.__defined_macros,
text=text,
main=('' if main is None else
'''
int main(int argc,char**argv){(void)argc;(void)argv;
%s
;}
''' % main
)), ext)
# Some tests check that the compiler rejects an input.
# SConf considers the result a failure when the compiler
# rejects the input. For tests that consider a rejection to
# be the good result, this conditional flips the sense of
# the result so that a compiler rejection is reported as
# success.
if expect_failure:
r = not r
context.Result((successmsg if r else failuremsg) or r)
if expected is not None and r != expected:
raise SCons.Errors.StopError('Expected and actual results differ. Test should %s, but it did not.' % ('succeed' if expected else 'fail'))
else:
choices = (self.sconf_force_failure, self.sconf_force_success, self.sconf_assume_success)
if forced not in choices:
try:
forced = choices[int(forced)]
except ValueError:
raise SCons.Errors.UserError("Unknown force value for sconf_%s: %s" % (co_name[6:], forced))
except IndexError:
raise SCons.Errors.UserError("Out of range force value for sconf_%s: %s" % (co_name[6:], forced))
if forced == self.sconf_force_failure:
# Pretend the test returned a failure result
r = False
elif forced == self.sconf_force_success or forced == self.sconf_assume_success:
# Pretend the test succeeded. Forced success modifies
# the environment as if the test had run and succeeded.
# Assumed success modifies the environment as if the
# test had run and failed.
#
# The latter is used when the user arranges for the
# environment to be correct. For example, if the
# compiler understands C++14, but uses a non-standard
# name for the option, the user would set assume-success
# and add the appropriate option to CXXFLAGS.
r = True
else:
raise SCons.Errors.UserError("Unknown force value for sconf_%s: %s" % (co_name[6:], forced))
# Flip the sense of the forced value, so that users can
# treat "force-failure" as force-bad-result regardless of
# whether the bad result is that the compiler rejected good
# input or that the compiler accepted bad input.
if expect_failure:
r = not r
context.Result('(forced){inverted}{forced}'.format(forced=forced, inverted='(inverted)' if expect_failure else ''))
# On success, revert to base flags + successflags
# On failure, revert to base flags
if r and forced != self.sconf_assume_success:
caller_modified_env_flags.restore(context.env)
context.env.Replace(CPPDEFINES=env_flags['CPPDEFINES'])
f = self.successful_flags
# Move most CPPDEFINES to the generated header, so that
# command lines are shorter.
for k, v in get_dictionary_item_view(successflags):
if k == 'CPPDEFINES':
continue
f[k].extend(v)
d = successflags.get('CPPDEFINES', None)
if d:
append_CPPDEFINE = f['CPPDEFINES'].append
Define = context.sconf.Define
for v in d:
# v is 'NAME' for -DNAME
# v is ('NAME', 'VALUE') for -DNAME=VALUE
d = (v, None) if isinstance(v, str) else v
if d[0] in ('_REENTRANT',):
# Blacklist defines that must not be moved to the
# configuration header.
append_CPPDEFINE(v)
continue
Define(d[0], d[1])
else: