blob: f55b4b6f02e92658b87c7d0e337200cb6e0b333a [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{
Colin Crosse5ff7702021-04-27 15:33:49 -07002161 Err: fmt.Errorf(" %s depends on %s",
2162 curModule, nextModule),
Colin Crossc4773d92020-08-25 17:12:59 -07002163 Pos: curModule.pos,
2164 })
2165 curModule = nextModule
2166 }
2167
2168 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002169}
2170
2171// updateDependencies recursively walks the module dependency graph and updates
2172// additional fields based on the dependencies. It builds a sorted list of modules
2173// such that dependencies of a module always appear first, and populates reverse
2174// dependency links and counts of total dependencies. It also reports errors when
2175// it encounters dependency cycles. This should called after resolveDependencies,
2176// as well as after any mutator pass has called addDependency
2177func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002178 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002179 visited := make(map[*moduleInfo]bool) // modules that were already checked
2180 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002181
Colin Cross7addea32015-03-11 15:43:52 -07002182 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002183
Colin Cross7addea32015-03-11 15:43:52 -07002184 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002185
Colin Cross7addea32015-03-11 15:43:52 -07002186 check = func(module *moduleInfo) []*moduleInfo {
2187 visited[module] = true
2188 checking[module] = true
2189 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002190
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002191 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2192 module.reverseDeps = module.reverseDeps[:0]
2193 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002194
2195 // Add an implicit dependency ordering on all earlier modules in the same module group
2196 for _, dep := range module.group.modules {
2197 if dep == module {
2198 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002199 }
Colin Cross5df74a82020-08-24 16:18:21 -07002200 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002201 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002202 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002203 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002204
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002205 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002206 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002207 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2208 for _, exists := range module.forwardDeps {
2209 if dep.module == exists {
2210 continue outer
2211 }
2212 }
2213 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002214 }
2215
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002216 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002217 if checking[dep] {
2218 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002219 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002220 }
2221
2222 if !visited[dep] {
2223 cycle := check(dep)
2224 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002225 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002226 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002227 // for generating the errors.
2228 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002229
2230 // We can continue processing this module's children to
2231 // find more cycles. Since all the modules that were
2232 // part of the found cycle were marked as visited we
2233 // won't run into that cycle again.
2234 } else {
2235 // We're not the "start" of the cycle, so we just append
2236 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002237 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002238 }
2239 }
2240 }
Colin Cross691a60d2015-01-07 18:08:56 -08002241
Colin Cross7addea32015-03-11 15:43:52 -07002242 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002243 }
2244
Colin Cross7addea32015-03-11 15:43:52 -07002245 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002246
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002247 return nil
2248 }
2249
Colin Cross7addea32015-03-11 15:43:52 -07002250 for _, module := range c.moduleInfo {
2251 if !visited[module] {
2252 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002253 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002254 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002255 panic("inconceivable!")
2256 }
Colin Crossc4773d92020-08-25 17:12:59 -07002257 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002258 }
2259 }
2260 }
2261
Colin Cross7addea32015-03-11 15:43:52 -07002262 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002263
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002264 return
2265}
2266
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002267type jsonVariationMap map[string]string
2268
2269type jsonModuleName struct {
2270 Name string
2271 Variations jsonVariationMap
2272 DependencyVariations jsonVariationMap
2273}
2274
2275type jsonDep struct {
2276 jsonModuleName
2277 Tag string
2278}
2279
2280type jsonModule struct {
2281 jsonModuleName
2282 Deps []jsonDep
2283 Type string
2284 Blueprint string
2285}
2286
2287func toJsonVariationMap(vm variationMap) jsonVariationMap {
2288 return jsonVariationMap(vm)
2289}
2290
2291func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2292 return &jsonModuleName{
2293 Name: m.Name(),
2294 Variations: toJsonVariationMap(m.variant.variations),
2295 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2296 }
2297}
2298
2299func jsonModuleFromModuleInfo(m *moduleInfo) *jsonModule {
2300 return &jsonModule{
2301 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2302 Deps: make([]jsonDep, 0),
2303 Type: m.typeName,
2304 Blueprint: m.relBlueprintsFile,
2305 }
2306}
2307
2308func (c *Context) PrintJSONGraph(w io.Writer) {
2309 modules := make([]*jsonModule, 0)
2310 for _, m := range c.modulesSorted {
2311 jm := jsonModuleFromModuleInfo(m)
2312 for _, d := range m.directDeps {
2313 jm.Deps = append(jm.Deps, jsonDep{
2314 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2315 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2316 })
2317 }
2318
2319 modules = append(modules, jm)
2320 }
2321
2322 json.NewEncoder(w).Encode(modules)
2323}
2324
Jamie Gennisd4e10182014-06-12 20:06:50 -07002325// PrepareBuildActions generates an internal representation of all the build
2326// actions that need to be performed. This process involves invoking the
2327// GenerateBuildActions method on each of the Module objects created during the
2328// parse phase and then on each of the registered Singleton objects.
2329//
2330// If the ResolveDependencies method has not already been called it is called
2331// automatically by this method.
2332//
2333// The config argument is made available to all of the Module and Singleton
2334// objects via the Config method on the ModuleContext and SingletonContext
2335// objects passed to GenerateBuildActions. It is also passed to the functions
2336// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2337// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002338//
2339// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002340// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2341// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2342// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002343
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002344func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002345 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2346 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002347
Colin Cross3a8c0252019-01-23 13:21:48 -08002348 if !c.dependenciesReady {
2349 var extraDeps []string
2350 extraDeps, errs = c.resolveDependencies(ctx, config)
2351 if len(errs) > 0 {
2352 return
2353 }
2354 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002355 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002356
Colin Cross3a8c0252019-01-23 13:21:48 -08002357 var depsModules []string
2358 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2359 if len(errs) > 0 {
2360 return
2361 }
2362
2363 var depsSingletons []string
2364 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2365 if len(errs) > 0 {
2366 return
2367 }
2368
2369 deps = append(deps, depsModules...)
2370 deps = append(deps, depsSingletons...)
2371
2372 if c.ninjaBuildDir != nil {
2373 err := c.liveGlobals.addNinjaStringDeps(c.ninjaBuildDir)
2374 if err != nil {
2375 errs = []error{err}
2376 return
2377 }
2378 }
2379
2380 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2381
2382 deps = append(deps, depsPackages...)
2383
Colin Cross92054a42021-01-21 16:49:25 -08002384 c.memoizeFullNames(c.liveGlobals, pkgNames)
2385
Colin Cross3a8c0252019-01-23 13:21:48 -08002386 // This will panic if it finds a problem since it's a programming error.
2387 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2388
2389 c.pkgNames = pkgNames
2390 c.globalVariables = c.liveGlobals.variables
2391 c.globalPools = c.liveGlobals.pools
2392 c.globalRules = c.liveGlobals.rules
2393
2394 c.buildActionsReady = true
2395 })
2396
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002397 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002398 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002399 }
2400
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002401 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002402}
2403
Colin Cross3a8c0252019-01-23 13:21:48 -08002404func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002405 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002406
Colin Cross3a8c0252019-01-23 13:21:48 -08002407 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2408 mutators = append(mutators, c.earlyMutatorInfo...)
2409 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002410
Colin Cross3a8c0252019-01-23 13:21:48 -08002411 for _, mutator := range mutators {
2412 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2413 var newDeps []string
2414 if mutator.topDownMutator != nil {
2415 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2416 } else if mutator.bottomUpMutator != nil {
2417 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2418 } else {
2419 panic("no mutator set on " + mutator.name)
2420 }
2421 if len(errs) > 0 {
2422 return
2423 }
2424 deps = append(deps, newDeps...)
2425 })
2426 if len(errs) > 0 {
2427 return
2428 }
Colin Crossc9028482014-12-18 16:28:54 -08002429 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002430 })
2431
2432 if len(errs) > 0 {
2433 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002434 }
2435
Colin Cross874a3462017-07-31 17:26:06 -07002436 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002437}
2438
Colin Cross3702ac72016-08-11 11:09:00 -07002439type mutatorDirection interface {
2440 run(mutator *mutatorInfo, ctx *mutatorContext)
2441 orderer() visitOrderer
2442 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002443}
2444
Colin Cross3702ac72016-08-11 11:09:00 -07002445type bottomUpMutatorImpl struct{}
2446
2447func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2448 mutator.bottomUpMutator(ctx)
2449}
2450
2451func (bottomUpMutatorImpl) orderer() visitOrderer {
2452 return bottomUpVisitor
2453}
2454
2455func (bottomUpMutatorImpl) String() string {
2456 return "bottom up mutator"
2457}
2458
2459type topDownMutatorImpl struct{}
2460
2461func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2462 mutator.topDownMutator(ctx)
2463}
2464
2465func (topDownMutatorImpl) orderer() visitOrderer {
2466 return topDownVisitor
2467}
2468
2469func (topDownMutatorImpl) String() string {
2470 return "top down mutator"
2471}
2472
2473var (
2474 topDownMutator topDownMutatorImpl
2475 bottomUpMutator bottomUpMutatorImpl
2476)
2477
Colin Cross49c279a2016-08-05 22:30:44 -07002478type reverseDep struct {
2479 module *moduleInfo
2480 dep depInfo
2481}
2482
Colin Cross3702ac72016-08-11 11:09:00 -07002483func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002484 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002485
2486 newModuleInfo := make(map[Module]*moduleInfo)
2487 for k, v := range c.moduleInfo {
2488 newModuleInfo[k] = v
2489 }
Colin Crossc9028482014-12-18 16:28:54 -08002490
Colin Cross0ce142c2016-12-09 10:29:05 -08002491 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002492 reverse []reverseDep
2493 rename []rename
2494 replace []replace
2495 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002496 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002497 }
2498
Colin Cross2c1f3d12016-04-11 15:47:28 -07002499 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002500 var rename []rename
2501 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002502 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002503
Colin Cross49c279a2016-08-05 22:30:44 -07002504 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002505 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002506 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002507 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002508
Colin Cross3702ac72016-08-11 11:09:00 -07002509 c.depsModified = 0
2510
Colin Crossc4773d92020-08-25 17:12:59 -07002511 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002512 if module.splitModules != nil {
2513 panic("split module found in sorted module list")
2514 }
2515
Colin Cross7addea32015-03-11 15:43:52 -07002516 mctx := &mutatorContext{
2517 baseModuleContext: baseModuleContext{
2518 context: c,
2519 config: config,
2520 module: module,
2521 },
Colin Crossc4773d92020-08-25 17:12:59 -07002522 name: mutator.name,
2523 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002524 }
Colin Crossc9028482014-12-18 16:28:54 -08002525
Colin Cross2da84922020-07-02 10:08:12 -07002526 module.startedMutator = mutator
2527
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002528 func() {
2529 defer func() {
2530 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002531 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002532 if err, ok := r.(panicError); ok {
2533 err.addIn(in)
2534 mctx.error(err)
2535 } else {
2536 mctx.error(newPanicErrorf(r, in))
2537 }
2538 }
2539 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002540 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002541 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002542
Colin Cross2da84922020-07-02 10:08:12 -07002543 module.finishedMutator = mutator
2544
Colin Cross7addea32015-03-11 15:43:52 -07002545 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002546 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002547 return true
Colin Cross7addea32015-03-11 15:43:52 -07002548 }
Colin Crossc9028482014-12-18 16:28:54 -08002549
Colin Cross5fe225f2017-07-28 15:22:46 -07002550 if len(mctx.newVariations) > 0 {
2551 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002552 }
2553
Colin Crossab0a83f2020-03-03 14:23:27 -08002554 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 -08002555 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002556 reverse: mctx.reverseDeps,
2557 replace: mctx.replace,
2558 rename: mctx.rename,
2559 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002560 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002561 }
Colin Cross49c279a2016-08-05 22:30:44 -07002562 }
2563
2564 return false
2565 }
2566
2567 // Process errs and reverseDeps in a single goroutine
2568 go func() {
2569 for {
2570 select {
2571 case newErrs := <-errsCh:
2572 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002573 case globalStateChange := <-globalStateCh:
2574 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002575 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2576 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002577 replace = append(replace, globalStateChange.replace...)
2578 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002579 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002580 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002581 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002582 for _, moduleOrAlias := range newVariations {
2583 if m := moduleOrAlias.module(); m != nil {
2584 newModuleInfo[m.logicModule] = m
2585 }
Colin Cross49c279a2016-08-05 22:30:44 -07002586 }
2587 case <-done:
2588 return
Colin Crossc9028482014-12-18 16:28:54 -08002589 }
2590 }
Colin Cross49c279a2016-08-05 22:30:44 -07002591 }()
Colin Crossc9028482014-12-18 16:28:54 -08002592
Colin Cross2da84922020-07-02 10:08:12 -07002593 c.startedMutator = mutator
2594
Colin Crossc4773d92020-08-25 17:12:59 -07002595 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002596 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002597 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002598 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002599 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002600 }
2601
Colin Crossc4773d92020-08-25 17:12:59 -07002602 if len(visitErrs) > 0 {
2603 return nil, visitErrs
2604 }
2605
Colin Cross2da84922020-07-02 10:08:12 -07002606 c.finishedMutators[mutator] = true
2607
Colin Cross49c279a2016-08-05 22:30:44 -07002608 done <- true
2609
2610 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002611 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002612 }
2613
2614 c.moduleInfo = newModuleInfo
2615
2616 for _, group := range c.moduleGroups {
2617 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002618 module := group.modules[i].module()
2619 if module == nil {
2620 // Existing alias, skip it
2621 continue
2622 }
Colin Cross49c279a2016-08-05 22:30:44 -07002623
2624 // Update module group to contain newly split variants
2625 if module.splitModules != nil {
2626 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2627 }
2628
2629 // Fix up any remaining dependencies on modules that were split into variants
2630 // by replacing them with the first variant
2631 for j, dep := range module.directDeps {
2632 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002633 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002634 }
2635 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002636
Colin Cross322cc012019-05-20 13:55:14 -07002637 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002638 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002639 }
2640
Colin Cross99bdb2a2019-03-29 16:35:02 -07002641 // Add in any new direct dependencies that were added by the mutator
2642 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2643 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002644 }
Colin Crossf7beb892019-11-13 20:11:14 -08002645
Colin Cross279489c2020-08-13 12:11:52 -07002646 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002647 for _, moduleOrAlias := range group.modules {
2648 if alias := moduleOrAlias.alias(); alias != nil {
2649 if alias.variant.variations.equal(variant.variations) {
2650 return alias.target
2651 }
Colin Cross279489c2020-08-13 12:11:52 -07002652 }
2653 }
2654 return nil
2655 }
2656
Colin Crossf7beb892019-11-13 20:11:14 -08002657 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002658 // Use a manual loop instead of range because len(group.modules) can
2659 // change inside the loop
2660 for i := 0; i < len(group.modules); i++ {
2661 if alias := group.modules[i].alias(); alias != nil {
2662 if alias.target.logicModule == nil {
2663 newTarget := findAliasTarget(alias.target.variant)
2664 if newTarget != nil {
2665 alias.target = newTarget
2666 } else {
2667 // The alias was left dangling, remove it.
2668 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2669 i--
2670 }
Colin Crossf7beb892019-11-13 20:11:14 -08002671 }
2672 }
2673 }
Colin Crossc9028482014-12-18 16:28:54 -08002674 }
2675
Colin Cross99bdb2a2019-03-29 16:35:02 -07002676 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002677 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002678 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002679 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002680 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002681 }
2682
Colin Crossaf4fd212017-07-28 14:32:36 -07002683 for _, module := range newModules {
2684 errs = c.addModule(module)
2685 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002686 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002687 }
2688 atomic.AddUint32(&c.depsModified, 1)
2689 }
2690
Colin Cross0ce142c2016-12-09 10:29:05 -08002691 errs = c.handleRenames(rename)
2692 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002693 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002694 }
2695
2696 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002697 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002698 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002699 }
2700
Colin Cross3702ac72016-08-11 11:09:00 -07002701 if c.depsModified > 0 {
2702 errs = c.updateDependencies()
2703 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002704 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002705 }
Colin Crossc9028482014-12-18 16:28:54 -08002706 }
2707
Colin Cross874a3462017-07-31 17:26:06 -07002708 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002709}
2710
Colin Cross910242b2016-04-11 15:41:52 -07002711// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2712// a mutator sets a non-property member variable on a module, which works until a later mutator
2713// creates variants of that module.
2714func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002715 type update struct {
2716 orig Module
2717 clone *moduleInfo
2718 }
Colin Cross7e723372018-03-28 11:50:12 -07002719 ch := make(chan update)
2720 doneCh := make(chan bool)
2721 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002722 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2723 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2724 origLogicModule := m.logicModule
2725 m.logicModule, m.properties = c.cloneLogicModule(m)
2726 ch <- update{origLogicModule, m}
2727 return false
2728 })
2729 if len(errs) > 0 {
2730 panic(errs)
2731 }
Colin Cross7e723372018-03-28 11:50:12 -07002732 doneCh <- true
2733 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002734
Colin Cross7e723372018-03-28 11:50:12 -07002735 done := false
2736 for !done {
2737 select {
2738 case <-doneCh:
2739 done = true
2740 case update := <-ch:
2741 delete(c.moduleInfo, update.orig)
2742 c.moduleInfo[update.clone.logicModule] = update.clone
2743 }
Colin Cross910242b2016-04-11 15:41:52 -07002744 }
2745}
2746
Colin Cross49c279a2016-08-05 22:30:44 -07002747// Removes modules[i] from the list and inserts newModules... where it was located, returning
2748// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002749func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002750 spliceSize := len(newModules)
2751 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002752 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002753 if cap(modules) >= len(modules)-1+len(newModules) {
2754 // We can fit the splice in the existing capacity, do everything in place
2755 dest = modules[:newLen]
2756 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002757 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002758 copy(dest, modules[:i])
2759 }
2760
2761 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002762 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002763
2764 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002765 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002766
Colin Cross49c279a2016-08-05 22:30:44 -07002767 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002768}
2769
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002770func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002771 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002772
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002773 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002774 var errs []error
2775
Colin Cross691a60d2015-01-07 18:08:56 -08002776 cancelCh := make(chan struct{})
2777 errsCh := make(chan []error)
2778 depsCh := make(chan []string)
2779
2780 go func() {
2781 for {
2782 select {
2783 case <-cancelCh:
2784 close(cancelCh)
2785 return
2786 case newErrs := <-errsCh:
2787 errs = append(errs, newErrs...)
2788 case newDeps := <-depsCh:
2789 deps = append(deps, newDeps...)
2790
2791 }
2792 }
2793 }()
2794
Colin Crossc4773d92020-08-25 17:12:59 -07002795 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2796 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2797 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2798 sanitizedName := toNinjaName(uniqueName)
Jeff Gaston0e907592017-12-01 17:10:52 -08002799
Colin Crossc4773d92020-08-25 17:12:59 -07002800 prefix := moduleNamespacePrefix(sanitizedName + "_" + module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002801
Colin Crossc4773d92020-08-25 17:12:59 -07002802 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2803 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2804 // just set it to nil.
2805 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002806
Colin Crossc4773d92020-08-25 17:12:59 -07002807 mctx := &moduleContext{
2808 baseModuleContext: baseModuleContext{
2809 context: c,
2810 config: config,
2811 module: module,
2812 },
2813 scope: scope,
2814 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002815 }
Colin Cross036a1df2015-12-17 15:49:30 -08002816
Colin Cross2da84922020-07-02 10:08:12 -07002817 mctx.module.startedGenerateBuildActions = true
2818
Colin Crossc4773d92020-08-25 17:12:59 -07002819 func() {
2820 defer func() {
2821 if r := recover(); r != nil {
2822 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2823 if err, ok := r.(panicError); ok {
2824 err.addIn(in)
2825 mctx.error(err)
2826 } else {
2827 mctx.error(newPanicErrorf(r, in))
2828 }
2829 }
2830 }()
2831 mctx.module.logicModule.GenerateBuildActions(mctx)
2832 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002833
Colin Cross2da84922020-07-02 10:08:12 -07002834 mctx.module.finishedGenerateBuildActions = true
2835
Colin Crossc4773d92020-08-25 17:12:59 -07002836 if len(mctx.errs) > 0 {
2837 errsCh <- mctx.errs
2838 return true
2839 }
2840
2841 if module.missingDeps != nil && !mctx.handledMissingDeps {
2842 var errs []error
2843 for _, depName := range module.missingDeps {
2844 errs = append(errs, c.missingDependencyError(module, depName))
2845 }
2846 errsCh <- errs
2847 return true
2848 }
2849
2850 depsCh <- mctx.ninjaFileDeps
2851
2852 newErrs := c.processLocalBuildActions(&module.actionDefs,
2853 &mctx.actionDefs, liveGlobals)
2854 if len(newErrs) > 0 {
2855 errsCh <- newErrs
2856 return true
2857 }
2858 return false
2859 })
Colin Cross691a60d2015-01-07 18:08:56 -08002860
2861 cancelCh <- struct{}{}
2862 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002863
Colin Crossc4773d92020-08-25 17:12:59 -07002864 errs = append(errs, visitErrs...)
2865
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002866 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002867}
2868
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002869func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002870 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002871
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002872 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002873 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002874
Colin Cross5f03f112017-11-07 13:29:54 -08002875 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002876 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2877 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2878 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002879 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002880
2881 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002882 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002883 context: c,
2884 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002885 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002886 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002887 }
2888
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002889 func() {
2890 defer func() {
2891 if r := recover(); r != nil {
2892 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2893 if err, ok := r.(panicError); ok {
2894 err.addIn(in)
2895 sctx.error(err)
2896 } else {
2897 sctx.error(newPanicErrorf(r, in))
2898 }
2899 }
2900 }()
2901 info.singleton.GenerateBuildActions(sctx)
2902 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002903
2904 if len(sctx.errs) > 0 {
2905 errs = append(errs, sctx.errs...)
2906 if len(errs) > maxErrors {
2907 break
2908 }
2909 continue
2910 }
2911
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002912 deps = append(deps, sctx.ninjaFileDeps...)
2913
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002914 newErrs := c.processLocalBuildActions(&info.actionDefs,
2915 &sctx.actionDefs, liveGlobals)
2916 errs = append(errs, newErrs...)
2917 if len(errs) > maxErrors {
2918 break
2919 }
2920 }
2921
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002922 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002923}
2924
2925func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2926 liveGlobals *liveTracker) []error {
2927
2928 var errs []error
2929
2930 // First we go through and add everything referenced by the module's
2931 // buildDefs to the live globals set. This will end up adding the live
2932 // locals to the set as well, but we'll take them out after.
2933 for _, def := range in.buildDefs {
2934 err := liveGlobals.AddBuildDefDeps(def)
2935 if err != nil {
2936 errs = append(errs, err)
2937 }
2938 }
2939
2940 if len(errs) > 0 {
2941 return errs
2942 }
2943
Colin Crossc9028482014-12-18 16:28:54 -08002944 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002945
2946 // We use the now-incorrect set of live "globals" to determine which local
2947 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002948 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002949 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002950 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002951 if isLive {
2952 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002953 }
2954 }
2955
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002956 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002957 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002958 if isLive {
2959 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002960 }
2961 }
2962
2963 return nil
2964}
2965
Colin Cross9607a9f2018-06-20 11:16:37 -07002966func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07002967 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07002968
2969 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002970 var visiting *moduleInfo
2971
2972 defer func() {
2973 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07002974 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
2975 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002976 }
2977 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07002978
2979 var walk func(module *moduleInfo)
2980 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002981 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07002982 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002983 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07002984 recurse := true
2985 if visitDown != nil {
2986 recurse = visitDown(dep, module)
2987 }
Colin Cross526e02f2018-06-21 13:31:53 -07002988 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002989 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01002990 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07002991 }
Colin Crossbafd5f52016-08-06 22:52:01 -07002992 if visitUp != nil {
2993 visitUp(dep, module)
2994 }
Yuchen Wu222e2452015-10-06 14:03:27 -07002995 }
2996 }
2997 }
2998
2999 walk(topModule)
3000}
3001
Colin Cross9cfd1982016-10-11 09:58:53 -07003002type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003003 from, to *moduleInfo
3004 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003005}
3006
Colin Crossc4e5b812016-10-12 10:45:05 -07003007type rename struct {
3008 group *moduleGroup
3009 name string
3010}
3011
Colin Cross0ce142c2016-12-09 10:29:05 -08003012func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003013 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003014
Colin Crossd03b59d2019-11-13 20:10:12 -08003015 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003016 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003017 }
3018
Colin Crossd03b59d2019-11-13 20:10:12 -08003019 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003020 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003021 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003022 }
3023 }
3024
Colin Cross0ce142c2016-12-09 10:29:05 -08003025 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003026}
3027
Colin Cross0ce142c2016-12-09 10:29:05 -08003028func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003029 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003030 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003031 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003032 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003033 continue
3034 }
3035
Jeff Gastond70bf752017-11-10 15:12:08 -08003036 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003037 }
3038
Colin Cross0ce142c2016-12-09 10:29:05 -08003039 return errs
3040}
3041
3042func (c *Context) handleReplacements(replacements []replace) []error {
3043 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003044 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003045 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003046 for _, m := range replace.from.reverseDeps {
3047 for i, d := range m.directDeps {
3048 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003049 // If the replacement has a predicate then check it.
3050 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3051 m.directDeps[i].module = replace.to
3052 changedDeps = true
3053 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003054 }
3055 }
3056 }
3057
Colin Cross9cfd1982016-10-11 09:58:53 -07003058 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003059
Paul Duffin8969cb62020-06-30 12:15:26 +01003060 if changedDeps {
3061 atomic.AddUint32(&c.depsModified, 1)
3062 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003063 return errs
3064}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003065
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003066func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3067 if depVariations != nil {
3068 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3069 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003070 if c.allowMissingDependencies {
3071 module.missingDeps = append(module.missingDeps, depName)
3072 return nil
3073 }
3074 return []error{c.missingDependencyError(module, depName)}
3075}
3076
3077func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3078 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3079
3080 return &BlueprintError{
3081 Err: err,
3082 Pos: module.pos,
3083 }
3084}
3085
Colin Crossd03b59d2019-11-13 20:10:12 -08003086func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003087 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3088 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003089 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003090 }
3091 return nil
3092}
3093
Jeff Gastond70bf752017-11-10 15:12:08 -08003094func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003095 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003096 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3097 result := make([]*moduleGroup, 0, len(wrappers))
3098 for _, group := range wrappers {
3099 result = append(result, group.moduleGroup)
3100 }
3101 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003102 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003103
3104 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003105 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003106 }
3107
Jeff Gastond70bf752017-11-10 15:12:08 -08003108 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003109}
3110
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003111func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003112 var module *moduleInfo
3113
3114 defer func() {
3115 if r := recover(); r != nil {
3116 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3117 funcName(visit), module))
3118 }
3119 }()
3120
Jeff Gastond70bf752017-11-10 15:12:08 -08003121 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003122 for _, moduleOrAlias := range moduleGroup.modules {
3123 if module = moduleOrAlias.module(); module != nil {
3124 visit(module.logicModule)
3125 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003126 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003127 }
3128}
3129
3130func (c *Context) visitAllModulesIf(pred func(Module) bool,
3131 visit func(Module)) {
3132
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003133 var module *moduleInfo
3134
3135 defer func() {
3136 if r := recover(); r != nil {
3137 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3138 funcName(pred), funcName(visit), module))
3139 }
3140 }()
3141
Jeff Gastond70bf752017-11-10 15:12:08 -08003142 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003143 for _, moduleOrAlias := range moduleGroup.modules {
3144 if module = moduleOrAlias.module(); module != nil {
3145 if pred(module.logicModule) {
3146 visit(module.logicModule)
3147 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003148 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003149 }
3150 }
3151}
3152
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003153func (c *Context) visitAllModuleVariants(module *moduleInfo,
3154 visit func(Module)) {
3155
3156 var variant *moduleInfo
3157
3158 defer func() {
3159 if r := recover(); r != nil {
3160 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3161 module, funcName(visit), variant))
3162 }
3163 }()
3164
Colin Cross5df74a82020-08-24 16:18:21 -07003165 for _, moduleOrAlias := range module.group.modules {
3166 if variant = moduleOrAlias.module(); variant != nil {
3167 visit(variant.logicModule)
3168 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003169 }
3170}
3171
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003172func (c *Context) requireNinjaVersion(major, minor, micro int) {
3173 if major != 1 {
3174 panic("ninja version with major version != 1 not supported")
3175 }
3176 if c.requiredNinjaMinor < minor {
3177 c.requiredNinjaMinor = minor
3178 c.requiredNinjaMicro = micro
3179 }
3180 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3181 c.requiredNinjaMicro = micro
3182 }
3183}
3184
Colin Cross2ce594e2020-01-29 12:58:03 -08003185func (c *Context) setNinjaBuildDir(value ninjaString) {
Colin Crossa2599452015-11-18 16:01:01 -08003186 if c.ninjaBuildDir == nil {
3187 c.ninjaBuildDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003188 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003189}
3190
3191func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003192 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003193
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003194 pkgs := make(map[string]*packageContext)
3195 pkgNames := make(map[*packageContext]string)
3196 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003197
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003198 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003199 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003200 // This is a built-in rule and has no package.
3201 return
3202 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003203 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003204 // We've already processed this package.
3205 return
3206 }
3207
Jamie Gennis2fb20952014-10-03 02:49:58 -07003208 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003209 if present {
3210 // Short name collision. Both this package and the one that's
3211 // already there need to use their full names. We leave the short
3212 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003213 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003214 longPkgNames[otherPkg] = true
3215 } else {
3216 // No collision so far. Tentatively set the package's name to be
3217 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003218 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003219 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003220 }
3221 }
3222
3223 // We try to give all packages their short name, but when we get collisions
3224 // we need to use the full unique package name.
3225 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003226 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003227 }
3228 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003229 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003230 }
3231 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003232 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003233 }
3234
3235 // Add the packages that had collisions using their full unique names. This
3236 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003237 for pctx := range longPkgNames {
3238 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003239 }
3240
Dan Willemsena481ae22015-12-18 15:18:03 -08003241 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3242 deps := []string{}
3243 for _, pkg := range pkgs {
3244 deps = append(deps, pkg.ninjaFileDeps...)
3245 }
3246
3247 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003248}
3249
Colin Cross92054a42021-01-21 16:49:25 -08003250// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3251// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3252// are used much more than once.
3253func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3254 for v := range liveGlobals.variables {
3255 v.memoizeFullName(pkgNames)
3256 }
3257 for r := range liveGlobals.rules {
3258 r.memoizeFullName(pkgNames)
3259 }
3260 for p := range liveGlobals.pools {
3261 p.memoizeFullName(pkgNames)
3262 }
3263}
3264
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003265func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003266 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003267
3268 visited := make(map[Variable]bool) // variables that were already checked
3269 checking := make(map[Variable]bool) // variables actively being checked
3270
3271 var check func(v Variable) []Variable
3272
3273 check = func(v Variable) []Variable {
3274 visited[v] = true
3275 checking[v] = true
3276 defer delete(checking, v)
3277
3278 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003279 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003280 if checking[dep] {
3281 // This is a cycle.
3282 return []Variable{dep, v}
3283 }
3284
3285 if !visited[dep] {
3286 cycle := check(dep)
3287 if cycle != nil {
3288 if cycle[0] == v {
3289 // We are the "start" of the cycle, so we're responsible
3290 // for generating the errors. The cycle list is in
3291 // reverse order because all the 'check' calls append
3292 // their own module to the list.
3293 msgs := []string{"detected variable reference cycle:"}
3294
3295 // Iterate backwards through the cycle list.
3296 curName := v.fullName(pkgNames)
3297 curValue := value.Value(pkgNames)
3298 for i := len(cycle) - 1; i >= 0; i-- {
3299 next := cycle[i]
3300 nextName := next.fullName(pkgNames)
3301 nextValue := variables[next].Value(pkgNames)
3302
3303 msgs = append(msgs, fmt.Sprintf(
3304 " %q depends on %q", curName, nextName))
3305 msgs = append(msgs, fmt.Sprintf(
3306 " [%s = %s]", curName, curValue))
3307
3308 curName = nextName
3309 curValue = nextValue
3310 }
3311
3312 // Variable reference cycles are a programming error,
3313 // not the fault of the Blueprint file authors.
3314 panic(strings.Join(msgs, "\n"))
3315 } else {
3316 // We're not the "start" of the cycle, so we just append
3317 // our module to the list and return it.
3318 return append(cycle, v)
3319 }
3320 }
3321 }
3322 }
3323
3324 return nil
3325 }
3326
3327 for v := range variables {
3328 if !visited[v] {
3329 cycle := check(v)
3330 if cycle != nil {
3331 panic("inconceivable!")
3332 }
3333 }
3334 }
3335}
3336
Jamie Gennisaf435562014-10-27 22:34:56 -07003337// AllTargets returns a map all the build target names to the rule used to build
3338// them. This is the same information that is output by running 'ninja -t
3339// targets all'. If this is called before PrepareBuildActions successfully
3340// completes then ErrbuildActionsNotReady is returned.
3341func (c *Context) AllTargets() (map[string]string, error) {
3342 if !c.buildActionsReady {
3343 return nil, ErrBuildActionsNotReady
3344 }
3345
3346 targets := map[string]string{}
3347
3348 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003349 for _, module := range c.moduleInfo {
3350 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003351 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003352 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003353 outputValue, err := output.Eval(c.globalVariables)
3354 if err != nil {
3355 return nil, err
3356 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003357 targets[outputValue] = ruleName
3358 }
3359 }
3360 }
3361
3362 // Collect all the singleton build targets.
3363 for _, info := range c.singletonInfo {
3364 for _, buildDef := range info.actionDefs.buildDefs {
3365 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003366 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003367 outputValue, err := output.Eval(c.globalVariables)
3368 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003369 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003370 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003371 targets[outputValue] = ruleName
3372 }
3373 }
3374 }
3375
3376 return targets, nil
3377}
3378
Colin Crossa2599452015-11-18 16:01:01 -08003379func (c *Context) NinjaBuildDir() (string, error) {
3380 if c.ninjaBuildDir != nil {
3381 return c.ninjaBuildDir.Eval(c.globalVariables)
3382 } else {
3383 return "", nil
3384 }
3385}
3386
Colin Cross4572edd2015-05-13 14:36:24 -07003387// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3388// property structs returned by the factory for that module type.
3389func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3390 ret := make(map[string][]interface{})
3391 for moduleType, factory := range c.moduleFactories {
3392 _, ret[moduleType] = factory()
3393 }
3394
3395 return ret
3396}
3397
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003398func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3399 ret := make(map[string]ModuleFactory)
3400 for k, v := range c.moduleFactories {
3401 ret[k] = v
3402 }
3403 return ret
3404}
3405
Colin Cross4572edd2015-05-13 14:36:24 -07003406func (c *Context) ModuleName(logicModule Module) string {
3407 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003408 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003409}
3410
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003411func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003412 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003413}
3414
Colin Cross8c602f72015-12-17 18:02:11 -08003415func (c *Context) ModuleSubDir(logicModule Module) string {
3416 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003417 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003418}
3419
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003420func (c *Context) ModuleType(logicModule Module) string {
3421 module := c.moduleInfo[logicModule]
3422 return module.typeName
3423}
3424
Colin Cross2da84922020-07-02 10:08:12 -07003425// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3426// provider was not set it returns the zero value of the type of the provider, which means the
3427// return value can always be type-asserted to the type of the provider. The return value should
3428// always be considered read-only. It panics if called before the appropriate mutator or
3429// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3430// copy of the value originally passed to SetProvider.
3431func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3432 module := c.moduleInfo[logicModule]
3433 value, _ := c.provider(module, provider)
3434 return value
3435}
3436
3437// ModuleHasProvider returns true if the provider for the given module has been set.
3438func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3439 module := c.moduleInfo[logicModule]
3440 _, ok := c.provider(module, provider)
3441 return ok
3442}
3443
Colin Cross4572edd2015-05-13 14:36:24 -07003444func (c *Context) BlueprintFile(logicModule Module) string {
3445 module := c.moduleInfo[logicModule]
3446 return module.relBlueprintsFile
3447}
3448
3449func (c *Context) ModuleErrorf(logicModule Module, format string,
3450 args ...interface{}) error {
3451
3452 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003453 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003454 Err: fmt.Errorf(format, args...),
3455 Pos: module.pos,
3456 }
3457}
3458
3459func (c *Context) VisitAllModules(visit func(Module)) {
3460 c.visitAllModules(visit)
3461}
3462
3463func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3464 visit func(Module)) {
3465
3466 c.visitAllModulesIf(pred, visit)
3467}
3468
Colin Cross080c1332017-03-17 13:09:05 -07003469func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3470 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003471
Colin Cross080c1332017-03-17 13:09:05 -07003472 var visiting *moduleInfo
3473
3474 defer func() {
3475 if r := recover(); r != nil {
3476 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3477 topModule, funcName(visit), visiting))
3478 }
3479 }()
3480
3481 for _, dep := range topModule.directDeps {
3482 visiting = dep.module
3483 visit(dep.module.logicModule)
3484 }
3485}
3486
3487func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3488 topModule := c.moduleInfo[module]
3489
3490 var visiting *moduleInfo
3491
3492 defer func() {
3493 if r := recover(); r != nil {
3494 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3495 topModule, funcName(pred), funcName(visit), visiting))
3496 }
3497 }()
3498
3499 for _, dep := range topModule.directDeps {
3500 visiting = dep.module
3501 if pred(dep.module.logicModule) {
3502 visit(dep.module.logicModule)
3503 }
3504 }
3505}
3506
3507func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003508 topModule := c.moduleInfo[module]
3509
3510 var visiting *moduleInfo
3511
3512 defer func() {
3513 if r := recover(); r != nil {
3514 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3515 topModule, funcName(visit), visiting))
3516 }
3517 }()
3518
Colin Cross9607a9f2018-06-20 11:16:37 -07003519 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003520 visiting = dep.module
3521 visit(dep.module.logicModule)
3522 })
Colin Cross4572edd2015-05-13 14:36:24 -07003523}
3524
Colin Cross080c1332017-03-17 13:09:05 -07003525func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003526 topModule := c.moduleInfo[module]
3527
3528 var visiting *moduleInfo
3529
3530 defer func() {
3531 if r := recover(); r != nil {
3532 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3533 topModule, funcName(pred), funcName(visit), visiting))
3534 }
3535 }()
3536
Colin Cross9607a9f2018-06-20 11:16:37 -07003537 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003538 if pred(dep.module.logicModule) {
3539 visiting = dep.module
3540 visit(dep.module.logicModule)
3541 }
3542 })
Colin Cross4572edd2015-05-13 14:36:24 -07003543}
3544
Colin Cross24ad5872015-11-17 16:22:29 -08003545func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003546 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003547}
3548
3549func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003550 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003551}
3552
3553func (c *Context) VisitAllModuleVariants(module Module,
3554 visit func(Module)) {
3555
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003556 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003557}
3558
Colin Cross9226d6c2019-02-25 18:07:44 -08003559// Singletons returns a list of all registered Singletons.
3560func (c *Context) Singletons() []Singleton {
3561 var ret []Singleton
3562 for _, s := range c.singletonInfo {
3563 ret = append(ret, s.singleton)
3564 }
3565 return ret
3566}
3567
3568// SingletonName returns the name that the given singleton was registered with.
3569func (c *Context) SingletonName(singleton Singleton) string {
3570 for _, s := range c.singletonInfo {
3571 if s.singleton == singleton {
3572 return s.name
3573 }
3574 }
3575 return ""
3576}
3577
Jamie Gennisd4e10182014-06-12 20:06:50 -07003578// WriteBuildFile writes the Ninja manifeset text for the generated build
3579// actions to w. If this is called before PrepareBuildActions successfully
3580// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003581func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003582 var err error
3583 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3584 if !c.buildActionsReady {
3585 err = ErrBuildActionsNotReady
3586 return
3587 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003588
Colin Cross3a8c0252019-01-23 13:21:48 -08003589 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003590
Colin Cross3a8c0252019-01-23 13:21:48 -08003591 err = c.writeBuildFileHeader(nw)
3592 if err != nil {
3593 return
3594 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003595
Colin Cross3a8c0252019-01-23 13:21:48 -08003596 err = c.writeNinjaRequiredVersion(nw)
3597 if err != nil {
3598 return
3599 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003600
Colin Cross3a8c0252019-01-23 13:21:48 -08003601 err = c.writeSubninjas(nw)
3602 if err != nil {
3603 return
3604 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003605
Colin Cross3a8c0252019-01-23 13:21:48 -08003606 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003607
Colin Cross3a8c0252019-01-23 13:21:48 -08003608 err = c.writeGlobalVariables(nw)
3609 if err != nil {
3610 return
3611 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003612
Colin Cross3a8c0252019-01-23 13:21:48 -08003613 err = c.writeGlobalPools(nw)
3614 if err != nil {
3615 return
3616 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003617
Colin Cross3a8c0252019-01-23 13:21:48 -08003618 err = c.writeBuildDir(nw)
3619 if err != nil {
3620 return
3621 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003622
Colin Cross3a8c0252019-01-23 13:21:48 -08003623 err = c.writeGlobalRules(nw)
3624 if err != nil {
3625 return
3626 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003627
Colin Cross3a8c0252019-01-23 13:21:48 -08003628 err = c.writeAllModuleActions(nw)
3629 if err != nil {
3630 return
3631 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003632
Colin Cross3a8c0252019-01-23 13:21:48 -08003633 err = c.writeAllSingletonActions(nw)
3634 if err != nil {
3635 return
3636 }
3637 })
3638
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003639 if err != nil {
3640 return err
3641 }
3642
3643 return nil
3644}
3645
Jamie Gennisc15544d2014-09-24 20:26:52 -07003646type pkgAssociation struct {
3647 PkgName string
3648 PkgPath string
3649}
3650
3651type pkgAssociationSorter struct {
3652 pkgs []pkgAssociation
3653}
3654
3655func (s *pkgAssociationSorter) Len() int {
3656 return len(s.pkgs)
3657}
3658
3659func (s *pkgAssociationSorter) Less(i, j int) bool {
3660 iName := s.pkgs[i].PkgName
3661 jName := s.pkgs[j].PkgName
3662 return iName < jName
3663}
3664
3665func (s *pkgAssociationSorter) Swap(i, j int) {
3666 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3667}
3668
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003669func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3670 headerTemplate := template.New("fileHeader")
3671 _, err := headerTemplate.Parse(fileHeaderTemplate)
3672 if err != nil {
3673 // This is a programming error.
3674 panic(err)
3675 }
3676
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003677 var pkgs []pkgAssociation
3678 maxNameLen := 0
3679 for pkg, name := range c.pkgNames {
3680 pkgs = append(pkgs, pkgAssociation{
3681 PkgName: name,
3682 PkgPath: pkg.pkgPath,
3683 })
3684 if len(name) > maxNameLen {
3685 maxNameLen = len(name)
3686 }
3687 }
3688
3689 for i := range pkgs {
3690 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3691 }
3692
Jamie Gennisc15544d2014-09-24 20:26:52 -07003693 sort.Sort(&pkgAssociationSorter{pkgs})
3694
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003695 params := map[string]interface{}{
3696 "Pkgs": pkgs,
3697 }
3698
3699 buf := bytes.NewBuffer(nil)
3700 err = headerTemplate.Execute(buf, params)
3701 if err != nil {
3702 return err
3703 }
3704
3705 return nw.Comment(buf.String())
3706}
3707
3708func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3709 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3710 c.requiredNinjaMicro)
3711
3712 err := nw.Assign("ninja_required_version", value)
3713 if err != nil {
3714 return err
3715 }
3716
3717 return nw.BlankLine()
3718}
3719
Dan Willemsenab223a52018-07-05 21:56:59 -07003720func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3721 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003722 err := nw.Subninja(subninja)
3723 if err != nil {
3724 return err
3725 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003726 }
3727 return nw.BlankLine()
3728}
3729
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003730func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Colin Crossa2599452015-11-18 16:01:01 -08003731 if c.ninjaBuildDir != nil {
3732 err := nw.Assign("builddir", c.ninjaBuildDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003733 if err != nil {
3734 return err
3735 }
3736
3737 err = nw.BlankLine()
3738 if err != nil {
3739 return err
3740 }
3741 }
3742 return nil
3743}
3744
Jamie Gennisc15544d2014-09-24 20:26:52 -07003745type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003746 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003747}
3748
Jamie Gennisc15544d2014-09-24 20:26:52 -07003749type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003750 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003751 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003752}
3753
Jamie Gennisc15544d2014-09-24 20:26:52 -07003754func (s *globalEntitySorter) Len() int {
3755 return len(s.entities)
3756}
3757
3758func (s *globalEntitySorter) Less(i, j int) bool {
3759 iName := s.entities[i].fullName(s.pkgNames)
3760 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003761 return iName < jName
3762}
3763
Jamie Gennisc15544d2014-09-24 20:26:52 -07003764func (s *globalEntitySorter) Swap(i, j int) {
3765 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003766}
3767
3768func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3769 visited := make(map[Variable]bool)
3770
3771 var walk func(v Variable) error
3772 walk = func(v Variable) error {
3773 visited[v] = true
3774
3775 // First visit variables on which this variable depends.
3776 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003777 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003778 if !visited[dep] {
3779 err := walk(dep)
3780 if err != nil {
3781 return err
3782 }
3783 }
3784 }
3785
3786 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3787 if err != nil {
3788 return err
3789 }
3790
3791 err = nw.BlankLine()
3792 if err != nil {
3793 return err
3794 }
3795
3796 return nil
3797 }
3798
Jamie Gennisc15544d2014-09-24 20:26:52 -07003799 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3800 for variable := range c.globalVariables {
3801 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003802 }
3803
Jamie Gennisc15544d2014-09-24 20:26:52 -07003804 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003805
Jamie Gennisc15544d2014-09-24 20:26:52 -07003806 for _, entity := range globalVariables {
3807 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003808 if !visited[v] {
3809 err := walk(v)
3810 if err != nil {
3811 return nil
3812 }
3813 }
3814 }
3815
3816 return nil
3817}
3818
3819func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003820 globalPools := make([]globalEntity, 0, len(c.globalPools))
3821 for pool := range c.globalPools {
3822 globalPools = append(globalPools, pool)
3823 }
3824
3825 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3826
3827 for _, entity := range globalPools {
3828 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003829 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003830 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003831 err := def.WriteTo(nw, name)
3832 if err != nil {
3833 return err
3834 }
3835
3836 err = nw.BlankLine()
3837 if err != nil {
3838 return err
3839 }
3840 }
3841
3842 return nil
3843}
3844
3845func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003846 globalRules := make([]globalEntity, 0, len(c.globalRules))
3847 for rule := range c.globalRules {
3848 globalRules = append(globalRules, rule)
3849 }
3850
3851 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3852
3853 for _, entity := range globalRules {
3854 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003855 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003856 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003857 err := def.WriteTo(nw, name, c.pkgNames)
3858 if err != nil {
3859 return err
3860 }
3861
3862 err = nw.BlankLine()
3863 if err != nil {
3864 return err
3865 }
3866 }
3867
3868 return nil
3869}
3870
Colin Cross2c1f3d12016-04-11 15:47:28 -07003871type depSorter []depInfo
3872
3873func (s depSorter) Len() int {
3874 return len(s)
3875}
3876
3877func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003878 iName := s[i].module.Name()
3879 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003880 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003881 iName = s[i].module.variant.name
3882 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003883 }
3884 return iName < jName
3885}
3886
3887func (s depSorter) Swap(i, j int) {
3888 s[i], s[j] = s[j], s[i]
3889}
3890
Jeff Gaston0e907592017-12-01 17:10:52 -08003891type moduleSorter struct {
3892 modules []*moduleInfo
3893 nameInterface NameInterface
3894}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003895
Colin Crossab6d7902015-03-11 16:17:52 -07003896func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003897 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003898}
3899
Colin Crossab6d7902015-03-11 16:17:52 -07003900func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003901 iMod := s.modules[i]
3902 jMod := s.modules[j]
3903 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3904 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003905 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003906 iVariantName := s.modules[i].variant.name
3907 jVariantName := s.modules[j].variant.name
3908 if iVariantName == jVariantName {
3909 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3910 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3911 } else {
3912 return iVariantName < jVariantName
3913 }
3914 } else {
3915 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003916 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003917}
3918
Colin Crossab6d7902015-03-11 16:17:52 -07003919func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003920 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003921}
3922
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003923func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3924 headerTemplate := template.New("moduleHeader")
3925 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3926 if err != nil {
3927 // This is a programming error.
3928 panic(err)
3929 }
3930
Colin Crossab6d7902015-03-11 16:17:52 -07003931 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3932 for _, module := range c.moduleInfo {
3933 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003934 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003935 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003936
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003937 buf := bytes.NewBuffer(nil)
3938
Colin Crossab6d7902015-03-11 16:17:52 -07003939 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003940 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3941 continue
3942 }
3943
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003944 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003945
3946 // In order to make the bootstrap build manifest independent of the
3947 // build dir we need to output the Blueprints file locations in the
3948 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003949 relPos := module.pos
3950 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003951
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003952 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003953 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003954 factoryName := factoryFunc.Name()
3955
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003956 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003957 "name": module.Name(),
3958 "typeName": module.typeName,
3959 "goFactory": factoryName,
3960 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07003961 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003962 }
3963 err = headerTemplate.Execute(buf, infoMap)
3964 if err != nil {
3965 return err
3966 }
3967
3968 err = nw.Comment(buf.String())
3969 if err != nil {
3970 return err
3971 }
3972
3973 err = nw.BlankLine()
3974 if err != nil {
3975 return err
3976 }
3977
Colin Crossab6d7902015-03-11 16:17:52 -07003978 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003979 if err != nil {
3980 return err
3981 }
3982
3983 err = nw.BlankLine()
3984 if err != nil {
3985 return err
3986 }
3987 }
3988
3989 return nil
3990}
3991
3992func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
3993 headerTemplate := template.New("singletonHeader")
3994 _, err := headerTemplate.Parse(singletonHeaderTemplate)
3995 if err != nil {
3996 // This is a programming error.
3997 panic(err)
3998 }
3999
4000 buf := bytes.NewBuffer(nil)
4001
Yuchen Wub9103ef2015-08-25 17:58:17 -07004002 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004003 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4004 continue
4005 }
4006
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004007 // Get the name of the factory function for the module.
4008 factory := info.factory
4009 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4010 factoryName := factoryFunc.Name()
4011
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004012 buf.Reset()
4013 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004014 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004015 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004016 }
4017 err = headerTemplate.Execute(buf, infoMap)
4018 if err != nil {
4019 return err
4020 }
4021
4022 err = nw.Comment(buf.String())
4023 if err != nil {
4024 return err
4025 }
4026
4027 err = nw.BlankLine()
4028 if err != nil {
4029 return err
4030 }
4031
4032 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4033 if err != nil {
4034 return err
4035 }
4036
4037 err = nw.BlankLine()
4038 if err != nil {
4039 return err
4040 }
4041 }
4042
4043 return nil
4044}
4045
4046func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4047 defs *localBuildActions) error {
4048
4049 // Write the local variable assignments.
4050 for _, v := range defs.variables {
4051 // A localVariable doesn't need the package names or config to
4052 // determine its name or value.
4053 name := v.fullName(nil)
4054 value, err := v.value(nil)
4055 if err != nil {
4056 panic(err)
4057 }
4058 err = nw.Assign(name, value.Value(c.pkgNames))
4059 if err != nil {
4060 return err
4061 }
4062 }
4063
4064 if len(defs.variables) > 0 {
4065 err := nw.BlankLine()
4066 if err != nil {
4067 return err
4068 }
4069 }
4070
4071 // Write the local rules.
4072 for _, r := range defs.rules {
4073 // A localRule doesn't need the package names or config to determine
4074 // its name or definition.
4075 name := r.fullName(nil)
4076 def, err := r.def(nil)
4077 if err != nil {
4078 panic(err)
4079 }
4080
4081 err = def.WriteTo(nw, name, c.pkgNames)
4082 if err != nil {
4083 return err
4084 }
4085
4086 err = nw.BlankLine()
4087 if err != nil {
4088 return err
4089 }
4090 }
4091
4092 // Write the build definitions.
4093 for _, buildDef := range defs.buildDefs {
4094 err := buildDef.WriteTo(nw, c.pkgNames)
4095 if err != nil {
4096 return err
4097 }
4098
4099 if len(buildDef.Args) > 0 {
4100 err = nw.BlankLine()
4101 if err != nil {
4102 return err
4103 }
4104 }
4105 }
4106
4107 return nil
4108}
4109
Colin Cross5df74a82020-08-24 16:18:21 -07004110func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004111 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004112 if a == b {
4113 return false
4114 }
Colin Cross65569e42015-03-10 20:08:19 -07004115 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004116 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004117 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004118 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004119 return found
4120 }
4121 }
4122
4123 missing := a
4124 if found {
4125 missing = b
4126 }
4127 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4128}
4129
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004130type panicError struct {
4131 panic interface{}
4132 stack []byte
4133 in string
4134}
4135
4136func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4137 buf := make([]byte, 4096)
4138 count := runtime.Stack(buf, false)
4139 return panicError{
4140 panic: panic,
4141 in: fmt.Sprintf(in, a...),
4142 stack: buf[:count],
4143 }
4144}
4145
4146func (p panicError) Error() string {
4147 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4148}
4149
4150func (p *panicError) addIn(in string) {
4151 p.in += " in " + in
4152}
4153
4154func funcName(f interface{}) string {
4155 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4156}
4157
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004158var fileHeaderTemplate = `******************************************************************************
4159*** This file is generated and should not be edited ***
4160******************************************************************************
4161{{if .Pkgs}}
4162This file contains variables, rules, and pools with name prefixes indicating
4163they were generated by the following Go packages:
4164{{range .Pkgs}}
4165 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4166
4167`
4168
4169var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004170Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004171Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004172Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004173Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004174Defined: {{.pos}}
4175`
4176
4177var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4178Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004179Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004180`