blob: b43ffdf194949e93a7a45abe26a5e700a7903e22 [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() {
Paul Duffin4fbfb592021-07-09 16:47:38 +010030 registerNamespaceBuildComponents(InitRegistrationContext)
31}
32
33func registerNamespaceBuildComponents(ctx RegistrationContext) {
34 ctx.RegisterModuleType("soong_namespace", NamespaceFactory)
Jeff Gaston088e29e2017-11-29 16:47:17 -080035}
36
37// threadsafe sorted list
38type sortedNamespaces struct {
39 lock sync.Mutex
40 items []*Namespace
41 sorted bool
42}
43
44func (s *sortedNamespaces) add(namespace *Namespace) {
45 s.lock.Lock()
46 defer s.lock.Unlock()
47 if s.sorted {
48 panic("It is not supported to call sortedNamespaces.add() after sortedNamespaces.sortedItems()")
49 }
50 s.items = append(s.items, namespace)
51}
52
53func (s *sortedNamespaces) sortedItems() []*Namespace {
54 s.lock.Lock()
55 defer s.lock.Unlock()
56 if !s.sorted {
57 less := func(i int, j int) bool {
58 return s.items[i].Path < s.items[j].Path
59 }
60 sort.Slice(s.items, less)
61 s.sorted = true
62 }
63 return s.items
64}
65
Jeff Gastonb274ed32017-12-01 17:10:33 -080066func (s *sortedNamespaces) index(namespace *Namespace) int {
67 for i, candidate := range s.sortedItems() {
68 if namespace == candidate {
69 return i
70 }
71 }
72 return -1
73}
74
Jeff Gaston088e29e2017-11-29 16:47:17 -080075// A NameResolver implements blueprint.NameInterface, and implements the logic to
76// find a module from namespaces based on a query string.
Usta Shresthac725f472022-01-11 02:44:21 -050077// A query string can be a module name or can be "//namespace_path:module_path"
Jeff Gaston088e29e2017-11-29 16:47:17 -080078type NameResolver struct {
79 rootNamespace *Namespace
80
81 // id counter for atomic.AddInt32
Jeff Gastonb274ed32017-12-01 17:10:33 -080082 nextNamespaceId int32
Jeff Gaston088e29e2017-11-29 16:47:17 -080083
84 // All namespaces, without duplicates.
85 sortedNamespaces sortedNamespaces
86
87 // Map from dir to namespace. Will have duplicates if two dirs are part of the same namespace.
88 namespacesByDir sync.Map // if generics were supported, this would be sync.Map[string]*Namespace
89
90 // func telling whether to export a namespace to Kati
91 namespaceExportFilter func(*Namespace) bool
92}
93
Paul Duffin3f7bf9f2022-11-08 12:21:15 +000094// NameResolverConfig provides the subset of the Config interface needed by the
95// NewNameResolver function.
96type NameResolverConfig interface {
97 // ExportedNamespaces is the list of namespaces that Soong must export to
98 // make.
99 ExportedNamespaces() []string
100}
101
102func NewNameResolver(config NameResolverConfig) *NameResolver {
103 namespacePathsToExport := make(map[string]bool)
104
105 for _, namespaceName := range config.ExportedNamespaces() {
106 namespacePathsToExport[namespaceName] = true
107 }
108
109 namespacePathsToExport["."] = true // always export the root namespace
110
111 namespaceExportFilter := func(namespace *Namespace) bool {
112 return namespacePathsToExport[namespace.Path]
113 }
114
Jeff Gaston088e29e2017-11-29 16:47:17 -0800115 r := &NameResolver{
Dan Willemsen59339a22018-07-22 21:18:45 -0700116 namespacesByDir: sync.Map{},
Jeff Gaston088e29e2017-11-29 16:47:17 -0800117 namespaceExportFilter: namespaceExportFilter,
118 }
119 r.rootNamespace = r.newNamespace(".")
120 r.rootNamespace.visibleNamespaces = []*Namespace{r.rootNamespace}
121 r.addNamespace(r.rootNamespace)
122
123 return r
124}
125
126func (r *NameResolver) newNamespace(path string) *Namespace {
127 namespace := NewNamespace(path)
128
129 namespace.exportToKati = r.namespaceExportFilter(namespace)
130
Jeff Gaston088e29e2017-11-29 16:47:17 -0800131 return namespace
132}
133
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800134func (r *NameResolver) addNewNamespaceForModule(module *NamespaceModule, path string) error {
135 fileName := filepath.Base(path)
136 if fileName != "Android.bp" {
137 return errors.New("A namespace may only be declared in a file named Android.bp")
138 }
139 dir := filepath.Dir(path)
140
Jeff Gaston088e29e2017-11-29 16:47:17 -0800141 namespace := r.newNamespace(dir)
142 module.namespace = namespace
143 module.resolver = r
144 namespace.importedNamespaceNames = module.properties.Imports
145 return r.addNamespace(namespace)
146}
147
148func (r *NameResolver) addNamespace(namespace *Namespace) (err error) {
149 existingNamespace, exists := r.namespaceAt(namespace.Path)
150 if exists {
151 if existingNamespace.Path == namespace.Path {
152 return fmt.Errorf("namespace %v already exists", namespace.Path)
153 } else {
154 // It would probably confuse readers if namespaces were declared anywhere but
155 // the top of the file, so we forbid declaring namespaces after anything else.
156 return fmt.Errorf("a namespace must be the first module in the file")
157 }
158 }
159 r.sortedNamespaces.add(namespace)
160
161 r.namespacesByDir.Store(namespace.Path, namespace)
162 return nil
163}
164
165// non-recursive check for namespace
166func (r *NameResolver) namespaceAt(path string) (namespace *Namespace, found bool) {
167 mapVal, found := r.namespacesByDir.Load(path)
168 if !found {
169 return nil, false
170 }
171 return mapVal.(*Namespace), true
172}
173
174// recursive search upward for a namespace
175func (r *NameResolver) findNamespace(path string) (namespace *Namespace) {
176 namespace, found := r.namespaceAt(path)
177 if found {
178 return namespace
179 }
180 parentDir := filepath.Dir(path)
181 if parentDir == path {
182 return nil
183 }
184 namespace = r.findNamespace(parentDir)
185 r.namespacesByDir.Store(path, namespace)
186 return namespace
187}
188
Colin Crossa6389e92022-06-22 16:44:07 -0700189// A NamespacelessModule can never be looked up by name. It must still implement Name(), and the name
190// still has to be unique.
191type NamespacelessModule interface {
192 Namespaceless()
Colin Cross9d34f352019-11-22 16:03:51 -0800193}
194
Jeff Gaston088e29e2017-11-29 16:47:17 -0800195func (r *NameResolver) NewModule(ctx blueprint.NamespaceContext, moduleGroup blueprint.ModuleGroup, module blueprint.Module) (namespace blueprint.Namespace, errs []error) {
196 // if this module is a namespace, then save it to our list of namespaces
197 newNamespace, ok := module.(*NamespaceModule)
198 if ok {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800199 err := r.addNewNamespaceForModule(newNamespace, ctx.ModulePath())
Jeff Gaston088e29e2017-11-29 16:47:17 -0800200 if err != nil {
201 return nil, []error{err}
202 }
203 return nil, nil
204 }
205
Colin Crossa6389e92022-06-22 16:44:07 -0700206 if _, ok := module.(NamespacelessModule); ok {
Colin Cross9d34f352019-11-22 16:03:51 -0800207 return nil, nil
208 }
209
Jeff Gaston088e29e2017-11-29 16:47:17 -0800210 // if this module is not a namespace, then save it into the appropriate namespace
211 ns := r.findNamespaceFromCtx(ctx)
212
213 _, errs = ns.moduleContainer.NewModule(ctx, moduleGroup, module)
214 if len(errs) > 0 {
215 return nil, errs
216 }
217
218 amod, ok := module.(Module)
219 if ok {
220 // inform the module whether its namespace is one that we want to export to Make
221 amod.base().commonProperties.NamespaceExportedToMake = ns.exportToKati
Colin Cross31a738b2019-12-30 18:45:15 -0800222 amod.base().commonProperties.DebugName = module.Name()
Jeff Gaston088e29e2017-11-29 16:47:17 -0800223 }
224
225 return ns, nil
226}
227
228func (r *NameResolver) AllModules() []blueprint.ModuleGroup {
229 childLists := [][]blueprint.ModuleGroup{}
230 totalCount := 0
231 for _, namespace := range r.sortedNamespaces.sortedItems() {
232 newModules := namespace.moduleContainer.AllModules()
233 totalCount += len(newModules)
234 childLists = append(childLists, newModules)
235 }
236
237 allModules := make([]blueprint.ModuleGroup, 0, totalCount)
238 for _, childList := range childLists {
239 allModules = append(allModules, childList...)
240 }
241 return allModules
242}
243
244// parses a fully-qualified path (like "//namespace_path:module_name") into a namespace name and a
245// module name
246func (r *NameResolver) parseFullyQualifiedName(name string) (namespaceName string, moduleName string, ok bool) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000247 if !strings.HasPrefix(name, "//") {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800248 return "", "", false
249 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000250 name = strings.TrimPrefix(name, "//")
251 components := strings.Split(name, ":")
Jeff Gaston088e29e2017-11-29 16:47:17 -0800252 if len(components) != 2 {
253 return "", "", false
254 }
255 return components[0], components[1], true
256
257}
258
Bob Badour38620ed2020-12-17 16:30:00 -0800259func (r *NameResolver) getNamespacesToSearchForModule(sourceNamespace blueprint.Namespace) (searchOrder []*Namespace) {
260 ns, ok := sourceNamespace.(*Namespace)
261 if !ok || ns.visibleNamespaces == nil {
Colin Crosscd84b4e2019-06-14 11:26:09 -0700262 // When handling dependencies before namespaceMutator, assume they are non-Soong Blueprint modules and give
263 // access to all namespaces.
264 return r.sortedNamespaces.sortedItems()
265 }
Bob Badour38620ed2020-12-17 16:30:00 -0800266 return ns.visibleNamespaces
Jeff Gaston088e29e2017-11-29 16:47:17 -0800267}
268
269func (r *NameResolver) ModuleFromName(name string, namespace blueprint.Namespace) (group blueprint.ModuleGroup, found bool) {
270 // handle fully qualified references like "//namespace_path:module_name"
271 nsName, moduleName, isAbs := r.parseFullyQualifiedName(name)
272 if isAbs {
273 namespace, found := r.namespaceAt(nsName)
274 if !found {
275 return blueprint.ModuleGroup{}, false
276 }
277 container := namespace.moduleContainer
278 return container.ModuleFromName(moduleName, nil)
279 }
Bob Badour38620ed2020-12-17 16:30:00 -0800280 for _, candidate := range r.getNamespacesToSearchForModule(namespace) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800281 group, found = candidate.moduleContainer.ModuleFromName(name, nil)
282 if found {
283 return group, true
284 }
285 }
286 return blueprint.ModuleGroup{}, false
287
288}
289
290func (r *NameResolver) Rename(oldName string, newName string, namespace blueprint.Namespace) []error {
Colin Crosseafb10c2018-04-16 13:58:10 -0700291 return namespace.(*Namespace).moduleContainer.Rename(oldName, newName, namespace)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800292}
293
294// resolve each element of namespace.importedNamespaceNames and put the result in namespace.visibleNamespaces
295func (r *NameResolver) FindNamespaceImports(namespace *Namespace) (err error) {
296 namespace.visibleNamespaces = make([]*Namespace, 0, 2+len(namespace.importedNamespaceNames))
297 // search itself first
298 namespace.visibleNamespaces = append(namespace.visibleNamespaces, namespace)
299 // search its imports next
300 for _, name := range namespace.importedNamespaceNames {
301 imp, ok := r.namespaceAt(name)
302 if !ok {
303 return fmt.Errorf("namespace %v does not exist", name)
304 }
305 namespace.visibleNamespaces = append(namespace.visibleNamespaces, imp)
306 }
307 // search the root namespace last
308 namespace.visibleNamespaces = append(namespace.visibleNamespaces, r.rootNamespace)
309 return nil
310}
311
Jeff Gastonb274ed32017-12-01 17:10:33 -0800312func (r *NameResolver) chooseId(namespace *Namespace) {
313 id := r.sortedNamespaces.index(namespace)
314 if id < 0 {
315 panic(fmt.Sprintf("Namespace not found: %v\n", namespace.id))
316 }
317 namespace.id = strconv.Itoa(id)
318}
319
Jeff Gaston088e29e2017-11-29 16:47:17 -0800320func (r *NameResolver) MissingDependencyError(depender string, dependerNamespace blueprint.Namespace, depName string) (err error) {
321 text := fmt.Sprintf("%q depends on undefined module %q", depender, depName)
322
323 _, _, isAbs := r.parseFullyQualifiedName(depName)
324 if isAbs {
325 // if the user gave a fully-qualified name, we don't need to look for other
326 // modules that they might have been referring to
327 return fmt.Errorf(text)
328 }
329
330 // determine which namespaces the module can be found in
331 foundInNamespaces := []string{}
332 for _, namespace := range r.sortedNamespaces.sortedItems() {
333 _, found := namespace.moduleContainer.ModuleFromName(depName, nil)
334 if found {
335 foundInNamespaces = append(foundInNamespaces, namespace.Path)
336 }
337 }
338 if len(foundInNamespaces) > 0 {
339 // determine which namespaces are visible to dependerNamespace
340 dependerNs := dependerNamespace.(*Namespace)
341 searched := r.getNamespacesToSearchForModule(dependerNs)
342 importedNames := []string{}
343 for _, ns := range searched {
344 importedNames = append(importedNames, ns.Path)
345 }
346 text += fmt.Sprintf("\nModule %q is defined in namespace %q which can read these %v namespaces: %q", depender, dependerNs.Path, len(importedNames), importedNames)
347 text += fmt.Sprintf("\nModule %q can be found in these namespaces: %q", depName, foundInNamespaces)
348 }
349
350 return fmt.Errorf(text)
351}
352
353func (r *NameResolver) GetNamespace(ctx blueprint.NamespaceContext) blueprint.Namespace {
354 return r.findNamespaceFromCtx(ctx)
355}
356
357func (r *NameResolver) findNamespaceFromCtx(ctx blueprint.NamespaceContext) *Namespace {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800358 return r.findNamespace(filepath.Dir(ctx.ModulePath()))
Jeff Gaston088e29e2017-11-29 16:47:17 -0800359}
360
Jeff Gastonb274ed32017-12-01 17:10:33 -0800361func (r *NameResolver) UniqueName(ctx blueprint.NamespaceContext, name string) (unique string) {
362 prefix := r.findNamespaceFromCtx(ctx).id
363 if prefix != "" {
364 prefix = prefix + "-"
365 }
366 return prefix + name
367}
368
Jeff Gaston088e29e2017-11-29 16:47:17 -0800369var _ blueprint.NameInterface = (*NameResolver)(nil)
370
371type Namespace struct {
372 blueprint.NamespaceMarker
373 Path string
374
375 // names of namespaces listed as imports by this namespace
376 importedNamespaceNames []string
377 // all namespaces that should be searched when a module in this namespace declares a dependency
378 visibleNamespaces []*Namespace
379
380 id string
381
382 exportToKati bool
383
384 moduleContainer blueprint.NameInterface
385}
386
387func NewNamespace(path string) *Namespace {
388 return &Namespace{Path: path, moduleContainer: blueprint.NewSimpleNameInterface()}
389}
390
391var _ blueprint.Namespace = (*Namespace)(nil)
392
Patrice Arruda64765aa2019-03-13 09:36:46 -0700393type namespaceProperties struct {
394 // a list of namespaces that contain modules that will be referenced
395 // by modules in this namespace.
396 Imports []string `android:"path"`
397}
398
Jeff Gaston088e29e2017-11-29 16:47:17 -0800399type NamespaceModule struct {
400 ModuleBase
401
402 namespace *Namespace
403 resolver *NameResolver
404
Patrice Arruda64765aa2019-03-13 09:36:46 -0700405 properties namespaceProperties
Jeff Gaston088e29e2017-11-29 16:47:17 -0800406}
407
Jeff Gaston088e29e2017-11-29 16:47:17 -0800408func (n *NamespaceModule) GenerateAndroidBuildActions(ctx ModuleContext) {
409}
410
411func (n *NamespaceModule) GenerateBuildActions(ctx blueprint.ModuleContext) {
412}
413
414func (n *NamespaceModule) Name() (name string) {
415 return *n.nameProperties.Name
416}
417
Patrice Arruda64765aa2019-03-13 09:36:46 -0700418// soong_namespace provides a scope to modules in an Android.bp file to prevent
419// module name conflicts with other defined modules in different Android.bp
420// files. Once soong_namespace has been defined in an Android.bp file, the
421// namespacing is applied to all modules that follow the soong_namespace in
422// the current Android.bp file, as well as modules defined in Android.bp files
423// in subdirectories. An Android.bp file in a subdirectory can define its own
424// soong_namespace which is applied to all its modules and as well as modules
425// defined in subdirectories Android.bp files. Modules in a soong_namespace are
426// visible to Make by listing the namespace path in PRODUCT_SOONG_NAMESPACES
427// make variable in a makefile.
Jeff Gaston088e29e2017-11-29 16:47:17 -0800428func NamespaceFactory() Module {
429 module := &NamespaceModule{}
430
431 name := "soong_namespace"
432 module.nameProperties.Name = &name
433
434 module.AddProperties(&module.properties)
435 return module
436}
437
438func RegisterNamespaceMutator(ctx RegisterMutatorsContext) {
Jeff Gastonb274ed32017-12-01 17:10:33 -0800439 ctx.BottomUp("namespace_deps", namespaceMutator).Parallel()
Jeff Gaston088e29e2017-11-29 16:47:17 -0800440}
441
Jeff Gastonb274ed32017-12-01 17:10:33 -0800442func namespaceMutator(ctx BottomUpMutatorContext) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800443 module, ok := ctx.Module().(*NamespaceModule)
444 if ok {
445 err := module.resolver.FindNamespaceImports(module.namespace)
446 if err != nil {
447 ctx.ModuleErrorf(err.Error())
448 }
Jeff Gastonb274ed32017-12-01 17:10:33 -0800449
450 module.resolver.chooseId(module.namespace)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800451 }
452}