blob: ccf040988c49a3721d1f1002056d19dc1f3db9a6 [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
Colin Cross2ce594e2020-01-29 12:58:03 -0800105 ninjaBuildDir ninjaString // The builddir special Ninja variable
106 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),
Colin Cross5f03f112017-11-07 13:29:54 -0800391 ninjaBuildDir: nil,
392 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
750 added chan<- struct{}
751 }
752
753 moduleCh := make(chan newModuleInfo)
Colin Cross23d7aa12015-06-30 16:05:22 -0700754 errsCh := make(chan []error)
755 doneCh := make(chan struct{})
756 var numErrs uint32
757 var numGoroutines int32
758
759 // handler must be reentrant
Jeff Gaston5f763d02017-08-08 14:43:58 -0700760 handleOneFile := func(file *parser.File) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700761 if atomic.LoadUint32(&numErrs) > maxErrors {
762 return
763 }
764
Colin Crossda70fd02019-12-30 18:40:09 -0800765 addedCh := make(chan struct{})
766
Colin Cross9672d862019-12-30 18:38:20 -0800767 var scopedModuleFactories map[string]ModuleFactory
768
Colin Crossda70fd02019-12-30 18:40:09 -0800769 var addModule func(module *moduleInfo) []error
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100770 addModule = func(module *moduleInfo) []error {
Paul Duffin244033b2020-05-04 11:00:03 +0100771 // Run any load hooks immediately before it is sent to the moduleCh and is
772 // registered by name. This allows load hooks to set and/or modify any aspect
773 // of the module (including names) using information that is not available when
774 // the module factory is called.
775 newModules, errs := runAndRemoveLoadHooks(c, config, module, &scopedModuleFactories)
Colin Crossda70fd02019-12-30 18:40:09 -0800776 if len(errs) > 0 {
777 return errs
778 }
Paul Duffin244033b2020-05-04 11:00:03 +0100779
780 moduleCh <- newModuleInfo{module, addedCh}
781 <-addedCh
Colin Crossda70fd02019-12-30 18:40:09 -0800782 for _, n := range newModules {
783 errs = addModule(n)
784 if len(errs) > 0 {
785 return errs
786 }
787 }
788 return nil
789 }
790
Jeff Gaston656870f2017-11-29 18:37:31 -0800791 for _, def := range file.Defs {
Jeff Gaston656870f2017-11-29 18:37:31 -0800792 switch def := def.(type) {
793 case *parser.Module:
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100794 module, errs := processModuleDef(def, file.Name, c.moduleFactories, scopedModuleFactories, c.ignoreUnknownModuleTypes)
Colin Crossda70fd02019-12-30 18:40:09 -0800795 if len(errs) == 0 && module != nil {
796 errs = addModule(module)
797 }
798
799 if len(errs) > 0 {
800 atomic.AddUint32(&numErrs, uint32(len(errs)))
801 errsCh <- errs
802 }
803
Jeff Gaston656870f2017-11-29 18:37:31 -0800804 case *parser.Assignment:
805 // Already handled via Scope object
806 default:
807 panic("unknown definition type")
Colin Cross23d7aa12015-06-30 16:05:22 -0700808 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800809
Jeff Gaston656870f2017-11-29 18:37:31 -0800810 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700811 }
812
813 atomic.AddInt32(&numGoroutines, 1)
814 go func() {
815 var errs []error
Jeff Gastonc3e28442017-08-09 15:13:12 -0700816 deps, errs = c.WalkBlueprintsFiles(rootDir, filePaths, handleOneFile)
Colin Cross23d7aa12015-06-30 16:05:22 -0700817 if len(errs) > 0 {
818 errsCh <- errs
819 }
820 doneCh <- struct{}{}
821 }()
822
823loop:
824 for {
825 select {
826 case newErrs := <-errsCh:
827 errs = append(errs, newErrs...)
828 case module := <-moduleCh:
Colin Crossda70fd02019-12-30 18:40:09 -0800829 newErrs := c.addModule(module.moduleInfo)
830 if module.added != nil {
831 module.added <- struct{}{}
832 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700833 if len(newErrs) > 0 {
834 errs = append(errs, newErrs...)
835 }
836 case <-doneCh:
837 n := atomic.AddInt32(&numGoroutines, -1)
838 if n == 0 {
839 break loop
840 }
841 }
842 }
843
844 return deps, errs
845}
846
847type FileHandler func(*parser.File)
848
Jeff Gastonc3e28442017-08-09 15:13:12 -0700849// WalkBlueprintsFiles walks a set of Blueprints files starting with the given filepaths,
850// calling the given file handler on each
851//
852// When WalkBlueprintsFiles encounters a Blueprints file with a set of subdirs listed,
853// it recursively parses any Blueprints files found in those subdirectories.
854//
855// If any of the file paths is an ancestor directory of any other of file path, the ancestor
856// will be parsed and visited first.
857//
858// the file handler will be called from a goroutine, so it must be reentrant.
Colin Cross23d7aa12015-06-30 16:05:22 -0700859//
860// If no errors are encountered while parsing the files, the list of paths on
861// which the future output will depend is returned. This list will include both
862// Blueprints file paths as well as directory paths for cases where wildcard
863// subdirs are found.
Jeff Gaston656870f2017-11-29 18:37:31 -0800864//
865// visitor will be called asynchronously, and will only be called once visitor for each
866// ancestor directory has completed.
867//
868// WalkBlueprintsFiles will not return until all calls to visitor have returned.
Jeff Gastonc3e28442017-08-09 15:13:12 -0700869func (c *Context) WalkBlueprintsFiles(rootDir string, filePaths []string,
870 visitor FileHandler) (deps []string, errs []error) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700871
Jeff Gastonc3e28442017-08-09 15:13:12 -0700872 // make a mapping from ancestors to their descendants to facilitate parsing ancestors first
873 descendantsMap, err := findBlueprintDescendants(filePaths)
874 if err != nil {
875 panic(err.Error())
Jeff Gastonc3e28442017-08-09 15:13:12 -0700876 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800877 blueprintsSet := make(map[string]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700878
Jeff Gaston5800d042017-12-05 14:57:58 -0800879 // Channels to receive data back from openAndParse goroutines
Jeff Gaston656870f2017-11-29 18:37:31 -0800880 blueprintsCh := make(chan fileParseContext)
Colin Cross7ad621c2015-01-07 16:22:45 -0800881 errsCh := make(chan []error)
Colin Cross7ad621c2015-01-07 16:22:45 -0800882 depsCh := make(chan string)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700883
Jeff Gaston5800d042017-12-05 14:57:58 -0800884 // Channel to notify main loop that a openAndParse goroutine has finished
Jeff Gaston656870f2017-11-29 18:37:31 -0800885 doneParsingCh := make(chan fileParseContext)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700886
Colin Cross7ad621c2015-01-07 16:22:45 -0800887 // Number of outstanding goroutines to wait for
Jeff Gaston5f763d02017-08-08 14:43:58 -0700888 activeCount := 0
Jeff Gaston656870f2017-11-29 18:37:31 -0800889 var pending []fileParseContext
Jeff Gastonc3e28442017-08-09 15:13:12 -0700890 tooManyErrors := false
891
892 // Limit concurrent calls to parseBlueprintFiles to 200
893 // Darwin has a default limit of 256 open files
894 maxActiveCount := 200
Colin Cross7ad621c2015-01-07 16:22:45 -0800895
Jeff Gaston656870f2017-11-29 18:37:31 -0800896 // count the number of pending calls to visitor()
897 visitorWaitGroup := sync.WaitGroup{}
898
899 startParseBlueprintsFile := func(blueprint fileParseContext) {
900 if blueprintsSet[blueprint.fileName] {
Colin Cross4a02a302017-05-16 10:33:58 -0700901 return
902 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800903 blueprintsSet[blueprint.fileName] = true
Jeff Gaston5f763d02017-08-08 14:43:58 -0700904 activeCount++
Jeff Gaston656870f2017-11-29 18:37:31 -0800905 deps = append(deps, blueprint.fileName)
906 visitorWaitGroup.Add(1)
Colin Cross7ad621c2015-01-07 16:22:45 -0800907 go func() {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800908 file, blueprints, deps, errs := c.openAndParse(blueprint.fileName, blueprint.Scope, rootDir,
909 &blueprint)
910 if len(errs) > 0 {
911 errsCh <- errs
912 }
913 for _, blueprint := range blueprints {
914 blueprintsCh <- blueprint
915 }
916 for _, dep := range deps {
917 depsCh <- dep
918 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800919 doneParsingCh <- blueprint
Jeff Gaston5f763d02017-08-08 14:43:58 -0700920
Jeff Gaston656870f2017-11-29 18:37:31 -0800921 if blueprint.parent != nil && blueprint.parent.doneVisiting != nil {
922 // wait for visitor() of parent to complete
923 <-blueprint.parent.doneVisiting
924 }
925
Jeff Gastona7e408a2017-12-05 15:11:55 -0800926 if len(errs) == 0 {
927 // process this file
928 visitor(file)
929 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800930 if blueprint.doneVisiting != nil {
931 close(blueprint.doneVisiting)
932 }
933 visitorWaitGroup.Done()
Colin Cross7ad621c2015-01-07 16:22:45 -0800934 }()
935 }
936
Jeff Gaston656870f2017-11-29 18:37:31 -0800937 foundParseableBlueprint := func(blueprint fileParseContext) {
Jeff Gastonc3e28442017-08-09 15:13:12 -0700938 if activeCount >= maxActiveCount {
939 pending = append(pending, blueprint)
940 } else {
941 startParseBlueprintsFile(blueprint)
942 }
943 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800944
Jeff Gaston656870f2017-11-29 18:37:31 -0800945 startParseDescendants := func(blueprint fileParseContext) {
946 descendants, hasDescendants := descendantsMap[blueprint.fileName]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700947 if hasDescendants {
948 for _, descendant := range descendants {
Jeff Gaston656870f2017-11-29 18:37:31 -0800949 foundParseableBlueprint(fileParseContext{descendant, parser.NewScope(blueprint.Scope), &blueprint, make(chan struct{})})
Jeff Gastonc3e28442017-08-09 15:13:12 -0700950 }
951 }
952 }
Colin Cross4a02a302017-05-16 10:33:58 -0700953
Jeff Gastonc3e28442017-08-09 15:13:12 -0700954 // begin parsing any files that have no ancestors
Jeff Gaston656870f2017-11-29 18:37:31 -0800955 startParseDescendants(fileParseContext{"", parser.NewScope(nil), nil, nil})
Colin Cross7ad621c2015-01-07 16:22:45 -0800956
957loop:
958 for {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700959 if len(errs) > maxErrors {
Colin Cross7ad621c2015-01-07 16:22:45 -0800960 tooManyErrors = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700961 }
962
Colin Cross7ad621c2015-01-07 16:22:45 -0800963 select {
964 case newErrs := <-errsCh:
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700965 errs = append(errs, newErrs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800966 case dep := <-depsCh:
967 deps = append(deps, dep)
Colin Cross7ad621c2015-01-07 16:22:45 -0800968 case blueprint := <-blueprintsCh:
969 if tooManyErrors {
970 continue
971 }
Jeff Gastonc3e28442017-08-09 15:13:12 -0700972 foundParseableBlueprint(blueprint)
Jeff Gaston656870f2017-11-29 18:37:31 -0800973 case blueprint := <-doneParsingCh:
Jeff Gaston5f763d02017-08-08 14:43:58 -0700974 activeCount--
Jeff Gastonc3e28442017-08-09 15:13:12 -0700975 if !tooManyErrors {
976 startParseDescendants(blueprint)
977 }
978 if activeCount < maxActiveCount && len(pending) > 0 {
979 // start to process the next one from the queue
980 next := pending[len(pending)-1]
Colin Cross4a02a302017-05-16 10:33:58 -0700981 pending = pending[:len(pending)-1]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700982 startParseBlueprintsFile(next)
Colin Cross4a02a302017-05-16 10:33:58 -0700983 }
Jeff Gaston5f763d02017-08-08 14:43:58 -0700984 if activeCount == 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -0800985 break loop
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700986 }
987 }
988 }
989
Jeff Gastonc3e28442017-08-09 15:13:12 -0700990 sort.Strings(deps)
991
Jeff Gaston656870f2017-11-29 18:37:31 -0800992 // wait for every visitor() to complete
993 visitorWaitGroup.Wait()
994
Colin Cross7ad621c2015-01-07 16:22:45 -0800995 return
996}
997
Colin Crossd7b0f602016-06-02 15:30:20 -0700998// MockFileSystem causes the Context to replace all reads with accesses to the provided map of
999// filenames to contents stored as a byte slice.
1000func (c *Context) MockFileSystem(files map[string][]byte) {
Jeff Gaston9f630902017-11-15 14:49:48 -08001001 // look for a module list file
1002 _, ok := files[MockModuleListFile]
1003 if !ok {
1004 // no module list file specified; find every file named Blueprints
1005 pathsToParse := []string{}
1006 for candidate := range files {
1007 if filepath.Base(candidate) == "Blueprints" {
1008 pathsToParse = append(pathsToParse, candidate)
1009 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001010 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001011 if len(pathsToParse) < 1 {
1012 panic(fmt.Sprintf("No Blueprints files found in mock filesystem: %v\n", files))
1013 }
1014 // put the list of Blueprints files into a list file
1015 files[MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
Jeff Gastonc3e28442017-08-09 15:13:12 -07001016 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001017 c.SetModuleListFile(MockModuleListFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001018
1019 // mock the filesystem
Colin Crossb519a7e2017-02-01 13:21:35 -08001020 c.fs = pathtools.MockFs(files)
Colin Crossd7b0f602016-06-02 15:30:20 -07001021}
1022
Colin Cross8cde4252019-12-17 13:11:21 -08001023func (c *Context) SetFs(fs pathtools.FileSystem) {
1024 c.fs = fs
1025}
1026
Jeff Gaston8fd95782017-12-05 15:03:51 -08001027// openAndParse opens and parses a single Blueprints file, and returns the results
Jeff Gaston5800d042017-12-05 14:57:58 -08001028func (c *Context) openAndParse(filename string, scope *parser.Scope, rootDir string,
Jeff Gaston8fd95782017-12-05 15:03:51 -08001029 parent *fileParseContext) (file *parser.File,
1030 subBlueprints []fileParseContext, deps []string, errs []error) {
Colin Cross7ad621c2015-01-07 16:22:45 -08001031
Colin Crossd7b0f602016-06-02 15:30:20 -07001032 f, err := c.fs.Open(filename)
Colin Cross7ad621c2015-01-07 16:22:45 -08001033 if err != nil {
Jeff Gastonaca42202017-08-23 17:30:05 -07001034 // couldn't open the file; see if we can provide a clearer error than "could not open file"
1035 stats, statErr := c.fs.Lstat(filename)
1036 if statErr == nil {
1037 isSymlink := stats.Mode()&os.ModeSymlink != 0
1038 if isSymlink {
1039 err = fmt.Errorf("could not open symlink %v : %v", filename, err)
1040 target, readlinkErr := os.Readlink(filename)
1041 if readlinkErr == nil {
1042 _, targetStatsErr := c.fs.Lstat(target)
1043 if targetStatsErr != nil {
1044 err = fmt.Errorf("could not open symlink %v; its target (%v) cannot be opened", filename, target)
1045 }
1046 }
1047 } else {
1048 err = fmt.Errorf("%v exists but could not be opened: %v", filename, err)
1049 }
1050 }
Jeff Gaston8fd95782017-12-05 15:03:51 -08001051 return nil, nil, nil, []error{err}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001052 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001053
Jeff Gaston8fd95782017-12-05 15:03:51 -08001054 func() {
1055 defer func() {
1056 err = f.Close()
1057 if err != nil {
1058 errs = append(errs, err)
1059 }
1060 }()
1061 file, subBlueprints, errs = c.parseOne(rootDir, filename, f, scope, parent)
Colin Cross23d7aa12015-06-30 16:05:22 -07001062 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001063
Colin Cross7ad621c2015-01-07 16:22:45 -08001064 if len(errs) > 0 {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001065 return nil, nil, nil, errs
Colin Cross7ad621c2015-01-07 16:22:45 -08001066 }
1067
Colin Cross1fef5362015-04-20 16:50:54 -07001068 for _, b := range subBlueprints {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001069 deps = append(deps, b.fileName)
Colin Cross1fef5362015-04-20 16:50:54 -07001070 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001071
Jeff Gaston8fd95782017-12-05 15:03:51 -08001072 return file, subBlueprints, deps, nil
Colin Cross1fef5362015-04-20 16:50:54 -07001073}
1074
Jeff Gastona12f22f2017-08-08 14:45:56 -07001075// parseOne parses a single Blueprints file from the given reader, creating Module
1076// objects for each of the module definitions encountered. If the Blueprints
1077// file contains an assignment to the "subdirs" variable, then the
1078// subdirectories listed are searched for Blueprints files returned in the
1079// subBlueprints return value. If the Blueprints file contains an assignment
1080// to the "build" variable, then the file listed are returned in the
1081// subBlueprints return value.
1082//
1083// rootDir specifies the path to the root directory of the source tree, while
1084// filename specifies the path to the Blueprints file. These paths are used for
1085// error reporting and for determining the module's directory.
1086func (c *Context) parseOne(rootDir, filename string, reader io.Reader,
Jeff Gaston656870f2017-11-29 18:37:31 -08001087 scope *parser.Scope, parent *fileParseContext) (file *parser.File, subBlueprints []fileParseContext, errs []error) {
Jeff Gastona12f22f2017-08-08 14:45:56 -07001088
1089 relBlueprintsFile, err := filepath.Rel(rootDir, filename)
1090 if err != nil {
1091 return nil, nil, []error{err}
1092 }
1093
Jeff Gastona12f22f2017-08-08 14:45:56 -07001094 scope.Remove("subdirs")
1095 scope.Remove("optional_subdirs")
1096 scope.Remove("build")
1097 file, errs = parser.ParseAndEval(filename, reader, scope)
1098 if len(errs) > 0 {
1099 for i, err := range errs {
1100 if parseErr, ok := err.(*parser.ParseError); ok {
1101 err = &BlueprintError{
1102 Err: parseErr.Err,
1103 Pos: parseErr.Pos,
1104 }
1105 errs[i] = err
1106 }
1107 }
1108
1109 // If there were any parse errors don't bother trying to interpret the
1110 // result.
1111 return nil, nil, errs
1112 }
1113 file.Name = relBlueprintsFile
1114
Jeff Gastona12f22f2017-08-08 14:45:56 -07001115 build, buildPos, err := getLocalStringListFromScope(scope, "build")
1116 if err != nil {
1117 errs = append(errs, err)
1118 }
Jeff Gastonf23e3662017-11-30 17:31:43 -08001119 for _, buildEntry := range build {
1120 if strings.Contains(buildEntry, "/") {
1121 errs = append(errs, &BlueprintError{
1122 Err: fmt.Errorf("illegal value %v. The '/' character is not permitted", buildEntry),
1123 Pos: buildPos,
1124 })
1125 }
1126 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001127
1128 subBlueprintsName, _, err := getStringFromScope(scope, "subname")
1129 if err != nil {
1130 errs = append(errs, err)
1131 }
1132
1133 if subBlueprintsName == "" {
1134 subBlueprintsName = "Blueprints"
1135 }
1136
1137 var blueprints []string
1138
1139 newBlueprints, newErrs := c.findBuildBlueprints(filepath.Dir(filename), build, buildPos)
1140 blueprints = append(blueprints, newBlueprints...)
1141 errs = append(errs, newErrs...)
1142
Jeff Gaston656870f2017-11-29 18:37:31 -08001143 subBlueprintsAndScope := make([]fileParseContext, len(blueprints))
Jeff Gastona12f22f2017-08-08 14:45:56 -07001144 for i, b := range blueprints {
Jeff Gaston656870f2017-11-29 18:37:31 -08001145 subBlueprintsAndScope[i] = fileParseContext{b, parser.NewScope(scope), parent, make(chan struct{})}
Jeff Gastona12f22f2017-08-08 14:45:56 -07001146 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001147 return file, subBlueprintsAndScope, errs
1148}
1149
Colin Cross7f507402015-12-16 13:03:41 -08001150func (c *Context) findBuildBlueprints(dir string, build []string,
Colin Cross127d2ea2016-11-01 11:10:51 -07001151 buildPos scanner.Position) ([]string, []error) {
1152
1153 var blueprints []string
1154 var errs []error
Colin Cross7f507402015-12-16 13:03:41 -08001155
1156 for _, file := range build {
Colin Cross127d2ea2016-11-01 11:10:51 -07001157 pattern := filepath.Join(dir, file)
1158 var matches []string
1159 var err error
1160
Colin Cross08e49542016-11-14 15:23:33 -08001161 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001162
Colin Cross7f507402015-12-16 13:03:41 -08001163 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001164 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001165 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross7f507402015-12-16 13:03:41 -08001166 Pos: buildPos,
1167 })
1168 continue
1169 }
1170
1171 if len(matches) == 0 {
Colin Cross2c628442016-10-07 17:13:10 -07001172 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001173 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross7f507402015-12-16 13:03:41 -08001174 Pos: buildPos,
1175 })
1176 }
1177
Colin Cross7f507402015-12-16 13:03:41 -08001178 for _, foundBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001179 if strings.HasSuffix(foundBlueprints, "/") {
1180 errs = append(errs, &BlueprintError{
1181 Err: fmt.Errorf("%q: is a directory", foundBlueprints),
1182 Pos: buildPos,
1183 })
1184 }
Colin Cross7f507402015-12-16 13:03:41 -08001185 blueprints = append(blueprints, foundBlueprints)
1186 }
1187 }
1188
Colin Cross127d2ea2016-11-01 11:10:51 -07001189 return blueprints, errs
Colin Cross7f507402015-12-16 13:03:41 -08001190}
1191
1192func (c *Context) findSubdirBlueprints(dir string, subdirs []string, subdirsPos scanner.Position,
Colin Cross127d2ea2016-11-01 11:10:51 -07001193 subBlueprintsName string, optional bool) ([]string, []error) {
1194
1195 var blueprints []string
1196 var errs []error
Colin Cross7ad621c2015-01-07 16:22:45 -08001197
1198 for _, subdir := range subdirs {
Colin Cross127d2ea2016-11-01 11:10:51 -07001199 pattern := filepath.Join(dir, subdir, subBlueprintsName)
1200 var matches []string
1201 var err error
1202
Colin Cross08e49542016-11-14 15:23:33 -08001203 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001204
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001205 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001206 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001207 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross1fef5362015-04-20 16:50:54 -07001208 Pos: subdirsPos,
1209 })
1210 continue
1211 }
1212
Colin Cross7f507402015-12-16 13:03:41 -08001213 if len(matches) == 0 && !optional {
Colin Cross2c628442016-10-07 17:13:10 -07001214 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001215 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross1fef5362015-04-20 16:50:54 -07001216 Pos: subdirsPos,
1217 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001218 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001219
Colin Cross127d2ea2016-11-01 11:10:51 -07001220 for _, subBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001221 if strings.HasSuffix(subBlueprints, "/") {
1222 errs = append(errs, &BlueprintError{
1223 Err: fmt.Errorf("%q: is a directory", subBlueprints),
1224 Pos: subdirsPos,
1225 })
1226 }
Colin Cross127d2ea2016-11-01 11:10:51 -07001227 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -08001228 }
1229 }
Colin Cross1fef5362015-04-20 16:50:54 -07001230
Colin Cross127d2ea2016-11-01 11:10:51 -07001231 return blueprints, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001232}
1233
Colin Cross6d8780f2015-07-10 17:51:55 -07001234func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
1235 if assignment, local := scope.Get(v); assignment == nil || !local {
1236 return nil, scanner.Position{}, nil
1237 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001238 switch value := assignment.Value.Eval().(type) {
1239 case *parser.List:
1240 ret := make([]string, 0, len(value.Values))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001241
Colin Crosse32cc802016-06-07 12:28:16 -07001242 for _, listValue := range value.Values {
1243 s, ok := listValue.(*parser.String)
1244 if !ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001245 // The parser should not produce this.
1246 panic("non-string value found in list")
1247 }
1248
Colin Crosse32cc802016-06-07 12:28:16 -07001249 ret = append(ret, s.Value)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001250 }
1251
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001252 return ret, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001253 case *parser.Bool, *parser.String:
Colin Cross2c628442016-10-07 17:13:10 -07001254 return nil, scanner.Position{}, &BlueprintError{
Colin Cross1fef5362015-04-20 16:50:54 -07001255 Err: fmt.Errorf("%q must be a list of strings", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001256 Pos: assignment.EqualsPos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001257 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001258 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001259 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001260 }
1261 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001262}
1263
Colin Cross29394222015-04-27 13:18:21 -07001264func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -07001265 if assignment, _ := scope.Get(v); assignment == nil {
1266 return "", scanner.Position{}, nil
1267 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001268 switch value := assignment.Value.Eval().(type) {
1269 case *parser.String:
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001270 return value.Value, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001271 case *parser.Bool, *parser.List:
Colin Cross2c628442016-10-07 17:13:10 -07001272 return "", scanner.Position{}, &BlueprintError{
Colin Cross29394222015-04-27 13:18:21 -07001273 Err: fmt.Errorf("%q must be a string", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001274 Pos: assignment.EqualsPos,
Colin Cross29394222015-04-27 13:18:21 -07001275 }
1276 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001277 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Colin Cross29394222015-04-27 13:18:21 -07001278 }
1279 }
Colin Cross29394222015-04-27 13:18:21 -07001280}
1281
Colin Cross910242b2016-04-11 15:41:52 -07001282// Clones a build logic module by calling the factory method for its module type, and then cloning
1283// property values. Any values stored in the module object that are not stored in properties
1284// structs will be lost.
1285func (c *Context) cloneLogicModule(origModule *moduleInfo) (Module, []interface{}) {
Colin Crossaf4fd212017-07-28 14:32:36 -07001286 newLogicModule, newProperties := origModule.factory()
Colin Cross910242b2016-04-11 15:41:52 -07001287
Colin Crossd2f4ac12017-07-28 14:31:03 -07001288 if len(newProperties) != len(origModule.properties) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001289 panic("mismatched properties array length in " + origModule.Name())
Colin Cross910242b2016-04-11 15:41:52 -07001290 }
1291
1292 for i := range newProperties {
Colin Cross5d57b2d2020-01-27 16:14:31 -08001293 dst := reflect.ValueOf(newProperties[i])
1294 src := reflect.ValueOf(origModule.properties[i])
Colin Cross910242b2016-04-11 15:41:52 -07001295
1296 proptools.CopyProperties(dst, src)
1297 }
1298
1299 return newLogicModule, newProperties
1300}
1301
Colin Crossedc41762020-08-13 12:07:30 -07001302func newVariant(module *moduleInfo, mutatorName string, variationName string,
1303 local bool) variant {
1304
1305 newVariantName := module.variant.name
1306 if variationName != "" {
1307 if newVariantName == "" {
1308 newVariantName = variationName
1309 } else {
1310 newVariantName += "_" + variationName
1311 }
1312 }
1313
1314 newVariations := module.variant.variations.clone()
1315 if newVariations == nil {
1316 newVariations = make(variationMap)
1317 }
1318 newVariations[mutatorName] = variationName
1319
1320 newDependencyVariations := module.variant.dependencyVariations.clone()
1321 if !local {
1322 if newDependencyVariations == nil {
1323 newDependencyVariations = make(variationMap)
1324 }
1325 newDependencyVariations[mutatorName] = variationName
1326 }
1327
1328 return variant{newVariantName, newVariations, newDependencyVariations}
1329}
1330
Colin Crossf5e34b92015-03-13 16:02:36 -07001331func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
Colin Cross5df74a82020-08-24 16:18:21 -07001332 defaultVariationName *string, variationNames []string, local bool) (modulesOrAliases, []error) {
Colin Crossc9028482014-12-18 16:28:54 -08001333
Colin Crossf4d18a62015-03-18 17:43:15 -07001334 if len(variationNames) == 0 {
1335 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001336 mutatorName, origModule.Name()))
Colin Crossf4d18a62015-03-18 17:43:15 -07001337 }
1338
Colin Cross5df74a82020-08-24 16:18:21 -07001339 var newModules modulesOrAliases
Colin Crossc9028482014-12-18 16:28:54 -08001340
Colin Cross174ae052015-03-03 17:37:03 -08001341 var errs []error
1342
Colin Crossf5e34b92015-03-13 16:02:36 -07001343 for i, variationName := range variationNames {
Colin Crossc9028482014-12-18 16:28:54 -08001344 var newLogicModule Module
1345 var newProperties []interface{}
1346
1347 if i == 0 {
1348 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -07001349 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
1350 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossd2f4ac12017-07-28 14:31:03 -07001351 newLogicModule, newProperties = origModule.logicModule, origModule.properties
Colin Crossc9028482014-12-18 16:28:54 -08001352 } else {
Colin Cross910242b2016-04-11 15:41:52 -07001353 newLogicModule, newProperties = c.cloneLogicModule(origModule)
Colin Crossc9028482014-12-18 16:28:54 -08001354 }
1355
Colin Crossed342d92015-03-11 00:57:25 -07001356 m := *origModule
1357 newModule := &m
Colin Cross2da84922020-07-02 10:08:12 -07001358 newModule.directDeps = append([]depInfo(nil), origModule.directDeps...)
Colin Cross7ff2e8d2021-01-21 22:39:28 -08001359 newModule.reverseDeps = nil
1360 newModule.forwardDeps = nil
Colin Crossed342d92015-03-11 00:57:25 -07001361 newModule.logicModule = newLogicModule
Colin Crossedc41762020-08-13 12:07:30 -07001362 newModule.variant = newVariant(origModule, mutatorName, variationName, local)
Colin Crossd2f4ac12017-07-28 14:31:03 -07001363 newModule.properties = newProperties
Colin Cross2da84922020-07-02 10:08:12 -07001364 newModule.providers = append([]interface{}(nil), origModule.providers...)
Colin Crossc9028482014-12-18 16:28:54 -08001365
1366 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -07001367
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001368 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName, defaultVariationName)
Colin Cross174ae052015-03-03 17:37:03 -08001369 if len(newErrs) > 0 {
1370 errs = append(errs, newErrs...)
1371 }
Colin Crossc9028482014-12-18 16:28:54 -08001372 }
1373
1374 // Mark original variant as invalid. Modules that depend on this module will still
1375 // depend on origModule, but we'll fix it when the mutator is called on them.
1376 origModule.logicModule = nil
1377 origModule.splitModules = newModules
1378
Colin Cross3702ac72016-08-11 11:09:00 -07001379 atomic.AddUint32(&c.depsModified, 1)
1380
Colin Cross174ae052015-03-03 17:37:03 -08001381 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -08001382}
1383
Colin Crossf5e34b92015-03-13 16:02:36 -07001384func (c *Context) convertDepsToVariation(module *moduleInfo,
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001385 mutatorName, variationName string, defaultVariationName *string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -08001386
Colin Crossc9028482014-12-18 16:28:54 -08001387 for i, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001388 if dep.module.logicModule == nil {
Colin Crossc9028482014-12-18 16:28:54 -08001389 var newDep *moduleInfo
Colin Cross2c1f3d12016-04-11 15:47:28 -07001390 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001391 if m.moduleOrAliasVariant().variations[mutatorName] == variationName {
1392 newDep = m.moduleOrAliasTarget()
Colin Crossc9028482014-12-18 16:28:54 -08001393 break
1394 }
1395 }
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001396 if newDep == nil && defaultVariationName != nil {
1397 // give it a second chance; match with defaultVariationName
1398 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001399 if m.moduleOrAliasVariant().variations[mutatorName] == *defaultVariationName {
1400 newDep = m.moduleOrAliasTarget()
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001401 break
1402 }
1403 }
1404 }
Colin Crossc9028482014-12-18 16:28:54 -08001405 if newDep == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001406 errs = append(errs, &BlueprintError{
Colin Crossf5e34b92015-03-13 16:02:36 -07001407 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001408 variationName, dep.module.Name(), module.Name()),
Colin Crossed342d92015-03-11 00:57:25 -07001409 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -08001410 })
1411 continue
Colin Crossc9028482014-12-18 16:28:54 -08001412 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001413 module.directDeps[i].module = newDep
Colin Crossc9028482014-12-18 16:28:54 -08001414 }
1415 }
Colin Cross174ae052015-03-03 17:37:03 -08001416
1417 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001418}
1419
Colin Crossedc41762020-08-13 12:07:30 -07001420func (c *Context) prettyPrintVariant(variations variationMap) string {
1421 names := make([]string, 0, len(variations))
Colin Cross65569e42015-03-10 20:08:19 -07001422 for _, m := range c.variantMutatorNames {
Colin Crossedc41762020-08-13 12:07:30 -07001423 if v, ok := variations[m]; ok {
Colin Cross65569e42015-03-10 20:08:19 -07001424 names = append(names, m+":"+v)
1425 }
1426 }
1427
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001428 return strings.Join(names, ",")
Colin Cross65569e42015-03-10 20:08:19 -07001429}
1430
Colin Crossd03b59d2019-11-13 20:10:12 -08001431func (c *Context) prettyPrintGroupVariants(group *moduleGroup) string {
1432 var variants []string
Colin Cross5df74a82020-08-24 16:18:21 -07001433 for _, moduleOrAlias := range group.modules {
1434 if mod := moduleOrAlias.module(); mod != nil {
1435 variants = append(variants, c.prettyPrintVariant(mod.variant.variations))
1436 } else if alias := moduleOrAlias.alias(); alias != nil {
1437 variants = append(variants, c.prettyPrintVariant(alias.variant.variations)+
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001438 " (alias to "+c.prettyPrintVariant(alias.target.variant.variations)+")")
Colin Cross5df74a82020-08-24 16:18:21 -07001439 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001440 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001441 return strings.Join(variants, "\n ")
1442}
1443
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001444func newModule(factory ModuleFactory) *moduleInfo {
Colin Crossaf4fd212017-07-28 14:32:36 -07001445 logicModule, properties := factory()
1446
1447 module := &moduleInfo{
1448 logicModule: logicModule,
1449 factory: factory,
1450 }
1451
1452 module.properties = properties
1453
1454 return module
1455}
1456
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001457func processModuleDef(moduleDef *parser.Module,
1458 relBlueprintsFile string, moduleFactories, scopedModuleFactories map[string]ModuleFactory, ignoreUnknownModuleTypes bool) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001459
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001460 factory, ok := moduleFactories[moduleDef.Type]
Colin Cross9672d862019-12-30 18:38:20 -08001461 if !ok && scopedModuleFactories != nil {
1462 factory, ok = scopedModuleFactories[moduleDef.Type]
1463 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001464 if !ok {
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001465 if ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001466 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001467 }
1468
Colin Cross7ad621c2015-01-07 16:22:45 -08001469 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001470 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001471 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1472 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001473 },
1474 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001475 }
1476
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001477 module := newModule(factory)
Colin Crossaf4fd212017-07-28 14:32:36 -07001478 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001479
Colin Crossaf4fd212017-07-28 14:32:36 -07001480 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001481
Colin Crossf27c5e42020-01-02 09:37:49 -08001482 propertyMap, errs := proptools.UnpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001483 if len(errs) > 0 {
Colin Crossf27c5e42020-01-02 09:37:49 -08001484 for i, err := range errs {
1485 if unpackErr, ok := err.(*proptools.UnpackError); ok {
1486 err = &BlueprintError{
1487 Err: unpackErr.Err,
1488 Pos: unpackErr.Pos,
1489 }
1490 errs[i] = err
1491 }
1492 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001493 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001494 }
1495
Colin Crossc32c4792016-06-09 15:52:30 -07001496 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001497 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001498 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001499 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001500 }
1501
Colin Cross7ad621c2015-01-07 16:22:45 -08001502 return module, nil
1503}
1504
Colin Cross23d7aa12015-06-30 16:05:22 -07001505func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001506 name := module.logicModule.Name()
Jaewoong Jungccc34942018-10-11 13:01:05 -07001507 if name == "" {
1508 return []error{
1509 &BlueprintError{
1510 Err: fmt.Errorf("property 'name' is missing from a module"),
1511 Pos: module.pos,
1512 },
1513 }
1514 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001515 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001516
Colin Cross0b7e83e2016-05-17 14:58:05 -07001517 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001518 name: name,
Colin Cross5df74a82020-08-24 16:18:21 -07001519 modules: modulesOrAliases{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001520 }
1521 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001522 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001523 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001524 ModuleGroup{moduleGroup: group},
1525 module.logicModule)
1526 if len(errs) > 0 {
1527 for i := range errs {
1528 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1529 }
1530 return errs
1531 }
1532 group.namespace = namespace
1533
Colin Cross0b7e83e2016-05-17 14:58:05 -07001534 c.moduleGroups = append(c.moduleGroups, group)
1535
Colin Cross23d7aa12015-06-30 16:05:22 -07001536 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001537}
1538
Jamie Gennisd4e10182014-06-12 20:06:50 -07001539// ResolveDependencies checks that the dependencies specified by all of the
1540// modules defined in the parsed Blueprints files are valid. This means that
1541// the modules depended upon are defined and that no circular dependencies
1542// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001543func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08001544 return c.resolveDependencies(c.Context, config)
1545}
Colin Cross5f03f112017-11-07 13:29:54 -08001546
Colin Cross3a8c0252019-01-23 13:21:48 -08001547func (c *Context) resolveDependencies(ctx context.Context, config interface{}) (deps []string, errs []error) {
1548 pprof.Do(ctx, pprof.Labels("blueprint", "ResolveDependencies"), func(ctx context.Context) {
Colin Cross2da84922020-07-02 10:08:12 -07001549 c.initProviders()
1550
Colin Cross3a8c0252019-01-23 13:21:48 -08001551 c.liveGlobals = newLiveTracker(config)
1552
1553 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1554 if len(errs) > 0 {
1555 return
1556 }
1557
1558 errs = c.updateDependencies()
1559 if len(errs) > 0 {
1560 return
1561 }
1562
1563 var mutatorDeps []string
1564 mutatorDeps, errs = c.runMutators(ctx, config)
1565 if len(errs) > 0 {
1566 return
1567 }
1568 deps = append(deps, mutatorDeps...)
1569
Colin Cross2da84922020-07-02 10:08:12 -07001570 if !c.skipCloneModulesAfterMutators {
1571 c.cloneModules()
1572 }
Colin Cross3a8c0252019-01-23 13:21:48 -08001573
1574 c.dependenciesReady = true
1575 })
1576
Colin Cross5f03f112017-11-07 13:29:54 -08001577 if len(errs) > 0 {
1578 return nil, errs
1579 }
1580
Colin Cross874a3462017-07-31 17:26:06 -07001581 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001582}
1583
Colin Cross763b6f12015-10-29 15:32:56 -07001584// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001585// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001586// module names returned by its DynamicDependencies method and those added by calling
1587// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001588func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001589 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001590 func() {
1591 defer func() {
1592 if r := recover(); r != nil {
1593 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1594 }
1595 }()
1596 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001597
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001598 if ctx.Failed() {
1599 return
1600 }
Colin Cross763b6f12015-10-29 15:32:56 -07001601
Colin Cross2c1f3d12016-04-11 15:47:28 -07001602 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001603 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001604 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001605}
1606
Colin Cross39644c02020-08-21 18:20:38 -07001607// findExactVariantOrSingle searches the moduleGroup for a module with the same variant as module,
1608// and returns the matching module, or nil if one is not found. A group with exactly one module
1609// is always considered matching.
1610func findExactVariantOrSingle(module *moduleInfo, possible *moduleGroup, reverse bool) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07001611 found, _ := findVariant(module, possible, nil, false, reverse)
1612 if found == nil {
1613 for _, moduleOrAlias := range possible.modules {
1614 if m := moduleOrAlias.module(); m != nil {
1615 if found != nil {
1616 // more than one possible match, give up
1617 return nil
1618 }
1619 found = m
1620 }
1621 }
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001622 }
Colin Cross5df74a82020-08-24 16:18:21 -07001623 return found
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001624}
1625
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001626func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) (*moduleInfo, []error) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001627 if _, ok := tag.(BaseDependencyTag); ok {
1628 panic("BaseDependencyTag is not allowed to be used directly!")
1629 }
1630
Colin Cross0b7e83e2016-05-17 14:58:05 -07001631 if depName == module.Name() {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001632 return nil, []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001633 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001634 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001635 }}
1636 }
1637
Colin Crossd03b59d2019-11-13 20:10:12 -08001638 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001639 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001640 return nil, c.discoveredMissingDependencies(module, depName, nil)
Colin Crossc9028482014-12-18 16:28:54 -08001641 }
1642
Colin Cross39644c02020-08-21 18:20:38 -07001643 if m := findExactVariantOrSingle(module, possibleDeps, false); m != nil {
Colin Cross99bdb2a2019-03-29 16:35:02 -07001644 module.newDirectDeps = append(module.newDirectDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001645 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001646 return m, nil
Colin Cross65569e42015-03-10 20:08:19 -07001647 }
Colin Crossc9028482014-12-18 16:28:54 -08001648
Paul Duffinb77556b2020-03-24 19:01:20 +00001649 if c.allowMissingDependencies {
1650 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001651 return nil, c.discoveredMissingDependencies(module, depName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001652 }
1653
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001654 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001655 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001656 depName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001657 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001658 c.prettyPrintGroupVariants(possibleDeps)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001659 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001660 }}
1661}
1662
Colin Cross8d8a7af2015-11-03 16:41:29 -08001663func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001664 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001665 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001666 Err: fmt.Errorf("%q depends on itself", destName),
1667 Pos: module.pos,
1668 }}
1669 }
1670
Colin Crossd03b59d2019-11-13 20:10:12 -08001671 possibleDeps := c.moduleGroupFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001672 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001673 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001674 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001675 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001676 Pos: module.pos,
1677 }}
1678 }
1679
Colin Cross39644c02020-08-21 18:20:38 -07001680 if m := findExactVariantOrSingle(module, possibleDeps, true); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001681 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001682 }
1683
Paul Duffinb77556b2020-03-24 19:01:20 +00001684 if c.allowMissingDependencies {
1685 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001686 return module, c.discoveredMissingDependencies(module, destName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001687 }
1688
Colin Cross2c628442016-10-07 17:13:10 -07001689 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001690 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001691 destName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001692 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001693 c.prettyPrintGroupVariants(possibleDeps)),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001694 Pos: module.pos,
1695 }}
1696}
1697
Colin Cross39644c02020-08-21 18:20:38 -07001698func findVariant(module *moduleInfo, possibleDeps *moduleGroup, variations []Variation, far bool, reverse bool) (*moduleInfo, variationMap) {
Colin Crossedc41762020-08-13 12:07:30 -07001699 // We can't just append variant.Variant to module.dependencyVariant.variantName and
Colin Cross65569e42015-03-10 20:08:19 -07001700 // compare the strings because the result won't be in mutator registration order.
1701 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001702 var newVariant variationMap
1703 if !far {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001704 if !reverse {
1705 // For forward dependency, ignore local variants by matching against
1706 // dependencyVariant which doesn't have the local variants
Colin Crossedc41762020-08-13 12:07:30 -07001707 newVariant = module.variant.dependencyVariations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001708 } else {
1709 // For reverse dependency, use all the variants
Colin Crossedc41762020-08-13 12:07:30 -07001710 newVariant = module.variant.variations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001711 }
Colin Cross89486232015-05-08 11:14:54 -07001712 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001713 for _, v := range variations {
Colin Cross9403b5a2019-11-13 20:11:04 -08001714 if newVariant == nil {
1715 newVariant = make(variationMap)
1716 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001717 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001718 }
1719
Colin Crossd03b59d2019-11-13 20:10:12 -08001720 check := func(variant variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -07001721 if far {
Colin Cross5dc67592020-08-24 14:46:13 -07001722 return newVariant.subsetOf(variant)
Colin Cross89486232015-05-08 11:14:54 -07001723 } else {
Colin Crossd03b59d2019-11-13 20:10:12 -08001724 return variant.equal(newVariant)
Colin Cross65569e42015-03-10 20:08:19 -07001725 }
1726 }
1727
Colin Crossd03b59d2019-11-13 20:10:12 -08001728 var foundDep *moduleInfo
1729 for _, m := range possibleDeps.modules {
Colin Cross5df74a82020-08-24 16:18:21 -07001730 if check(m.moduleOrAliasVariant().variations) {
1731 foundDep = m.moduleOrAliasTarget()
Colin Crossd03b59d2019-11-13 20:10:12 -08001732 break
1733 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001734 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001735
Martin Stjernholm2f212472020-03-06 00:29:24 +00001736 return foundDep, newVariant
1737}
1738
1739func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001740 tag DependencyTag, depName string, far bool) (*moduleInfo, []error) {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001741 if _, ok := tag.(BaseDependencyTag); ok {
1742 panic("BaseDependencyTag is not allowed to be used directly!")
1743 }
1744
1745 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
1746 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001747 return nil, c.discoveredMissingDependencies(module, depName, nil)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001748 }
1749
Colin Cross5df74a82020-08-24 16:18:21 -07001750 foundDep, newVariant := findVariant(module, possibleDeps, variations, far, false)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001751
Colin Crossf7beb892019-11-13 20:11:14 -08001752 if foundDep == nil {
Paul Duffinb77556b2020-03-24 19:01:20 +00001753 if c.allowMissingDependencies {
1754 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001755 return nil, c.discoveredMissingDependencies(module, depName, newVariant)
Paul Duffinb77556b2020-03-24 19:01:20 +00001756 }
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001757 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001758 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
1759 depName, module.Name(),
1760 c.prettyPrintVariant(newVariant),
1761 c.prettyPrintGroupVariants(possibleDeps)),
1762 Pos: module.pos,
1763 }}
1764 }
1765
1766 if module == foundDep {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001767 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001768 Err: fmt.Errorf("%q depends on itself", depName),
1769 Pos: module.pos,
1770 }}
1771 }
1772 // AddVariationDependency allows adding a dependency on itself, but only if
1773 // that module is earlier in the module list than this one, since we always
1774 // run GenerateBuildActions in order for the variants of a module
1775 if foundDep.group == module.group && beforeInModuleList(module, foundDep, module.group.modules) {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001776 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001777 Err: fmt.Errorf("%q depends on later version of itself", depName),
1778 Pos: module.pos,
1779 }}
1780 }
1781 module.newDirectDeps = append(module.newDirectDeps, depInfo{foundDep, tag})
1782 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001783 return foundDep, nil
Colin Crossc9028482014-12-18 16:28:54 -08001784}
1785
Colin Crossf1875462016-04-11 17:33:13 -07001786func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001787 from, to Module) *moduleInfo {
Nan Zhang346b2d02017-03-10 16:39:27 -08001788 if _, ok := tag.(BaseDependencyTag); ok {
1789 panic("BaseDependencyTag is not allowed to be used directly!")
1790 }
Colin Crossf1875462016-04-11 17:33:13 -07001791
1792 var fromInfo, toInfo *moduleInfo
Colin Cross5df74a82020-08-24 16:18:21 -07001793 for _, moduleOrAlias := range origModule.splitModules {
1794 if m := moduleOrAlias.module(); m != nil {
1795 if m.logicModule == from {
1796 fromInfo = m
1797 }
1798 if m.logicModule == to {
1799 toInfo = m
1800 if fromInfo != nil {
1801 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
1802 }
Colin Crossf1875462016-04-11 17:33:13 -07001803 }
1804 }
1805 }
1806
1807 if fromInfo == nil || toInfo == nil {
1808 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001809 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001810 }
1811
Colin Cross99bdb2a2019-03-29 16:35:02 -07001812 fromInfo.newDirectDeps = append(fromInfo.newDirectDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001813 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001814 return toInfo
Colin Crossf1875462016-04-11 17:33:13 -07001815}
1816
Jeff Gastonc3e28442017-08-09 15:13:12 -07001817// findBlueprintDescendants returns a map linking parent Blueprints files to child Blueprints files
1818// For example, if paths = []string{"a/b/c/Android.bp", "a/Blueprints"},
1819// then descendants = {"":[]string{"a/Blueprints"}, "a/Blueprints":[]string{"a/b/c/Android.bp"}}
1820func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1821 // make mapping from dir path to file path
1822 filesByDir := make(map[string]string, len(paths))
1823 for _, path := range paths {
1824 dir := filepath.Dir(path)
1825 _, alreadyFound := filesByDir[dir]
1826 if alreadyFound {
1827 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1828 }
1829 filesByDir[dir] = path
1830 }
1831
Jeff Gaston656870f2017-11-29 18:37:31 -08001832 findAncestor := func(childFile string) (ancestor string) {
1833 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001834 for {
1835 ancestorDir := filepath.Dir(prevAncestorDir)
1836 if ancestorDir == prevAncestorDir {
1837 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001838 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001839 }
1840
1841 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1842 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001843 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001844 }
1845 prevAncestorDir = ancestorDir
1846 }
1847 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001848 // generate the descendants map
1849 descendants = make(map[string][]string, len(filesByDir))
1850 for _, childFile := range filesByDir {
1851 ancestorFile := findAncestor(childFile)
1852 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1853 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001854 return descendants, nil
1855}
1856
Colin Cross3702ac72016-08-11 11:09:00 -07001857type visitOrderer interface {
1858 // returns the number of modules that this module needs to wait for
1859 waitCount(module *moduleInfo) int
1860 // returns the list of modules that are waiting for this module
1861 propagate(module *moduleInfo) []*moduleInfo
1862 // visit modules in order
Colin Crossc4773d92020-08-25 17:12:59 -07001863 visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool)
Colin Cross3702ac72016-08-11 11:09:00 -07001864}
1865
Colin Cross7e723372018-03-28 11:50:12 -07001866type unorderedVisitorImpl struct{}
1867
1868func (unorderedVisitorImpl) waitCount(module *moduleInfo) int {
1869 return 0
1870}
1871
1872func (unorderedVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1873 return nil
1874}
1875
Colin Crossc4773d92020-08-25 17:12:59 -07001876func (unorderedVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross7e723372018-03-28 11:50:12 -07001877 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001878 if visit(module, nil) {
Colin Cross7e723372018-03-28 11:50:12 -07001879 return
1880 }
1881 }
1882}
1883
Colin Cross3702ac72016-08-11 11:09:00 -07001884type bottomUpVisitorImpl struct{}
1885
1886func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1887 return len(module.forwardDeps)
1888}
1889
1890func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1891 return module.reverseDeps
1892}
1893
Colin Crossc4773d92020-08-25 17:12:59 -07001894func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001895 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001896 if visit(module, nil) {
Colin Cross49c279a2016-08-05 22:30:44 -07001897 return
1898 }
1899 }
1900}
1901
Colin Cross3702ac72016-08-11 11:09:00 -07001902type topDownVisitorImpl struct{}
1903
1904func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1905 return len(module.reverseDeps)
1906}
1907
1908func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1909 return module.forwardDeps
1910}
1911
Colin Crossc4773d92020-08-25 17:12:59 -07001912func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001913 for i := 0; i < len(modules); i++ {
1914 module := modules[len(modules)-1-i]
Colin Crossc4773d92020-08-25 17:12:59 -07001915 if visit(module, nil) {
Colin Cross3702ac72016-08-11 11:09:00 -07001916 return
1917 }
1918 }
1919}
1920
1921var (
1922 bottomUpVisitor bottomUpVisitorImpl
1923 topDownVisitor topDownVisitorImpl
1924)
1925
Colin Crossc4773d92020-08-25 17:12:59 -07001926// pauseSpec describes a pause that a module needs to occur until another module has been visited,
1927// at which point the unpause channel will be closed.
1928type pauseSpec struct {
1929 paused *moduleInfo
1930 until *moduleInfo
1931 unpause unpause
1932}
1933
1934type unpause chan struct{}
1935
1936const parallelVisitLimit = 1000
1937
Colin Cross49c279a2016-08-05 22:30:44 -07001938// 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 -07001939// of its dependencies has finished. A visit function can write a pauseSpec to the pause channel
1940// to wait for another dependency to be visited. If a visit function returns true to cancel
1941// while another visitor is paused, the paused visitor will never be resumed and its goroutine
1942// will stay paused forever.
1943func parallelVisit(modules []*moduleInfo, order visitOrderer, limit int,
1944 visit func(module *moduleInfo, pause chan<- pauseSpec) bool) []error {
1945
Colin Cross7addea32015-03-11 15:43:52 -07001946 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001947 cancelCh := make(chan bool)
Colin Crossc4773d92020-08-25 17:12:59 -07001948 pauseCh := make(chan pauseSpec)
Colin Cross8900e9b2015-03-02 14:03:01 -08001949 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001950
Colin Crossc4773d92020-08-25 17:12:59 -07001951 var backlog []*moduleInfo // Visitors that are ready to start but backlogged due to limit.
1952 var unpauseBacklog []pauseSpec // Visitors that are ready to unpause but backlogged due to limit.
1953
1954 active := 0 // Number of visitors running, not counting paused visitors.
1955 visited := 0 // Number of finished visitors.
1956
1957 pauseMap := make(map[*moduleInfo][]pauseSpec)
1958
1959 for _, module := range modules {
Colin Cross3702ac72016-08-11 11:09:00 -07001960 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001961 }
1962
Colin Crossc4773d92020-08-25 17:12:59 -07001963 // Call the visitor on a module if there are fewer active visitors than the parallelism
1964 // limit, otherwise add it to the backlog.
1965 startOrBacklog := func(module *moduleInfo) {
1966 if active < limit {
1967 active++
Colin Cross7e723372018-03-28 11:50:12 -07001968 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07001969 ret := visit(module, pauseCh)
Colin Cross7e723372018-03-28 11:50:12 -07001970 if ret {
1971 cancelCh <- true
1972 }
1973 doneCh <- module
1974 }()
1975 } else {
1976 backlog = append(backlog, module)
1977 }
Colin Cross691a60d2015-01-07 18:08:56 -08001978 }
1979
Colin Crossc4773d92020-08-25 17:12:59 -07001980 // Unpause the already-started but paused visitor on a module if there are fewer active
1981 // visitors than the parallelism limit, otherwise add it to the backlog.
1982 unpauseOrBacklog := func(pauseSpec pauseSpec) {
1983 if active < limit {
1984 active++
1985 close(pauseSpec.unpause)
1986 } else {
1987 unpauseBacklog = append(unpauseBacklog, pauseSpec)
Colin Cross691a60d2015-01-07 18:08:56 -08001988 }
1989 }
1990
Colin Crossc4773d92020-08-25 17:12:59 -07001991 // Start any modules in the backlog up to the parallelism limit. Unpause paused modules first
1992 // since they may already be holding resources.
1993 unpauseOrStartFromBacklog := func() {
1994 for active < limit && len(unpauseBacklog) > 0 {
1995 unpause := unpauseBacklog[0]
1996 unpauseBacklog = unpauseBacklog[1:]
1997 unpauseOrBacklog(unpause)
1998 }
1999 for active < limit && len(backlog) > 0 {
2000 toVisit := backlog[0]
2001 backlog = backlog[1:]
2002 startOrBacklog(toVisit)
2003 }
2004 }
2005
2006 toVisit := len(modules)
2007
2008 // Start or backlog any modules that are not waiting for any other modules.
2009 for _, module := range modules {
2010 if module.waitingCount == 0 {
2011 startOrBacklog(module)
2012 }
2013 }
2014
2015 for active > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08002016 select {
Colin Cross7e723372018-03-28 11:50:12 -07002017 case <-cancelCh:
2018 cancel = true
2019 backlog = nil
Colin Cross7addea32015-03-11 15:43:52 -07002020 case doneModule := <-doneCh:
Colin Crossc4773d92020-08-25 17:12:59 -07002021 active--
Colin Cross8900e9b2015-03-02 14:03:01 -08002022 if !cancel {
Colin Crossc4773d92020-08-25 17:12:59 -07002023 // Mark this module as done.
2024 doneModule.waitingCount = -1
2025 visited++
2026
2027 // Unpause or backlog any modules that were waiting for this one.
2028 if unpauses, ok := pauseMap[doneModule]; ok {
2029 delete(pauseMap, doneModule)
2030 for _, unpause := range unpauses {
2031 unpauseOrBacklog(unpause)
2032 }
Colin Cross7e723372018-03-28 11:50:12 -07002033 }
Colin Crossc4773d92020-08-25 17:12:59 -07002034
2035 // Start any backlogged modules up to limit.
2036 unpauseOrStartFromBacklog()
2037
2038 // Decrement waitingCount on the next modules in the tree based
2039 // on propagation order, and start or backlog them if they are
2040 // ready to start.
Colin Cross3702ac72016-08-11 11:09:00 -07002041 for _, module := range order.propagate(doneModule) {
2042 module.waitingCount--
2043 if module.waitingCount == 0 {
Colin Crossc4773d92020-08-25 17:12:59 -07002044 startOrBacklog(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08002045 }
Colin Cross691a60d2015-01-07 18:08:56 -08002046 }
2047 }
Colin Crossc4773d92020-08-25 17:12:59 -07002048 case pauseSpec := <-pauseCh:
2049 if pauseSpec.until.waitingCount == -1 {
2050 // Module being paused for is already finished, resume immediately.
2051 close(pauseSpec.unpause)
2052 } else {
2053 // Register for unpausing.
2054 pauseMap[pauseSpec.until] = append(pauseMap[pauseSpec.until], pauseSpec)
2055
2056 // Don't count paused visitors as active so that this can't deadlock
2057 // if 1000 visitors are paused simultaneously.
2058 active--
2059 unpauseOrStartFromBacklog()
2060 }
Colin Cross691a60d2015-01-07 18:08:56 -08002061 }
2062 }
Colin Crossc4773d92020-08-25 17:12:59 -07002063
2064 if !cancel {
2065 // Invariant check: no backlogged modules, these weren't waiting on anything except
2066 // the parallelism limit so they should have run.
2067 if len(backlog) > 0 {
2068 panic(fmt.Errorf("parallelVisit finished with %d backlogged visitors", len(backlog)))
2069 }
2070
2071 // Invariant check: no backlogged paused modules, these weren't waiting on anything
2072 // except the parallelism limit so they should have run.
2073 if len(unpauseBacklog) > 0 {
2074 panic(fmt.Errorf("parallelVisit finished with %d backlogged unpaused visitors", len(unpauseBacklog)))
2075 }
2076
2077 if len(pauseMap) > 0 {
Colin Cross7d4958d2021-02-08 15:34:08 -08002078 // Probably a deadlock due to a newly added dependency cycle. Start from each module in
2079 // the order of the input modules list and perform a depth-first search for the module
2080 // it is paused on, ignoring modules that are marked as done. Note this traverses from
2081 // modules to the modules that would have been unblocked when that module finished, i.e
2082 // the reverse of the visitOrderer.
Colin Crossc4773d92020-08-25 17:12:59 -07002083
Colin Cross9793b0a2021-04-27 15:20:15 -07002084 // In order to reduce duplicated work, once a module has been checked and determined
2085 // not to be part of a cycle add it and everything that depends on it to the checked
2086 // map.
2087 checked := make(map[*moduleInfo]struct{})
2088
Colin Cross7d4958d2021-02-08 15:34:08 -08002089 var check func(module, end *moduleInfo) []*moduleInfo
2090 check = func(module, end *moduleInfo) []*moduleInfo {
Colin Crossc4773d92020-08-25 17:12:59 -07002091 if module.waitingCount == -1 {
2092 // This module was finished, it can't be part of a loop.
2093 return nil
2094 }
2095 if module == end {
2096 // This module is the end of the loop, start rolling up the cycle.
2097 return []*moduleInfo{module}
2098 }
2099
Colin Cross9793b0a2021-04-27 15:20:15 -07002100 if _, alreadyChecked := checked[module]; alreadyChecked {
2101 return nil
2102 }
2103
Colin Crossc4773d92020-08-25 17:12:59 -07002104 for _, dep := range order.propagate(module) {
Colin Cross7d4958d2021-02-08 15:34:08 -08002105 cycle := check(dep, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002106 if cycle != nil {
2107 return append([]*moduleInfo{module}, cycle...)
2108 }
2109 }
2110 for _, depPauseSpec := range pauseMap[module] {
Colin Cross7d4958d2021-02-08 15:34:08 -08002111 cycle := check(depPauseSpec.paused, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002112 if cycle != nil {
2113 return append([]*moduleInfo{module}, cycle...)
2114 }
2115 }
2116
Colin Cross9793b0a2021-04-27 15:20:15 -07002117 checked[module] = struct{}{}
Colin Crossc4773d92020-08-25 17:12:59 -07002118 return nil
2119 }
2120
Colin Cross7d4958d2021-02-08 15:34:08 -08002121 // Iterate over the modules list instead of pauseMap to provide deterministic ordering.
2122 for _, module := range modules {
2123 for _, pauseSpec := range pauseMap[module] {
2124 cycle := check(pauseSpec.paused, pauseSpec.until)
2125 if len(cycle) > 0 {
2126 return cycleError(cycle)
2127 }
2128 }
Colin Crossc4773d92020-08-25 17:12:59 -07002129 }
2130 }
2131
2132 // Invariant check: if there was no deadlock and no cancellation every module
2133 // should have been visited.
2134 if visited != toVisit {
2135 panic(fmt.Errorf("parallelVisit ran %d visitors, expected %d", visited, toVisit))
2136 }
2137
2138 // Invariant check: if there was no deadlock and no cancellation every module
2139 // should have been visited, so there is nothing left to be paused on.
2140 if len(pauseMap) > 0 {
2141 panic(fmt.Errorf("parallelVisit finished with %d paused visitors", len(pauseMap)))
2142 }
2143 }
2144
2145 return nil
2146}
2147
2148func cycleError(cycle []*moduleInfo) (errs []error) {
2149 // The cycle list is in reverse order because all the 'check' calls append
2150 // their own module to the list.
2151 errs = append(errs, &BlueprintError{
2152 Err: fmt.Errorf("encountered dependency cycle:"),
2153 Pos: cycle[len(cycle)-1].pos,
2154 })
2155
2156 // Iterate backwards through the cycle list.
2157 curModule := cycle[0]
2158 for i := len(cycle) - 1; i >= 0; i-- {
2159 nextModule := cycle[i]
2160 errs = append(errs, &BlueprintError{
2161 Err: fmt.Errorf(" %q depends on %q",
2162 curModule.Name(),
2163 nextModule.Name()),
2164 Pos: curModule.pos,
2165 })
2166 curModule = nextModule
2167 }
2168
2169 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002170}
2171
2172// updateDependencies recursively walks the module dependency graph and updates
2173// additional fields based on the dependencies. It builds a sorted list of modules
2174// such that dependencies of a module always appear first, and populates reverse
2175// dependency links and counts of total dependencies. It also reports errors when
2176// it encounters dependency cycles. This should called after resolveDependencies,
2177// as well as after any mutator pass has called addDependency
2178func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002179 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002180 visited := make(map[*moduleInfo]bool) // modules that were already checked
2181 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002182
Colin Cross7addea32015-03-11 15:43:52 -07002183 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002184
Colin Cross7addea32015-03-11 15:43:52 -07002185 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002186
Colin Cross7addea32015-03-11 15:43:52 -07002187 check = func(module *moduleInfo) []*moduleInfo {
2188 visited[module] = true
2189 checking[module] = true
2190 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002191
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002192 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2193 module.reverseDeps = module.reverseDeps[:0]
2194 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002195
2196 // Add an implicit dependency ordering on all earlier modules in the same module group
2197 for _, dep := range module.group.modules {
2198 if dep == module {
2199 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002200 }
Colin Cross5df74a82020-08-24 16:18:21 -07002201 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002202 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002203 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002204 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002205
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002206 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002207 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002208 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2209 for _, exists := range module.forwardDeps {
2210 if dep.module == exists {
2211 continue outer
2212 }
2213 }
2214 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002215 }
2216
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002217 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002218 if checking[dep] {
2219 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002220 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002221 }
2222
2223 if !visited[dep] {
2224 cycle := check(dep)
2225 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002226 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002227 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002228 // for generating the errors.
2229 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002230
2231 // We can continue processing this module's children to
2232 // find more cycles. Since all the modules that were
2233 // part of the found cycle were marked as visited we
2234 // won't run into that cycle again.
2235 } else {
2236 // We're not the "start" of the cycle, so we just append
2237 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002238 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002239 }
2240 }
2241 }
Colin Cross691a60d2015-01-07 18:08:56 -08002242
Colin Cross7addea32015-03-11 15:43:52 -07002243 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002244 }
2245
Colin Cross7addea32015-03-11 15:43:52 -07002246 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002247
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002248 return nil
2249 }
2250
Colin Cross7addea32015-03-11 15:43:52 -07002251 for _, module := range c.moduleInfo {
2252 if !visited[module] {
2253 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002254 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002255 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002256 panic("inconceivable!")
2257 }
Colin Crossc4773d92020-08-25 17:12:59 -07002258 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002259 }
2260 }
2261 }
2262
Colin Cross7addea32015-03-11 15:43:52 -07002263 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002264
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002265 return
2266}
2267
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002268type jsonVariationMap map[string]string
2269
2270type jsonModuleName struct {
2271 Name string
2272 Variations jsonVariationMap
2273 DependencyVariations jsonVariationMap
2274}
2275
2276type jsonDep struct {
2277 jsonModuleName
2278 Tag string
2279}
2280
2281type jsonModule struct {
2282 jsonModuleName
2283 Deps []jsonDep
2284 Type string
2285 Blueprint string
2286}
2287
2288func toJsonVariationMap(vm variationMap) jsonVariationMap {
2289 return jsonVariationMap(vm)
2290}
2291
2292func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2293 return &jsonModuleName{
2294 Name: m.Name(),
2295 Variations: toJsonVariationMap(m.variant.variations),
2296 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2297 }
2298}
2299
2300func jsonModuleFromModuleInfo(m *moduleInfo) *jsonModule {
2301 return &jsonModule{
2302 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2303 Deps: make([]jsonDep, 0),
2304 Type: m.typeName,
2305 Blueprint: m.relBlueprintsFile,
2306 }
2307}
2308
2309func (c *Context) PrintJSONGraph(w io.Writer) {
2310 modules := make([]*jsonModule, 0)
2311 for _, m := range c.modulesSorted {
2312 jm := jsonModuleFromModuleInfo(m)
2313 for _, d := range m.directDeps {
2314 jm.Deps = append(jm.Deps, jsonDep{
2315 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2316 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2317 })
2318 }
2319
2320 modules = append(modules, jm)
2321 }
2322
2323 json.NewEncoder(w).Encode(modules)
2324}
2325
Jamie Gennisd4e10182014-06-12 20:06:50 -07002326// PrepareBuildActions generates an internal representation of all the build
2327// actions that need to be performed. This process involves invoking the
2328// GenerateBuildActions method on each of the Module objects created during the
2329// parse phase and then on each of the registered Singleton objects.
2330//
2331// If the ResolveDependencies method has not already been called it is called
2332// automatically by this method.
2333//
2334// The config argument is made available to all of the Module and Singleton
2335// objects via the Config method on the ModuleContext and SingletonContext
2336// objects passed to GenerateBuildActions. It is also passed to the functions
2337// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2338// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002339//
2340// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002341// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2342// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2343// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002344
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002345func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002346 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2347 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002348
Colin Cross3a8c0252019-01-23 13:21:48 -08002349 if !c.dependenciesReady {
2350 var extraDeps []string
2351 extraDeps, errs = c.resolveDependencies(ctx, config)
2352 if len(errs) > 0 {
2353 return
2354 }
2355 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002356 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002357
Colin Cross3a8c0252019-01-23 13:21:48 -08002358 var depsModules []string
2359 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2360 if len(errs) > 0 {
2361 return
2362 }
2363
2364 var depsSingletons []string
2365 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2366 if len(errs) > 0 {
2367 return
2368 }
2369
2370 deps = append(deps, depsModules...)
2371 deps = append(deps, depsSingletons...)
2372
2373 if c.ninjaBuildDir != nil {
2374 err := c.liveGlobals.addNinjaStringDeps(c.ninjaBuildDir)
2375 if err != nil {
2376 errs = []error{err}
2377 return
2378 }
2379 }
2380
2381 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2382
2383 deps = append(deps, depsPackages...)
2384
Colin Cross92054a42021-01-21 16:49:25 -08002385 c.memoizeFullNames(c.liveGlobals, pkgNames)
2386
Colin Cross3a8c0252019-01-23 13:21:48 -08002387 // This will panic if it finds a problem since it's a programming error.
2388 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2389
2390 c.pkgNames = pkgNames
2391 c.globalVariables = c.liveGlobals.variables
2392 c.globalPools = c.liveGlobals.pools
2393 c.globalRules = c.liveGlobals.rules
2394
2395 c.buildActionsReady = true
2396 })
2397
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002398 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002399 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002400 }
2401
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002402 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002403}
2404
Colin Cross3a8c0252019-01-23 13:21:48 -08002405func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002406 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002407
Colin Cross3a8c0252019-01-23 13:21:48 -08002408 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2409 mutators = append(mutators, c.earlyMutatorInfo...)
2410 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002411
Colin Cross3a8c0252019-01-23 13:21:48 -08002412 for _, mutator := range mutators {
2413 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2414 var newDeps []string
2415 if mutator.topDownMutator != nil {
2416 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2417 } else if mutator.bottomUpMutator != nil {
2418 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2419 } else {
2420 panic("no mutator set on " + mutator.name)
2421 }
2422 if len(errs) > 0 {
2423 return
2424 }
2425 deps = append(deps, newDeps...)
2426 })
2427 if len(errs) > 0 {
2428 return
2429 }
Colin Crossc9028482014-12-18 16:28:54 -08002430 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002431 })
2432
2433 if len(errs) > 0 {
2434 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002435 }
2436
Colin Cross874a3462017-07-31 17:26:06 -07002437 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002438}
2439
Colin Cross3702ac72016-08-11 11:09:00 -07002440type mutatorDirection interface {
2441 run(mutator *mutatorInfo, ctx *mutatorContext)
2442 orderer() visitOrderer
2443 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002444}
2445
Colin Cross3702ac72016-08-11 11:09:00 -07002446type bottomUpMutatorImpl struct{}
2447
2448func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2449 mutator.bottomUpMutator(ctx)
2450}
2451
2452func (bottomUpMutatorImpl) orderer() visitOrderer {
2453 return bottomUpVisitor
2454}
2455
2456func (bottomUpMutatorImpl) String() string {
2457 return "bottom up mutator"
2458}
2459
2460type topDownMutatorImpl struct{}
2461
2462func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2463 mutator.topDownMutator(ctx)
2464}
2465
2466func (topDownMutatorImpl) orderer() visitOrderer {
2467 return topDownVisitor
2468}
2469
2470func (topDownMutatorImpl) String() string {
2471 return "top down mutator"
2472}
2473
2474var (
2475 topDownMutator topDownMutatorImpl
2476 bottomUpMutator bottomUpMutatorImpl
2477)
2478
Colin Cross49c279a2016-08-05 22:30:44 -07002479type reverseDep struct {
2480 module *moduleInfo
2481 dep depInfo
2482}
2483
Colin Cross3702ac72016-08-11 11:09:00 -07002484func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002485 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002486
2487 newModuleInfo := make(map[Module]*moduleInfo)
2488 for k, v := range c.moduleInfo {
2489 newModuleInfo[k] = v
2490 }
Colin Crossc9028482014-12-18 16:28:54 -08002491
Colin Cross0ce142c2016-12-09 10:29:05 -08002492 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002493 reverse []reverseDep
2494 rename []rename
2495 replace []replace
2496 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002497 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002498 }
2499
Colin Cross2c1f3d12016-04-11 15:47:28 -07002500 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002501 var rename []rename
2502 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002503 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002504
Colin Cross49c279a2016-08-05 22:30:44 -07002505 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002506 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002507 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002508 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002509
Colin Cross3702ac72016-08-11 11:09:00 -07002510 c.depsModified = 0
2511
Colin Crossc4773d92020-08-25 17:12:59 -07002512 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002513 if module.splitModules != nil {
2514 panic("split module found in sorted module list")
2515 }
2516
Colin Cross7addea32015-03-11 15:43:52 -07002517 mctx := &mutatorContext{
2518 baseModuleContext: baseModuleContext{
2519 context: c,
2520 config: config,
2521 module: module,
2522 },
Colin Crossc4773d92020-08-25 17:12:59 -07002523 name: mutator.name,
2524 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002525 }
Colin Crossc9028482014-12-18 16:28:54 -08002526
Colin Cross2da84922020-07-02 10:08:12 -07002527 module.startedMutator = mutator
2528
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002529 func() {
2530 defer func() {
2531 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002532 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002533 if err, ok := r.(panicError); ok {
2534 err.addIn(in)
2535 mctx.error(err)
2536 } else {
2537 mctx.error(newPanicErrorf(r, in))
2538 }
2539 }
2540 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002541 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002542 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002543
Colin Cross2da84922020-07-02 10:08:12 -07002544 module.finishedMutator = mutator
2545
Colin Cross7addea32015-03-11 15:43:52 -07002546 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002547 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002548 return true
Colin Cross7addea32015-03-11 15:43:52 -07002549 }
Colin Crossc9028482014-12-18 16:28:54 -08002550
Colin Cross5fe225f2017-07-28 15:22:46 -07002551 if len(mctx.newVariations) > 0 {
2552 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002553 }
2554
Colin Crossab0a83f2020-03-03 14:23:27 -08002555 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 -08002556 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002557 reverse: mctx.reverseDeps,
2558 replace: mctx.replace,
2559 rename: mctx.rename,
2560 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002561 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002562 }
Colin Cross49c279a2016-08-05 22:30:44 -07002563 }
2564
2565 return false
2566 }
2567
2568 // Process errs and reverseDeps in a single goroutine
2569 go func() {
2570 for {
2571 select {
2572 case newErrs := <-errsCh:
2573 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002574 case globalStateChange := <-globalStateCh:
2575 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002576 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2577 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002578 replace = append(replace, globalStateChange.replace...)
2579 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002580 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002581 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002582 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002583 for _, moduleOrAlias := range newVariations {
2584 if m := moduleOrAlias.module(); m != nil {
2585 newModuleInfo[m.logicModule] = m
2586 }
Colin Cross49c279a2016-08-05 22:30:44 -07002587 }
2588 case <-done:
2589 return
Colin Crossc9028482014-12-18 16:28:54 -08002590 }
2591 }
Colin Cross49c279a2016-08-05 22:30:44 -07002592 }()
Colin Crossc9028482014-12-18 16:28:54 -08002593
Colin Cross2da84922020-07-02 10:08:12 -07002594 c.startedMutator = mutator
2595
Colin Crossc4773d92020-08-25 17:12:59 -07002596 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002597 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002598 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002599 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002600 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002601 }
2602
Colin Crossc4773d92020-08-25 17:12:59 -07002603 if len(visitErrs) > 0 {
2604 return nil, visitErrs
2605 }
2606
Colin Cross2da84922020-07-02 10:08:12 -07002607 c.finishedMutators[mutator] = true
2608
Colin Cross49c279a2016-08-05 22:30:44 -07002609 done <- true
2610
2611 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002612 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002613 }
2614
2615 c.moduleInfo = newModuleInfo
2616
2617 for _, group := range c.moduleGroups {
2618 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002619 module := group.modules[i].module()
2620 if module == nil {
2621 // Existing alias, skip it
2622 continue
2623 }
Colin Cross49c279a2016-08-05 22:30:44 -07002624
2625 // Update module group to contain newly split variants
2626 if module.splitModules != nil {
2627 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2628 }
2629
2630 // Fix up any remaining dependencies on modules that were split into variants
2631 // by replacing them with the first variant
2632 for j, dep := range module.directDeps {
2633 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002634 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002635 }
2636 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002637
Colin Cross322cc012019-05-20 13:55:14 -07002638 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002639 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002640 }
2641
Colin Cross99bdb2a2019-03-29 16:35:02 -07002642 // Add in any new direct dependencies that were added by the mutator
2643 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2644 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002645 }
Colin Crossf7beb892019-11-13 20:11:14 -08002646
Colin Cross279489c2020-08-13 12:11:52 -07002647 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002648 for _, moduleOrAlias := range group.modules {
2649 if alias := moduleOrAlias.alias(); alias != nil {
2650 if alias.variant.variations.equal(variant.variations) {
2651 return alias.target
2652 }
Colin Cross279489c2020-08-13 12:11:52 -07002653 }
2654 }
2655 return nil
2656 }
2657
Colin Crossf7beb892019-11-13 20:11:14 -08002658 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002659 // Use a manual loop instead of range because len(group.modules) can
2660 // change inside the loop
2661 for i := 0; i < len(group.modules); i++ {
2662 if alias := group.modules[i].alias(); alias != nil {
2663 if alias.target.logicModule == nil {
2664 newTarget := findAliasTarget(alias.target.variant)
2665 if newTarget != nil {
2666 alias.target = newTarget
2667 } else {
2668 // The alias was left dangling, remove it.
2669 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2670 i--
2671 }
Colin Crossf7beb892019-11-13 20:11:14 -08002672 }
2673 }
2674 }
Colin Crossc9028482014-12-18 16:28:54 -08002675 }
2676
Colin Cross99bdb2a2019-03-29 16:35:02 -07002677 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002678 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002679 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002680 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002681 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002682 }
2683
Colin Crossaf4fd212017-07-28 14:32:36 -07002684 for _, module := range newModules {
2685 errs = c.addModule(module)
2686 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002687 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002688 }
2689 atomic.AddUint32(&c.depsModified, 1)
2690 }
2691
Colin Cross0ce142c2016-12-09 10:29:05 -08002692 errs = c.handleRenames(rename)
2693 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002694 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002695 }
2696
2697 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002698 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002699 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002700 }
2701
Colin Cross3702ac72016-08-11 11:09:00 -07002702 if c.depsModified > 0 {
2703 errs = c.updateDependencies()
2704 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002705 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002706 }
Colin Crossc9028482014-12-18 16:28:54 -08002707 }
2708
Colin Cross874a3462017-07-31 17:26:06 -07002709 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002710}
2711
Colin Cross910242b2016-04-11 15:41:52 -07002712// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2713// a mutator sets a non-property member variable on a module, which works until a later mutator
2714// creates variants of that module.
2715func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002716 type update struct {
2717 orig Module
2718 clone *moduleInfo
2719 }
Colin Cross7e723372018-03-28 11:50:12 -07002720 ch := make(chan update)
2721 doneCh := make(chan bool)
2722 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002723 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2724 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2725 origLogicModule := m.logicModule
2726 m.logicModule, m.properties = c.cloneLogicModule(m)
2727 ch <- update{origLogicModule, m}
2728 return false
2729 })
2730 if len(errs) > 0 {
2731 panic(errs)
2732 }
Colin Cross7e723372018-03-28 11:50:12 -07002733 doneCh <- true
2734 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002735
Colin Cross7e723372018-03-28 11:50:12 -07002736 done := false
2737 for !done {
2738 select {
2739 case <-doneCh:
2740 done = true
2741 case update := <-ch:
2742 delete(c.moduleInfo, update.orig)
2743 c.moduleInfo[update.clone.logicModule] = update.clone
2744 }
Colin Cross910242b2016-04-11 15:41:52 -07002745 }
2746}
2747
Colin Cross49c279a2016-08-05 22:30:44 -07002748// Removes modules[i] from the list and inserts newModules... where it was located, returning
2749// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002750func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002751 spliceSize := len(newModules)
2752 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002753 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002754 if cap(modules) >= len(modules)-1+len(newModules) {
2755 // We can fit the splice in the existing capacity, do everything in place
2756 dest = modules[:newLen]
2757 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002758 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002759 copy(dest, modules[:i])
2760 }
2761
2762 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002763 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002764
2765 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002766 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002767
Colin Cross49c279a2016-08-05 22:30:44 -07002768 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002769}
2770
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002771func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002772 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002773
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002774 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002775 var errs []error
2776
Colin Cross691a60d2015-01-07 18:08:56 -08002777 cancelCh := make(chan struct{})
2778 errsCh := make(chan []error)
2779 depsCh := make(chan []string)
2780
2781 go func() {
2782 for {
2783 select {
2784 case <-cancelCh:
2785 close(cancelCh)
2786 return
2787 case newErrs := <-errsCh:
2788 errs = append(errs, newErrs...)
2789 case newDeps := <-depsCh:
2790 deps = append(deps, newDeps...)
2791
2792 }
2793 }
2794 }()
2795
Colin Crossc4773d92020-08-25 17:12:59 -07002796 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2797 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2798 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2799 sanitizedName := toNinjaName(uniqueName)
Jeff Gaston0e907592017-12-01 17:10:52 -08002800
Colin Crossc4773d92020-08-25 17:12:59 -07002801 prefix := moduleNamespacePrefix(sanitizedName + "_" + module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002802
Colin Crossc4773d92020-08-25 17:12:59 -07002803 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2804 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2805 // just set it to nil.
2806 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002807
Colin Crossc4773d92020-08-25 17:12:59 -07002808 mctx := &moduleContext{
2809 baseModuleContext: baseModuleContext{
2810 context: c,
2811 config: config,
2812 module: module,
2813 },
2814 scope: scope,
2815 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002816 }
Colin Cross036a1df2015-12-17 15:49:30 -08002817
Colin Cross2da84922020-07-02 10:08:12 -07002818 mctx.module.startedGenerateBuildActions = true
2819
Colin Crossc4773d92020-08-25 17:12:59 -07002820 func() {
2821 defer func() {
2822 if r := recover(); r != nil {
2823 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2824 if err, ok := r.(panicError); ok {
2825 err.addIn(in)
2826 mctx.error(err)
2827 } else {
2828 mctx.error(newPanicErrorf(r, in))
2829 }
2830 }
2831 }()
2832 mctx.module.logicModule.GenerateBuildActions(mctx)
2833 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002834
Colin Cross2da84922020-07-02 10:08:12 -07002835 mctx.module.finishedGenerateBuildActions = true
2836
Colin Crossc4773d92020-08-25 17:12:59 -07002837 if len(mctx.errs) > 0 {
2838 errsCh <- mctx.errs
2839 return true
2840 }
2841
2842 if module.missingDeps != nil && !mctx.handledMissingDeps {
2843 var errs []error
2844 for _, depName := range module.missingDeps {
2845 errs = append(errs, c.missingDependencyError(module, depName))
2846 }
2847 errsCh <- errs
2848 return true
2849 }
2850
2851 depsCh <- mctx.ninjaFileDeps
2852
2853 newErrs := c.processLocalBuildActions(&module.actionDefs,
2854 &mctx.actionDefs, liveGlobals)
2855 if len(newErrs) > 0 {
2856 errsCh <- newErrs
2857 return true
2858 }
2859 return false
2860 })
Colin Cross691a60d2015-01-07 18:08:56 -08002861
2862 cancelCh <- struct{}{}
2863 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002864
Colin Crossc4773d92020-08-25 17:12:59 -07002865 errs = append(errs, visitErrs...)
2866
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002867 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002868}
2869
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002870func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002871 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002872
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002873 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002874 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002875
Colin Cross5f03f112017-11-07 13:29:54 -08002876 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002877 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2878 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2879 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002880 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002881
2882 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002883 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002884 context: c,
2885 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002886 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002887 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002888 }
2889
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002890 func() {
2891 defer func() {
2892 if r := recover(); r != nil {
2893 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2894 if err, ok := r.(panicError); ok {
2895 err.addIn(in)
2896 sctx.error(err)
2897 } else {
2898 sctx.error(newPanicErrorf(r, in))
2899 }
2900 }
2901 }()
2902 info.singleton.GenerateBuildActions(sctx)
2903 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002904
2905 if len(sctx.errs) > 0 {
2906 errs = append(errs, sctx.errs...)
2907 if len(errs) > maxErrors {
2908 break
2909 }
2910 continue
2911 }
2912
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002913 deps = append(deps, sctx.ninjaFileDeps...)
2914
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002915 newErrs := c.processLocalBuildActions(&info.actionDefs,
2916 &sctx.actionDefs, liveGlobals)
2917 errs = append(errs, newErrs...)
2918 if len(errs) > maxErrors {
2919 break
2920 }
2921 }
2922
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002923 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002924}
2925
2926func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2927 liveGlobals *liveTracker) []error {
2928
2929 var errs []error
2930
2931 // First we go through and add everything referenced by the module's
2932 // buildDefs to the live globals set. This will end up adding the live
2933 // locals to the set as well, but we'll take them out after.
2934 for _, def := range in.buildDefs {
2935 err := liveGlobals.AddBuildDefDeps(def)
2936 if err != nil {
2937 errs = append(errs, err)
2938 }
2939 }
2940
2941 if len(errs) > 0 {
2942 return errs
2943 }
2944
Colin Crossc9028482014-12-18 16:28:54 -08002945 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002946
2947 // We use the now-incorrect set of live "globals" to determine which local
2948 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002949 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002950 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002951 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002952 if isLive {
2953 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002954 }
2955 }
2956
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002957 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002958 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002959 if isLive {
2960 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002961 }
2962 }
2963
2964 return nil
2965}
2966
Colin Cross9607a9f2018-06-20 11:16:37 -07002967func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07002968 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07002969
2970 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002971 var visiting *moduleInfo
2972
2973 defer func() {
2974 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07002975 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
2976 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002977 }
2978 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07002979
2980 var walk func(module *moduleInfo)
2981 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002982 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07002983 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002984 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07002985 recurse := true
2986 if visitDown != nil {
2987 recurse = visitDown(dep, module)
2988 }
Colin Cross526e02f2018-06-21 13:31:53 -07002989 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002990 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01002991 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07002992 }
Colin Crossbafd5f52016-08-06 22:52:01 -07002993 if visitUp != nil {
2994 visitUp(dep, module)
2995 }
Yuchen Wu222e2452015-10-06 14:03:27 -07002996 }
2997 }
2998 }
2999
3000 walk(topModule)
3001}
3002
Colin Cross9cfd1982016-10-11 09:58:53 -07003003type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003004 from, to *moduleInfo
3005 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003006}
3007
Colin Crossc4e5b812016-10-12 10:45:05 -07003008type rename struct {
3009 group *moduleGroup
3010 name string
3011}
3012
Colin Cross0ce142c2016-12-09 10:29:05 -08003013func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003014 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003015
Colin Crossd03b59d2019-11-13 20:10:12 -08003016 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003017 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003018 }
3019
Colin Crossd03b59d2019-11-13 20:10:12 -08003020 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003021 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003022 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003023 }
3024 }
3025
Colin Cross0ce142c2016-12-09 10:29:05 -08003026 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003027}
3028
Colin Cross0ce142c2016-12-09 10:29:05 -08003029func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003030 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003031 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003032 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003033 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003034 continue
3035 }
3036
Jeff Gastond70bf752017-11-10 15:12:08 -08003037 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003038 }
3039
Colin Cross0ce142c2016-12-09 10:29:05 -08003040 return errs
3041}
3042
3043func (c *Context) handleReplacements(replacements []replace) []error {
3044 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003045 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003046 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003047 for _, m := range replace.from.reverseDeps {
3048 for i, d := range m.directDeps {
3049 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003050 // If the replacement has a predicate then check it.
3051 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3052 m.directDeps[i].module = replace.to
3053 changedDeps = true
3054 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003055 }
3056 }
3057 }
3058
Colin Cross9cfd1982016-10-11 09:58:53 -07003059 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003060
Paul Duffin8969cb62020-06-30 12:15:26 +01003061 if changedDeps {
3062 atomic.AddUint32(&c.depsModified, 1)
3063 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003064 return errs
3065}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003066
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003067func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3068 if depVariations != nil {
3069 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3070 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003071 if c.allowMissingDependencies {
3072 module.missingDeps = append(module.missingDeps, depName)
3073 return nil
3074 }
3075 return []error{c.missingDependencyError(module, depName)}
3076}
3077
3078func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3079 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3080
3081 return &BlueprintError{
3082 Err: err,
3083 Pos: module.pos,
3084 }
3085}
3086
Colin Crossd03b59d2019-11-13 20:10:12 -08003087func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003088 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3089 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003090 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003091 }
3092 return nil
3093}
3094
Jeff Gastond70bf752017-11-10 15:12:08 -08003095func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003096 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003097 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3098 result := make([]*moduleGroup, 0, len(wrappers))
3099 for _, group := range wrappers {
3100 result = append(result, group.moduleGroup)
3101 }
3102 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003103 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003104
3105 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003106 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003107 }
3108
Jeff Gastond70bf752017-11-10 15:12:08 -08003109 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003110}
3111
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003112func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003113 var module *moduleInfo
3114
3115 defer func() {
3116 if r := recover(); r != nil {
3117 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3118 funcName(visit), module))
3119 }
3120 }()
3121
Jeff Gastond70bf752017-11-10 15:12:08 -08003122 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003123 for _, moduleOrAlias := range moduleGroup.modules {
3124 if module = moduleOrAlias.module(); module != nil {
3125 visit(module.logicModule)
3126 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003127 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003128 }
3129}
3130
3131func (c *Context) visitAllModulesIf(pred func(Module) bool,
3132 visit func(Module)) {
3133
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003134 var module *moduleInfo
3135
3136 defer func() {
3137 if r := recover(); r != nil {
3138 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3139 funcName(pred), funcName(visit), module))
3140 }
3141 }()
3142
Jeff Gastond70bf752017-11-10 15:12:08 -08003143 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003144 for _, moduleOrAlias := range moduleGroup.modules {
3145 if module = moduleOrAlias.module(); module != nil {
3146 if pred(module.logicModule) {
3147 visit(module.logicModule)
3148 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003149 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003150 }
3151 }
3152}
3153
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003154func (c *Context) visitAllModuleVariants(module *moduleInfo,
3155 visit func(Module)) {
3156
3157 var variant *moduleInfo
3158
3159 defer func() {
3160 if r := recover(); r != nil {
3161 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3162 module, funcName(visit), variant))
3163 }
3164 }()
3165
Colin Cross5df74a82020-08-24 16:18:21 -07003166 for _, moduleOrAlias := range module.group.modules {
3167 if variant = moduleOrAlias.module(); variant != nil {
3168 visit(variant.logicModule)
3169 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003170 }
3171}
3172
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003173func (c *Context) requireNinjaVersion(major, minor, micro int) {
3174 if major != 1 {
3175 panic("ninja version with major version != 1 not supported")
3176 }
3177 if c.requiredNinjaMinor < minor {
3178 c.requiredNinjaMinor = minor
3179 c.requiredNinjaMicro = micro
3180 }
3181 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3182 c.requiredNinjaMicro = micro
3183 }
3184}
3185
Colin Cross2ce594e2020-01-29 12:58:03 -08003186func (c *Context) setNinjaBuildDir(value ninjaString) {
Colin Crossa2599452015-11-18 16:01:01 -08003187 if c.ninjaBuildDir == nil {
3188 c.ninjaBuildDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003189 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003190}
3191
3192func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003193 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003194
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003195 pkgs := make(map[string]*packageContext)
3196 pkgNames := make(map[*packageContext]string)
3197 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003198
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003199 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003200 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003201 // This is a built-in rule and has no package.
3202 return
3203 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003204 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003205 // We've already processed this package.
3206 return
3207 }
3208
Jamie Gennis2fb20952014-10-03 02:49:58 -07003209 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003210 if present {
3211 // Short name collision. Both this package and the one that's
3212 // already there need to use their full names. We leave the short
3213 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003214 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003215 longPkgNames[otherPkg] = true
3216 } else {
3217 // No collision so far. Tentatively set the package's name to be
3218 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003219 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003220 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003221 }
3222 }
3223
3224 // We try to give all packages their short name, but when we get collisions
3225 // we need to use the full unique package name.
3226 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003227 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003228 }
3229 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003230 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003231 }
3232 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003233 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003234 }
3235
3236 // Add the packages that had collisions using their full unique names. This
3237 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003238 for pctx := range longPkgNames {
3239 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003240 }
3241
Dan Willemsena481ae22015-12-18 15:18:03 -08003242 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3243 deps := []string{}
3244 for _, pkg := range pkgs {
3245 deps = append(deps, pkg.ninjaFileDeps...)
3246 }
3247
3248 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003249}
3250
Colin Cross92054a42021-01-21 16:49:25 -08003251// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3252// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3253// are used much more than once.
3254func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3255 for v := range liveGlobals.variables {
3256 v.memoizeFullName(pkgNames)
3257 }
3258 for r := range liveGlobals.rules {
3259 r.memoizeFullName(pkgNames)
3260 }
3261 for p := range liveGlobals.pools {
3262 p.memoizeFullName(pkgNames)
3263 }
3264}
3265
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003266func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003267 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003268
3269 visited := make(map[Variable]bool) // variables that were already checked
3270 checking := make(map[Variable]bool) // variables actively being checked
3271
3272 var check func(v Variable) []Variable
3273
3274 check = func(v Variable) []Variable {
3275 visited[v] = true
3276 checking[v] = true
3277 defer delete(checking, v)
3278
3279 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003280 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003281 if checking[dep] {
3282 // This is a cycle.
3283 return []Variable{dep, v}
3284 }
3285
3286 if !visited[dep] {
3287 cycle := check(dep)
3288 if cycle != nil {
3289 if cycle[0] == v {
3290 // We are the "start" of the cycle, so we're responsible
3291 // for generating the errors. The cycle list is in
3292 // reverse order because all the 'check' calls append
3293 // their own module to the list.
3294 msgs := []string{"detected variable reference cycle:"}
3295
3296 // Iterate backwards through the cycle list.
3297 curName := v.fullName(pkgNames)
3298 curValue := value.Value(pkgNames)
3299 for i := len(cycle) - 1; i >= 0; i-- {
3300 next := cycle[i]
3301 nextName := next.fullName(pkgNames)
3302 nextValue := variables[next].Value(pkgNames)
3303
3304 msgs = append(msgs, fmt.Sprintf(
3305 " %q depends on %q", curName, nextName))
3306 msgs = append(msgs, fmt.Sprintf(
3307 " [%s = %s]", curName, curValue))
3308
3309 curName = nextName
3310 curValue = nextValue
3311 }
3312
3313 // Variable reference cycles are a programming error,
3314 // not the fault of the Blueprint file authors.
3315 panic(strings.Join(msgs, "\n"))
3316 } else {
3317 // We're not the "start" of the cycle, so we just append
3318 // our module to the list and return it.
3319 return append(cycle, v)
3320 }
3321 }
3322 }
3323 }
3324
3325 return nil
3326 }
3327
3328 for v := range variables {
3329 if !visited[v] {
3330 cycle := check(v)
3331 if cycle != nil {
3332 panic("inconceivable!")
3333 }
3334 }
3335 }
3336}
3337
Jamie Gennisaf435562014-10-27 22:34:56 -07003338// AllTargets returns a map all the build target names to the rule used to build
3339// them. This is the same information that is output by running 'ninja -t
3340// targets all'. If this is called before PrepareBuildActions successfully
3341// completes then ErrbuildActionsNotReady is returned.
3342func (c *Context) AllTargets() (map[string]string, error) {
3343 if !c.buildActionsReady {
3344 return nil, ErrBuildActionsNotReady
3345 }
3346
3347 targets := map[string]string{}
3348
3349 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003350 for _, module := range c.moduleInfo {
3351 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003352 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003353 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003354 outputValue, err := output.Eval(c.globalVariables)
3355 if err != nil {
3356 return nil, err
3357 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003358 targets[outputValue] = ruleName
3359 }
3360 }
3361 }
3362
3363 // Collect all the singleton build targets.
3364 for _, info := range c.singletonInfo {
3365 for _, buildDef := range info.actionDefs.buildDefs {
3366 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003367 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003368 outputValue, err := output.Eval(c.globalVariables)
3369 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003370 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003371 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003372 targets[outputValue] = ruleName
3373 }
3374 }
3375 }
3376
3377 return targets, nil
3378}
3379
Colin Crossa2599452015-11-18 16:01:01 -08003380func (c *Context) NinjaBuildDir() (string, error) {
3381 if c.ninjaBuildDir != nil {
3382 return c.ninjaBuildDir.Eval(c.globalVariables)
3383 } else {
3384 return "", nil
3385 }
3386}
3387
Colin Cross4572edd2015-05-13 14:36:24 -07003388// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3389// property structs returned by the factory for that module type.
3390func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3391 ret := make(map[string][]interface{})
3392 for moduleType, factory := range c.moduleFactories {
3393 _, ret[moduleType] = factory()
3394 }
3395
3396 return ret
3397}
3398
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003399func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3400 ret := make(map[string]ModuleFactory)
3401 for k, v := range c.moduleFactories {
3402 ret[k] = v
3403 }
3404 return ret
3405}
3406
Colin Cross4572edd2015-05-13 14:36:24 -07003407func (c *Context) ModuleName(logicModule Module) string {
3408 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003409 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003410}
3411
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003412func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003413 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003414}
3415
Colin Cross8c602f72015-12-17 18:02:11 -08003416func (c *Context) ModuleSubDir(logicModule Module) string {
3417 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003418 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003419}
3420
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003421func (c *Context) ModuleType(logicModule Module) string {
3422 module := c.moduleInfo[logicModule]
3423 return module.typeName
3424}
3425
Colin Cross2da84922020-07-02 10:08:12 -07003426// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3427// provider was not set it returns the zero value of the type of the provider, which means the
3428// return value can always be type-asserted to the type of the provider. The return value should
3429// always be considered read-only. It panics if called before the appropriate mutator or
3430// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3431// copy of the value originally passed to SetProvider.
3432func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3433 module := c.moduleInfo[logicModule]
3434 value, _ := c.provider(module, provider)
3435 return value
3436}
3437
3438// ModuleHasProvider returns true if the provider for the given module has been set.
3439func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3440 module := c.moduleInfo[logicModule]
3441 _, ok := c.provider(module, provider)
3442 return ok
3443}
3444
Colin Cross4572edd2015-05-13 14:36:24 -07003445func (c *Context) BlueprintFile(logicModule Module) string {
3446 module := c.moduleInfo[logicModule]
3447 return module.relBlueprintsFile
3448}
3449
3450func (c *Context) ModuleErrorf(logicModule Module, format string,
3451 args ...interface{}) error {
3452
3453 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003454 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003455 Err: fmt.Errorf(format, args...),
3456 Pos: module.pos,
3457 }
3458}
3459
3460func (c *Context) VisitAllModules(visit func(Module)) {
3461 c.visitAllModules(visit)
3462}
3463
3464func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3465 visit func(Module)) {
3466
3467 c.visitAllModulesIf(pred, visit)
3468}
3469
Colin Cross080c1332017-03-17 13:09:05 -07003470func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3471 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003472
Colin Cross080c1332017-03-17 13:09:05 -07003473 var visiting *moduleInfo
3474
3475 defer func() {
3476 if r := recover(); r != nil {
3477 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3478 topModule, funcName(visit), visiting))
3479 }
3480 }()
3481
3482 for _, dep := range topModule.directDeps {
3483 visiting = dep.module
3484 visit(dep.module.logicModule)
3485 }
3486}
3487
3488func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3489 topModule := c.moduleInfo[module]
3490
3491 var visiting *moduleInfo
3492
3493 defer func() {
3494 if r := recover(); r != nil {
3495 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3496 topModule, funcName(pred), funcName(visit), visiting))
3497 }
3498 }()
3499
3500 for _, dep := range topModule.directDeps {
3501 visiting = dep.module
3502 if pred(dep.module.logicModule) {
3503 visit(dep.module.logicModule)
3504 }
3505 }
3506}
3507
3508func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003509 topModule := c.moduleInfo[module]
3510
3511 var visiting *moduleInfo
3512
3513 defer func() {
3514 if r := recover(); r != nil {
3515 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3516 topModule, funcName(visit), visiting))
3517 }
3518 }()
3519
Colin Cross9607a9f2018-06-20 11:16:37 -07003520 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003521 visiting = dep.module
3522 visit(dep.module.logicModule)
3523 })
Colin Cross4572edd2015-05-13 14:36:24 -07003524}
3525
Colin Cross080c1332017-03-17 13:09:05 -07003526func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003527 topModule := c.moduleInfo[module]
3528
3529 var visiting *moduleInfo
3530
3531 defer func() {
3532 if r := recover(); r != nil {
3533 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3534 topModule, funcName(pred), funcName(visit), visiting))
3535 }
3536 }()
3537
Colin Cross9607a9f2018-06-20 11:16:37 -07003538 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003539 if pred(dep.module.logicModule) {
3540 visiting = dep.module
3541 visit(dep.module.logicModule)
3542 }
3543 })
Colin Cross4572edd2015-05-13 14:36:24 -07003544}
3545
Colin Cross24ad5872015-11-17 16:22:29 -08003546func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003547 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003548}
3549
3550func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003551 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003552}
3553
3554func (c *Context) VisitAllModuleVariants(module Module,
3555 visit func(Module)) {
3556
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003557 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003558}
3559
Colin Cross9226d6c2019-02-25 18:07:44 -08003560// Singletons returns a list of all registered Singletons.
3561func (c *Context) Singletons() []Singleton {
3562 var ret []Singleton
3563 for _, s := range c.singletonInfo {
3564 ret = append(ret, s.singleton)
3565 }
3566 return ret
3567}
3568
3569// SingletonName returns the name that the given singleton was registered with.
3570func (c *Context) SingletonName(singleton Singleton) string {
3571 for _, s := range c.singletonInfo {
3572 if s.singleton == singleton {
3573 return s.name
3574 }
3575 }
3576 return ""
3577}
3578
Jamie Gennisd4e10182014-06-12 20:06:50 -07003579// WriteBuildFile writes the Ninja manifeset text for the generated build
3580// actions to w. If this is called before PrepareBuildActions successfully
3581// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003582func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003583 var err error
3584 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3585 if !c.buildActionsReady {
3586 err = ErrBuildActionsNotReady
3587 return
3588 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003589
Colin Cross3a8c0252019-01-23 13:21:48 -08003590 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003591
Colin Cross3a8c0252019-01-23 13:21:48 -08003592 err = c.writeBuildFileHeader(nw)
3593 if err != nil {
3594 return
3595 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003596
Colin Cross3a8c0252019-01-23 13:21:48 -08003597 err = c.writeNinjaRequiredVersion(nw)
3598 if err != nil {
3599 return
3600 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003601
Colin Cross3a8c0252019-01-23 13:21:48 -08003602 err = c.writeSubninjas(nw)
3603 if err != nil {
3604 return
3605 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003606
Colin Cross3a8c0252019-01-23 13:21:48 -08003607 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003608
Colin Cross3a8c0252019-01-23 13:21:48 -08003609 err = c.writeGlobalVariables(nw)
3610 if err != nil {
3611 return
3612 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003613
Colin Cross3a8c0252019-01-23 13:21:48 -08003614 err = c.writeGlobalPools(nw)
3615 if err != nil {
3616 return
3617 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003618
Colin Cross3a8c0252019-01-23 13:21:48 -08003619 err = c.writeBuildDir(nw)
3620 if err != nil {
3621 return
3622 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003623
Colin Cross3a8c0252019-01-23 13:21:48 -08003624 err = c.writeGlobalRules(nw)
3625 if err != nil {
3626 return
3627 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003628
Colin Cross3a8c0252019-01-23 13:21:48 -08003629 err = c.writeAllModuleActions(nw)
3630 if err != nil {
3631 return
3632 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003633
Colin Cross3a8c0252019-01-23 13:21:48 -08003634 err = c.writeAllSingletonActions(nw)
3635 if err != nil {
3636 return
3637 }
3638 })
3639
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003640 if err != nil {
3641 return err
3642 }
3643
3644 return nil
3645}
3646
Jamie Gennisc15544d2014-09-24 20:26:52 -07003647type pkgAssociation struct {
3648 PkgName string
3649 PkgPath string
3650}
3651
3652type pkgAssociationSorter struct {
3653 pkgs []pkgAssociation
3654}
3655
3656func (s *pkgAssociationSorter) Len() int {
3657 return len(s.pkgs)
3658}
3659
3660func (s *pkgAssociationSorter) Less(i, j int) bool {
3661 iName := s.pkgs[i].PkgName
3662 jName := s.pkgs[j].PkgName
3663 return iName < jName
3664}
3665
3666func (s *pkgAssociationSorter) Swap(i, j int) {
3667 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3668}
3669
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003670func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3671 headerTemplate := template.New("fileHeader")
3672 _, err := headerTemplate.Parse(fileHeaderTemplate)
3673 if err != nil {
3674 // This is a programming error.
3675 panic(err)
3676 }
3677
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003678 var pkgs []pkgAssociation
3679 maxNameLen := 0
3680 for pkg, name := range c.pkgNames {
3681 pkgs = append(pkgs, pkgAssociation{
3682 PkgName: name,
3683 PkgPath: pkg.pkgPath,
3684 })
3685 if len(name) > maxNameLen {
3686 maxNameLen = len(name)
3687 }
3688 }
3689
3690 for i := range pkgs {
3691 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3692 }
3693
Jamie Gennisc15544d2014-09-24 20:26:52 -07003694 sort.Sort(&pkgAssociationSorter{pkgs})
3695
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003696 params := map[string]interface{}{
3697 "Pkgs": pkgs,
3698 }
3699
3700 buf := bytes.NewBuffer(nil)
3701 err = headerTemplate.Execute(buf, params)
3702 if err != nil {
3703 return err
3704 }
3705
3706 return nw.Comment(buf.String())
3707}
3708
3709func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3710 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3711 c.requiredNinjaMicro)
3712
3713 err := nw.Assign("ninja_required_version", value)
3714 if err != nil {
3715 return err
3716 }
3717
3718 return nw.BlankLine()
3719}
3720
Dan Willemsenab223a52018-07-05 21:56:59 -07003721func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3722 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003723 err := nw.Subninja(subninja)
3724 if err != nil {
3725 return err
3726 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003727 }
3728 return nw.BlankLine()
3729}
3730
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003731func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Colin Crossa2599452015-11-18 16:01:01 -08003732 if c.ninjaBuildDir != nil {
3733 err := nw.Assign("builddir", c.ninjaBuildDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003734 if err != nil {
3735 return err
3736 }
3737
3738 err = nw.BlankLine()
3739 if err != nil {
3740 return err
3741 }
3742 }
3743 return nil
3744}
3745
Jamie Gennisc15544d2014-09-24 20:26:52 -07003746type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003747 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003748}
3749
Jamie Gennisc15544d2014-09-24 20:26:52 -07003750type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003751 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003752 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003753}
3754
Jamie Gennisc15544d2014-09-24 20:26:52 -07003755func (s *globalEntitySorter) Len() int {
3756 return len(s.entities)
3757}
3758
3759func (s *globalEntitySorter) Less(i, j int) bool {
3760 iName := s.entities[i].fullName(s.pkgNames)
3761 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003762 return iName < jName
3763}
3764
Jamie Gennisc15544d2014-09-24 20:26:52 -07003765func (s *globalEntitySorter) Swap(i, j int) {
3766 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003767}
3768
3769func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3770 visited := make(map[Variable]bool)
3771
3772 var walk func(v Variable) error
3773 walk = func(v Variable) error {
3774 visited[v] = true
3775
3776 // First visit variables on which this variable depends.
3777 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003778 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003779 if !visited[dep] {
3780 err := walk(dep)
3781 if err != nil {
3782 return err
3783 }
3784 }
3785 }
3786
3787 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3788 if err != nil {
3789 return err
3790 }
3791
3792 err = nw.BlankLine()
3793 if err != nil {
3794 return err
3795 }
3796
3797 return nil
3798 }
3799
Jamie Gennisc15544d2014-09-24 20:26:52 -07003800 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3801 for variable := range c.globalVariables {
3802 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003803 }
3804
Jamie Gennisc15544d2014-09-24 20:26:52 -07003805 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003806
Jamie Gennisc15544d2014-09-24 20:26:52 -07003807 for _, entity := range globalVariables {
3808 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003809 if !visited[v] {
3810 err := walk(v)
3811 if err != nil {
3812 return nil
3813 }
3814 }
3815 }
3816
3817 return nil
3818}
3819
3820func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003821 globalPools := make([]globalEntity, 0, len(c.globalPools))
3822 for pool := range c.globalPools {
3823 globalPools = append(globalPools, pool)
3824 }
3825
3826 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3827
3828 for _, entity := range globalPools {
3829 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003830 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003831 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003832 err := def.WriteTo(nw, name)
3833 if err != nil {
3834 return err
3835 }
3836
3837 err = nw.BlankLine()
3838 if err != nil {
3839 return err
3840 }
3841 }
3842
3843 return nil
3844}
3845
3846func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003847 globalRules := make([]globalEntity, 0, len(c.globalRules))
3848 for rule := range c.globalRules {
3849 globalRules = append(globalRules, rule)
3850 }
3851
3852 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3853
3854 for _, entity := range globalRules {
3855 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003856 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003857 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003858 err := def.WriteTo(nw, name, c.pkgNames)
3859 if err != nil {
3860 return err
3861 }
3862
3863 err = nw.BlankLine()
3864 if err != nil {
3865 return err
3866 }
3867 }
3868
3869 return nil
3870}
3871
Colin Cross2c1f3d12016-04-11 15:47:28 -07003872type depSorter []depInfo
3873
3874func (s depSorter) Len() int {
3875 return len(s)
3876}
3877
3878func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003879 iName := s[i].module.Name()
3880 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003881 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003882 iName = s[i].module.variant.name
3883 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003884 }
3885 return iName < jName
3886}
3887
3888func (s depSorter) Swap(i, j int) {
3889 s[i], s[j] = s[j], s[i]
3890}
3891
Jeff Gaston0e907592017-12-01 17:10:52 -08003892type moduleSorter struct {
3893 modules []*moduleInfo
3894 nameInterface NameInterface
3895}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003896
Colin Crossab6d7902015-03-11 16:17:52 -07003897func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003898 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003899}
3900
Colin Crossab6d7902015-03-11 16:17:52 -07003901func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003902 iMod := s.modules[i]
3903 jMod := s.modules[j]
3904 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3905 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003906 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003907 iVariantName := s.modules[i].variant.name
3908 jVariantName := s.modules[j].variant.name
3909 if iVariantName == jVariantName {
3910 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3911 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3912 } else {
3913 return iVariantName < jVariantName
3914 }
3915 } else {
3916 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003917 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003918}
3919
Colin Crossab6d7902015-03-11 16:17:52 -07003920func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003921 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003922}
3923
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003924func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3925 headerTemplate := template.New("moduleHeader")
3926 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3927 if err != nil {
3928 // This is a programming error.
3929 panic(err)
3930 }
3931
Colin Crossab6d7902015-03-11 16:17:52 -07003932 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3933 for _, module := range c.moduleInfo {
3934 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003935 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003936 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003937
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003938 buf := bytes.NewBuffer(nil)
3939
Colin Crossab6d7902015-03-11 16:17:52 -07003940 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003941 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3942 continue
3943 }
3944
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003945 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003946
3947 // In order to make the bootstrap build manifest independent of the
3948 // build dir we need to output the Blueprints file locations in the
3949 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003950 relPos := module.pos
3951 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003952
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003953 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003954 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003955 factoryName := factoryFunc.Name()
3956
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003957 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003958 "name": module.Name(),
3959 "typeName": module.typeName,
3960 "goFactory": factoryName,
3961 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07003962 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003963 }
3964 err = headerTemplate.Execute(buf, infoMap)
3965 if err != nil {
3966 return err
3967 }
3968
3969 err = nw.Comment(buf.String())
3970 if err != nil {
3971 return err
3972 }
3973
3974 err = nw.BlankLine()
3975 if err != nil {
3976 return err
3977 }
3978
Colin Crossab6d7902015-03-11 16:17:52 -07003979 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003980 if err != nil {
3981 return err
3982 }
3983
3984 err = nw.BlankLine()
3985 if err != nil {
3986 return err
3987 }
3988 }
3989
3990 return nil
3991}
3992
3993func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
3994 headerTemplate := template.New("singletonHeader")
3995 _, err := headerTemplate.Parse(singletonHeaderTemplate)
3996 if err != nil {
3997 // This is a programming error.
3998 panic(err)
3999 }
4000
4001 buf := bytes.NewBuffer(nil)
4002
Yuchen Wub9103ef2015-08-25 17:58:17 -07004003 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004004 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4005 continue
4006 }
4007
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004008 // Get the name of the factory function for the module.
4009 factory := info.factory
4010 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4011 factoryName := factoryFunc.Name()
4012
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004013 buf.Reset()
4014 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004015 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004016 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004017 }
4018 err = headerTemplate.Execute(buf, infoMap)
4019 if err != nil {
4020 return err
4021 }
4022
4023 err = nw.Comment(buf.String())
4024 if err != nil {
4025 return err
4026 }
4027
4028 err = nw.BlankLine()
4029 if err != nil {
4030 return err
4031 }
4032
4033 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4034 if err != nil {
4035 return err
4036 }
4037
4038 err = nw.BlankLine()
4039 if err != nil {
4040 return err
4041 }
4042 }
4043
4044 return nil
4045}
4046
4047func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4048 defs *localBuildActions) error {
4049
4050 // Write the local variable assignments.
4051 for _, v := range defs.variables {
4052 // A localVariable doesn't need the package names or config to
4053 // determine its name or value.
4054 name := v.fullName(nil)
4055 value, err := v.value(nil)
4056 if err != nil {
4057 panic(err)
4058 }
4059 err = nw.Assign(name, value.Value(c.pkgNames))
4060 if err != nil {
4061 return err
4062 }
4063 }
4064
4065 if len(defs.variables) > 0 {
4066 err := nw.BlankLine()
4067 if err != nil {
4068 return err
4069 }
4070 }
4071
4072 // Write the local rules.
4073 for _, r := range defs.rules {
4074 // A localRule doesn't need the package names or config to determine
4075 // its name or definition.
4076 name := r.fullName(nil)
4077 def, err := r.def(nil)
4078 if err != nil {
4079 panic(err)
4080 }
4081
4082 err = def.WriteTo(nw, name, c.pkgNames)
4083 if err != nil {
4084 return err
4085 }
4086
4087 err = nw.BlankLine()
4088 if err != nil {
4089 return err
4090 }
4091 }
4092
4093 // Write the build definitions.
4094 for _, buildDef := range defs.buildDefs {
4095 err := buildDef.WriteTo(nw, c.pkgNames)
4096 if err != nil {
4097 return err
4098 }
4099
4100 if len(buildDef.Args) > 0 {
4101 err = nw.BlankLine()
4102 if err != nil {
4103 return err
4104 }
4105 }
4106 }
4107
4108 return nil
4109}
4110
Colin Cross5df74a82020-08-24 16:18:21 -07004111func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004112 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004113 if a == b {
4114 return false
4115 }
Colin Cross65569e42015-03-10 20:08:19 -07004116 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004117 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004118 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004119 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004120 return found
4121 }
4122 }
4123
4124 missing := a
4125 if found {
4126 missing = b
4127 }
4128 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4129}
4130
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004131type panicError struct {
4132 panic interface{}
4133 stack []byte
4134 in string
4135}
4136
4137func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4138 buf := make([]byte, 4096)
4139 count := runtime.Stack(buf, false)
4140 return panicError{
4141 panic: panic,
4142 in: fmt.Sprintf(in, a...),
4143 stack: buf[:count],
4144 }
4145}
4146
4147func (p panicError) Error() string {
4148 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4149}
4150
4151func (p *panicError) addIn(in string) {
4152 p.in += " in " + in
4153}
4154
4155func funcName(f interface{}) string {
4156 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4157}
4158
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004159var fileHeaderTemplate = `******************************************************************************
4160*** This file is generated and should not be edited ***
4161******************************************************************************
4162{{if .Pkgs}}
4163This file contains variables, rules, and pools with name prefixes indicating
4164they were generated by the following Go packages:
4165{{range .Pkgs}}
4166 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4167
4168`
4169
4170var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004171Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004172Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004173Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004174Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004175Defined: {{.pos}}
4176`
4177
4178var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4179Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004180Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004181`