blob: c4d60ad530a0b385fe5d84abda28ddef2d6609cb [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 Weksteen064f6e92020-12-03 20:58:32 +010078// crateSource finds the main source file (.rs) for a crate.
79func crateSource(ctx android.SingletonContext, rModule *Module, comp *baseCompiler) (string, bool) {
80 srcs := comp.Properties.Srcs
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +020081 if len(srcs) != 0 {
82 return path.Join(ctx.ModuleDir(rModule), srcs[0]), true
83 }
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +010084 rustLib, ok := rModule.compiler.(*libraryDecorator)
85 if !ok {
86 return "", false
87 }
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +020088 if !rustLib.source() {
89 return "", false
90 }
91 // It is a SourceProvider module. If this module is host only, uses the variation for the host.
92 // Otherwise, use the variation for the primary target.
93 switch rModule.hod {
94 case android.HostSupported:
95 case android.HostSupportedNoCross:
96 if rModule.Target().String() != ctx.Config().BuildOSTarget.String() {
97 return "", false
98 }
99 default:
Jaewoong Jung642916f2020-10-09 17:25:15 -0700100 if rModule.Target().String() != ctx.Config().AndroidFirstDeviceTarget.String() {
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200101 return "", false
102 }
103 }
104 src := rustLib.sourceProvider.Srcs()[0]
105 return src.String(), true
106}
107
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200108func (singleton *projectGeneratorSingleton) mergeDependencies(ctx android.SingletonContext,
109 module android.Module, crate *rustProjectCrate, deps map[string]int) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200110
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200111 ctx.VisitDirectDeps(module, func(child android.Module) {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200112 childId, childCrateName, ok := singleton.appendLibraryAndDeps(ctx, child)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200113 if !ok {
114 return
115 }
Thiébaud Weksteen3c5905b2020-11-25 16:09:32 +0100116 // Skip intra-module dependencies (i.e., generated-source library depending on the source variant).
117 if module.Name() == child.Name() {
118 return
119 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200120 if _, ok = deps[ctx.ModuleName(child)]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200121 return
122 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200123 crate.Deps = append(crate.Deps, rustProjectDep{Crate: childId, Name: childCrateName})
124 deps[ctx.ModuleName(child)] = childId
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200125 })
126}
127
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200128// appendLibraryAndDeps creates a rustProjectCrate for the module argument and appends it to singleton.project.
129// It visits the dependencies of the module depth-first so the dependency ID can be added to the current module. If the
130// current module is already in singleton.knownCrates, its dependencies are merged. Returns a tuple (id, crate_name, ok).
131func (singleton *projectGeneratorSingleton) appendLibraryAndDeps(ctx android.SingletonContext, module android.Module) (int, string, bool) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200132 rModule, ok := module.(*Module)
133 if !ok {
134 return 0, "", false
135 }
136 if rModule.compiler == nil {
137 return 0, "", false
138 }
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100139 var comp *baseCompiler
140 switch c := rModule.compiler.(type) {
141 case *libraryDecorator:
142 comp = c.baseCompiler
143 case *binaryDecorator:
144 comp = c.baseCompiler
145 case *testDecorator:
146 comp = c.binaryDecorator.baseCompiler
147 default:
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200148 return 0, "", false
149 }
Thiébaud Weksteen2f628ba2020-08-05 14:27:32 +0200150 moduleName := ctx.ModuleName(module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200151 crateName := rModule.CrateName()
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200152 if cInfo, ok := singleton.knownCrates[moduleName]; ok {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200153 // We have seen this crate already; merge any new dependencies.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200154 crate := singleton.project.Crates[cInfo.ID]
155 singleton.mergeDependencies(ctx, module, &crate, cInfo.Deps)
156 singleton.project.Crates[cInfo.ID] = crate
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200157 return cInfo.ID, crateName, true
158 }
159 crate := rustProjectCrate{Deps: make([]rustProjectDep, 0), Cfgs: make([]string, 0)}
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100160 rootModule, ok := crateSource(ctx, rModule, comp)
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200161 if !ok {
Thiébaud Weksteen83ee52f2020-08-05 09:29:23 +0200162 return 0, "", false
163 }
Thiébaud Weksteena6351ca2020-09-29 09:53:21 +0200164 crate.RootModule = rootModule
Thiébaud Weksteen064f6e92020-12-03 20:58:32 +0100165 crate.Edition = comp.edition()
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200166
167 deps := make(map[string]int)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200168 singleton.mergeDependencies(ctx, module, &crate, deps)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200169
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200170 id := len(singleton.project.Crates)
171 singleton.knownCrates[moduleName] = crateInfo{ID: id, Deps: deps}
172 singleton.project.Crates = append(singleton.project.Crates, crate)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200173 // rust-analyzer requires that all crates belong to at least one root:
174 // https://github.com/rust-analyzer/rust-analyzer/issues/4735.
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200175 singleton.project.Roots = append(singleton.project.Roots, path.Dir(crate.RootModule))
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200176 return id, crateName, true
177}
178
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200179func (singleton *projectGeneratorSingleton) GenerateBuildActions(ctx android.SingletonContext) {
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200180 if !ctx.Config().IsEnvTrue(envVariableCollectRustDeps) {
181 return
182 }
183
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200184 singleton.knownCrates = make(map[string]crateInfo)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200185 ctx.VisitAllModules(func(module android.Module) {
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200186 singleton.appendLibraryAndDeps(ctx, module)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200187 })
188
189 path := android.PathForOutput(ctx, rustProjectJsonFileName)
Thiébaud Weksteen3805f5c2020-09-28 14:42:07 +0200190 err := createJsonFile(singleton.project, path)
Thiébaud Weksteene4d12a02020-06-05 11:09:27 +0200191 if err != nil {
192 ctx.Errorf(err.Error())
193 }
194}
195
196func createJsonFile(project rustProjectJson, rustProjectPath android.WritablePath) error {
197 buf, err := json.MarshalIndent(project, "", " ")
198 if err != nil {
199 return fmt.Errorf("JSON marshal of rustProjectJson failed: %s", err)
200 }
201 err = android.WriteFileToOutputDir(rustProjectPath, buf, 0666)
202 if err != nil {
203 return fmt.Errorf("Writing rust-project to %s failed: %s", rustProjectPath.String(), err)
204 }
205 return nil
206}