blob: faa7db5f72a459297da71c54123d817a136bb71f [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"`
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020054}
55
56type rustProjectJson struct {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020057 Crates []rustProjectCrate `json:"crates"`
58}
59
60// crateInfo is used during the processing to keep track of the known crates.
61type crateInfo struct {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010062 Idx int // Index of the crate in rustProjectJson.Crates slice.
63 Deps map[string]int // The keys are the module names and not the crate names.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020064}
65
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020066type projectGeneratorSingleton struct {
67 project rustProjectJson
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010068 knownCrates map[string]crateInfo // Keys are module names.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020069}
70
71func rustProjectGeneratorSingleton() android.Singleton {
72 return &projectGeneratorSingleton{}
73}
74
75func init() {
76 android.RegisterSingletonType("rust_project_generator", rustProjectGeneratorSingleton)
77}
78
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010079// sourceProviderVariantSource returns the path to the source file if this
80// module variant should be used as a priority.
81//
82// SourceProvider modules may have multiple variants considered as source
83// (e.g., x86_64 and armv8). For a module available on device, use the source
84// generated for the target. For a host-only module, use the source generated
85// for the host.
86func sourceProviderVariantSource(ctx android.SingletonContext, rModule *Module) (string, bool) {
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +010087 rustLib, ok := rModule.compiler.(*libraryDecorator)
88 if !ok {
89 return "", false
90 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010091 if rustLib.source() {
92 switch rModule.hod {
93 case android.HostSupported, android.HostSupportedNoCross:
94 if rModule.Target().String() == ctx.Config().BuildOSTarget.String() {
95 src := rustLib.sourceProvider.Srcs()[0]
96 return src.String(), true
97 }
98 default:
99 if rModule.Target().String() == ctx.Config().AndroidFirstDeviceTarget.String() {
100 src := rustLib.sourceProvider.Srcs()[0]
101 return src.String(), true
102 }
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200103 }
104 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100105 return "", false
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200106}
107
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100108// sourceProviderSource finds the main source file of a source-provider crate.
109func sourceProviderSource(ctx android.SingletonContext, rModule *Module) (string, bool) {
110 rustLib, ok := rModule.compiler.(*libraryDecorator)
111 if !ok {
112 return "", false
113 }
114 if rustLib.source() {
115 // This is a source-variant, check if we are the right variant
116 // depending on the module configuration.
117 if src, ok := sourceProviderVariantSource(ctx, rModule); ok {
118 return src, true
119 }
120 }
121 foundSource := false
122 sourceSrc := ""
123 // Find the variant with the source and return its.
124 ctx.VisitAllModuleVariants(rModule, func(variant android.Module) {
125 if foundSource {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200126 return
127 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100128 // All variants of a source provider library are libraries.
129 rVariant, _ := variant.(*Module)
130 variantLib, _ := rVariant.compiler.(*libraryDecorator)
131 if variantLib.source() {
132 sourceSrc, ok = sourceProviderVariantSource(ctx, rVariant)
133 if ok {
134 foundSource = true
135 }
136 }
137 })
138 if !foundSource {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100139 ctx.Errorf("No valid source for source provider found: %v\n", rModule)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100140 }
141 return sourceSrc, foundSource
142}
143
144// crateSource finds the main source file (.rs) for a crate.
145func crateSource(ctx android.SingletonContext, rModule *Module, comp *baseCompiler) (string, bool) {
146 // Basic libraries, executables and tests.
147 srcs := comp.Properties.Srcs
148 if len(srcs) != 0 {
149 return path.Join(ctx.ModuleDir(rModule), srcs[0]), true
150 }
151 // SourceProvider libraries.
152 if rModule.sourceProvider != nil {
153 return sourceProviderSource(ctx, rModule)
154 }
155 return "", false
156}
157
158// mergeDependencies visits all the dependencies for module and updates crate and deps
159// with any new dependency.
160func (singleton *projectGeneratorSingleton) mergeDependencies(ctx android.SingletonContext,
161 module *Module, crate *rustProjectCrate, deps map[string]int) {
162
163 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen3c5905b2020-11-25 16:09:32 +0100164 // Skip intra-module dependencies (i.e., generated-source library depending on the source variant).
165 if module.Name() == child.Name() {
166 return
167 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100168 // Skip unsupported modules.
169 rChild, compChild, ok := isModuleSupported(ctx, child)
170 if !ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200171 return
172 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100173 // For unknown dependency, add it first.
174 var childId int
175 cInfo, known := singleton.knownCrates[rChild.Name()]
176 if !known {
177 childId, ok = singleton.addCrate(ctx, rChild, compChild)
178 if !ok {
179 return
180 }
181 } else {
182 childId = cInfo.Idx
183 }
184 // Is this dependency known already?
185 if _, ok = deps[child.Name()]; ok {
186 return
187 }
188 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: rChild.CrateName()})
189 deps[child.Name()] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200190 })
191}
192
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100193// isModuleSupported returns the RustModule and baseCompiler if the module
194// should be considered for inclusion in rust-project.json.
195func isModuleSupported(ctx android.SingletonContext, module android.Module) (*Module, *baseCompiler, bool) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200196 rModule, ok := module.(*Module)
197 if !ok {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100198 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200199 }
200 if rModule.compiler == nil {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100201 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200202 }
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100203 var comp *baseCompiler
204 switch c := rModule.compiler.(type) {
205 case *libraryDecorator:
206 comp = c.baseCompiler
207 case *binaryDecorator:
208 comp = c.baseCompiler
209 case *testDecorator:
210 comp = c.binaryDecorator.baseCompiler
211 default:
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100212 return nil, nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200213 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100214 return rModule, comp, true
215}
216
217// addCrate adds a crate to singleton.project.Crates ensuring that required
218// dependencies are also added. It returns the index of the new crate in
219// singleton.project.Crates
220func (singleton *projectGeneratorSingleton) addCrate(ctx android.SingletonContext, rModule *Module, comp *baseCompiler) (int, bool) {
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100221 rootModule, ok := crateSource(ctx, rModule, comp)
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200222 if !ok {
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100223 ctx.Errorf("Unable to find source for valid module: %v", rModule)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100224 return 0, false
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200225 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100226
227 crate := rustProjectCrate{
228 DisplayName: rModule.Name(),
229 RootModule: rootModule,
230 Edition: comp.edition(),
231 Deps: make([]rustProjectDep, 0),
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +0100232 Cfg: make([]string, 0),
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100233 Env: make(map[string]string),
234 }
235
236 if comp.CargoOutDir().Valid() {
237 crate.Env["OUT_DIR"] = comp.CargoOutDir().String()
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100238 }
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200239
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +0100240 for _, feature := range comp.Properties.Features {
241 crate.Cfg = append(crate.Cfg, "feature=\""+feature+"\"")
242 }
243
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200244 deps := make(map[string]int)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100245 singleton.mergeDependencies(ctx, rModule, &crate, deps)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200246
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100247 idx := len(singleton.project.Crates)
248 singleton.knownCrates[rModule.Name()] = crateInfo{Idx: idx, Deps: deps}
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200249 singleton.project.Crates = append(singleton.project.Crates, crate)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100250 return idx, true
251}
252
253// appendCrateAndDependencies creates a rustProjectCrate for the module argument and appends it to singleton.project.
254// It visits the dependencies of the module depth-first so the dependency ID can be added to the current module. If the
255// current module is already in singleton.knownCrates, its dependencies are merged.
256func (singleton *projectGeneratorSingleton) appendCrateAndDependencies(ctx android.SingletonContext, module android.Module) {
257 rModule, comp, ok := isModuleSupported(ctx, module)
258 if !ok {
259 return
260 }
261 // If we have seen this crate already; merge any new dependencies.
262 if cInfo, ok := singleton.knownCrates[module.Name()]; ok {
263 crate := singleton.project.Crates[cInfo.Idx]
264 singleton.mergeDependencies(ctx, rModule, &crate, cInfo.Deps)
265 singleton.project.Crates[cInfo.Idx] = crate
266 return
267 }
268 singleton.addCrate(ctx, rModule, comp)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200269}
270
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200271func (singleton *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200272 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
273 return
274 }
275
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200276 singleton.knownCrates = make(map[string]crateInfo)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200277 ctx.VisitAllModules(func(module android.Module) {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100278 singleton.appendCrateAndDependencies(ctx, module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200279 })
280
281 path := android.PathForOutput(ctx, rustProjectJsonFileName)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200282 err := createJsonFile(singleton.project, path)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200283 if err != nil {
284 ctx.Errorf(err.Error())
285 }
286}
287
288func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
289 buf, err := json.MarshalIndent(project, "", " ")
290 if err != nil {
291 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
292 }
293 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
294 if err != nil {
295 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
296 }
297 return nil
298}