blob: 27ec1635e776d8e4df466a7580eb4cae7825b57a [file] [log] [blame]
Jeff Gaston088e29e2017-11-29 16:47:17 -08001// Copyright 2017 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 android
16
17import (
Jeff Gaston5c3886d2017-11-30 16:46:47 -080018 "errors"
Jeff Gaston088e29e2017-11-29 16:47:17 -080019 "fmt"
20 "path/filepath"
21 "sort"
22 "strconv"
23 "strings"
24 "sync"
Jeff Gaston088e29e2017-11-29 16:47:17 -080025
26 "github.com/google/blueprint"
27)
28
Jeff Gaston088e29e2017-11-29 16:47:17 -080029func init() {
30 RegisterModuleType("soong_namespace", NamespaceFactory)
31}
32
33// threadsafe sorted list
34type sortedNamespaces struct {
35 lock sync.Mutex
36 items []*Namespace
37 sorted bool
38}
39
40func (s *sortedNamespaces) add(namespace *Namespace) {
41 s.lock.Lock()
42 defer s.lock.Unlock()
43 if s.sorted {
44 panic("It is not supported to call sortedNamespaces.add() after sortedNamespaces.sortedItems()")
45 }
46 s.items = append(s.items, namespace)
47}
48
49func (s *sortedNamespaces) sortedItems() []*Namespace {
50 s.lock.Lock()
51 defer s.lock.Unlock()
52 if !s.sorted {
53 less := func(i int, j int) bool {
54 return s.items[i].Path < s.items[j].Path
55 }
56 sort.Slice(s.items, less)
57 s.sorted = true
58 }
59 return s.items
60}
61
Jeff Gastonb274ed32017-12-01 17:10:33 -080062func (s *sortedNamespaces) index(namespace *Namespace) int {
63 for i, candidate := range s.sortedItems() {
64 if namespace == candidate {
65 return i
66 }
67 }
68 return -1
69}
70
Jeff Gaston088e29e2017-11-29 16:47:17 -080071// A NameResolver implements blueprint.NameInterface, and implements the logic to
72// find a module from namespaces based on a query string.
73// A query string can be a module name or can be be "//namespace_path:module_path"
74type NameResolver struct {
75 rootNamespace *Namespace
76
77 // id counter for atomic.AddInt32
Jeff Gastonb274ed32017-12-01 17:10:33 -080078 nextNamespaceId int32
Jeff Gaston088e29e2017-11-29 16:47:17 -080079
80 // All namespaces, without duplicates.
81 sortedNamespaces sortedNamespaces
82
83 // Map from dir to namespace. Will have duplicates if two dirs are part of the same namespace.
84 namespacesByDir sync.Map // if generics were supported, this would be sync.Map[string]*Namespace
85
86 // func telling whether to export a namespace to Kati
87 namespaceExportFilter func(*Namespace) bool
88}
89
90func NewNameResolver(namespaceExportFilter func(*Namespace) bool) *NameResolver {
Jeff Gaston088e29e2017-11-29 16:47:17 -080091 r := &NameResolver{
Dan Willemsen59339a22018-07-22 21:18:45 -070092 namespacesByDir: sync.Map{},
Jeff Gaston088e29e2017-11-29 16:47:17 -080093 namespaceExportFilter: namespaceExportFilter,
94 }
95 r.rootNamespace = r.newNamespace(".")
96 r.rootNamespace.visibleNamespaces = []*Namespace{r.rootNamespace}
97 r.addNamespace(r.rootNamespace)
98
99 return r
100}
101
102func (r *NameResolver) newNamespace(path string) *Namespace {
103 namespace := NewNamespace(path)
104
105 namespace.exportToKati = r.namespaceExportFilter(namespace)
106
Jeff Gaston088e29e2017-11-29 16:47:17 -0800107 return namespace
108}
109
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800110func (r *NameResolver) addNewNamespaceForModule(module *NamespaceModule, path string) error {
111 fileName := filepath.Base(path)
112 if fileName != "Android.bp" {
113 return errors.New("A namespace may only be declared in a file named Android.bp")
114 }
115 dir := filepath.Dir(path)
116
Jeff Gaston088e29e2017-11-29 16:47:17 -0800117 namespace := r.newNamespace(dir)
118 module.namespace = namespace
119 module.resolver = r
120 namespace.importedNamespaceNames = module.properties.Imports
121 return r.addNamespace(namespace)
122}
123
124func (r *NameResolver) addNamespace(namespace *Namespace) (err error) {
125 existingNamespace, exists := r.namespaceAt(namespace.Path)
126 if exists {
127 if existingNamespace.Path == namespace.Path {
128 return fmt.Errorf("namespace %v already exists", namespace.Path)
129 } else {
130 // It would probably confuse readers if namespaces were declared anywhere but
131 // the top of the file, so we forbid declaring namespaces after anything else.
132 return fmt.Errorf("a namespace must be the first module in the file")
133 }
134 }
135 r.sortedNamespaces.add(namespace)
136
137 r.namespacesByDir.Store(namespace.Path, namespace)
138 return nil
139}
140
141// non-recursive check for namespace
142func (r *NameResolver) namespaceAt(path string) (namespace *Namespace, found bool) {
143 mapVal, found := r.namespacesByDir.Load(path)
144 if !found {
145 return nil, false
146 }
147 return mapVal.(*Namespace), true
148}
149
150// recursive search upward for a namespace
151func (r *NameResolver) findNamespace(path string) (namespace *Namespace) {
152 namespace, found := r.namespaceAt(path)
153 if found {
154 return namespace
155 }
156 parentDir := filepath.Dir(path)
157 if parentDir == path {
158 return nil
159 }
160 namespace = r.findNamespace(parentDir)
161 r.namespacesByDir.Store(path, namespace)
162 return namespace
163}
164
165func (r *NameResolver) NewModule(ctx blueprint.NamespaceContext, moduleGroup blueprint.ModuleGroup, module blueprint.Module) (namespace blueprint.Namespace, errs []error) {
166 // if this module is a namespace, then save it to our list of namespaces
167 newNamespace, ok := module.(*NamespaceModule)
168 if ok {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800169 err := r.addNewNamespaceForModule(newNamespace, ctx.ModulePath())
Jeff Gaston088e29e2017-11-29 16:47:17 -0800170 if err != nil {
171 return nil, []error{err}
172 }
173 return nil, nil
174 }
175
176 // if this module is not a namespace, then save it into the appropriate namespace
177 ns := r.findNamespaceFromCtx(ctx)
178
179 _, errs = ns.moduleContainer.NewModule(ctx, moduleGroup, module)
180 if len(errs) > 0 {
181 return nil, errs
182 }
183
184 amod, ok := module.(Module)
185 if ok {
186 // inform the module whether its namespace is one that we want to export to Make
187 amod.base().commonProperties.NamespaceExportedToMake = ns.exportToKati
188 }
189
190 return ns, nil
191}
192
193func (r *NameResolver) AllModules() []blueprint.ModuleGroup {
194 childLists := [][]blueprint.ModuleGroup{}
195 totalCount := 0
196 for _, namespace := range r.sortedNamespaces.sortedItems() {
197 newModules := namespace.moduleContainer.AllModules()
198 totalCount += len(newModules)
199 childLists = append(childLists, newModules)
200 }
201
202 allModules := make([]blueprint.ModuleGroup, 0, totalCount)
203 for _, childList := range childLists {
204 allModules = append(allModules, childList...)
205 }
206 return allModules
207}
208
209// parses a fully-qualified path (like "//namespace_path:module_name") into a namespace name and a
210// module name
211func (r *NameResolver) parseFullyQualifiedName(name string) (namespaceName string, moduleName string, ok bool) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000212 if !strings.HasPrefix(name, "//") {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800213 return "", "", false
214 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000215 name = strings.TrimPrefix(name, "//")
216 components := strings.Split(name, ":")
Jeff Gaston088e29e2017-11-29 16:47:17 -0800217 if len(components) != 2 {
218 return "", "", false
219 }
220 return components[0], components[1], true
221
222}
223
224func (r *NameResolver) getNamespacesToSearchForModule(sourceNamespace *Namespace) (searchOrder []*Namespace) {
Colin Crosscd84b4e2019-06-14 11:26:09 -0700225 if sourceNamespace.visibleNamespaces == nil {
226 // When handling dependencies before namespaceMutator, assume they are non-Soong Blueprint modules and give
227 // access to all namespaces.
228 return r.sortedNamespaces.sortedItems()
229 }
Jeff Gaston088e29e2017-11-29 16:47:17 -0800230 return sourceNamespace.visibleNamespaces
231}
232
233func (r *NameResolver) ModuleFromName(name string, namespace blueprint.Namespace) (group blueprint.ModuleGroup, found bool) {
234 // handle fully qualified references like "//namespace_path:module_name"
235 nsName, moduleName, isAbs := r.parseFullyQualifiedName(name)
236 if isAbs {
237 namespace, found := r.namespaceAt(nsName)
238 if !found {
239 return blueprint.ModuleGroup{}, false
240 }
241 container := namespace.moduleContainer
242 return container.ModuleFromName(moduleName, nil)
243 }
244 for _, candidate := range r.getNamespacesToSearchForModule(namespace.(*Namespace)) {
245 group, found = candidate.moduleContainer.ModuleFromName(name, nil)
246 if found {
247 return group, true
248 }
249 }
250 return blueprint.ModuleGroup{}, false
251
252}
253
254func (r *NameResolver) Rename(oldName string, newName string, namespace blueprint.Namespace) []error {
Colin Crosseafb10c2018-04-16 13:58:10 -0700255 return namespace.(*Namespace).moduleContainer.Rename(oldName, newName, namespace)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800256}
257
258// resolve each element of namespace.importedNamespaceNames and put the result in namespace.visibleNamespaces
259func (r *NameResolver) FindNamespaceImports(namespace *Namespace) (err error) {
260 namespace.visibleNamespaces = make([]*Namespace, 0, 2+len(namespace.importedNamespaceNames))
261 // search itself first
262 namespace.visibleNamespaces = append(namespace.visibleNamespaces, namespace)
263 // search its imports next
264 for _, name := range namespace.importedNamespaceNames {
265 imp, ok := r.namespaceAt(name)
266 if !ok {
267 return fmt.Errorf("namespace %v does not exist", name)
268 }
269 namespace.visibleNamespaces = append(namespace.visibleNamespaces, imp)
270 }
271 // search the root namespace last
272 namespace.visibleNamespaces = append(namespace.visibleNamespaces, r.rootNamespace)
273 return nil
274}
275
Jeff Gastonb274ed32017-12-01 17:10:33 -0800276func (r *NameResolver) chooseId(namespace *Namespace) {
277 id := r.sortedNamespaces.index(namespace)
278 if id < 0 {
279 panic(fmt.Sprintf("Namespace not found: %v\n", namespace.id))
280 }
281 namespace.id = strconv.Itoa(id)
282}
283
Jeff Gaston088e29e2017-11-29 16:47:17 -0800284func (r *NameResolver) MissingDependencyError(depender string, dependerNamespace blueprint.Namespace, depName string) (err error) {
285 text := fmt.Sprintf("%q depends on undefined module %q", depender, depName)
286
287 _, _, isAbs := r.parseFullyQualifiedName(depName)
288 if isAbs {
289 // if the user gave a fully-qualified name, we don't need to look for other
290 // modules that they might have been referring to
291 return fmt.Errorf(text)
292 }
293
294 // determine which namespaces the module can be found in
295 foundInNamespaces := []string{}
296 for _, namespace := range r.sortedNamespaces.sortedItems() {
297 _, found := namespace.moduleContainer.ModuleFromName(depName, nil)
298 if found {
299 foundInNamespaces = append(foundInNamespaces, namespace.Path)
300 }
301 }
302 if len(foundInNamespaces) > 0 {
303 // determine which namespaces are visible to dependerNamespace
304 dependerNs := dependerNamespace.(*Namespace)
305 searched := r.getNamespacesToSearchForModule(dependerNs)
306 importedNames := []string{}
307 for _, ns := range searched {
308 importedNames = append(importedNames, ns.Path)
309 }
310 text += fmt.Sprintf("\nModule %q is defined in namespace %q which can read these %v namespaces: %q", depender, dependerNs.Path, len(importedNames), importedNames)
311 text += fmt.Sprintf("\nModule %q can be found in these namespaces: %q", depName, foundInNamespaces)
312 }
313
314 return fmt.Errorf(text)
315}
316
317func (r *NameResolver) GetNamespace(ctx blueprint.NamespaceContext) blueprint.Namespace {
318 return r.findNamespaceFromCtx(ctx)
319}
320
321func (r *NameResolver) findNamespaceFromCtx(ctx blueprint.NamespaceContext) *Namespace {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800322 return r.findNamespace(filepath.Dir(ctx.ModulePath()))
Jeff Gaston088e29e2017-11-29 16:47:17 -0800323}
324
Jeff Gastonb274ed32017-12-01 17:10:33 -0800325func (r *NameResolver) UniqueName(ctx blueprint.NamespaceContext, name string) (unique string) {
326 prefix := r.findNamespaceFromCtx(ctx).id
327 if prefix != "" {
328 prefix = prefix + "-"
329 }
330 return prefix + name
331}
332
Jeff Gaston088e29e2017-11-29 16:47:17 -0800333var _ blueprint.NameInterface = (*NameResolver)(nil)
334
335type Namespace struct {
336 blueprint.NamespaceMarker
337 Path string
338
339 // names of namespaces listed as imports by this namespace
340 importedNamespaceNames []string
341 // all namespaces that should be searched when a module in this namespace declares a dependency
342 visibleNamespaces []*Namespace
343
344 id string
345
346 exportToKati bool
347
348 moduleContainer blueprint.NameInterface
349}
350
351func NewNamespace(path string) *Namespace {
352 return &Namespace{Path: path, moduleContainer: blueprint.NewSimpleNameInterface()}
353}
354
355var _ blueprint.Namespace = (*Namespace)(nil)
356
Patrice Arruda64765aa2019-03-13 09:36:46 -0700357type namespaceProperties struct {
358 // a list of namespaces that contain modules that will be referenced
359 // by modules in this namespace.
360 Imports []string `android:"path"`
361}
362
Jeff Gaston088e29e2017-11-29 16:47:17 -0800363type NamespaceModule struct {
364 ModuleBase
365
366 namespace *Namespace
367 resolver *NameResolver
368
Patrice Arruda64765aa2019-03-13 09:36:46 -0700369 properties namespaceProperties
Jeff Gaston088e29e2017-11-29 16:47:17 -0800370}
371
Jeff Gaston088e29e2017-11-29 16:47:17 -0800372func (n *NamespaceModule) GenerateAndroidBuildActions(ctx ModuleContext) {
373}
374
375func (n *NamespaceModule) GenerateBuildActions(ctx blueprint.ModuleContext) {
376}
377
378func (n *NamespaceModule) Name() (name string) {
379 return *n.nameProperties.Name
380}
381
Patrice Arruda64765aa2019-03-13 09:36:46 -0700382// soong_namespace provides a scope to modules in an Android.bp file to prevent
383// module name conflicts with other defined modules in different Android.bp
384// files. Once soong_namespace has been defined in an Android.bp file, the
385// namespacing is applied to all modules that follow the soong_namespace in
386// the current Android.bp file, as well as modules defined in Android.bp files
387// in subdirectories. An Android.bp file in a subdirectory can define its own
388// soong_namespace which is applied to all its modules and as well as modules
389// defined in subdirectories Android.bp files. Modules in a soong_namespace are
390// visible to Make by listing the namespace path in PRODUCT_SOONG_NAMESPACES
391// make variable in a makefile.
Jeff Gaston088e29e2017-11-29 16:47:17 -0800392func NamespaceFactory() Module {
393 module := &NamespaceModule{}
394
395 name := "soong_namespace"
396 module.nameProperties.Name = &name
397
398 module.AddProperties(&module.properties)
399 return module
400}
401
402func RegisterNamespaceMutator(ctx RegisterMutatorsContext) {
Jeff Gastonb274ed32017-12-01 17:10:33 -0800403 ctx.BottomUp("namespace_deps", namespaceMutator).Parallel()
Jeff Gaston088e29e2017-11-29 16:47:17 -0800404}
405
Jeff Gastonb274ed32017-12-01 17:10:33 -0800406func namespaceMutator(ctx BottomUpMutatorContext) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800407 module, ok := ctx.Module().(*NamespaceModule)
408 if ok {
409 err := module.resolver.FindNamespaceImports(module.namespace)
410 if err != nil {
411 ctx.ModuleErrorf(err.Error())
412 }
Jeff Gastonb274ed32017-12-01 17:10:33 -0800413
414 module.resolver.chooseId(module.namespace)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800415 }
416}