Debian Codegraph @

third_party/upb/cmake/make_cmakelists.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2009-2021, Google LLC
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution.
13 # * Neither the name of Google LLC nor the
14 # names of its contributors may be used to endorse or promote products
15 # derived from this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 # DISCLAIMED. IN NO EVENT SHALL Google LLC BE LIABLE FOR ANY
21 # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28 """A tool to convert {WORKSPACE, BUILD} -> CMakeLists.txt.
29
30 This tool is very upb-specific at the moment, and should not be seen as a
31 generic Bazel -> CMake converter.
32 """
33
34 from __future__ import absolute_import
35 from __future__ import division
36 from __future__ import print_function
37
38 import sys
39 import textwrap
40 import os
41
42 def StripFirstChar(deps):
43 return [dep[1:] for dep in deps]
44
45 def IsSourceFile(name):
46 return name.endswith(".c") or name.endswith(".cc")
47
48 class BuildFileFunctions(object):
49 def __init__(self, converter):
50 self.converter = converter
51
52 def _add_deps(self, kwargs, keyword=""):
53 if "deps" not in kwargs:
54 return
55 self.converter.toplevel += "target_link_libraries(%s%s\n %s)\n" % (
56 kwargs["name"],
57 keyword,
58 "\n ".join(StripFirstChar(kwargs["deps"]))
59 )
60
61 def load(self, *args):
62 pass
63
64 def cc_library(self, **kwargs):
65 if kwargs["name"].endswith("amalgamation"):
66 return
67 if kwargs["name"] == "upbc_generator":
68 return
69 if kwargs["name"] == "lupb":
70 return
71 files = kwargs.get("srcs", []) + kwargs.get("hdrs", [])
72 found_files = []
73 pregenerated_files = [
74 "CMakeLists.txt", "descriptor.upb.h", "descriptor.upb.c"
75 ]
76 for file in files:
77 if os.path.basename(file) in pregenerated_files:
78 found_files.append("../cmake/" + file)
79 else:
80 found_files.append("../" + file)
81
82 if list(filter(IsSourceFile, files)):
83 # Has sources, make this a normal library.
84 self.converter.toplevel += "add_library(%s\n %s)\n" % (
85 kwargs["name"],
86 "\n ".join(found_files)
87 )
88 self._add_deps(kwargs)
89 else:
90 # Header-only library, have to do a couple things differently.
91 # For some info, see:
92 # http://mariobadr.com/creating-a-header-only-library-with-cmake.html
93 self.converter.toplevel += "add_library(%s INTERFACE)\n" % (
94 kwargs["name"]
95 )
96 self._add_deps(kwargs, " INTERFACE")
97
98 def cc_binary(self, **kwargs):
99 pass
100
101 def cc_test(self, **kwargs):
102 # Disable this until we properly support upb_proto_library().
103 # self.converter.toplevel += "add_executable(%s\n %s)\n" % (
104 # kwargs["name"],
105 # "\n ".join(kwargs["srcs"])
106 # )
107 # self.converter.toplevel += "add_test(NAME %s COMMAND %s)\n" % (
108 # kwargs["name"],
109 # kwargs["name"],
110 # )
111
112 # if "data" in kwargs:
113 # for data_dep in kwargs["data"]:
114 # self.converter.toplevel += textwrap.dedent("""\
115 # add_custom_command(
116 # TARGET %s POST_BUILD
117 # COMMAND ${CMAKE_COMMAND} -E copy
118 # ${CMAKE_SOURCE_DIR}/%s
119 # ${CMAKE_CURRENT_BINARY_DIR}/%s)\n""" % (
120 # kwargs["name"], data_dep, data_dep
121 # ))
122
123 # self._add_deps(kwargs)
124 pass
125
126 def cc_fuzz_test(self, **kwargs):
127 pass
128
129 def py_library(self, **kwargs):
130 pass
131
132 def py_binary(self, **kwargs):
133 pass
134
135 def lua_proto_library(self, **kwargs):
136 pass
137
138 def sh_test(self, **kwargs):
139 pass
140
141 def make_shell_script(self, **kwargs):
142 pass
143
144 def exports_files(self, files, **kwargs):
145 pass
146
147 def proto_library(self, **kwargs):
148 pass
149
150 def cc_proto_library(self, **kwargs):
151 pass
152
153 def generated_file_staleness_test(self, **kwargs):
154 pass
155
156 def upb_amalgamation(self, **kwargs):
157 pass
158
159 def upb_proto_library(self, **kwargs):
160 pass
161
162 def upb_proto_library_copts(self, **kwargs):
163 pass
164
165 def upb_proto_reflection_library(self, **kwargs):
166 pass
167
168 def upb_proto_srcs(self, **kwargs):
169 pass
170
171 def genrule(self, **kwargs):
172 pass
173
174 def config_setting(self, **kwargs):
175 pass
176
177 def upb_fasttable_enabled(self, **kwargs):
178 pass
179
180 def select(self, arg_dict):
181 return []
182
183 def glob(self, *args):
184 return []
185
186 def licenses(self, *args):
187 pass
188
189 def filegroup(self, **kwargs):
190 pass
191
192 def map_dep(self, arg):
193 return arg
194
195 def package_group(self, **kwargs):
196 pass
197
198
199 class WorkspaceFileFunctions(object):
200 def __init__(self, converter):
201 self.converter = converter
202
203 def load(self, *args):
204 pass
205
206 def workspace(self, **kwargs):
207 self.converter.prelude += "project(%s)\n" % (kwargs["name"])
208 self.converter.prelude += "set(CMAKE_C_STANDARD 99)\n"
209
210 def http_archive(self, **kwargs):
211 pass
212
213 def git_repository(self, **kwargs):
214 pass
215
216 def new_git_repository(self, **kwargs):
217 pass
218
219 def bazel_version_repository(self, **kwargs):
220 pass
221
222 def upb_deps(self):
223 pass
224
225 def protobuf_deps(self):
226 pass
227
228 def rules_fuzzing_dependencies(self):
229 pass
230
231 def rules_fuzzing_init(self):
232 pass
233
234 def system_python(self, **kwargs):
235 pass
236
237 def register_toolchains(self, toolchain):
238 pass
239
240 def python_source_archive(self, **kwargs):
241 pass
242
243 def python_nuget_package(self, **kwargs):
244 pass
245
246
247 class Converter(object):
248 def __init__(self):
249 self.prelude = ""
250 self.toplevel = ""
251 self.if_lua = ""
252
253 def convert(self):
254 return self.template % {
255 "prelude": converter.prelude,
256 "toplevel": converter.toplevel,
257 }
258
259 template = textwrap.dedent("""\
260 # This file was generated from BUILD using tools/make_cmakelists.py.
261
262 cmake_minimum_required(VERSION 3.1)
263
264 if(${CMAKE_VERSION} VERSION_LESS 3.12)
265 cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
266 else()
267 cmake_policy(VERSION 3.12)
268 endif()
269
270 cmake_minimum_required (VERSION 3.0)
271 cmake_policy(SET CMP0048 NEW)
272
273 %(prelude)s
274
275 # Prevent CMake from setting -rdynamic on Linux (!!).
276 SET(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
277 SET(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "")
278
279 # Set default build type.
280 if(NOT CMAKE_BUILD_TYPE)
281 message(STATUS "Setting build type to 'RelWithDebInfo' as none was specified.")
282 set(CMAKE_BUILD_TYPE "RelWithDebInfo" CACHE STRING
283 "Choose the type of build, options are: Debug Release RelWithDebInfo MinSizeRel."
284 FORCE)
285 endif()
286
287 # When using Ninja, compiler output won't be colorized without this.
288 include(CheckCXXCompilerFlag)
289 CHECK_CXX_COMPILER_FLAG(-fdiagnostics-color=always SUPPORTS_COLOR_ALWAYS)
290 if(SUPPORTS_COLOR_ALWAYS)
291 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color=always")
292 endif()
293
294 # Implement ASAN/UBSAN options
295 if(UPB_ENABLE_ASAN)
296 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
297 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address")
298 set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
299 set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address")
300 endif()
301
302 if(UPB_ENABLE_UBSAN)
303 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined")
304 set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address")
305 set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fsanitize=address")
306 set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fsanitize=address")
307 endif()
308
309 include_directories(..)
310 include_directories(../cmake)
311 include_directories(${CMAKE_CURRENT_BINARY_DIR})
312
313 if(APPLE)
314 set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -undefined dynamic_lookup -flat_namespace")
315 elseif(UNIX)
316 set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--build-id")
317 endif()
318
319 enable_testing()
320
321 %(toplevel)s
322
323 """)
324
325 data = {}
326 converter = Converter()
327
328 def GetDict(obj):
329 ret = {}
330 ret["UPB_DEFAULT_COPTS"] = [] # HACK
331 ret["UPB_DEFAULT_CPPOPTS"] = [] # HACK
332 for k in dir(obj):
333 if not k.startswith("_"):
334 ret[k] = getattr(obj, k);
335 return ret
336
337 globs = GetDict(converter)
338
339 exec(open("WORKSPACE").read(), GetDict(WorkspaceFileFunctions(converter)))
340 exec(open("BUILD").read(), GetDict(BuildFileFunctions(converter)))
341
342 with open(sys.argv[1], "w") as f:
343 f.write(converter.convert())