blob: 631e88ff9dafeb66738806735cb9360ca207292a [file] [log] [blame]
Paul Duffin2e61fa62019-03-28 14:10:57 +00001// Copyright 2019 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 (
18 "fmt"
19 "regexp"
Paul Duffin157f40f2020-09-29 16:01:08 +010020 "sort"
Paul Duffin2e61fa62019-03-28 14:10:57 +000021 "strings"
22 "sync"
Paul Duffin78ac5b92020-01-14 12:42:08 +000023
24 "github.com/google/blueprint"
Paul Duffin2e61fa62019-03-28 14:10:57 +000025)
26
27// Enforces visibility rules between modules.
28//
Paul Duffine2453c72019-05-31 14:00:04 +010029// Multi stage process:
30// * First stage works bottom up, before defaults expansion, to check the syntax of the visibility
31// rules that have been specified.
32//
33// * Second stage works bottom up to extract the package info for each package and store them in a
34// map by package name. See package.go for functionality for this.
35//
36// * Third stage works bottom up to extract visibility information from the modules, parse it,
Paul Duffin2e61fa62019-03-28 14:10:57 +000037// create visibilityRule structures and store them in a map keyed by the module's
38// qualifiedModuleName instance, i.e. //<pkg>:<name>. The map is stored in the context rather
39// than a global variable for testing. Each test has its own Config so they do not share a map
Paul Duffine2453c72019-05-31 14:00:04 +010040// and so can be run in parallel. If a module has no visibility specified then it uses the
41// default package visibility if specified.
Paul Duffin2e61fa62019-03-28 14:10:57 +000042//
Paul Duffine2453c72019-05-31 14:00:04 +010043// * Fourth stage works top down and iterates over all the deps for each module. If the dep is in
Paul Duffin2e61fa62019-03-28 14:10:57 +000044// the same package then it is automatically visible. Otherwise, for each dep it first extracts
45// its visibilityRule from the config map. If one could not be found then it assumes that it is
46// publicly visible. Otherwise, it calls the visibility rule to check that the module can see
47// the dependency. If it cannot then an error is reported.
48//
49// TODO(b/130631145) - Make visibility work properly with prebuilts.
50// TODO(b/130796911) - Make visibility work properly with defaults.
51
52// Patterns for the values that can be specified in visibility property.
53const (
54 packagePattern = `//([^/:]+(?:/[^/:]+)*)`
55 namePattern = `:([^/:]+)`
56 visibilityRulePattern = `^(?:` + packagePattern + `)?(?:` + namePattern + `)?$`
57)
58
59var visibilityRuleRegexp = regexp.MustCompile(visibilityRulePattern)
60
Paul Duffin2e61fa62019-03-28 14:10:57 +000061// A visibility rule is associated with a module and determines which other modules it is visible
62// to, i.e. which other modules can depend on the rule's module.
63type visibilityRule interface {
64 // Check to see whether this rules matches m.
65 // Returns true if it does, false otherwise.
66 matches(m qualifiedModuleName) bool
67
68 String() string
69}
70
Paul Duffine2453c72019-05-31 14:00:04 +010071// Describes the properties provided by a module that contain visibility rules.
72type visibilityPropertyImpl struct {
Paul Duffin63c6e182019-07-24 14:24:38 +010073 name string
74 stringsProperty *[]string
Paul Duffine2453c72019-05-31 14:00:04 +010075}
76
77type visibilityProperty interface {
78 getName() string
79 getStrings() []string
80}
81
Paul Duffin63c6e182019-07-24 14:24:38 +010082func newVisibilityProperty(name string, stringsProperty *[]string) visibilityProperty {
Paul Duffine2453c72019-05-31 14:00:04 +010083 return visibilityPropertyImpl{
Paul Duffin63c6e182019-07-24 14:24:38 +010084 name: name,
85 stringsProperty: stringsProperty,
Paul Duffine2453c72019-05-31 14:00:04 +010086 }
87}
88
89func (p visibilityPropertyImpl) getName() string {
90 return p.name
91}
92
93func (p visibilityPropertyImpl) getStrings() []string {
Paul Duffin63c6e182019-07-24 14:24:38 +010094 return *p.stringsProperty
Paul Duffine2453c72019-05-31 14:00:04 +010095}
96
Martin Stjernholm226b20d2019-05-17 22:42:02 +010097// A compositeRule is a visibility rule composed from a list of atomic visibility rules.
98//
99// The list corresponds to the list of strings in the visibility property after defaults expansion.
100// Even though //visibility:public is not allowed together with other rules in the visibility list
101// of a single module, it is allowed here to permit a module to override an inherited visibility
102// spec with public visibility.
103//
104// //visibility:private is not allowed in the same way, since we'd need to check for it during the
105// defaults expansion to make that work. No non-private visibility rules are allowed in a
106// compositeRule containing a privateRule.
107//
Paul Duffin2e61fa62019-03-28 14:10:57 +0000108// This array will only be [] if all the rules are invalid and will behave as if visibility was
109// ["//visibility:private"].
110type compositeRule []visibilityRule
111
112// A compositeRule matches if and only if any of its rules matches.
113func (c compositeRule) matches(m qualifiedModuleName) bool {
114 for _, r := range c {
115 if r.matches(m) {
116 return true
117 }
118 }
119 return false
120}
121
Paul Duffine2453c72019-05-31 14:00:04 +0100122func (c compositeRule) String() string {
Paul Duffin593b3c92019-12-05 14:31:48 +0000123 return "[" + strings.Join(c.Strings(), ", ") + "]"
124}
125
126func (c compositeRule) Strings() []string {
Paul Duffine2453c72019-05-31 14:00:04 +0100127 s := make([]string, 0, len(c))
128 for _, r := range c {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000129 s = append(s, r.String())
130 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000131 return s
Paul Duffin2e61fa62019-03-28 14:10:57 +0000132}
133
134// A packageRule is a visibility rule that matches modules in a specific package (i.e. directory).
135type packageRule struct {
136 pkg string
137}
138
139func (r packageRule) matches(m qualifiedModuleName) bool {
140 return m.pkg == r.pkg
141}
142
143func (r packageRule) String() string {
Martin Stjernholm01407c52020-05-13 01:54:21 +0100144 return fmt.Sprintf("//%s", r.pkg) // :__pkg__ is the default, so skip it.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000145}
146
147// A subpackagesRule is a visibility rule that matches modules in a specific package (i.e.
148// directory) or any of its subpackages (i.e. subdirectories).
149type subpackagesRule struct {
150 pkgPrefix string
151}
152
153func (r subpackagesRule) matches(m qualifiedModuleName) bool {
154 return isAncestor(r.pkgPrefix, m.pkg)
155}
156
157func isAncestor(p1 string, p2 string) bool {
158 return strings.HasPrefix(p2+"/", p1+"/")
159}
160
161func (r subpackagesRule) String() string {
162 return fmt.Sprintf("//%s:__subpackages__", r.pkgPrefix)
163}
164
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100165// visibilityRule for //visibility:public
166type publicRule struct{}
167
168func (r publicRule) matches(_ qualifiedModuleName) bool {
169 return true
170}
171
172func (r publicRule) String() string {
173 return "//visibility:public"
174}
175
176// visibilityRule for //visibility:private
177type privateRule struct{}
178
179func (r privateRule) matches(_ qualifiedModuleName) bool {
180 return false
181}
182
183func (r privateRule) String() string {
184 return "//visibility:private"
185}
186
Paul Duffin2e61fa62019-03-28 14:10:57 +0000187var visibilityRuleMap = NewOnceKey("visibilityRuleMap")
188
189// The map from qualifiedModuleName to visibilityRule.
Paul Duffin44885e22020-02-19 16:10:09 +0000190func moduleToVisibilityRuleMap(config Config) *sync.Map {
191 return config.Once(visibilityRuleMap, func() interface{} {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000192 return &sync.Map{}
193 }).(*sync.Map)
194}
195
Paul Duffin78ac5b92020-01-14 12:42:08 +0000196// Marker interface that identifies dependencies that are excluded from visibility
197// enforcement.
198type ExcludeFromVisibilityEnforcementTag interface {
199 blueprint.DependencyTag
200
201 // Method that differentiates this interface from others.
202 ExcludeFromVisibilityEnforcement()
203}
204
Paul Duffincfd33742021-02-27 11:59:02 +0000205var PrepareForTestWithVisibilityRuleChecker = FixtureRegisterWithContext(func(ctx RegistrationContext) {
206 ctx.PreArchMutators(RegisterVisibilityRuleChecker)
207})
208
209var PrepareForTestWithVisibilityRuleGatherer = FixtureRegisterWithContext(func(ctx RegistrationContext) {
210 ctx.PreArchMutators(RegisterVisibilityRuleGatherer)
211})
212
213var PrepareForTestWithVisibilityRuleEnforcer = FixtureRegisterWithContext(func(ctx RegistrationContext) {
214 ctx.PostDepsMutators(RegisterVisibilityRuleEnforcer)
215})
216
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100217// The rule checker needs to be registered before defaults expansion to correctly check that
218// //visibility:xxx isn't combined with other packages in the same list in any one module.
Paul Duffin593b3c92019-12-05 14:31:48 +0000219func RegisterVisibilityRuleChecker(ctx RegisterMutatorsContext) {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100220 ctx.BottomUp("visibilityRuleChecker", visibilityRuleChecker).Parallel()
221}
222
Paul Duffine2453c72019-05-31 14:00:04 +0100223// Registers the function that gathers the visibility rules for each module.
224//
Paul Duffin2e61fa62019-03-28 14:10:57 +0000225// Visibility is not dependent on arch so this must be registered before the arch phase to avoid
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100226// having to process multiple variants for each module. This goes after defaults expansion to gather
Paul Duffine2453c72019-05-31 14:00:04 +0100227// the complete visibility lists from flat lists and after the package info is gathered to ensure
228// that default_visibility is available.
Paul Duffin593b3c92019-12-05 14:31:48 +0000229func RegisterVisibilityRuleGatherer(ctx RegisterMutatorsContext) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000230 ctx.BottomUp("visibilityRuleGatherer", visibilityRuleGatherer).Parallel()
231}
232
233// This must be registered after the deps have been resolved.
Paul Duffin593b3c92019-12-05 14:31:48 +0000234func RegisterVisibilityRuleEnforcer(ctx RegisterMutatorsContext) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000235 ctx.TopDown("visibilityRuleEnforcer", visibilityRuleEnforcer).Parallel()
236}
237
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100238// Checks the per-module visibility rule lists before defaults expansion.
239func visibilityRuleChecker(ctx BottomUpMutatorContext) {
240 qualified := createQualifiedModuleName(ctx)
Paul Duffin63c6e182019-07-24 14:24:38 +0100241 if m, ok := ctx.Module().(Module); ok {
Paul Duffine2453c72019-05-31 14:00:04 +0100242 visibilityProperties := m.visibilityProperties()
243 for _, p := range visibilityProperties {
244 if visibility := p.getStrings(); visibility != nil {
245 checkRules(ctx, qualified.pkg, p.getName(), visibility)
246 }
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100247 }
248 }
249}
250
Paul Duffine2453c72019-05-31 14:00:04 +0100251func checkRules(ctx BaseModuleContext, currentPkg, property string, visibility []string) {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100252 ruleCount := len(visibility)
253 if ruleCount == 0 {
254 // This prohibits an empty list as its meaning is unclear, e.g. it could mean no visibility and
255 // it could mean public visibility. Requiring at least one rule makes the owner's intent
256 // clearer.
Paul Duffine2453c72019-05-31 14:00:04 +0100257 ctx.PropertyErrorf(property, "must contain at least one visibility rule")
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100258 return
259 }
260
Paul Duffin51084ff2020-05-05 19:19:22 +0100261 for i, v := range visibility {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100262 ok, pkg, name := splitRule(ctx, v, currentPkg, property)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100263 if !ok {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100264 continue
265 }
266
267 if pkg == "visibility" {
268 switch name {
269 case "private", "public":
270 case "legacy_public":
Paul Duffine2453c72019-05-31 14:00:04 +0100271 ctx.PropertyErrorf(property, "//visibility:legacy_public must not be used")
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100272 continue
Paul Duffin51084ff2020-05-05 19:19:22 +0100273 case "override":
274 // This keyword does not create a rule so pretend it does not exist.
275 ruleCount -= 1
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100276 default:
Paul Duffine2453c72019-05-31 14:00:04 +0100277 ctx.PropertyErrorf(property, "unrecognized visibility rule %q", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100278 continue
279 }
Paul Duffin51084ff2020-05-05 19:19:22 +0100280 if name == "override" {
281 if i != 0 {
282 ctx.PropertyErrorf(property, `"%v" may only be used at the start of the visibility rules`, v)
283 }
284 } else if ruleCount != 1 {
Paul Duffine2453c72019-05-31 14:00:04 +0100285 ctx.PropertyErrorf(property, "cannot mix %q with any other visibility rules", v)
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100286 continue
287 }
288 }
289
290 // If the current directory is not in the vendor tree then there are some additional
291 // restrictions on the rules.
292 if !isAncestor("vendor", currentPkg) {
293 if !isAllowedFromOutsideVendor(pkg, name) {
Paul Duffine2453c72019-05-31 14:00:04 +0100294 ctx.PropertyErrorf(property,
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100295 "%q is not allowed. Packages outside //vendor cannot make themselves visible to specific"+
296 " targets within //vendor, they can only use //vendor:__subpackages__.", v)
297 continue
298 }
299 }
300 }
301}
302
303// Gathers the flattened visibility rules after defaults expansion, parses the visibility
304// properties, stores them in a map by qualifiedModuleName for retrieval during enforcement.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000305//
306// See ../README.md#Visibility for information on the format of the visibility rules.
Paul Duffin2e61fa62019-03-28 14:10:57 +0000307func visibilityRuleGatherer(ctx BottomUpMutatorContext) {
308 m, ok := ctx.Module().(Module)
309 if !ok {
310 return
311 }
312
Paul Duffine2453c72019-05-31 14:00:04 +0100313 qualifiedModuleId := m.qualifiedModuleId(ctx)
314 currentPkg := qualifiedModuleId.pkg
Paul Duffin2e61fa62019-03-28 14:10:57 +0000315
Paul Duffin63c6e182019-07-24 14:24:38 +0100316 // Parse the visibility rules that control access to the module and store them by id
317 // for use when enforcing the rules.
Paul Duffin0c83aba2020-05-01 18:13:36 +0100318 primaryProperty := m.base().primaryVisibilityProperty
319 if primaryProperty != nil {
320 if visibility := primaryProperty.getStrings(); visibility != nil {
321 rule := parseRules(ctx, currentPkg, primaryProperty.getName(), visibility)
322 if rule != nil {
323 moduleToVisibilityRuleMap(ctx.Config()).Store(qualifiedModuleId, rule)
324 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000325 }
326 }
327}
328
Paul Duffin0c83aba2020-05-01 18:13:36 +0100329func parseRules(ctx BaseModuleContext, currentPkg, property string, visibility []string) compositeRule {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100330 rules := make(compositeRule, 0, len(visibility))
331 hasPrivateRule := false
Paul Duffin44885e22020-02-19 16:10:09 +0000332 hasPublicRule := false
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100333 hasNonPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000334 for _, v := range visibility {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100335 ok, pkg, name := splitRule(ctx, v, currentPkg, property)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000336 if !ok {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000337 continue
338 }
339
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100340 var r visibilityRule
341 isPrivateRule := false
Paul Duffin2e61fa62019-03-28 14:10:57 +0000342 if pkg == "visibility" {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000343 switch name {
344 case "private":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100345 r = privateRule{}
346 isPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000347 case "public":
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100348 r = publicRule{}
Paul Duffin44885e22020-02-19 16:10:09 +0000349 hasPublicRule = true
Paul Duffin51084ff2020-05-05 19:19:22 +0100350 case "override":
351 // Discard all preceding rules and any state based on them.
352 rules = nil
353 hasPrivateRule = false
354 hasPublicRule = false
355 hasNonPrivateRule = false
356 // This does not actually create a rule so continue onto the next rule.
357 continue
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100358 }
359 } else {
360 switch name {
361 case "__pkg__":
362 r = packageRule{pkg}
363 case "__subpackages__":
364 r = subpackagesRule{pkg}
Paul Duffin2e61fa62019-03-28 14:10:57 +0000365 default:
Liz Kammer873f4b62020-10-15 08:42:01 -0700366 ctx.PropertyErrorf(property, "invalid visibility pattern %q. Must match "+
367 " //<package>:<scope>, //<package> or :<scope> "+
368 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
369 v)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000370 }
371 }
372
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100373 if isPrivateRule {
374 hasPrivateRule = true
375 } else {
376 hasNonPrivateRule = true
Paul Duffin2e61fa62019-03-28 14:10:57 +0000377 }
378
379 rules = append(rules, r)
380 }
381
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100382 if hasPrivateRule && hasNonPrivateRule {
383 ctx.PropertyErrorf("visibility",
384 "cannot mix \"//visibility:private\" with any other visibility rules")
385 return compositeRule{privateRule{}}
386 }
387
Paul Duffin44885e22020-02-19 16:10:09 +0000388 if hasPublicRule {
389 // Public overrides all other rules so just return it.
390 return compositeRule{publicRule{}}
391 }
392
Paul Duffin2e61fa62019-03-28 14:10:57 +0000393 return rules
394}
395
396func isAllowedFromOutsideVendor(pkg string, name string) bool {
397 if pkg == "vendor" {
398 if name == "__subpackages__" {
399 return true
400 }
401 return false
402 }
403
404 return !isAncestor("vendor", pkg)
405}
406
Paul Duffin0c83aba2020-05-01 18:13:36 +0100407func splitRule(ctx BaseModuleContext, ruleExpression string, currentPkg, property string) (bool, string, string) {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000408 // Make sure that the rule is of the correct format.
409 matches := visibilityRuleRegexp.FindStringSubmatch(ruleExpression)
410 if ruleExpression == "" || matches == nil {
Paul Duffin0c83aba2020-05-01 18:13:36 +0100411 // Visibility rule is invalid so ignore it. Keep going rather than aborting straight away to
412 // ensure all the rules on this module are checked.
413 ctx.PropertyErrorf(property,
414 "invalid visibility pattern %q must match"+
Liz Kammer873f4b62020-10-15 08:42:01 -0700415 " //<package>:<scope>, //<package> or :<scope> "+
416 "where <scope> is one of \"__pkg__\", \"__subpackages__\"",
Paul Duffin0c83aba2020-05-01 18:13:36 +0100417 ruleExpression)
Paul Duffin2e61fa62019-03-28 14:10:57 +0000418 return false, "", ""
419 }
420
421 // Extract the package and name.
422 pkg := matches[1]
423 name := matches[2]
424
425 // Normalize the short hands
426 if pkg == "" {
427 pkg = currentPkg
428 }
429 if name == "" {
430 name = "__pkg__"
431 }
432
433 return true, pkg, name
434}
435
436func visibilityRuleEnforcer(ctx TopDownMutatorContext) {
Martin Stjernholm226b20d2019-05-17 22:42:02 +0100437 if _, ok := ctx.Module().(Module); !ok {
Paul Duffin2e61fa62019-03-28 14:10:57 +0000438 return
439 }
440
441 qualified := createQualifiedModuleName(ctx)
442
Paul Duffin2e61fa62019-03-28 14:10:57 +0000443 // Visit all the dependencies making sure that this module has access to them all.
444 ctx.VisitDirectDeps(func(dep Module) {
Paul Duffin78ac5b92020-01-14 12:42:08 +0000445 // Ignore dependencies that have an ExcludeFromVisibilityEnforcementTag
446 tag := ctx.OtherModuleDependencyTag(dep)
447 if _, ok := tag.(ExcludeFromVisibilityEnforcementTag); ok {
448 return
449 }
450
Paul Duffin2e61fa62019-03-28 14:10:57 +0000451 depName := ctx.OtherModuleName(dep)
452 depDir := ctx.OtherModuleDir(dep)
453 depQualified := qualifiedModuleName{depDir, depName}
454
455 // Targets are always visible to other targets in their own package.
456 if depQualified.pkg == qualified.pkg {
457 return
458 }
459
Paul Duffin44885e22020-02-19 16:10:09 +0000460 rule := effectiveVisibilityRules(ctx.Config(), depQualified)
Paul Duffind99d9972020-09-29 16:00:55 +0100461 if !rule.matches(qualified) {
Liz Kammere501bb42020-10-15 11:46:38 -0700462 ctx.ModuleErrorf("depends on %s which is not visible to this module\nYou may need to add %q to its visibility", depQualified, "//"+ctx.ModuleDir())
Paul Duffine2453c72019-05-31 14:00:04 +0100463 }
Paul Duffin2e61fa62019-03-28 14:10:57 +0000464 })
465}
466
Paul Duffind99d9972020-09-29 16:00:55 +0100467// Default visibility is public.
468var defaultVisibility = compositeRule{publicRule{}}
469
470// Return the effective visibility rules.
471//
472// If no rules have been specified this will return the default visibility rule
473// which is currently //visibility:public.
Paul Duffin44885e22020-02-19 16:10:09 +0000474func effectiveVisibilityRules(config Config, qualified qualifiedModuleName) compositeRule {
475 moduleToVisibilityRule := moduleToVisibilityRuleMap(config)
Paul Duffin593b3c92019-12-05 14:31:48 +0000476 value, ok := moduleToVisibilityRule.Load(qualified)
477 var rule compositeRule
478 if ok {
479 rule = value.(compositeRule)
480 } else {
Paul Duffin44885e22020-02-19 16:10:09 +0000481 rule = packageDefaultVisibility(config, qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000482 }
Paul Duffind99d9972020-09-29 16:00:55 +0100483
484 // If no rule is specified then return the default visibility rule to avoid
485 // every caller having to treat nil as public.
486 if rule == nil {
487 rule = defaultVisibility
488 }
Paul Duffin593b3c92019-12-05 14:31:48 +0000489 return rule
490}
491
Paul Duffin2e61fa62019-03-28 14:10:57 +0000492func createQualifiedModuleName(ctx BaseModuleContext) qualifiedModuleName {
493 moduleName := ctx.ModuleName()
494 dir := ctx.ModuleDir()
495 qualified := qualifiedModuleName{dir, moduleName}
496 return qualified
497}
Paul Duffine484f472019-06-20 16:38:08 +0100498
Paul Duffin44885e22020-02-19 16:10:09 +0000499func packageDefaultVisibility(config Config, moduleId qualifiedModuleName) compositeRule {
500 moduleToVisibilityRule := moduleToVisibilityRuleMap(config)
Paul Duffine484f472019-06-20 16:38:08 +0100501 packageQualifiedId := moduleId.getContainingPackageId()
502 for {
503 value, ok := moduleToVisibilityRule.Load(packageQualifiedId)
504 if ok {
505 return value.(compositeRule)
506 }
507
508 if packageQualifiedId.isRootPackage() {
509 return nil
510 }
511
512 packageQualifiedId = packageQualifiedId.getContainingPackageId()
513 }
514}
Paul Duffin593b3c92019-12-05 14:31:48 +0000515
Paul Duffin157f40f2020-09-29 16:01:08 +0100516type VisibilityRuleSet interface {
517 // Widen the visibility with some extra rules.
518 Widen(extra []string) error
519
520 Strings() []string
521}
522
523type visibilityRuleSet struct {
524 rules []string
525}
526
527var _ VisibilityRuleSet = (*visibilityRuleSet)(nil)
528
529func (v *visibilityRuleSet) Widen(extra []string) error {
530 // Check the extra rules first just in case they are invalid. Otherwise, if
531 // the current visibility is public then the extra rules will just be ignored.
532 if len(extra) == 1 {
533 singularRule := extra[0]
534 switch singularRule {
535 case "//visibility:public":
536 // Public overrides everything so just discard any existing rules.
537 v.rules = extra
538 return nil
539 case "//visibility:private":
540 // Extending rule with private is an error.
541 return fmt.Errorf("%q does not widen the visibility", singularRule)
542 }
543 }
544
545 if len(v.rules) == 1 {
546 switch v.rules[0] {
547 case "//visibility:public":
548 // No point in adding rules to something which is already public.
549 return nil
550 case "//visibility:private":
551 // Adding any rules to private means it is no longer private so the
552 // private can be discarded.
553 v.rules = nil
554 }
555 }
556
557 v.rules = FirstUniqueStrings(append(v.rules, extra...))
558 sort.Strings(v.rules)
559 return nil
560}
561
562func (v *visibilityRuleSet) Strings() []string {
563 return v.rules
564}
565
Paul Duffin593b3c92019-12-05 14:31:48 +0000566// Get the effective visibility rules, i.e. the actual rules that affect the visibility of the
567// property irrespective of where they are defined.
568//
569// Includes visibility rules specified by package default_visibility and/or on defaults.
570// Short hand forms, e.g. //:__subpackages__ are replaced with their full form, e.g.
571// //package/containing/rule:__subpackages__.
Paul Duffin157f40f2020-09-29 16:01:08 +0100572func EffectiveVisibilityRules(ctx BaseModuleContext, module Module) VisibilityRuleSet {
Paul Duffin593b3c92019-12-05 14:31:48 +0000573 moduleName := ctx.OtherModuleName(module)
574 dir := ctx.OtherModuleDir(module)
575 qualified := qualifiedModuleName{dir, moduleName}
576
Paul Duffin44885e22020-02-19 16:10:09 +0000577 rule := effectiveVisibilityRules(ctx.Config(), qualified)
Paul Duffin593b3c92019-12-05 14:31:48 +0000578
Martin Stjernholm0641d182020-05-13 02:20:06 +0100579 // Modules are implicitly visible to other modules in the same package,
580 // without checking the visibility rules. Here we need to add that visibility
581 // explicitly.
Paul Duffind99d9972020-09-29 16:00:55 +0100582 if !rule.matches(qualified) {
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100583 if len(rule) == 1 {
584 if _, ok := rule[0].(privateRule); ok {
585 // If the rule is //visibility:private we can't append another
586 // visibility to it. Semantically we need to convert it to a package
587 // visibility rule for the location where the result is used, but since
588 // modules are implicitly visible within the package we get the same
589 // result without any rule at all, so just make it an empty list to be
590 // appended below.
Paul Duffind99d9972020-09-29 16:00:55 +0100591 rule = nil
Martin Stjernholm64aeaad2020-05-13 22:11:40 +0100592 }
593 }
Martin Stjernholm0641d182020-05-13 02:20:06 +0100594 rule = append(rule, packageRule{dir})
595 }
596
Paul Duffin157f40f2020-09-29 16:01:08 +0100597 return &visibilityRuleSet{rule.Strings()}
Paul Duffin593b3c92019-12-05 14:31:48 +0000598}
Paul Duffin5ec73ec2020-05-01 17:52:01 +0100599
600// Clear the default visibility properties so they can be replaced.
601func clearVisibilityProperties(module Module) {
602 module.base().visibilityPropertyInfo = nil
603}
604
605// Add a property that contains visibility rules so that they are checked for
606// correctness.
607func AddVisibilityProperty(module Module, name string, stringsProperty *[]string) {
608 addVisibilityProperty(module, name, stringsProperty)
609}
610
611func addVisibilityProperty(module Module, name string, stringsProperty *[]string) visibilityProperty {
612 base := module.base()
613 property := newVisibilityProperty(name, stringsProperty)
614 base.visibilityPropertyInfo = append(base.visibilityPropertyInfo, property)
615 return property
616}
617
618// Set the primary visibility property.
619//
620// Also adds the property to the list of properties to be validated.
621func setPrimaryVisibilityProperty(module Module, name string, stringsProperty *[]string) {
622 module.base().primaryVisibilityProperty = addVisibilityProperty(module, name, stringsProperty)
623}