blob: 831047938e5ccec7321f99c1faa0eba36ae40913 [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 Weksteene4d12a02020-06-05 11:09:27 +020078 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020079 childId, childCrateName, ok := appendLibraryAndDeps(ctx, project, knownCrates, child)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020080 if !ok {
81 return
82 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020083 if _, ok = deps[ctx.ModuleName(child)]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020084 return
85 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +020086 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childCrateName})
87 deps[ctx.ModuleName(child)] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020088 })
89}
90
91// appendLibraryAndDeps creates a rustProjectCrate for the module argument and
92// appends it to the rustProjectJson struct. It visits the dependencies of the
93// module depth-first. If the current module is already in knownCrates, its
Thiébaud Weksteen9b7b8f12020-08-03 10:44:18 +020094// dependencies are merged. Returns a tuple (id, crate_name, ok).
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020095func appendLibraryAndDeps(ctx android.SingletonContext, project *rustProjectJson,
96 knownCrates map[string]crateInfo, module android.Module) (int, string, bool) {
97 rModule, ok := module.(*Module)
98 if !ok {
99 return 0, "", false
100 }
101 if rModule.compiler == nil {
102 return 0, "", false
103 }
104 rustLib, ok := rModule.compiler.(*libraryDecorator)
105 if !ok {
106 return 0, "", false
107 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200108 moduleName := ctx.ModuleName(module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200109 crateName := rModule.CrateName()
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200110 if cInfo, ok := knownCrates[moduleName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200111 // We have seen this crate already; merge any new dependencies.
112 crate := project.Crates[cInfo.ID]
113 mergeDependencies(ctx, project, knownCrates, module, &crate, cInfo.Deps)
Thiébaud Weksteen9b7b8f12020-08-03 10:44:18 +0200114 project.Crates[cInfo.ID] = crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200115 return cInfo.ID, crateName, true
116 }
117 crate := rustProjectCrate{Deps: make([]rustProjectDep, 0), Cfgs: make([]string, 0)}
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200118 srcs := rustLib.baseCompiler.Properties.Srcs
119 if len(srcs) == 0 {
120 return 0, "", false
121 }
122 crate.RootModule = path.Join(ctx.ModuleDir(rModule), srcs[0])
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200123 crate.Edition = rustLib.baseCompiler.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200124
125 deps := make(map[string]int)
126 mergeDependencies(ctx, project, knownCrates, module, &crate, deps)
127
128 id := len(project.Crates)
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200129 knownCrates[moduleName] = crateInfo{ID: id, Deps: deps}
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200130 project.Crates = append(project.Crates, crate)
131 // rust-analyzer requires that all crates belong to at least one root:
132 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
133 project.Roots = append(project.Roots, path.Dir(crate.RootModule))
134 return id, crateName, true
135}
136
137func (r *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
138 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
139 return
140 }
141
142 project := rustProjectJson{}
143 knownCrates := make(map[string]crateInfo)
144 ctx.VisitAllModules(func(module android.Module) {
145 appendLibraryAndDeps(ctx, &project, knownCrates, module)
146 })
147
148 path := android.PathForOutput(ctx, rustProjectJsonFileName)
149 err := createJsonFile(project, path)
150 if err != nil {
151 ctx.Errorf(err.Error())
152 }
153}
154
155func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
156 buf, err := json.MarshalIndent(project, "", " ")
157 if err != nil {
158 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
159 }
160 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
161 if err != nil {
162 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
163 }
164 return nil
165}