blob: 9fe27c4c93bf55ac47ea0bd060622c296506c591 [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"
22)
23
24var (
25 defaultProtobufFlags = []string{""}
26)
27
Zach Johnson3df4e632020-11-06 11:56:27 -080028const (
29 grpcSuffix = "_grpc"
30)
31
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050032type PluginType int
33
Treehugger Robot588aae72020-08-21 10:01:58 +000034func init() {
35 android.RegisterModuleType("rust_protobuf", RustProtobufFactory)
36 android.RegisterModuleType("rust_protobuf_host", RustProtobufHostFactory)
37}
38
39var _ SourceProvider = (*protobufDecorator)(nil)
40
41type ProtobufProperties struct {
Ivan Lozano6eff9002020-12-11 15:25:59 -050042 // List of relative paths to proto files that will be used to generate the source.
43 // Either this or grpc_protos must be defined.
Ivan Lozano57f434e2020-10-28 09:32:10 -040044 Protos []string `android:"path,arch_variant"`
Treehugger Robot588aae72020-08-21 10:01:58 +000045
Ivan Lozano6eff9002020-12-11 15:25:59 -050046 // List of relative paths to GRPC-containing proto files that will be used to generate the source.
47 // Either this or protos must be defined.
48 Grpc_protos []string `android:"path,arch_variant"`
49
Treehugger Robot588aae72020-08-21 10:01:58 +000050 // List of additional flags to pass to aprotoc
51 Proto_flags []string `android:"arch_variant"`
Zach Johnson3df4e632020-11-06 11:56:27 -080052
53 // List of libraries which export include paths required for this module
Ivan Lozano9b443832020-11-17 13:39:30 -050054 Header_libs []string `android:"arch_variant,variant_prepend"`
Treehugger Robot588aae72020-08-21 10:01:58 +000055}
56
57type protobufDecorator struct {
58 *BaseSourceProvider
59
60 Properties ProtobufProperties
Ivan Lozano6eff9002020-12-11 15:25:59 -050061 protoNames []string
62 grpcNames []string
63
64 grpcProtoFlags android.ProtoFlags
65 protoFlags android.ProtoFlags
Treehugger Robot588aae72020-08-21 10:01:58 +000066}
67
68func (proto *protobufDecorator) GenerateSource(ctx ModuleContext, deps PathDeps) android.Path {
69 var protoFlags android.ProtoFlags
Ivan Lozano6eff9002020-12-11 15:25:59 -050070 var grpcProtoFlags android.ProtoFlags
71 var commonProtoFlags []string
Treehugger Robot588aae72020-08-21 10:01:58 +000072
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050073 outDir := android.PathForModuleOut(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -040074 protoFiles := android.PathsForModuleSrc(ctx, proto.Properties.Protos)
Ivan Lozano6eff9002020-12-11 15:25:59 -050075 grpcFiles := android.PathsForModuleSrc(ctx, proto.Properties.Grpc_protos)
76 protoPluginPath := ctx.Config().HostToolPath(ctx, "protoc-gen-rust")
Treehugger Robot588aae72020-08-21 10:01:58 +000077
Ivan Lozano6eff9002020-12-11 15:25:59 -050078 commonProtoFlags = append(commonProtoFlags, defaultProtobufFlags...)
79 commonProtoFlags = append(commonProtoFlags, proto.Properties.Proto_flags...)
80 commonProtoFlags = append(commonProtoFlags, "--plugin=protoc-gen-rust="+protoPluginPath.String())
81
82 if len(protoFiles) > 0 {
83 protoFlags.OutTypeFlag = "--rust_out"
84 protoFlags.Flags = append(protoFlags.Flags, commonProtoFlags...)
85
86 protoFlags.Deps = append(protoFlags.Deps, protoPluginPath)
87 }
88
89 if len(grpcFiles) > 0 {
90 grpcPath := ctx.Config().HostToolPath(ctx, "grpc_rust_plugin")
91
92 grpcProtoFlags.OutTypeFlag = "--rust_out"
93 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--grpc_out="+outDir.String())
94 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--plugin=protoc-gen-grpc="+grpcPath.String())
95 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, commonProtoFlags...)
96
97 grpcProtoFlags.Deps = append(grpcProtoFlags.Deps, grpcPath, protoPluginPath)
98 }
99
100 if len(protoFiles) == 0 && len(grpcFiles) == 0 {
101 ctx.PropertyErrorf("protos",
102 "at least one protobuf must be defined in either protos or grpc_protos.")
Ivan Lozano9d74a522020-12-01 09:25:22 -0500103 }
104
Zach Johnson3df4e632020-11-06 11:56:27 -0800105 // Add exported dependency include paths
106 for _, include := range deps.depIncludePaths {
107 protoFlags.Flags = append(protoFlags.Flags, "-I"+include.String())
Ivan Lozano6eff9002020-12-11 15:25:59 -0500108 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "-I"+include.String())
Zach Johnson3df4e632020-11-06 11:56:27 -0800109 }
110
Chih-Hung Hsiehc49649c2020-10-01 21:25:05 -0700111 stem := proto.BaseSourceProvider.getStem(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400112
113 // The mod_stem.rs file is used to avoid collisions if this is not included as a crate.
114 stemFile := android.PathForModuleOut(ctx, "mod_"+stem+".rs")
115
116 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
Ivan Lozano9d74a522020-12-01 09:25:22 -0500117 var outputs android.WritablePaths
Treehugger Robot588aae72020-08-21 10:01:58 +0000118
Colin Crossf1a035e2020-11-16 17:32:30 -0800119 rule := android.NewRuleBuilder(pctx, ctx)
Ivan Lozano6eff9002020-12-11 15:25:59 -0500120
Ivan Lozano57f434e2020-10-28 09:32:10 -0400121 for _, protoFile := range protoFiles {
Ivan Lozano6eff9002020-12-11 15:25:59 -0500122 // Since we're iterating over the protoFiles already, make sure they're not redeclared in grpcFiles
123 if android.InList(protoFile.String(), grpcFiles.Strings()) {
124 ctx.PropertyErrorf("protos",
125 "A proto can only be added once to either grpc_protos or protos. %q is declared in both properties",
126 protoFile.String())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400127 }
128
Ivan Lozano6eff9002020-12-11 15:25:59 -0500129 protoName := strings.TrimSuffix(protoFile.Base(), ".proto")
130 proto.protoNames = append(proto.protoNames, protoName)
131
132 protoOut := android.PathForModuleOut(ctx, protoName+".rs")
Ivan Lozano57f434e2020-10-28 09:32:10 -0400133 depFile := android.PathForModuleOut(ctx, protoName+".d")
134
Ivan Lozano6eff9002020-12-11 15:25:59 -0500135 ruleOutputs := android.WritablePaths{protoOut, depFile}
136
Colin Crossf1a035e2020-11-16 17:32:30 -0800137 android.ProtoRule(rule, protoFile, protoFlags, protoFlags.Deps, outDir, depFile, ruleOutputs)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400138 outputs = append(outputs, ruleOutputs...)
139 }
140
Ivan Lozano6eff9002020-12-11 15:25:59 -0500141 for _, grpcFile := range grpcFiles {
142 grpcName := strings.TrimSuffix(grpcFile.Base(), ".proto")
143 proto.grpcNames = append(proto.grpcNames, grpcName)
144
145 // GRPC protos produce two files, a proto.rs and a proto_grpc.rs
146 protoOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+".rs"))
147 grpcOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+grpcSuffix+".rs"))
148 depFile := android.PathForModuleOut(ctx, grpcName+".d")
149
150 ruleOutputs := android.WritablePaths{protoOut, grpcOut, depFile}
151
152 android.ProtoRule(rule, grpcFile, grpcProtoFlags, grpcProtoFlags.Deps, outDir, depFile, ruleOutputs)
153 outputs = append(outputs, ruleOutputs...)
154 }
155
156 // Check that all proto base filenames are unique as outputs are written to the same directory.
157 baseFilenames := append(proto.protoNames, proto.grpcNames...)
158 if len(baseFilenames) != len(android.FirstUniqueStrings(baseFilenames)) {
159 ctx.PropertyErrorf("protos", "proto filenames must be unique across 'protos' and 'grpc_protos' "+
160 "to be used in the same rust_protobuf module. For example, foo.proto and src/foo.proto will conflict.")
161 }
162
163 android.WriteFileRule(ctx, stemFile, proto.genModFileContents())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400164
Colin Crossf1a035e2020-11-16 17:32:30 -0800165 rule.Build("protoc_"+ctx.ModuleName(), "protoc "+ctx.ModuleName())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400166
Ivan Lozano9d74a522020-12-01 09:25:22 -0500167 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
168 proto.BaseSourceProvider.OutputFiles = append(android.Paths{stemFile}, outputs.Paths()...)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400169
170 // mod_stem.rs is the entry-point for our library modules, so this is what we return.
171 return stemFile
Treehugger Robot588aae72020-08-21 10:01:58 +0000172}
173
Ivan Lozano6eff9002020-12-11 15:25:59 -0500174func (proto *protobufDecorator) genModFileContents() string {
Zach Johnson3df4e632020-11-06 11:56:27 -0800175 lines := []string{
Ivan Lozano57f434e2020-10-28 09:32:10 -0400176 "// @Soong generated Source",
177 }
Ivan Lozano6eff9002020-12-11 15:25:59 -0500178 for _, protoName := range proto.protoNames {
Ivan Lozano57f434e2020-10-28 09:32:10 -0400179 lines = append(lines, fmt.Sprintf("pub mod %s;", protoName))
Zach Johnson3df4e632020-11-06 11:56:27 -0800180 }
181
Ivan Lozano6eff9002020-12-11 15:25:59 -0500182 for _, grpcName := range proto.grpcNames {
183 lines = append(lines, fmt.Sprintf("pub mod %s;", grpcName))
184 lines = append(lines, fmt.Sprintf("pub mod %s%s;", grpcName, grpcSuffix))
185 }
186 if len(proto.grpcNames) > 0 {
Zach Johnson3df4e632020-11-06 11:56:27 -0800187 lines = append(
188 lines,
189 "pub mod empty {",
190 " pub use protobuf::well_known_types::Empty;",
David Duarteb6be48d2022-01-04 08:51:21 +0000191 "}",
192 "pub mod wrappers {",
193 " pub use protobuf::well_known_types::{",
194 " DoubleValue, FloatValue, Int64Value, UInt64Value, Int32Value, UInt32Value,",
195 " BoolValue, StringValue, BytesValue",
196 " };",
Zach Johnson3df4e632020-11-06 11:56:27 -0800197 "}")
198 }
199
Ivan Lozano9d74a522020-12-01 09:25:22 -0500200 return strings.Join(lines, "\n")
Zach Johnson3df4e632020-11-06 11:56:27 -0800201}
202
Treehugger Robot588aae72020-08-21 10:01:58 +0000203func (proto *protobufDecorator) SourceProviderProps() []interface{} {
204 return append(proto.BaseSourceProvider.SourceProviderProps(), &proto.Properties)
205}
206
207func (proto *protobufDecorator) SourceProviderDeps(ctx DepsContext, deps Deps) Deps {
208 deps = proto.BaseSourceProvider.SourceProviderDeps(ctx, deps)
209 deps.Rustlibs = append(deps.Rustlibs, "libprotobuf")
Zach Johnson3df4e632020-11-06 11:56:27 -0800210 deps.HeaderLibs = append(deps.SharedLibs, proto.Properties.Header_libs...)
211
Ivan Lozano6eff9002020-12-11 15:25:59 -0500212 if len(proto.Properties.Grpc_protos) > 0 {
Zach Johnson3df4e632020-11-06 11:56:27 -0800213 deps.Rustlibs = append(deps.Rustlibs, "libgrpcio", "libfutures")
214 deps.HeaderLibs = append(deps.HeaderLibs, "libprotobuf-cpp-full")
215 }
216
Treehugger Robot588aae72020-08-21 10:01:58 +0000217 return deps
218}
219
220// rust_protobuf generates protobuf rust code from the provided proto file. This uses the protoc-gen-rust plugin for
221// protoc. Additional flags to the protoc command can be passed via the proto_flags property. This module type will
222// create library variants that can be used as a crate dependency by adding it to the rlibs, dylibs, and rustlibs
223// properties of other modules.
224func RustProtobufFactory() android.Module {
225 module, _ := NewRustProtobuf(android.HostAndDeviceSupported)
226 return module.Init()
227}
228
229// A host-only variant of rust_protobuf. Refer to rust_protobuf for more details.
230func RustProtobufHostFactory() android.Module {
231 module, _ := NewRustProtobuf(android.HostSupported)
232 return module.Init()
233}
234
235func NewRustProtobuf(hod android.HostOrDeviceSupported) (*Module, *protobufDecorator) {
236 protobuf := &protobufDecorator{
237 BaseSourceProvider: NewSourceProvider(),
238 Properties: ProtobufProperties{},
Treehugger Robot588aae72020-08-21 10:01:58 +0000239 }
240
241 module := NewSourceProviderModule(hod, protobuf, false)
242
243 return module, protobuf
244}