xref: /aosp_15_r20/build/blueprint/singleton_ctx.go (revision 1fa6dee971e1612fa5cc0aa5ca2d35a22e2c34a3)
1// Copyright 2014 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 blueprint
16
17import (
18	"fmt"
19
20	"github.com/google/blueprint/pathtools"
21)
22
23type Singleton interface {
24	GenerateBuildActions(SingletonContext)
25}
26
27type SingletonContext interface {
28	// Config returns the config object that was passed to Context.PrepareBuildActions.
29	Config() interface{}
30
31	// Name returns the name of the current singleton passed to Context.RegisterSingletonType
32	Name() string
33
34	// ModuleName returns the name of the given Module.  See BaseModuleContext.ModuleName for more information.
35	ModuleName(module Module) string
36
37	// ModuleDir returns the directory of the given Module.  See BaseModuleContext.ModuleDir for more information.
38	ModuleDir(module Module) string
39
40	// ModuleSubDir returns the unique subdirectory name of the given Module.  See ModuleContext.ModuleSubDir for
41	// more information.
42	ModuleSubDir(module Module) string
43
44	// ModuleType returns the type of the given Module.  See BaseModuleContext.ModuleType for more information.
45	ModuleType(module Module) string
46
47	// BlueprintFile returns the path of the Blueprint file that defined the given module.
48	BlueprintFile(module Module) string
49
50	// ModuleProvider returns the value, if any, for the provider for a module.  If the value for the
51	// provider was not set it returns the zero value of the type of the provider, which means the
52	// return value can always be type-asserted to the type of the provider.  The return value should
53	// always be considered read-only.  It panics if called before the appropriate mutator or
54	// GenerateBuildActions pass for the provider on the module.
55	ModuleProvider(module Module, provider AnyProviderKey) (any, bool)
56
57	// ModuleErrorf reports an error at the line number of the module type in the module definition.
58	ModuleErrorf(module Module, format string, args ...interface{})
59
60	// Errorf reports an error at the specified position of the module definition file.
61	Errorf(format string, args ...interface{})
62
63	// OtherModulePropertyErrorf reports an error on the line number of the given property of the given module
64	OtherModulePropertyErrorf(module Module, property string, format string, args ...interface{})
65
66	// Failed returns true if any errors have been reported.  In most cases the singleton can continue with generating
67	// build rules after an error, allowing it to report additional errors in a single run, but in cases where the error
68	// has prevented the singleton from creating necessary data it can return early when Failed returns true.
69	Failed() bool
70
71	// Variable creates a new ninja variable scoped to the singleton.  It can be referenced by calls to Rule and Build
72	// in the same singleton.
73	Variable(pctx PackageContext, name, value string)
74
75	// Rule creates a new ninja rule scoped to the singleton.  It can be referenced by calls to Build in the same
76	// singleton.
77	Rule(pctx PackageContext, name string, params RuleParams, argNames ...string) Rule
78
79	// Build creates a new ninja build statement.
80	Build(pctx PackageContext, params BuildParams)
81
82	// RequireNinjaVersion sets the generated ninja manifest to require at least the specified version of ninja.
83	RequireNinjaVersion(major, minor, micro int)
84
85	// SetOutDir sets the value of the top-level "builddir" Ninja variable
86	// that controls where Ninja stores its build log files.  This value can be
87	// set at most one time for a single build, later calls are ignored.
88	SetOutDir(pctx PackageContext, value string)
89
90	// AddSubninja adds a ninja file to include with subninja. This should likely
91	// only ever be used inside bootstrap to handle glob rules.
92	AddSubninja(file string)
93
94	// Eval takes a string with embedded ninja variables, and returns a string
95	// with all of the variables recursively expanded. Any variables references
96	// are expanded in the scope of the PackageContext.
97	Eval(pctx PackageContext, ninjaStr string) (string, error)
98
99	// VisitAllModules calls visit for each defined variant of each module in an unspecified order.
100	VisitAllModules(visit func(Module))
101
102	// VisitAllModuleProxies calls visit for each defined variant of each module in an unspecified order.
103	VisitAllModuleProxies(visit func(proxy ModuleProxy))
104
105	// VisitAllModules calls pred for each defined variant of each module in an unspecified order, and if pred returns
106	// true calls visit.
107	VisitAllModulesIf(pred func(Module) bool, visit func(Module))
108
109	// VisitDirectDeps calls visit for each direct dependency of the Module.  If there are
110	// multiple direct dependencies on the same module visit will be called multiple times on
111	// that module and OtherModuleDependencyTag will return a different tag for each.
112	//
113	// The Module passed to the visit function should not be retained outside of the visit
114	// function, it may be invalidated by future mutators.
115	VisitDirectDeps(module Module, visit func(Module))
116
117	// VisitDirectDepsIf calls pred for each direct dependency of the Module, and if pred
118	// returns true calls visit.  If there are multiple direct dependencies on the same module
119	// pred and visit will be called multiple times on that module and OtherModuleDependencyTag
120	// will return a different tag for each.
121	//
122	// The Module passed to the visit function should not be retained outside of the visit
123	// function, it may be invalidated by future mutators.
124	VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module))
125
126	// VisitDepsDepthFirst calls visit for each transitive dependency, traversing the dependency tree in depth first
127	// order. visit will only be called once for any given module, even if there are multiple paths through the
128	// dependency tree to the module or multiple direct dependencies with different tags.
129	VisitDepsDepthFirst(module Module, visit func(Module))
130
131	// VisitDepsDepthFirst calls pred for each transitive dependency, and if pred returns true calls visit, traversing
132	// the dependency tree in depth first order.  visit will only be called once for any given module, even if there are
133	// multiple paths through the dependency tree to the module or multiple direct dependencies with different tags.
134	VisitDepsDepthFirstIf(module Module, pred func(Module) bool,
135		visit func(Module))
136
137	// VisitAllModuleVariants calls visit for each variant of the given module.
138	VisitAllModuleVariants(module Module, visit func(Module))
139
140	// VisitAllModuleVariantProxies calls visit for each variant of the given module.
141	VisitAllModuleVariantProxies(module Module, visit func(proxy ModuleProxy))
142
143	// PrimaryModule returns the first variant of the given module.  This can be used to perform
144	//	// singleton actions that are only done once for all variants of a module.
145	PrimaryModule(module Module) Module
146
147	// IsFinalModule returns if the given module is the last variant. This can be used to perform
148	// singleton actions that are only done once for all variants of a module.
149	IsFinalModule(module Module) bool
150
151	// AddNinjaFileDeps adds dependencies on the specified files to the rule that creates the ninja manifest.  The
152	// primary builder will be rerun whenever the specified files are modified.
153	AddNinjaFileDeps(deps ...string)
154
155	// GlobWithDeps returns a list of files and directories that match the
156	// specified pattern but do not match any of the patterns in excludes.
157	// Any directories will have a '/' suffix. It also adds efficient
158	// dependencies to rerun the primary builder whenever a file matching
159	// the pattern as added or removed, without rerunning if a file that
160	// does not match the pattern is added to a searched directory.
161	GlobWithDeps(pattern string, excludes []string) ([]string, error)
162
163	// Fs returns a pathtools.Filesystem that can be used to interact with files.  Using the Filesystem interface allows
164	// the singleton to be used in build system tests that run against a mock filesystem.
165	Fs() pathtools.FileSystem
166
167	// ModuleVariantsFromName returns the list of module variants named `name` in the same namespace as `referer`.
168	// Allows generating build actions for `referer` based on the metadata for `name` deferred until the singleton context.
169	ModuleVariantsFromName(referer Module, name string) []Module
170
171	// HasMutatorFinished returns true if the given mutator has finished running.
172	// It will panic if given an invalid mutator name.
173	HasMutatorFinished(mutatorName string) bool
174}
175
176var _ SingletonContext = (*singletonContext)(nil)
177
178type singletonContext struct {
179	name    string
180	context *Context
181	config  interface{}
182	scope   *localScope
183	globals *liveTracker
184
185	ninjaFileDeps []string
186	errs          []error
187
188	actionDefs localBuildActions
189}
190
191func (s *singletonContext) Config() interface{} {
192	return s.config
193}
194
195func (s *singletonContext) Name() string {
196	return s.name
197}
198
199func (s *singletonContext) ModuleName(logicModule Module) string {
200	return s.context.ModuleName(getWrappedModule(logicModule))
201}
202
203func (s *singletonContext) ModuleDir(logicModule Module) string {
204	return s.context.ModuleDir(getWrappedModule(logicModule))
205}
206
207func (s *singletonContext) ModuleSubDir(logicModule Module) string {
208	return s.context.ModuleSubDir(getWrappedModule(logicModule))
209}
210
211func (s *singletonContext) ModuleType(logicModule Module) string {
212	return s.context.ModuleType(getWrappedModule(logicModule))
213}
214
215func (s *singletonContext) ModuleProvider(logicModule Module, provider AnyProviderKey) (any, bool) {
216	return s.context.ModuleProvider(getWrappedModule(logicModule), provider)
217}
218
219func (s *singletonContext) BlueprintFile(logicModule Module) string {
220	return s.context.BlueprintFile(logicModule)
221}
222
223func (s *singletonContext) error(err error) {
224	if err != nil {
225		s.errs = append(s.errs, err)
226	}
227}
228
229func (s *singletonContext) ModuleErrorf(logicModule Module, format string,
230	args ...interface{}) {
231
232	s.error(s.context.ModuleErrorf(logicModule, format, args...))
233}
234
235func (s *singletonContext) Errorf(format string, args ...interface{}) {
236	// TODO: Make this not result in the error being printed as "internal error"
237	s.error(fmt.Errorf(format, args...))
238}
239
240func (s *singletonContext) OtherModulePropertyErrorf(logicModule Module, property string, format string,
241	args ...interface{}) {
242
243	s.error(s.context.PropertyErrorf(logicModule, property, format, args...))
244}
245
246func (s *singletonContext) Failed() bool {
247	return len(s.errs) > 0
248}
249
250func (s *singletonContext) Variable(pctx PackageContext, name, value string) {
251	s.scope.ReparentTo(pctx)
252
253	v, err := s.scope.AddLocalVariable(name, value)
254	if err != nil {
255		panic(err)
256	}
257
258	s.actionDefs.variables = append(s.actionDefs.variables, v)
259}
260
261func (s *singletonContext) Rule(pctx PackageContext, name string,
262	params RuleParams, argNames ...string) Rule {
263
264	s.scope.ReparentTo(pctx)
265
266	r, err := s.scope.AddLocalRule(name, &params, argNames...)
267	if err != nil {
268		panic(err)
269	}
270
271	s.actionDefs.rules = append(s.actionDefs.rules, r)
272
273	return r
274}
275
276func (s *singletonContext) Build(pctx PackageContext, params BuildParams) {
277	s.scope.ReparentTo(pctx)
278
279	def, err := parseBuildParams(s.scope, &params, map[string]string{
280		"module_name": s.name,
281		"module_type": "singleton",
282	})
283	if err != nil {
284		panic(err)
285	}
286
287	s.actionDefs.buildDefs = append(s.actionDefs.buildDefs, def)
288}
289
290func (s *singletonContext) Eval(pctx PackageContext, str string) (string, error) {
291	s.scope.ReparentTo(pctx)
292
293	ninjaStr, err := parseNinjaString(s.scope, str)
294	if err != nil {
295		return "", err
296	}
297
298	err = s.globals.addNinjaStringDeps(ninjaStr)
299	if err != nil {
300		return "", err
301	}
302
303	return s.globals.Eval(ninjaStr)
304}
305
306func (s *singletonContext) RequireNinjaVersion(major, minor, micro int) {
307	s.context.requireNinjaVersion(major, minor, micro)
308}
309
310func (s *singletonContext) SetOutDir(pctx PackageContext, value string) {
311	s.scope.ReparentTo(pctx)
312
313	ninjaValue, err := parseNinjaString(s.scope, value)
314	if err != nil {
315		panic(err)
316	}
317
318	s.context.setOutDir(ninjaValue)
319}
320
321func (s *singletonContext) AddSubninja(file string) {
322	s.context.subninjas = append(s.context.subninjas, file)
323}
324
325func (s *singletonContext) VisitAllModules(visit func(Module)) {
326	var visitingModule Module
327	defer func() {
328		if r := recover(); r != nil {
329			panic(newPanicErrorf(r, "VisitAllModules(%s) for module %s",
330				funcName(visit), s.context.moduleInfo[visitingModule]))
331		}
332	}()
333
334	s.context.VisitAllModules(func(m Module) {
335		visitingModule = m
336		visit(m)
337	})
338}
339
340func (s *singletonContext) VisitAllModuleProxies(visit func(proxy ModuleProxy)) {
341	s.VisitAllModules(visitProxyAdaptor(visit))
342}
343
344func (s *singletonContext) VisitAllModulesIf(pred func(Module) bool,
345	visit func(Module)) {
346
347	s.context.VisitAllModulesIf(pred, visit)
348}
349
350func (s *singletonContext) VisitDirectDeps(module Module, visit func(Module)) {
351	s.context.VisitDirectDeps(module, visit)
352}
353
354func (s *singletonContext) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
355	s.context.VisitDirectDepsIf(module, pred, visit)
356}
357
358func (s *singletonContext) VisitDepsDepthFirst(module Module,
359	visit func(Module)) {
360
361	s.context.VisitDepsDepthFirst(module, visit)
362}
363
364func (s *singletonContext) VisitDepsDepthFirstIf(module Module,
365	pred func(Module) bool, visit func(Module)) {
366
367	s.context.VisitDepsDepthFirstIf(module, pred, visit)
368}
369
370func (s *singletonContext) PrimaryModule(module Module) Module {
371	return s.context.PrimaryModule(module)
372}
373
374func (s *singletonContext) IsFinalModule(module Module) bool {
375	return s.context.IsFinalModule(module)
376}
377
378func (s *singletonContext) VisitAllModuleVariants(module Module, visit func(Module)) {
379	s.context.VisitAllModuleVariants(module, visit)
380}
381
382func (s *singletonContext) VisitAllModuleVariantProxies(module Module, visit func(proxy ModuleProxy)) {
383	s.context.VisitAllModuleVariants(module, visitProxyAdaptor(visit))
384}
385
386func (s *singletonContext) AddNinjaFileDeps(deps ...string) {
387	s.ninjaFileDeps = append(s.ninjaFileDeps, deps...)
388}
389
390func (s *singletonContext) GlobWithDeps(pattern string,
391	excludes []string) ([]string, error) {
392	return s.context.glob(pattern, excludes)
393}
394
395func (s *singletonContext) Fs() pathtools.FileSystem {
396	return s.context.fs
397}
398
399func (s *singletonContext) ModuleVariantsFromName(referer Module, name string) []Module {
400	c := s.context
401
402	refererInfo := c.moduleInfo[referer]
403	if refererInfo == nil {
404		s.ModuleErrorf(referer, "could not find module %q", referer.Name())
405		return nil
406	}
407
408	moduleGroup, exists := c.nameInterface.ModuleFromName(name, refererInfo.namespace())
409	if !exists {
410		return nil
411	}
412	result := make([]Module, 0, len(moduleGroup.modules))
413	for _, moduleInfo := range moduleGroup.modules {
414		result = append(result, moduleInfo.logicModule)
415	}
416	return result
417}
418
419func (s *singletonContext) HasMutatorFinished(mutatorName string) bool {
420	return s.context.HasMutatorFinished(mutatorName)
421}
422
423func visitProxyAdaptor(visit func(proxy ModuleProxy)) func(module Module) {
424	return func(module Module) {
425		visit(ModuleProxy{
426			module: module,
427		})
428	}
429}
430