blob: c8d2bdaebbac188fb292430ead4711bee95cfabe [file] [log] [blame]
Treehugger Robot588aae72020-08-21 10:01:58 +00001// Copyright 2020 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package rust
16
17import (
Zach Johnson3df4e632020-11-06 11:56:27 -080018 "fmt"
19 "strings"
20
Treehugger Robot588aae72020-08-21 10:01:58 +000021 "android/soong/android"
Vinh Tran0c4b9ec2023-08-24 11:10:01 -040022 "android/soong/bazel"
23
24 "github.com/google/blueprint/proptools"
Treehugger Robot588aae72020-08-21 10:01:58 +000025)
26
27var (
28 defaultProtobufFlags = []string{""}
29)
30
Zach Johnson3df4e632020-11-06 11:56:27 -080031const (
32 grpcSuffix = "_grpc"
33)
34
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050035type PluginType int
36
Treehugger Robot588aae72020-08-21 10:01:58 +000037func init() {
38 android.RegisterModuleType("rust_protobuf", RustProtobufFactory)
39 android.RegisterModuleType("rust_protobuf_host", RustProtobufHostFactory)
40}
41
42var _ SourceProvider = (*protobufDecorator)(nil)
43
44type ProtobufProperties struct {
Ivan Lozano6eff9002020-12-11 15:25:59 -050045 // List of relative paths to proto files that will be used to generate the source.
46 // Either this or grpc_protos must be defined.
Ivan Lozano57f434e2020-10-28 09:32:10 -040047 Protos []string `android:"path,arch_variant"`
Treehugger Robot588aae72020-08-21 10:01:58 +000048
Ivan Lozano6eff9002020-12-11 15:25:59 -050049 // List of relative paths to GRPC-containing proto files that will be used to generate the source.
50 // Either this or protos must be defined.
51 Grpc_protos []string `android:"path,arch_variant"`
52
Treehugger Robot588aae72020-08-21 10:01:58 +000053 // List of additional flags to pass to aprotoc
54 Proto_flags []string `android:"arch_variant"`
Zach Johnson3df4e632020-11-06 11:56:27 -080055
56 // List of libraries which export include paths required for this module
Ivan Lozano9b443832020-11-17 13:39:30 -050057 Header_libs []string `android:"arch_variant,variant_prepend"`
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020058
59 // Use protobuf version 3.x. This will be deleted once we migrate all current users
60 // of protobuf off of 2.x.
61 Use_protobuf3 *bool
Treehugger Robot588aae72020-08-21 10:01:58 +000062}
63
64type protobufDecorator struct {
65 *BaseSourceProvider
66
67 Properties ProtobufProperties
Ivan Lozano6eff9002020-12-11 15:25:59 -050068 protoNames []string
69 grpcNames []string
70
71 grpcProtoFlags android.ProtoFlags
72 protoFlags android.ProtoFlags
Treehugger Robot588aae72020-08-21 10:01:58 +000073}
74
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020075func (proto *protobufDecorator) useProtobuf3() bool {
76 return Bool(proto.Properties.Use_protobuf3)
77}
78
Treehugger Robot588aae72020-08-21 10:01:58 +000079func (proto *protobufDecorator) GenerateSource(ctx ModuleContext, deps PathDeps) android.Path {
80 var protoFlags android.ProtoFlags
Ivan Lozano6eff9002020-12-11 15:25:59 -050081 var grpcProtoFlags android.ProtoFlags
82 var commonProtoFlags []string
Treehugger Robot588aae72020-08-21 10:01:58 +000083
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050084 outDir := android.PathForModuleOut(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -040085 protoFiles := android.PathsForModuleSrc(ctx, proto.Properties.Protos)
Ivan Lozano6eff9002020-12-11 15:25:59 -050086 grpcFiles := android.PathsForModuleSrc(ctx, proto.Properties.Grpc_protos)
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020087
88 // For now protobuf2 (the deprecated version) remains the default. This will change in the
89 // future as we update the various users.
Jeff Vander Stoep91c04662023-03-22 15:09:00 +010090 protoPluginPath := ctx.Config().HostToolPath(ctx, "protoc-gen-rust-deprecated")
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020091 if proto.useProtobuf3() == true {
92 protoPluginPath = ctx.Config().HostToolPath(ctx, "protoc-gen-rust")
93 }
Treehugger Robot588aae72020-08-21 10:01:58 +000094
Ivan Lozano6eff9002020-12-11 15:25:59 -050095 commonProtoFlags = append(commonProtoFlags, defaultProtobufFlags...)
96 commonProtoFlags = append(commonProtoFlags, proto.Properties.Proto_flags...)
97 commonProtoFlags = append(commonProtoFlags, "--plugin=protoc-gen-rust="+protoPluginPath.String())
98
99 if len(protoFiles) > 0 {
100 protoFlags.OutTypeFlag = "--rust_out"
101 protoFlags.Flags = append(protoFlags.Flags, commonProtoFlags...)
102
103 protoFlags.Deps = append(protoFlags.Deps, protoPluginPath)
104 }
105
106 if len(grpcFiles) > 0 {
107 grpcPath := ctx.Config().HostToolPath(ctx, "grpc_rust_plugin")
108
109 grpcProtoFlags.OutTypeFlag = "--rust_out"
110 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--grpc_out="+outDir.String())
111 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--plugin=protoc-gen-grpc="+grpcPath.String())
112 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, commonProtoFlags...)
113
114 grpcProtoFlags.Deps = append(grpcProtoFlags.Deps, grpcPath, protoPluginPath)
115 }
116
117 if len(protoFiles) == 0 && len(grpcFiles) == 0 {
118 ctx.PropertyErrorf("protos",
119 "at least one protobuf must be defined in either protos or grpc_protos.")
Ivan Lozano9d74a522020-12-01 09:25:22 -0500120 }
121
Zach Johnson3df4e632020-11-06 11:56:27 -0800122 // Add exported dependency include paths
123 for _, include := range deps.depIncludePaths {
124 protoFlags.Flags = append(protoFlags.Flags, "-I"+include.String())
Ivan Lozano6eff9002020-12-11 15:25:59 -0500125 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "-I"+include.String())
Zach Johnson3df4e632020-11-06 11:56:27 -0800126 }
127
Chih-Hung Hsiehc49649c2020-10-01 21:25:05 -0700128 stem := proto.BaseSourceProvider.getStem(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400129
130 // The mod_stem.rs file is used to avoid collisions if this is not included as a crate.
131 stemFile := android.PathForModuleOut(ctx, "mod_"+stem+".rs")
132
133 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
Ivan Lozano9d74a522020-12-01 09:25:22 -0500134 var outputs android.WritablePaths
Treehugger Robot588aae72020-08-21 10:01:58 +0000135
Colin Crossf1a035e2020-11-16 17:32:30 -0800136 rule := android.NewRuleBuilder(pctx, ctx)
Ivan Lozano6eff9002020-12-11 15:25:59 -0500137
Ivan Lozano57f434e2020-10-28 09:32:10 -0400138 for _, protoFile := range protoFiles {
Ivan Lozano6eff9002020-12-11 15:25:59 -0500139 // Since we're iterating over the protoFiles already, make sure they're not redeclared in grpcFiles
140 if android.InList(protoFile.String(), grpcFiles.Strings()) {
141 ctx.PropertyErrorf("protos",
142 "A proto can only be added once to either grpc_protos or protos. %q is declared in both properties",
143 protoFile.String())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400144 }
145
Ivan Lozano6eff9002020-12-11 15:25:59 -0500146 protoName := strings.TrimSuffix(protoFile.Base(), ".proto")
147 proto.protoNames = append(proto.protoNames, protoName)
148
149 protoOut := android.PathForModuleOut(ctx, protoName+".rs")
Ivan Lozano57f434e2020-10-28 09:32:10 -0400150 depFile := android.PathForModuleOut(ctx, protoName+".d")
151
Ivan Lozano6eff9002020-12-11 15:25:59 -0500152 ruleOutputs := android.WritablePaths{protoOut, depFile}
153
Colin Crossf1a035e2020-11-16 17:32:30 -0800154 android.ProtoRule(rule, protoFile, protoFlags, protoFlags.Deps, outDir, depFile, ruleOutputs)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400155 outputs = append(outputs, ruleOutputs...)
156 }
157
Ivan Lozano6eff9002020-12-11 15:25:59 -0500158 for _, grpcFile := range grpcFiles {
159 grpcName := strings.TrimSuffix(grpcFile.Base(), ".proto")
160 proto.grpcNames = append(proto.grpcNames, grpcName)
161
162 // GRPC protos produce two files, a proto.rs and a proto_grpc.rs
163 protoOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+".rs"))
164 grpcOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+grpcSuffix+".rs"))
165 depFile := android.PathForModuleOut(ctx, grpcName+".d")
166
167 ruleOutputs := android.WritablePaths{protoOut, grpcOut, depFile}
168
169 android.ProtoRule(rule, grpcFile, grpcProtoFlags, grpcProtoFlags.Deps, outDir, depFile, ruleOutputs)
170 outputs = append(outputs, ruleOutputs...)
171 }
172
173 // Check that all proto base filenames are unique as outputs are written to the same directory.
174 baseFilenames := append(proto.protoNames, proto.grpcNames...)
175 if len(baseFilenames) != len(android.FirstUniqueStrings(baseFilenames)) {
176 ctx.PropertyErrorf("protos", "proto filenames must be unique across 'protos' and 'grpc_protos' "+
177 "to be used in the same rust_protobuf module. For example, foo.proto and src/foo.proto will conflict.")
178 }
179
180 android.WriteFileRule(ctx, stemFile, proto.genModFileContents())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400181
Colin Crossf1a035e2020-11-16 17:32:30 -0800182 rule.Build("protoc_"+ctx.ModuleName(), "protoc "+ctx.ModuleName())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400183
Ivan Lozano9d74a522020-12-01 09:25:22 -0500184 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
185 proto.BaseSourceProvider.OutputFiles = append(android.Paths{stemFile}, outputs.Paths()...)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400186
187 // mod_stem.rs is the entry-point for our library modules, so this is what we return.
188 return stemFile
Treehugger Robot588aae72020-08-21 10:01:58 +0000189}
190
Ivan Lozano6eff9002020-12-11 15:25:59 -0500191func (proto *protobufDecorator) genModFileContents() string {
Zach Johnson3df4e632020-11-06 11:56:27 -0800192 lines := []string{
Ivan Lozano57f434e2020-10-28 09:32:10 -0400193 "// @Soong generated Source",
194 }
Ivan Lozano6eff9002020-12-11 15:25:59 -0500195 for _, protoName := range proto.protoNames {
Ivan Lozano57f434e2020-10-28 09:32:10 -0400196 lines = append(lines, fmt.Sprintf("pub mod %s;", protoName))
Zach Johnson3df4e632020-11-06 11:56:27 -0800197 }
198
Ivan Lozano6eff9002020-12-11 15:25:59 -0500199 for _, grpcName := range proto.grpcNames {
200 lines = append(lines, fmt.Sprintf("pub mod %s;", grpcName))
201 lines = append(lines, fmt.Sprintf("pub mod %s%s;", grpcName, grpcSuffix))
202 }
203 if len(proto.grpcNames) > 0 {
Zach Johnson3df4e632020-11-06 11:56:27 -0800204 lines = append(
205 lines,
206 "pub mod empty {",
207 " pub use protobuf::well_known_types::Empty;",
David Duarteb6be48d2022-01-04 08:51:21 +0000208 "}",
209 "pub mod wrappers {",
210 " pub use protobuf::well_known_types::{",
211 " DoubleValue, FloatValue, Int64Value, UInt64Value, Int32Value, UInt32Value,",
212 " BoolValue, StringValue, BytesValue",
213 " };",
Zach Johnson3df4e632020-11-06 11:56:27 -0800214 "}")
215 }
216
Ivan Lozano9d74a522020-12-01 09:25:22 -0500217 return strings.Join(lines, "\n")
Zach Johnson3df4e632020-11-06 11:56:27 -0800218}
219
Treehugger Robot588aae72020-08-21 10:01:58 +0000220func (proto *protobufDecorator) SourceProviderProps() []interface{} {
221 return append(proto.BaseSourceProvider.SourceProviderProps(), &proto.Properties)
222}
223
224func (proto *protobufDecorator) SourceProviderDeps(ctx DepsContext, deps Deps) Deps {
225 deps = proto.BaseSourceProvider.SourceProviderDeps(ctx, deps)
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +0200226 useProtobuf3 := proto.useProtobuf3()
227 if useProtobuf3 == true {
228 deps.Rustlibs = append(deps.Rustlibs, "libprotobuf")
229 } else {
230 deps.Rustlibs = append(deps.Rustlibs, "libprotobuf_deprecated")
231 }
Zach Johnson3df4e632020-11-06 11:56:27 -0800232 deps.HeaderLibs = append(deps.SharedLibs, proto.Properties.Header_libs...)
233
Ivan Lozano6eff9002020-12-11 15:25:59 -0500234 if len(proto.Properties.Grpc_protos) > 0 {
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +0200235 if useProtobuf3 == true {
236 ctx.PropertyErrorf("protos", "rust_protobuf with grpc_protos defined must currently use "+
237 "`use_protobuf3: false,` in the Android.bp file. This is temporary until the "+
238 "grpcio crate is updated to use the current version of the protobuf crate.")
239 }
Zach Johnson3df4e632020-11-06 11:56:27 -0800240 deps.Rustlibs = append(deps.Rustlibs, "libgrpcio", "libfutures")
241 deps.HeaderLibs = append(deps.HeaderLibs, "libprotobuf-cpp-full")
242 }
243
Treehugger Robot588aae72020-08-21 10:01:58 +0000244 return deps
245}
246
247// rust_protobuf generates protobuf rust code from the provided proto file. This uses the protoc-gen-rust plugin for
248// protoc. Additional flags to the protoc command can be passed via the proto_flags property. This module type will
Vinh Tran4eeb2a92023-08-14 13:29:30 -0400249// create library variants that can be used as a crate dependency by adding it to the rlibs and rustlibs
Treehugger Robot588aae72020-08-21 10:01:58 +0000250// properties of other modules.
251func RustProtobufFactory() android.Module {
252 module, _ := NewRustProtobuf(android.HostAndDeviceSupported)
253 return module.Init()
254}
255
256// A host-only variant of rust_protobuf. Refer to rust_protobuf for more details.
257func RustProtobufHostFactory() android.Module {
258 module, _ := NewRustProtobuf(android.HostSupported)
259 return module.Init()
260}
261
262func NewRustProtobuf(hod android.HostOrDeviceSupported) (*Module, *protobufDecorator) {
263 protobuf := &protobufDecorator{
264 BaseSourceProvider: NewSourceProvider(),
265 Properties: ProtobufProperties{},
Treehugger Robot588aae72020-08-21 10:01:58 +0000266 }
267
Matthew Maurere94f3e72022-08-10 20:25:50 +0000268 module := NewSourceProviderModule(hod, protobuf, false, false)
Treehugger Robot588aae72020-08-21 10:01:58 +0000269
Vinh Tran0c4b9ec2023-08-24 11:10:01 -0400270 android.InitBazelModule(module)
271
Treehugger Robot588aae72020-08-21 10:01:58 +0000272 return module, protobuf
273}
Vinh Tran0c4b9ec2023-08-24 11:10:01 -0400274
275type rustProtoAttributes struct {
276 Srcs bazel.LabelListAttribute
277 Crate_name bazel.StringAttribute
278 Deps bazel.LabelListAttribute
279}
280
281type protoLibraryAttributes struct {
282 Srcs bazel.LabelListAttribute
283}
284
Chris Parsons637458d2023-09-19 20:09:00 +0000285func protoLibraryBp2build(ctx android.Bp2buildMutatorContext, m *Module) {
Vinh Tran0c4b9ec2023-08-24 11:10:01 -0400286 var protoFiles []string
287
288 for _, propsInterface := range m.sourceProvider.SourceProviderProps() {
289 if possibleProps, ok := propsInterface.(*ProtobufProperties); ok {
290 protoFiles = possibleProps.Protos
291 break
292 }
293 }
294
295 protoLibraryName := m.Name() + "_proto"
296
297 protoDeps := bazel.LabelListAttribute{
298 Value: bazel.LabelList{
299 Includes: []bazel.Label{
300 {
301 Label: ":" + protoLibraryName,
302 OriginalModuleName: m.Name(),
303 },
304 },
305 },
306 }
307
308 ctx.CreateBazelTargetModule(
309 bazel.BazelTargetModuleProperties{
310 Rule_class: "proto_library",
311 },
312 android.CommonAttributes{
313 Name: protoLibraryName,
314 },
315 &protoLibraryAttributes{
316 Srcs: bazel.MakeLabelListAttribute(
317 android.BazelLabelForModuleSrc(ctx, protoFiles),
318 ),
319 },
320 )
321
322 ctx.CreateBazelTargetModule(
323 bazel.BazelTargetModuleProperties{
324 Rule_class: "rust_proto_library",
325 Bzl_load_location: "@rules_rust//proto/protobuf:defs.bzl",
326 },
327 android.CommonAttributes{
328 Name: m.Name(),
329 },
330 &rustProtoAttributes{
331 Crate_name: bazel.StringAttribute{
332 Value: proptools.StringPtr(m.CrateName()),
333 },
334 Deps: protoDeps,
335 },
336 )
337}