blob: e0442ce3945c744adbaa0befdb6d21f4269aed9f [file] [log] [blame]
Colin Cross8e0c5112015-01-23 14:15:10 -08001// 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
Jamie Gennis1bc967e2014-05-27 16:34:41 -070015package blueprint
16
17import (
Jamie Gennis1bc967e2014-05-27 16:34:41 -070018 "bytes"
Colin Cross3a8c0252019-01-23 13:21:48 -080019 "context"
Lukacs T. Berki6f682822021-04-01 18:27:31 +020020 "encoding/json"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070021 "errors"
22 "fmt"
23 "io"
Jeff Gastonc3e28442017-08-09 15:13:12 -070024 "io/ioutil"
Jeff Gastonaca42202017-08-23 17:30:05 -070025 "os"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070026 "path/filepath"
27 "reflect"
Romain Guy28529652014-08-12 17:50:11 -070028 "runtime"
Colin Cross3a8c0252019-01-23 13:21:48 -080029 "runtime/pprof"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070030 "sort"
31 "strings"
Colin Cross127d2ea2016-11-01 11:10:51 -070032 "sync"
Colin Cross23d7aa12015-06-30 16:05:22 -070033 "sync/atomic"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070034 "text/scanner"
35 "text/template"
Colin Cross1fef5362015-04-20 16:50:54 -070036
37 "github.com/google/blueprint/parser"
Colin Crossb519a7e2017-02-01 13:21:35 -080038 "github.com/google/blueprint/pathtools"
Colin Cross1fef5362015-04-20 16:50:54 -070039 "github.com/google/blueprint/proptools"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070040)
41
42var ErrBuildActionsNotReady = errors.New("build actions are not ready")
43
44const maxErrors = 10
Jeff Gaston9f630902017-11-15 14:49:48 -080045const MockModuleListFile = "bplist"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070046
Jamie Gennisd4e10182014-06-12 20:06:50 -070047// A Context contains all the state needed to parse a set of Blueprints files
48// and generate a Ninja file. The process of generating a Ninja file proceeds
49// through a series of four phases. Each phase corresponds with a some methods
50// on the Context object
51//
52// Phase Methods
53// ------------ -------------------------------------------
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070054// 1. Registration RegisterModuleType, RegisterSingletonType
Jamie Gennisd4e10182014-06-12 20:06:50 -070055//
56// 2. Parse ParseBlueprintsFiles, Parse
57//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070058// 3. Generate ResolveDependencies, PrepareBuildActions
Jamie Gennisd4e10182014-06-12 20:06:50 -070059//
60// 4. Write WriteBuildFile
61//
62// The registration phase prepares the context to process Blueprints files
63// containing various types of modules. The parse phase reads in one or more
64// Blueprints files and validates their contents against the module types that
65// have been registered. The generate phase then analyzes the parsed Blueprints
66// contents to create an internal representation for the build actions that must
67// be performed. This phase also performs validation of the module dependencies
68// and property values defined in the parsed Blueprints files. Finally, the
69// write phase generates the Ninja manifest text based on the generated build
70// actions.
Jamie Gennis1bc967e2014-05-27 16:34:41 -070071type Context struct {
Colin Cross3a8c0252019-01-23 13:21:48 -080072 context.Context
73
Jamie Gennis1bc967e2014-05-27 16:34:41 -070074 // set at instantiation
Colin Cross65569e42015-03-10 20:08:19 -070075 moduleFactories map[string]ModuleFactory
Jeff Gastond70bf752017-11-10 15:12:08 -080076 nameInterface NameInterface
Colin Cross0b7e83e2016-05-17 14:58:05 -070077 moduleGroups []*moduleGroup
Colin Cross65569e42015-03-10 20:08:19 -070078 moduleInfo map[Module]*moduleInfo
79 modulesSorted []*moduleInfo
Colin Cross5f03f112017-11-07 13:29:54 -080080 preSingletonInfo []*singletonInfo
Yuchen Wub9103ef2015-08-25 17:58:17 -070081 singletonInfo []*singletonInfo
Colin Cross65569e42015-03-10 20:08:19 -070082 mutatorInfo []*mutatorInfo
Colin Crossf8b50422016-08-10 12:56:40 -070083 earlyMutatorInfo []*mutatorInfo
Colin Cross65569e42015-03-10 20:08:19 -070084 variantMutatorNames []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070085
Colin Cross3702ac72016-08-11 11:09:00 -070086 depsModified uint32 // positive if a mutator modified the dependencies
87
Jamie Gennis1bc967e2014-05-27 16:34:41 -070088 dependenciesReady bool // set to true on a successful ResolveDependencies
89 buildActionsReady bool // set to true on a successful PrepareBuildActions
90
91 // set by SetIgnoreUnknownModuleTypes
92 ignoreUnknownModuleTypes bool
93
Colin Cross036a1df2015-12-17 15:49:30 -080094 // set by SetAllowMissingDependencies
95 allowMissingDependencies bool
96
Jamie Gennis1bc967e2014-05-27 16:34:41 -070097 // set during PrepareBuildActions
Dan Willemsenaeffbf72015-11-25 15:29:32 -080098 pkgNames map[*packageContext]string
Colin Cross5f03f112017-11-07 13:29:54 -080099 liveGlobals *liveTracker
Colin Cross2ce594e2020-01-29 12:58:03 -0800100 globalVariables map[Variable]ninjaString
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700101 globalPools map[Pool]*poolDef
102 globalRules map[Rule]*ruleDef
103
104 // set during PrepareBuildActions
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +0200105 outDir ninjaString // The builddir special Ninja variable
Colin Cross2ce594e2020-01-29 12:58:03 -0800106 requiredNinjaMajor int // For the ninja_required_version variable
107 requiredNinjaMinor int // For the ninja_required_version variable
108 requiredNinjaMicro int // For the ninja_required_version variable
Jamie Gennisc15544d2014-09-24 20:26:52 -0700109
Dan Willemsenab223a52018-07-05 21:56:59 -0700110 subninjas []string
111
Jeff Gastond70bf752017-11-10 15:12:08 -0800112 // set lazily by sortedModuleGroups
113 cachedSortedModuleGroups []*moduleGroup
Liz Kammer9ae14f12020-11-30 16:30:45 -0700114 // cache deps modified to determine whether cachedSortedModuleGroups needs to be recalculated
115 cachedDepsModified bool
Colin Crossd7b0f602016-06-02 15:30:20 -0700116
Colin Cross25236982021-04-05 17:20:34 -0700117 globs map[globKey]pathtools.GlobResult
Colin Cross127d2ea2016-11-01 11:10:51 -0700118 globLock sync.Mutex
119
Colin Crossc5fa50e2019-12-17 13:12:35 -0800120 srcDir string
Jeff Gastonc3e28442017-08-09 15:13:12 -0700121 fs pathtools.FileSystem
122 moduleListFile string
Colin Cross2da84922020-07-02 10:08:12 -0700123
124 // Mutators indexed by the ID of the provider associated with them. Not all mutators will
125 // have providers, and not all providers will have a mutator, or if they do the mutator may
126 // not be registered in this Context.
127 providerMutators []*mutatorInfo
128
129 // The currently running mutator
130 startedMutator *mutatorInfo
131 // True for any mutators that have already run over all modules
132 finishedMutators map[*mutatorInfo]bool
133
134 // Can be set by tests to avoid invalidating Module values after mutators.
135 skipCloneModulesAfterMutators bool
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700136}
137
Jamie Gennisd4e10182014-06-12 20:06:50 -0700138// An Error describes a problem that was encountered that is related to a
139// particular location in a Blueprints file.
Colin Cross2c628442016-10-07 17:13:10 -0700140type BlueprintError struct {
Jamie Gennisd4e10182014-06-12 20:06:50 -0700141 Err error // the error that occurred
142 Pos scanner.Position // the relevant Blueprints file location
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700143}
144
Colin Cross2c628442016-10-07 17:13:10 -0700145// A ModuleError describes a problem that was encountered that is related to a
146// particular module in a Blueprints file
147type ModuleError struct {
148 BlueprintError
149 module *moduleInfo
150}
151
152// A PropertyError describes a problem that was encountered that is related to a
153// particular property in a Blueprints file
154type PropertyError struct {
155 ModuleError
156 property string
157}
158
159func (e *BlueprintError) Error() string {
160 return fmt.Sprintf("%s: %s", e.Pos, e.Err)
161}
162
163func (e *ModuleError) Error() string {
164 return fmt.Sprintf("%s: %s: %s", e.Pos, e.module, e.Err)
165}
166
167func (e *PropertyError) Error() string {
168 return fmt.Sprintf("%s: %s: %s: %s", e.Pos, e.module, e.property, e.Err)
169}
170
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700171type localBuildActions struct {
172 variables []*localVariable
173 rules []*localRule
174 buildDefs []*buildDef
175}
176
Colin Crossf7beb892019-11-13 20:11:14 -0800177type moduleAlias struct {
Colin Crossedc41762020-08-13 12:07:30 -0700178 variant variant
179 target *moduleInfo
Colin Crossf7beb892019-11-13 20:11:14 -0800180}
181
Colin Cross5df74a82020-08-24 16:18:21 -0700182func (m *moduleAlias) alias() *moduleAlias { return m }
183func (m *moduleAlias) module() *moduleInfo { return nil }
184func (m *moduleAlias) moduleOrAliasTarget() *moduleInfo { return m.target }
185func (m *moduleAlias) moduleOrAliasVariant() variant { return m.variant }
186
187func (m *moduleInfo) alias() *moduleAlias { return nil }
188func (m *moduleInfo) module() *moduleInfo { return m }
189func (m *moduleInfo) moduleOrAliasTarget() *moduleInfo { return m }
190func (m *moduleInfo) moduleOrAliasVariant() variant { return m.variant }
191
192type moduleOrAlias interface {
193 alias() *moduleAlias
194 module() *moduleInfo
195 moduleOrAliasTarget() *moduleInfo
196 moduleOrAliasVariant() variant
197}
198
199type modulesOrAliases []moduleOrAlias
200
201func (l modulesOrAliases) firstModule() *moduleInfo {
202 for _, moduleOrAlias := range l {
203 if m := moduleOrAlias.module(); m != nil {
204 return m
205 }
206 }
207 panic(fmt.Errorf("no first module!"))
208}
209
210func (l modulesOrAliases) lastModule() *moduleInfo {
211 for i := range l {
212 if m := l[len(l)-1-i].module(); m != nil {
213 return m
214 }
215 }
216 panic(fmt.Errorf("no last module!"))
217}
218
Colin Crossbbfa51a2014-12-17 16:12:41 -0800219type moduleGroup struct {
Colin Crossed342d92015-03-11 00:57:25 -0700220 name string
221 ninjaName string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700222
Colin Cross5df74a82020-08-24 16:18:21 -0700223 modules modulesOrAliases
Jeff Gastond70bf752017-11-10 15:12:08 -0800224
225 namespace Namespace
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700226}
227
Colin Cross5df74a82020-08-24 16:18:21 -0700228func (group *moduleGroup) moduleOrAliasByVariantName(name string) moduleOrAlias {
229 for _, module := range group.modules {
230 if module.moduleOrAliasVariant().name == name {
231 return module
232 }
233 }
234 return nil
235}
236
237func (group *moduleGroup) moduleByVariantName(name string) *moduleInfo {
238 return group.moduleOrAliasByVariantName(name).module()
239}
240
Colin Crossbbfa51a2014-12-17 16:12:41 -0800241type moduleInfo struct {
Colin Crossed342d92015-03-11 00:57:25 -0700242 // set during Parse
243 typeName string
Colin Crossaf4fd212017-07-28 14:32:36 -0700244 factory ModuleFactory
Colin Crossed342d92015-03-11 00:57:25 -0700245 relBlueprintsFile string
246 pos scanner.Position
247 propertyPos map[string]scanner.Position
Colin Cross322cc012019-05-20 13:55:14 -0700248 createdBy *moduleInfo
Colin Crossed342d92015-03-11 00:57:25 -0700249
Colin Crossedc41762020-08-13 12:07:30 -0700250 variant variant
Colin Crosse7daa222015-03-11 14:35:41 -0700251
Colin Crossd2f4ac12017-07-28 14:31:03 -0700252 logicModule Module
253 group *moduleGroup
254 properties []interface{}
Colin Crossc9028482014-12-18 16:28:54 -0800255
256 // set during ResolveDependencies
Colin Cross99bdb2a2019-03-29 16:35:02 -0700257 missingDeps []string
258 newDirectDeps []depInfo
Colin Crossc9028482014-12-18 16:28:54 -0800259
Colin Cross7addea32015-03-11 15:43:52 -0700260 // set during updateDependencies
261 reverseDeps []*moduleInfo
Colin Cross3702ac72016-08-11 11:09:00 -0700262 forwardDeps []*moduleInfo
Colin Cross99bdb2a2019-03-29 16:35:02 -0700263 directDeps []depInfo
Colin Cross7addea32015-03-11 15:43:52 -0700264
Colin Crossc4773d92020-08-25 17:12:59 -0700265 // used by parallelVisit
Colin Cross7addea32015-03-11 15:43:52 -0700266 waitingCount int
267
Colin Crossc9028482014-12-18 16:28:54 -0800268 // set during each runMutator
Colin Cross5df74a82020-08-24 16:18:21 -0700269 splitModules modulesOrAliases
Colin Crossab6d7902015-03-11 16:17:52 -0700270
271 // set during PrepareBuildActions
272 actionDefs localBuildActions
Colin Cross2da84922020-07-02 10:08:12 -0700273
274 providers []interface{}
275
276 startedMutator *mutatorInfo
277 finishedMutator *mutatorInfo
278
279 startedGenerateBuildActions bool
280 finishedGenerateBuildActions bool
Colin Crossc9028482014-12-18 16:28:54 -0800281}
282
Colin Crossedc41762020-08-13 12:07:30 -0700283type variant struct {
284 name string
285 variations variationMap
286 dependencyVariations variationMap
287}
288
Colin Cross2c1f3d12016-04-11 15:47:28 -0700289type depInfo struct {
290 module *moduleInfo
291 tag DependencyTag
292}
293
Colin Cross0b7e83e2016-05-17 14:58:05 -0700294func (module *moduleInfo) Name() string {
Paul Duffin244033b2020-05-04 11:00:03 +0100295 // If this is called from a LoadHook (which is run before the module has been registered)
296 // then group will not be set and so the name is retrieved from logicModule.Name().
297 // Usually, using that method is not safe as it does not track renames (group.name does).
298 // However, when called from LoadHook it is safe as there is no way to rename a module
299 // until after the LoadHook has run and the module has been registered.
300 if module.group != nil {
301 return module.group.name
302 } else {
303 return module.logicModule.Name()
304 }
Colin Cross0b7e83e2016-05-17 14:58:05 -0700305}
306
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800307func (module *moduleInfo) String() string {
Colin Cross0b7e83e2016-05-17 14:58:05 -0700308 s := fmt.Sprintf("module %q", module.Name())
Colin Crossedc41762020-08-13 12:07:30 -0700309 if module.variant.name != "" {
310 s += fmt.Sprintf(" variant %q", module.variant.name)
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800311 }
Colin Cross322cc012019-05-20 13:55:14 -0700312 if module.createdBy != nil {
313 s += fmt.Sprintf(" (created by %s)", module.createdBy)
314 }
315
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800316 return s
317}
318
Jeff Gastond70bf752017-11-10 15:12:08 -0800319func (module *moduleInfo) namespace() Namespace {
320 return module.group.namespace
321}
322
Colin Crossf5e34b92015-03-13 16:02:36 -0700323// A Variation is a way that a variant of a module differs from other variants of the same module.
324// For example, two variants of the same module might have Variation{"arch","arm"} and
325// Variation{"arch","arm64"}
326type Variation struct {
327 // Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Colin Cross65569e42015-03-10 20:08:19 -0700328 Mutator string
Colin Crossf5e34b92015-03-13 16:02:36 -0700329 // Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
330 // "shared" or "static" for link.
331 Variation string
Colin Cross65569e42015-03-10 20:08:19 -0700332}
333
Colin Crossf5e34b92015-03-13 16:02:36 -0700334// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
335type variationMap map[string]string
Colin Crosse7daa222015-03-11 14:35:41 -0700336
Colin Crossf5e34b92015-03-13 16:02:36 -0700337func (vm variationMap) clone() variationMap {
Colin Cross9403b5a2019-11-13 20:11:04 -0800338 if vm == nil {
339 return nil
340 }
Colin Crossf5e34b92015-03-13 16:02:36 -0700341 newVm := make(variationMap)
Colin Crosse7daa222015-03-11 14:35:41 -0700342 for k, v := range vm {
343 newVm[k] = v
344 }
345
346 return newVm
Colin Crossc9028482014-12-18 16:28:54 -0800347}
348
Colin Cross89486232015-05-08 11:14:54 -0700349// Compare this variationMap to another one. Returns true if the every entry in this map
Colin Cross5dc67592020-08-24 14:46:13 -0700350// exists and has the same value in the other map.
351func (vm variationMap) subsetOf(other variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -0700352 for k, v1 := range vm {
Colin Cross5dc67592020-08-24 14:46:13 -0700353 if v2, ok := other[k]; !ok || v1 != v2 {
Colin Cross89486232015-05-08 11:14:54 -0700354 return false
355 }
356 }
357 return true
358}
359
Colin Crossf5e34b92015-03-13 16:02:36 -0700360func (vm variationMap) equal(other variationMap) bool {
Colin Crosse7daa222015-03-11 14:35:41 -0700361 return reflect.DeepEqual(vm, other)
Colin Crossbbfa51a2014-12-17 16:12:41 -0800362}
363
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700364type singletonInfo struct {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700365 // set during RegisterSingletonType
366 factory SingletonFactory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700367 singleton Singleton
Yuchen Wub9103ef2015-08-25 17:58:17 -0700368 name string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700369
370 // set during PrepareBuildActions
371 actionDefs localBuildActions
372}
373
Colin Crossc9028482014-12-18 16:28:54 -0800374type mutatorInfo struct {
375 // set during RegisterMutator
Colin Crossc0dbc552015-01-02 15:19:28 -0800376 topDownMutator TopDownMutator
377 bottomUpMutator BottomUpMutator
378 name string
Colin Cross49c279a2016-08-05 22:30:44 -0700379 parallel bool
Colin Crossc9028482014-12-18 16:28:54 -0800380}
381
Colin Crossaf4fd212017-07-28 14:32:36 -0700382func newContext() *Context {
383 return &Context{
Colin Cross3a8c0252019-01-23 13:21:48 -0800384 Context: context.Background(),
Colin Cross5f03f112017-11-07 13:29:54 -0800385 moduleFactories: make(map[string]ModuleFactory),
Jeff Gastond70bf752017-11-10 15:12:08 -0800386 nameInterface: NewSimpleNameInterface(),
Colin Cross5f03f112017-11-07 13:29:54 -0800387 moduleInfo: make(map[Module]*moduleInfo),
Colin Cross25236982021-04-05 17:20:34 -0700388 globs: make(map[globKey]pathtools.GlobResult),
Colin Cross5f03f112017-11-07 13:29:54 -0800389 fs: pathtools.OsFs,
Colin Cross2da84922020-07-02 10:08:12 -0700390 finishedMutators: make(map[*mutatorInfo]bool),
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +0200391 outDir: nil,
Colin Cross5f03f112017-11-07 13:29:54 -0800392 requiredNinjaMajor: 1,
393 requiredNinjaMinor: 7,
394 requiredNinjaMicro: 0,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700395 }
Colin Crossaf4fd212017-07-28 14:32:36 -0700396}
397
398// NewContext creates a new Context object. The created context initially has
399// no module or singleton factories registered, so the RegisterModuleFactory and
400// RegisterSingletonFactory methods must be called before it can do anything
401// useful.
402func NewContext() *Context {
403 ctx := newContext()
Colin Cross763b6f12015-10-29 15:32:56 -0700404
405 ctx.RegisterBottomUpMutator("blueprint_deps", blueprintDepsMutator)
406
407 return ctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700408}
409
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700410// A ModuleFactory function creates a new Module object. See the
411// Context.RegisterModuleType method for details about how a registered
412// ModuleFactory is used by a Context.
413type ModuleFactory func() (m Module, propertyStructs []interface{})
414
Jamie Gennisd4e10182014-06-12 20:06:50 -0700415// RegisterModuleType associates a module type name (which can appear in a
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700416// Blueprints file) with a Module factory function. When the given module type
417// name is encountered in a Blueprints file during parsing, the Module factory
418// is invoked to instantiate a new Module object to handle the build action
Colin Crossc9028482014-12-18 16:28:54 -0800419// generation for the module. If a Mutator splits a module into multiple variants,
420// the factory is invoked again to create a new Module for each variant.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700421//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700422// The module type names given here must be unique for the context. The factory
423// function should be a named function so that its package and name can be
424// included in the generated Ninja file for debugging purposes.
425//
426// The factory function returns two values. The first is the newly created
427// Module object. The second is a slice of pointers to that Module object's
428// properties structs. Each properties struct is examined when parsing a module
429// definition of this type in a Blueprints file. Exported fields of the
430// properties structs are automatically set to the property values specified in
431// the Blueprints file. The properties struct field names determine the name of
432// the Blueprints file properties that are used - the Blueprints property name
433// matches that of the properties struct field name with the first letter
434// converted to lower-case.
435//
436// The fields of the properties struct must be either []string, a string, or
437// bool. The Context will panic if a Module gets instantiated with a properties
438// struct containing a field that is not one these supported types.
439//
440// Any properties that appear in the Blueprints files that are not built-in
441// module properties (such as "name" and "deps") and do not have a corresponding
442// field in the returned module properties struct result in an error during the
443// Context's parse phase.
444//
445// As an example, the follow code:
446//
447// type myModule struct {
448// properties struct {
449// Foo string
450// Bar []string
451// }
452// }
453//
454// func NewMyModule() (blueprint.Module, []interface{}) {
455// module := new(myModule)
456// properties := &module.properties
457// return module, []interface{}{properties}
458// }
459//
460// func main() {
461// ctx := blueprint.NewContext()
462// ctx.RegisterModuleType("my_module", NewMyModule)
463// // ...
464// }
465//
466// would support parsing a module defined in a Blueprints file as follows:
467//
468// my_module {
469// name: "myName",
470// foo: "my foo string",
471// bar: ["my", "bar", "strings"],
472// }
473//
Colin Cross7ad621c2015-01-07 16:22:45 -0800474// The factory function may be called from multiple goroutines. Any accesses
475// to global variables must be synchronized.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700476func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
477 if _, present := c.moduleFactories[name]; present {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700478 panic(errors.New("module type name is already registered"))
479 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700480 c.moduleFactories[name] = factory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700481}
482
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700483// A SingletonFactory function creates a new Singleton object. See the
484// Context.RegisterSingletonType method for details about how a registered
485// SingletonFactory is used by a Context.
486type SingletonFactory func() Singleton
487
488// RegisterSingletonType registers a singleton type that will be invoked to
Usta Shresthaee7a5d72022-01-10 22:46:23 -0500489// generate build actions. Each registered singleton type is instantiated
Yuchen Wub9103ef2015-08-25 17:58:17 -0700490// and invoked exactly once as part of the generate phase. Each registered
491// singleton is invoked in registration order.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700492//
493// The singleton type names given here must be unique for the context. The
494// factory function should be a named function so that its package and name can
495// be included in the generated Ninja file for debugging purposes.
496func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
Yuchen Wub9103ef2015-08-25 17:58:17 -0700497 for _, s := range c.singletonInfo {
498 if s.name == name {
499 panic(errors.New("singleton name is already registered"))
500 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700501 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700502
Yuchen Wub9103ef2015-08-25 17:58:17 -0700503 c.singletonInfo = append(c.singletonInfo, &singletonInfo{
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700504 factory: factory,
505 singleton: factory(),
Yuchen Wub9103ef2015-08-25 17:58:17 -0700506 name: name,
507 })
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700508}
509
Colin Cross5f03f112017-11-07 13:29:54 -0800510// RegisterPreSingletonType registers a presingleton type that will be invoked to
511// generate build actions before any Blueprint files have been read. Each registered
512// presingleton type is instantiated and invoked exactly once at the beginning of the
513// parse phase. Each registered presingleton is invoked in registration order.
514//
515// The presingleton type names given here must be unique for the context. The
516// factory function should be a named function so that its package and name can
517// be included in the generated Ninja file for debugging purposes.
518func (c *Context) RegisterPreSingletonType(name string, factory SingletonFactory) {
519 for _, s := range c.preSingletonInfo {
520 if s.name == name {
521 panic(errors.New("presingleton name is already registered"))
522 }
523 }
524
525 c.preSingletonInfo = append(c.preSingletonInfo, &singletonInfo{
526 factory: factory,
527 singleton: factory(),
528 name: name,
529 })
530}
531
Jeff Gastond70bf752017-11-10 15:12:08 -0800532func (c *Context) SetNameInterface(i NameInterface) {
533 c.nameInterface = i
534}
535
Colin Crossc5fa50e2019-12-17 13:12:35 -0800536func (c *Context) SetSrcDir(path string) {
537 c.srcDir = path
538 c.fs = pathtools.NewOsFs(path)
539}
540
541func (c *Context) SrcDir() string {
542 return c.srcDir
543}
544
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700545func singletonPkgPath(singleton Singleton) string {
546 typ := reflect.TypeOf(singleton)
547 for typ.Kind() == reflect.Ptr {
548 typ = typ.Elem()
549 }
550 return typ.PkgPath()
551}
552
553func singletonTypeName(singleton Singleton) string {
554 typ := reflect.TypeOf(singleton)
555 for typ.Kind() == reflect.Ptr {
556 typ = typ.Elem()
557 }
558 return typ.PkgPath() + "." + typ.Name()
559}
560
Colin Cross3702ac72016-08-11 11:09:00 -0700561// RegisterTopDownMutator registers a mutator that will be invoked to propagate dependency info
562// top-down between Modules. Each registered mutator is invoked in registration order (mixing
563// TopDownMutators and BottomUpMutators) once per Module, and the invocation on any module will
564// have returned before it is in invoked on any of its dependencies.
Colin Crossc9028482014-12-18 16:28:54 -0800565//
Colin Cross65569e42015-03-10 20:08:19 -0700566// The mutator type names given here must be unique to all top down mutators in
567// the Context.
Colin Cross3702ac72016-08-11 11:09:00 -0700568//
569// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
570// parallel while maintaining ordering.
571func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) MutatorHandle {
Colin Crossc9028482014-12-18 16:28:54 -0800572 for _, m := range c.mutatorInfo {
573 if m.name == name && m.topDownMutator != nil {
574 panic(fmt.Errorf("mutator name %s is already registered", name))
575 }
576 }
577
Colin Cross3702ac72016-08-11 11:09:00 -0700578 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800579 topDownMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800580 name: name,
Colin Cross3702ac72016-08-11 11:09:00 -0700581 }
582
583 c.mutatorInfo = append(c.mutatorInfo, info)
584
585 return info
Colin Crossc9028482014-12-18 16:28:54 -0800586}
587
Colin Cross3702ac72016-08-11 11:09:00 -0700588// RegisterBottomUpMutator registers a mutator that will be invoked to split Modules into variants.
589// Each registered mutator is invoked in registration order (mixing TopDownMutators and
590// BottomUpMutators) once per Module, will not be invoked on a module until the invocations on all
591// of the modules dependencies have returned.
Colin Crossc9028482014-12-18 16:28:54 -0800592//
Colin Cross65569e42015-03-10 20:08:19 -0700593// The mutator type names given here must be unique to all bottom up or early
594// mutators in the Context.
Colin Cross49c279a2016-08-05 22:30:44 -0700595//
Colin Cross3702ac72016-08-11 11:09:00 -0700596// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
597// parallel while maintaining ordering.
598func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) MutatorHandle {
Colin Cross65569e42015-03-10 20:08:19 -0700599 for _, m := range c.variantMutatorNames {
600 if m == name {
Colin Crossc9028482014-12-18 16:28:54 -0800601 panic(fmt.Errorf("mutator name %s is already registered", name))
602 }
603 }
604
Colin Cross49c279a2016-08-05 22:30:44 -0700605 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800606 bottomUpMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800607 name: name,
Colin Cross49c279a2016-08-05 22:30:44 -0700608 }
609 c.mutatorInfo = append(c.mutatorInfo, info)
Colin Cross65569e42015-03-10 20:08:19 -0700610
611 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Cross49c279a2016-08-05 22:30:44 -0700612
613 return info
614}
615
Colin Cross3702ac72016-08-11 11:09:00 -0700616type MutatorHandle interface {
617 // Set the mutator to visit modules in parallel while maintaining ordering. Calling any
618 // method on the mutator context is thread-safe, but the mutator must handle synchronization
619 // for any modifications to global state or any modules outside the one it was invoked on.
620 Parallel() MutatorHandle
Colin Cross49c279a2016-08-05 22:30:44 -0700621}
622
Colin Cross3702ac72016-08-11 11:09:00 -0700623func (mutator *mutatorInfo) Parallel() MutatorHandle {
Colin Cross49c279a2016-08-05 22:30:44 -0700624 mutator.parallel = true
625 return mutator
Colin Cross65569e42015-03-10 20:08:19 -0700626}
627
628// RegisterEarlyMutator registers a mutator that will be invoked to split
629// Modules into multiple variant Modules before any dependencies have been
630// created. Each registered mutator is invoked in registration order once
631// per Module (including each variant from previous early mutators). Module
632// order is unpredictable.
633//
634// In order for dependencies to be satisifed in a later pass, all dependencies
Colin Crossf5e34b92015-03-13 16:02:36 -0700635// of a module either must have an identical variant or must have no variations.
Colin Cross65569e42015-03-10 20:08:19 -0700636//
637// The mutator type names given here must be unique to all bottom up or early
638// mutators in the Context.
Colin Cross763b6f12015-10-29 15:32:56 -0700639//
640// Deprecated, use a BottomUpMutator instead. The only difference between
641// EarlyMutator and BottomUpMutator is that EarlyMutator runs before the
642// deprecated DynamicDependencies.
Colin Cross65569e42015-03-10 20:08:19 -0700643func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
644 for _, m := range c.variantMutatorNames {
645 if m == name {
646 panic(fmt.Errorf("mutator name %s is already registered", name))
647 }
648 }
649
Colin Crossf8b50422016-08-10 12:56:40 -0700650 c.earlyMutatorInfo = append(c.earlyMutatorInfo, &mutatorInfo{
651 bottomUpMutator: func(mctx BottomUpMutatorContext) {
652 mutator(mctx)
653 },
654 name: name,
Colin Cross65569e42015-03-10 20:08:19 -0700655 })
656
657 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Crossc9028482014-12-18 16:28:54 -0800658}
659
Jamie Gennisd4e10182014-06-12 20:06:50 -0700660// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
661// where it encounters an unknown module type while parsing Blueprints files. By
662// default, the context will report unknown module types as an error. If this
663// method is called with ignoreUnknownModuleTypes set to true then the context
664// will silently ignore unknown module types.
665//
666// This method should generally not be used. It exists to facilitate the
667// bootstrapping process.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700668func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
669 c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
670}
671
Colin Cross036a1df2015-12-17 15:49:30 -0800672// SetAllowMissingDependencies changes the behavior of Blueprint to ignore
673// unresolved dependencies. If the module's GenerateBuildActions calls
674// ModuleContext.GetMissingDependencies Blueprint will not emit any errors
675// for missing dependencies.
676func (c *Context) SetAllowMissingDependencies(allowMissingDependencies bool) {
677 c.allowMissingDependencies = allowMissingDependencies
678}
679
Jeff Gastonc3e28442017-08-09 15:13:12 -0700680func (c *Context) SetModuleListFile(listFile string) {
681 c.moduleListFile = listFile
682}
683
684func (c *Context) ListModulePaths(baseDir string) (paths []string, err error) {
685 reader, err := c.fs.Open(c.moduleListFile)
686 if err != nil {
687 return nil, err
688 }
689 bytes, err := ioutil.ReadAll(reader)
690 if err != nil {
691 return nil, err
692 }
693 text := string(bytes)
694
695 text = strings.Trim(text, "\n")
696 lines := strings.Split(text, "\n")
697 for i := range lines {
698 lines[i] = filepath.Join(baseDir, lines[i])
699 }
700
701 return lines, nil
702}
703
Jeff Gaston656870f2017-11-29 18:37:31 -0800704// a fileParseContext tells the status of parsing a particular file
705type fileParseContext struct {
706 // name of file
707 fileName string
708
709 // scope to use when resolving variables
710 Scope *parser.Scope
711
712 // pointer to the one in the parent directory
713 parent *fileParseContext
714
715 // is closed once FileHandler has completed for this file
716 doneVisiting chan struct{}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700717}
718
Jamie Gennisd4e10182014-06-12 20:06:50 -0700719// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
720// at rootFile. When it encounters a Blueprints file with a set of subdirs
721// listed it recursively parses any Blueprints files found in those
722// subdirectories.
723//
724// If no errors are encountered while parsing the files, the list of paths on
725// which the future output will depend is returned. This list will include both
726// Blueprints file paths as well as directory paths for cases where wildcard
727// subdirs are found.
Colin Crossda70fd02019-12-30 18:40:09 -0800728func (c *Context) ParseBlueprintsFiles(rootFile string,
729 config interface{}) (deps []string, errs []error) {
730
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800731 baseDir := filepath.Dir(rootFile)
732 pathsToParse, err := c.ListModulePaths(baseDir)
733 if err != nil {
734 return nil, []error{err}
735 }
Colin Crossda70fd02019-12-30 18:40:09 -0800736 return c.ParseFileList(baseDir, pathsToParse, config)
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800737}
738
Colin Crossda70fd02019-12-30 18:40:09 -0800739func (c *Context) ParseFileList(rootDir string, filePaths []string,
740 config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700741
Jeff Gastonc3e28442017-08-09 15:13:12 -0700742 if len(filePaths) < 1 {
743 return nil, []error{fmt.Errorf("no paths provided to parse")}
744 }
745
Colin Cross7ad621c2015-01-07 16:22:45 -0800746 c.dependenciesReady = false
747
Colin Crossda70fd02019-12-30 18:40:09 -0800748 type newModuleInfo struct {
749 *moduleInfo
Colin Cross13b5bef2021-05-19 10:07:19 -0700750 deps []string
Colin Crossda70fd02019-12-30 18:40:09 -0800751 added chan<- struct{}
752 }
753
754 moduleCh := make(chan newModuleInfo)
Colin Cross23d7aa12015-06-30 16:05:22 -0700755 errsCh := make(chan []error)
756 doneCh := make(chan struct{})
757 var numErrs uint32
758 var numGoroutines int32
759
760 // handler must be reentrant
Jeff Gaston5f763d02017-08-08 14:43:58 -0700761 handleOneFile := func(file *parser.File) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700762 if atomic.LoadUint32(&numErrs) > maxErrors {
763 return
764 }
765
Colin Crossda70fd02019-12-30 18:40:09 -0800766 addedCh := make(chan struct{})
767
Colin Cross9672d862019-12-30 18:38:20 -0800768 var scopedModuleFactories map[string]ModuleFactory
769
Colin Crossda70fd02019-12-30 18:40:09 -0800770 var addModule func(module *moduleInfo) []error
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100771 addModule = func(module *moduleInfo) []error {
Paul Duffin244033b2020-05-04 11:00:03 +0100772 // Run any load hooks immediately before it is sent to the moduleCh and is
773 // registered by name. This allows load hooks to set and/or modify any aspect
774 // of the module (including names) using information that is not available when
775 // the module factory is called.
Colin Cross13b5bef2021-05-19 10:07:19 -0700776 newModules, newDeps, errs := runAndRemoveLoadHooks(c, config, module, &scopedModuleFactories)
Colin Crossda70fd02019-12-30 18:40:09 -0800777 if len(errs) > 0 {
778 return errs
779 }
Paul Duffin244033b2020-05-04 11:00:03 +0100780
Colin Cross13b5bef2021-05-19 10:07:19 -0700781 moduleCh <- newModuleInfo{module, newDeps, addedCh}
Paul Duffin244033b2020-05-04 11:00:03 +0100782 <-addedCh
Colin Crossda70fd02019-12-30 18:40:09 -0800783 for _, n := range newModules {
784 errs = addModule(n)
785 if len(errs) > 0 {
786 return errs
787 }
788 }
789 return nil
790 }
791
Jeff Gaston656870f2017-11-29 18:37:31 -0800792 for _, def := range file.Defs {
Jeff Gaston656870f2017-11-29 18:37:31 -0800793 switch def := def.(type) {
794 case *parser.Module:
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100795 module, errs := processModuleDef(def, file.Name, c.moduleFactories, scopedModuleFactories, c.ignoreUnknownModuleTypes)
Colin Crossda70fd02019-12-30 18:40:09 -0800796 if len(errs) == 0 && module != nil {
797 errs = addModule(module)
798 }
799
800 if len(errs) > 0 {
801 atomic.AddUint32(&numErrs, uint32(len(errs)))
802 errsCh <- errs
803 }
804
Jeff Gaston656870f2017-11-29 18:37:31 -0800805 case *parser.Assignment:
806 // Already handled via Scope object
807 default:
808 panic("unknown definition type")
Colin Cross23d7aa12015-06-30 16:05:22 -0700809 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800810
Jeff Gaston656870f2017-11-29 18:37:31 -0800811 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700812 }
813
814 atomic.AddInt32(&numGoroutines, 1)
815 go func() {
816 var errs []error
Jeff Gastonc3e28442017-08-09 15:13:12 -0700817 deps, errs = c.WalkBlueprintsFiles(rootDir, filePaths, handleOneFile)
Colin Cross23d7aa12015-06-30 16:05:22 -0700818 if len(errs) > 0 {
819 errsCh <- errs
820 }
821 doneCh <- struct{}{}
822 }()
823
Colin Cross13b5bef2021-05-19 10:07:19 -0700824 var hookDeps []string
Colin Cross23d7aa12015-06-30 16:05:22 -0700825loop:
826 for {
827 select {
828 case newErrs := <-errsCh:
829 errs = append(errs, newErrs...)
830 case module := <-moduleCh:
Colin Crossda70fd02019-12-30 18:40:09 -0800831 newErrs := c.addModule(module.moduleInfo)
Colin Cross13b5bef2021-05-19 10:07:19 -0700832 hookDeps = append(hookDeps, module.deps...)
Colin Crossda70fd02019-12-30 18:40:09 -0800833 if module.added != nil {
834 module.added <- struct{}{}
835 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700836 if len(newErrs) > 0 {
837 errs = append(errs, newErrs...)
838 }
839 case <-doneCh:
840 n := atomic.AddInt32(&numGoroutines, -1)
841 if n == 0 {
842 break loop
843 }
844 }
845 }
846
Colin Cross13b5bef2021-05-19 10:07:19 -0700847 deps = append(deps, hookDeps...)
Colin Cross23d7aa12015-06-30 16:05:22 -0700848 return deps, errs
849}
850
851type FileHandler func(*parser.File)
852
Jeff Gastonc3e28442017-08-09 15:13:12 -0700853// WalkBlueprintsFiles walks a set of Blueprints files starting with the given filepaths,
854// calling the given file handler on each
855//
856// When WalkBlueprintsFiles encounters a Blueprints file with a set of subdirs listed,
857// it recursively parses any Blueprints files found in those subdirectories.
858//
859// If any of the file paths is an ancestor directory of any other of file path, the ancestor
860// will be parsed and visited first.
861//
862// the file handler will be called from a goroutine, so it must be reentrant.
Colin Cross23d7aa12015-06-30 16:05:22 -0700863//
864// If no errors are encountered while parsing the files, the list of paths on
865// which the future output will depend is returned. This list will include both
866// Blueprints file paths as well as directory paths for cases where wildcard
867// subdirs are found.
Jeff Gaston656870f2017-11-29 18:37:31 -0800868//
869// visitor will be called asynchronously, and will only be called once visitor for each
870// ancestor directory has completed.
871//
872// WalkBlueprintsFiles will not return until all calls to visitor have returned.
Jeff Gastonc3e28442017-08-09 15:13:12 -0700873func (c *Context) WalkBlueprintsFiles(rootDir string, filePaths []string,
874 visitor FileHandler) (deps []string, errs []error) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700875
Jeff Gastonc3e28442017-08-09 15:13:12 -0700876 // make a mapping from ancestors to their descendants to facilitate parsing ancestors first
877 descendantsMap, err := findBlueprintDescendants(filePaths)
878 if err != nil {
879 panic(err.Error())
Jeff Gastonc3e28442017-08-09 15:13:12 -0700880 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800881 blueprintsSet := make(map[string]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700882
Jeff Gaston5800d042017-12-05 14:57:58 -0800883 // Channels to receive data back from openAndParse goroutines
Jeff Gaston656870f2017-11-29 18:37:31 -0800884 blueprintsCh := make(chan fileParseContext)
Colin Cross7ad621c2015-01-07 16:22:45 -0800885 errsCh := make(chan []error)
Colin Cross7ad621c2015-01-07 16:22:45 -0800886 depsCh := make(chan string)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700887
Jeff Gaston5800d042017-12-05 14:57:58 -0800888 // Channel to notify main loop that a openAndParse goroutine has finished
Jeff Gaston656870f2017-11-29 18:37:31 -0800889 doneParsingCh := make(chan fileParseContext)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700890
Colin Cross7ad621c2015-01-07 16:22:45 -0800891 // Number of outstanding goroutines to wait for
Jeff Gaston5f763d02017-08-08 14:43:58 -0700892 activeCount := 0
Jeff Gaston656870f2017-11-29 18:37:31 -0800893 var pending []fileParseContext
Jeff Gastonc3e28442017-08-09 15:13:12 -0700894 tooManyErrors := false
895
896 // Limit concurrent calls to parseBlueprintFiles to 200
897 // Darwin has a default limit of 256 open files
898 maxActiveCount := 200
Colin Cross7ad621c2015-01-07 16:22:45 -0800899
Jeff Gaston656870f2017-11-29 18:37:31 -0800900 // count the number of pending calls to visitor()
901 visitorWaitGroup := sync.WaitGroup{}
902
903 startParseBlueprintsFile := func(blueprint fileParseContext) {
904 if blueprintsSet[blueprint.fileName] {
Colin Cross4a02a302017-05-16 10:33:58 -0700905 return
906 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800907 blueprintsSet[blueprint.fileName] = true
Jeff Gaston5f763d02017-08-08 14:43:58 -0700908 activeCount++
Jeff Gaston656870f2017-11-29 18:37:31 -0800909 deps = append(deps, blueprint.fileName)
910 visitorWaitGroup.Add(1)
Colin Cross7ad621c2015-01-07 16:22:45 -0800911 go func() {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800912 file, blueprints, deps, errs := c.openAndParse(blueprint.fileName, blueprint.Scope, rootDir,
913 &blueprint)
914 if len(errs) > 0 {
915 errsCh <- errs
916 }
917 for _, blueprint := range blueprints {
918 blueprintsCh <- blueprint
919 }
920 for _, dep := range deps {
921 depsCh <- dep
922 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800923 doneParsingCh <- blueprint
Jeff Gaston5f763d02017-08-08 14:43:58 -0700924
Jeff Gaston656870f2017-11-29 18:37:31 -0800925 if blueprint.parent != nil && blueprint.parent.doneVisiting != nil {
926 // wait for visitor() of parent to complete
927 <-blueprint.parent.doneVisiting
928 }
929
Jeff Gastona7e408a2017-12-05 15:11:55 -0800930 if len(errs) == 0 {
931 // process this file
932 visitor(file)
933 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800934 if blueprint.doneVisiting != nil {
935 close(blueprint.doneVisiting)
936 }
937 visitorWaitGroup.Done()
Colin Cross7ad621c2015-01-07 16:22:45 -0800938 }()
939 }
940
Jeff Gaston656870f2017-11-29 18:37:31 -0800941 foundParseableBlueprint := func(blueprint fileParseContext) {
Jeff Gastonc3e28442017-08-09 15:13:12 -0700942 if activeCount >= maxActiveCount {
943 pending = append(pending, blueprint)
944 } else {
945 startParseBlueprintsFile(blueprint)
946 }
947 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800948
Jeff Gaston656870f2017-11-29 18:37:31 -0800949 startParseDescendants := func(blueprint fileParseContext) {
950 descendants, hasDescendants := descendantsMap[blueprint.fileName]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700951 if hasDescendants {
952 for _, descendant := range descendants {
Jeff Gaston656870f2017-11-29 18:37:31 -0800953 foundParseableBlueprint(fileParseContext{descendant, parser.NewScope(blueprint.Scope), &blueprint, make(chan struct{})})
Jeff Gastonc3e28442017-08-09 15:13:12 -0700954 }
955 }
956 }
Colin Cross4a02a302017-05-16 10:33:58 -0700957
Jeff Gastonc3e28442017-08-09 15:13:12 -0700958 // begin parsing any files that have no ancestors
Jeff Gaston656870f2017-11-29 18:37:31 -0800959 startParseDescendants(fileParseContext{"", parser.NewScope(nil), nil, nil})
Colin Cross7ad621c2015-01-07 16:22:45 -0800960
961loop:
962 for {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700963 if len(errs) > maxErrors {
Colin Cross7ad621c2015-01-07 16:22:45 -0800964 tooManyErrors = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700965 }
966
Colin Cross7ad621c2015-01-07 16:22:45 -0800967 select {
968 case newErrs := <-errsCh:
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700969 errs = append(errs, newErrs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800970 case dep := <-depsCh:
971 deps = append(deps, dep)
Colin Cross7ad621c2015-01-07 16:22:45 -0800972 case blueprint := <-blueprintsCh:
973 if tooManyErrors {
974 continue
975 }
Jeff Gastonc3e28442017-08-09 15:13:12 -0700976 foundParseableBlueprint(blueprint)
Jeff Gaston656870f2017-11-29 18:37:31 -0800977 case blueprint := <-doneParsingCh:
Jeff Gaston5f763d02017-08-08 14:43:58 -0700978 activeCount--
Jeff Gastonc3e28442017-08-09 15:13:12 -0700979 if !tooManyErrors {
980 startParseDescendants(blueprint)
981 }
982 if activeCount < maxActiveCount && len(pending) > 0 {
983 // start to process the next one from the queue
984 next := pending[len(pending)-1]
Colin Cross4a02a302017-05-16 10:33:58 -0700985 pending = pending[:len(pending)-1]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700986 startParseBlueprintsFile(next)
Colin Cross4a02a302017-05-16 10:33:58 -0700987 }
Jeff Gaston5f763d02017-08-08 14:43:58 -0700988 if activeCount == 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -0800989 break loop
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700990 }
991 }
992 }
993
Jeff Gastonc3e28442017-08-09 15:13:12 -0700994 sort.Strings(deps)
995
Jeff Gaston656870f2017-11-29 18:37:31 -0800996 // wait for every visitor() to complete
997 visitorWaitGroup.Wait()
998
Colin Cross7ad621c2015-01-07 16:22:45 -0800999 return
1000}
1001
Colin Crossd7b0f602016-06-02 15:30:20 -07001002// MockFileSystem causes the Context to replace all reads with accesses to the provided map of
1003// filenames to contents stored as a byte slice.
1004func (c *Context) MockFileSystem(files map[string][]byte) {
Jeff Gaston9f630902017-11-15 14:49:48 -08001005 // look for a module list file
1006 _, ok := files[MockModuleListFile]
1007 if !ok {
1008 // no module list file specified; find every file named Blueprints
1009 pathsToParse := []string{}
1010 for candidate := range files {
Lukacs T. Berkieef56852021-09-02 11:34:06 +02001011 if filepath.Base(candidate) == "Android.bp" {
Jeff Gaston9f630902017-11-15 14:49:48 -08001012 pathsToParse = append(pathsToParse, candidate)
1013 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001014 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001015 if len(pathsToParse) < 1 {
1016 panic(fmt.Sprintf("No Blueprints files found in mock filesystem: %v\n", files))
1017 }
1018 // put the list of Blueprints files into a list file
1019 files[MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
Jeff Gastonc3e28442017-08-09 15:13:12 -07001020 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001021 c.SetModuleListFile(MockModuleListFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001022
1023 // mock the filesystem
Colin Crossb519a7e2017-02-01 13:21:35 -08001024 c.fs = pathtools.MockFs(files)
Colin Crossd7b0f602016-06-02 15:30:20 -07001025}
1026
Colin Cross8cde4252019-12-17 13:11:21 -08001027func (c *Context) SetFs(fs pathtools.FileSystem) {
1028 c.fs = fs
1029}
1030
Jeff Gaston8fd95782017-12-05 15:03:51 -08001031// openAndParse opens and parses a single Blueprints file, and returns the results
Jeff Gaston5800d042017-12-05 14:57:58 -08001032func (c *Context) openAndParse(filename string, scope *parser.Scope, rootDir string,
Jeff Gaston8fd95782017-12-05 15:03:51 -08001033 parent *fileParseContext) (file *parser.File,
1034 subBlueprints []fileParseContext, deps []string, errs []error) {
Colin Cross7ad621c2015-01-07 16:22:45 -08001035
Colin Crossd7b0f602016-06-02 15:30:20 -07001036 f, err := c.fs.Open(filename)
Colin Cross7ad621c2015-01-07 16:22:45 -08001037 if err != nil {
Jeff Gastonaca42202017-08-23 17:30:05 -07001038 // couldn't open the file; see if we can provide a clearer error than "could not open file"
1039 stats, statErr := c.fs.Lstat(filename)
1040 if statErr == nil {
1041 isSymlink := stats.Mode()&os.ModeSymlink != 0
1042 if isSymlink {
1043 err = fmt.Errorf("could not open symlink %v : %v", filename, err)
1044 target, readlinkErr := os.Readlink(filename)
1045 if readlinkErr == nil {
1046 _, targetStatsErr := c.fs.Lstat(target)
1047 if targetStatsErr != nil {
1048 err = fmt.Errorf("could not open symlink %v; its target (%v) cannot be opened", filename, target)
1049 }
1050 }
1051 } else {
1052 err = fmt.Errorf("%v exists but could not be opened: %v", filename, err)
1053 }
1054 }
Jeff Gaston8fd95782017-12-05 15:03:51 -08001055 return nil, nil, nil, []error{err}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001056 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001057
Jeff Gaston8fd95782017-12-05 15:03:51 -08001058 func() {
1059 defer func() {
1060 err = f.Close()
1061 if err != nil {
1062 errs = append(errs, err)
1063 }
1064 }()
1065 file, subBlueprints, errs = c.parseOne(rootDir, filename, f, scope, parent)
Colin Cross23d7aa12015-06-30 16:05:22 -07001066 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001067
Colin Cross7ad621c2015-01-07 16:22:45 -08001068 if len(errs) > 0 {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001069 return nil, nil, nil, errs
Colin Cross7ad621c2015-01-07 16:22:45 -08001070 }
1071
Colin Cross1fef5362015-04-20 16:50:54 -07001072 for _, b := range subBlueprints {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001073 deps = append(deps, b.fileName)
Colin Cross1fef5362015-04-20 16:50:54 -07001074 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001075
Jeff Gaston8fd95782017-12-05 15:03:51 -08001076 return file, subBlueprints, deps, nil
Colin Cross1fef5362015-04-20 16:50:54 -07001077}
1078
Jeff Gastona12f22f2017-08-08 14:45:56 -07001079// parseOne parses a single Blueprints file from the given reader, creating Module
1080// objects for each of the module definitions encountered. If the Blueprints
1081// file contains an assignment to the "subdirs" variable, then the
1082// subdirectories listed are searched for Blueprints files returned in the
1083// subBlueprints return value. If the Blueprints file contains an assignment
1084// to the "build" variable, then the file listed are returned in the
1085// subBlueprints return value.
1086//
1087// rootDir specifies the path to the root directory of the source tree, while
1088// filename specifies the path to the Blueprints file. These paths are used for
1089// error reporting and for determining the module's directory.
1090func (c *Context) parseOne(rootDir, filename string, reader io.Reader,
Jeff Gaston656870f2017-11-29 18:37:31 -08001091 scope *parser.Scope, parent *fileParseContext) (file *parser.File, subBlueprints []fileParseContext, errs []error) {
Jeff Gastona12f22f2017-08-08 14:45:56 -07001092
1093 relBlueprintsFile, err := filepath.Rel(rootDir, filename)
1094 if err != nil {
1095 return nil, nil, []error{err}
1096 }
1097
Jeff Gastona12f22f2017-08-08 14:45:56 -07001098 scope.Remove("subdirs")
1099 scope.Remove("optional_subdirs")
1100 scope.Remove("build")
1101 file, errs = parser.ParseAndEval(filename, reader, scope)
1102 if len(errs) > 0 {
1103 for i, err := range errs {
1104 if parseErr, ok := err.(*parser.ParseError); ok {
1105 err = &BlueprintError{
1106 Err: parseErr.Err,
1107 Pos: parseErr.Pos,
1108 }
1109 errs[i] = err
1110 }
1111 }
1112
1113 // If there were any parse errors don't bother trying to interpret the
1114 // result.
1115 return nil, nil, errs
1116 }
1117 file.Name = relBlueprintsFile
1118
Jeff Gastona12f22f2017-08-08 14:45:56 -07001119 build, buildPos, err := getLocalStringListFromScope(scope, "build")
1120 if err != nil {
1121 errs = append(errs, err)
1122 }
Jeff Gastonf23e3662017-11-30 17:31:43 -08001123 for _, buildEntry := range build {
1124 if strings.Contains(buildEntry, "/") {
1125 errs = append(errs, &BlueprintError{
1126 Err: fmt.Errorf("illegal value %v. The '/' character is not permitted", buildEntry),
1127 Pos: buildPos,
1128 })
1129 }
1130 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001131
Jeff Gastona12f22f2017-08-08 14:45:56 -07001132 if err != nil {
1133 errs = append(errs, err)
1134 }
1135
Jeff Gastona12f22f2017-08-08 14:45:56 -07001136 var blueprints []string
1137
1138 newBlueprints, newErrs := c.findBuildBlueprints(filepath.Dir(filename), build, buildPos)
1139 blueprints = append(blueprints, newBlueprints...)
1140 errs = append(errs, newErrs...)
1141
Jeff Gaston656870f2017-11-29 18:37:31 -08001142 subBlueprintsAndScope := make([]fileParseContext, len(blueprints))
Jeff Gastona12f22f2017-08-08 14:45:56 -07001143 for i, b := range blueprints {
Jeff Gaston656870f2017-11-29 18:37:31 -08001144 subBlueprintsAndScope[i] = fileParseContext{b, parser.NewScope(scope), parent, make(chan struct{})}
Jeff Gastona12f22f2017-08-08 14:45:56 -07001145 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001146 return file, subBlueprintsAndScope, errs
1147}
1148
Colin Cross7f507402015-12-16 13:03:41 -08001149func (c *Context) findBuildBlueprints(dir string, build []string,
Colin Cross127d2ea2016-11-01 11:10:51 -07001150 buildPos scanner.Position) ([]string, []error) {
1151
1152 var blueprints []string
1153 var errs []error
Colin Cross7f507402015-12-16 13:03:41 -08001154
1155 for _, file := range build {
Colin Cross127d2ea2016-11-01 11:10:51 -07001156 pattern := filepath.Join(dir, file)
1157 var matches []string
1158 var err error
1159
Colin Cross08e49542016-11-14 15:23:33 -08001160 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001161
Colin Cross7f507402015-12-16 13:03:41 -08001162 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001163 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001164 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross7f507402015-12-16 13:03:41 -08001165 Pos: buildPos,
1166 })
1167 continue
1168 }
1169
1170 if len(matches) == 0 {
Colin Cross2c628442016-10-07 17:13:10 -07001171 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001172 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross7f507402015-12-16 13:03:41 -08001173 Pos: buildPos,
1174 })
1175 }
1176
Colin Cross7f507402015-12-16 13:03:41 -08001177 for _, foundBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001178 if strings.HasSuffix(foundBlueprints, "/") {
1179 errs = append(errs, &BlueprintError{
1180 Err: fmt.Errorf("%q: is a directory", foundBlueprints),
1181 Pos: buildPos,
1182 })
1183 }
Colin Cross7f507402015-12-16 13:03:41 -08001184 blueprints = append(blueprints, foundBlueprints)
1185 }
1186 }
1187
Colin Cross127d2ea2016-11-01 11:10:51 -07001188 return blueprints, errs
Colin Cross7f507402015-12-16 13:03:41 -08001189}
1190
1191func (c *Context) findSubdirBlueprints(dir string, subdirs []string, subdirsPos scanner.Position,
Colin Cross127d2ea2016-11-01 11:10:51 -07001192 subBlueprintsName string, optional bool) ([]string, []error) {
1193
1194 var blueprints []string
1195 var errs []error
Colin Cross7ad621c2015-01-07 16:22:45 -08001196
1197 for _, subdir := range subdirs {
Colin Cross127d2ea2016-11-01 11:10:51 -07001198 pattern := filepath.Join(dir, subdir, subBlueprintsName)
1199 var matches []string
1200 var err error
1201
Colin Cross08e49542016-11-14 15:23:33 -08001202 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001203
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001204 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001205 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001206 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross1fef5362015-04-20 16:50:54 -07001207 Pos: subdirsPos,
1208 })
1209 continue
1210 }
1211
Colin Cross7f507402015-12-16 13:03:41 -08001212 if len(matches) == 0 && !optional {
Colin Cross2c628442016-10-07 17:13:10 -07001213 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001214 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross1fef5362015-04-20 16:50:54 -07001215 Pos: subdirsPos,
1216 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001217 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001218
Colin Cross127d2ea2016-11-01 11:10:51 -07001219 for _, subBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001220 if strings.HasSuffix(subBlueprints, "/") {
1221 errs = append(errs, &BlueprintError{
1222 Err: fmt.Errorf("%q: is a directory", subBlueprints),
1223 Pos: subdirsPos,
1224 })
1225 }
Colin Cross127d2ea2016-11-01 11:10:51 -07001226 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -08001227 }
1228 }
Colin Cross1fef5362015-04-20 16:50:54 -07001229
Colin Cross127d2ea2016-11-01 11:10:51 -07001230 return blueprints, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001231}
1232
Colin Cross6d8780f2015-07-10 17:51:55 -07001233func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
1234 if assignment, local := scope.Get(v); assignment == nil || !local {
1235 return nil, scanner.Position{}, nil
1236 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001237 switch value := assignment.Value.Eval().(type) {
1238 case *parser.List:
1239 ret := make([]string, 0, len(value.Values))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001240
Colin Crosse32cc802016-06-07 12:28:16 -07001241 for _, listValue := range value.Values {
1242 s, ok := listValue.(*parser.String)
1243 if !ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001244 // The parser should not produce this.
1245 panic("non-string value found in list")
1246 }
1247
Colin Crosse32cc802016-06-07 12:28:16 -07001248 ret = append(ret, s.Value)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001249 }
1250
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001251 return ret, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001252 case *parser.Bool, *parser.String:
Colin Cross2c628442016-10-07 17:13:10 -07001253 return nil, scanner.Position{}, &BlueprintError{
Colin Cross1fef5362015-04-20 16:50:54 -07001254 Err: fmt.Errorf("%q must be a list of strings", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001255 Pos: assignment.EqualsPos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001256 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001257 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001258 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001259 }
1260 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001261}
1262
Colin Cross29394222015-04-27 13:18:21 -07001263func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -07001264 if assignment, _ := scope.Get(v); assignment == nil {
1265 return "", scanner.Position{}, nil
1266 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001267 switch value := assignment.Value.Eval().(type) {
1268 case *parser.String:
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001269 return value.Value, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001270 case *parser.Bool, *parser.List:
Colin Cross2c628442016-10-07 17:13:10 -07001271 return "", scanner.Position{}, &BlueprintError{
Colin Cross29394222015-04-27 13:18:21 -07001272 Err: fmt.Errorf("%q must be a string", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001273 Pos: assignment.EqualsPos,
Colin Cross29394222015-04-27 13:18:21 -07001274 }
1275 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001276 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Colin Cross29394222015-04-27 13:18:21 -07001277 }
1278 }
Colin Cross29394222015-04-27 13:18:21 -07001279}
1280
Colin Cross910242b2016-04-11 15:41:52 -07001281// Clones a build logic module by calling the factory method for its module type, and then cloning
1282// property values. Any values stored in the module object that are not stored in properties
1283// structs will be lost.
1284func (c *Context) cloneLogicModule(origModule *moduleInfo) (Module, []interface{}) {
Colin Crossaf4fd212017-07-28 14:32:36 -07001285 newLogicModule, newProperties := origModule.factory()
Colin Cross910242b2016-04-11 15:41:52 -07001286
Colin Crossd2f4ac12017-07-28 14:31:03 -07001287 if len(newProperties) != len(origModule.properties) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001288 panic("mismatched properties array length in " + origModule.Name())
Colin Cross910242b2016-04-11 15:41:52 -07001289 }
1290
1291 for i := range newProperties {
Colin Cross5d57b2d2020-01-27 16:14:31 -08001292 dst := reflect.ValueOf(newProperties[i])
1293 src := reflect.ValueOf(origModule.properties[i])
Colin Cross910242b2016-04-11 15:41:52 -07001294
1295 proptools.CopyProperties(dst, src)
1296 }
1297
1298 return newLogicModule, newProperties
1299}
1300
Colin Crossedc41762020-08-13 12:07:30 -07001301func newVariant(module *moduleInfo, mutatorName string, variationName string,
1302 local bool) variant {
1303
1304 newVariantName := module.variant.name
1305 if variationName != "" {
1306 if newVariantName == "" {
1307 newVariantName = variationName
1308 } else {
1309 newVariantName += "_" + variationName
1310 }
1311 }
1312
1313 newVariations := module.variant.variations.clone()
1314 if newVariations == nil {
1315 newVariations = make(variationMap)
1316 }
1317 newVariations[mutatorName] = variationName
1318
1319 newDependencyVariations := module.variant.dependencyVariations.clone()
1320 if !local {
1321 if newDependencyVariations == nil {
1322 newDependencyVariations = make(variationMap)
1323 }
1324 newDependencyVariations[mutatorName] = variationName
1325 }
1326
1327 return variant{newVariantName, newVariations, newDependencyVariations}
1328}
1329
Colin Crossf5e34b92015-03-13 16:02:36 -07001330func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
Colin Cross5df74a82020-08-24 16:18:21 -07001331 defaultVariationName *string, variationNames []string, local bool) (modulesOrAliases, []error) {
Colin Crossc9028482014-12-18 16:28:54 -08001332
Colin Crossf4d18a62015-03-18 17:43:15 -07001333 if len(variationNames) == 0 {
1334 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001335 mutatorName, origModule.Name()))
Colin Crossf4d18a62015-03-18 17:43:15 -07001336 }
1337
Colin Cross5df74a82020-08-24 16:18:21 -07001338 var newModules modulesOrAliases
Colin Crossc9028482014-12-18 16:28:54 -08001339
Colin Cross174ae052015-03-03 17:37:03 -08001340 var errs []error
1341
Colin Crossf5e34b92015-03-13 16:02:36 -07001342 for i, variationName := range variationNames {
Colin Crossc9028482014-12-18 16:28:54 -08001343 var newLogicModule Module
1344 var newProperties []interface{}
1345
1346 if i == 0 {
1347 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -07001348 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
1349 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossd2f4ac12017-07-28 14:31:03 -07001350 newLogicModule, newProperties = origModule.logicModule, origModule.properties
Colin Crossc9028482014-12-18 16:28:54 -08001351 } else {
Colin Cross910242b2016-04-11 15:41:52 -07001352 newLogicModule, newProperties = c.cloneLogicModule(origModule)
Colin Crossc9028482014-12-18 16:28:54 -08001353 }
1354
Colin Crossed342d92015-03-11 00:57:25 -07001355 m := *origModule
1356 newModule := &m
Colin Cross2da84922020-07-02 10:08:12 -07001357 newModule.directDeps = append([]depInfo(nil), origModule.directDeps...)
Colin Cross7ff2e8d2021-01-21 22:39:28 -08001358 newModule.reverseDeps = nil
1359 newModule.forwardDeps = nil
Colin Crossed342d92015-03-11 00:57:25 -07001360 newModule.logicModule = newLogicModule
Colin Crossedc41762020-08-13 12:07:30 -07001361 newModule.variant = newVariant(origModule, mutatorName, variationName, local)
Colin Crossd2f4ac12017-07-28 14:31:03 -07001362 newModule.properties = newProperties
Colin Cross2da84922020-07-02 10:08:12 -07001363 newModule.providers = append([]interface{}(nil), origModule.providers...)
Colin Crossc9028482014-12-18 16:28:54 -08001364
1365 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -07001366
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001367 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName, defaultVariationName)
Colin Cross174ae052015-03-03 17:37:03 -08001368 if len(newErrs) > 0 {
1369 errs = append(errs, newErrs...)
1370 }
Colin Crossc9028482014-12-18 16:28:54 -08001371 }
1372
1373 // Mark original variant as invalid. Modules that depend on this module will still
1374 // depend on origModule, but we'll fix it when the mutator is called on them.
1375 origModule.logicModule = nil
1376 origModule.splitModules = newModules
1377
Colin Cross3702ac72016-08-11 11:09:00 -07001378 atomic.AddUint32(&c.depsModified, 1)
1379
Colin Cross174ae052015-03-03 17:37:03 -08001380 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -08001381}
1382
Colin Crossf5e34b92015-03-13 16:02:36 -07001383func (c *Context) convertDepsToVariation(module *moduleInfo,
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001384 mutatorName, variationName string, defaultVariationName *string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -08001385
Colin Crossc9028482014-12-18 16:28:54 -08001386 for i, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001387 if dep.module.logicModule == nil {
Colin Crossc9028482014-12-18 16:28:54 -08001388 var newDep *moduleInfo
Colin Cross2c1f3d12016-04-11 15:47:28 -07001389 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001390 if m.moduleOrAliasVariant().variations[mutatorName] == variationName {
1391 newDep = m.moduleOrAliasTarget()
Colin Crossc9028482014-12-18 16:28:54 -08001392 break
1393 }
1394 }
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001395 if newDep == nil && defaultVariationName != nil {
1396 // give it a second chance; match with defaultVariationName
1397 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001398 if m.moduleOrAliasVariant().variations[mutatorName] == *defaultVariationName {
1399 newDep = m.moduleOrAliasTarget()
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001400 break
1401 }
1402 }
1403 }
Colin Crossc9028482014-12-18 16:28:54 -08001404 if newDep == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001405 errs = append(errs, &BlueprintError{
Colin Crossf5e34b92015-03-13 16:02:36 -07001406 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001407 variationName, dep.module.Name(), module.Name()),
Colin Crossed342d92015-03-11 00:57:25 -07001408 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -08001409 })
1410 continue
Colin Crossc9028482014-12-18 16:28:54 -08001411 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001412 module.directDeps[i].module = newDep
Colin Crossc9028482014-12-18 16:28:54 -08001413 }
1414 }
Colin Cross174ae052015-03-03 17:37:03 -08001415
1416 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001417}
1418
Colin Crossedc41762020-08-13 12:07:30 -07001419func (c *Context) prettyPrintVariant(variations variationMap) string {
1420 names := make([]string, 0, len(variations))
Colin Cross65569e42015-03-10 20:08:19 -07001421 for _, m := range c.variantMutatorNames {
Colin Crossedc41762020-08-13 12:07:30 -07001422 if v, ok := variations[m]; ok {
Colin Cross65569e42015-03-10 20:08:19 -07001423 names = append(names, m+":"+v)
1424 }
1425 }
1426
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001427 return strings.Join(names, ",")
Colin Cross65569e42015-03-10 20:08:19 -07001428}
1429
Colin Crossd03b59d2019-11-13 20:10:12 -08001430func (c *Context) prettyPrintGroupVariants(group *moduleGroup) string {
1431 var variants []string
Colin Cross5df74a82020-08-24 16:18:21 -07001432 for _, moduleOrAlias := range group.modules {
1433 if mod := moduleOrAlias.module(); mod != nil {
1434 variants = append(variants, c.prettyPrintVariant(mod.variant.variations))
1435 } else if alias := moduleOrAlias.alias(); alias != nil {
1436 variants = append(variants, c.prettyPrintVariant(alias.variant.variations)+
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001437 " (alias to "+c.prettyPrintVariant(alias.target.variant.variations)+")")
Colin Cross5df74a82020-08-24 16:18:21 -07001438 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001439 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001440 return strings.Join(variants, "\n ")
1441}
1442
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001443func newModule(factory ModuleFactory) *moduleInfo {
Colin Crossaf4fd212017-07-28 14:32:36 -07001444 logicModule, properties := factory()
1445
Usta Shresthaee7a5d72022-01-10 22:46:23 -05001446 return &moduleInfo{
Colin Crossaf4fd212017-07-28 14:32:36 -07001447 logicModule: logicModule,
1448 factory: factory,
Usta Shresthaee7a5d72022-01-10 22:46:23 -05001449 properties: properties,
Colin Crossaf4fd212017-07-28 14:32:36 -07001450 }
Colin Crossaf4fd212017-07-28 14:32:36 -07001451}
1452
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001453func processModuleDef(moduleDef *parser.Module,
1454 relBlueprintsFile string, moduleFactories, scopedModuleFactories map[string]ModuleFactory, ignoreUnknownModuleTypes bool) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001455
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001456 factory, ok := moduleFactories[moduleDef.Type]
Colin Cross9672d862019-12-30 18:38:20 -08001457 if !ok && scopedModuleFactories != nil {
1458 factory, ok = scopedModuleFactories[moduleDef.Type]
1459 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001460 if !ok {
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001461 if ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001462 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001463 }
1464
Colin Cross7ad621c2015-01-07 16:22:45 -08001465 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001466 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001467 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1468 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001469 },
1470 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001471 }
1472
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001473 module := newModule(factory)
Colin Crossaf4fd212017-07-28 14:32:36 -07001474 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001475
Colin Crossaf4fd212017-07-28 14:32:36 -07001476 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001477
Colin Crossf27c5e42020-01-02 09:37:49 -08001478 propertyMap, errs := proptools.UnpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001479 if len(errs) > 0 {
Colin Crossf27c5e42020-01-02 09:37:49 -08001480 for i, err := range errs {
1481 if unpackErr, ok := err.(*proptools.UnpackError); ok {
1482 err = &BlueprintError{
1483 Err: unpackErr.Err,
1484 Pos: unpackErr.Pos,
1485 }
1486 errs[i] = err
1487 }
1488 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001489 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001490 }
1491
Colin Crossc32c4792016-06-09 15:52:30 -07001492 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001493 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001494 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001495 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001496 }
1497
Colin Cross7ad621c2015-01-07 16:22:45 -08001498 return module, nil
1499}
1500
Colin Cross23d7aa12015-06-30 16:05:22 -07001501func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001502 name := module.logicModule.Name()
Jaewoong Jungccc34942018-10-11 13:01:05 -07001503 if name == "" {
1504 return []error{
1505 &BlueprintError{
1506 Err: fmt.Errorf("property 'name' is missing from a module"),
1507 Pos: module.pos,
1508 },
1509 }
1510 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001511 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001512
Colin Cross0b7e83e2016-05-17 14:58:05 -07001513 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001514 name: name,
Colin Cross5df74a82020-08-24 16:18:21 -07001515 modules: modulesOrAliases{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001516 }
1517 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001518 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001519 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001520 ModuleGroup{moduleGroup: group},
1521 module.logicModule)
1522 if len(errs) > 0 {
1523 for i := range errs {
1524 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1525 }
1526 return errs
1527 }
1528 group.namespace = namespace
1529
Colin Cross0b7e83e2016-05-17 14:58:05 -07001530 c.moduleGroups = append(c.moduleGroups, group)
1531
Colin Cross23d7aa12015-06-30 16:05:22 -07001532 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001533}
1534
Jamie Gennisd4e10182014-06-12 20:06:50 -07001535// ResolveDependencies checks that the dependencies specified by all of the
1536// modules defined in the parsed Blueprints files are valid. This means that
1537// the modules depended upon are defined and that no circular dependencies
1538// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001539func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08001540 return c.resolveDependencies(c.Context, config)
1541}
Colin Cross5f03f112017-11-07 13:29:54 -08001542
Colin Cross3a8c0252019-01-23 13:21:48 -08001543func (c *Context) resolveDependencies(ctx context.Context, config interface{}) (deps []string, errs []error) {
1544 pprof.Do(ctx, pprof.Labels("blueprint", "ResolveDependencies"), func(ctx context.Context) {
Colin Cross2da84922020-07-02 10:08:12 -07001545 c.initProviders()
1546
Colin Cross3a8c0252019-01-23 13:21:48 -08001547 c.liveGlobals = newLiveTracker(config)
1548
1549 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1550 if len(errs) > 0 {
1551 return
1552 }
1553
1554 errs = c.updateDependencies()
1555 if len(errs) > 0 {
1556 return
1557 }
1558
1559 var mutatorDeps []string
1560 mutatorDeps, errs = c.runMutators(ctx, config)
1561 if len(errs) > 0 {
1562 return
1563 }
1564 deps = append(deps, mutatorDeps...)
1565
Colin Cross2da84922020-07-02 10:08:12 -07001566 if !c.skipCloneModulesAfterMutators {
1567 c.cloneModules()
1568 }
Colin Cross3a8c0252019-01-23 13:21:48 -08001569
1570 c.dependenciesReady = true
1571 })
1572
Colin Cross5f03f112017-11-07 13:29:54 -08001573 if len(errs) > 0 {
1574 return nil, errs
1575 }
1576
Colin Cross874a3462017-07-31 17:26:06 -07001577 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001578}
1579
Colin Cross763b6f12015-10-29 15:32:56 -07001580// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001581// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001582// module names returned by its DynamicDependencies method and those added by calling
1583// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001584func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001585 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001586 func() {
1587 defer func() {
1588 if r := recover(); r != nil {
1589 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1590 }
1591 }()
1592 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001593
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001594 if ctx.Failed() {
1595 return
1596 }
Colin Cross763b6f12015-10-29 15:32:56 -07001597
Colin Cross2c1f3d12016-04-11 15:47:28 -07001598 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001599 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001600 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001601}
1602
Colin Cross39644c02020-08-21 18:20:38 -07001603// findExactVariantOrSingle searches the moduleGroup for a module with the same variant as module,
1604// and returns the matching module, or nil if one is not found. A group with exactly one module
1605// is always considered matching.
1606func findExactVariantOrSingle(module *moduleInfo, possible *moduleGroup, reverse bool) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07001607 found, _ := findVariant(module, possible, nil, false, reverse)
1608 if found == nil {
1609 for _, moduleOrAlias := range possible.modules {
1610 if m := moduleOrAlias.module(); m != nil {
1611 if found != nil {
1612 // more than one possible match, give up
1613 return nil
1614 }
1615 found = m
1616 }
1617 }
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001618 }
Colin Cross5df74a82020-08-24 16:18:21 -07001619 return found
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001620}
1621
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001622func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) (*moduleInfo, []error) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001623 if _, ok := tag.(BaseDependencyTag); ok {
1624 panic("BaseDependencyTag is not allowed to be used directly!")
1625 }
1626
Colin Cross0b7e83e2016-05-17 14:58:05 -07001627 if depName == module.Name() {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001628 return nil, []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001629 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001630 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001631 }}
1632 }
1633
Colin Crossd03b59d2019-11-13 20:10:12 -08001634 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001635 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001636 return nil, c.discoveredMissingDependencies(module, depName, nil)
Colin Crossc9028482014-12-18 16:28:54 -08001637 }
1638
Colin Cross39644c02020-08-21 18:20:38 -07001639 if m := findExactVariantOrSingle(module, possibleDeps, false); m != nil {
Colin Cross99bdb2a2019-03-29 16:35:02 -07001640 module.newDirectDeps = append(module.newDirectDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001641 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001642 return m, nil
Colin Cross65569e42015-03-10 20:08:19 -07001643 }
Colin Crossc9028482014-12-18 16:28:54 -08001644
Paul Duffinb77556b2020-03-24 19:01:20 +00001645 if c.allowMissingDependencies {
1646 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001647 return nil, c.discoveredMissingDependencies(module, depName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001648 }
1649
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001650 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001651 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001652 depName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001653 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001654 c.prettyPrintGroupVariants(possibleDeps)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001655 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001656 }}
1657}
1658
Colin Cross8d8a7af2015-11-03 16:41:29 -08001659func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001660 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001661 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001662 Err: fmt.Errorf("%q depends on itself", destName),
1663 Pos: module.pos,
1664 }}
1665 }
1666
Colin Crossd03b59d2019-11-13 20:10:12 -08001667 possibleDeps := c.moduleGroupFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001668 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001669 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001670 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001671 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001672 Pos: module.pos,
1673 }}
1674 }
1675
Colin Cross39644c02020-08-21 18:20:38 -07001676 if m := findExactVariantOrSingle(module, possibleDeps, true); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001677 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001678 }
1679
Paul Duffinb77556b2020-03-24 19:01:20 +00001680 if c.allowMissingDependencies {
1681 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001682 return module, c.discoveredMissingDependencies(module, destName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001683 }
1684
Colin Cross2c628442016-10-07 17:13:10 -07001685 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001686 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001687 destName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001688 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001689 c.prettyPrintGroupVariants(possibleDeps)),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001690 Pos: module.pos,
1691 }}
1692}
1693
Colin Cross39644c02020-08-21 18:20:38 -07001694func findVariant(module *moduleInfo, possibleDeps *moduleGroup, variations []Variation, far bool, reverse bool) (*moduleInfo, variationMap) {
Colin Crossedc41762020-08-13 12:07:30 -07001695 // We can't just append variant.Variant to module.dependencyVariant.variantName and
Colin Cross65569e42015-03-10 20:08:19 -07001696 // compare the strings because the result won't be in mutator registration order.
1697 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001698 var newVariant variationMap
1699 if !far {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001700 if !reverse {
1701 // For forward dependency, ignore local variants by matching against
1702 // dependencyVariant which doesn't have the local variants
Colin Crossedc41762020-08-13 12:07:30 -07001703 newVariant = module.variant.dependencyVariations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001704 } else {
1705 // For reverse dependency, use all the variants
Colin Crossedc41762020-08-13 12:07:30 -07001706 newVariant = module.variant.variations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001707 }
Colin Cross89486232015-05-08 11:14:54 -07001708 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001709 for _, v := range variations {
Colin Cross9403b5a2019-11-13 20:11:04 -08001710 if newVariant == nil {
1711 newVariant = make(variationMap)
1712 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001713 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001714 }
1715
Colin Crossd03b59d2019-11-13 20:10:12 -08001716 check := func(variant variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -07001717 if far {
Colin Cross5dc67592020-08-24 14:46:13 -07001718 return newVariant.subsetOf(variant)
Colin Cross89486232015-05-08 11:14:54 -07001719 } else {
Colin Crossd03b59d2019-11-13 20:10:12 -08001720 return variant.equal(newVariant)
Colin Cross65569e42015-03-10 20:08:19 -07001721 }
1722 }
1723
Colin Crossd03b59d2019-11-13 20:10:12 -08001724 var foundDep *moduleInfo
1725 for _, m := range possibleDeps.modules {
Colin Cross5df74a82020-08-24 16:18:21 -07001726 if check(m.moduleOrAliasVariant().variations) {
1727 foundDep = m.moduleOrAliasTarget()
Colin Crossd03b59d2019-11-13 20:10:12 -08001728 break
1729 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001730 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001731
Martin Stjernholm2f212472020-03-06 00:29:24 +00001732 return foundDep, newVariant
1733}
1734
1735func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001736 tag DependencyTag, depName string, far bool) (*moduleInfo, []error) {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001737 if _, ok := tag.(BaseDependencyTag); ok {
1738 panic("BaseDependencyTag is not allowed to be used directly!")
1739 }
1740
1741 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
1742 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001743 return nil, c.discoveredMissingDependencies(module, depName, nil)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001744 }
1745
Colin Cross5df74a82020-08-24 16:18:21 -07001746 foundDep, newVariant := findVariant(module, possibleDeps, variations, far, false)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001747
Colin Crossf7beb892019-11-13 20:11:14 -08001748 if foundDep == nil {
Paul Duffinb77556b2020-03-24 19:01:20 +00001749 if c.allowMissingDependencies {
1750 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001751 return nil, c.discoveredMissingDependencies(module, depName, newVariant)
Paul Duffinb77556b2020-03-24 19:01:20 +00001752 }
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001753 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001754 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
1755 depName, module.Name(),
1756 c.prettyPrintVariant(newVariant),
1757 c.prettyPrintGroupVariants(possibleDeps)),
1758 Pos: module.pos,
1759 }}
1760 }
1761
1762 if module == foundDep {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001763 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001764 Err: fmt.Errorf("%q depends on itself", depName),
1765 Pos: module.pos,
1766 }}
1767 }
1768 // AddVariationDependency allows adding a dependency on itself, but only if
1769 // that module is earlier in the module list than this one, since we always
1770 // run GenerateBuildActions in order for the variants of a module
1771 if foundDep.group == module.group && beforeInModuleList(module, foundDep, module.group.modules) {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001772 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001773 Err: fmt.Errorf("%q depends on later version of itself", depName),
1774 Pos: module.pos,
1775 }}
1776 }
1777 module.newDirectDeps = append(module.newDirectDeps, depInfo{foundDep, tag})
1778 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001779 return foundDep, nil
Colin Crossc9028482014-12-18 16:28:54 -08001780}
1781
Colin Crossf1875462016-04-11 17:33:13 -07001782func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001783 from, to Module) *moduleInfo {
Nan Zhang346b2d02017-03-10 16:39:27 -08001784 if _, ok := tag.(BaseDependencyTag); ok {
1785 panic("BaseDependencyTag is not allowed to be used directly!")
1786 }
Colin Crossf1875462016-04-11 17:33:13 -07001787
1788 var fromInfo, toInfo *moduleInfo
Colin Cross5df74a82020-08-24 16:18:21 -07001789 for _, moduleOrAlias := range origModule.splitModules {
1790 if m := moduleOrAlias.module(); m != nil {
1791 if m.logicModule == from {
1792 fromInfo = m
1793 }
1794 if m.logicModule == to {
1795 toInfo = m
1796 if fromInfo != nil {
1797 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
1798 }
Colin Crossf1875462016-04-11 17:33:13 -07001799 }
1800 }
1801 }
1802
1803 if fromInfo == nil || toInfo == nil {
1804 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001805 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001806 }
1807
Colin Cross99bdb2a2019-03-29 16:35:02 -07001808 fromInfo.newDirectDeps = append(fromInfo.newDirectDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001809 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001810 return toInfo
Colin Crossf1875462016-04-11 17:33:13 -07001811}
1812
Lukacs T. Berkieef56852021-09-02 11:34:06 +02001813// findBlueprintDescendants returns a map linking parent Blueprint files to child Blueprints files
1814// For example, if paths = []string{"a/b/c/Android.bp", "a/Android.bp"},
1815// then descendants = {"":[]string{"a/Android.bp"}, "a/Android.bp":[]string{"a/b/c/Android.bp"}}
Jeff Gastonc3e28442017-08-09 15:13:12 -07001816func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1817 // make mapping from dir path to file path
1818 filesByDir := make(map[string]string, len(paths))
1819 for _, path := range paths {
1820 dir := filepath.Dir(path)
1821 _, alreadyFound := filesByDir[dir]
1822 if alreadyFound {
1823 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1824 }
1825 filesByDir[dir] = path
1826 }
1827
Jeff Gaston656870f2017-11-29 18:37:31 -08001828 findAncestor := func(childFile string) (ancestor string) {
1829 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001830 for {
1831 ancestorDir := filepath.Dir(prevAncestorDir)
1832 if ancestorDir == prevAncestorDir {
1833 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001834 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001835 }
1836
1837 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1838 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001839 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001840 }
1841 prevAncestorDir = ancestorDir
1842 }
1843 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001844 // generate the descendants map
1845 descendants = make(map[string][]string, len(filesByDir))
1846 for _, childFile := range filesByDir {
1847 ancestorFile := findAncestor(childFile)
1848 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1849 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001850 return descendants, nil
1851}
1852
Colin Cross3702ac72016-08-11 11:09:00 -07001853type visitOrderer interface {
1854 // returns the number of modules that this module needs to wait for
1855 waitCount(module *moduleInfo) int
1856 // returns the list of modules that are waiting for this module
1857 propagate(module *moduleInfo) []*moduleInfo
1858 // visit modules in order
Colin Crossc4773d92020-08-25 17:12:59 -07001859 visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool)
Colin Cross3702ac72016-08-11 11:09:00 -07001860}
1861
Colin Cross7e723372018-03-28 11:50:12 -07001862type unorderedVisitorImpl struct{}
1863
1864func (unorderedVisitorImpl) waitCount(module *moduleInfo) int {
1865 return 0
1866}
1867
1868func (unorderedVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1869 return nil
1870}
1871
Colin Crossc4773d92020-08-25 17:12:59 -07001872func (unorderedVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross7e723372018-03-28 11:50:12 -07001873 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001874 if visit(module, nil) {
Colin Cross7e723372018-03-28 11:50:12 -07001875 return
1876 }
1877 }
1878}
1879
Colin Cross3702ac72016-08-11 11:09:00 -07001880type bottomUpVisitorImpl struct{}
1881
1882func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1883 return len(module.forwardDeps)
1884}
1885
1886func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1887 return module.reverseDeps
1888}
1889
Colin Crossc4773d92020-08-25 17:12:59 -07001890func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001891 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001892 if visit(module, nil) {
Colin Cross49c279a2016-08-05 22:30:44 -07001893 return
1894 }
1895 }
1896}
1897
Colin Cross3702ac72016-08-11 11:09:00 -07001898type topDownVisitorImpl struct{}
1899
1900func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1901 return len(module.reverseDeps)
1902}
1903
1904func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1905 return module.forwardDeps
1906}
1907
Colin Crossc4773d92020-08-25 17:12:59 -07001908func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001909 for i := 0; i < len(modules); i++ {
1910 module := modules[len(modules)-1-i]
Colin Crossc4773d92020-08-25 17:12:59 -07001911 if visit(module, nil) {
Colin Cross3702ac72016-08-11 11:09:00 -07001912 return
1913 }
1914 }
1915}
1916
1917var (
1918 bottomUpVisitor bottomUpVisitorImpl
1919 topDownVisitor topDownVisitorImpl
1920)
1921
Colin Crossc4773d92020-08-25 17:12:59 -07001922// pauseSpec describes a pause that a module needs to occur until another module has been visited,
1923// at which point the unpause channel will be closed.
1924type pauseSpec struct {
1925 paused *moduleInfo
1926 until *moduleInfo
1927 unpause unpause
1928}
1929
1930type unpause chan struct{}
1931
1932const parallelVisitLimit = 1000
1933
Colin Cross49c279a2016-08-05 22:30:44 -07001934// Calls visit on each module, guaranteeing that visit is not called on a module until visit on all
Colin Crossc4773d92020-08-25 17:12:59 -07001935// of its dependencies has finished. A visit function can write a pauseSpec to the pause channel
1936// to wait for another dependency to be visited. If a visit function returns true to cancel
1937// while another visitor is paused, the paused visitor will never be resumed and its goroutine
1938// will stay paused forever.
1939func parallelVisit(modules []*moduleInfo, order visitOrderer, limit int,
1940 visit func(module *moduleInfo, pause chan<- pauseSpec) bool) []error {
1941
Colin Cross7addea32015-03-11 15:43:52 -07001942 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001943 cancelCh := make(chan bool)
Colin Crossc4773d92020-08-25 17:12:59 -07001944 pauseCh := make(chan pauseSpec)
Colin Cross8900e9b2015-03-02 14:03:01 -08001945 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001946
Colin Crossc4773d92020-08-25 17:12:59 -07001947 var backlog []*moduleInfo // Visitors that are ready to start but backlogged due to limit.
1948 var unpauseBacklog []pauseSpec // Visitors that are ready to unpause but backlogged due to limit.
1949
1950 active := 0 // Number of visitors running, not counting paused visitors.
1951 visited := 0 // Number of finished visitors.
1952
1953 pauseMap := make(map[*moduleInfo][]pauseSpec)
1954
1955 for _, module := range modules {
Colin Cross3702ac72016-08-11 11:09:00 -07001956 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001957 }
1958
Colin Crossc4773d92020-08-25 17:12:59 -07001959 // Call the visitor on a module if there are fewer active visitors than the parallelism
1960 // limit, otherwise add it to the backlog.
1961 startOrBacklog := func(module *moduleInfo) {
1962 if active < limit {
1963 active++
Colin Cross7e723372018-03-28 11:50:12 -07001964 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07001965 ret := visit(module, pauseCh)
Colin Cross7e723372018-03-28 11:50:12 -07001966 if ret {
1967 cancelCh <- true
1968 }
1969 doneCh <- module
1970 }()
1971 } else {
1972 backlog = append(backlog, module)
1973 }
Colin Cross691a60d2015-01-07 18:08:56 -08001974 }
1975
Colin Crossc4773d92020-08-25 17:12:59 -07001976 // Unpause the already-started but paused visitor on a module if there are fewer active
1977 // visitors than the parallelism limit, otherwise add it to the backlog.
1978 unpauseOrBacklog := func(pauseSpec pauseSpec) {
1979 if active < limit {
1980 active++
1981 close(pauseSpec.unpause)
1982 } else {
1983 unpauseBacklog = append(unpauseBacklog, pauseSpec)
Colin Cross691a60d2015-01-07 18:08:56 -08001984 }
1985 }
1986
Colin Crossc4773d92020-08-25 17:12:59 -07001987 // Start any modules in the backlog up to the parallelism limit. Unpause paused modules first
1988 // since they may already be holding resources.
1989 unpauseOrStartFromBacklog := func() {
1990 for active < limit && len(unpauseBacklog) > 0 {
1991 unpause := unpauseBacklog[0]
1992 unpauseBacklog = unpauseBacklog[1:]
1993 unpauseOrBacklog(unpause)
1994 }
1995 for active < limit && len(backlog) > 0 {
1996 toVisit := backlog[0]
1997 backlog = backlog[1:]
1998 startOrBacklog(toVisit)
1999 }
2000 }
2001
2002 toVisit := len(modules)
2003
2004 // Start or backlog any modules that are not waiting for any other modules.
2005 for _, module := range modules {
2006 if module.waitingCount == 0 {
2007 startOrBacklog(module)
2008 }
2009 }
2010
2011 for active > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08002012 select {
Colin Cross7e723372018-03-28 11:50:12 -07002013 case <-cancelCh:
2014 cancel = true
2015 backlog = nil
Colin Cross7addea32015-03-11 15:43:52 -07002016 case doneModule := <-doneCh:
Colin Crossc4773d92020-08-25 17:12:59 -07002017 active--
Colin Cross8900e9b2015-03-02 14:03:01 -08002018 if !cancel {
Colin Crossc4773d92020-08-25 17:12:59 -07002019 // Mark this module as done.
2020 doneModule.waitingCount = -1
2021 visited++
2022
2023 // Unpause or backlog any modules that were waiting for this one.
2024 if unpauses, ok := pauseMap[doneModule]; ok {
2025 delete(pauseMap, doneModule)
2026 for _, unpause := range unpauses {
2027 unpauseOrBacklog(unpause)
2028 }
Colin Cross7e723372018-03-28 11:50:12 -07002029 }
Colin Crossc4773d92020-08-25 17:12:59 -07002030
2031 // Start any backlogged modules up to limit.
2032 unpauseOrStartFromBacklog()
2033
2034 // Decrement waitingCount on the next modules in the tree based
2035 // on propagation order, and start or backlog them if they are
2036 // ready to start.
Colin Cross3702ac72016-08-11 11:09:00 -07002037 for _, module := range order.propagate(doneModule) {
2038 module.waitingCount--
2039 if module.waitingCount == 0 {
Colin Crossc4773d92020-08-25 17:12:59 -07002040 startOrBacklog(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08002041 }
Colin Cross691a60d2015-01-07 18:08:56 -08002042 }
2043 }
Colin Crossc4773d92020-08-25 17:12:59 -07002044 case pauseSpec := <-pauseCh:
2045 if pauseSpec.until.waitingCount == -1 {
2046 // Module being paused for is already finished, resume immediately.
2047 close(pauseSpec.unpause)
2048 } else {
2049 // Register for unpausing.
2050 pauseMap[pauseSpec.until] = append(pauseMap[pauseSpec.until], pauseSpec)
2051
2052 // Don't count paused visitors as active so that this can't deadlock
2053 // if 1000 visitors are paused simultaneously.
2054 active--
2055 unpauseOrStartFromBacklog()
2056 }
Colin Cross691a60d2015-01-07 18:08:56 -08002057 }
2058 }
Colin Crossc4773d92020-08-25 17:12:59 -07002059
2060 if !cancel {
2061 // Invariant check: no backlogged modules, these weren't waiting on anything except
2062 // the parallelism limit so they should have run.
2063 if len(backlog) > 0 {
2064 panic(fmt.Errorf("parallelVisit finished with %d backlogged visitors", len(backlog)))
2065 }
2066
2067 // Invariant check: no backlogged paused modules, these weren't waiting on anything
2068 // except the parallelism limit so they should have run.
2069 if len(unpauseBacklog) > 0 {
2070 panic(fmt.Errorf("parallelVisit finished with %d backlogged unpaused visitors", len(unpauseBacklog)))
2071 }
2072
2073 if len(pauseMap) > 0 {
Colin Cross7d4958d2021-02-08 15:34:08 -08002074 // Probably a deadlock due to a newly added dependency cycle. Start from each module in
2075 // the order of the input modules list and perform a depth-first search for the module
2076 // it is paused on, ignoring modules that are marked as done. Note this traverses from
2077 // modules to the modules that would have been unblocked when that module finished, i.e
2078 // the reverse of the visitOrderer.
Colin Crossc4773d92020-08-25 17:12:59 -07002079
Colin Cross9793b0a2021-04-27 15:20:15 -07002080 // In order to reduce duplicated work, once a module has been checked and determined
2081 // not to be part of a cycle add it and everything that depends on it to the checked
2082 // map.
2083 checked := make(map[*moduleInfo]struct{})
2084
Colin Cross7d4958d2021-02-08 15:34:08 -08002085 var check func(module, end *moduleInfo) []*moduleInfo
2086 check = func(module, end *moduleInfo) []*moduleInfo {
Colin Crossc4773d92020-08-25 17:12:59 -07002087 if module.waitingCount == -1 {
2088 // This module was finished, it can't be part of a loop.
2089 return nil
2090 }
2091 if module == end {
2092 // This module is the end of the loop, start rolling up the cycle.
2093 return []*moduleInfo{module}
2094 }
2095
Colin Cross9793b0a2021-04-27 15:20:15 -07002096 if _, alreadyChecked := checked[module]; alreadyChecked {
2097 return nil
2098 }
2099
Colin Crossc4773d92020-08-25 17:12:59 -07002100 for _, dep := range order.propagate(module) {
Colin Cross7d4958d2021-02-08 15:34:08 -08002101 cycle := check(dep, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002102 if cycle != nil {
2103 return append([]*moduleInfo{module}, cycle...)
2104 }
2105 }
2106 for _, depPauseSpec := range pauseMap[module] {
Colin Cross7d4958d2021-02-08 15:34:08 -08002107 cycle := check(depPauseSpec.paused, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002108 if cycle != nil {
2109 return append([]*moduleInfo{module}, cycle...)
2110 }
2111 }
2112
Colin Cross9793b0a2021-04-27 15:20:15 -07002113 checked[module] = struct{}{}
Colin Crossc4773d92020-08-25 17:12:59 -07002114 return nil
2115 }
2116
Colin Cross7d4958d2021-02-08 15:34:08 -08002117 // Iterate over the modules list instead of pauseMap to provide deterministic ordering.
2118 for _, module := range modules {
2119 for _, pauseSpec := range pauseMap[module] {
2120 cycle := check(pauseSpec.paused, pauseSpec.until)
2121 if len(cycle) > 0 {
2122 return cycleError(cycle)
2123 }
2124 }
Colin Crossc4773d92020-08-25 17:12:59 -07002125 }
2126 }
2127
2128 // Invariant check: if there was no deadlock and no cancellation every module
2129 // should have been visited.
2130 if visited != toVisit {
2131 panic(fmt.Errorf("parallelVisit ran %d visitors, expected %d", visited, toVisit))
2132 }
2133
2134 // Invariant check: if there was no deadlock and no cancellation every module
2135 // should have been visited, so there is nothing left to be paused on.
2136 if len(pauseMap) > 0 {
2137 panic(fmt.Errorf("parallelVisit finished with %d paused visitors", len(pauseMap)))
2138 }
2139 }
2140
2141 return nil
2142}
2143
2144func cycleError(cycle []*moduleInfo) (errs []error) {
2145 // The cycle list is in reverse order because all the 'check' calls append
2146 // their own module to the list.
2147 errs = append(errs, &BlueprintError{
2148 Err: fmt.Errorf("encountered dependency cycle:"),
2149 Pos: cycle[len(cycle)-1].pos,
2150 })
2151
2152 // Iterate backwards through the cycle list.
2153 curModule := cycle[0]
2154 for i := len(cycle) - 1; i >= 0; i-- {
2155 nextModule := cycle[i]
2156 errs = append(errs, &BlueprintError{
Colin Crosse5ff7702021-04-27 15:33:49 -07002157 Err: fmt.Errorf(" %s depends on %s",
2158 curModule, nextModule),
Colin Crossc4773d92020-08-25 17:12:59 -07002159 Pos: curModule.pos,
2160 })
2161 curModule = nextModule
2162 }
2163
2164 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002165}
2166
2167// updateDependencies recursively walks the module dependency graph and updates
2168// additional fields based on the dependencies. It builds a sorted list of modules
2169// such that dependencies of a module always appear first, and populates reverse
2170// dependency links and counts of total dependencies. It also reports errors when
Usta Shresthaee7a5d72022-01-10 22:46:23 -05002171// it encounters dependency cycles. This should be called after resolveDependencies,
Colin Cross691a60d2015-01-07 18:08:56 -08002172// as well as after any mutator pass has called addDependency
2173func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002174 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002175 visited := make(map[*moduleInfo]bool) // modules that were already checked
2176 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002177
Colin Cross7addea32015-03-11 15:43:52 -07002178 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002179
Colin Cross7addea32015-03-11 15:43:52 -07002180 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002181
Colin Cross7addea32015-03-11 15:43:52 -07002182 check = func(module *moduleInfo) []*moduleInfo {
2183 visited[module] = true
2184 checking[module] = true
2185 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002186
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002187 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2188 module.reverseDeps = module.reverseDeps[:0]
2189 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002190
2191 // Add an implicit dependency ordering on all earlier modules in the same module group
2192 for _, dep := range module.group.modules {
2193 if dep == module {
2194 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002195 }
Colin Cross5df74a82020-08-24 16:18:21 -07002196 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002197 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002198 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002199 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002200
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002201 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002202 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002203 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2204 for _, exists := range module.forwardDeps {
2205 if dep.module == exists {
2206 continue outer
2207 }
2208 }
2209 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002210 }
2211
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002212 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002213 if checking[dep] {
2214 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002215 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002216 }
2217
2218 if !visited[dep] {
2219 cycle := check(dep)
2220 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002221 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002222 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002223 // for generating the errors.
2224 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002225
2226 // We can continue processing this module's children to
2227 // find more cycles. Since all the modules that were
2228 // part of the found cycle were marked as visited we
2229 // won't run into that cycle again.
2230 } else {
2231 // We're not the "start" of the cycle, so we just append
2232 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002233 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002234 }
2235 }
2236 }
Colin Cross691a60d2015-01-07 18:08:56 -08002237
Colin Cross7addea32015-03-11 15:43:52 -07002238 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002239 }
2240
Colin Cross7addea32015-03-11 15:43:52 -07002241 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002242
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002243 return nil
2244 }
2245
Colin Cross7addea32015-03-11 15:43:52 -07002246 for _, module := range c.moduleInfo {
2247 if !visited[module] {
2248 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002249 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002250 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002251 panic("inconceivable!")
2252 }
Colin Crossc4773d92020-08-25 17:12:59 -07002253 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002254 }
2255 }
2256 }
2257
Colin Cross7addea32015-03-11 15:43:52 -07002258 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002259
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002260 return
2261}
2262
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002263type jsonVariationMap map[string]string
2264
2265type jsonModuleName struct {
2266 Name string
2267 Variations jsonVariationMap
2268 DependencyVariations jsonVariationMap
2269}
2270
2271type jsonDep struct {
2272 jsonModuleName
2273 Tag string
2274}
2275
Lukacs T. Berki16022262021-06-25 09:10:56 +02002276type JsonModule struct {
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002277 jsonModuleName
2278 Deps []jsonDep
2279 Type string
2280 Blueprint string
Lukacs T. Berki16022262021-06-25 09:10:56 +02002281 Module map[string]interface{}
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002282}
2283
2284func toJsonVariationMap(vm variationMap) jsonVariationMap {
2285 return jsonVariationMap(vm)
2286}
2287
2288func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2289 return &jsonModuleName{
2290 Name: m.Name(),
2291 Variations: toJsonVariationMap(m.variant.variations),
2292 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2293 }
2294}
2295
Lukacs T. Berki16022262021-06-25 09:10:56 +02002296type JSONDataSupplier interface {
2297 AddJSONData(d *map[string]interface{})
2298}
2299
kgui20f19a52022-01-10 12:17:32 +08002300// A JSONDataAction contains the inputs and outputs of actions of a module. Which helps pass such
2301// data to be included in the JSON module graph.
2302type JSONDataAction struct {
2303 Inputs []string
2304 Outputs []string
2305}
2306
2307// FormatJSONDataActions puts the content of a list of JSONDataActions into a standard format to be
2308// appended into the JSON module graph.
2309func FormatJSONDataActions(jsonDataActions []JSONDataAction) []map[string]interface{} {
2310 var actions []map[string]interface{}
2311 for _, jsonDataAction := range jsonDataActions {
2312 actions = append(actions, map[string]interface{}{
2313 "Inputs": jsonDataAction.Inputs,
2314 "Outputs": jsonDataAction.Outputs,
2315 })
2316 }
2317 return actions
2318}
2319
Lukacs T. Berki16022262021-06-25 09:10:56 +02002320func jsonModuleFromModuleInfo(m *moduleInfo) *JsonModule {
2321 result := &JsonModule{
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002322 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2323 Deps: make([]jsonDep, 0),
2324 Type: m.typeName,
2325 Blueprint: m.relBlueprintsFile,
Lukacs T. Berki16022262021-06-25 09:10:56 +02002326 Module: make(map[string]interface{}),
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002327 }
Lukacs T. Berki16022262021-06-25 09:10:56 +02002328
2329 if j, ok := m.logicModule.(JSONDataSupplier); ok {
2330 j.AddJSONData(&result.Module)
2331 }
2332
2333 for _, p := range m.providers {
2334 if j, ok := p.(JSONDataSupplier); ok {
2335 j.AddJSONData(&result.Module)
2336 }
2337 }
2338 return result
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002339}
2340
2341func (c *Context) PrintJSONGraph(w io.Writer) {
Lukacs T. Berki16022262021-06-25 09:10:56 +02002342 modules := make([]*JsonModule, 0)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002343 for _, m := range c.modulesSorted {
2344 jm := jsonModuleFromModuleInfo(m)
2345 for _, d := range m.directDeps {
2346 jm.Deps = append(jm.Deps, jsonDep{
2347 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2348 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2349 })
2350 }
2351
2352 modules = append(modules, jm)
2353 }
2354
Liz Kammer6e4ee8d2021-08-17 17:32:42 -04002355 e := json.NewEncoder(w)
2356 e.SetIndent("", "\t")
2357 e.Encode(modules)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002358}
2359
Jamie Gennisd4e10182014-06-12 20:06:50 -07002360// PrepareBuildActions generates an internal representation of all the build
2361// actions that need to be performed. This process involves invoking the
2362// GenerateBuildActions method on each of the Module objects created during the
2363// parse phase and then on each of the registered Singleton objects.
2364//
2365// If the ResolveDependencies method has not already been called it is called
2366// automatically by this method.
2367//
2368// The config argument is made available to all of the Module and Singleton
2369// objects via the Config method on the ModuleContext and SingletonContext
2370// objects passed to GenerateBuildActions. It is also passed to the functions
2371// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2372// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002373//
2374// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002375// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2376// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2377// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002378
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002379func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002380 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2381 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002382
Colin Cross3a8c0252019-01-23 13:21:48 -08002383 if !c.dependenciesReady {
2384 var extraDeps []string
2385 extraDeps, errs = c.resolveDependencies(ctx, config)
2386 if len(errs) > 0 {
2387 return
2388 }
2389 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002390 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002391
Colin Cross3a8c0252019-01-23 13:21:48 -08002392 var depsModules []string
2393 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2394 if len(errs) > 0 {
2395 return
2396 }
2397
2398 var depsSingletons []string
2399 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2400 if len(errs) > 0 {
2401 return
2402 }
2403
2404 deps = append(deps, depsModules...)
2405 deps = append(deps, depsSingletons...)
2406
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02002407 if c.outDir != nil {
2408 err := c.liveGlobals.addNinjaStringDeps(c.outDir)
Colin Cross3a8c0252019-01-23 13:21:48 -08002409 if err != nil {
2410 errs = []error{err}
2411 return
2412 }
2413 }
2414
2415 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2416
2417 deps = append(deps, depsPackages...)
2418
Colin Cross92054a42021-01-21 16:49:25 -08002419 c.memoizeFullNames(c.liveGlobals, pkgNames)
2420
Colin Cross3a8c0252019-01-23 13:21:48 -08002421 // This will panic if it finds a problem since it's a programming error.
2422 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2423
2424 c.pkgNames = pkgNames
2425 c.globalVariables = c.liveGlobals.variables
2426 c.globalPools = c.liveGlobals.pools
2427 c.globalRules = c.liveGlobals.rules
2428
2429 c.buildActionsReady = true
2430 })
2431
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002432 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002433 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002434 }
2435
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002436 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002437}
2438
Colin Cross3a8c0252019-01-23 13:21:48 -08002439func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002440 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002441
Colin Cross3a8c0252019-01-23 13:21:48 -08002442 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2443 mutators = append(mutators, c.earlyMutatorInfo...)
2444 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002445
Colin Cross3a8c0252019-01-23 13:21:48 -08002446 for _, mutator := range mutators {
2447 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2448 var newDeps []string
2449 if mutator.topDownMutator != nil {
2450 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2451 } else if mutator.bottomUpMutator != nil {
2452 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2453 } else {
2454 panic("no mutator set on " + mutator.name)
2455 }
2456 if len(errs) > 0 {
2457 return
2458 }
2459 deps = append(deps, newDeps...)
2460 })
2461 if len(errs) > 0 {
2462 return
2463 }
Colin Crossc9028482014-12-18 16:28:54 -08002464 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002465 })
2466
2467 if len(errs) > 0 {
2468 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002469 }
2470
Colin Cross874a3462017-07-31 17:26:06 -07002471 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002472}
2473
Colin Cross3702ac72016-08-11 11:09:00 -07002474type mutatorDirection interface {
2475 run(mutator *mutatorInfo, ctx *mutatorContext)
2476 orderer() visitOrderer
2477 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002478}
2479
Colin Cross3702ac72016-08-11 11:09:00 -07002480type bottomUpMutatorImpl struct{}
2481
2482func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2483 mutator.bottomUpMutator(ctx)
2484}
2485
2486func (bottomUpMutatorImpl) orderer() visitOrderer {
2487 return bottomUpVisitor
2488}
2489
2490func (bottomUpMutatorImpl) String() string {
2491 return "bottom up mutator"
2492}
2493
2494type topDownMutatorImpl struct{}
2495
2496func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2497 mutator.topDownMutator(ctx)
2498}
2499
2500func (topDownMutatorImpl) orderer() visitOrderer {
2501 return topDownVisitor
2502}
2503
2504func (topDownMutatorImpl) String() string {
2505 return "top down mutator"
2506}
2507
2508var (
2509 topDownMutator topDownMutatorImpl
2510 bottomUpMutator bottomUpMutatorImpl
2511)
2512
Colin Cross49c279a2016-08-05 22:30:44 -07002513type reverseDep struct {
2514 module *moduleInfo
2515 dep depInfo
2516}
2517
Colin Cross3702ac72016-08-11 11:09:00 -07002518func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002519 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002520
2521 newModuleInfo := make(map[Module]*moduleInfo)
2522 for k, v := range c.moduleInfo {
2523 newModuleInfo[k] = v
2524 }
Colin Crossc9028482014-12-18 16:28:54 -08002525
Colin Cross0ce142c2016-12-09 10:29:05 -08002526 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002527 reverse []reverseDep
2528 rename []rename
2529 replace []replace
2530 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002531 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002532 }
2533
Colin Cross2c1f3d12016-04-11 15:47:28 -07002534 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002535 var rename []rename
2536 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002537 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002538
Colin Cross49c279a2016-08-05 22:30:44 -07002539 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002540 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002541 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002542 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002543
Colin Cross3702ac72016-08-11 11:09:00 -07002544 c.depsModified = 0
2545
Colin Crossc4773d92020-08-25 17:12:59 -07002546 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002547 if module.splitModules != nil {
2548 panic("split module found in sorted module list")
2549 }
2550
Colin Cross7addea32015-03-11 15:43:52 -07002551 mctx := &mutatorContext{
2552 baseModuleContext: baseModuleContext{
2553 context: c,
2554 config: config,
2555 module: module,
2556 },
Colin Crossc4773d92020-08-25 17:12:59 -07002557 name: mutator.name,
2558 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002559 }
Colin Crossc9028482014-12-18 16:28:54 -08002560
Colin Cross2da84922020-07-02 10:08:12 -07002561 module.startedMutator = mutator
2562
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002563 func() {
2564 defer func() {
2565 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002566 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002567 if err, ok := r.(panicError); ok {
2568 err.addIn(in)
2569 mctx.error(err)
2570 } else {
2571 mctx.error(newPanicErrorf(r, in))
2572 }
2573 }
2574 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002575 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002576 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002577
Colin Cross2da84922020-07-02 10:08:12 -07002578 module.finishedMutator = mutator
2579
Colin Cross7addea32015-03-11 15:43:52 -07002580 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002581 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002582 return true
Colin Cross7addea32015-03-11 15:43:52 -07002583 }
Colin Crossc9028482014-12-18 16:28:54 -08002584
Colin Cross5fe225f2017-07-28 15:22:46 -07002585 if len(mctx.newVariations) > 0 {
2586 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002587 }
2588
Colin Crossab0a83f2020-03-03 14:23:27 -08002589 if len(mctx.reverseDeps) > 0 || len(mctx.replace) > 0 || len(mctx.rename) > 0 || len(mctx.newModules) > 0 || len(mctx.ninjaFileDeps) > 0 {
Colin Cross0ce142c2016-12-09 10:29:05 -08002590 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002591 reverse: mctx.reverseDeps,
2592 replace: mctx.replace,
2593 rename: mctx.rename,
2594 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002595 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002596 }
Colin Cross49c279a2016-08-05 22:30:44 -07002597 }
2598
2599 return false
2600 }
2601
2602 // Process errs and reverseDeps in a single goroutine
2603 go func() {
2604 for {
2605 select {
2606 case newErrs := <-errsCh:
2607 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002608 case globalStateChange := <-globalStateCh:
2609 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002610 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2611 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002612 replace = append(replace, globalStateChange.replace...)
2613 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002614 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002615 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002616 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002617 for _, moduleOrAlias := range newVariations {
2618 if m := moduleOrAlias.module(); m != nil {
2619 newModuleInfo[m.logicModule] = m
2620 }
Colin Cross49c279a2016-08-05 22:30:44 -07002621 }
2622 case <-done:
2623 return
Colin Crossc9028482014-12-18 16:28:54 -08002624 }
2625 }
Colin Cross49c279a2016-08-05 22:30:44 -07002626 }()
Colin Crossc9028482014-12-18 16:28:54 -08002627
Colin Cross2da84922020-07-02 10:08:12 -07002628 c.startedMutator = mutator
2629
Colin Crossc4773d92020-08-25 17:12:59 -07002630 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002631 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002632 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002633 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002634 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002635 }
2636
Colin Crossc4773d92020-08-25 17:12:59 -07002637 if len(visitErrs) > 0 {
2638 return nil, visitErrs
2639 }
2640
Colin Cross2da84922020-07-02 10:08:12 -07002641 c.finishedMutators[mutator] = true
2642
Colin Cross49c279a2016-08-05 22:30:44 -07002643 done <- true
2644
2645 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002646 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002647 }
2648
2649 c.moduleInfo = newModuleInfo
2650
2651 for _, group := range c.moduleGroups {
2652 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002653 module := group.modules[i].module()
2654 if module == nil {
2655 // Existing alias, skip it
2656 continue
2657 }
Colin Cross49c279a2016-08-05 22:30:44 -07002658
2659 // Update module group to contain newly split variants
2660 if module.splitModules != nil {
2661 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2662 }
2663
2664 // Fix up any remaining dependencies on modules that were split into variants
2665 // by replacing them with the first variant
2666 for j, dep := range module.directDeps {
2667 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002668 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002669 }
2670 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002671
Colin Cross322cc012019-05-20 13:55:14 -07002672 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002673 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002674 }
2675
Colin Cross99bdb2a2019-03-29 16:35:02 -07002676 // Add in any new direct dependencies that were added by the mutator
2677 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2678 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002679 }
Colin Crossf7beb892019-11-13 20:11:14 -08002680
Colin Cross279489c2020-08-13 12:11:52 -07002681 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002682 for _, moduleOrAlias := range group.modules {
2683 if alias := moduleOrAlias.alias(); alias != nil {
2684 if alias.variant.variations.equal(variant.variations) {
2685 return alias.target
2686 }
Colin Cross279489c2020-08-13 12:11:52 -07002687 }
2688 }
2689 return nil
2690 }
2691
Colin Crossf7beb892019-11-13 20:11:14 -08002692 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002693 // Use a manual loop instead of range because len(group.modules) can
2694 // change inside the loop
2695 for i := 0; i < len(group.modules); i++ {
2696 if alias := group.modules[i].alias(); alias != nil {
2697 if alias.target.logicModule == nil {
2698 newTarget := findAliasTarget(alias.target.variant)
2699 if newTarget != nil {
2700 alias.target = newTarget
2701 } else {
2702 // The alias was left dangling, remove it.
2703 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2704 i--
2705 }
Colin Crossf7beb892019-11-13 20:11:14 -08002706 }
2707 }
2708 }
Colin Crossc9028482014-12-18 16:28:54 -08002709 }
2710
Colin Cross99bdb2a2019-03-29 16:35:02 -07002711 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002712 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002713 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002714 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002715 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002716 }
2717
Colin Crossaf4fd212017-07-28 14:32:36 -07002718 for _, module := range newModules {
2719 errs = c.addModule(module)
2720 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002721 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002722 }
2723 atomic.AddUint32(&c.depsModified, 1)
2724 }
2725
Colin Cross0ce142c2016-12-09 10:29:05 -08002726 errs = c.handleRenames(rename)
2727 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002728 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002729 }
2730
2731 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002732 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002733 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002734 }
2735
Colin Cross3702ac72016-08-11 11:09:00 -07002736 if c.depsModified > 0 {
2737 errs = c.updateDependencies()
2738 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002739 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002740 }
Colin Crossc9028482014-12-18 16:28:54 -08002741 }
2742
Colin Cross874a3462017-07-31 17:26:06 -07002743 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002744}
2745
Colin Cross910242b2016-04-11 15:41:52 -07002746// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2747// a mutator sets a non-property member variable on a module, which works until a later mutator
2748// creates variants of that module.
2749func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002750 type update struct {
2751 orig Module
2752 clone *moduleInfo
2753 }
Colin Cross7e723372018-03-28 11:50:12 -07002754 ch := make(chan update)
2755 doneCh := make(chan bool)
2756 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002757 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2758 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2759 origLogicModule := m.logicModule
2760 m.logicModule, m.properties = c.cloneLogicModule(m)
2761 ch <- update{origLogicModule, m}
2762 return false
2763 })
2764 if len(errs) > 0 {
2765 panic(errs)
2766 }
Colin Cross7e723372018-03-28 11:50:12 -07002767 doneCh <- true
2768 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002769
Colin Cross7e723372018-03-28 11:50:12 -07002770 done := false
2771 for !done {
2772 select {
2773 case <-doneCh:
2774 done = true
2775 case update := <-ch:
2776 delete(c.moduleInfo, update.orig)
2777 c.moduleInfo[update.clone.logicModule] = update.clone
2778 }
Colin Cross910242b2016-04-11 15:41:52 -07002779 }
2780}
2781
Colin Cross49c279a2016-08-05 22:30:44 -07002782// Removes modules[i] from the list and inserts newModules... where it was located, returning
2783// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002784func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002785 spliceSize := len(newModules)
2786 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002787 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002788 if cap(modules) >= len(modules)-1+len(newModules) {
2789 // We can fit the splice in the existing capacity, do everything in place
2790 dest = modules[:newLen]
2791 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002792 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002793 copy(dest, modules[:i])
2794 }
2795
2796 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002797 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002798
2799 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002800 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002801
Colin Cross49c279a2016-08-05 22:30:44 -07002802 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002803}
2804
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002805func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002806 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002807
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002808 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002809 var errs []error
2810
Colin Cross691a60d2015-01-07 18:08:56 -08002811 cancelCh := make(chan struct{})
2812 errsCh := make(chan []error)
2813 depsCh := make(chan []string)
2814
2815 go func() {
2816 for {
2817 select {
2818 case <-cancelCh:
2819 close(cancelCh)
2820 return
2821 case newErrs := <-errsCh:
2822 errs = append(errs, newErrs...)
2823 case newDeps := <-depsCh:
2824 deps = append(deps, newDeps...)
2825
2826 }
2827 }
2828 }()
2829
Colin Crossc4773d92020-08-25 17:12:59 -07002830 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2831 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2832 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2833 sanitizedName := toNinjaName(uniqueName)
Yi Konga08e7222021-12-21 15:50:57 +08002834 sanitizedVariant := toNinjaName(module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002835
Yi Konga08e7222021-12-21 15:50:57 +08002836 prefix := moduleNamespacePrefix(sanitizedName + "_" + sanitizedVariant)
Jeff Gaston0e907592017-12-01 17:10:52 -08002837
Colin Crossc4773d92020-08-25 17:12:59 -07002838 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2839 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2840 // just set it to nil.
2841 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002842
Colin Crossc4773d92020-08-25 17:12:59 -07002843 mctx := &moduleContext{
2844 baseModuleContext: baseModuleContext{
2845 context: c,
2846 config: config,
2847 module: module,
2848 },
2849 scope: scope,
2850 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002851 }
Colin Cross036a1df2015-12-17 15:49:30 -08002852
Colin Cross2da84922020-07-02 10:08:12 -07002853 mctx.module.startedGenerateBuildActions = true
2854
Colin Crossc4773d92020-08-25 17:12:59 -07002855 func() {
2856 defer func() {
2857 if r := recover(); r != nil {
2858 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2859 if err, ok := r.(panicError); ok {
2860 err.addIn(in)
2861 mctx.error(err)
2862 } else {
2863 mctx.error(newPanicErrorf(r, in))
2864 }
2865 }
2866 }()
2867 mctx.module.logicModule.GenerateBuildActions(mctx)
2868 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002869
Colin Cross2da84922020-07-02 10:08:12 -07002870 mctx.module.finishedGenerateBuildActions = true
2871
Colin Crossc4773d92020-08-25 17:12:59 -07002872 if len(mctx.errs) > 0 {
2873 errsCh <- mctx.errs
2874 return true
2875 }
2876
2877 if module.missingDeps != nil && !mctx.handledMissingDeps {
2878 var errs []error
2879 for _, depName := range module.missingDeps {
2880 errs = append(errs, c.missingDependencyError(module, depName))
2881 }
2882 errsCh <- errs
2883 return true
2884 }
2885
2886 depsCh <- mctx.ninjaFileDeps
2887
2888 newErrs := c.processLocalBuildActions(&module.actionDefs,
2889 &mctx.actionDefs, liveGlobals)
2890 if len(newErrs) > 0 {
2891 errsCh <- newErrs
2892 return true
2893 }
2894 return false
2895 })
Colin Cross691a60d2015-01-07 18:08:56 -08002896
2897 cancelCh <- struct{}{}
2898 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002899
Colin Crossc4773d92020-08-25 17:12:59 -07002900 errs = append(errs, visitErrs...)
2901
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002902 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002903}
2904
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002905func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002906 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002907
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002908 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002909 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002910
Colin Cross5f03f112017-11-07 13:29:54 -08002911 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002912 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2913 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2914 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002915 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002916
2917 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002918 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002919 context: c,
2920 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002921 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002922 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002923 }
2924
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002925 func() {
2926 defer func() {
2927 if r := recover(); r != nil {
2928 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2929 if err, ok := r.(panicError); ok {
2930 err.addIn(in)
2931 sctx.error(err)
2932 } else {
2933 sctx.error(newPanicErrorf(r, in))
2934 }
2935 }
2936 }()
2937 info.singleton.GenerateBuildActions(sctx)
2938 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002939
2940 if len(sctx.errs) > 0 {
2941 errs = append(errs, sctx.errs...)
2942 if len(errs) > maxErrors {
2943 break
2944 }
2945 continue
2946 }
2947
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002948 deps = append(deps, sctx.ninjaFileDeps...)
2949
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002950 newErrs := c.processLocalBuildActions(&info.actionDefs,
2951 &sctx.actionDefs, liveGlobals)
2952 errs = append(errs, newErrs...)
2953 if len(errs) > maxErrors {
2954 break
2955 }
2956 }
2957
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002958 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002959}
2960
2961func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2962 liveGlobals *liveTracker) []error {
2963
2964 var errs []error
2965
2966 // First we go through and add everything referenced by the module's
2967 // buildDefs to the live globals set. This will end up adding the live
2968 // locals to the set as well, but we'll take them out after.
2969 for _, def := range in.buildDefs {
2970 err := liveGlobals.AddBuildDefDeps(def)
2971 if err != nil {
2972 errs = append(errs, err)
2973 }
2974 }
2975
2976 if len(errs) > 0 {
2977 return errs
2978 }
2979
Colin Crossc9028482014-12-18 16:28:54 -08002980 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002981
2982 // We use the now-incorrect set of live "globals" to determine which local
2983 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002984 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002985 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002986 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002987 if isLive {
2988 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002989 }
2990 }
2991
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002992 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002993 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002994 if isLive {
2995 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002996 }
2997 }
2998
2999 return nil
3000}
3001
Colin Cross9607a9f2018-06-20 11:16:37 -07003002func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07003003 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07003004
3005 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003006 var visiting *moduleInfo
3007
3008 defer func() {
3009 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07003010 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
3011 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003012 }
3013 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07003014
3015 var walk func(module *moduleInfo)
3016 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003017 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07003018 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003019 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07003020 recurse := true
3021 if visitDown != nil {
3022 recurse = visitDown(dep, module)
3023 }
Colin Cross526e02f2018-06-21 13:31:53 -07003024 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003025 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01003026 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07003027 }
Colin Crossbafd5f52016-08-06 22:52:01 -07003028 if visitUp != nil {
3029 visitUp(dep, module)
3030 }
Yuchen Wu222e2452015-10-06 14:03:27 -07003031 }
3032 }
3033 }
3034
3035 walk(topModule)
3036}
3037
Colin Cross9cfd1982016-10-11 09:58:53 -07003038type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003039 from, to *moduleInfo
3040 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003041}
3042
Colin Crossc4e5b812016-10-12 10:45:05 -07003043type rename struct {
3044 group *moduleGroup
3045 name string
3046}
3047
Colin Cross0ce142c2016-12-09 10:29:05 -08003048func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003049 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003050
Colin Crossd03b59d2019-11-13 20:10:12 -08003051 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003052 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003053 }
3054
Colin Crossd03b59d2019-11-13 20:10:12 -08003055 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003056 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003057 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003058 }
3059 }
3060
Colin Cross0ce142c2016-12-09 10:29:05 -08003061 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003062}
3063
Colin Cross0ce142c2016-12-09 10:29:05 -08003064func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003065 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003066 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003067 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003068 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003069 continue
3070 }
3071
Jeff Gastond70bf752017-11-10 15:12:08 -08003072 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003073 }
3074
Colin Cross0ce142c2016-12-09 10:29:05 -08003075 return errs
3076}
3077
3078func (c *Context) handleReplacements(replacements []replace) []error {
3079 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003080 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003081 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003082 for _, m := range replace.from.reverseDeps {
3083 for i, d := range m.directDeps {
3084 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003085 // If the replacement has a predicate then check it.
3086 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3087 m.directDeps[i].module = replace.to
3088 changedDeps = true
3089 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003090 }
3091 }
3092 }
3093
Colin Cross9cfd1982016-10-11 09:58:53 -07003094 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003095
Paul Duffin8969cb62020-06-30 12:15:26 +01003096 if changedDeps {
3097 atomic.AddUint32(&c.depsModified, 1)
3098 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003099 return errs
3100}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003101
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003102func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3103 if depVariations != nil {
3104 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3105 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003106 if c.allowMissingDependencies {
3107 module.missingDeps = append(module.missingDeps, depName)
3108 return nil
3109 }
3110 return []error{c.missingDependencyError(module, depName)}
3111}
3112
3113func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3114 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3115
3116 return &BlueprintError{
3117 Err: err,
3118 Pos: module.pos,
3119 }
3120}
3121
Colin Crossd03b59d2019-11-13 20:10:12 -08003122func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003123 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3124 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003125 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003126 }
3127 return nil
3128}
3129
Jeff Gastond70bf752017-11-10 15:12:08 -08003130func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003131 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003132 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3133 result := make([]*moduleGroup, 0, len(wrappers))
3134 for _, group := range wrappers {
3135 result = append(result, group.moduleGroup)
3136 }
3137 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003138 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003139
3140 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003141 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003142 }
3143
Jeff Gastond70bf752017-11-10 15:12:08 -08003144 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003145}
3146
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003147func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003148 var module *moduleInfo
3149
3150 defer func() {
3151 if r := recover(); r != nil {
3152 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3153 funcName(visit), module))
3154 }
3155 }()
3156
Jeff Gastond70bf752017-11-10 15:12:08 -08003157 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003158 for _, moduleOrAlias := range moduleGroup.modules {
3159 if module = moduleOrAlias.module(); module != nil {
3160 visit(module.logicModule)
3161 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003162 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003163 }
3164}
3165
3166func (c *Context) visitAllModulesIf(pred func(Module) bool,
3167 visit func(Module)) {
3168
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003169 var module *moduleInfo
3170
3171 defer func() {
3172 if r := recover(); r != nil {
3173 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3174 funcName(pred), funcName(visit), module))
3175 }
3176 }()
3177
Jeff Gastond70bf752017-11-10 15:12:08 -08003178 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003179 for _, moduleOrAlias := range moduleGroup.modules {
3180 if module = moduleOrAlias.module(); module != nil {
3181 if pred(module.logicModule) {
3182 visit(module.logicModule)
3183 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003184 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003185 }
3186 }
3187}
3188
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003189func (c *Context) visitAllModuleVariants(module *moduleInfo,
3190 visit func(Module)) {
3191
3192 var variant *moduleInfo
3193
3194 defer func() {
3195 if r := recover(); r != nil {
3196 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3197 module, funcName(visit), variant))
3198 }
3199 }()
3200
Colin Cross5df74a82020-08-24 16:18:21 -07003201 for _, moduleOrAlias := range module.group.modules {
3202 if variant = moduleOrAlias.module(); variant != nil {
3203 visit(variant.logicModule)
3204 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003205 }
3206}
3207
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003208func (c *Context) requireNinjaVersion(major, minor, micro int) {
3209 if major != 1 {
3210 panic("ninja version with major version != 1 not supported")
3211 }
3212 if c.requiredNinjaMinor < minor {
3213 c.requiredNinjaMinor = minor
3214 c.requiredNinjaMicro = micro
3215 }
3216 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3217 c.requiredNinjaMicro = micro
3218 }
3219}
3220
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003221func (c *Context) setOutDir(value ninjaString) {
3222 if c.outDir == nil {
3223 c.outDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003224 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003225}
3226
3227func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003228 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003229
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003230 pkgs := make(map[string]*packageContext)
3231 pkgNames := make(map[*packageContext]string)
3232 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003233
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003234 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003235 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003236 // This is a built-in rule and has no package.
3237 return
3238 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003239 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003240 // We've already processed this package.
3241 return
3242 }
3243
Jamie Gennis2fb20952014-10-03 02:49:58 -07003244 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003245 if present {
3246 // Short name collision. Both this package and the one that's
3247 // already there need to use their full names. We leave the short
3248 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003249 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003250 longPkgNames[otherPkg] = true
3251 } else {
3252 // No collision so far. Tentatively set the package's name to be
3253 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003254 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003255 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003256 }
3257 }
3258
3259 // We try to give all packages their short name, but when we get collisions
3260 // we need to use the full unique package name.
3261 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003262 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003263 }
3264 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003265 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003266 }
3267 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003268 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003269 }
3270
3271 // Add the packages that had collisions using their full unique names. This
3272 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003273 for pctx := range longPkgNames {
3274 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003275 }
3276
Dan Willemsena481ae22015-12-18 15:18:03 -08003277 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3278 deps := []string{}
3279 for _, pkg := range pkgs {
3280 deps = append(deps, pkg.ninjaFileDeps...)
3281 }
3282
3283 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003284}
3285
Colin Cross92054a42021-01-21 16:49:25 -08003286// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3287// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3288// are used much more than once.
3289func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3290 for v := range liveGlobals.variables {
3291 v.memoizeFullName(pkgNames)
3292 }
3293 for r := range liveGlobals.rules {
3294 r.memoizeFullName(pkgNames)
3295 }
3296 for p := range liveGlobals.pools {
3297 p.memoizeFullName(pkgNames)
3298 }
3299}
3300
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003301func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003302 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003303
3304 visited := make(map[Variable]bool) // variables that were already checked
3305 checking := make(map[Variable]bool) // variables actively being checked
3306
3307 var check func(v Variable) []Variable
3308
3309 check = func(v Variable) []Variable {
3310 visited[v] = true
3311 checking[v] = true
3312 defer delete(checking, v)
3313
3314 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003315 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003316 if checking[dep] {
3317 // This is a cycle.
3318 return []Variable{dep, v}
3319 }
3320
3321 if !visited[dep] {
3322 cycle := check(dep)
3323 if cycle != nil {
3324 if cycle[0] == v {
3325 // We are the "start" of the cycle, so we're responsible
3326 // for generating the errors. The cycle list is in
3327 // reverse order because all the 'check' calls append
3328 // their own module to the list.
3329 msgs := []string{"detected variable reference cycle:"}
3330
3331 // Iterate backwards through the cycle list.
3332 curName := v.fullName(pkgNames)
3333 curValue := value.Value(pkgNames)
3334 for i := len(cycle) - 1; i >= 0; i-- {
3335 next := cycle[i]
3336 nextName := next.fullName(pkgNames)
3337 nextValue := variables[next].Value(pkgNames)
3338
3339 msgs = append(msgs, fmt.Sprintf(
3340 " %q depends on %q", curName, nextName))
3341 msgs = append(msgs, fmt.Sprintf(
3342 " [%s = %s]", curName, curValue))
3343
3344 curName = nextName
3345 curValue = nextValue
3346 }
3347
3348 // Variable reference cycles are a programming error,
3349 // not the fault of the Blueprint file authors.
3350 panic(strings.Join(msgs, "\n"))
3351 } else {
3352 // We're not the "start" of the cycle, so we just append
3353 // our module to the list and return it.
3354 return append(cycle, v)
3355 }
3356 }
3357 }
3358 }
3359
3360 return nil
3361 }
3362
3363 for v := range variables {
3364 if !visited[v] {
3365 cycle := check(v)
3366 if cycle != nil {
3367 panic("inconceivable!")
3368 }
3369 }
3370 }
3371}
3372
Jamie Gennisaf435562014-10-27 22:34:56 -07003373// AllTargets returns a map all the build target names to the rule used to build
3374// them. This is the same information that is output by running 'ninja -t
3375// targets all'. If this is called before PrepareBuildActions successfully
3376// completes then ErrbuildActionsNotReady is returned.
3377func (c *Context) AllTargets() (map[string]string, error) {
3378 if !c.buildActionsReady {
3379 return nil, ErrBuildActionsNotReady
3380 }
3381
3382 targets := map[string]string{}
3383
3384 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003385 for _, module := range c.moduleInfo {
3386 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003387 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003388 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003389 outputValue, err := output.Eval(c.globalVariables)
3390 if err != nil {
3391 return nil, err
3392 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003393 targets[outputValue] = ruleName
3394 }
3395 }
3396 }
3397
3398 // Collect all the singleton build targets.
3399 for _, info := range c.singletonInfo {
3400 for _, buildDef := range info.actionDefs.buildDefs {
3401 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003402 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003403 outputValue, err := output.Eval(c.globalVariables)
3404 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003405 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003406 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003407 targets[outputValue] = ruleName
3408 }
3409 }
3410 }
3411
3412 return targets, nil
3413}
3414
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003415func (c *Context) OutDir() (string, error) {
3416 if c.outDir != nil {
3417 return c.outDir.Eval(c.globalVariables)
Colin Crossa2599452015-11-18 16:01:01 -08003418 } else {
3419 return "", nil
3420 }
3421}
3422
Colin Cross4572edd2015-05-13 14:36:24 -07003423// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3424// property structs returned by the factory for that module type.
3425func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3426 ret := make(map[string][]interface{})
3427 for moduleType, factory := range c.moduleFactories {
3428 _, ret[moduleType] = factory()
3429 }
3430
3431 return ret
3432}
3433
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003434func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3435 ret := make(map[string]ModuleFactory)
3436 for k, v := range c.moduleFactories {
3437 ret[k] = v
3438 }
3439 return ret
3440}
3441
Colin Cross4572edd2015-05-13 14:36:24 -07003442func (c *Context) ModuleName(logicModule Module) string {
3443 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003444 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003445}
3446
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003447func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003448 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003449}
3450
Colin Cross8c602f72015-12-17 18:02:11 -08003451func (c *Context) ModuleSubDir(logicModule Module) string {
3452 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003453 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003454}
3455
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003456func (c *Context) ModuleType(logicModule Module) string {
3457 module := c.moduleInfo[logicModule]
3458 return module.typeName
3459}
3460
Colin Cross2da84922020-07-02 10:08:12 -07003461// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3462// provider was not set it returns the zero value of the type of the provider, which means the
3463// return value can always be type-asserted to the type of the provider. The return value should
3464// always be considered read-only. It panics if called before the appropriate mutator or
3465// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3466// copy of the value originally passed to SetProvider.
3467func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3468 module := c.moduleInfo[logicModule]
3469 value, _ := c.provider(module, provider)
3470 return value
3471}
3472
3473// ModuleHasProvider returns true if the provider for the given module has been set.
3474func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3475 module := c.moduleInfo[logicModule]
3476 _, ok := c.provider(module, provider)
3477 return ok
3478}
3479
Colin Cross4572edd2015-05-13 14:36:24 -07003480func (c *Context) BlueprintFile(logicModule Module) string {
3481 module := c.moduleInfo[logicModule]
3482 return module.relBlueprintsFile
3483}
3484
3485func (c *Context) ModuleErrorf(logicModule Module, format string,
3486 args ...interface{}) error {
3487
3488 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003489 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003490 Err: fmt.Errorf(format, args...),
3491 Pos: module.pos,
3492 }
3493}
3494
3495func (c *Context) VisitAllModules(visit func(Module)) {
3496 c.visitAllModules(visit)
3497}
3498
3499func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3500 visit func(Module)) {
3501
3502 c.visitAllModulesIf(pred, visit)
3503}
3504
Colin Cross080c1332017-03-17 13:09:05 -07003505func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3506 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003507
Colin Cross080c1332017-03-17 13:09:05 -07003508 var visiting *moduleInfo
3509
3510 defer func() {
3511 if r := recover(); r != nil {
3512 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3513 topModule, funcName(visit), visiting))
3514 }
3515 }()
3516
3517 for _, dep := range topModule.directDeps {
3518 visiting = dep.module
3519 visit(dep.module.logicModule)
3520 }
3521}
3522
3523func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3524 topModule := c.moduleInfo[module]
3525
3526 var visiting *moduleInfo
3527
3528 defer func() {
3529 if r := recover(); r != nil {
3530 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3531 topModule, funcName(pred), funcName(visit), visiting))
3532 }
3533 }()
3534
3535 for _, dep := range topModule.directDeps {
3536 visiting = dep.module
3537 if pred(dep.module.logicModule) {
3538 visit(dep.module.logicModule)
3539 }
3540 }
3541}
3542
3543func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003544 topModule := c.moduleInfo[module]
3545
3546 var visiting *moduleInfo
3547
3548 defer func() {
3549 if r := recover(); r != nil {
3550 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3551 topModule, funcName(visit), visiting))
3552 }
3553 }()
3554
Colin Cross9607a9f2018-06-20 11:16:37 -07003555 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003556 visiting = dep.module
3557 visit(dep.module.logicModule)
3558 })
Colin Cross4572edd2015-05-13 14:36:24 -07003559}
3560
Colin Cross080c1332017-03-17 13:09:05 -07003561func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003562 topModule := c.moduleInfo[module]
3563
3564 var visiting *moduleInfo
3565
3566 defer func() {
3567 if r := recover(); r != nil {
3568 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3569 topModule, funcName(pred), funcName(visit), visiting))
3570 }
3571 }()
3572
Colin Cross9607a9f2018-06-20 11:16:37 -07003573 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003574 if pred(dep.module.logicModule) {
3575 visiting = dep.module
3576 visit(dep.module.logicModule)
3577 }
3578 })
Colin Cross4572edd2015-05-13 14:36:24 -07003579}
3580
Colin Cross24ad5872015-11-17 16:22:29 -08003581func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003582 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003583}
3584
3585func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003586 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003587}
3588
3589func (c *Context) VisitAllModuleVariants(module Module,
3590 visit func(Module)) {
3591
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003592 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003593}
3594
Colin Cross9226d6c2019-02-25 18:07:44 -08003595// Singletons returns a list of all registered Singletons.
3596func (c *Context) Singletons() []Singleton {
3597 var ret []Singleton
3598 for _, s := range c.singletonInfo {
3599 ret = append(ret, s.singleton)
3600 }
3601 return ret
3602}
3603
3604// SingletonName returns the name that the given singleton was registered with.
3605func (c *Context) SingletonName(singleton Singleton) string {
3606 for _, s := range c.singletonInfo {
3607 if s.singleton == singleton {
3608 return s.name
3609 }
3610 }
3611 return ""
3612}
3613
Jamie Gennisd4e10182014-06-12 20:06:50 -07003614// WriteBuildFile writes the Ninja manifeset text for the generated build
3615// actions to w. If this is called before PrepareBuildActions successfully
3616// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003617func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003618 var err error
3619 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3620 if !c.buildActionsReady {
3621 err = ErrBuildActionsNotReady
3622 return
3623 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003624
Colin Cross3a8c0252019-01-23 13:21:48 -08003625 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003626
Colin Cross3a8c0252019-01-23 13:21:48 -08003627 err = c.writeBuildFileHeader(nw)
3628 if err != nil {
3629 return
3630 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003631
Colin Cross3a8c0252019-01-23 13:21:48 -08003632 err = c.writeNinjaRequiredVersion(nw)
3633 if err != nil {
3634 return
3635 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003636
Colin Cross3a8c0252019-01-23 13:21:48 -08003637 err = c.writeSubninjas(nw)
3638 if err != nil {
3639 return
3640 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003641
Colin Cross3a8c0252019-01-23 13:21:48 -08003642 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003643
Colin Cross3a8c0252019-01-23 13:21:48 -08003644 err = c.writeGlobalVariables(nw)
3645 if err != nil {
3646 return
3647 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003648
Colin Cross3a8c0252019-01-23 13:21:48 -08003649 err = c.writeGlobalPools(nw)
3650 if err != nil {
3651 return
3652 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003653
Colin Cross3a8c0252019-01-23 13:21:48 -08003654 err = c.writeBuildDir(nw)
3655 if err != nil {
3656 return
3657 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003658
Colin Cross3a8c0252019-01-23 13:21:48 -08003659 err = c.writeGlobalRules(nw)
3660 if err != nil {
3661 return
3662 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003663
Colin Cross3a8c0252019-01-23 13:21:48 -08003664 err = c.writeAllModuleActions(nw)
3665 if err != nil {
3666 return
3667 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003668
Colin Cross3a8c0252019-01-23 13:21:48 -08003669 err = c.writeAllSingletonActions(nw)
3670 if err != nil {
3671 return
3672 }
3673 })
3674
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003675 if err != nil {
3676 return err
3677 }
3678
3679 return nil
3680}
3681
Jamie Gennisc15544d2014-09-24 20:26:52 -07003682type pkgAssociation struct {
3683 PkgName string
3684 PkgPath string
3685}
3686
3687type pkgAssociationSorter struct {
3688 pkgs []pkgAssociation
3689}
3690
3691func (s *pkgAssociationSorter) Len() int {
3692 return len(s.pkgs)
3693}
3694
3695func (s *pkgAssociationSorter) Less(i, j int) bool {
3696 iName := s.pkgs[i].PkgName
3697 jName := s.pkgs[j].PkgName
3698 return iName < jName
3699}
3700
3701func (s *pkgAssociationSorter) Swap(i, j int) {
3702 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3703}
3704
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003705func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3706 headerTemplate := template.New("fileHeader")
3707 _, err := headerTemplate.Parse(fileHeaderTemplate)
3708 if err != nil {
3709 // This is a programming error.
3710 panic(err)
3711 }
3712
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003713 var pkgs []pkgAssociation
3714 maxNameLen := 0
3715 for pkg, name := range c.pkgNames {
3716 pkgs = append(pkgs, pkgAssociation{
3717 PkgName: name,
3718 PkgPath: pkg.pkgPath,
3719 })
3720 if len(name) > maxNameLen {
3721 maxNameLen = len(name)
3722 }
3723 }
3724
3725 for i := range pkgs {
3726 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3727 }
3728
Jamie Gennisc15544d2014-09-24 20:26:52 -07003729 sort.Sort(&pkgAssociationSorter{pkgs})
3730
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003731 params := map[string]interface{}{
3732 "Pkgs": pkgs,
3733 }
3734
3735 buf := bytes.NewBuffer(nil)
3736 err = headerTemplate.Execute(buf, params)
3737 if err != nil {
3738 return err
3739 }
3740
3741 return nw.Comment(buf.String())
3742}
3743
3744func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3745 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3746 c.requiredNinjaMicro)
3747
3748 err := nw.Assign("ninja_required_version", value)
3749 if err != nil {
3750 return err
3751 }
3752
3753 return nw.BlankLine()
3754}
3755
Dan Willemsenab223a52018-07-05 21:56:59 -07003756func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3757 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003758 err := nw.Subninja(subninja)
3759 if err != nil {
3760 return err
3761 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003762 }
3763 return nw.BlankLine()
3764}
3765
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003766func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003767 if c.outDir != nil {
3768 err := nw.Assign("builddir", c.outDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003769 if err != nil {
3770 return err
3771 }
3772
3773 err = nw.BlankLine()
3774 if err != nil {
3775 return err
3776 }
3777 }
3778 return nil
3779}
3780
Jamie Gennisc15544d2014-09-24 20:26:52 -07003781type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003782 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003783}
3784
Jamie Gennisc15544d2014-09-24 20:26:52 -07003785type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003786 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003787 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003788}
3789
Jamie Gennisc15544d2014-09-24 20:26:52 -07003790func (s *globalEntitySorter) Len() int {
3791 return len(s.entities)
3792}
3793
3794func (s *globalEntitySorter) Less(i, j int) bool {
3795 iName := s.entities[i].fullName(s.pkgNames)
3796 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003797 return iName < jName
3798}
3799
Jamie Gennisc15544d2014-09-24 20:26:52 -07003800func (s *globalEntitySorter) Swap(i, j int) {
3801 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003802}
3803
3804func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3805 visited := make(map[Variable]bool)
3806
3807 var walk func(v Variable) error
3808 walk = func(v Variable) error {
3809 visited[v] = true
3810
3811 // First visit variables on which this variable depends.
3812 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003813 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003814 if !visited[dep] {
3815 err := walk(dep)
3816 if err != nil {
3817 return err
3818 }
3819 }
3820 }
3821
3822 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3823 if err != nil {
3824 return err
3825 }
3826
3827 err = nw.BlankLine()
3828 if err != nil {
3829 return err
3830 }
3831
3832 return nil
3833 }
3834
Jamie Gennisc15544d2014-09-24 20:26:52 -07003835 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3836 for variable := range c.globalVariables {
3837 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003838 }
3839
Jamie Gennisc15544d2014-09-24 20:26:52 -07003840 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003841
Jamie Gennisc15544d2014-09-24 20:26:52 -07003842 for _, entity := range globalVariables {
3843 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003844 if !visited[v] {
3845 err := walk(v)
3846 if err != nil {
3847 return nil
3848 }
3849 }
3850 }
3851
3852 return nil
3853}
3854
3855func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003856 globalPools := make([]globalEntity, 0, len(c.globalPools))
3857 for pool := range c.globalPools {
3858 globalPools = append(globalPools, pool)
3859 }
3860
3861 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3862
3863 for _, entity := range globalPools {
3864 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003865 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003866 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003867 err := def.WriteTo(nw, name)
3868 if err != nil {
3869 return err
3870 }
3871
3872 err = nw.BlankLine()
3873 if err != nil {
3874 return err
3875 }
3876 }
3877
3878 return nil
3879}
3880
3881func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003882 globalRules := make([]globalEntity, 0, len(c.globalRules))
3883 for rule := range c.globalRules {
3884 globalRules = append(globalRules, rule)
3885 }
3886
3887 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3888
3889 for _, entity := range globalRules {
3890 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003891 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003892 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003893 err := def.WriteTo(nw, name, c.pkgNames)
3894 if err != nil {
3895 return err
3896 }
3897
3898 err = nw.BlankLine()
3899 if err != nil {
3900 return err
3901 }
3902 }
3903
3904 return nil
3905}
3906
Colin Cross2c1f3d12016-04-11 15:47:28 -07003907type depSorter []depInfo
3908
3909func (s depSorter) Len() int {
3910 return len(s)
3911}
3912
3913func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003914 iName := s[i].module.Name()
3915 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003916 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003917 iName = s[i].module.variant.name
3918 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003919 }
3920 return iName < jName
3921}
3922
3923func (s depSorter) Swap(i, j int) {
3924 s[i], s[j] = s[j], s[i]
3925}
3926
Jeff Gaston0e907592017-12-01 17:10:52 -08003927type moduleSorter struct {
3928 modules []*moduleInfo
3929 nameInterface NameInterface
3930}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003931
Colin Crossab6d7902015-03-11 16:17:52 -07003932func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003933 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003934}
3935
Colin Crossab6d7902015-03-11 16:17:52 -07003936func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003937 iMod := s.modules[i]
3938 jMod := s.modules[j]
3939 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3940 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003941 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003942 iVariantName := s.modules[i].variant.name
3943 jVariantName := s.modules[j].variant.name
3944 if iVariantName == jVariantName {
3945 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3946 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3947 } else {
3948 return iVariantName < jVariantName
3949 }
3950 } else {
3951 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003952 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003953}
3954
Colin Crossab6d7902015-03-11 16:17:52 -07003955func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003956 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003957}
3958
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003959func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3960 headerTemplate := template.New("moduleHeader")
3961 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3962 if err != nil {
3963 // This is a programming error.
3964 panic(err)
3965 }
3966
Colin Crossab6d7902015-03-11 16:17:52 -07003967 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3968 for _, module := range c.moduleInfo {
3969 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003970 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003971 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003972
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003973 buf := bytes.NewBuffer(nil)
3974
Colin Crossab6d7902015-03-11 16:17:52 -07003975 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003976 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3977 continue
3978 }
3979
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003980 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003981
3982 // In order to make the bootstrap build manifest independent of the
3983 // build dir we need to output the Blueprints file locations in the
3984 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003985 relPos := module.pos
3986 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003987
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003988 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003989 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003990 factoryName := factoryFunc.Name()
3991
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003992 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003993 "name": module.Name(),
3994 "typeName": module.typeName,
3995 "goFactory": factoryName,
3996 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07003997 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003998 }
3999 err = headerTemplate.Execute(buf, infoMap)
4000 if err != nil {
4001 return err
4002 }
4003
4004 err = nw.Comment(buf.String())
4005 if err != nil {
4006 return err
4007 }
4008
4009 err = nw.BlankLine()
4010 if err != nil {
4011 return err
4012 }
4013
Colin Crossab6d7902015-03-11 16:17:52 -07004014 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004015 if err != nil {
4016 return err
4017 }
4018
4019 err = nw.BlankLine()
4020 if err != nil {
4021 return err
4022 }
4023 }
4024
4025 return nil
4026}
4027
4028func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
4029 headerTemplate := template.New("singletonHeader")
4030 _, err := headerTemplate.Parse(singletonHeaderTemplate)
4031 if err != nil {
4032 // This is a programming error.
4033 panic(err)
4034 }
4035
4036 buf := bytes.NewBuffer(nil)
4037
Yuchen Wub9103ef2015-08-25 17:58:17 -07004038 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004039 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4040 continue
4041 }
4042
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004043 // Get the name of the factory function for the module.
4044 factory := info.factory
4045 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4046 factoryName := factoryFunc.Name()
4047
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004048 buf.Reset()
4049 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004050 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004051 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004052 }
4053 err = headerTemplate.Execute(buf, infoMap)
4054 if err != nil {
4055 return err
4056 }
4057
4058 err = nw.Comment(buf.String())
4059 if err != nil {
4060 return err
4061 }
4062
4063 err = nw.BlankLine()
4064 if err != nil {
4065 return err
4066 }
4067
4068 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4069 if err != nil {
4070 return err
4071 }
4072
4073 err = nw.BlankLine()
4074 if err != nil {
4075 return err
4076 }
4077 }
4078
4079 return nil
4080}
4081
4082func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4083 defs *localBuildActions) error {
4084
4085 // Write the local variable assignments.
4086 for _, v := range defs.variables {
4087 // A localVariable doesn't need the package names or config to
4088 // determine its name or value.
4089 name := v.fullName(nil)
4090 value, err := v.value(nil)
4091 if err != nil {
4092 panic(err)
4093 }
4094 err = nw.Assign(name, value.Value(c.pkgNames))
4095 if err != nil {
4096 return err
4097 }
4098 }
4099
4100 if len(defs.variables) > 0 {
4101 err := nw.BlankLine()
4102 if err != nil {
4103 return err
4104 }
4105 }
4106
4107 // Write the local rules.
4108 for _, r := range defs.rules {
4109 // A localRule doesn't need the package names or config to determine
4110 // its name or definition.
4111 name := r.fullName(nil)
4112 def, err := r.def(nil)
4113 if err != nil {
4114 panic(err)
4115 }
4116
4117 err = def.WriteTo(nw, name, c.pkgNames)
4118 if err != nil {
4119 return err
4120 }
4121
4122 err = nw.BlankLine()
4123 if err != nil {
4124 return err
4125 }
4126 }
4127
4128 // Write the build definitions.
4129 for _, buildDef := range defs.buildDefs {
4130 err := buildDef.WriteTo(nw, c.pkgNames)
4131 if err != nil {
4132 return err
4133 }
4134
4135 if len(buildDef.Args) > 0 {
4136 err = nw.BlankLine()
4137 if err != nil {
4138 return err
4139 }
4140 }
4141 }
4142
4143 return nil
4144}
4145
Colin Cross5df74a82020-08-24 16:18:21 -07004146func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004147 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004148 if a == b {
4149 return false
4150 }
Colin Cross65569e42015-03-10 20:08:19 -07004151 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004152 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004153 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004154 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004155 return found
4156 }
4157 }
4158
4159 missing := a
4160 if found {
4161 missing = b
4162 }
4163 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4164}
4165
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004166type panicError struct {
4167 panic interface{}
4168 stack []byte
4169 in string
4170}
4171
4172func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4173 buf := make([]byte, 4096)
4174 count := runtime.Stack(buf, false)
4175 return panicError{
4176 panic: panic,
4177 in: fmt.Sprintf(in, a...),
4178 stack: buf[:count],
4179 }
4180}
4181
4182func (p panicError) Error() string {
4183 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4184}
4185
4186func (p *panicError) addIn(in string) {
4187 p.in += " in " + in
4188}
4189
4190func funcName(f interface{}) string {
4191 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4192}
4193
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004194var fileHeaderTemplate = `******************************************************************************
4195*** This file is generated and should not be edited ***
4196******************************************************************************
4197{{if .Pkgs}}
4198This file contains variables, rules, and pools with name prefixes indicating
4199they were generated by the following Go packages:
4200{{range .Pkgs}}
4201 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4202
4203`
4204
4205var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004206Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004207Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004208Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004209Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004210Defined: {{.pos}}
4211`
4212
4213var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4214Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004215Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004216`