blob: 0b26b80fa499fd108610046ee36c506012b6fa05 [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"
Ivan Lozanod106efe2023-09-21 23:30:26 -040022 "android/soong/cc"
Treehugger Robot588aae72020-08-21 10:01:58 +000023)
24
25var (
26 defaultProtobufFlags = []string{""}
27)
28
Zach Johnson3df4e632020-11-06 11:56:27 -080029const (
30 grpcSuffix = "_grpc"
31)
32
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050033type PluginType int
34
Treehugger Robot588aae72020-08-21 10:01:58 +000035func init() {
36 android.RegisterModuleType("rust_protobuf", RustProtobufFactory)
37 android.RegisterModuleType("rust_protobuf_host", RustProtobufHostFactory)
38}
39
40var _ SourceProvider = (*protobufDecorator)(nil)
41
42type ProtobufProperties struct {
Ivan Lozano6eff9002020-12-11 15:25:59 -050043 // List of relative paths to proto files that will be used to generate the source.
44 // Either this or grpc_protos must be defined.
Ivan Lozano57f434e2020-10-28 09:32:10 -040045 Protos []string `android:"path,arch_variant"`
Treehugger Robot588aae72020-08-21 10:01:58 +000046
Ivan Lozano6eff9002020-12-11 15:25:59 -050047 // List of relative paths to GRPC-containing proto files that will be used to generate the source.
48 // Either this or protos must be defined.
49 Grpc_protos []string `android:"path,arch_variant"`
50
Treehugger Robot588aae72020-08-21 10:01:58 +000051 // List of additional flags to pass to aprotoc
52 Proto_flags []string `android:"arch_variant"`
Zach Johnson3df4e632020-11-06 11:56:27 -080053
54 // List of libraries which export include paths required for this module
Ivan Lozano9b443832020-11-17 13:39:30 -050055 Header_libs []string `android:"arch_variant,variant_prepend"`
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020056
Ivan Lozanod106efe2023-09-21 23:30:26 -040057 // List of exported include paths containing proto files for dependent rust_protobuf modules.
58 Exported_include_dirs []string
Treehugger Robot588aae72020-08-21 10:01:58 +000059}
60
61type protobufDecorator struct {
62 *BaseSourceProvider
63
Ivan Lozanod106efe2023-09-21 23:30:26 -040064 Properties ProtobufProperties
65 protoNames []string
66 additionalCrates []string
67 grpcNames []string
Ivan Lozano6eff9002020-12-11 15:25:59 -050068
69 grpcProtoFlags android.ProtoFlags
70 protoFlags android.ProtoFlags
Treehugger Robot588aae72020-08-21 10:01:58 +000071}
72
73func (proto *protobufDecorator) GenerateSource(ctx ModuleContext, deps PathDeps) android.Path {
74 var protoFlags android.ProtoFlags
Ivan Lozano6eff9002020-12-11 15:25:59 -050075 var grpcProtoFlags android.ProtoFlags
76 var commonProtoFlags []string
Treehugger Robot588aae72020-08-21 10:01:58 +000077
Ivan Lozano6a3d1e92020-11-02 15:06:26 -050078 outDir := android.PathForModuleOut(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -040079 protoFiles := android.PathsForModuleSrc(ctx, proto.Properties.Protos)
Ivan Lozano6eff9002020-12-11 15:25:59 -050080 grpcFiles := android.PathsForModuleSrc(ctx, proto.Properties.Grpc_protos)
Jeff Vander Stoepc1490ec2023-04-24 11:28:25 +020081
Ludovic Barman19739bf2023-11-04 15:13:49 +000082 protoPluginPath := ctx.Config().HostToolPath(ctx, "protoc-gen-rust")
Treehugger Robot588aae72020-08-21 10:01:58 +000083
Ivan Lozano6eff9002020-12-11 15:25:59 -050084 commonProtoFlags = append(commonProtoFlags, defaultProtobufFlags...)
85 commonProtoFlags = append(commonProtoFlags, proto.Properties.Proto_flags...)
86 commonProtoFlags = append(commonProtoFlags, "--plugin=protoc-gen-rust="+protoPluginPath.String())
87
88 if len(protoFiles) > 0 {
89 protoFlags.OutTypeFlag = "--rust_out"
90 protoFlags.Flags = append(protoFlags.Flags, commonProtoFlags...)
91
92 protoFlags.Deps = append(protoFlags.Deps, protoPluginPath)
93 }
94
95 if len(grpcFiles) > 0 {
96 grpcPath := ctx.Config().HostToolPath(ctx, "grpc_rust_plugin")
97
98 grpcProtoFlags.OutTypeFlag = "--rust_out"
99 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--grpc_out="+outDir.String())
100 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "--plugin=protoc-gen-grpc="+grpcPath.String())
101 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, commonProtoFlags...)
102
103 grpcProtoFlags.Deps = append(grpcProtoFlags.Deps, grpcPath, protoPluginPath)
104 }
105
106 if len(protoFiles) == 0 && len(grpcFiles) == 0 {
107 ctx.PropertyErrorf("protos",
108 "at least one protobuf must be defined in either protos or grpc_protos.")
Ivan Lozano9d74a522020-12-01 09:25:22 -0500109 }
110
Zach Johnson3df4e632020-11-06 11:56:27 -0800111 // Add exported dependency include paths
112 for _, include := range deps.depIncludePaths {
113 protoFlags.Flags = append(protoFlags.Flags, "-I"+include.String())
Ivan Lozano6eff9002020-12-11 15:25:59 -0500114 grpcProtoFlags.Flags = append(grpcProtoFlags.Flags, "-I"+include.String())
Zach Johnson3df4e632020-11-06 11:56:27 -0800115 }
116
Chih-Hung Hsiehc49649c2020-10-01 21:25:05 -0700117 stem := proto.BaseSourceProvider.getStem(ctx)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400118
119 // The mod_stem.rs file is used to avoid collisions if this is not included as a crate.
120 stemFile := android.PathForModuleOut(ctx, "mod_"+stem+".rs")
121
122 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
Ivan Lozano9d74a522020-12-01 09:25:22 -0500123 var outputs android.WritablePaths
Treehugger Robot588aae72020-08-21 10:01:58 +0000124
Colin Crossf1a035e2020-11-16 17:32:30 -0800125 rule := android.NewRuleBuilder(pctx, ctx)
Ivan Lozano6eff9002020-12-11 15:25:59 -0500126
Ivan Lozano57f434e2020-10-28 09:32:10 -0400127 for _, protoFile := range protoFiles {
Ivan Lozano6eff9002020-12-11 15:25:59 -0500128 // Since we're iterating over the protoFiles already, make sure they're not redeclared in grpcFiles
129 if android.InList(protoFile.String(), grpcFiles.Strings()) {
130 ctx.PropertyErrorf("protos",
131 "A proto can only be added once to either grpc_protos or protos. %q is declared in both properties",
132 protoFile.String())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400133 }
134
Ivan Lozano6eff9002020-12-11 15:25:59 -0500135 protoName := strings.TrimSuffix(protoFile.Base(), ".proto")
136 proto.protoNames = append(proto.protoNames, protoName)
137
138 protoOut := android.PathForModuleOut(ctx, protoName+".rs")
Ivan Lozano57f434e2020-10-28 09:32:10 -0400139 depFile := android.PathForModuleOut(ctx, protoName+".d")
140
Ivan Lozano6eff9002020-12-11 15:25:59 -0500141 ruleOutputs := android.WritablePaths{protoOut, depFile}
142
Colin Crossf1a035e2020-11-16 17:32:30 -0800143 android.ProtoRule(rule, protoFile, protoFlags, protoFlags.Deps, outDir, depFile, ruleOutputs)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400144 outputs = append(outputs, ruleOutputs...)
145 }
146
Ivan Lozano6eff9002020-12-11 15:25:59 -0500147 for _, grpcFile := range grpcFiles {
148 grpcName := strings.TrimSuffix(grpcFile.Base(), ".proto")
149 proto.grpcNames = append(proto.grpcNames, grpcName)
150
151 // GRPC protos produce two files, a proto.rs and a proto_grpc.rs
152 protoOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+".rs"))
153 grpcOut := android.WritablePath(android.PathForModuleOut(ctx, grpcName+grpcSuffix+".rs"))
154 depFile := android.PathForModuleOut(ctx, grpcName+".d")
155
156 ruleOutputs := android.WritablePaths{protoOut, grpcOut, depFile}
157
158 android.ProtoRule(rule, grpcFile, grpcProtoFlags, grpcProtoFlags.Deps, outDir, depFile, ruleOutputs)
159 outputs = append(outputs, ruleOutputs...)
160 }
161
162 // Check that all proto base filenames are unique as outputs are written to the same directory.
163 baseFilenames := append(proto.protoNames, proto.grpcNames...)
164 if len(baseFilenames) != len(android.FirstUniqueStrings(baseFilenames)) {
165 ctx.PropertyErrorf("protos", "proto filenames must be unique across 'protos' and 'grpc_protos' "+
166 "to be used in the same rust_protobuf module. For example, foo.proto and src/foo.proto will conflict.")
167 }
168
169 android.WriteFileRule(ctx, stemFile, proto.genModFileContents())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400170
Colin Crossf1a035e2020-11-16 17:32:30 -0800171 rule.Build("protoc_"+ctx.ModuleName(), "protoc "+ctx.ModuleName())
Ivan Lozano57f434e2020-10-28 09:32:10 -0400172
Ivan Lozano9d74a522020-12-01 09:25:22 -0500173 // stemFile must be first here as the first path in BaseSourceProvider.OutputFiles is the library entry-point.
174 proto.BaseSourceProvider.OutputFiles = append(android.Paths{stemFile}, outputs.Paths()...)
Ivan Lozano57f434e2020-10-28 09:32:10 -0400175
Colin Cross40213022023-12-13 15:19:49 -0800176 android.SetProvider(ctx, cc.FlagExporterInfoProvider, cc.FlagExporterInfo{
Ivan Lozanod106efe2023-09-21 23:30:26 -0400177 IncludeDirs: android.PathsForModuleSrc(ctx, proto.Properties.Exported_include_dirs),
178 })
179
Ivan Lozano57f434e2020-10-28 09:32:10 -0400180 // mod_stem.rs is the entry-point for our library modules, so this is what we return.
181 return stemFile
Treehugger Robot588aae72020-08-21 10:01:58 +0000182}
183
Ivan Lozano6eff9002020-12-11 15:25:59 -0500184func (proto *protobufDecorator) genModFileContents() string {
Zach Johnson3df4e632020-11-06 11:56:27 -0800185 lines := []string{
Ivan Lozano57f434e2020-10-28 09:32:10 -0400186 "// @Soong generated Source",
187 }
Ivan Lozanod106efe2023-09-21 23:30:26 -0400188
Ivan Lozano6eff9002020-12-11 15:25:59 -0500189 for _, protoName := range proto.protoNames {
Ivan Lozano57f434e2020-10-28 09:32:10 -0400190 lines = append(lines, fmt.Sprintf("pub mod %s;", protoName))
Zach Johnson3df4e632020-11-06 11:56:27 -0800191 }
192
Ivan Lozanod106efe2023-09-21 23:30:26 -0400193 for _, crate := range proto.additionalCrates {
194 lines = append(lines, fmt.Sprintf("pub use %s::*;", crate))
195
196 }
197
Ivan Lozano6eff9002020-12-11 15:25:59 -0500198 for _, grpcName := range proto.grpcNames {
199 lines = append(lines, fmt.Sprintf("pub mod %s;", grpcName))
200 lines = append(lines, fmt.Sprintf("pub mod %s%s;", grpcName, grpcSuffix))
201 }
202 if len(proto.grpcNames) > 0 {
Zach Johnson3df4e632020-11-06 11:56:27 -0800203 lines = append(
204 lines,
205 "pub mod empty {",
Ludovic Barman19739bf2023-11-04 15:13:49 +0000206 " pub use protobuf::well_known_types::empty::Empty;",
Zach Johnson3df4e632020-11-06 11:56:27 -0800207 "}")
208 }
209
Ivan Lozano9d74a522020-12-01 09:25:22 -0500210 return strings.Join(lines, "\n")
Zach Johnson3df4e632020-11-06 11:56:27 -0800211}
212
Treehugger Robot588aae72020-08-21 10:01:58 +0000213func (proto *protobufDecorator) SourceProviderProps() []interface{} {
214 return append(proto.BaseSourceProvider.SourceProviderProps(), &proto.Properties)
215}
216
217func (proto *protobufDecorator) SourceProviderDeps(ctx DepsContext, deps Deps) Deps {
218 deps = proto.BaseSourceProvider.SourceProviderDeps(ctx, deps)
Ludovic Barman19739bf2023-11-04 15:13:49 +0000219 deps.Rustlibs = append(deps.Rustlibs, "libprotobuf")
Zach Johnson3df4e632020-11-06 11:56:27 -0800220 deps.HeaderLibs = append(deps.SharedLibs, proto.Properties.Header_libs...)
221
Ivan Lozano6eff9002020-12-11 15:25:59 -0500222 if len(proto.Properties.Grpc_protos) > 0 {
Zach Johnson3df4e632020-11-06 11:56:27 -0800223 deps.Rustlibs = append(deps.Rustlibs, "libgrpcio", "libfutures")
224 deps.HeaderLibs = append(deps.HeaderLibs, "libprotobuf-cpp-full")
225 }
226
Treehugger Robot588aae72020-08-21 10:01:58 +0000227 return deps
228}
229
230// rust_protobuf generates protobuf rust code from the provided proto file. This uses the protoc-gen-rust plugin for
231// 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 -0400232// 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 +0000233// properties of other modules.
234func RustProtobufFactory() android.Module {
235 module, _ := NewRustProtobuf(android.HostAndDeviceSupported)
236 return module.Init()
237}
238
239// A host-only variant of rust_protobuf. Refer to rust_protobuf for more details.
240func RustProtobufHostFactory() android.Module {
241 module, _ := NewRustProtobuf(android.HostSupported)
242 return module.Init()
243}
244
245func NewRustProtobuf(hod android.HostOrDeviceSupported) (*Module, *protobufDecorator) {
246 protobuf := &protobufDecorator{
247 BaseSourceProvider: NewSourceProvider(),
248 Properties: ProtobufProperties{},
Treehugger Robot588aae72020-08-21 10:01:58 +0000249 }
250
Matthew Maurere94f3e72022-08-10 20:25:50 +0000251 module := NewSourceProviderModule(hod, protobuf, false, false)
Treehugger Robot588aae72020-08-21 10:01:58 +0000252
253 return module, protobuf
254}