blob: 40aa7c7362b7c3cd318f3c7d107f76a6f6b855bd [file] [log] [blame]
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +02001// Copyright 2020 Google Inc. All rights reserved.
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 (
18 "encoding/json"
19 "fmt"
20 "path"
21
22 "android/soong/android"
23)
24
25// This singleton collects Rust crate definitions and generates a JSON file
26// (${OUT_DIR}/soong/rust-project.json) which can be use by external tools,
27// such as rust-analyzer. It does so when either make, mm, mma, mmm or mmma is
28// called. This singleton is enabled only if SOONG_GEN_RUST_PROJECT is set.
29// For example,
30//
31// $ SOONG_GEN_RUST_PROJECT=1 m nothing
32
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020033const (
34 // Environment variables used to control the behavior of this singleton.
35 envVariableCollectRustDeps = "SOONG_GEN_RUST_PROJECT"
36 rustProjectJsonFileName = "rust-project.json"
37)
38
39// The format of rust-project.json is not yet finalized. A current description is available at:
40// https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc#non-cargo-based-projects
41type rustProjectDep struct {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020042 // The Crate attribute is the index of the dependency in the Crates array in rustProjectJson.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020043 Crate int `json:"crate"`
44 Name string `json:"name"`
45}
46
47type rustProjectCrate struct {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +010048 DisplayName string `json:"display_name"`
49 RootModule string `json:"root_module"`
50 Edition string `json:"edition,omitempty"`
51 Deps []rustProjectDep `json:"deps"`
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +010052 Cfg []string `json:"cfg"`
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +010053 Env map[string]string `json:"env"`
Seth Mooreaf96f992021-10-06 10:45:34 -070054 ProcMacro bool `json:"is_proc_macro"`
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020055}
56
57type rustProjectJson struct {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020058 Crates []rustProjectCrate `json:"crates"`
59}
60
61// crateInfo is used during the processing to keep track of the known crates.
62type crateInfo struct {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010063 Idx int // Index of the crate in rustProjectJson.Crates slice.
64 Deps map[string]int // The keys are the module names and not the crate names.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020065}
66
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020067type projectGeneratorSingleton struct {
68 project rustProjectJson
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010069 knownCrates map[string]crateInfo // Keys are module names.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020070}
71
72func rustProjectGeneratorSingleton() android.Singleton {
73 return &projectGeneratorSingleton{}
74}
75
76func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000077 android.RegisterParallelSingletonType("rust_project_generator", rustProjectGeneratorSingleton)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020078}
79
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010080// sourceProviderVariantSource returns the path to the source file if this
81// module variant should be used as a priority.
82//
83// SourceProvider modules may have multiple variants considered as source
84// (e.g., x86_64 and armv8). For a module available on device, use the source
85// generated for the target. For a host-only module, use the source generated
86// for the host.
87func sourceProviderVariantSource(ctx android.SingletonContext, rModule *Module) (string, bool) {
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +010088 rustLib, ok := rModule.compiler.(*libraryDecorator)
89 if !ok {
90 return "", false
91 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010092 if rustLib.source() {
93 switch rModule.hod {
94 case android.HostSupported, android.HostSupportedNoCross:
95 if rModule.Target().String() == ctx.Config().BuildOSTarget.String() {
96 src := rustLib.sourceProvider.Srcs()[0]
97 return src.String(), true
98 }
99 default:
100 if rModule.Target().String() == ctx.Config().AndroidFirstDeviceTarget.String() {
101 src := rustLib.sourceProvider.Srcs()[0]
102 return src.String(), true
103 }
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200104 }
105 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100106 return "", false
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200107}
108
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100109// sourceProviderSource finds the main source file of a source-provider crate.
110func sourceProviderSource(ctx android.SingletonContext, rModule *Module) (string, bool) {
111 rustLib, ok := rModule.compiler.(*libraryDecorator)
112 if !ok {
113 return "", false
114 }
115 if rustLib.source() {
116 // This is a source-variant, check if we are the right variant
117 // depending on the module configuration.
118 if src, ok := sourceProviderVariantSource(ctx, rModule); ok {
119 return src, true
120 }
121 }
122 foundSource := false
123 sourceSrc := ""
124 // Find the variant with the source and return its.
125 ctx.VisitAllModuleVariants(rModule, func(variant android.Module) {
126 if foundSource {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200127 return
128 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100129 // All variants of a source provider library are libraries.
130 rVariant, _ := variant.(*Module)
131 variantLib, _ := rVariant.compiler.(*libraryDecorator)
132 if variantLib.source() {
133 sourceSrc, ok = sourceProviderVariantSource(ctx, rVariant)
134 if ok {
135 foundSource = true
136 }
137 }
138 })
139 if !foundSource {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100140 ctx.Errorf("No valid source for source provider found: %v\n", rModule)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100141 }
142 return sourceSrc, foundSource
143}
144
145// crateSource finds the main source file (.rs) for a crate.
146func crateSource(ctx android.SingletonContext, rModule *Module, comp *baseCompiler) (string, bool) {
147 // Basic libraries, executables and tests.
148 srcs := comp.Properties.Srcs
149 if len(srcs) != 0 {
150 return path.Join(ctx.ModuleDir(rModule), srcs[0]), true
151 }
152 // SourceProvider libraries.
153 if rModule.sourceProvider != nil {
154 return sourceProviderSource(ctx, rModule)
155 }
156 return "", false
157}
158
159// mergeDependencies visits all the dependencies for module and updates crate and deps
160// with any new dependency.
161func (singleton *projectGeneratorSingleton) mergeDependencies(ctx android.SingletonContext,
162 module *Module, crate *rustProjectCrate, deps map[string]int) {
163
164 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen3c5905b2020-11-25 16:09:32 +0100165 // Skip intra-module dependencies (i.e., generated-source library depending on the source variant).
166 if module.Name() == child.Name() {
167 return
168 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100169 // Skip unsupported modules.
170 rChild, compChild, ok := isModuleSupported(ctx, child)
171 if !ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200172 return
173 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100174 // For unknown dependency, add it first.
175 var childId int
176 cInfo, known := singleton.knownCrates[rChild.Name()]
177 if !known {
178 childId, ok = singleton.addCrate(ctx, rChild, compChild)
179 if !ok {
180 return
181 }
182 } else {
183 childId = cInfo.Idx
184 }
185 // Is this dependency known already?
186 if _, ok = deps[child.Name()]; ok {
187 return
188 }
189 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: rChild.CrateName()})
190 deps[child.Name()] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200191 })
192}
193
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100194// isModuleSupported returns the RustModule and baseCompiler if the module
195// should be considered for inclusion in rust-project.json.
196func isModuleSupported(ctx android.SingletonContext, module android.Module) (*Module, *baseCompiler, bool) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200197 rModule, ok := module.(*Module)
198 if !ok {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100199 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200200 }
201 if rModule.compiler == nil {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100202 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200203 }
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100204 var comp *baseCompiler
205 switch c := rModule.compiler.(type) {
206 case *libraryDecorator:
207 comp = c.baseCompiler
208 case *binaryDecorator:
209 comp = c.baseCompiler
210 case *testDecorator:
211 comp = c.binaryDecorator.baseCompiler
Seth Mooreaf96f992021-10-06 10:45:34 -0700212 case *procMacroDecorator:
213 comp = c.baseCompiler
Thiébaud Weksteen566eb802021-12-08 17:54:19 +1100214 case *toolchainLibraryDecorator:
215 comp = c.baseCompiler
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100216 default:
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100217 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200218 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100219 return rModule, comp, true
220}
221
222// addCrate adds a crate to singleton.project.Crates ensuring that required
223// dependencies are also added. It returns the index of the new crate in
224// singleton.project.Crates
225func (singleton *projectGeneratorSingleton) addCrate(ctx android.SingletonContext, rModule *Module, comp *baseCompiler) (int, bool) {
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100226 rootModule, ok := crateSource(ctx, rModule, comp)
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200227 if !ok {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100228 ctx.Errorf("Unable to find source for valid module: %v", rModule)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100229 return 0, false
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200230 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100231
Seth Mooreaf96f992021-10-06 10:45:34 -0700232 _, procMacro := rModule.compiler.(*procMacroDecorator)
233
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100234 crate := rustProjectCrate{
235 DisplayName: rModule.Name(),
236 RootModule: rootModule,
237 Edition: comp.edition(),
238 Deps: make([]rustProjectDep, 0),
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +0100239 Cfg: make([]string, 0),
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100240 Env: make(map[string]string),
Seth Mooreaf96f992021-10-06 10:45:34 -0700241 ProcMacro: procMacro,
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100242 }
243
244 if comp.CargoOutDir().Valid() {
245 crate.Env["OUT_DIR"] = comp.CargoOutDir().String()
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100246 }
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200247
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +0100248 for _, feature := range comp.Properties.Features {
249 crate.Cfg = append(crate.Cfg, "feature=\""+feature+"\"")
250 }
251
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200252 deps := make(map[string]int)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100253 singleton.mergeDependencies(ctx, rModule, &crate, deps)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200254
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100255 idx := len(singleton.project.Crates)
256 singleton.knownCrates[rModule.Name()] = crateInfo{Idx: idx, Deps: deps}
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200257 singleton.project.Crates = append(singleton.project.Crates, crate)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100258 return idx, true
259}
260
261// appendCrateAndDependencies creates a rustProjectCrate for the module argument and appends it to singleton.project.
262// It visits the dependencies of the module depth-first so the dependency ID can be added to the current module. If the
263// current module is already in singleton.knownCrates, its dependencies are merged.
264func (singleton *projectGeneratorSingleton) appendCrateAndDependencies(ctx android.SingletonContext, module android.Module) {
265 rModule, comp, ok := isModuleSupported(ctx, module)
266 if !ok {
267 return
268 }
269 // If we have seen this crate already; merge any new dependencies.
270 if cInfo, ok := singleton.knownCrates[module.Name()]; ok {
271 crate := singleton.project.Crates[cInfo.Idx]
272 singleton.mergeDependencies(ctx, rModule, &crate, cInfo.Deps)
273 singleton.project.Crates[cInfo.Idx] = crate
274 return
275 }
276 singleton.addCrate(ctx, rModule, comp)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200277}
278
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200279func (singleton *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200280 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
281 return
282 }
283
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200284 singleton.knownCrates = make(map[string]crateInfo)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200285 ctx.VisitAllModules(func(module android.Module) {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100286 singleton.appendCrateAndDependencies(ctx, module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200287 })
288
289 path := android.PathForOutput(ctx, rustProjectJsonFileName)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200290 err := createJsonFile(singleton.project, path)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200291 if err != nil {
292 ctx.Errorf(err.Error())
293 }
294}
295
296func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
297 buf, err := json.MarshalIndent(project, "", " ")
298 if err != nil {
299 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
300 }
301 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
302 if err != nil {
303 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
304 }
305 return nil
306}