blob: 5c3d785d6f615ac2aaa40b00ba7d470a93f9fbb9 [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
33func init() {
34 android.RegisterSingletonType("rust_project_generator", rustProjectGeneratorSingleton)
35}
36
37func rustProjectGeneratorSingleton() android.Singleton {
38 return &projectGeneratorSingleton{}
39}
40
41type projectGeneratorSingleton struct{}
42
43const (
44 // Environment variables used to control the behavior of this singleton.
45 envVariableCollectRustDeps = "SOONG_GEN_RUST_PROJECT"
46 rustProjectJsonFileName = "rust-project.json"
47)
48
49// The format of rust-project.json is not yet finalized. A current description is available at:
50// https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc#non-cargo-based-projects
51type rustProjectDep struct {
52 Crate int `json:"crate"`
53 Name string `json:"name"`
54}
55
56type rustProjectCrate struct {
57 RootModule string `json:"root_module"`
58 Edition string `json:"edition,omitempty"`
59 Deps []rustProjectDep `json:"deps"`
60 Cfgs []string `json:"cfgs"`
61}
62
63type rustProjectJson struct {
64 Roots []string `json:"roots"`
65 Crates []rustProjectCrate `json:"crates"`
66}
67
68// crateInfo is used during the processing to keep track of the known crates.
69type crateInfo struct {
70 ID int
71 Deps map[string]int
72}
73
74func mergeDependencies(ctx android.SingletonContext, project *rustProjectJson,
75 knownCrates map[string]crateInfo, module android.Module,
76 crate *rustProjectCrate, deps map[string]int) {
77
Thiébaud Weksteenc8105102020-08-06 07:50:31 +000078 //TODO(tweek): The stdlib dependencies do not appear here. We need to manually add them.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020079 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020080 childId, childCrateName, ok := appendLibraryAndDeps(ctx, project, knownCrates, child)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020081 if !ok {
82 return
83 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020084 if _, ok = deps[ctx.ModuleName(child)]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020085 return
86 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020087 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childCrateName})
88 deps[ctx.ModuleName(child)] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020089 })
90}
91
92// appendLibraryAndDeps creates a rustProjectCrate for the module argument and
93// appends it to the rustProjectJson struct. It visits the dependencies of the
94// module depth-first. If the current module is already in knownCrates, its
Thiébaud Weksteen9b7b8f12020-08-03 10:44:18 +020095// dependencies are merged. Returns a tuple (id, crate_name, ok).
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020096func appendLibraryAndDeps(ctx android.SingletonContext, project *rustProjectJson,
97 knownCrates map[string]crateInfo, module android.Module) (int, string, bool) {
98 rModule, ok := module.(*Module)
99 if !ok {
100 return 0, "", false
101 }
102 if rModule.compiler == nil {
103 return 0, "", false
104 }
105 rustLib, ok := rModule.compiler.(*libraryDecorator)
106 if !ok {
107 return 0, "", false
108 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200109 moduleName := ctx.ModuleName(module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200110 crateName := rModule.CrateName()
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200111 if cInfo, ok := knownCrates[moduleName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200112 // We have seen this crate already; merge any new dependencies.
113 crate := project.Crates[cInfo.ID]
114 mergeDependencies(ctx, project, knownCrates, module, &crate, cInfo.Deps)
Thiébaud Weksteen9b7b8f12020-08-03 10:44:18 +0200115 project.Crates[cInfo.ID] = crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200116 return cInfo.ID, crateName, true
117 }
118 crate := rustProjectCrate{Deps: make([]rustProjectDep, 0), Cfgs: make([]string, 0)}
Thiébaud Weksteenc8105102020-08-06 07:50:31 +0000119 src := rustLib.baseCompiler.Properties.Srcs[0]
120 crate.RootModule = path.Join(ctx.ModuleDir(rModule), src)
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200121 crate.Edition = rustLib.baseCompiler.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200122
123 deps := make(map[string]int)
124 mergeDependencies(ctx, project, knownCrates, module, &crate, deps)
125
126 id := len(project.Crates)
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200127 knownCrates[moduleName] = crateInfo{ID: id, Deps: deps}
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200128 project.Crates = append(project.Crates, crate)
129 // rust-analyzer requires that all crates belong to at least one root:
130 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
131 project.Roots = append(project.Roots, path.Dir(crate.RootModule))
132 return id, crateName, true
133}
134
135func (r *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
136 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
137 return
138 }
139
140 project := rustProjectJson{}
141 knownCrates := make(map[string]crateInfo)
142 ctx.VisitAllModules(func(module android.Module) {
143 appendLibraryAndDeps(ctx, &project, knownCrates, module)
144 })
145
146 path := android.PathForOutput(ctx, rustProjectJsonFileName)
147 err := createJsonFile(project, path)
148 if err != nil {
149 ctx.Errorf(err.Error())
150 }
151}
152
153func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
154 buf, err := json.MarshalIndent(project, "", " ")
155 if err != nil {
156 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
157 }
158 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
159 if err != nil {
160 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
161 }
162 return nil
163}