blob: 41dd194ee9b318f68d4cf84ac8d88e628ad2260c [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
78 //TODO(tweek): The stdlib dependencies do not appear here. We need to manually add them.
79 ctx.VisitDirectDeps(module, func(child android.Module) {
80 childId, childName, ok := appendLibraryAndDeps(ctx, project, knownCrates, child)
81 if !ok {
82 return
83 }
84 if _, ok = deps[childName]; ok {
85 return
86 }
87 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childName})
88 deps[childName] = childId
89 })
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 }
109 crateName := rModule.CrateName()
110 if cInfo, ok := knownCrates[crateName]; ok {
111 // 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)}
Ivan Lozano8a23fa42020-06-16 10:26:57 -0400118 src := rustLib.baseCompiler.Properties.Srcs[0]
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200119 crate.RootModule = path.Join(ctx.ModuleDir(rModule), src)
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200120 crate.Edition = rustLib.baseCompiler.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200121
122 deps := make(map[string]int)
123 mergeDependencies(ctx, project, knownCrates, module, &crate, deps)
124
125 id := len(project.Crates)
126 knownCrates[crateName] = crateInfo{ID: id, Deps: deps}
127 project.Crates = append(project.Crates, crate)
128 // rust-analyzer requires that all crates belong to at least one root:
129 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
130 project.Roots = append(project.Roots, path.Dir(crate.RootModule))
131 return id, crateName, true
132}
133
134func (r *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
135 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
136 return
137 }
138
139 project := rustProjectJson{}
140 knownCrates := make(map[string]crateInfo)
141 ctx.VisitAllModules(func(module android.Module) {
142 appendLibraryAndDeps(ctx, &project, knownCrates, module)
143 })
144
145 path := android.PathForOutput(ctx, rustProjectJsonFileName)
146 err := createJsonFile(project, path)
147 if err != nil {
148 ctx.Errorf(err.Error())
149 }
150}
151
152func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
153 buf, err := json.MarshalIndent(project, "", " ")
154 if err != nil {
155 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
156 }
157 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
158 if err != nil {
159 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
160 }
161 return nil
162}