Skip to content

Commit 78500d0

Browse files
xinzhengzhangilibilib
authored andcommitted
Add support for swift
1 parent 3bb6d78 commit 78500d0

File tree

2 files changed

+108
-21
lines changed

2 files changed

+108
-21
lines changed

refresh.template.py

Lines changed: 104 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,23 @@ def _print_header_finding_warning_once():
9393
Continuing gracefully...""")
9494
_print_header_finding_warning_once.has_logged = False
9595

96+
def _file_exists(source_file, warn_missing_generated = True):
97+
if not os.path.isfile(source_file):
98+
if not _file_exists.has_logged_missing_file_error and True == warn_missing_generated: # Just log once; subsequent messages wouldn't add anything.
99+
_file_exists.has_logged_missing_file_error = True
100+
log_warning(f""">>> A source file you compile doesn't (yet) exist: {source_file}
101+
It's probably a generated file, and you haven't yet run a build to generate it.
102+
That's OK; your code doesn't even have to compile for this tool to work.
103+
If you can, though, you might want to run a build of your code.
104+
That way everything is generated, browsable and indexed for autocomplete.
105+
However, if you have *already* built your code, and generated the missing file...
106+
Please make sure you're supplying this tool with the same flags you use to build.
107+
You can either use a refresh_compile_commands rule or the special -- syntax. Please see the README.
108+
[Supplying flags normally won't work. That just causes this tool to be built with those flags.]
109+
Continuing gracefully...""")
110+
return False
111+
return True
112+
_file_exists.has_logged_missing_file_error = False
96113

97114
@functools.lru_cache(maxsize=None)
98115
def _get_bazel_cached_action_keys():
@@ -564,19 +581,7 @@ def _get_files(compile_action):
564581
assert source_file.endswith(_get_files.source_extensions), f"Source file candidate, {source_file}, seems to be wrong.\nSelected from {compile_action.arguments}.\nPlease file an issue with this information!"
565582

566583
# Warn gently about missing files
567-
if not os.path.isfile(source_file):
568-
if not _get_files.has_logged_missing_file_error: # Just log once; subsequent messages wouldn't add anything.
569-
_get_files.has_logged_missing_file_error = True
570-
log_warning(f""">>> A source file you compile doesn't (yet) exist: {source_file}
571-
It's probably a generated file, and you haven't yet run a build to generate it.
572-
That's OK; your code doesn't even have to compile for this tool to work.
573-
If you can, though, you might want to run a build of your code.
574-
That way everything is generated, browsable and indexed for autocomplete.
575-
However, if you have *already* built your code, and generated the missing file...
576-
Please make sure you're supplying this tool with the same flags you use to build.
577-
You can either use a refresh_compile_commands rule or the special -- syntax. Please see the README.
578-
[Supplying flags normally won't work. That just causes this tool to be built with those flags.]
579-
Continuing gracefully...""")
584+
if not _file_exists(source_file):
580585
return {source_file}, set()
581586

582587
# Note: We need to apply commands to headers and sources.
@@ -605,7 +610,6 @@ def _get_files(compile_action):
605610
compile_action.arguments.insert(1, lang_flag)
606611

607612
return {source_file}, header_files
608-
_get_files.has_logged_missing_file_error = False
609613
# Setup extensions and flags for the whole C-language family.
610614
# Clang has a list: https://github.com/llvm/llvm-project/blob/b9f3b7f89a4cb4cf541b7116d9389c73690f78fa/clang/lib/Driver/Types.cpp#L293
611615
_get_files.c_source_extensions = ('.c', '.i')
@@ -650,7 +654,7 @@ def _get_apple_SDKROOT(SDK_name: str):
650654
# Traditionally stored in SDKROOT environment variable, but not provided by Bazel. See https://github.com/bazelbuild/bazel/issues/12852
651655

652656

653-
def _get_apple_platform(compile_args: typing.List[str]):
657+
def _get_apple_platform(compile_args: typing.List[str], environmentVariables = None):
654658
"""Figure out which Apple platform a command is for.
655659
656660
Is the name used by Xcode in the SDK files, not the marketing name.
@@ -661,6 +665,13 @@ def _get_apple_platform(compile_args: typing.List[str]):
661665
match = re.search('/Platforms/([a-zA-Z]+).platform/Developer/', arg)
662666
if match:
663667
return match.group(1)
668+
if environmentVariables:
669+
match = next(
670+
filter(lambda x: x.key == "APPLE_SDK_PLATFORM", environmentVariables),
671+
None
672+
)
673+
if match:
674+
return match.value
664675
return None
665676

666677

@@ -683,7 +694,36 @@ def _get_apple_active_clang():
683694
# Unless xcode-select has been invoked (like for a beta) we'd expect, e.g., '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang' or '/Library/Developer/CommandLineTools/usr/bin/clang'.
684695

685696

686-
def _apple_platform_patch(compile_args: typing.List[str]):
697+
@functools.lru_cache(maxsize=None)
698+
def _get_apple_active_swiftc():
699+
"""Get path to xcode-select'd clang version."""
700+
return subprocess.check_output(
701+
('xcrun', '--find', 'swiftc'),
702+
stderr=subprocess.DEVNULL, # Suppress superfluous error messages like "Requested but did not find extension point with identifier..."
703+
encoding=locale.getpreferredencoding()
704+
).rstrip()
705+
706+
707+
def _apple_swift_patch(compile_args: typing.List[str]):
708+
"""De-Bazel(rule_swift) the command into something sourcekit-lsp can parse."""
709+
710+
# Remove build_bazel_rules_swift/tools/worker/worker
711+
compile_args.pop(0)
712+
713+
# Expand -debug-prefix-pwd-is-dot
714+
match = next((i for i,v in enumerate(compile_args) if v == "-Xwrapped-swift=-debug-prefix-pwd-is-dot"), None)
715+
if match:
716+
compile_args[match] = "-debug-prefix-map"
717+
compile_args.insert(match + 1, os.environ["BUILD_WORKSPACE_DIRECTORY"] + "=.")
718+
719+
# Remove other -Xwrapped-swift arguments like `-ephemeral-module-cache` `-global-index-store-import-path`
720+
# We could override index-store by config sourcekit-lsp
721+
compile_args = [arg for arg in compile_args if not arg.startswith('-Xwrapped-swift')]
722+
723+
return compile_args
724+
725+
726+
def _apple_platform_patch(compile_args: typing.List[str], environmentVariables = None):
687727
"""De-Bazel the command into something clangd can parse.
688728
689729
This function has fixes specific to Apple platforms, but you should call it on all platforms. It'll determine whether the fixes should be applied or not.
@@ -694,7 +734,12 @@ def _apple_platform_patch(compile_args: typing.List[str]):
694734
# Undo Bazel's Apple platform compiler wrapping.
695735
# Bazel wraps the compiler as `external/local_config_cc/wrapped_clang` and exports that wrapped compiler in the proto. However, we need a clang call that clangd can introspect. (See notes in "how clangd uses compile_commands.json" in ImplementationReadme.md for more.)
696736
# Removing the wrapper is also important because Bazel's Xcode (but not CommandLineTools) wrapper crashes if you don't specify particular environment variables (replaced below). We'd need the wrapper to be invokable by clangd's --query-driver if we didn't remove the wrapper.
697-
compile_args[0] = _get_apple_active_clang()
737+
# Bazel wrapps the swiftc as `external/build_bazel_rules_swift/tools/worker/worker swiftc ` and worker has been removed in apple_swift_patch
738+
739+
if compile_args[0][-6:] == "swiftc":
740+
compile_args[0] = _get_apple_active_swiftc()
741+
else:
742+
compile_args[0] = _get_apple_active_clang()
698743

699744
# We have to manually substitute out Bazel's macros so clang can parse the command
700745
# Code this mirrors is in https://github.com/bazelbuild/bazel/blob/master/tools/osx/crosstool/wrapped_clang.cc
@@ -703,7 +748,7 @@ def _apple_platform_patch(compile_args: typing.List[str]):
703748
# We also have to manually figure out the values of SDKROOT and DEVELOPER_DIR, since they're missing from the environment variables Bazel provides.
704749
# Filed Bazel issue about the missing environment variables: https://github.com/bazelbuild/bazel/issues/12852
705750
compile_args = [arg.replace('__BAZEL_XCODE_DEVELOPER_DIR__', _get_apple_DEVELOPER_DIR()) for arg in compile_args]
706-
apple_platform = _get_apple_platform(compile_args)
751+
apple_platform = _get_apple_platform(compile_args, environmentVariables)
707752
assert apple_platform, f"Apple platform not detected in CMD: {compile_args}"
708753
compile_args = [arg.replace('__BAZEL_XCODE_SDKROOT__', _get_apple_SDKROOT(apple_platform)) for arg in compile_args]
709754

@@ -761,6 +806,40 @@ def _get_cpp_command_for_files(compile_action):
761806
return source_files, header_files, compile_action.arguments
762807

763808

809+
def _get_swift_command_for_files(compile_action):
810+
"""Reformat compile_action into a compile command sourcekit-lsp (https://github.com/apple/sourcekit-lsp) can understand.
811+
812+
Compile_action was produced by rule_swift (https://github.com/bazelbuild/rules_swift)
813+
"""
814+
# Patch command
815+
compile_action.arguments = _all_platform_patch(compile_action.arguments)
816+
compile_action.arguments = _apple_swift_patch(compile_action.arguments)
817+
compile_action.arguments = _apple_platform_patch(compile_action.arguments, compile_action.environmentVariables)
818+
819+
# Source files is end with `.swift`
820+
source_files = set(filter(lambda x: x[-6:] == ".swift", compile_action.arguments))
821+
822+
for source_file in source_files:
823+
_file_exists(source_file)
824+
825+
return source_files, set(), compile_action.arguments
826+
827+
828+
def _get_command_for_files(compile_action):
829+
"""Routing to correspond parser
830+
"""
831+
832+
assert compile_action.mnemonic in compile_action.mnemonic, f"Expecting mnemonic is one of (Objc|Cpp|Swift)Compile. Found mnemonic {compile_action.mnemonic}, target {compile_action}"
833+
834+
return _get_command_map[compile_action.mnemonic](compile_action)
835+
836+
_get_command_map = {
837+
"ObjcCompile": _get_cpp_command_for_files,
838+
"CppCompile": _get_cpp_command_for_files,
839+
"SwiftCompile": _get_swift_command_for_files,
840+
}
841+
842+
764843
def _convert_compile_commands(aquery_output):
765844
"""Converts from Bazel's aquery format to de-Bazeled compile_commands.json entries.
766845
@@ -794,7 +873,7 @@ def _amend_action_as_external(action):
794873
with concurrent.futures.ThreadPoolExecutor(
795874
max_workers=min(32, (os.cpu_count() or 1) + 4) # Backport. Default in MIN_PY=3.8. See "using very large resources implicitly on many-core machines" in https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor
796875
) as threadpool:
797-
outputs = threadpool.map(_get_cpp_command_for_files, aquery_output.actions)
876+
outputs = threadpool.map(_get_command_for_files, aquery_output.actions)
798877

799878
# Yield as compile_commands.json entries
800879
header_files_already_written = set()
@@ -843,14 +922,19 @@ def _get_commands(target: str, flags: str):
843922
Try adding them as flags in your refresh_compile_commands rather than targets.
844923
In a moment, Bazel will likely fail to parse.""")
845924

925+
support_mnemonics = ["Objc", "Cpp"]
926+
if {enable_swift}:
927+
support_mnemonics += ["Swift"]
928+
mnemonics_string = '|'.join(support_mnemonics)
929+
846930
# First, query Bazel's C-family compile actions for that configured target
847931
aquery_args = [
848932
'bazel',
849933
'aquery',
850934
# Aquery docs if you need em: https://docs.bazel.build/versions/master/aquery.html
851935
# Aquery output proto reference: https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/analysis_v2.proto
852936
# One bummer, not described in the docs, is that aquery filters over *all* actions for a given target, rather than just those that would be run by a build to produce a given output. This mostly isn't a problem, but can sometimes surface extra, unnecessary, misconfigured actions. Chris has emailed the authors to discuss and filed an issue so anyone reading this could track it: https://github.com/bazelbuild/bazel/issues/14156.
853-
f"mnemonic('(Objc|Cpp)Compile',deps({target}))",
937+
f"mnemonic('({mnemonics_string})Compile',deps({target}))",
854938
# We switched to jsonproto instead of proto because of https://github.com/bazelbuild/bazel/issues/13404. We could change back when fixed--reverting most of the commit that added this line and tweaking the build file to depend on the target in that issue. That said, it's kinda nice to be free of the dependency, unless (OPTIMNOTE) jsonproto becomes a performance bottleneck compated to binary protos.
855939
'--output=jsonproto',
856940
# We'll disable artifact output for efficiency, since it's large and we don't use them. Small win timewise, but dramatically less json output from aquery.

refresh_compile_commands.bzl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ def refresh_compile_commands(
6363
targets = None,
6464
exclude_headers = None,
6565
exclude_external_sources = False,
66+
enable_swift = False,
6667
**kwargs): # For the other common attributes. Tags, compatible_with, etc. https://docs.bazel.build/versions/main/be/common-definitions.html#common-attributes.
6768
# Convert the various, acceptable target shorthands into the dictionary format
6869
# In Python, `type(x) == y` is an antipattern, but [Starlark doesn't support inheritance](https://bazel.build/rules/language), so `isinstance` doesn't exist, and this is the correct way to switch on type.
@@ -75,7 +76,7 @@ def refresh_compile_commands(
7576

7677
# Generate runnable python script from template
7778
script_name = name + ".py"
78-
_expand_template(name = script_name, labels_to_flags = targets, exclude_headers = exclude_headers, exclude_external_sources = exclude_external_sources, **kwargs)
79+
_expand_template(name = script_name, labels_to_flags = targets, exclude_headers = exclude_headers, exclude_external_sources = exclude_external_sources, enable_swift = enable_swift, **kwargs)
7980
native.py_binary(name = name, srcs = [script_name], **kwargs)
8081

8182
def _expand_template_impl(ctx):
@@ -91,6 +92,7 @@ def _expand_template_impl(ctx):
9192
" {windows_default_include_paths}": "\n".join([" %r," % path for path in find_cpp_toolchain(ctx).built_in_include_directories]), # find_cpp_toolchain is from https://docs.bazel.build/versions/main/integrating-with-rules-cc.html
9293
"{exclude_headers}": '"' + str(ctx.attr.exclude_headers) + '"',
9394
"{exclude_external_sources}": str(ctx.attr.exclude_external_sources),
95+
"{enable_swift}": str(ctx.attr.enable_swift),
9496
},
9597
)
9698
return DefaultInfo(files = depset([script]))
@@ -100,6 +102,7 @@ _expand_template = rule(
100102
"labels_to_flags": attr.string_dict(mandatory = True), # string keys instead of label_keyed because Bazel doesn't support parsing wildcard target patterns (..., *, :all) in BUILD attributes.
101103
"exclude_external_sources": attr.bool(default = False),
102104
"exclude_headers": attr.string(values = ["all", "external", ""]), # "" needed only for compatibility with Bazel < 3.6.0
105+
"enable_swift": attr.bool(default = False),
103106
"_script_template": attr.label(allow_single_file = True, default = "refresh.template.py"),
104107
"_cc_toolchain": attr.label(default = "@bazel_tools//tools/cpp:current_cc_toolchain"), # For Windows INCLUDE. If this were eliminated, for example by the resolution of https://github.com/clangd/clangd/issues/123, we'd be able to just use a macro and skylib's expand_template rule: https://github.com/bazelbuild/bazel-skylib/pull/330
105108
},

0 commit comments

Comments
 (0)