blob: 8d9e50ca95a4a73b3139f067786987a493ab62f1 [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
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020033const (
34 // Environment variables used to control the behavior of this singleton.
35 envVariableCollectRustDeps = "SOONG_GEN_RUST_PROJECT"
36 rustProjectJsonFileName = "rust-project.json"
37)
38
39// The format of rust-project.json is not yet finalized. A current description is available at:
40// https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/manual.adoc#non-cargo-based-projects
41type rustProjectDep struct {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020042 // The Crate attribute is the index of the dependency in the Crates array in rustProjectJson.
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +020043 Crate int `json:"crate"`
44 Name string `json:"name"`
45}
46
47type rustProjectCrate struct {
48 RootModule string `json:"root_module"`
49 Edition string `json:"edition,omitempty"`
50 Deps []rustProjectDep `json:"deps"`
51 Cfgs []string `json:"cfgs"`
52}
53
54type rustProjectJson struct {
55 Roots []string `json:"roots"`
56 Crates []rustProjectCrate `json:"crates"`
57}
58
59// crateInfo is used during the processing to keep track of the known crates.
60type crateInfo struct {
61 ID int
62 Deps map[string]int
63}
64
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +020065type projectGeneratorSingleton struct {
66 project rustProjectJson
67 knownCrates map[string]crateInfo
68}
69
70func rustProjectGeneratorSingleton() android.Singleton {
71 return &projectGeneratorSingleton{}
72}
73
74func init() {
75 android.RegisterSingletonType("rust_project_generator", rustProjectGeneratorSingleton)
76}
77
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +020078// librarySource finds the main source file (.rs) for a crate.
79func librarySource(ctx android.SingletonContext, rModule *Module, rustLib *libraryDecorator) (string, bool) {
80 srcs := rustLib.baseCompiler.Properties.Srcs
81 if len(srcs) != 0 {
82 return path.Join(ctx.ModuleDir(rModule), srcs[0]), true
83 }
84 if !rustLib.source() {
85 return "", false
86 }
87 // It is a SourceProvider module. If this module is host only, uses the variation for the host.
88 // Otherwise, use the variation for the primary target.
89 switch rModule.hod {
90 case android.HostSupported:
91 case android.HostSupportedNoCross:
92 if rModule.Target().String() != ctx.Config().BuildOSTarget.String() {
93 return "", false
94 }
95 default:
Jaewoong Jung642916f2020-10-09 17:25:15 -070096 if rModule.Target().String() != ctx.Config().AndroidFirstDeviceTarget.String() {
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +020097 return "", false
98 }
99 }
100 src := rustLib.sourceProvider.Srcs()[0]
101 return src.String(), true
102}
103
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200104func (singleton *projectGeneratorSingleton) mergeDependencies(ctx android.SingletonContext,
105 module android.Module, crate *rustProjectCrate, deps map[string]int) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200106
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200107 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200108 childId, childCrateName, ok := singleton.appendLibraryAndDeps(ctx, child)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200109 if !ok {
110 return
111 }
Thiébaud Weksteen3c5905b2020-11-25 16:09:32 +0100112 // Skip intra-module dependencies (i.e., generated-source library depending on the source variant).
113 if module.Name() == child.Name() {
114 return
115 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200116 if _, ok = deps[ctx.ModuleName(child)]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200117 return
118 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200119 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childCrateName})
120 deps[ctx.ModuleName(child)] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200121 })
122}
123
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200124// appendLibraryAndDeps creates a rustProjectCrate for the module argument and appends it to singleton.project.
125// It visits the dependencies of the module depth-first so the dependency ID can be added to the current module. If the
126// current module is already in singleton.knownCrates, its dependencies are merged. Returns a tuple (id, crate_name, ok).
127func (singleton *projectGeneratorSingleton) appendLibraryAndDeps(ctx android.SingletonContext, module android.Module) (int, string, bool) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200128 rModule, ok := module.(*Module)
129 if !ok {
130 return 0, "", false
131 }
132 if rModule.compiler == nil {
133 return 0, "", false
134 }
135 rustLib, ok := rModule.compiler.(*libraryDecorator)
136 if !ok {
137 return 0, "", false
138 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200139 moduleName := ctx.ModuleName(module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200140 crateName := rModule.CrateName()
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200141 if cInfo, ok := singleton.knownCrates[moduleName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200142 // We have seen this crate already; merge any new dependencies.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200143 crate := singleton.project.Crates[cInfo.ID]
144 singleton.mergeDependencies(ctx, module, &crate, cInfo.Deps)
145 singleton.project.Crates[cInfo.ID] = crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200146 return cInfo.ID, crateName, true
147 }
148 crate := rustProjectCrate{Deps: make([]rustProjectDep, 0), Cfgs: make([]string, 0)}
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200149 rootModule, ok := librarySource(ctx, rModule, rustLib)
150 if !ok {
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200151 return 0, "", false
152 }
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200153 crate.RootModule = rootModule
Thiébaud Weksteene81c9242020-08-03 10:46:28 +0200154 crate.Edition = rustLib.baseCompiler.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200155
156 deps := make(map[string]int)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200157 singleton.mergeDependencies(ctx, module, &crate, deps)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200158
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200159 id := len(singleton.project.Crates)
160 singleton.knownCrates[moduleName] = crateInfo{ID: id, Deps: deps}
161 singleton.project.Crates = append(singleton.project.Crates, crate)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200162 // rust-analyzer requires that all crates belong to at least one root:
163 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200164 singleton.project.Roots = append(singleton.project.Roots, path.Dir(crate.RootModule))
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200165 return id, crateName, true
166}
167
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200168func (singleton *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200169 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
170 return
171 }
172
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200173 singleton.knownCrates = make(map[string]crateInfo)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200174 ctx.VisitAllModules(func(module android.Module) {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200175 singleton.appendLibraryAndDeps(ctx, module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200176 })
177
178 path := android.PathForOutput(ctx, rustProjectJsonFileName)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200179 err := createJsonFile(singleton.project, path)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200180 if err != nil {
181 ctx.Errorf(err.Error())
182 }
183}
184
185func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
186 buf, err := json.MarshalIndent(project, "", " ")
187 if err != nil {
188 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
189 }
190 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
191 if err != nil {
192 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
193 }
194 return nil
195}