1#===----------------------------------------------------------------------===##
2#
3# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4# See https://llvm.org/LICENSE.txt for license information.
5# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6#
7#===----------------------------------------------------------------------===##
8
9import libcxx.test.newformat
10import lit
11import lit.util
12import os
13import pipes
14import subprocess
15import tempfile
16
17def _memoize(f):
18  cache = dict()
19  def memoized(x):
20    if x not in cache:
21      cache[x] = f(x)
22    return cache[x]
23  return memoized
24
25@_memoize
26def _subprocess_call(command):
27  devNull = open(os.devnull, 'w')
28  return subprocess.call(command, shell=True, stdout=devNull, stderr=devNull)
29
30@_memoize
31def _subprocess_check_output(command):
32  devNull = open(os.devnull, 'w')
33  return lit.util.to_string(subprocess.check_output(command, shell=True, stderr=devNull))
34
35def _makeConfigTest(config):
36  sourceRoot = os.path.join(config.test_exec_root, '__config_src__')
37  execRoot = os.path.join(config.test_exec_root, '__config_exec__')
38  suite = lit.Test.TestSuite('__config__', sourceRoot, execRoot, config)
39  if not os.path.exists(sourceRoot):
40    os.makedirs(sourceRoot)
41  tmp = tempfile.NamedTemporaryFile(dir=sourceRoot, delete=False)
42  tmp.close()
43  pathInSuite = [os.path.relpath(tmp.name, sourceRoot)]
44  class TestWrapper(lit.Test.Test):
45    def __enter__(self):       return self
46    def __exit__(self, *args): os.remove(tmp.name)
47  return TestWrapper(suite, pathInSuite, config)
48
49def hasCompileFlag(config, flag):
50  """
51  Return whether the compiler in the configuration supports a given compiler flag.
52
53  This is done by executing the %{cxx} substitution with the given flag and
54  checking whether that succeeds.
55  """
56  with _makeConfigTest(config) as test:
57    command = "%{{cxx}} -xc++ {} -Werror -fsyntax-only %{{flags}} %{{compile_flags}} {}".format(os.devnull, flag)
58    command = libcxx.test.newformat.parseScript(test, preamble=[command], fileDependencies=[])[0]
59    result = _subprocess_call(command)
60    return result == 0
61
62def hasLocale(config, locale):
63  """
64  Return whether the runtime execution environment supports a given locale.
65
66  This is done by executing a program that tries to set the given locale using
67  %{exec} -- this means that the command may be executed on a remote host
68  depending on the %{exec} substitution.
69  """
70  with _makeConfigTest(config) as test:
71    with open(test.getSourcePath(), 'w') as source:
72      source.write("""
73      #include <locale.h>
74      int main(int, char** argv) {{
75        if (::setlocale(LC_ALL, argv[1]) != NULL) return 0;
76        else                                      return 1;
77      }}
78      """)
79    commands = [
80      "mkdir -p %T",
81      "%{cxx} -xc++ %s %{flags} %{compile_flags} %{link_flags} -o %t.exe",
82      "%{{exec}} %t.exe {}".format(pipes.quote(locale)),
83    ]
84    commands = libcxx.test.newformat.parseScript(test, preamble=commands, fileDependencies=['%t.exe'])
85    result = _subprocess_call(' && '.join(commands))
86    cleanup = libcxx.test.newformat.parseScript(test, preamble=['rm %t.exe'], fileDependencies=[])[0]
87    _subprocess_call(cleanup)
88    return result == 0
89
90def compilerMacros(config, flags=''):
91  """
92  Return a dictionary of predefined compiler macros.
93
94  The keys are strings representing macros, and the values are strings
95  representing what each macro is defined to.
96
97  If the optional `flags` argument (a string) is provided, these flags will
98  be added to the compiler invocation when generating the macros.
99  """
100  with _makeConfigTest(config) as test:
101    command = "%{{cxx}} -xc++ {} -dM -E %{{flags}} %{{compile_flags}} {}".format(os.devnull, flags)
102    command = libcxx.test.newformat.parseScript(test, preamble=[command], fileDependencies=[])[0]
103    unparsed = _subprocess_check_output(command)
104    parsedMacros = dict()
105    for line in filter(None, map(str.strip, unparsed.split('\n'))):
106      assert line.startswith('#define ')
107      line = line[len('#define '):]
108      macro, _, value = line.partition(' ')
109      parsedMacros[macro] = value
110    return parsedMacros
111
112def featureTestMacros(config, flags=''):
113  """
114  Return a dictionary of feature test macros.
115
116  The keys are strings representing feature test macros, and the values are
117  integers representing the value of the macro.
118  """
119  allMacros = compilerMacros(config, flags)
120  return {m: int(v.rstrip('LlUu')) for (m, v) in allMacros.items() if m.startswith('__cpp_')}
121
122
123class Feature(object):
124  """
125  Represents a Lit available feature that is enabled whenever it is supported.
126
127  A feature like this informs the test suite about a capability of the compiler,
128  platform, etc. Unlike Parameters, it does not make sense to explicitly
129  control whether a Feature is enabled -- it should be enabled whenever it
130  is supported.
131  """
132  def __init__(self, name, compileFlag=None, linkFlag=None, when=lambda _: True):
133    """
134    Create a Lit feature for consumption by a test suite.
135
136    - name
137        The name of the feature. This is what will end up in Lit's available
138        features if the feature is enabled. This can be either a string or a
139        callable, in which case it is passed the TestingConfig and should
140        generate a string representing the name of the feature.
141
142    - compileFlag
143        An optional compile flag to add when this feature is added to a
144        TestingConfig. If provided, this must be a string representing a
145        compile flag that will be appended to the end of the %{compile_flags}
146        substitution of the TestingConfig.
147
148    - linkFlag
149        An optional link flag to add when this feature is added to a
150        TestingConfig. If provided, this must be a string representing a
151        link flag that will be appended to the end of the %{link_flags}
152        substitution of the TestingConfig.
153
154    - when
155        A callable that gets passed a TestingConfig and should return a
156        boolean representing whether the feature is supported in that
157        configuration. For example, this can use `hasCompileFlag` to
158        check whether the compiler supports the flag that the feature
159        represents. If omitted, the feature will always be considered
160        supported.
161    """
162    self._name = name
163    self._compileFlag = compileFlag
164    self._linkFlag = linkFlag
165    self._isSupported = when
166
167  def isSupported(self, config):
168    """
169    Return whether the feature is supported by the given TestingConfig.
170    """
171    return self._isSupported(config)
172
173  def enableIn(self, config):
174    """
175    Enable a feature in a TestingConfig.
176
177    The name of the feature is added to the set of available features of
178    `config`, and any compile or link flags provided upon construction of
179    the Feature are added to the end of the corresponding substitution in
180    the config.
181
182    It is an error to call `f.enableIn(cfg)` if the feature `f` is not
183    supported in that TestingConfig (i.e. if `not f.isSupported(cfg)`).
184    """
185    assert self.isSupported(config), \
186      "Trying to enable feature {} that is not supported in the given configuration".format(self._name)
187
188    addTo = lambda subs, sub, flag: [(s, x + ' ' + flag) if s == sub else (s, x) for (s, x) in subs]
189    if self._compileFlag:
190      config.substitutions = addTo(config.substitutions, '%{compile_flags}', self._compileFlag)
191    if self._linkFlag:
192      config.substitutions = addTo(config.substitutions, '%{link_flags}', self._linkFlag)
193
194    name = self._name(config) if callable(self._name) else self._name
195    config.available_features.add(name)
196
197
198def _str_to_bool(s):
199  """
200  Convert a string value to a boolean.
201
202  True values are "y", "yes", "t", "true", "on" and "1", regardless of capitalization.
203  False values are "n", "no", "f", "false", "off" and "0", regardless of capitalization.
204  """
205  trueVals = ["y", "yes", "t", "true", "on", "1"]
206  falseVals = ["n", "no", "f", "false", "off", "0"]
207  lower = s.lower()
208  if lower in trueVals:
209    return True
210  elif lower in falseVals:
211    return False
212  else:
213    raise ValueError("Got string '{}', which isn't a valid boolean".format(s))
214
215
216class Parameter(object):
217  """
218  Represents a parameter of a Lit test suite.
219
220  Parameters are used to customize the behavior of test suites in a user
221  controllable way, more specifically by passing `--param <KEY>=<VALUE>`
222  when running Lit. Parameters have multiple possible values, and they can
223  have a default value when left unspecified.
224
225  Parameters can have a Feature associated to them, in which case the Feature
226  is added to the TestingConfig if the parameter is enabled. It is an error if
227  the Parameter is enabled but the Feature associated to it is not supported,
228  for example trying to set the compilation standard to C++17 when `-std=c++17`
229  is not supported by the compiler.
230
231  One important point is that Parameters customize the behavior of the test
232  suite in a bounded way, i.e. there should be a finite set of possible choices
233  for `<VALUE>`. While this may appear to be an aggressive restriction, this
234  is actually a very important constraint that ensures that the set of
235  configurations supported by a test suite is finite. Otherwise, a test
236  suite could have an unbounded number of supported configurations, and
237  nobody wants to be stuck maintaining that. If it's not possible for an
238  option to have a finite set of possible values (e.g. the path to the
239  compiler), it can be handled in the `lit.cfg`, but it shouldn't be
240  represented with a Parameter.
241  """
242  def __init__(self, name, choices, type, help, feature, default=None):
243    """
244    Create a Lit parameter to customize the behavior of a test suite.
245
246    - name
247        The name of the parameter that can be used to set it on the command-line.
248        On the command-line, the parameter can be set using `--param <name>=<value>`
249        when running Lit. This must be non-empty.
250
251    - choices
252        A non-empty set of possible values for this parameter. This must be
253        anything that can be iterated. It is an error if the parameter is
254        given a value that is not in that set, whether explicitly or through
255        a default value.
256
257    - type
258        A callable that can be used to parse the value of the parameter given
259        on the command-line. As a special case, using the type `bool` also
260        allows parsing strings with boolean-like contents.
261
262    - help
263        A string explaining the parameter, for documentation purposes.
264        TODO: We should be able to surface those from the Lit command-line.
265
266    - feature
267        A callable that gets passed the parsed value of the parameter (either
268        the one passed on the command-line or the default one), and that returns
269        either None or a Feature.
270
271    - default
272        An optional default value to use for the parameter when no value is
273        provided on the command-line. If the default value is a callable, it
274        is called with the TestingConfig and should return the default value
275        for the parameter. Whether the default value is computed or specified
276        directly, it must be in the 'choices' provided for that Parameter.
277    """
278    self._name = name
279    if len(self._name) == 0:
280      raise ValueError("Parameter name must not be the empty string")
281
282    self._choices = list(choices) # should be finite
283    if len(self._choices) == 0:
284      raise ValueError("Parameter '{}' must be given at least one possible value".format(self._name))
285
286    self._parse = lambda x: (_str_to_bool(x) if type is bool and isinstance(x, str)
287                                             else type(x))
288    self._help = help
289    self._feature = feature
290    self._default = default
291
292  @property
293  def name(self):
294    """
295    Return the name of the parameter.
296
297    This is the name that can be used to set the parameter on the command-line
298    when running Lit.
299    """
300    return self._name
301
302  def getFeature(self, config, litParams):
303    param = litParams.get(self.name, None)
304    if param is None and self._default is None:
305      raise ValueError("Parameter {} doesn't have a default value, but it was not specified in the Lit parameters".format(self.name))
306    getDefault = lambda: self._default(config) if callable(self._default) else self._default
307    value = self._parse(param) if param is not None else getDefault()
308    if value not in self._choices:
309      raise ValueError("Got value '{}' for parameter '{}', which is not in the provided set of possible choices: {}".format(value, self.name, self._choices))
310    return self._feature(value)
311