blob: 6cf492b496996710114cbfd9e0c222c1849d7126 [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"
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020020
21 "android/soong/android"
22)
23
24// This singleton collects Rust crate definitions and generates a JSON file
25// (${OUT_DIR}/soong/rust-project.json) which can be use by external tools,
26// such as rust-analyzer. It does so when either make, mm, mma, mmm or mmma is
27// called. This singleton is enabled only if SOONG_GEN_RUST_PROJECT is set.
28// For example,
29//
30// $ SOONG_GEN_RUST_PROJECT=1 m nothing
31
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020032const (
33 // Environment variables used to control the behavior of this singleton.
34 envVariableCollectRustDeps = "SOONG_GEN_RUST_PROJECT"
35 rustProjectJsonFileName = "rust-project.json"
36)
37
38// The format of rust-project.json is not yet finalized. A current description is available at:
39// https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc#non-cargo-based-projects
40type rustProjectDep struct {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020041 // The Crate attribute is the index of the dependency in the Crates array in rustProjectJson.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020042 Crate int `json:"crate"`
43 Name string `json:"name"`
44}
45
46type rustProjectCrate struct {
Matthew Maurer2b3da462024-11-01 17:36:10 +000047 DisplayName string `json:"display_name"`
48 RootModule string `json:"root_module"`
49 Edition string `json:"edition,omitempty"`
50 Deps []rustProjectDep `json:"deps"`
51 Cfg []string `json:"cfg"`
52 Env map[string]string `json:"env"`
53 ProcMacro bool `json:"is_proc_macro"`
54 ProcMacroDylib *string `json:"proc_macro_dylib_path"`
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 {
Matthew Maurerdb72f7e2023-11-21 00:20:02 +000063 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.
65 Device bool // True if the crate at idx was a device crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020066}
67
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020068type projectGeneratorSingleton struct {
69 project rustProjectJson
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010070 knownCrates map[string]crateInfo // Keys are module names.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020071}
72
73func rustProjectGeneratorSingleton() android.Singleton {
74 return &projectGeneratorSingleton{}
75}
76
77func init() {
LaMont Jones0c10e4d2023-05-16 00:58:37 +000078 android.RegisterParallelSingletonType("rust_project_generator", rustProjectGeneratorSingleton)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020079}
80
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010081// mergeDependencies visits all the dependencies for module and updates crate and deps
82// with any new dependency.
83func (singleton *projectGeneratorSingleton) mergeDependencies(ctx android.SingletonContext,
84 module *Module, crate *rustProjectCrate, deps map[string]int) {
85
86 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen3c5905b2020-11-25 16:09:32 +010087 // Skip intra-module dependencies (i.e., generated-source library depending on the source variant).
88 if module.Name() == child.Name() {
89 return
90 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010091 // Skip unsupported modules.
Matthew Maurerdb72f7e2023-11-21 00:20:02 +000092 rChild, ok := isModuleSupported(ctx, child)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010093 if !ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020094 return
95 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +010096 // For unknown dependency, add it first.
97 var childId int
98 cInfo, known := singleton.knownCrates[rChild.Name()]
99 if !known {
Matthew Maurerc1e0cb62024-04-30 23:06:05 +0000100 childId, ok = singleton.addCrate(ctx, rChild)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100101 if !ok {
102 return
103 }
104 } else {
105 childId = cInfo.Idx
106 }
107 // Is this dependency known already?
108 if _, ok = deps[child.Name()]; ok {
109 return
110 }
111 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: rChild.CrateName()})
112 deps[child.Name()] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200113 })
114}
115
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000116// isModuleSupported returns the RustModule if the module
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100117// should be considered for inclusion in rust-project.json.
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000118func isModuleSupported(ctx android.SingletonContext, module android.Module) (*Module, bool) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200119 rModule, ok := module.(*Module)
120 if !ok {
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000121 return nil, false
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200122 }
Cole Fausta963b942024-04-11 17:43:00 -0700123 if !rModule.Enabled(ctx) {
Matthew Maurer5a3c71c2023-11-27 17:51:58 +0000124 return nil, false
125 }
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000126 return rModule, true
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100127}
128
129// addCrate adds a crate to singleton.project.Crates ensuring that required
130// dependencies are also added. It returns the index of the new crate in
131// singleton.project.Crates
Matthew Maurerc1e0cb62024-04-30 23:06:05 +0000132func (singleton *projectGeneratorSingleton) addCrate(ctx android.SingletonContext, rModule *Module) (int, bool) {
133 deps := make(map[string]int)
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000134 rootModule, err := rModule.compiler.checkedCrateRootPath()
135 if err != nil {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100136 return 0, false
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200137 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100138
Matthew Maurer2b3da462024-11-01 17:36:10 +0000139 var procMacroDylib *string = nil
140 if procDec, procMacro := rModule.compiler.(*procMacroDecorator); procMacro {
141 procMacroDylib = new(string)
142 *procMacroDylib = procDec.baseCompiler.unstrippedOutputFilePath().String()
143 }
Seth Mooreaf96f992021-10-06 10:45:34 -0700144
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100145 crate := rustProjectCrate{
Matthew Maurer2b3da462024-11-01 17:36:10 +0000146 DisplayName: rModule.Name(),
147 RootModule: rootModule.String(),
148 Edition: rModule.compiler.edition(),
149 Deps: make([]rustProjectDep, 0),
150 Cfg: make([]string, 0),
151 Env: make(map[string]string),
152 ProcMacro: procMacroDylib != nil,
153 ProcMacroDylib: procMacroDylib,
Thiébaud Weksteenee6a89b2021-02-25 16:30:57 +0100154 }
155
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000156 if rModule.compiler.cargoOutDir().Valid() {
157 crate.Env["OUT_DIR"] = rModule.compiler.cargoOutDir().String()
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100158 }
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200159
Jihoon Kang091ffd82024-10-03 01:13:24 +0000160 for _, feature := range rModule.compiler.features(ctx, rModule) {
Thiébaud Weksteene8b0ee72021-03-25 09:26:07 +0100161 crate.Cfg = append(crate.Cfg, "feature=\""+feature+"\"")
162 }
163
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100164 singleton.mergeDependencies(ctx, rModule, &crate, deps)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200165
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000166 var idx int
167 if cInfo, ok := singleton.knownCrates[rModule.Name()]; ok {
168 idx = cInfo.Idx
169 singleton.project.Crates[idx] = crate
170 } else {
171 idx = len(singleton.project.Crates)
172 singleton.project.Crates = append(singleton.project.Crates, crate)
173 }
174 singleton.knownCrates[rModule.Name()] = crateInfo{Idx: idx, Deps: deps, Device: rModule.Device()}
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100175 return idx, true
176}
177
178// appendCrateAndDependencies creates a rustProjectCrate for the module argument and appends it to singleton.project.
179// It visits the dependencies of the module depth-first so the dependency ID can be added to the current module. If the
180// current module is already in singleton.knownCrates, its dependencies are merged.
181func (singleton *projectGeneratorSingleton) appendCrateAndDependencies(ctx android.SingletonContext, module android.Module) {
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000182 rModule, ok := isModuleSupported(ctx, module)
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100183 if !ok {
184 return
185 }
186 // If we have seen this crate already; merge any new dependencies.
187 if cInfo, ok := singleton.knownCrates[module.Name()]; ok {
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000188 // If we have a new device variant, override the old one
189 if !cInfo.Device && rModule.Device() {
Matthew Maurerc1e0cb62024-04-30 23:06:05 +0000190 singleton.addCrate(ctx, rModule)
Matthew Maurerdb72f7e2023-11-21 00:20:02 +0000191 return
192 }
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100193 crate := singleton.project.Crates[cInfo.Idx]
194 singleton.mergeDependencies(ctx, rModule, &crate, cInfo.Deps)
195 singleton.project.Crates[cInfo.Idx] = crate
196 return
197 }
Matthew Maurerc1e0cb62024-04-30 23:06:05 +0000198 singleton.addCrate(ctx, rModule)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200199}
200
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200201func (singleton *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200202 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
203 return
204 }
205
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200206 singleton.knownCrates = make(map[string]crateInfo)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200207 ctx.VisitAllModules(func(module android.Module) {
Thiébaud Weksteenfa5feae2020-12-07 13:40:19 +0100208 singleton.appendCrateAndDependencies(ctx, module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200209 })
210
211 path := android.PathForOutput(ctx, rustProjectJsonFileName)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200212 err := createJsonFile(singleton.project, path)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200213 if err != nil {
214 ctx.Errorf(err.Error())
215 }
216}
217
218func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
219 buf, err := json.MarshalIndent(project, "", " ")
220 if err != nil {
221 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
222 }
223 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
224 if err != nil {
225 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
226 }
227 return nil
228}