blob: 92c5d3075b6f754671d3368112d9c3dda4bec863 [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
489// generate build actions. Each registered singleton type is instantiated and
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
1446 module := &moduleInfo{
1447 logicModule: logicModule,
1448 factory: factory,
1449 }
1450
1451 module.properties = properties
1452
1453 return module
1454}
1455
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001456func processModuleDef(moduleDef *parser.Module,
1457 relBlueprintsFile string, moduleFactories, scopedModuleFactories map[string]ModuleFactory, ignoreUnknownModuleTypes bool) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001458
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001459 factory, ok := moduleFactories[moduleDef.Type]
Colin Cross9672d862019-12-30 18:38:20 -08001460 if !ok && scopedModuleFactories != nil {
1461 factory, ok = scopedModuleFactories[moduleDef.Type]
1462 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001463 if !ok {
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001464 if ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001465 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001466 }
1467
Colin Cross7ad621c2015-01-07 16:22:45 -08001468 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001469 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001470 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1471 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001472 },
1473 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001474 }
1475
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001476 module := newModule(factory)
Colin Crossaf4fd212017-07-28 14:32:36 -07001477 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001478
Colin Crossaf4fd212017-07-28 14:32:36 -07001479 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001480
Colin Crossf27c5e42020-01-02 09:37:49 -08001481 propertyMap, errs := proptools.UnpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001482 if len(errs) > 0 {
Colin Crossf27c5e42020-01-02 09:37:49 -08001483 for i, err := range errs {
1484 if unpackErr, ok := err.(*proptools.UnpackError); ok {
1485 err = &BlueprintError{
1486 Err: unpackErr.Err,
1487 Pos: unpackErr.Pos,
1488 }
1489 errs[i] = err
1490 }
1491 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001492 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001493 }
1494
Colin Crossc32c4792016-06-09 15:52:30 -07001495 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001496 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001497 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001498 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001499 }
1500
Colin Cross7ad621c2015-01-07 16:22:45 -08001501 return module, nil
1502}
1503
Colin Cross23d7aa12015-06-30 16:05:22 -07001504func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001505 name := module.logicModule.Name()
Jaewoong Jungccc34942018-10-11 13:01:05 -07001506 if name == "" {
1507 return []error{
1508 &BlueprintError{
1509 Err: fmt.Errorf("property 'name' is missing from a module"),
1510 Pos: module.pos,
1511 },
1512 }
1513 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001514 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001515
Colin Cross0b7e83e2016-05-17 14:58:05 -07001516 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001517 name: name,
Colin Cross5df74a82020-08-24 16:18:21 -07001518 modules: modulesOrAliases{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001519 }
1520 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001521 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001522 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001523 ModuleGroup{moduleGroup: group},
1524 module.logicModule)
1525 if len(errs) > 0 {
1526 for i := range errs {
1527 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1528 }
1529 return errs
1530 }
1531 group.namespace = namespace
1532
Colin Cross0b7e83e2016-05-17 14:58:05 -07001533 c.moduleGroups = append(c.moduleGroups, group)
1534
Colin Cross23d7aa12015-06-30 16:05:22 -07001535 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001536}
1537
Jamie Gennisd4e10182014-06-12 20:06:50 -07001538// ResolveDependencies checks that the dependencies specified by all of the
1539// modules defined in the parsed Blueprints files are valid. This means that
1540// the modules depended upon are defined and that no circular dependencies
1541// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001542func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08001543 return c.resolveDependencies(c.Context, config)
1544}
Colin Cross5f03f112017-11-07 13:29:54 -08001545
Colin Cross3a8c0252019-01-23 13:21:48 -08001546func (c *Context) resolveDependencies(ctx context.Context, config interface{}) (deps []string, errs []error) {
1547 pprof.Do(ctx, pprof.Labels("blueprint", "ResolveDependencies"), func(ctx context.Context) {
Colin Cross2da84922020-07-02 10:08:12 -07001548 c.initProviders()
1549
Colin Cross3a8c0252019-01-23 13:21:48 -08001550 c.liveGlobals = newLiveTracker(config)
1551
1552 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1553 if len(errs) > 0 {
1554 return
1555 }
1556
1557 errs = c.updateDependencies()
1558 if len(errs) > 0 {
1559 return
1560 }
1561
1562 var mutatorDeps []string
1563 mutatorDeps, errs = c.runMutators(ctx, config)
1564 if len(errs) > 0 {
1565 return
1566 }
1567 deps = append(deps, mutatorDeps...)
1568
Colin Cross2da84922020-07-02 10:08:12 -07001569 if !c.skipCloneModulesAfterMutators {
1570 c.cloneModules()
1571 }
Colin Cross3a8c0252019-01-23 13:21:48 -08001572
1573 c.dependenciesReady = true
1574 })
1575
Colin Cross5f03f112017-11-07 13:29:54 -08001576 if len(errs) > 0 {
1577 return nil, errs
1578 }
1579
Colin Cross874a3462017-07-31 17:26:06 -07001580 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001581}
1582
Colin Cross763b6f12015-10-29 15:32:56 -07001583// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001584// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001585// module names returned by its DynamicDependencies method and those added by calling
1586// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001587func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001588 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001589 func() {
1590 defer func() {
1591 if r := recover(); r != nil {
1592 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1593 }
1594 }()
1595 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001596
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001597 if ctx.Failed() {
1598 return
1599 }
Colin Cross763b6f12015-10-29 15:32:56 -07001600
Colin Cross2c1f3d12016-04-11 15:47:28 -07001601 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001602 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001603 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001604}
1605
Colin Cross39644c02020-08-21 18:20:38 -07001606// findExactVariantOrSingle searches the moduleGroup for a module with the same variant as module,
1607// and returns the matching module, or nil if one is not found. A group with exactly one module
1608// is always considered matching.
1609func findExactVariantOrSingle(module *moduleInfo, possible *moduleGroup, reverse bool) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07001610 found, _ := findVariant(module, possible, nil, false, reverse)
1611 if found == nil {
1612 for _, moduleOrAlias := range possible.modules {
1613 if m := moduleOrAlias.module(); m != nil {
1614 if found != nil {
1615 // more than one possible match, give up
1616 return nil
1617 }
1618 found = m
1619 }
1620 }
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001621 }
Colin Cross5df74a82020-08-24 16:18:21 -07001622 return found
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001623}
1624
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001625func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) (*moduleInfo, []error) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001626 if _, ok := tag.(BaseDependencyTag); ok {
1627 panic("BaseDependencyTag is not allowed to be used directly!")
1628 }
1629
Colin Cross0b7e83e2016-05-17 14:58:05 -07001630 if depName == module.Name() {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001631 return nil, []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001632 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001633 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001634 }}
1635 }
1636
Colin Crossd03b59d2019-11-13 20:10:12 -08001637 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001638 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001639 return nil, c.discoveredMissingDependencies(module, depName, nil)
Colin Crossc9028482014-12-18 16:28:54 -08001640 }
1641
Colin Cross39644c02020-08-21 18:20:38 -07001642 if m := findExactVariantOrSingle(module, possibleDeps, false); m != nil {
Colin Cross99bdb2a2019-03-29 16:35:02 -07001643 module.newDirectDeps = append(module.newDirectDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001644 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001645 return m, nil
Colin Cross65569e42015-03-10 20:08:19 -07001646 }
Colin Crossc9028482014-12-18 16:28:54 -08001647
Paul Duffinb77556b2020-03-24 19:01:20 +00001648 if c.allowMissingDependencies {
1649 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001650 return nil, c.discoveredMissingDependencies(module, depName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001651 }
1652
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001653 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001654 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001655 depName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001656 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001657 c.prettyPrintGroupVariants(possibleDeps)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001658 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001659 }}
1660}
1661
Colin Cross8d8a7af2015-11-03 16:41:29 -08001662func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001663 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001664 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001665 Err: fmt.Errorf("%q depends on itself", destName),
1666 Pos: module.pos,
1667 }}
1668 }
1669
Colin Crossd03b59d2019-11-13 20:10:12 -08001670 possibleDeps := c.moduleGroupFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001671 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001672 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001673 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001674 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001675 Pos: module.pos,
1676 }}
1677 }
1678
Colin Cross39644c02020-08-21 18:20:38 -07001679 if m := findExactVariantOrSingle(module, possibleDeps, true); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001680 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001681 }
1682
Paul Duffinb77556b2020-03-24 19:01:20 +00001683 if c.allowMissingDependencies {
1684 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001685 return module, c.discoveredMissingDependencies(module, destName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001686 }
1687
Colin Cross2c628442016-10-07 17:13:10 -07001688 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001689 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001690 destName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001691 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001692 c.prettyPrintGroupVariants(possibleDeps)),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001693 Pos: module.pos,
1694 }}
1695}
1696
Colin Cross39644c02020-08-21 18:20:38 -07001697func findVariant(module *moduleInfo, possibleDeps *moduleGroup, variations []Variation, far bool, reverse bool) (*moduleInfo, variationMap) {
Colin Crossedc41762020-08-13 12:07:30 -07001698 // We can't just append variant.Variant to module.dependencyVariant.variantName and
Colin Cross65569e42015-03-10 20:08:19 -07001699 // compare the strings because the result won't be in mutator registration order.
1700 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001701 var newVariant variationMap
1702 if !far {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001703 if !reverse {
1704 // For forward dependency, ignore local variants by matching against
1705 // dependencyVariant which doesn't have the local variants
Colin Crossedc41762020-08-13 12:07:30 -07001706 newVariant = module.variant.dependencyVariations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001707 } else {
1708 // For reverse dependency, use all the variants
Colin Crossedc41762020-08-13 12:07:30 -07001709 newVariant = module.variant.variations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001710 }
Colin Cross89486232015-05-08 11:14:54 -07001711 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001712 for _, v := range variations {
Colin Cross9403b5a2019-11-13 20:11:04 -08001713 if newVariant == nil {
1714 newVariant = make(variationMap)
1715 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001716 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001717 }
1718
Colin Crossd03b59d2019-11-13 20:10:12 -08001719 check := func(variant variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -07001720 if far {
Colin Cross5dc67592020-08-24 14:46:13 -07001721 return newVariant.subsetOf(variant)
Colin Cross89486232015-05-08 11:14:54 -07001722 } else {
Colin Crossd03b59d2019-11-13 20:10:12 -08001723 return variant.equal(newVariant)
Colin Cross65569e42015-03-10 20:08:19 -07001724 }
1725 }
1726
Colin Crossd03b59d2019-11-13 20:10:12 -08001727 var foundDep *moduleInfo
1728 for _, m := range possibleDeps.modules {
Colin Cross5df74a82020-08-24 16:18:21 -07001729 if check(m.moduleOrAliasVariant().variations) {
1730 foundDep = m.moduleOrAliasTarget()
Colin Crossd03b59d2019-11-13 20:10:12 -08001731 break
1732 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001733 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001734
Martin Stjernholm2f212472020-03-06 00:29:24 +00001735 return foundDep, newVariant
1736}
1737
1738func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001739 tag DependencyTag, depName string, far bool) (*moduleInfo, []error) {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001740 if _, ok := tag.(BaseDependencyTag); ok {
1741 panic("BaseDependencyTag is not allowed to be used directly!")
1742 }
1743
1744 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
1745 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001746 return nil, c.discoveredMissingDependencies(module, depName, nil)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001747 }
1748
Colin Cross5df74a82020-08-24 16:18:21 -07001749 foundDep, newVariant := findVariant(module, possibleDeps, variations, far, false)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001750
Colin Crossf7beb892019-11-13 20:11:14 -08001751 if foundDep == nil {
Paul Duffinb77556b2020-03-24 19:01:20 +00001752 if c.allowMissingDependencies {
1753 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001754 return nil, c.discoveredMissingDependencies(module, depName, newVariant)
Paul Duffinb77556b2020-03-24 19:01:20 +00001755 }
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001756 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001757 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
1758 depName, module.Name(),
1759 c.prettyPrintVariant(newVariant),
1760 c.prettyPrintGroupVariants(possibleDeps)),
1761 Pos: module.pos,
1762 }}
1763 }
1764
1765 if module == foundDep {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001766 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001767 Err: fmt.Errorf("%q depends on itself", depName),
1768 Pos: module.pos,
1769 }}
1770 }
1771 // AddVariationDependency allows adding a dependency on itself, but only if
1772 // that module is earlier in the module list than this one, since we always
1773 // run GenerateBuildActions in order for the variants of a module
1774 if foundDep.group == module.group && beforeInModuleList(module, foundDep, module.group.modules) {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001775 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001776 Err: fmt.Errorf("%q depends on later version of itself", depName),
1777 Pos: module.pos,
1778 }}
1779 }
1780 module.newDirectDeps = append(module.newDirectDeps, depInfo{foundDep, tag})
1781 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001782 return foundDep, nil
Colin Crossc9028482014-12-18 16:28:54 -08001783}
1784
Colin Crossf1875462016-04-11 17:33:13 -07001785func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001786 from, to Module) *moduleInfo {
Nan Zhang346b2d02017-03-10 16:39:27 -08001787 if _, ok := tag.(BaseDependencyTag); ok {
1788 panic("BaseDependencyTag is not allowed to be used directly!")
1789 }
Colin Crossf1875462016-04-11 17:33:13 -07001790
1791 var fromInfo, toInfo *moduleInfo
Colin Cross5df74a82020-08-24 16:18:21 -07001792 for _, moduleOrAlias := range origModule.splitModules {
1793 if m := moduleOrAlias.module(); m != nil {
1794 if m.logicModule == from {
1795 fromInfo = m
1796 }
1797 if m.logicModule == to {
1798 toInfo = m
1799 if fromInfo != nil {
1800 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
1801 }
Colin Crossf1875462016-04-11 17:33:13 -07001802 }
1803 }
1804 }
1805
1806 if fromInfo == nil || toInfo == nil {
1807 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001808 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001809 }
1810
Colin Cross99bdb2a2019-03-29 16:35:02 -07001811 fromInfo.newDirectDeps = append(fromInfo.newDirectDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001812 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001813 return toInfo
Colin Crossf1875462016-04-11 17:33:13 -07001814}
1815
Lukacs T. Berkieef56852021-09-02 11:34:06 +02001816// findBlueprintDescendants returns a map linking parent Blueprint files to child Blueprints files
1817// For example, if paths = []string{"a/b/c/Android.bp", "a/Android.bp"},
1818// then descendants = {"":[]string{"a/Android.bp"}, "a/Android.bp":[]string{"a/b/c/Android.bp"}}
Jeff Gastonc3e28442017-08-09 15:13:12 -07001819func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1820 // make mapping from dir path to file path
1821 filesByDir := make(map[string]string, len(paths))
1822 for _, path := range paths {
1823 dir := filepath.Dir(path)
1824 _, alreadyFound := filesByDir[dir]
1825 if alreadyFound {
1826 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1827 }
1828 filesByDir[dir] = path
1829 }
1830
Jeff Gaston656870f2017-11-29 18:37:31 -08001831 findAncestor := func(childFile string) (ancestor string) {
1832 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001833 for {
1834 ancestorDir := filepath.Dir(prevAncestorDir)
1835 if ancestorDir == prevAncestorDir {
1836 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001837 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001838 }
1839
1840 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1841 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001842 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001843 }
1844 prevAncestorDir = ancestorDir
1845 }
1846 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001847 // generate the descendants map
1848 descendants = make(map[string][]string, len(filesByDir))
1849 for _, childFile := range filesByDir {
1850 ancestorFile := findAncestor(childFile)
1851 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1852 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001853 return descendants, nil
1854}
1855
Colin Cross3702ac72016-08-11 11:09:00 -07001856type visitOrderer interface {
1857 // returns the number of modules that this module needs to wait for
1858 waitCount(module *moduleInfo) int
1859 // returns the list of modules that are waiting for this module
1860 propagate(module *moduleInfo) []*moduleInfo
1861 // visit modules in order
Colin Crossc4773d92020-08-25 17:12:59 -07001862 visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool)
Colin Cross3702ac72016-08-11 11:09:00 -07001863}
1864
Colin Cross7e723372018-03-28 11:50:12 -07001865type unorderedVisitorImpl struct{}
1866
1867func (unorderedVisitorImpl) waitCount(module *moduleInfo) int {
1868 return 0
1869}
1870
1871func (unorderedVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1872 return nil
1873}
1874
Colin Crossc4773d92020-08-25 17:12:59 -07001875func (unorderedVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross7e723372018-03-28 11:50:12 -07001876 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001877 if visit(module, nil) {
Colin Cross7e723372018-03-28 11:50:12 -07001878 return
1879 }
1880 }
1881}
1882
Colin Cross3702ac72016-08-11 11:09:00 -07001883type bottomUpVisitorImpl struct{}
1884
1885func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1886 return len(module.forwardDeps)
1887}
1888
1889func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1890 return module.reverseDeps
1891}
1892
Colin Crossc4773d92020-08-25 17:12:59 -07001893func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001894 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001895 if visit(module, nil) {
Colin Cross49c279a2016-08-05 22:30:44 -07001896 return
1897 }
1898 }
1899}
1900
Colin Cross3702ac72016-08-11 11:09:00 -07001901type topDownVisitorImpl struct{}
1902
1903func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1904 return len(module.reverseDeps)
1905}
1906
1907func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1908 return module.forwardDeps
1909}
1910
Colin Crossc4773d92020-08-25 17:12:59 -07001911func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001912 for i := 0; i < len(modules); i++ {
1913 module := modules[len(modules)-1-i]
Colin Crossc4773d92020-08-25 17:12:59 -07001914 if visit(module, nil) {
Colin Cross3702ac72016-08-11 11:09:00 -07001915 return
1916 }
1917 }
1918}
1919
1920var (
1921 bottomUpVisitor bottomUpVisitorImpl
1922 topDownVisitor topDownVisitorImpl
1923)
1924
Colin Crossc4773d92020-08-25 17:12:59 -07001925// pauseSpec describes a pause that a module needs to occur until another module has been visited,
1926// at which point the unpause channel will be closed.
1927type pauseSpec struct {
1928 paused *moduleInfo
1929 until *moduleInfo
1930 unpause unpause
1931}
1932
1933type unpause chan struct{}
1934
1935const parallelVisitLimit = 1000
1936
Colin Cross49c279a2016-08-05 22:30:44 -07001937// 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 -07001938// of its dependencies has finished. A visit function can write a pauseSpec to the pause channel
1939// to wait for another dependency to be visited. If a visit function returns true to cancel
1940// while another visitor is paused, the paused visitor will never be resumed and its goroutine
1941// will stay paused forever.
1942func parallelVisit(modules []*moduleInfo, order visitOrderer, limit int,
1943 visit func(module *moduleInfo, pause chan<- pauseSpec) bool) []error {
1944
Colin Cross7addea32015-03-11 15:43:52 -07001945 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001946 cancelCh := make(chan bool)
Colin Crossc4773d92020-08-25 17:12:59 -07001947 pauseCh := make(chan pauseSpec)
Colin Cross8900e9b2015-03-02 14:03:01 -08001948 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001949
Colin Crossc4773d92020-08-25 17:12:59 -07001950 var backlog []*moduleInfo // Visitors that are ready to start but backlogged due to limit.
1951 var unpauseBacklog []pauseSpec // Visitors that are ready to unpause but backlogged due to limit.
1952
1953 active := 0 // Number of visitors running, not counting paused visitors.
1954 visited := 0 // Number of finished visitors.
1955
1956 pauseMap := make(map[*moduleInfo][]pauseSpec)
1957
1958 for _, module := range modules {
Colin Cross3702ac72016-08-11 11:09:00 -07001959 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001960 }
1961
Colin Crossc4773d92020-08-25 17:12:59 -07001962 // Call the visitor on a module if there are fewer active visitors than the parallelism
1963 // limit, otherwise add it to the backlog.
1964 startOrBacklog := func(module *moduleInfo) {
1965 if active < limit {
1966 active++
Colin Cross7e723372018-03-28 11:50:12 -07001967 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07001968 ret := visit(module, pauseCh)
Colin Cross7e723372018-03-28 11:50:12 -07001969 if ret {
1970 cancelCh <- true
1971 }
1972 doneCh <- module
1973 }()
1974 } else {
1975 backlog = append(backlog, module)
1976 }
Colin Cross691a60d2015-01-07 18:08:56 -08001977 }
1978
Colin Crossc4773d92020-08-25 17:12:59 -07001979 // Unpause the already-started but paused visitor on a module if there are fewer active
1980 // visitors than the parallelism limit, otherwise add it to the backlog.
1981 unpauseOrBacklog := func(pauseSpec pauseSpec) {
1982 if active < limit {
1983 active++
1984 close(pauseSpec.unpause)
1985 } else {
1986 unpauseBacklog = append(unpauseBacklog, pauseSpec)
Colin Cross691a60d2015-01-07 18:08:56 -08001987 }
1988 }
1989
Colin Crossc4773d92020-08-25 17:12:59 -07001990 // Start any modules in the backlog up to the parallelism limit. Unpause paused modules first
1991 // since they may already be holding resources.
1992 unpauseOrStartFromBacklog := func() {
1993 for active < limit && len(unpauseBacklog) > 0 {
1994 unpause := unpauseBacklog[0]
1995 unpauseBacklog = unpauseBacklog[1:]
1996 unpauseOrBacklog(unpause)
1997 }
1998 for active < limit && len(backlog) > 0 {
1999 toVisit := backlog[0]
2000 backlog = backlog[1:]
2001 startOrBacklog(toVisit)
2002 }
2003 }
2004
2005 toVisit := len(modules)
2006
2007 // Start or backlog any modules that are not waiting for any other modules.
2008 for _, module := range modules {
2009 if module.waitingCount == 0 {
2010 startOrBacklog(module)
2011 }
2012 }
2013
2014 for active > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08002015 select {
Colin Cross7e723372018-03-28 11:50:12 -07002016 case <-cancelCh:
2017 cancel = true
2018 backlog = nil
Colin Cross7addea32015-03-11 15:43:52 -07002019 case doneModule := <-doneCh:
Colin Crossc4773d92020-08-25 17:12:59 -07002020 active--
Colin Cross8900e9b2015-03-02 14:03:01 -08002021 if !cancel {
Colin Crossc4773d92020-08-25 17:12:59 -07002022 // Mark this module as done.
2023 doneModule.waitingCount = -1
2024 visited++
2025
2026 // Unpause or backlog any modules that were waiting for this one.
2027 if unpauses, ok := pauseMap[doneModule]; ok {
2028 delete(pauseMap, doneModule)
2029 for _, unpause := range unpauses {
2030 unpauseOrBacklog(unpause)
2031 }
Colin Cross7e723372018-03-28 11:50:12 -07002032 }
Colin Crossc4773d92020-08-25 17:12:59 -07002033
2034 // Start any backlogged modules up to limit.
2035 unpauseOrStartFromBacklog()
2036
2037 // Decrement waitingCount on the next modules in the tree based
2038 // on propagation order, and start or backlog them if they are
2039 // ready to start.
Colin Cross3702ac72016-08-11 11:09:00 -07002040 for _, module := range order.propagate(doneModule) {
2041 module.waitingCount--
2042 if module.waitingCount == 0 {
Colin Crossc4773d92020-08-25 17:12:59 -07002043 startOrBacklog(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08002044 }
Colin Cross691a60d2015-01-07 18:08:56 -08002045 }
2046 }
Colin Crossc4773d92020-08-25 17:12:59 -07002047 case pauseSpec := <-pauseCh:
2048 if pauseSpec.until.waitingCount == -1 {
2049 // Module being paused for is already finished, resume immediately.
2050 close(pauseSpec.unpause)
2051 } else {
2052 // Register for unpausing.
2053 pauseMap[pauseSpec.until] = append(pauseMap[pauseSpec.until], pauseSpec)
2054
2055 // Don't count paused visitors as active so that this can't deadlock
2056 // if 1000 visitors are paused simultaneously.
2057 active--
2058 unpauseOrStartFromBacklog()
2059 }
Colin Cross691a60d2015-01-07 18:08:56 -08002060 }
2061 }
Colin Crossc4773d92020-08-25 17:12:59 -07002062
2063 if !cancel {
2064 // Invariant check: no backlogged modules, these weren't waiting on anything except
2065 // the parallelism limit so they should have run.
2066 if len(backlog) > 0 {
2067 panic(fmt.Errorf("parallelVisit finished with %d backlogged visitors", len(backlog)))
2068 }
2069
2070 // Invariant check: no backlogged paused modules, these weren't waiting on anything
2071 // except the parallelism limit so they should have run.
2072 if len(unpauseBacklog) > 0 {
2073 panic(fmt.Errorf("parallelVisit finished with %d backlogged unpaused visitors", len(unpauseBacklog)))
2074 }
2075
2076 if len(pauseMap) > 0 {
Colin Cross7d4958d2021-02-08 15:34:08 -08002077 // Probably a deadlock due to a newly added dependency cycle. Start from each module in
2078 // the order of the input modules list and perform a depth-first search for the module
2079 // it is paused on, ignoring modules that are marked as done. Note this traverses from
2080 // modules to the modules that would have been unblocked when that module finished, i.e
2081 // the reverse of the visitOrderer.
Colin Crossc4773d92020-08-25 17:12:59 -07002082
Colin Cross9793b0a2021-04-27 15:20:15 -07002083 // In order to reduce duplicated work, once a module has been checked and determined
2084 // not to be part of a cycle add it and everything that depends on it to the checked
2085 // map.
2086 checked := make(map[*moduleInfo]struct{})
2087
Colin Cross7d4958d2021-02-08 15:34:08 -08002088 var check func(module, end *moduleInfo) []*moduleInfo
2089 check = func(module, end *moduleInfo) []*moduleInfo {
Colin Crossc4773d92020-08-25 17:12:59 -07002090 if module.waitingCount == -1 {
2091 // This module was finished, it can't be part of a loop.
2092 return nil
2093 }
2094 if module == end {
2095 // This module is the end of the loop, start rolling up the cycle.
2096 return []*moduleInfo{module}
2097 }
2098
Colin Cross9793b0a2021-04-27 15:20:15 -07002099 if _, alreadyChecked := checked[module]; alreadyChecked {
2100 return nil
2101 }
2102
Colin Crossc4773d92020-08-25 17:12:59 -07002103 for _, dep := range order.propagate(module) {
Colin Cross7d4958d2021-02-08 15:34:08 -08002104 cycle := check(dep, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002105 if cycle != nil {
2106 return append([]*moduleInfo{module}, cycle...)
2107 }
2108 }
2109 for _, depPauseSpec := range pauseMap[module] {
Colin Cross7d4958d2021-02-08 15:34:08 -08002110 cycle := check(depPauseSpec.paused, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002111 if cycle != nil {
2112 return append([]*moduleInfo{module}, cycle...)
2113 }
2114 }
2115
Colin Cross9793b0a2021-04-27 15:20:15 -07002116 checked[module] = struct{}{}
Colin Crossc4773d92020-08-25 17:12:59 -07002117 return nil
2118 }
2119
Colin Cross7d4958d2021-02-08 15:34:08 -08002120 // Iterate over the modules list instead of pauseMap to provide deterministic ordering.
2121 for _, module := range modules {
2122 for _, pauseSpec := range pauseMap[module] {
2123 cycle := check(pauseSpec.paused, pauseSpec.until)
2124 if len(cycle) > 0 {
2125 return cycleError(cycle)
2126 }
2127 }
Colin Crossc4773d92020-08-25 17:12:59 -07002128 }
2129 }
2130
2131 // Invariant check: if there was no deadlock and no cancellation every module
2132 // should have been visited.
2133 if visited != toVisit {
2134 panic(fmt.Errorf("parallelVisit ran %d visitors, expected %d", visited, toVisit))
2135 }
2136
2137 // Invariant check: if there was no deadlock and no cancellation every module
2138 // should have been visited, so there is nothing left to be paused on.
2139 if len(pauseMap) > 0 {
2140 panic(fmt.Errorf("parallelVisit finished with %d paused visitors", len(pauseMap)))
2141 }
2142 }
2143
2144 return nil
2145}
2146
2147func cycleError(cycle []*moduleInfo) (errs []error) {
2148 // The cycle list is in reverse order because all the 'check' calls append
2149 // their own module to the list.
2150 errs = append(errs, &BlueprintError{
2151 Err: fmt.Errorf("encountered dependency cycle:"),
2152 Pos: cycle[len(cycle)-1].pos,
2153 })
2154
2155 // Iterate backwards through the cycle list.
2156 curModule := cycle[0]
2157 for i := len(cycle) - 1; i >= 0; i-- {
2158 nextModule := cycle[i]
2159 errs = append(errs, &BlueprintError{
Colin Crosse5ff7702021-04-27 15:33:49 -07002160 Err: fmt.Errorf(" %s depends on %s",
2161 curModule, nextModule),
Colin Crossc4773d92020-08-25 17:12:59 -07002162 Pos: curModule.pos,
2163 })
2164 curModule = nextModule
2165 }
2166
2167 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002168}
2169
2170// updateDependencies recursively walks the module dependency graph and updates
2171// additional fields based on the dependencies. It builds a sorted list of modules
2172// such that dependencies of a module always appear first, and populates reverse
2173// dependency links and counts of total dependencies. It also reports errors when
2174// it encounters dependency cycles. This should called after resolveDependencies,
2175// as well as after any mutator pass has called addDependency
2176func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002177 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002178 visited := make(map[*moduleInfo]bool) // modules that were already checked
2179 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002180
Colin Cross7addea32015-03-11 15:43:52 -07002181 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002182
Colin Cross7addea32015-03-11 15:43:52 -07002183 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002184
Colin Cross7addea32015-03-11 15:43:52 -07002185 check = func(module *moduleInfo) []*moduleInfo {
2186 visited[module] = true
2187 checking[module] = true
2188 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002189
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002190 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2191 module.reverseDeps = module.reverseDeps[:0]
2192 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002193
2194 // Add an implicit dependency ordering on all earlier modules in the same module group
2195 for _, dep := range module.group.modules {
2196 if dep == module {
2197 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002198 }
Colin Cross5df74a82020-08-24 16:18:21 -07002199 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002200 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002201 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002202 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002203
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002204 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002205 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002206 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2207 for _, exists := range module.forwardDeps {
2208 if dep.module == exists {
2209 continue outer
2210 }
2211 }
2212 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002213 }
2214
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002215 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002216 if checking[dep] {
2217 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002218 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002219 }
2220
2221 if !visited[dep] {
2222 cycle := check(dep)
2223 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002224 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002225 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002226 // for generating the errors.
2227 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002228
2229 // We can continue processing this module's children to
2230 // find more cycles. Since all the modules that were
2231 // part of the found cycle were marked as visited we
2232 // won't run into that cycle again.
2233 } else {
2234 // We're not the "start" of the cycle, so we just append
2235 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002236 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002237 }
2238 }
2239 }
Colin Cross691a60d2015-01-07 18:08:56 -08002240
Colin Cross7addea32015-03-11 15:43:52 -07002241 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002242 }
2243
Colin Cross7addea32015-03-11 15:43:52 -07002244 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002245
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002246 return nil
2247 }
2248
Colin Cross7addea32015-03-11 15:43:52 -07002249 for _, module := range c.moduleInfo {
2250 if !visited[module] {
2251 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002252 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002253 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002254 panic("inconceivable!")
2255 }
Colin Crossc4773d92020-08-25 17:12:59 -07002256 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002257 }
2258 }
2259 }
2260
Colin Cross7addea32015-03-11 15:43:52 -07002261 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002262
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002263 return
2264}
2265
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002266type jsonVariationMap map[string]string
2267
2268type jsonModuleName struct {
2269 Name string
2270 Variations jsonVariationMap
2271 DependencyVariations jsonVariationMap
2272}
2273
2274type jsonDep struct {
2275 jsonModuleName
2276 Tag string
2277}
2278
Lukacs T. Berki16022262021-06-25 09:10:56 +02002279type JsonModule struct {
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002280 jsonModuleName
2281 Deps []jsonDep
2282 Type string
2283 Blueprint string
Lukacs T. Berki16022262021-06-25 09:10:56 +02002284 Module map[string]interface{}
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002285}
2286
2287func toJsonVariationMap(vm variationMap) jsonVariationMap {
2288 return jsonVariationMap(vm)
2289}
2290
2291func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2292 return &jsonModuleName{
2293 Name: m.Name(),
2294 Variations: toJsonVariationMap(m.variant.variations),
2295 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2296 }
2297}
2298
Lukacs T. Berki16022262021-06-25 09:10:56 +02002299type JSONDataSupplier interface {
2300 AddJSONData(d *map[string]interface{})
2301}
2302
kgui20f19a52022-01-10 12:17:32 +08002303// A JSONDataAction contains the inputs and outputs of actions of a module. Which helps pass such
2304// data to be included in the JSON module graph.
2305type JSONDataAction struct {
2306 Inputs []string
2307 Outputs []string
2308}
2309
2310// FormatJSONDataActions puts the content of a list of JSONDataActions into a standard format to be
2311// appended into the JSON module graph.
2312func FormatJSONDataActions(jsonDataActions []JSONDataAction) []map[string]interface{} {
2313 var actions []map[string]interface{}
2314 for _, jsonDataAction := range jsonDataActions {
2315 actions = append(actions, map[string]interface{}{
2316 "Inputs": jsonDataAction.Inputs,
2317 "Outputs": jsonDataAction.Outputs,
2318 })
2319 }
2320 return actions
2321}
2322
Lukacs T. Berki16022262021-06-25 09:10:56 +02002323func jsonModuleFromModuleInfo(m *moduleInfo) *JsonModule {
2324 result := &JsonModule{
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002325 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2326 Deps: make([]jsonDep, 0),
2327 Type: m.typeName,
2328 Blueprint: m.relBlueprintsFile,
Lukacs T. Berki16022262021-06-25 09:10:56 +02002329 Module: make(map[string]interface{}),
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002330 }
Lukacs T. Berki16022262021-06-25 09:10:56 +02002331
2332 if j, ok := m.logicModule.(JSONDataSupplier); ok {
2333 j.AddJSONData(&result.Module)
2334 }
2335
2336 for _, p := range m.providers {
2337 if j, ok := p.(JSONDataSupplier); ok {
2338 j.AddJSONData(&result.Module)
2339 }
2340 }
2341 return result
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002342}
2343
2344func (c *Context) PrintJSONGraph(w io.Writer) {
Lukacs T. Berki16022262021-06-25 09:10:56 +02002345 modules := make([]*JsonModule, 0)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002346 for _, m := range c.modulesSorted {
2347 jm := jsonModuleFromModuleInfo(m)
2348 for _, d := range m.directDeps {
2349 jm.Deps = append(jm.Deps, jsonDep{
2350 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2351 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2352 })
2353 }
2354
2355 modules = append(modules, jm)
2356 }
2357
Liz Kammer6e4ee8d2021-08-17 17:32:42 -04002358 e := json.NewEncoder(w)
2359 e.SetIndent("", "\t")
2360 e.Encode(modules)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002361}
2362
Jamie Gennisd4e10182014-06-12 20:06:50 -07002363// PrepareBuildActions generates an internal representation of all the build
2364// actions that need to be performed. This process involves invoking the
2365// GenerateBuildActions method on each of the Module objects created during the
2366// parse phase and then on each of the registered Singleton objects.
2367//
2368// If the ResolveDependencies method has not already been called it is called
2369// automatically by this method.
2370//
2371// The config argument is made available to all of the Module and Singleton
2372// objects via the Config method on the ModuleContext and SingletonContext
2373// objects passed to GenerateBuildActions. It is also passed to the functions
2374// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2375// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002376//
2377// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002378// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2379// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2380// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002381
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002382func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002383 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2384 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002385
Colin Cross3a8c0252019-01-23 13:21:48 -08002386 if !c.dependenciesReady {
2387 var extraDeps []string
2388 extraDeps, errs = c.resolveDependencies(ctx, config)
2389 if len(errs) > 0 {
2390 return
2391 }
2392 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002393 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002394
Colin Cross3a8c0252019-01-23 13:21:48 -08002395 var depsModules []string
2396 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2397 if len(errs) > 0 {
2398 return
2399 }
2400
2401 var depsSingletons []string
2402 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2403 if len(errs) > 0 {
2404 return
2405 }
2406
2407 deps = append(deps, depsModules...)
2408 deps = append(deps, depsSingletons...)
2409
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02002410 if c.outDir != nil {
2411 err := c.liveGlobals.addNinjaStringDeps(c.outDir)
Colin Cross3a8c0252019-01-23 13:21:48 -08002412 if err != nil {
2413 errs = []error{err}
2414 return
2415 }
2416 }
2417
2418 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2419
2420 deps = append(deps, depsPackages...)
2421
Colin Cross92054a42021-01-21 16:49:25 -08002422 c.memoizeFullNames(c.liveGlobals, pkgNames)
2423
Colin Cross3a8c0252019-01-23 13:21:48 -08002424 // This will panic if it finds a problem since it's a programming error.
2425 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2426
2427 c.pkgNames = pkgNames
2428 c.globalVariables = c.liveGlobals.variables
2429 c.globalPools = c.liveGlobals.pools
2430 c.globalRules = c.liveGlobals.rules
2431
2432 c.buildActionsReady = true
2433 })
2434
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002435 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002436 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002437 }
2438
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002439 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002440}
2441
Colin Cross3a8c0252019-01-23 13:21:48 -08002442func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002443 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002444
Colin Cross3a8c0252019-01-23 13:21:48 -08002445 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2446 mutators = append(mutators, c.earlyMutatorInfo...)
2447 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002448
Colin Cross3a8c0252019-01-23 13:21:48 -08002449 for _, mutator := range mutators {
2450 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2451 var newDeps []string
2452 if mutator.topDownMutator != nil {
2453 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2454 } else if mutator.bottomUpMutator != nil {
2455 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2456 } else {
2457 panic("no mutator set on " + mutator.name)
2458 }
2459 if len(errs) > 0 {
2460 return
2461 }
2462 deps = append(deps, newDeps...)
2463 })
2464 if len(errs) > 0 {
2465 return
2466 }
Colin Crossc9028482014-12-18 16:28:54 -08002467 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002468 })
2469
2470 if len(errs) > 0 {
2471 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002472 }
2473
Colin Cross874a3462017-07-31 17:26:06 -07002474 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002475}
2476
Colin Cross3702ac72016-08-11 11:09:00 -07002477type mutatorDirection interface {
2478 run(mutator *mutatorInfo, ctx *mutatorContext)
2479 orderer() visitOrderer
2480 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002481}
2482
Colin Cross3702ac72016-08-11 11:09:00 -07002483type bottomUpMutatorImpl struct{}
2484
2485func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2486 mutator.bottomUpMutator(ctx)
2487}
2488
2489func (bottomUpMutatorImpl) orderer() visitOrderer {
2490 return bottomUpVisitor
2491}
2492
2493func (bottomUpMutatorImpl) String() string {
2494 return "bottom up mutator"
2495}
2496
2497type topDownMutatorImpl struct{}
2498
2499func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2500 mutator.topDownMutator(ctx)
2501}
2502
2503func (topDownMutatorImpl) orderer() visitOrderer {
2504 return topDownVisitor
2505}
2506
2507func (topDownMutatorImpl) String() string {
2508 return "top down mutator"
2509}
2510
2511var (
2512 topDownMutator topDownMutatorImpl
2513 bottomUpMutator bottomUpMutatorImpl
2514)
2515
Colin Cross49c279a2016-08-05 22:30:44 -07002516type reverseDep struct {
2517 module *moduleInfo
2518 dep depInfo
2519}
2520
Colin Cross3702ac72016-08-11 11:09:00 -07002521func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002522 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002523
2524 newModuleInfo := make(map[Module]*moduleInfo)
2525 for k, v := range c.moduleInfo {
2526 newModuleInfo[k] = v
2527 }
Colin Crossc9028482014-12-18 16:28:54 -08002528
Colin Cross0ce142c2016-12-09 10:29:05 -08002529 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002530 reverse []reverseDep
2531 rename []rename
2532 replace []replace
2533 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002534 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002535 }
2536
Colin Cross2c1f3d12016-04-11 15:47:28 -07002537 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002538 var rename []rename
2539 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002540 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002541
Colin Cross49c279a2016-08-05 22:30:44 -07002542 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002543 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002544 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002545 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002546
Colin Cross3702ac72016-08-11 11:09:00 -07002547 c.depsModified = 0
2548
Colin Crossc4773d92020-08-25 17:12:59 -07002549 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002550 if module.splitModules != nil {
2551 panic("split module found in sorted module list")
2552 }
2553
Colin Cross7addea32015-03-11 15:43:52 -07002554 mctx := &mutatorContext{
2555 baseModuleContext: baseModuleContext{
2556 context: c,
2557 config: config,
2558 module: module,
2559 },
Colin Crossc4773d92020-08-25 17:12:59 -07002560 name: mutator.name,
2561 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002562 }
Colin Crossc9028482014-12-18 16:28:54 -08002563
Colin Cross2da84922020-07-02 10:08:12 -07002564 module.startedMutator = mutator
2565
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002566 func() {
2567 defer func() {
2568 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002569 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002570 if err, ok := r.(panicError); ok {
2571 err.addIn(in)
2572 mctx.error(err)
2573 } else {
2574 mctx.error(newPanicErrorf(r, in))
2575 }
2576 }
2577 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002578 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002579 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002580
Colin Cross2da84922020-07-02 10:08:12 -07002581 module.finishedMutator = mutator
2582
Colin Cross7addea32015-03-11 15:43:52 -07002583 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002584 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002585 return true
Colin Cross7addea32015-03-11 15:43:52 -07002586 }
Colin Crossc9028482014-12-18 16:28:54 -08002587
Colin Cross5fe225f2017-07-28 15:22:46 -07002588 if len(mctx.newVariations) > 0 {
2589 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002590 }
2591
Colin Crossab0a83f2020-03-03 14:23:27 -08002592 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 -08002593 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002594 reverse: mctx.reverseDeps,
2595 replace: mctx.replace,
2596 rename: mctx.rename,
2597 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002598 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002599 }
Colin Cross49c279a2016-08-05 22:30:44 -07002600 }
2601
2602 return false
2603 }
2604
2605 // Process errs and reverseDeps in a single goroutine
2606 go func() {
2607 for {
2608 select {
2609 case newErrs := <-errsCh:
2610 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002611 case globalStateChange := <-globalStateCh:
2612 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002613 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2614 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002615 replace = append(replace, globalStateChange.replace...)
2616 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002617 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002618 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002619 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002620 for _, moduleOrAlias := range newVariations {
2621 if m := moduleOrAlias.module(); m != nil {
2622 newModuleInfo[m.logicModule] = m
2623 }
Colin Cross49c279a2016-08-05 22:30:44 -07002624 }
2625 case <-done:
2626 return
Colin Crossc9028482014-12-18 16:28:54 -08002627 }
2628 }
Colin Cross49c279a2016-08-05 22:30:44 -07002629 }()
Colin Crossc9028482014-12-18 16:28:54 -08002630
Colin Cross2da84922020-07-02 10:08:12 -07002631 c.startedMutator = mutator
2632
Colin Crossc4773d92020-08-25 17:12:59 -07002633 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002634 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002635 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002636 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002637 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002638 }
2639
Colin Crossc4773d92020-08-25 17:12:59 -07002640 if len(visitErrs) > 0 {
2641 return nil, visitErrs
2642 }
2643
Colin Cross2da84922020-07-02 10:08:12 -07002644 c.finishedMutators[mutator] = true
2645
Colin Cross49c279a2016-08-05 22:30:44 -07002646 done <- true
2647
2648 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002649 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002650 }
2651
2652 c.moduleInfo = newModuleInfo
2653
2654 for _, group := range c.moduleGroups {
2655 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002656 module := group.modules[i].module()
2657 if module == nil {
2658 // Existing alias, skip it
2659 continue
2660 }
Colin Cross49c279a2016-08-05 22:30:44 -07002661
2662 // Update module group to contain newly split variants
2663 if module.splitModules != nil {
2664 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2665 }
2666
2667 // Fix up any remaining dependencies on modules that were split into variants
2668 // by replacing them with the first variant
2669 for j, dep := range module.directDeps {
2670 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002671 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002672 }
2673 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002674
Colin Cross322cc012019-05-20 13:55:14 -07002675 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002676 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002677 }
2678
Colin Cross99bdb2a2019-03-29 16:35:02 -07002679 // Add in any new direct dependencies that were added by the mutator
2680 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2681 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002682 }
Colin Crossf7beb892019-11-13 20:11:14 -08002683
Colin Cross279489c2020-08-13 12:11:52 -07002684 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002685 for _, moduleOrAlias := range group.modules {
2686 if alias := moduleOrAlias.alias(); alias != nil {
2687 if alias.variant.variations.equal(variant.variations) {
2688 return alias.target
2689 }
Colin Cross279489c2020-08-13 12:11:52 -07002690 }
2691 }
2692 return nil
2693 }
2694
Colin Crossf7beb892019-11-13 20:11:14 -08002695 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002696 // Use a manual loop instead of range because len(group.modules) can
2697 // change inside the loop
2698 for i := 0; i < len(group.modules); i++ {
2699 if alias := group.modules[i].alias(); alias != nil {
2700 if alias.target.logicModule == nil {
2701 newTarget := findAliasTarget(alias.target.variant)
2702 if newTarget != nil {
2703 alias.target = newTarget
2704 } else {
2705 // The alias was left dangling, remove it.
2706 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2707 i--
2708 }
Colin Crossf7beb892019-11-13 20:11:14 -08002709 }
2710 }
2711 }
Colin Crossc9028482014-12-18 16:28:54 -08002712 }
2713
Colin Cross99bdb2a2019-03-29 16:35:02 -07002714 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002715 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002716 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002717 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002718 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002719 }
2720
Colin Crossaf4fd212017-07-28 14:32:36 -07002721 for _, module := range newModules {
2722 errs = c.addModule(module)
2723 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002724 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002725 }
2726 atomic.AddUint32(&c.depsModified, 1)
2727 }
2728
Colin Cross0ce142c2016-12-09 10:29:05 -08002729 errs = c.handleRenames(rename)
2730 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002731 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002732 }
2733
2734 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002735 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002736 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002737 }
2738
Colin Cross3702ac72016-08-11 11:09:00 -07002739 if c.depsModified > 0 {
2740 errs = c.updateDependencies()
2741 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002742 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002743 }
Colin Crossc9028482014-12-18 16:28:54 -08002744 }
2745
Colin Cross874a3462017-07-31 17:26:06 -07002746 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002747}
2748
Colin Cross910242b2016-04-11 15:41:52 -07002749// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2750// a mutator sets a non-property member variable on a module, which works until a later mutator
2751// creates variants of that module.
2752func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002753 type update struct {
2754 orig Module
2755 clone *moduleInfo
2756 }
Colin Cross7e723372018-03-28 11:50:12 -07002757 ch := make(chan update)
2758 doneCh := make(chan bool)
2759 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002760 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2761 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2762 origLogicModule := m.logicModule
2763 m.logicModule, m.properties = c.cloneLogicModule(m)
2764 ch <- update{origLogicModule, m}
2765 return false
2766 })
2767 if len(errs) > 0 {
2768 panic(errs)
2769 }
Colin Cross7e723372018-03-28 11:50:12 -07002770 doneCh <- true
2771 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002772
Colin Cross7e723372018-03-28 11:50:12 -07002773 done := false
2774 for !done {
2775 select {
2776 case <-doneCh:
2777 done = true
2778 case update := <-ch:
2779 delete(c.moduleInfo, update.orig)
2780 c.moduleInfo[update.clone.logicModule] = update.clone
2781 }
Colin Cross910242b2016-04-11 15:41:52 -07002782 }
2783}
2784
Colin Cross49c279a2016-08-05 22:30:44 -07002785// Removes modules[i] from the list and inserts newModules... where it was located, returning
2786// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002787func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002788 spliceSize := len(newModules)
2789 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002790 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002791 if cap(modules) >= len(modules)-1+len(newModules) {
2792 // We can fit the splice in the existing capacity, do everything in place
2793 dest = modules[:newLen]
2794 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002795 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002796 copy(dest, modules[:i])
2797 }
2798
2799 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002800 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002801
2802 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002803 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002804
Colin Cross49c279a2016-08-05 22:30:44 -07002805 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002806}
2807
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002808func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002809 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002810
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002811 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002812 var errs []error
2813
Colin Cross691a60d2015-01-07 18:08:56 -08002814 cancelCh := make(chan struct{})
2815 errsCh := make(chan []error)
2816 depsCh := make(chan []string)
2817
2818 go func() {
2819 for {
2820 select {
2821 case <-cancelCh:
2822 close(cancelCh)
2823 return
2824 case newErrs := <-errsCh:
2825 errs = append(errs, newErrs...)
2826 case newDeps := <-depsCh:
2827 deps = append(deps, newDeps...)
2828
2829 }
2830 }
2831 }()
2832
Colin Crossc4773d92020-08-25 17:12:59 -07002833 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2834 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2835 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2836 sanitizedName := toNinjaName(uniqueName)
Yi Konga08e7222021-12-21 15:50:57 +08002837 sanitizedVariant := toNinjaName(module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002838
Yi Konga08e7222021-12-21 15:50:57 +08002839 prefix := moduleNamespacePrefix(sanitizedName + "_" + sanitizedVariant)
Jeff Gaston0e907592017-12-01 17:10:52 -08002840
Colin Crossc4773d92020-08-25 17:12:59 -07002841 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2842 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2843 // just set it to nil.
2844 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002845
Colin Crossc4773d92020-08-25 17:12:59 -07002846 mctx := &moduleContext{
2847 baseModuleContext: baseModuleContext{
2848 context: c,
2849 config: config,
2850 module: module,
2851 },
2852 scope: scope,
2853 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002854 }
Colin Cross036a1df2015-12-17 15:49:30 -08002855
Colin Cross2da84922020-07-02 10:08:12 -07002856 mctx.module.startedGenerateBuildActions = true
2857
Colin Crossc4773d92020-08-25 17:12:59 -07002858 func() {
2859 defer func() {
2860 if r := recover(); r != nil {
2861 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2862 if err, ok := r.(panicError); ok {
2863 err.addIn(in)
2864 mctx.error(err)
2865 } else {
2866 mctx.error(newPanicErrorf(r, in))
2867 }
2868 }
2869 }()
2870 mctx.module.logicModule.GenerateBuildActions(mctx)
2871 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002872
Colin Cross2da84922020-07-02 10:08:12 -07002873 mctx.module.finishedGenerateBuildActions = true
2874
Colin Crossc4773d92020-08-25 17:12:59 -07002875 if len(mctx.errs) > 0 {
2876 errsCh <- mctx.errs
2877 return true
2878 }
2879
2880 if module.missingDeps != nil && !mctx.handledMissingDeps {
2881 var errs []error
2882 for _, depName := range module.missingDeps {
2883 errs = append(errs, c.missingDependencyError(module, depName))
2884 }
2885 errsCh <- errs
2886 return true
2887 }
2888
2889 depsCh <- mctx.ninjaFileDeps
2890
2891 newErrs := c.processLocalBuildActions(&module.actionDefs,
2892 &mctx.actionDefs, liveGlobals)
2893 if len(newErrs) > 0 {
2894 errsCh <- newErrs
2895 return true
2896 }
2897 return false
2898 })
Colin Cross691a60d2015-01-07 18:08:56 -08002899
2900 cancelCh <- struct{}{}
2901 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002902
Colin Crossc4773d92020-08-25 17:12:59 -07002903 errs = append(errs, visitErrs...)
2904
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002905 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002906}
2907
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002908func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002909 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002910
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002911 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002912 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002913
Colin Cross5f03f112017-11-07 13:29:54 -08002914 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002915 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2916 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2917 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002918 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002919
2920 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002921 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002922 context: c,
2923 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002924 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002925 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002926 }
2927
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002928 func() {
2929 defer func() {
2930 if r := recover(); r != nil {
2931 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2932 if err, ok := r.(panicError); ok {
2933 err.addIn(in)
2934 sctx.error(err)
2935 } else {
2936 sctx.error(newPanicErrorf(r, in))
2937 }
2938 }
2939 }()
2940 info.singleton.GenerateBuildActions(sctx)
2941 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002942
2943 if len(sctx.errs) > 0 {
2944 errs = append(errs, sctx.errs...)
2945 if len(errs) > maxErrors {
2946 break
2947 }
2948 continue
2949 }
2950
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002951 deps = append(deps, sctx.ninjaFileDeps...)
2952
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002953 newErrs := c.processLocalBuildActions(&info.actionDefs,
2954 &sctx.actionDefs, liveGlobals)
2955 errs = append(errs, newErrs...)
2956 if len(errs) > maxErrors {
2957 break
2958 }
2959 }
2960
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002961 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002962}
2963
2964func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2965 liveGlobals *liveTracker) []error {
2966
2967 var errs []error
2968
2969 // First we go through and add everything referenced by the module's
2970 // buildDefs to the live globals set. This will end up adding the live
2971 // locals to the set as well, but we'll take them out after.
2972 for _, def := range in.buildDefs {
2973 err := liveGlobals.AddBuildDefDeps(def)
2974 if err != nil {
2975 errs = append(errs, err)
2976 }
2977 }
2978
2979 if len(errs) > 0 {
2980 return errs
2981 }
2982
Colin Crossc9028482014-12-18 16:28:54 -08002983 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002984
2985 // We use the now-incorrect set of live "globals" to determine which local
2986 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002987 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002988 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002989 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002990 if isLive {
2991 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002992 }
2993 }
2994
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002995 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002996 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002997 if isLive {
2998 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002999 }
3000 }
3001
3002 return nil
3003}
3004
Colin Cross9607a9f2018-06-20 11:16:37 -07003005func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07003006 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07003007
3008 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003009 var visiting *moduleInfo
3010
3011 defer func() {
3012 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07003013 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
3014 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003015 }
3016 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07003017
3018 var walk func(module *moduleInfo)
3019 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003020 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07003021 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003022 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07003023 recurse := true
3024 if visitDown != nil {
3025 recurse = visitDown(dep, module)
3026 }
Colin Cross526e02f2018-06-21 13:31:53 -07003027 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003028 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01003029 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07003030 }
Colin Crossbafd5f52016-08-06 22:52:01 -07003031 if visitUp != nil {
3032 visitUp(dep, module)
3033 }
Yuchen Wu222e2452015-10-06 14:03:27 -07003034 }
3035 }
3036 }
3037
3038 walk(topModule)
3039}
3040
Colin Cross9cfd1982016-10-11 09:58:53 -07003041type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003042 from, to *moduleInfo
3043 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003044}
3045
Colin Crossc4e5b812016-10-12 10:45:05 -07003046type rename struct {
3047 group *moduleGroup
3048 name string
3049}
3050
Colin Cross0ce142c2016-12-09 10:29:05 -08003051func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003052 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003053
Colin Crossd03b59d2019-11-13 20:10:12 -08003054 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003055 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003056 }
3057
Colin Crossd03b59d2019-11-13 20:10:12 -08003058 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003059 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003060 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003061 }
3062 }
3063
Colin Cross0ce142c2016-12-09 10:29:05 -08003064 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003065}
3066
Colin Cross0ce142c2016-12-09 10:29:05 -08003067func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003068 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003069 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003070 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003071 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003072 continue
3073 }
3074
Jeff Gastond70bf752017-11-10 15:12:08 -08003075 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003076 }
3077
Colin Cross0ce142c2016-12-09 10:29:05 -08003078 return errs
3079}
3080
3081func (c *Context) handleReplacements(replacements []replace) []error {
3082 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003083 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003084 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003085 for _, m := range replace.from.reverseDeps {
3086 for i, d := range m.directDeps {
3087 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003088 // If the replacement has a predicate then check it.
3089 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3090 m.directDeps[i].module = replace.to
3091 changedDeps = true
3092 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003093 }
3094 }
3095 }
3096
Colin Cross9cfd1982016-10-11 09:58:53 -07003097 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003098
Paul Duffin8969cb62020-06-30 12:15:26 +01003099 if changedDeps {
3100 atomic.AddUint32(&c.depsModified, 1)
3101 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003102 return errs
3103}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003104
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003105func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3106 if depVariations != nil {
3107 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3108 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003109 if c.allowMissingDependencies {
3110 module.missingDeps = append(module.missingDeps, depName)
3111 return nil
3112 }
3113 return []error{c.missingDependencyError(module, depName)}
3114}
3115
3116func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3117 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3118
3119 return &BlueprintError{
3120 Err: err,
3121 Pos: module.pos,
3122 }
3123}
3124
Colin Crossd03b59d2019-11-13 20:10:12 -08003125func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003126 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3127 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003128 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003129 }
3130 return nil
3131}
3132
Jeff Gastond70bf752017-11-10 15:12:08 -08003133func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003134 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003135 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3136 result := make([]*moduleGroup, 0, len(wrappers))
3137 for _, group := range wrappers {
3138 result = append(result, group.moduleGroup)
3139 }
3140 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003141 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003142
3143 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003144 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003145 }
3146
Jeff Gastond70bf752017-11-10 15:12:08 -08003147 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003148}
3149
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003150func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003151 var module *moduleInfo
3152
3153 defer func() {
3154 if r := recover(); r != nil {
3155 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3156 funcName(visit), module))
3157 }
3158 }()
3159
Jeff Gastond70bf752017-11-10 15:12:08 -08003160 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003161 for _, moduleOrAlias := range moduleGroup.modules {
3162 if module = moduleOrAlias.module(); module != nil {
3163 visit(module.logicModule)
3164 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003165 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003166 }
3167}
3168
3169func (c *Context) visitAllModulesIf(pred func(Module) bool,
3170 visit func(Module)) {
3171
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003172 var module *moduleInfo
3173
3174 defer func() {
3175 if r := recover(); r != nil {
3176 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3177 funcName(pred), funcName(visit), module))
3178 }
3179 }()
3180
Jeff Gastond70bf752017-11-10 15:12:08 -08003181 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003182 for _, moduleOrAlias := range moduleGroup.modules {
3183 if module = moduleOrAlias.module(); module != nil {
3184 if pred(module.logicModule) {
3185 visit(module.logicModule)
3186 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003187 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003188 }
3189 }
3190}
3191
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003192func (c *Context) visitAllModuleVariants(module *moduleInfo,
3193 visit func(Module)) {
3194
3195 var variant *moduleInfo
3196
3197 defer func() {
3198 if r := recover(); r != nil {
3199 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3200 module, funcName(visit), variant))
3201 }
3202 }()
3203
Colin Cross5df74a82020-08-24 16:18:21 -07003204 for _, moduleOrAlias := range module.group.modules {
3205 if variant = moduleOrAlias.module(); variant != nil {
3206 visit(variant.logicModule)
3207 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003208 }
3209}
3210
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003211func (c *Context) requireNinjaVersion(major, minor, micro int) {
3212 if major != 1 {
3213 panic("ninja version with major version != 1 not supported")
3214 }
3215 if c.requiredNinjaMinor < minor {
3216 c.requiredNinjaMinor = minor
3217 c.requiredNinjaMicro = micro
3218 }
3219 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3220 c.requiredNinjaMicro = micro
3221 }
3222}
3223
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003224func (c *Context) setOutDir(value ninjaString) {
3225 if c.outDir == nil {
3226 c.outDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003227 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003228}
3229
3230func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003231 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003232
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003233 pkgs := make(map[string]*packageContext)
3234 pkgNames := make(map[*packageContext]string)
3235 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003236
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003237 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003238 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003239 // This is a built-in rule and has no package.
3240 return
3241 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003242 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003243 // We've already processed this package.
3244 return
3245 }
3246
Jamie Gennis2fb20952014-10-03 02:49:58 -07003247 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003248 if present {
3249 // Short name collision. Both this package and the one that's
3250 // already there need to use their full names. We leave the short
3251 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003252 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003253 longPkgNames[otherPkg] = true
3254 } else {
3255 // No collision so far. Tentatively set the package's name to be
3256 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003257 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003258 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003259 }
3260 }
3261
3262 // We try to give all packages their short name, but when we get collisions
3263 // we need to use the full unique package name.
3264 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003265 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003266 }
3267 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003268 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003269 }
3270 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003271 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003272 }
3273
3274 // Add the packages that had collisions using their full unique names. This
3275 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003276 for pctx := range longPkgNames {
3277 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003278 }
3279
Dan Willemsena481ae22015-12-18 15:18:03 -08003280 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3281 deps := []string{}
3282 for _, pkg := range pkgs {
3283 deps = append(deps, pkg.ninjaFileDeps...)
3284 }
3285
3286 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003287}
3288
Colin Cross92054a42021-01-21 16:49:25 -08003289// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3290// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3291// are used much more than once.
3292func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3293 for v := range liveGlobals.variables {
3294 v.memoizeFullName(pkgNames)
3295 }
3296 for r := range liveGlobals.rules {
3297 r.memoizeFullName(pkgNames)
3298 }
3299 for p := range liveGlobals.pools {
3300 p.memoizeFullName(pkgNames)
3301 }
3302}
3303
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003304func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003305 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003306
3307 visited := make(map[Variable]bool) // variables that were already checked
3308 checking := make(map[Variable]bool) // variables actively being checked
3309
3310 var check func(v Variable) []Variable
3311
3312 check = func(v Variable) []Variable {
3313 visited[v] = true
3314 checking[v] = true
3315 defer delete(checking, v)
3316
3317 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003318 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003319 if checking[dep] {
3320 // This is a cycle.
3321 return []Variable{dep, v}
3322 }
3323
3324 if !visited[dep] {
3325 cycle := check(dep)
3326 if cycle != nil {
3327 if cycle[0] == v {
3328 // We are the "start" of the cycle, so we're responsible
3329 // for generating the errors. The cycle list is in
3330 // reverse order because all the 'check' calls append
3331 // their own module to the list.
3332 msgs := []string{"detected variable reference cycle:"}
3333
3334 // Iterate backwards through the cycle list.
3335 curName := v.fullName(pkgNames)
3336 curValue := value.Value(pkgNames)
3337 for i := len(cycle) - 1; i >= 0; i-- {
3338 next := cycle[i]
3339 nextName := next.fullName(pkgNames)
3340 nextValue := variables[next].Value(pkgNames)
3341
3342 msgs = append(msgs, fmt.Sprintf(
3343 " %q depends on %q", curName, nextName))
3344 msgs = append(msgs, fmt.Sprintf(
3345 " [%s = %s]", curName, curValue))
3346
3347 curName = nextName
3348 curValue = nextValue
3349 }
3350
3351 // Variable reference cycles are a programming error,
3352 // not the fault of the Blueprint file authors.
3353 panic(strings.Join(msgs, "\n"))
3354 } else {
3355 // We're not the "start" of the cycle, so we just append
3356 // our module to the list and return it.
3357 return append(cycle, v)
3358 }
3359 }
3360 }
3361 }
3362
3363 return nil
3364 }
3365
3366 for v := range variables {
3367 if !visited[v] {
3368 cycle := check(v)
3369 if cycle != nil {
3370 panic("inconceivable!")
3371 }
3372 }
3373 }
3374}
3375
Jamie Gennisaf435562014-10-27 22:34:56 -07003376// AllTargets returns a map all the build target names to the rule used to build
3377// them. This is the same information that is output by running 'ninja -t
3378// targets all'. If this is called before PrepareBuildActions successfully
3379// completes then ErrbuildActionsNotReady is returned.
3380func (c *Context) AllTargets() (map[string]string, error) {
3381 if !c.buildActionsReady {
3382 return nil, ErrBuildActionsNotReady
3383 }
3384
3385 targets := map[string]string{}
3386
3387 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003388 for _, module := range c.moduleInfo {
3389 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003390 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003391 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003392 outputValue, err := output.Eval(c.globalVariables)
3393 if err != nil {
3394 return nil, err
3395 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003396 targets[outputValue] = ruleName
3397 }
3398 }
3399 }
3400
3401 // Collect all the singleton build targets.
3402 for _, info := range c.singletonInfo {
3403 for _, buildDef := range info.actionDefs.buildDefs {
3404 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003405 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003406 outputValue, err := output.Eval(c.globalVariables)
3407 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003408 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003409 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003410 targets[outputValue] = ruleName
3411 }
3412 }
3413 }
3414
3415 return targets, nil
3416}
3417
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003418func (c *Context) OutDir() (string, error) {
3419 if c.outDir != nil {
3420 return c.outDir.Eval(c.globalVariables)
Colin Crossa2599452015-11-18 16:01:01 -08003421 } else {
3422 return "", nil
3423 }
3424}
3425
Colin Cross4572edd2015-05-13 14:36:24 -07003426// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3427// property structs returned by the factory for that module type.
3428func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3429 ret := make(map[string][]interface{})
3430 for moduleType, factory := range c.moduleFactories {
3431 _, ret[moduleType] = factory()
3432 }
3433
3434 return ret
3435}
3436
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003437func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3438 ret := make(map[string]ModuleFactory)
3439 for k, v := range c.moduleFactories {
3440 ret[k] = v
3441 }
3442 return ret
3443}
3444
Colin Cross4572edd2015-05-13 14:36:24 -07003445func (c *Context) ModuleName(logicModule Module) string {
3446 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003447 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003448}
3449
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003450func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003451 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003452}
3453
Colin Cross8c602f72015-12-17 18:02:11 -08003454func (c *Context) ModuleSubDir(logicModule Module) string {
3455 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003456 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003457}
3458
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003459func (c *Context) ModuleType(logicModule Module) string {
3460 module := c.moduleInfo[logicModule]
3461 return module.typeName
3462}
3463
Colin Cross2da84922020-07-02 10:08:12 -07003464// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3465// provider was not set it returns the zero value of the type of the provider, which means the
3466// return value can always be type-asserted to the type of the provider. The return value should
3467// always be considered read-only. It panics if called before the appropriate mutator or
3468// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3469// copy of the value originally passed to SetProvider.
3470func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3471 module := c.moduleInfo[logicModule]
3472 value, _ := c.provider(module, provider)
3473 return value
3474}
3475
3476// ModuleHasProvider returns true if the provider for the given module has been set.
3477func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3478 module := c.moduleInfo[logicModule]
3479 _, ok := c.provider(module, provider)
3480 return ok
3481}
3482
Colin Cross4572edd2015-05-13 14:36:24 -07003483func (c *Context) BlueprintFile(logicModule Module) string {
3484 module := c.moduleInfo[logicModule]
3485 return module.relBlueprintsFile
3486}
3487
3488func (c *Context) ModuleErrorf(logicModule Module, format string,
3489 args ...interface{}) error {
3490
3491 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003492 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003493 Err: fmt.Errorf(format, args...),
3494 Pos: module.pos,
3495 }
3496}
3497
3498func (c *Context) VisitAllModules(visit func(Module)) {
3499 c.visitAllModules(visit)
3500}
3501
3502func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3503 visit func(Module)) {
3504
3505 c.visitAllModulesIf(pred, visit)
3506}
3507
Colin Cross080c1332017-03-17 13:09:05 -07003508func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3509 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003510
Colin Cross080c1332017-03-17 13:09:05 -07003511 var visiting *moduleInfo
3512
3513 defer func() {
3514 if r := recover(); r != nil {
3515 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3516 topModule, funcName(visit), visiting))
3517 }
3518 }()
3519
3520 for _, dep := range topModule.directDeps {
3521 visiting = dep.module
3522 visit(dep.module.logicModule)
3523 }
3524}
3525
3526func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3527 topModule := c.moduleInfo[module]
3528
3529 var visiting *moduleInfo
3530
3531 defer func() {
3532 if r := recover(); r != nil {
3533 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3534 topModule, funcName(pred), funcName(visit), visiting))
3535 }
3536 }()
3537
3538 for _, dep := range topModule.directDeps {
3539 visiting = dep.module
3540 if pred(dep.module.logicModule) {
3541 visit(dep.module.logicModule)
3542 }
3543 }
3544}
3545
3546func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003547 topModule := c.moduleInfo[module]
3548
3549 var visiting *moduleInfo
3550
3551 defer func() {
3552 if r := recover(); r != nil {
3553 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3554 topModule, funcName(visit), visiting))
3555 }
3556 }()
3557
Colin Cross9607a9f2018-06-20 11:16:37 -07003558 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003559 visiting = dep.module
3560 visit(dep.module.logicModule)
3561 })
Colin Cross4572edd2015-05-13 14:36:24 -07003562}
3563
Colin Cross080c1332017-03-17 13:09:05 -07003564func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003565 topModule := c.moduleInfo[module]
3566
3567 var visiting *moduleInfo
3568
3569 defer func() {
3570 if r := recover(); r != nil {
3571 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3572 topModule, funcName(pred), funcName(visit), visiting))
3573 }
3574 }()
3575
Colin Cross9607a9f2018-06-20 11:16:37 -07003576 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003577 if pred(dep.module.logicModule) {
3578 visiting = dep.module
3579 visit(dep.module.logicModule)
3580 }
3581 })
Colin Cross4572edd2015-05-13 14:36:24 -07003582}
3583
Colin Cross24ad5872015-11-17 16:22:29 -08003584func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003585 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003586}
3587
3588func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003589 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003590}
3591
3592func (c *Context) VisitAllModuleVariants(module Module,
3593 visit func(Module)) {
3594
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003595 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003596}
3597
Colin Cross9226d6c2019-02-25 18:07:44 -08003598// Singletons returns a list of all registered Singletons.
3599func (c *Context) Singletons() []Singleton {
3600 var ret []Singleton
3601 for _, s := range c.singletonInfo {
3602 ret = append(ret, s.singleton)
3603 }
3604 return ret
3605}
3606
3607// SingletonName returns the name that the given singleton was registered with.
3608func (c *Context) SingletonName(singleton Singleton) string {
3609 for _, s := range c.singletonInfo {
3610 if s.singleton == singleton {
3611 return s.name
3612 }
3613 }
3614 return ""
3615}
3616
Jamie Gennisd4e10182014-06-12 20:06:50 -07003617// WriteBuildFile writes the Ninja manifeset text for the generated build
3618// actions to w. If this is called before PrepareBuildActions successfully
3619// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003620func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003621 var err error
3622 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3623 if !c.buildActionsReady {
3624 err = ErrBuildActionsNotReady
3625 return
3626 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003627
Colin Cross3a8c0252019-01-23 13:21:48 -08003628 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003629
Colin Cross3a8c0252019-01-23 13:21:48 -08003630 err = c.writeBuildFileHeader(nw)
3631 if err != nil {
3632 return
3633 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003634
Colin Cross3a8c0252019-01-23 13:21:48 -08003635 err = c.writeNinjaRequiredVersion(nw)
3636 if err != nil {
3637 return
3638 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003639
Colin Cross3a8c0252019-01-23 13:21:48 -08003640 err = c.writeSubninjas(nw)
3641 if err != nil {
3642 return
3643 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003644
Colin Cross3a8c0252019-01-23 13:21:48 -08003645 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003646
Colin Cross3a8c0252019-01-23 13:21:48 -08003647 err = c.writeGlobalVariables(nw)
3648 if err != nil {
3649 return
3650 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003651
Colin Cross3a8c0252019-01-23 13:21:48 -08003652 err = c.writeGlobalPools(nw)
3653 if err != nil {
3654 return
3655 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003656
Colin Cross3a8c0252019-01-23 13:21:48 -08003657 err = c.writeBuildDir(nw)
3658 if err != nil {
3659 return
3660 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003661
Colin Cross3a8c0252019-01-23 13:21:48 -08003662 err = c.writeGlobalRules(nw)
3663 if err != nil {
3664 return
3665 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003666
Colin Cross3a8c0252019-01-23 13:21:48 -08003667 err = c.writeAllModuleActions(nw)
3668 if err != nil {
3669 return
3670 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003671
Colin Cross3a8c0252019-01-23 13:21:48 -08003672 err = c.writeAllSingletonActions(nw)
3673 if err != nil {
3674 return
3675 }
3676 })
3677
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003678 if err != nil {
3679 return err
3680 }
3681
3682 return nil
3683}
3684
Jamie Gennisc15544d2014-09-24 20:26:52 -07003685type pkgAssociation struct {
3686 PkgName string
3687 PkgPath string
3688}
3689
3690type pkgAssociationSorter struct {
3691 pkgs []pkgAssociation
3692}
3693
3694func (s *pkgAssociationSorter) Len() int {
3695 return len(s.pkgs)
3696}
3697
3698func (s *pkgAssociationSorter) Less(i, j int) bool {
3699 iName := s.pkgs[i].PkgName
3700 jName := s.pkgs[j].PkgName
3701 return iName < jName
3702}
3703
3704func (s *pkgAssociationSorter) Swap(i, j int) {
3705 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3706}
3707
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003708func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3709 headerTemplate := template.New("fileHeader")
3710 _, err := headerTemplate.Parse(fileHeaderTemplate)
3711 if err != nil {
3712 // This is a programming error.
3713 panic(err)
3714 }
3715
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003716 var pkgs []pkgAssociation
3717 maxNameLen := 0
3718 for pkg, name := range c.pkgNames {
3719 pkgs = append(pkgs, pkgAssociation{
3720 PkgName: name,
3721 PkgPath: pkg.pkgPath,
3722 })
3723 if len(name) > maxNameLen {
3724 maxNameLen = len(name)
3725 }
3726 }
3727
3728 for i := range pkgs {
3729 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3730 }
3731
Jamie Gennisc15544d2014-09-24 20:26:52 -07003732 sort.Sort(&pkgAssociationSorter{pkgs})
3733
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003734 params := map[string]interface{}{
3735 "Pkgs": pkgs,
3736 }
3737
3738 buf := bytes.NewBuffer(nil)
3739 err = headerTemplate.Execute(buf, params)
3740 if err != nil {
3741 return err
3742 }
3743
3744 return nw.Comment(buf.String())
3745}
3746
3747func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3748 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3749 c.requiredNinjaMicro)
3750
3751 err := nw.Assign("ninja_required_version", value)
3752 if err != nil {
3753 return err
3754 }
3755
3756 return nw.BlankLine()
3757}
3758
Dan Willemsenab223a52018-07-05 21:56:59 -07003759func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3760 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003761 err := nw.Subninja(subninja)
3762 if err != nil {
3763 return err
3764 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003765 }
3766 return nw.BlankLine()
3767}
3768
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003769func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003770 if c.outDir != nil {
3771 err := nw.Assign("builddir", c.outDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003772 if err != nil {
3773 return err
3774 }
3775
3776 err = nw.BlankLine()
3777 if err != nil {
3778 return err
3779 }
3780 }
3781 return nil
3782}
3783
Jamie Gennisc15544d2014-09-24 20:26:52 -07003784type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003785 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003786}
3787
Jamie Gennisc15544d2014-09-24 20:26:52 -07003788type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003789 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003790 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003791}
3792
Jamie Gennisc15544d2014-09-24 20:26:52 -07003793func (s *globalEntitySorter) Len() int {
3794 return len(s.entities)
3795}
3796
3797func (s *globalEntitySorter) Less(i, j int) bool {
3798 iName := s.entities[i].fullName(s.pkgNames)
3799 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003800 return iName < jName
3801}
3802
Jamie Gennisc15544d2014-09-24 20:26:52 -07003803func (s *globalEntitySorter) Swap(i, j int) {
3804 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003805}
3806
3807func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3808 visited := make(map[Variable]bool)
3809
3810 var walk func(v Variable) error
3811 walk = func(v Variable) error {
3812 visited[v] = true
3813
3814 // First visit variables on which this variable depends.
3815 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003816 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003817 if !visited[dep] {
3818 err := walk(dep)
3819 if err != nil {
3820 return err
3821 }
3822 }
3823 }
3824
3825 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3826 if err != nil {
3827 return err
3828 }
3829
3830 err = nw.BlankLine()
3831 if err != nil {
3832 return err
3833 }
3834
3835 return nil
3836 }
3837
Jamie Gennisc15544d2014-09-24 20:26:52 -07003838 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3839 for variable := range c.globalVariables {
3840 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003841 }
3842
Jamie Gennisc15544d2014-09-24 20:26:52 -07003843 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003844
Jamie Gennisc15544d2014-09-24 20:26:52 -07003845 for _, entity := range globalVariables {
3846 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003847 if !visited[v] {
3848 err := walk(v)
3849 if err != nil {
3850 return nil
3851 }
3852 }
3853 }
3854
3855 return nil
3856}
3857
3858func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003859 globalPools := make([]globalEntity, 0, len(c.globalPools))
3860 for pool := range c.globalPools {
3861 globalPools = append(globalPools, pool)
3862 }
3863
3864 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3865
3866 for _, entity := range globalPools {
3867 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003868 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003869 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003870 err := def.WriteTo(nw, name)
3871 if err != nil {
3872 return err
3873 }
3874
3875 err = nw.BlankLine()
3876 if err != nil {
3877 return err
3878 }
3879 }
3880
3881 return nil
3882}
3883
3884func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003885 globalRules := make([]globalEntity, 0, len(c.globalRules))
3886 for rule := range c.globalRules {
3887 globalRules = append(globalRules, rule)
3888 }
3889
3890 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3891
3892 for _, entity := range globalRules {
3893 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003894 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003895 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003896 err := def.WriteTo(nw, name, c.pkgNames)
3897 if err != nil {
3898 return err
3899 }
3900
3901 err = nw.BlankLine()
3902 if err != nil {
3903 return err
3904 }
3905 }
3906
3907 return nil
3908}
3909
Colin Cross2c1f3d12016-04-11 15:47:28 -07003910type depSorter []depInfo
3911
3912func (s depSorter) Len() int {
3913 return len(s)
3914}
3915
3916func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003917 iName := s[i].module.Name()
3918 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003919 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003920 iName = s[i].module.variant.name
3921 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003922 }
3923 return iName < jName
3924}
3925
3926func (s depSorter) Swap(i, j int) {
3927 s[i], s[j] = s[j], s[i]
3928}
3929
Jeff Gaston0e907592017-12-01 17:10:52 -08003930type moduleSorter struct {
3931 modules []*moduleInfo
3932 nameInterface NameInterface
3933}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003934
Colin Crossab6d7902015-03-11 16:17:52 -07003935func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003936 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003937}
3938
Colin Crossab6d7902015-03-11 16:17:52 -07003939func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003940 iMod := s.modules[i]
3941 jMod := s.modules[j]
3942 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3943 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003944 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003945 iVariantName := s.modules[i].variant.name
3946 jVariantName := s.modules[j].variant.name
3947 if iVariantName == jVariantName {
3948 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3949 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3950 } else {
3951 return iVariantName < jVariantName
3952 }
3953 } else {
3954 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003955 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003956}
3957
Colin Crossab6d7902015-03-11 16:17:52 -07003958func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003959 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003960}
3961
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003962func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3963 headerTemplate := template.New("moduleHeader")
3964 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3965 if err != nil {
3966 // This is a programming error.
3967 panic(err)
3968 }
3969
Colin Crossab6d7902015-03-11 16:17:52 -07003970 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3971 for _, module := range c.moduleInfo {
3972 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003973 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003974 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003975
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003976 buf := bytes.NewBuffer(nil)
3977
Colin Crossab6d7902015-03-11 16:17:52 -07003978 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003979 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3980 continue
3981 }
3982
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003983 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003984
3985 // In order to make the bootstrap build manifest independent of the
3986 // build dir we need to output the Blueprints file locations in the
3987 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003988 relPos := module.pos
3989 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003990
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003991 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003992 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003993 factoryName := factoryFunc.Name()
3994
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003995 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003996 "name": module.Name(),
3997 "typeName": module.typeName,
3998 "goFactory": factoryName,
3999 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07004000 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004001 }
4002 err = headerTemplate.Execute(buf, infoMap)
4003 if err != nil {
4004 return err
4005 }
4006
4007 err = nw.Comment(buf.String())
4008 if err != nil {
4009 return err
4010 }
4011
4012 err = nw.BlankLine()
4013 if err != nil {
4014 return err
4015 }
4016
Colin Crossab6d7902015-03-11 16:17:52 -07004017 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004018 if err != nil {
4019 return err
4020 }
4021
4022 err = nw.BlankLine()
4023 if err != nil {
4024 return err
4025 }
4026 }
4027
4028 return nil
4029}
4030
4031func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
4032 headerTemplate := template.New("singletonHeader")
4033 _, err := headerTemplate.Parse(singletonHeaderTemplate)
4034 if err != nil {
4035 // This is a programming error.
4036 panic(err)
4037 }
4038
4039 buf := bytes.NewBuffer(nil)
4040
Yuchen Wub9103ef2015-08-25 17:58:17 -07004041 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004042 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4043 continue
4044 }
4045
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004046 // Get the name of the factory function for the module.
4047 factory := info.factory
4048 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4049 factoryName := factoryFunc.Name()
4050
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004051 buf.Reset()
4052 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004053 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004054 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004055 }
4056 err = headerTemplate.Execute(buf, infoMap)
4057 if err != nil {
4058 return err
4059 }
4060
4061 err = nw.Comment(buf.String())
4062 if err != nil {
4063 return err
4064 }
4065
4066 err = nw.BlankLine()
4067 if err != nil {
4068 return err
4069 }
4070
4071 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4072 if err != nil {
4073 return err
4074 }
4075
4076 err = nw.BlankLine()
4077 if err != nil {
4078 return err
4079 }
4080 }
4081
4082 return nil
4083}
4084
4085func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4086 defs *localBuildActions) error {
4087
4088 // Write the local variable assignments.
4089 for _, v := range defs.variables {
4090 // A localVariable doesn't need the package names or config to
4091 // determine its name or value.
4092 name := v.fullName(nil)
4093 value, err := v.value(nil)
4094 if err != nil {
4095 panic(err)
4096 }
4097 err = nw.Assign(name, value.Value(c.pkgNames))
4098 if err != nil {
4099 return err
4100 }
4101 }
4102
4103 if len(defs.variables) > 0 {
4104 err := nw.BlankLine()
4105 if err != nil {
4106 return err
4107 }
4108 }
4109
4110 // Write the local rules.
4111 for _, r := range defs.rules {
4112 // A localRule doesn't need the package names or config to determine
4113 // its name or definition.
4114 name := r.fullName(nil)
4115 def, err := r.def(nil)
4116 if err != nil {
4117 panic(err)
4118 }
4119
4120 err = def.WriteTo(nw, name, c.pkgNames)
4121 if err != nil {
4122 return err
4123 }
4124
4125 err = nw.BlankLine()
4126 if err != nil {
4127 return err
4128 }
4129 }
4130
4131 // Write the build definitions.
4132 for _, buildDef := range defs.buildDefs {
4133 err := buildDef.WriteTo(nw, c.pkgNames)
4134 if err != nil {
4135 return err
4136 }
4137
4138 if len(buildDef.Args) > 0 {
4139 err = nw.BlankLine()
4140 if err != nil {
4141 return err
4142 }
4143 }
4144 }
4145
4146 return nil
4147}
4148
Colin Cross5df74a82020-08-24 16:18:21 -07004149func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004150 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004151 if a == b {
4152 return false
4153 }
Colin Cross65569e42015-03-10 20:08:19 -07004154 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004155 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004156 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004157 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004158 return found
4159 }
4160 }
4161
4162 missing := a
4163 if found {
4164 missing = b
4165 }
4166 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4167}
4168
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004169type panicError struct {
4170 panic interface{}
4171 stack []byte
4172 in string
4173}
4174
4175func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4176 buf := make([]byte, 4096)
4177 count := runtime.Stack(buf, false)
4178 return panicError{
4179 panic: panic,
4180 in: fmt.Sprintf(in, a...),
4181 stack: buf[:count],
4182 }
4183}
4184
4185func (p panicError) Error() string {
4186 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4187}
4188
4189func (p *panicError) addIn(in string) {
4190 p.in += " in " + in
4191}
4192
4193func funcName(f interface{}) string {
4194 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4195}
4196
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004197var fileHeaderTemplate = `******************************************************************************
4198*** This file is generated and should not be edited ***
4199******************************************************************************
4200{{if .Pkgs}}
4201This file contains variables, rules, and pools with name prefixes indicating
4202they were generated by the following Go packages:
4203{{range .Pkgs}}
4204 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4205
4206`
4207
4208var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004209Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004210Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004211Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004212Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004213Defined: {{.pos}}
4214`
4215
4216var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4217Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004218Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004219`