blob: 75375408caa136e073ebd943b1ef9032462a755d [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 Weksteen246e69c2020-08-06 07:50:31 +000079 childId, childName, ok := appendLibraryAndDeps(ctx, project, knownCrates, child)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020080 if !ok {
81 return
82 }
Thiébaud Weksteen246e69c2020-08-06 07:50:31 +000083 if _, ok = deps[childName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020084 return
85 }
Thiébaud Weksteen246e69c2020-08-06 07:50:31 +000086 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childName})
87 deps[childName] = 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 }
108 crateName := rModule.CrateName()
Thiébaud Weksteen246e69c2020-08-06 07:50:31 +0000109 if cInfo, ok := knownCrates[crateName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200110 // We have seen this crate already; merge any new dependencies.
111 crate := project.Crates[cInfo.ID]
112 mergeDependencies(ctx, project, knownCrates, module, &crate, cInfo.Deps)
Thiébaud Weksteen9b7b8f12020-08-03 10:44:18 +0200113 project.Crates[cInfo.ID] = crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200114 return cInfo.ID, crateName, true
115 }
116 crate := rustProjectCrate{Deps: make([]rustProjectDep, 0), Cfgs: make([]string, 0)}
Thiébaud Weksteen891cd572020-08-05 09:29:23 +0200117 srcs := rustLib.baseCompiler.Properties.Srcs
118 if len(srcs) == 0 {
119 return 0, "", false
120 }
121 crate.RootModule = path.Join(ctx.ModuleDir(rModule), srcs[0])
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200122 crate.Edition = rustLib.baseCompiler.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200123
124 deps := make(map[string]int)
125 mergeDependencies(ctx, project, knownCrates, module, &crate, deps)
126
127 id := len(project.Crates)
Thiébaud Weksteen246e69c2020-08-06 07:50:31 +0000128 knownCrates[crateName] = crateInfo{ID: id, Deps: deps}
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200129 project.Crates = append(project.Crates, crate)
130 // rust-analyzer requires that all crates belong to at least one root:
131 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
132 project.Roots = append(project.Roots, path.Dir(crate.RootModule))
133 return id, crateName, true
134}
135
136func (r *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
137 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
138 return
139 }
140
141 project := rustProjectJson{}
142 knownCrates := make(map[string]crateInfo)
143 ctx.VisitAllModules(func(module android.Module) {
144 appendLibraryAndDeps(ctx, &project, knownCrates, module)
145 })
146
147 path := android.PathForOutput(ctx, rustProjectJsonFileName)
148 err := createJsonFile(project, path)
149 if err != nil {
150 ctx.Errorf(err.Error())
151 }
152}
153
154func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
155 buf, err := json.MarshalIndent(project, "", " ")
156 if err != nil {
157 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
158 }
159 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
160 if err != nil {
161 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
162 }
163 return nil
164}