blob: 1f8ef5a66032afd22593516e788d405cecdda423 [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
29// This file implements namespaces
30const (
31 namespacePrefix = "//"
32 modulePrefix = ":"
33)
34
35func init() {
36 RegisterModuleType("soong_namespace", NamespaceFactory)
37}
38
39// threadsafe sorted list
40type sortedNamespaces struct {
41 lock sync.Mutex
42 items []*Namespace
43 sorted bool
44}
45
46func (s *sortedNamespaces) add(namespace *Namespace) {
47 s.lock.Lock()
48 defer s.lock.Unlock()
49 if s.sorted {
50 panic("It is not supported to call sortedNamespaces.add() after sortedNamespaces.sortedItems()")
51 }
52 s.items = append(s.items, namespace)
53}
54
55func (s *sortedNamespaces) sortedItems() []*Namespace {
56 s.lock.Lock()
57 defer s.lock.Unlock()
58 if !s.sorted {
59 less := func(i int, j int) bool {
60 return s.items[i].Path < s.items[j].Path
61 }
62 sort.Slice(s.items, less)
63 s.sorted = true
64 }
65 return s.items
66}
67
Jeff Gastonb274ed32017-12-01 17:10:33 -080068func (s *sortedNamespaces) index(namespace *Namespace) int {
69 for i, candidate := range s.sortedItems() {
70 if namespace == candidate {
71 return i
72 }
73 }
74 return -1
75}
76
Jeff Gaston088e29e2017-11-29 16:47:17 -080077// A NameResolver implements blueprint.NameInterface, and implements the logic to
78// find a module from namespaces based on a query string.
79// A query string can be a module name or can be be "//namespace_path:module_path"
80type NameResolver struct {
81 rootNamespace *Namespace
82
83 // id counter for atomic.AddInt32
Jeff Gastonb274ed32017-12-01 17:10:33 -080084 nextNamespaceId int32
Jeff Gaston088e29e2017-11-29 16:47:17 -080085
86 // All namespaces, without duplicates.
87 sortedNamespaces sortedNamespaces
88
89 // Map from dir to namespace. Will have duplicates if two dirs are part of the same namespace.
90 namespacesByDir sync.Map // if generics were supported, this would be sync.Map[string]*Namespace
91
92 // func telling whether to export a namespace to Kati
93 namespaceExportFilter func(*Namespace) bool
94}
95
96func NewNameResolver(namespaceExportFilter func(*Namespace) bool) *NameResolver {
97 namespacesByDir := sync.Map{}
98
99 r := &NameResolver{
100 namespacesByDir: namespacesByDir,
101 namespaceExportFilter: namespaceExportFilter,
102 }
103 r.rootNamespace = r.newNamespace(".")
104 r.rootNamespace.visibleNamespaces = []*Namespace{r.rootNamespace}
105 r.addNamespace(r.rootNamespace)
106
107 return r
108}
109
110func (r *NameResolver) newNamespace(path string) *Namespace {
111 namespace := NewNamespace(path)
112
113 namespace.exportToKati = r.namespaceExportFilter(namespace)
114
Jeff Gaston088e29e2017-11-29 16:47:17 -0800115 return namespace
116}
117
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800118func (r *NameResolver) addNewNamespaceForModule(module *NamespaceModule, path string) error {
119 fileName := filepath.Base(path)
120 if fileName != "Android.bp" {
121 return errors.New("A namespace may only be declared in a file named Android.bp")
122 }
123 dir := filepath.Dir(path)
124
Jeff Gaston088e29e2017-11-29 16:47:17 -0800125 namespace := r.newNamespace(dir)
126 module.namespace = namespace
127 module.resolver = r
128 namespace.importedNamespaceNames = module.properties.Imports
129 return r.addNamespace(namespace)
130}
131
132func (r *NameResolver) addNamespace(namespace *Namespace) (err error) {
133 existingNamespace, exists := r.namespaceAt(namespace.Path)
134 if exists {
135 if existingNamespace.Path == namespace.Path {
136 return fmt.Errorf("namespace %v already exists", namespace.Path)
137 } else {
138 // It would probably confuse readers if namespaces were declared anywhere but
139 // the top of the file, so we forbid declaring namespaces after anything else.
140 return fmt.Errorf("a namespace must be the first module in the file")
141 }
142 }
143 r.sortedNamespaces.add(namespace)
144
145 r.namespacesByDir.Store(namespace.Path, namespace)
146 return nil
147}
148
149// non-recursive check for namespace
150func (r *NameResolver) namespaceAt(path string) (namespace *Namespace, found bool) {
151 mapVal, found := r.namespacesByDir.Load(path)
152 if !found {
153 return nil, false
154 }
155 return mapVal.(*Namespace), true
156}
157
158// recursive search upward for a namespace
159func (r *NameResolver) findNamespace(path string) (namespace *Namespace) {
160 namespace, found := r.namespaceAt(path)
161 if found {
162 return namespace
163 }
164 parentDir := filepath.Dir(path)
165 if parentDir == path {
166 return nil
167 }
168 namespace = r.findNamespace(parentDir)
169 r.namespacesByDir.Store(path, namespace)
170 return namespace
171}
172
173func (r *NameResolver) NewModule(ctx blueprint.NamespaceContext, moduleGroup blueprint.ModuleGroup, module blueprint.Module) (namespace blueprint.Namespace, errs []error) {
174 // if this module is a namespace, then save it to our list of namespaces
175 newNamespace, ok := module.(*NamespaceModule)
176 if ok {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800177 err := r.addNewNamespaceForModule(newNamespace, ctx.ModulePath())
Jeff Gaston088e29e2017-11-29 16:47:17 -0800178 if err != nil {
179 return nil, []error{err}
180 }
181 return nil, nil
182 }
183
184 // if this module is not a namespace, then save it into the appropriate namespace
185 ns := r.findNamespaceFromCtx(ctx)
186
187 _, errs = ns.moduleContainer.NewModule(ctx, moduleGroup, module)
188 if len(errs) > 0 {
189 return nil, errs
190 }
191
192 amod, ok := module.(Module)
193 if ok {
194 // inform the module whether its namespace is one that we want to export to Make
195 amod.base().commonProperties.NamespaceExportedToMake = ns.exportToKati
196 }
197
198 return ns, nil
199}
200
201func (r *NameResolver) AllModules() []blueprint.ModuleGroup {
202 childLists := [][]blueprint.ModuleGroup{}
203 totalCount := 0
204 for _, namespace := range r.sortedNamespaces.sortedItems() {
205 newModules := namespace.moduleContainer.AllModules()
206 totalCount += len(newModules)
207 childLists = append(childLists, newModules)
208 }
209
210 allModules := make([]blueprint.ModuleGroup, 0, totalCount)
211 for _, childList := range childLists {
212 allModules = append(allModules, childList...)
213 }
214 return allModules
215}
216
217// parses a fully-qualified path (like "//namespace_path:module_name") into a namespace name and a
218// module name
219func (r *NameResolver) parseFullyQualifiedName(name string) (namespaceName string, moduleName string, ok bool) {
220 if !strings.HasPrefix(name, namespacePrefix) {
221 return "", "", false
222 }
223 name = strings.TrimPrefix(name, namespacePrefix)
224 components := strings.Split(name, modulePrefix)
225 if len(components) != 2 {
226 return "", "", false
227 }
228 return components[0], components[1], true
229
230}
231
232func (r *NameResolver) getNamespacesToSearchForModule(sourceNamespace *Namespace) (searchOrder []*Namespace) {
233 return sourceNamespace.visibleNamespaces
234}
235
236func (r *NameResolver) ModuleFromName(name string, namespace blueprint.Namespace) (group blueprint.ModuleGroup, found bool) {
237 // handle fully qualified references like "//namespace_path:module_name"
238 nsName, moduleName, isAbs := r.parseFullyQualifiedName(name)
239 if isAbs {
240 namespace, found := r.namespaceAt(nsName)
241 if !found {
242 return blueprint.ModuleGroup{}, false
243 }
244 container := namespace.moduleContainer
245 return container.ModuleFromName(moduleName, nil)
246 }
247 for _, candidate := range r.getNamespacesToSearchForModule(namespace.(*Namespace)) {
248 group, found = candidate.moduleContainer.ModuleFromName(name, nil)
249 if found {
250 return group, true
251 }
252 }
253 return blueprint.ModuleGroup{}, false
254
255}
256
257func (r *NameResolver) Rename(oldName string, newName string, namespace blueprint.Namespace) []error {
258 oldNs := r.findNamespace(oldName)
259 newNs := r.findNamespace(newName)
260 if oldNs != newNs {
261 return []error{fmt.Errorf("cannot rename %v to %v because the destination is outside namespace %v", oldName, newName, oldNs.Path)}
262 }
263
264 oldName, err := filepath.Rel(oldNs.Path, oldName)
265 if err != nil {
266 panic(err)
267 }
268 newName, err = filepath.Rel(newNs.Path, newName)
269 if err != nil {
270 panic(err)
271 }
272
273 return oldNs.moduleContainer.Rename(oldName, newName, nil)
274}
275
276// resolve each element of namespace.importedNamespaceNames and put the result in namespace.visibleNamespaces
277func (r *NameResolver) FindNamespaceImports(namespace *Namespace) (err error) {
278 namespace.visibleNamespaces = make([]*Namespace, 0, 2+len(namespace.importedNamespaceNames))
279 // search itself first
280 namespace.visibleNamespaces = append(namespace.visibleNamespaces, namespace)
281 // search its imports next
282 for _, name := range namespace.importedNamespaceNames {
283 imp, ok := r.namespaceAt(name)
284 if !ok {
285 return fmt.Errorf("namespace %v does not exist", name)
286 }
287 namespace.visibleNamespaces = append(namespace.visibleNamespaces, imp)
288 }
289 // search the root namespace last
290 namespace.visibleNamespaces = append(namespace.visibleNamespaces, r.rootNamespace)
291 return nil
292}
293
Jeff Gastonb274ed32017-12-01 17:10:33 -0800294func (r *NameResolver) chooseId(namespace *Namespace) {
295 id := r.sortedNamespaces.index(namespace)
296 if id < 0 {
297 panic(fmt.Sprintf("Namespace not found: %v\n", namespace.id))
298 }
299 namespace.id = strconv.Itoa(id)
300}
301
Jeff Gaston088e29e2017-11-29 16:47:17 -0800302func (r *NameResolver) MissingDependencyError(depender string, dependerNamespace blueprint.Namespace, depName string) (err error) {
303 text := fmt.Sprintf("%q depends on undefined module %q", depender, depName)
304
305 _, _, isAbs := r.parseFullyQualifiedName(depName)
306 if isAbs {
307 // if the user gave a fully-qualified name, we don't need to look for other
308 // modules that they might have been referring to
309 return fmt.Errorf(text)
310 }
311
312 // determine which namespaces the module can be found in
313 foundInNamespaces := []string{}
314 for _, namespace := range r.sortedNamespaces.sortedItems() {
315 _, found := namespace.moduleContainer.ModuleFromName(depName, nil)
316 if found {
317 foundInNamespaces = append(foundInNamespaces, namespace.Path)
318 }
319 }
320 if len(foundInNamespaces) > 0 {
321 // determine which namespaces are visible to dependerNamespace
322 dependerNs := dependerNamespace.(*Namespace)
323 searched := r.getNamespacesToSearchForModule(dependerNs)
324 importedNames := []string{}
325 for _, ns := range searched {
326 importedNames = append(importedNames, ns.Path)
327 }
328 text += fmt.Sprintf("\nModule %q is defined in namespace %q which can read these %v namespaces: %q", depender, dependerNs.Path, len(importedNames), importedNames)
329 text += fmt.Sprintf("\nModule %q can be found in these namespaces: %q", depName, foundInNamespaces)
330 }
331
332 return fmt.Errorf(text)
333}
334
335func (r *NameResolver) GetNamespace(ctx blueprint.NamespaceContext) blueprint.Namespace {
336 return r.findNamespaceFromCtx(ctx)
337}
338
339func (r *NameResolver) findNamespaceFromCtx(ctx blueprint.NamespaceContext) *Namespace {
Jeff Gaston5c3886d2017-11-30 16:46:47 -0800340 return r.findNamespace(filepath.Dir(ctx.ModulePath()))
Jeff Gaston088e29e2017-11-29 16:47:17 -0800341}
342
Jeff Gastonb274ed32017-12-01 17:10:33 -0800343func (r *NameResolver) UniqueName(ctx blueprint.NamespaceContext, name string) (unique string) {
344 prefix := r.findNamespaceFromCtx(ctx).id
345 if prefix != "" {
346 prefix = prefix + "-"
347 }
348 return prefix + name
349}
350
Jeff Gaston088e29e2017-11-29 16:47:17 -0800351var _ blueprint.NameInterface = (*NameResolver)(nil)
352
353type Namespace struct {
354 blueprint.NamespaceMarker
355 Path string
356
357 // names of namespaces listed as imports by this namespace
358 importedNamespaceNames []string
359 // all namespaces that should be searched when a module in this namespace declares a dependency
360 visibleNamespaces []*Namespace
361
362 id string
363
364 exportToKati bool
365
366 moduleContainer blueprint.NameInterface
367}
368
369func NewNamespace(path string) *Namespace {
370 return &Namespace{Path: path, moduleContainer: blueprint.NewSimpleNameInterface()}
371}
372
373var _ blueprint.Namespace = (*Namespace)(nil)
374
375type NamespaceModule struct {
376 ModuleBase
377
378 namespace *Namespace
379 resolver *NameResolver
380
381 properties struct {
382 Imports []string
383 }
384}
385
386func (n *NamespaceModule) DepsMutator(context BottomUpMutatorContext) {
387}
388
389func (n *NamespaceModule) GenerateAndroidBuildActions(ctx ModuleContext) {
390}
391
392func (n *NamespaceModule) GenerateBuildActions(ctx blueprint.ModuleContext) {
393}
394
395func (n *NamespaceModule) Name() (name string) {
396 return *n.nameProperties.Name
397}
398
399func NamespaceFactory() Module {
400 module := &NamespaceModule{}
401
402 name := "soong_namespace"
403 module.nameProperties.Name = &name
404
405 module.AddProperties(&module.properties)
406 return module
407}
408
409func RegisterNamespaceMutator(ctx RegisterMutatorsContext) {
Jeff Gastonb274ed32017-12-01 17:10:33 -0800410 ctx.BottomUp("namespace_deps", namespaceMutator).Parallel()
Jeff Gaston088e29e2017-11-29 16:47:17 -0800411}
412
Jeff Gastonb274ed32017-12-01 17:10:33 -0800413func namespaceMutator(ctx BottomUpMutatorContext) {
Jeff Gaston088e29e2017-11-29 16:47:17 -0800414 module, ok := ctx.Module().(*NamespaceModule)
415 if ok {
416 err := module.resolver.FindNamespaceImports(module.namespace)
417 if err != nil {
418 ctx.ModuleErrorf(err.Error())
419 }
Jeff Gastonb274ed32017-12-01 17:10:33 -0800420
421 module.resolver.chooseId(module.namespace)
Jeff Gaston088e29e2017-11-29 16:47:17 -0800422 }
423}