aboutsummaryrefslogtreecommitdiffhomepage
path: root/tools/build_defs/apple/swift.bzl
blob: f75557534caca5ef9e90a56f4c966e3f385ccff0 (plain)
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
# Copyright 2016 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Skylark rules for Swift."""

load("shared", "xcrun_action", "XCRUNWRAPPER_LABEL")

def _framework_dirs(framework_files):
  """Computes a set of framework parent directories.

  Collects framework directories based on the list of files from ObjcProvider
  and returns the parent directory for each one. Suitable for passing as -F
  flags to the compiler.

  Args:
    framework_files: A list of files from various ObjcProvider FRAMEWORK* keys.
  Returns:
    A list of paths that represent parent directories to framework bundles.
  """
  dirs = []

  for f in framework_files:
    d = f.dirname
    dirs.append(d[:d.rfind("/", 0, d.find(".framework"))])

  return set(dirs)

def _intersperse(separator, iterable):
  """Inserts separator before each item in iterable."""
  result = []
  for x in iterable:
    result.append(separator)
    result.append(x)

  return result

def _swift_target(cpu, sdk_version):
  """Returns a target triplet for Swift compiler."""
  return "%s-apple-ios%s" % (cpu, sdk_version)

def _swift_library_impl(ctx):
  """Implementation for swift_library Skylark rule."""
  cpu = ctx.fragments.apple.ios_cpu()
  platform = ctx.fragments.apple.ios_cpu_platform()
  sdk_version = ctx.fragments.apple.sdk_version_for_platform(platform)
  target = _swift_target(cpu, sdk_version)
  apple_toolchain = apple_common.apple_toolchain()

  # A list of paths to pass with -F flag.
  frameworks = set([
      apple_toolchain.platform_developer_framework_dir(ctx.fragments.apple)])

  # Collect transitive dependecies.
  dep_modules = []
  dep_libs = []

  swift_providers = [x.swift for x in ctx.attr.deps if hasattr(x, "swift")]
  objc_providers = [x.objc for x in ctx.attr.deps if hasattr(x, "objc")]

  for swift in swift_providers:
    dep_libs += swift.transitive_libs
    dep_modules += swift.transitive_modules

  objc_includes = set()    # Everything that needs to be included with -I
  objc_files = set()       # All inputs required for the compile action
  for objc in objc_providers:
    objc_includes += objc.include
    objc_includes = objc_includes.union([x.dirname for x in objc.module_map])

    objc_files += objc.header
    objc_files += objc.module_map

    # TODO(b/28978494): Switch to reading FRAMEWORK_DIR.
    if hasattr(objc, "framework_file"):
      objc_files += objc.framework_file
      frameworks += _framework_dirs(objc.framework_file)
    else:
      files = set(objc.static_framework_file) + set(objc.dynamic_framework_file)
      objc_files += files
      frameworks += _framework_dirs(files)

  # TODO(b/28005753): Currently this is not really a library, but an object
  # file, does not matter to the linker, but should be replaced with proper ar
  # call.
  output_lib = ctx.outputs.swift_lib
  output_module = ctx.outputs.swift_module
  output_header = ctx.outputs.swift_header

  srcs_args = [f.path for f in ctx.files.srcs]

  # TODO(b/28005582): Instead of including a dir for each dependecy, output to
  # a shared dir and include that?
  include_dirs = set([x.dirname for x in dep_modules])

  include_args = ["-I%s" % d for d in include_dirs + objc_includes]
  framework_args = ["-F%s" % x for x in frameworks]

  # Add the current directory to clang's search path.
  # This instance of clang is spawned by swiftc to compile module maps and is
  # not passed the current directory as a search path by default.
  clang_args = _intersperse("-Xcc", ["-iquote", "."])

  args = [
      "swift",
      "-frontend",
      "-emit-object",
      "-emit-module-path", output_module.path,
      "-module-name", ctx.label.name,
      "-emit-objc-header-path", output_header.path,
      "-parse-as-library",
      "-target", target,
      "-sdk", apple_toolchain.sdk_dir(),
      "-o", output_lib.path,
      ] + srcs_args + include_args + framework_args + clang_args

  xcrun_action(
      ctx,
      inputs = ctx.files.srcs + dep_modules + dep_libs + list(objc_files),
      outputs = (output_lib, output_module, output_header),
      mnemonic = "SwiftCompile",
      arguments = args,
      use_default_shell_env = False,
      progress_message = ("Compiling Swift module %s (%d files)"
                          % (ctx.label.name, len(ctx.files.srcs))))

  objc_provider = apple_common.new_objc_provider(
      library=set([output_lib] + dep_libs),
      header=set([output_header]),
      providers=objc_providers)

  return struct(
      swift=struct(
          transitive_libs=[output_lib] + dep_libs,
          transitive_modules=[output_module] + dep_modules),
      objc=objc_provider)

swift_library = rule(
    _swift_library_impl,
    attrs = {
        "srcs": attr.label_list(allow_files = FileType([".swift"])),
        "deps": attr.label_list(providers=[["swift"], ["objc"]]),
        "_xcrunwrapper": attr.label(
            executable=True,
            default=Label(XCRUNWRAPPER_LABEL))},
    fragments = ["apple"],
    output_to_genfiles=True,
    outputs = {
        "swift_lib": "%{name}.a",
        "swift_module": "%{name}.swiftmodule",
        "swift_header": "%{name}-Swift.h",
    },
)
"""
Builds a Swift module.

A module is a pair of static library (.a) + module header (.swiftmodule).
Dependant targets can import this module as "import RuleName".

Args:
  srcs: Swift sources that comprise this module.
  deps: Other Swift modules.
"""