blob: bd61f07090f159d3c71bf38cc2cdb8de2a669cb5 [file] [log] [blame]
Colin Cross8e0c5112015-01-23 14:15:10 -08001// Copyright 2014 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Jamie Gennis1bc967e2014-05-27 16:34:41 -070015package blueprint
16
17import (
Jamie Gennis1bc967e2014-05-27 16:34:41 -070018 "bytes"
Colin Cross3a8c0252019-01-23 13:21:48 -080019 "context"
Lukacs T. Berki6f682822021-04-01 18:27:31 +020020 "encoding/json"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070021 "errors"
22 "fmt"
23 "io"
Jeff Gastonc3e28442017-08-09 15:13:12 -070024 "io/ioutil"
Jeff Gastonaca42202017-08-23 17:30:05 -070025 "os"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070026 "path/filepath"
27 "reflect"
Romain Guy28529652014-08-12 17:50:11 -070028 "runtime"
Colin Cross3a8c0252019-01-23 13:21:48 -080029 "runtime/pprof"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070030 "sort"
31 "strings"
Colin Cross127d2ea2016-11-01 11:10:51 -070032 "sync"
Colin Cross23d7aa12015-06-30 16:05:22 -070033 "sync/atomic"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070034 "text/scanner"
35 "text/template"
Colin Cross1fef5362015-04-20 16:50:54 -070036
37 "github.com/google/blueprint/parser"
Colin Crossb519a7e2017-02-01 13:21:35 -080038 "github.com/google/blueprint/pathtools"
Colin Cross1fef5362015-04-20 16:50:54 -070039 "github.com/google/blueprint/proptools"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070040)
41
42var ErrBuildActionsNotReady = errors.New("build actions are not ready")
43
44const maxErrors = 10
Jeff Gaston9f630902017-11-15 14:49:48 -080045const MockModuleListFile = "bplist"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070046
Jamie Gennisd4e10182014-06-12 20:06:50 -070047// A Context contains all the state needed to parse a set of Blueprints files
48// and generate a Ninja file. The process of generating a Ninja file proceeds
49// through a series of four phases. Each phase corresponds with a some methods
50// on the Context object
51//
52// Phase Methods
53// ------------ -------------------------------------------
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070054// 1. Registration RegisterModuleType, RegisterSingletonType
Jamie Gennisd4e10182014-06-12 20:06:50 -070055//
56// 2. Parse ParseBlueprintsFiles, Parse
57//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070058// 3. Generate ResolveDependencies, PrepareBuildActions
Jamie Gennisd4e10182014-06-12 20:06:50 -070059//
60// 4. Write WriteBuildFile
61//
62// The registration phase prepares the context to process Blueprints files
63// containing various types of modules. The parse phase reads in one or more
64// Blueprints files and validates their contents against the module types that
65// have been registered. The generate phase then analyzes the parsed Blueprints
66// contents to create an internal representation for the build actions that must
67// be performed. This phase also performs validation of the module dependencies
68// and property values defined in the parsed Blueprints files. Finally, the
69// write phase generates the Ninja manifest text based on the generated build
70// actions.
Jamie Gennis1bc967e2014-05-27 16:34:41 -070071type Context struct {
Colin Cross3a8c0252019-01-23 13:21:48 -080072 context.Context
73
Jamie Gennis1bc967e2014-05-27 16:34:41 -070074 // set at instantiation
Colin Cross65569e42015-03-10 20:08:19 -070075 moduleFactories map[string]ModuleFactory
Jeff Gastond70bf752017-11-10 15:12:08 -080076 nameInterface NameInterface
Colin Cross0b7e83e2016-05-17 14:58:05 -070077 moduleGroups []*moduleGroup
Colin Cross65569e42015-03-10 20:08:19 -070078 moduleInfo map[Module]*moduleInfo
79 modulesSorted []*moduleInfo
Colin Cross5f03f112017-11-07 13:29:54 -080080 preSingletonInfo []*singletonInfo
Yuchen Wub9103ef2015-08-25 17:58:17 -070081 singletonInfo []*singletonInfo
Colin Cross65569e42015-03-10 20:08:19 -070082 mutatorInfo []*mutatorInfo
Colin Crossf8b50422016-08-10 12:56:40 -070083 earlyMutatorInfo []*mutatorInfo
Colin Cross65569e42015-03-10 20:08:19 -070084 variantMutatorNames []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070085
Colin Cross3702ac72016-08-11 11:09:00 -070086 depsModified uint32 // positive if a mutator modified the dependencies
87
Jamie Gennis1bc967e2014-05-27 16:34:41 -070088 dependenciesReady bool // set to true on a successful ResolveDependencies
89 buildActionsReady bool // set to true on a successful PrepareBuildActions
90
91 // set by SetIgnoreUnknownModuleTypes
92 ignoreUnknownModuleTypes bool
93
Colin Cross036a1df2015-12-17 15:49:30 -080094 // set by SetAllowMissingDependencies
95 allowMissingDependencies bool
96
Jamie Gennis1bc967e2014-05-27 16:34:41 -070097 // set during PrepareBuildActions
Dan Willemsenaeffbf72015-11-25 15:29:32 -080098 pkgNames map[*packageContext]string
Colin Cross5f03f112017-11-07 13:29:54 -080099 liveGlobals *liveTracker
Colin Cross2ce594e2020-01-29 12:58:03 -0800100 globalVariables map[Variable]ninjaString
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700101 globalPools map[Pool]*poolDef
102 globalRules map[Rule]*ruleDef
103
104 // set during PrepareBuildActions
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +0200105 outDir ninjaString // The builddir special Ninja variable
Colin Cross2ce594e2020-01-29 12:58:03 -0800106 requiredNinjaMajor int // For the ninja_required_version variable
107 requiredNinjaMinor int // For the ninja_required_version variable
108 requiredNinjaMicro int // For the ninja_required_version variable
Jamie Gennisc15544d2014-09-24 20:26:52 -0700109
Dan Willemsenab223a52018-07-05 21:56:59 -0700110 subninjas []string
111
Jeff Gastond70bf752017-11-10 15:12:08 -0800112 // set lazily by sortedModuleGroups
113 cachedSortedModuleGroups []*moduleGroup
Liz Kammer9ae14f12020-11-30 16:30:45 -0700114 // cache deps modified to determine whether cachedSortedModuleGroups needs to be recalculated
115 cachedDepsModified bool
Colin Crossd7b0f602016-06-02 15:30:20 -0700116
Colin Cross25236982021-04-05 17:20:34 -0700117 globs map[globKey]pathtools.GlobResult
Colin Cross127d2ea2016-11-01 11:10:51 -0700118 globLock sync.Mutex
119
Colin Crossc5fa50e2019-12-17 13:12:35 -0800120 srcDir string
Jeff Gastonc3e28442017-08-09 15:13:12 -0700121 fs pathtools.FileSystem
122 moduleListFile string
Colin Cross2da84922020-07-02 10:08:12 -0700123
124 // Mutators indexed by the ID of the provider associated with them. Not all mutators will
125 // have providers, and not all providers will have a mutator, or if they do the mutator may
126 // not be registered in this Context.
127 providerMutators []*mutatorInfo
128
129 // The currently running mutator
130 startedMutator *mutatorInfo
131 // True for any mutators that have already run over all modules
132 finishedMutators map[*mutatorInfo]bool
133
134 // Can be set by tests to avoid invalidating Module values after mutators.
135 skipCloneModulesAfterMutators bool
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700136}
137
Jamie Gennisd4e10182014-06-12 20:06:50 -0700138// An Error describes a problem that was encountered that is related to a
139// particular location in a Blueprints file.
Colin Cross2c628442016-10-07 17:13:10 -0700140type BlueprintError struct {
Jamie Gennisd4e10182014-06-12 20:06:50 -0700141 Err error // the error that occurred
142 Pos scanner.Position // the relevant Blueprints file location
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700143}
144
Colin Cross2c628442016-10-07 17:13:10 -0700145// A ModuleError describes a problem that was encountered that is related to a
146// particular module in a Blueprints file
147type ModuleError struct {
148 BlueprintError
149 module *moduleInfo
150}
151
152// A PropertyError describes a problem that was encountered that is related to a
153// particular property in a Blueprints file
154type PropertyError struct {
155 ModuleError
156 property string
157}
158
159func (e *BlueprintError) Error() string {
160 return fmt.Sprintf("%s: %s", e.Pos, e.Err)
161}
162
163func (e *ModuleError) Error() string {
164 return fmt.Sprintf("%s: %s: %s", e.Pos, e.module, e.Err)
165}
166
167func (e *PropertyError) Error() string {
168 return fmt.Sprintf("%s: %s: %s: %s", e.Pos, e.module, e.property, e.Err)
169}
170
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700171type localBuildActions struct {
172 variables []*localVariable
173 rules []*localRule
174 buildDefs []*buildDef
175}
176
Colin Crossf7beb892019-11-13 20:11:14 -0800177type moduleAlias struct {
Colin Crossedc41762020-08-13 12:07:30 -0700178 variant variant
179 target *moduleInfo
Colin Crossf7beb892019-11-13 20:11:14 -0800180}
181
Colin Cross5df74a82020-08-24 16:18:21 -0700182func (m *moduleAlias) alias() *moduleAlias { return m }
183func (m *moduleAlias) module() *moduleInfo { return nil }
184func (m *moduleAlias) moduleOrAliasTarget() *moduleInfo { return m.target }
185func (m *moduleAlias) moduleOrAliasVariant() variant { return m.variant }
186
187func (m *moduleInfo) alias() *moduleAlias { return nil }
188func (m *moduleInfo) module() *moduleInfo { return m }
189func (m *moduleInfo) moduleOrAliasTarget() *moduleInfo { return m }
190func (m *moduleInfo) moduleOrAliasVariant() variant { return m.variant }
191
192type moduleOrAlias interface {
193 alias() *moduleAlias
194 module() *moduleInfo
195 moduleOrAliasTarget() *moduleInfo
196 moduleOrAliasVariant() variant
197}
198
199type modulesOrAliases []moduleOrAlias
200
201func (l modulesOrAliases) firstModule() *moduleInfo {
202 for _, moduleOrAlias := range l {
203 if m := moduleOrAlias.module(); m != nil {
204 return m
205 }
206 }
207 panic(fmt.Errorf("no first module!"))
208}
209
210func (l modulesOrAliases) lastModule() *moduleInfo {
211 for i := range l {
212 if m := l[len(l)-1-i].module(); m != nil {
213 return m
214 }
215 }
216 panic(fmt.Errorf("no last module!"))
217}
218
Colin Crossbbfa51a2014-12-17 16:12:41 -0800219type moduleGroup struct {
Colin Crossed342d92015-03-11 00:57:25 -0700220 name string
221 ninjaName string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700222
Colin Cross5df74a82020-08-24 16:18:21 -0700223 modules modulesOrAliases
Jeff Gastond70bf752017-11-10 15:12:08 -0800224
225 namespace Namespace
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700226}
227
Colin Cross5df74a82020-08-24 16:18:21 -0700228func (group *moduleGroup) moduleOrAliasByVariantName(name string) moduleOrAlias {
229 for _, module := range group.modules {
230 if module.moduleOrAliasVariant().name == name {
231 return module
232 }
233 }
234 return nil
235}
236
237func (group *moduleGroup) moduleByVariantName(name string) *moduleInfo {
238 return group.moduleOrAliasByVariantName(name).module()
239}
240
Colin Crossbbfa51a2014-12-17 16:12:41 -0800241type moduleInfo struct {
Colin Crossed342d92015-03-11 00:57:25 -0700242 // set during Parse
243 typeName string
Colin Crossaf4fd212017-07-28 14:32:36 -0700244 factory ModuleFactory
Colin Crossed342d92015-03-11 00:57:25 -0700245 relBlueprintsFile string
246 pos scanner.Position
247 propertyPos map[string]scanner.Position
Colin Cross322cc012019-05-20 13:55:14 -0700248 createdBy *moduleInfo
Colin Crossed342d92015-03-11 00:57:25 -0700249
Colin Crossedc41762020-08-13 12:07:30 -0700250 variant variant
Colin Crosse7daa222015-03-11 14:35:41 -0700251
Colin Crossd2f4ac12017-07-28 14:31:03 -0700252 logicModule Module
253 group *moduleGroup
254 properties []interface{}
Colin Crossc9028482014-12-18 16:28:54 -0800255
256 // set during ResolveDependencies
Colin Cross99bdb2a2019-03-29 16:35:02 -0700257 missingDeps []string
258 newDirectDeps []depInfo
Colin Crossc9028482014-12-18 16:28:54 -0800259
Colin Cross7addea32015-03-11 15:43:52 -0700260 // set during updateDependencies
261 reverseDeps []*moduleInfo
Colin Cross3702ac72016-08-11 11:09:00 -0700262 forwardDeps []*moduleInfo
Colin Cross99bdb2a2019-03-29 16:35:02 -0700263 directDeps []depInfo
Colin Cross7addea32015-03-11 15:43:52 -0700264
Colin Crossc4773d92020-08-25 17:12:59 -0700265 // used by parallelVisit
Colin Cross7addea32015-03-11 15:43:52 -0700266 waitingCount int
267
Colin Crossc9028482014-12-18 16:28:54 -0800268 // set during each runMutator
Colin Cross5df74a82020-08-24 16:18:21 -0700269 splitModules modulesOrAliases
Colin Crossab6d7902015-03-11 16:17:52 -0700270
271 // set during PrepareBuildActions
272 actionDefs localBuildActions
Colin Cross2da84922020-07-02 10:08:12 -0700273
274 providers []interface{}
275
276 startedMutator *mutatorInfo
277 finishedMutator *mutatorInfo
278
279 startedGenerateBuildActions bool
280 finishedGenerateBuildActions bool
Colin Crossc9028482014-12-18 16:28:54 -0800281}
282
Colin Crossedc41762020-08-13 12:07:30 -0700283type variant struct {
284 name string
285 variations variationMap
286 dependencyVariations variationMap
287}
288
Colin Cross2c1f3d12016-04-11 15:47:28 -0700289type depInfo struct {
290 module *moduleInfo
291 tag DependencyTag
292}
293
Colin Cross0b7e83e2016-05-17 14:58:05 -0700294func (module *moduleInfo) Name() string {
Paul Duffin244033b2020-05-04 11:00:03 +0100295 // If this is called from a LoadHook (which is run before the module has been registered)
296 // then group will not be set and so the name is retrieved from logicModule.Name().
297 // Usually, using that method is not safe as it does not track renames (group.name does).
298 // However, when called from LoadHook it is safe as there is no way to rename a module
299 // until after the LoadHook has run and the module has been registered.
300 if module.group != nil {
301 return module.group.name
302 } else {
303 return module.logicModule.Name()
304 }
Colin Cross0b7e83e2016-05-17 14:58:05 -0700305}
306
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800307func (module *moduleInfo) String() string {
Colin Cross0b7e83e2016-05-17 14:58:05 -0700308 s := fmt.Sprintf("module %q", module.Name())
Colin Crossedc41762020-08-13 12:07:30 -0700309 if module.variant.name != "" {
310 s += fmt.Sprintf(" variant %q", module.variant.name)
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800311 }
Colin Cross322cc012019-05-20 13:55:14 -0700312 if module.createdBy != nil {
313 s += fmt.Sprintf(" (created by %s)", module.createdBy)
314 }
315
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800316 return s
317}
318
Jeff Gastond70bf752017-11-10 15:12:08 -0800319func (module *moduleInfo) namespace() Namespace {
320 return module.group.namespace
321}
322
Colin Crossf5e34b92015-03-13 16:02:36 -0700323// A Variation is a way that a variant of a module differs from other variants of the same module.
324// For example, two variants of the same module might have Variation{"arch","arm"} and
325// Variation{"arch","arm64"}
326type Variation struct {
327 // Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Colin Cross65569e42015-03-10 20:08:19 -0700328 Mutator string
Colin Crossf5e34b92015-03-13 16:02:36 -0700329 // Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
330 // "shared" or "static" for link.
331 Variation string
Colin Cross65569e42015-03-10 20:08:19 -0700332}
333
Colin Crossf5e34b92015-03-13 16:02:36 -0700334// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
335type variationMap map[string]string
Colin Crosse7daa222015-03-11 14:35:41 -0700336
Colin Crossf5e34b92015-03-13 16:02:36 -0700337func (vm variationMap) clone() variationMap {
Colin Cross9403b5a2019-11-13 20:11:04 -0800338 if vm == nil {
339 return nil
340 }
Colin Crossf5e34b92015-03-13 16:02:36 -0700341 newVm := make(variationMap)
Colin Crosse7daa222015-03-11 14:35:41 -0700342 for k, v := range vm {
343 newVm[k] = v
344 }
345
346 return newVm
Colin Crossc9028482014-12-18 16:28:54 -0800347}
348
Colin Cross89486232015-05-08 11:14:54 -0700349// Compare this variationMap to another one. Returns true if the every entry in this map
Colin Cross5dc67592020-08-24 14:46:13 -0700350// exists and has the same value in the other map.
351func (vm variationMap) subsetOf(other variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -0700352 for k, v1 := range vm {
Colin Cross5dc67592020-08-24 14:46:13 -0700353 if v2, ok := other[k]; !ok || v1 != v2 {
Colin Cross89486232015-05-08 11:14:54 -0700354 return false
355 }
356 }
357 return true
358}
359
Colin Crossf5e34b92015-03-13 16:02:36 -0700360func (vm variationMap) equal(other variationMap) bool {
Colin Crosse7daa222015-03-11 14:35:41 -0700361 return reflect.DeepEqual(vm, other)
Colin Crossbbfa51a2014-12-17 16:12:41 -0800362}
363
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700364type singletonInfo struct {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700365 // set during RegisterSingletonType
366 factory SingletonFactory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700367 singleton Singleton
Yuchen Wub9103ef2015-08-25 17:58:17 -0700368 name string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700369
370 // set during PrepareBuildActions
371 actionDefs localBuildActions
372}
373
Colin Crossc9028482014-12-18 16:28:54 -0800374type mutatorInfo struct {
375 // set during RegisterMutator
Colin Crossc0dbc552015-01-02 15:19:28 -0800376 topDownMutator TopDownMutator
377 bottomUpMutator BottomUpMutator
378 name string
Colin Cross49c279a2016-08-05 22:30:44 -0700379 parallel bool
Colin Crossc9028482014-12-18 16:28:54 -0800380}
381
Colin Crossaf4fd212017-07-28 14:32:36 -0700382func newContext() *Context {
383 return &Context{
Colin Cross3a8c0252019-01-23 13:21:48 -0800384 Context: context.Background(),
Colin Cross5f03f112017-11-07 13:29:54 -0800385 moduleFactories: make(map[string]ModuleFactory),
Jeff Gastond70bf752017-11-10 15:12:08 -0800386 nameInterface: NewSimpleNameInterface(),
Colin Cross5f03f112017-11-07 13:29:54 -0800387 moduleInfo: make(map[Module]*moduleInfo),
Colin Cross25236982021-04-05 17:20:34 -0700388 globs: make(map[globKey]pathtools.GlobResult),
Colin Cross5f03f112017-11-07 13:29:54 -0800389 fs: pathtools.OsFs,
Colin Cross2da84922020-07-02 10:08:12 -0700390 finishedMutators: make(map[*mutatorInfo]bool),
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +0200391 outDir: nil,
Colin Cross5f03f112017-11-07 13:29:54 -0800392 requiredNinjaMajor: 1,
393 requiredNinjaMinor: 7,
394 requiredNinjaMicro: 0,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700395 }
Colin Crossaf4fd212017-07-28 14:32:36 -0700396}
397
398// NewContext creates a new Context object. The created context initially has
399// no module or singleton factories registered, so the RegisterModuleFactory and
400// RegisterSingletonFactory methods must be called before it can do anything
401// useful.
402func NewContext() *Context {
403 ctx := newContext()
Colin Cross763b6f12015-10-29 15:32:56 -0700404
405 ctx.RegisterBottomUpMutator("blueprint_deps", blueprintDepsMutator)
406
407 return ctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700408}
409
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700410// A ModuleFactory function creates a new Module object. See the
411// Context.RegisterModuleType method for details about how a registered
412// ModuleFactory is used by a Context.
413type ModuleFactory func() (m Module, propertyStructs []interface{})
414
Jamie Gennisd4e10182014-06-12 20:06:50 -0700415// RegisterModuleType associates a module type name (which can appear in a
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700416// Blueprints file) with a Module factory function. When the given module type
417// name is encountered in a Blueprints file during parsing, the Module factory
418// is invoked to instantiate a new Module object to handle the build action
Colin Crossc9028482014-12-18 16:28:54 -0800419// generation for the module. If a Mutator splits a module into multiple variants,
420// the factory is invoked again to create a new Module for each variant.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700421//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700422// The module type names given here must be unique for the context. The factory
423// function should be a named function so that its package and name can be
424// included in the generated Ninja file for debugging purposes.
425//
426// The factory function returns two values. The first is the newly created
427// Module object. The second is a slice of pointers to that Module object's
428// properties structs. Each properties struct is examined when parsing a module
429// definition of this type in a Blueprints file. Exported fields of the
430// properties structs are automatically set to the property values specified in
431// the Blueprints file. The properties struct field names determine the name of
432// the Blueprints file properties that are used - the Blueprints property name
433// matches that of the properties struct field name with the first letter
434// converted to lower-case.
435//
436// The fields of the properties struct must be either []string, a string, or
437// bool. The Context will panic if a Module gets instantiated with a properties
438// struct containing a field that is not one these supported types.
439//
440// Any properties that appear in the Blueprints files that are not built-in
441// module properties (such as "name" and "deps") and do not have a corresponding
442// field in the returned module properties struct result in an error during the
443// Context's parse phase.
444//
445// As an example, the follow code:
446//
447// type myModule struct {
448// properties struct {
449// Foo string
450// Bar []string
451// }
452// }
453//
454// func NewMyModule() (blueprint.Module, []interface{}) {
455// module := new(myModule)
456// properties := &module.properties
457// return module, []interface{}{properties}
458// }
459//
460// func main() {
461// ctx := blueprint.NewContext()
462// ctx.RegisterModuleType("my_module", NewMyModule)
463// // ...
464// }
465//
466// would support parsing a module defined in a Blueprints file as follows:
467//
468// my_module {
469// name: "myName",
470// foo: "my foo string",
471// bar: ["my", "bar", "strings"],
472// }
473//
Colin Cross7ad621c2015-01-07 16:22:45 -0800474// The factory function may be called from multiple goroutines. Any accesses
475// to global variables must be synchronized.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700476func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
477 if _, present := c.moduleFactories[name]; present {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700478 panic(errors.New("module type name is already registered"))
479 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700480 c.moduleFactories[name] = factory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700481}
482
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700483// A SingletonFactory function creates a new Singleton object. See the
484// Context.RegisterSingletonType method for details about how a registered
485// SingletonFactory is used by a Context.
486type SingletonFactory func() Singleton
487
488// RegisterSingletonType registers a singleton type that will be invoked to
489// generate build actions. Each registered singleton type is instantiated and
Yuchen Wub9103ef2015-08-25 17:58:17 -0700490// and invoked exactly once as part of the generate phase. Each registered
491// singleton is invoked in registration order.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700492//
493// The singleton type names given here must be unique for the context. The
494// factory function should be a named function so that its package and name can
495// be included in the generated Ninja file for debugging purposes.
496func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
Yuchen Wub9103ef2015-08-25 17:58:17 -0700497 for _, s := range c.singletonInfo {
498 if s.name == name {
499 panic(errors.New("singleton name is already registered"))
500 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700501 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700502
Yuchen Wub9103ef2015-08-25 17:58:17 -0700503 c.singletonInfo = append(c.singletonInfo, &singletonInfo{
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700504 factory: factory,
505 singleton: factory(),
Yuchen Wub9103ef2015-08-25 17:58:17 -0700506 name: name,
507 })
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700508}
509
Colin Cross5f03f112017-11-07 13:29:54 -0800510// RegisterPreSingletonType registers a presingleton type that will be invoked to
511// generate build actions before any Blueprint files have been read. Each registered
512// presingleton type is instantiated and invoked exactly once at the beginning of the
513// parse phase. Each registered presingleton is invoked in registration order.
514//
515// The presingleton type names given here must be unique for the context. The
516// factory function should be a named function so that its package and name can
517// be included in the generated Ninja file for debugging purposes.
518func (c *Context) RegisterPreSingletonType(name string, factory SingletonFactory) {
519 for _, s := range c.preSingletonInfo {
520 if s.name == name {
521 panic(errors.New("presingleton name is already registered"))
522 }
523 }
524
525 c.preSingletonInfo = append(c.preSingletonInfo, &singletonInfo{
526 factory: factory,
527 singleton: factory(),
528 name: name,
529 })
530}
531
Jeff Gastond70bf752017-11-10 15:12:08 -0800532func (c *Context) SetNameInterface(i NameInterface) {
533 c.nameInterface = i
534}
535
Colin Crossc5fa50e2019-12-17 13:12:35 -0800536func (c *Context) SetSrcDir(path string) {
537 c.srcDir = path
538 c.fs = pathtools.NewOsFs(path)
539}
540
541func (c *Context) SrcDir() string {
542 return c.srcDir
543}
544
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700545func singletonPkgPath(singleton Singleton) string {
546 typ := reflect.TypeOf(singleton)
547 for typ.Kind() == reflect.Ptr {
548 typ = typ.Elem()
549 }
550 return typ.PkgPath()
551}
552
553func singletonTypeName(singleton Singleton) string {
554 typ := reflect.TypeOf(singleton)
555 for typ.Kind() == reflect.Ptr {
556 typ = typ.Elem()
557 }
558 return typ.PkgPath() + "." + typ.Name()
559}
560
Colin Cross3702ac72016-08-11 11:09:00 -0700561// RegisterTopDownMutator registers a mutator that will be invoked to propagate dependency info
562// top-down between Modules. Each registered mutator is invoked in registration order (mixing
563// TopDownMutators and BottomUpMutators) once per Module, and the invocation on any module will
564// have returned before it is in invoked on any of its dependencies.
Colin Crossc9028482014-12-18 16:28:54 -0800565//
Colin Cross65569e42015-03-10 20:08:19 -0700566// The mutator type names given here must be unique to all top down mutators in
567// the Context.
Colin Cross3702ac72016-08-11 11:09:00 -0700568//
569// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
570// parallel while maintaining ordering.
571func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) MutatorHandle {
Colin Crossc9028482014-12-18 16:28:54 -0800572 for _, m := range c.mutatorInfo {
573 if m.name == name && m.topDownMutator != nil {
574 panic(fmt.Errorf("mutator name %s is already registered", name))
575 }
576 }
577
Colin Cross3702ac72016-08-11 11:09:00 -0700578 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800579 topDownMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800580 name: name,
Colin Cross3702ac72016-08-11 11:09:00 -0700581 }
582
583 c.mutatorInfo = append(c.mutatorInfo, info)
584
585 return info
Colin Crossc9028482014-12-18 16:28:54 -0800586}
587
Colin Cross3702ac72016-08-11 11:09:00 -0700588// RegisterBottomUpMutator registers a mutator that will be invoked to split Modules into variants.
589// Each registered mutator is invoked in registration order (mixing TopDownMutators and
590// BottomUpMutators) once per Module, will not be invoked on a module until the invocations on all
591// of the modules dependencies have returned.
Colin Crossc9028482014-12-18 16:28:54 -0800592//
Colin Cross65569e42015-03-10 20:08:19 -0700593// The mutator type names given here must be unique to all bottom up or early
594// mutators in the Context.
Colin Cross49c279a2016-08-05 22:30:44 -0700595//
Colin Cross3702ac72016-08-11 11:09:00 -0700596// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
597// parallel while maintaining ordering.
598func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) MutatorHandle {
Colin Cross65569e42015-03-10 20:08:19 -0700599 for _, m := range c.variantMutatorNames {
600 if m == name {
Colin Crossc9028482014-12-18 16:28:54 -0800601 panic(fmt.Errorf("mutator name %s is already registered", name))
602 }
603 }
604
Colin Cross49c279a2016-08-05 22:30:44 -0700605 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800606 bottomUpMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800607 name: name,
Colin Cross49c279a2016-08-05 22:30:44 -0700608 }
609 c.mutatorInfo = append(c.mutatorInfo, info)
Colin Cross65569e42015-03-10 20:08:19 -0700610
611 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Cross49c279a2016-08-05 22:30:44 -0700612
613 return info
614}
615
Colin Cross3702ac72016-08-11 11:09:00 -0700616type MutatorHandle interface {
617 // Set the mutator to visit modules in parallel while maintaining ordering. Calling any
618 // method on the mutator context is thread-safe, but the mutator must handle synchronization
619 // for any modifications to global state or any modules outside the one it was invoked on.
620 Parallel() MutatorHandle
Colin Cross49c279a2016-08-05 22:30:44 -0700621}
622
Colin Cross3702ac72016-08-11 11:09:00 -0700623func (mutator *mutatorInfo) Parallel() MutatorHandle {
Colin Cross49c279a2016-08-05 22:30:44 -0700624 mutator.parallel = true
625 return mutator
Colin Cross65569e42015-03-10 20:08:19 -0700626}
627
628// RegisterEarlyMutator registers a mutator that will be invoked to split
629// Modules into multiple variant Modules before any dependencies have been
630// created. Each registered mutator is invoked in registration order once
631// per Module (including each variant from previous early mutators). Module
632// order is unpredictable.
633//
634// In order for dependencies to be satisifed in a later pass, all dependencies
Colin Crossf5e34b92015-03-13 16:02:36 -0700635// of a module either must have an identical variant or must have no variations.
Colin Cross65569e42015-03-10 20:08:19 -0700636//
637// The mutator type names given here must be unique to all bottom up or early
638// mutators in the Context.
Colin Cross763b6f12015-10-29 15:32:56 -0700639//
640// Deprecated, use a BottomUpMutator instead. The only difference between
641// EarlyMutator and BottomUpMutator is that EarlyMutator runs before the
642// deprecated DynamicDependencies.
Colin Cross65569e42015-03-10 20:08:19 -0700643func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
644 for _, m := range c.variantMutatorNames {
645 if m == name {
646 panic(fmt.Errorf("mutator name %s is already registered", name))
647 }
648 }
649
Colin Crossf8b50422016-08-10 12:56:40 -0700650 c.earlyMutatorInfo = append(c.earlyMutatorInfo, &mutatorInfo{
651 bottomUpMutator: func(mctx BottomUpMutatorContext) {
652 mutator(mctx)
653 },
654 name: name,
Colin Cross65569e42015-03-10 20:08:19 -0700655 })
656
657 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Crossc9028482014-12-18 16:28:54 -0800658}
659
Jamie Gennisd4e10182014-06-12 20:06:50 -0700660// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
661// where it encounters an unknown module type while parsing Blueprints files. By
662// default, the context will report unknown module types as an error. If this
663// method is called with ignoreUnknownModuleTypes set to true then the context
664// will silently ignore unknown module types.
665//
666// This method should generally not be used. It exists to facilitate the
667// bootstrapping process.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700668func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
669 c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
670}
671
Colin Cross036a1df2015-12-17 15:49:30 -0800672// SetAllowMissingDependencies changes the behavior of Blueprint to ignore
673// unresolved dependencies. If the module's GenerateBuildActions calls
674// ModuleContext.GetMissingDependencies Blueprint will not emit any errors
675// for missing dependencies.
676func (c *Context) SetAllowMissingDependencies(allowMissingDependencies bool) {
677 c.allowMissingDependencies = allowMissingDependencies
678}
679
Jeff Gastonc3e28442017-08-09 15:13:12 -0700680func (c *Context) SetModuleListFile(listFile string) {
681 c.moduleListFile = listFile
682}
683
684func (c *Context) ListModulePaths(baseDir string) (paths []string, err error) {
685 reader, err := c.fs.Open(c.moduleListFile)
686 if err != nil {
687 return nil, err
688 }
689 bytes, err := ioutil.ReadAll(reader)
690 if err != nil {
691 return nil, err
692 }
693 text := string(bytes)
694
695 text = strings.Trim(text, "\n")
696 lines := strings.Split(text, "\n")
697 for i := range lines {
698 lines[i] = filepath.Join(baseDir, lines[i])
699 }
700
701 return lines, nil
702}
703
Jeff Gaston656870f2017-11-29 18:37:31 -0800704// a fileParseContext tells the status of parsing a particular file
705type fileParseContext struct {
706 // name of file
707 fileName string
708
709 // scope to use when resolving variables
710 Scope *parser.Scope
711
712 // pointer to the one in the parent directory
713 parent *fileParseContext
714
715 // is closed once FileHandler has completed for this file
716 doneVisiting chan struct{}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700717}
718
Jamie Gennisd4e10182014-06-12 20:06:50 -0700719// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
720// at rootFile. When it encounters a Blueprints file with a set of subdirs
721// listed it recursively parses any Blueprints files found in those
722// subdirectories.
723//
724// If no errors are encountered while parsing the files, the list of paths on
725// which the future output will depend is returned. This list will include both
726// Blueprints file paths as well as directory paths for cases where wildcard
727// subdirs are found.
Colin Crossda70fd02019-12-30 18:40:09 -0800728func (c *Context) ParseBlueprintsFiles(rootFile string,
729 config interface{}) (deps []string, errs []error) {
730
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800731 baseDir := filepath.Dir(rootFile)
732 pathsToParse, err := c.ListModulePaths(baseDir)
733 if err != nil {
734 return nil, []error{err}
735 }
Colin Crossda70fd02019-12-30 18:40:09 -0800736 return c.ParseFileList(baseDir, pathsToParse, config)
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800737}
738
Colin Crossda70fd02019-12-30 18:40:09 -0800739func (c *Context) ParseFileList(rootDir string, filePaths []string,
740 config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700741
Jeff Gastonc3e28442017-08-09 15:13:12 -0700742 if len(filePaths) < 1 {
743 return nil, []error{fmt.Errorf("no paths provided to parse")}
744 }
745
Colin Cross7ad621c2015-01-07 16:22:45 -0800746 c.dependenciesReady = false
747
Colin Crossda70fd02019-12-30 18:40:09 -0800748 type newModuleInfo struct {
749 *moduleInfo
Colin Cross13b5bef2021-05-19 10:07:19 -0700750 deps []string
Colin Crossda70fd02019-12-30 18:40:09 -0800751 added chan<- struct{}
752 }
753
754 moduleCh := make(chan newModuleInfo)
Colin Cross23d7aa12015-06-30 16:05:22 -0700755 errsCh := make(chan []error)
756 doneCh := make(chan struct{})
757 var numErrs uint32
758 var numGoroutines int32
759
760 // handler must be reentrant
Jeff Gaston5f763d02017-08-08 14:43:58 -0700761 handleOneFile := func(file *parser.File) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700762 if atomic.LoadUint32(&numErrs) > maxErrors {
763 return
764 }
765
Colin Crossda70fd02019-12-30 18:40:09 -0800766 addedCh := make(chan struct{})
767
Colin Cross9672d862019-12-30 18:38:20 -0800768 var scopedModuleFactories map[string]ModuleFactory
769
Colin Crossda70fd02019-12-30 18:40:09 -0800770 var addModule func(module *moduleInfo) []error
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100771 addModule = func(module *moduleInfo) []error {
Paul Duffin244033b2020-05-04 11:00:03 +0100772 // Run any load hooks immediately before it is sent to the moduleCh and is
773 // registered by name. This allows load hooks to set and/or modify any aspect
774 // of the module (including names) using information that is not available when
775 // the module factory is called.
Colin Cross13b5bef2021-05-19 10:07:19 -0700776 newModules, newDeps, errs := runAndRemoveLoadHooks(c, config, module, &scopedModuleFactories)
Colin Crossda70fd02019-12-30 18:40:09 -0800777 if len(errs) > 0 {
778 return errs
779 }
Paul Duffin244033b2020-05-04 11:00:03 +0100780
Colin Cross13b5bef2021-05-19 10:07:19 -0700781 moduleCh <- newModuleInfo{module, newDeps, addedCh}
Paul Duffin244033b2020-05-04 11:00:03 +0100782 <-addedCh
Colin Crossda70fd02019-12-30 18:40:09 -0800783 for _, n := range newModules {
784 errs = addModule(n)
785 if len(errs) > 0 {
786 return errs
787 }
788 }
789 return nil
790 }
791
Jeff Gaston656870f2017-11-29 18:37:31 -0800792 for _, def := range file.Defs {
Jeff Gaston656870f2017-11-29 18:37:31 -0800793 switch def := def.(type) {
794 case *parser.Module:
Paul Duffin2a2c58e2020-05-13 09:06:17 +0100795 module, errs := processModuleDef(def, file.Name, c.moduleFactories, scopedModuleFactories, c.ignoreUnknownModuleTypes)
Colin Crossda70fd02019-12-30 18:40:09 -0800796 if len(errs) == 0 && module != nil {
797 errs = addModule(module)
798 }
799
800 if len(errs) > 0 {
801 atomic.AddUint32(&numErrs, uint32(len(errs)))
802 errsCh <- errs
803 }
804
Jeff Gaston656870f2017-11-29 18:37:31 -0800805 case *parser.Assignment:
806 // Already handled via Scope object
807 default:
808 panic("unknown definition type")
Colin Cross23d7aa12015-06-30 16:05:22 -0700809 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800810
Jeff Gaston656870f2017-11-29 18:37:31 -0800811 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700812 }
813
814 atomic.AddInt32(&numGoroutines, 1)
815 go func() {
816 var errs []error
Jeff Gastonc3e28442017-08-09 15:13:12 -0700817 deps, errs = c.WalkBlueprintsFiles(rootDir, filePaths, handleOneFile)
Colin Cross23d7aa12015-06-30 16:05:22 -0700818 if len(errs) > 0 {
819 errsCh <- errs
820 }
821 doneCh <- struct{}{}
822 }()
823
Colin Cross13b5bef2021-05-19 10:07:19 -0700824 var hookDeps []string
Colin Cross23d7aa12015-06-30 16:05:22 -0700825loop:
826 for {
827 select {
828 case newErrs := <-errsCh:
829 errs = append(errs, newErrs...)
830 case module := <-moduleCh:
Colin Crossda70fd02019-12-30 18:40:09 -0800831 newErrs := c.addModule(module.moduleInfo)
Colin Cross13b5bef2021-05-19 10:07:19 -0700832 hookDeps = append(hookDeps, module.deps...)
Colin Crossda70fd02019-12-30 18:40:09 -0800833 if module.added != nil {
834 module.added <- struct{}{}
835 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700836 if len(newErrs) > 0 {
837 errs = append(errs, newErrs...)
838 }
839 case <-doneCh:
840 n := atomic.AddInt32(&numGoroutines, -1)
841 if n == 0 {
842 break loop
843 }
844 }
845 }
846
Colin Cross13b5bef2021-05-19 10:07:19 -0700847 deps = append(deps, hookDeps...)
Colin Cross23d7aa12015-06-30 16:05:22 -0700848 return deps, errs
849}
850
851type FileHandler func(*parser.File)
852
Jeff Gastonc3e28442017-08-09 15:13:12 -0700853// WalkBlueprintsFiles walks a set of Blueprints files starting with the given filepaths,
854// calling the given file handler on each
855//
856// When WalkBlueprintsFiles encounters a Blueprints file with a set of subdirs listed,
857// it recursively parses any Blueprints files found in those subdirectories.
858//
859// If any of the file paths is an ancestor directory of any other of file path, the ancestor
860// will be parsed and visited first.
861//
862// the file handler will be called from a goroutine, so it must be reentrant.
Colin Cross23d7aa12015-06-30 16:05:22 -0700863//
864// If no errors are encountered while parsing the files, the list of paths on
865// which the future output will depend is returned. This list will include both
866// Blueprints file paths as well as directory paths for cases where wildcard
867// subdirs are found.
Jeff Gaston656870f2017-11-29 18:37:31 -0800868//
869// visitor will be called asynchronously, and will only be called once visitor for each
870// ancestor directory has completed.
871//
872// WalkBlueprintsFiles will not return until all calls to visitor have returned.
Jeff Gastonc3e28442017-08-09 15:13:12 -0700873func (c *Context) WalkBlueprintsFiles(rootDir string, filePaths []string,
874 visitor FileHandler) (deps []string, errs []error) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700875
Jeff Gastonc3e28442017-08-09 15:13:12 -0700876 // make a mapping from ancestors to their descendants to facilitate parsing ancestors first
877 descendantsMap, err := findBlueprintDescendants(filePaths)
878 if err != nil {
879 panic(err.Error())
Jeff Gastonc3e28442017-08-09 15:13:12 -0700880 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800881 blueprintsSet := make(map[string]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700882
Jeff Gaston5800d042017-12-05 14:57:58 -0800883 // Channels to receive data back from openAndParse goroutines
Jeff Gaston656870f2017-11-29 18:37:31 -0800884 blueprintsCh := make(chan fileParseContext)
Colin Cross7ad621c2015-01-07 16:22:45 -0800885 errsCh := make(chan []error)
Colin Cross7ad621c2015-01-07 16:22:45 -0800886 depsCh := make(chan string)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700887
Jeff Gaston5800d042017-12-05 14:57:58 -0800888 // Channel to notify main loop that a openAndParse goroutine has finished
Jeff Gaston656870f2017-11-29 18:37:31 -0800889 doneParsingCh := make(chan fileParseContext)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700890
Colin Cross7ad621c2015-01-07 16:22:45 -0800891 // Number of outstanding goroutines to wait for
Jeff Gaston5f763d02017-08-08 14:43:58 -0700892 activeCount := 0
Jeff Gaston656870f2017-11-29 18:37:31 -0800893 var pending []fileParseContext
Jeff Gastonc3e28442017-08-09 15:13:12 -0700894 tooManyErrors := false
895
896 // Limit concurrent calls to parseBlueprintFiles to 200
897 // Darwin has a default limit of 256 open files
898 maxActiveCount := 200
Colin Cross7ad621c2015-01-07 16:22:45 -0800899
Jeff Gaston656870f2017-11-29 18:37:31 -0800900 // count the number of pending calls to visitor()
901 visitorWaitGroup := sync.WaitGroup{}
902
903 startParseBlueprintsFile := func(blueprint fileParseContext) {
904 if blueprintsSet[blueprint.fileName] {
Colin Cross4a02a302017-05-16 10:33:58 -0700905 return
906 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800907 blueprintsSet[blueprint.fileName] = true
Jeff Gaston5f763d02017-08-08 14:43:58 -0700908 activeCount++
Jeff Gaston656870f2017-11-29 18:37:31 -0800909 deps = append(deps, blueprint.fileName)
910 visitorWaitGroup.Add(1)
Colin Cross7ad621c2015-01-07 16:22:45 -0800911 go func() {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800912 file, blueprints, deps, errs := c.openAndParse(blueprint.fileName, blueprint.Scope, rootDir,
913 &blueprint)
914 if len(errs) > 0 {
915 errsCh <- errs
916 }
917 for _, blueprint := range blueprints {
918 blueprintsCh <- blueprint
919 }
920 for _, dep := range deps {
921 depsCh <- dep
922 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800923 doneParsingCh <- blueprint
Jeff Gaston5f763d02017-08-08 14:43:58 -0700924
Jeff Gaston656870f2017-11-29 18:37:31 -0800925 if blueprint.parent != nil && blueprint.parent.doneVisiting != nil {
926 // wait for visitor() of parent to complete
927 <-blueprint.parent.doneVisiting
928 }
929
Jeff Gastona7e408a2017-12-05 15:11:55 -0800930 if len(errs) == 0 {
931 // process this file
932 visitor(file)
933 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800934 if blueprint.doneVisiting != nil {
935 close(blueprint.doneVisiting)
936 }
937 visitorWaitGroup.Done()
Colin Cross7ad621c2015-01-07 16:22:45 -0800938 }()
939 }
940
Jeff Gaston656870f2017-11-29 18:37:31 -0800941 foundParseableBlueprint := func(blueprint fileParseContext) {
Jeff Gastonc3e28442017-08-09 15:13:12 -0700942 if activeCount >= maxActiveCount {
943 pending = append(pending, blueprint)
944 } else {
945 startParseBlueprintsFile(blueprint)
946 }
947 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800948
Jeff Gaston656870f2017-11-29 18:37:31 -0800949 startParseDescendants := func(blueprint fileParseContext) {
950 descendants, hasDescendants := descendantsMap[blueprint.fileName]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700951 if hasDescendants {
952 for _, descendant := range descendants {
Jeff Gaston656870f2017-11-29 18:37:31 -0800953 foundParseableBlueprint(fileParseContext{descendant, parser.NewScope(blueprint.Scope), &blueprint, make(chan struct{})})
Jeff Gastonc3e28442017-08-09 15:13:12 -0700954 }
955 }
956 }
Colin Cross4a02a302017-05-16 10:33:58 -0700957
Jeff Gastonc3e28442017-08-09 15:13:12 -0700958 // begin parsing any files that have no ancestors
Jeff Gaston656870f2017-11-29 18:37:31 -0800959 startParseDescendants(fileParseContext{"", parser.NewScope(nil), nil, nil})
Colin Cross7ad621c2015-01-07 16:22:45 -0800960
961loop:
962 for {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700963 if len(errs) > maxErrors {
Colin Cross7ad621c2015-01-07 16:22:45 -0800964 tooManyErrors = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700965 }
966
Colin Cross7ad621c2015-01-07 16:22:45 -0800967 select {
968 case newErrs := <-errsCh:
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700969 errs = append(errs, newErrs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800970 case dep := <-depsCh:
971 deps = append(deps, dep)
Colin Cross7ad621c2015-01-07 16:22:45 -0800972 case blueprint := <-blueprintsCh:
973 if tooManyErrors {
974 continue
975 }
Jeff Gastonc3e28442017-08-09 15:13:12 -0700976 foundParseableBlueprint(blueprint)
Jeff Gaston656870f2017-11-29 18:37:31 -0800977 case blueprint := <-doneParsingCh:
Jeff Gaston5f763d02017-08-08 14:43:58 -0700978 activeCount--
Jeff Gastonc3e28442017-08-09 15:13:12 -0700979 if !tooManyErrors {
980 startParseDescendants(blueprint)
981 }
982 if activeCount < maxActiveCount && len(pending) > 0 {
983 // start to process the next one from the queue
984 next := pending[len(pending)-1]
Colin Cross4a02a302017-05-16 10:33:58 -0700985 pending = pending[:len(pending)-1]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700986 startParseBlueprintsFile(next)
Colin Cross4a02a302017-05-16 10:33:58 -0700987 }
Jeff Gaston5f763d02017-08-08 14:43:58 -0700988 if activeCount == 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -0800989 break loop
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700990 }
991 }
992 }
993
Jeff Gastonc3e28442017-08-09 15:13:12 -0700994 sort.Strings(deps)
995
Jeff Gaston656870f2017-11-29 18:37:31 -0800996 // wait for every visitor() to complete
997 visitorWaitGroup.Wait()
998
Colin Cross7ad621c2015-01-07 16:22:45 -0800999 return
1000}
1001
Colin Crossd7b0f602016-06-02 15:30:20 -07001002// MockFileSystem causes the Context to replace all reads with accesses to the provided map of
1003// filenames to contents stored as a byte slice.
1004func (c *Context) MockFileSystem(files map[string][]byte) {
Jeff Gaston9f630902017-11-15 14:49:48 -08001005 // look for a module list file
1006 _, ok := files[MockModuleListFile]
1007 if !ok {
1008 // no module list file specified; find every file named Blueprints
1009 pathsToParse := []string{}
1010 for candidate := range files {
Lukacs T. Berkieef56852021-09-02 11:34:06 +02001011 if filepath.Base(candidate) == "Android.bp" {
Jeff Gaston9f630902017-11-15 14:49:48 -08001012 pathsToParse = append(pathsToParse, candidate)
1013 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001014 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001015 if len(pathsToParse) < 1 {
1016 panic(fmt.Sprintf("No Blueprints files found in mock filesystem: %v\n", files))
1017 }
1018 // put the list of Blueprints files into a list file
1019 files[MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
Jeff Gastonc3e28442017-08-09 15:13:12 -07001020 }
Jeff Gaston9f630902017-11-15 14:49:48 -08001021 c.SetModuleListFile(MockModuleListFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001022
1023 // mock the filesystem
Colin Crossb519a7e2017-02-01 13:21:35 -08001024 c.fs = pathtools.MockFs(files)
Colin Crossd7b0f602016-06-02 15:30:20 -07001025}
1026
Colin Cross8cde4252019-12-17 13:11:21 -08001027func (c *Context) SetFs(fs pathtools.FileSystem) {
1028 c.fs = fs
1029}
1030
Jeff Gaston8fd95782017-12-05 15:03:51 -08001031// openAndParse opens and parses a single Blueprints file, and returns the results
Jeff Gaston5800d042017-12-05 14:57:58 -08001032func (c *Context) openAndParse(filename string, scope *parser.Scope, rootDir string,
Jeff Gaston8fd95782017-12-05 15:03:51 -08001033 parent *fileParseContext) (file *parser.File,
1034 subBlueprints []fileParseContext, deps []string, errs []error) {
Colin Cross7ad621c2015-01-07 16:22:45 -08001035
Colin Crossd7b0f602016-06-02 15:30:20 -07001036 f, err := c.fs.Open(filename)
Colin Cross7ad621c2015-01-07 16:22:45 -08001037 if err != nil {
Jeff Gastonaca42202017-08-23 17:30:05 -07001038 // couldn't open the file; see if we can provide a clearer error than "could not open file"
1039 stats, statErr := c.fs.Lstat(filename)
1040 if statErr == nil {
1041 isSymlink := stats.Mode()&os.ModeSymlink != 0
1042 if isSymlink {
1043 err = fmt.Errorf("could not open symlink %v : %v", filename, err)
1044 target, readlinkErr := os.Readlink(filename)
1045 if readlinkErr == nil {
1046 _, targetStatsErr := c.fs.Lstat(target)
1047 if targetStatsErr != nil {
1048 err = fmt.Errorf("could not open symlink %v; its target (%v) cannot be opened", filename, target)
1049 }
1050 }
1051 } else {
1052 err = fmt.Errorf("%v exists but could not be opened: %v", filename, err)
1053 }
1054 }
Jeff Gaston8fd95782017-12-05 15:03:51 -08001055 return nil, nil, nil, []error{err}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001056 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001057
Jeff Gaston8fd95782017-12-05 15:03:51 -08001058 func() {
1059 defer func() {
1060 err = f.Close()
1061 if err != nil {
1062 errs = append(errs, err)
1063 }
1064 }()
1065 file, subBlueprints, errs = c.parseOne(rootDir, filename, f, scope, parent)
Colin Cross23d7aa12015-06-30 16:05:22 -07001066 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001067
Colin Cross7ad621c2015-01-07 16:22:45 -08001068 if len(errs) > 0 {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001069 return nil, nil, nil, errs
Colin Cross7ad621c2015-01-07 16:22:45 -08001070 }
1071
Colin Cross1fef5362015-04-20 16:50:54 -07001072 for _, b := range subBlueprints {
Jeff Gaston8fd95782017-12-05 15:03:51 -08001073 deps = append(deps, b.fileName)
Colin Cross1fef5362015-04-20 16:50:54 -07001074 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001075
Jeff Gaston8fd95782017-12-05 15:03:51 -08001076 return file, subBlueprints, deps, nil
Colin Cross1fef5362015-04-20 16:50:54 -07001077}
1078
Jeff Gastona12f22f2017-08-08 14:45:56 -07001079// parseOne parses a single Blueprints file from the given reader, creating Module
1080// objects for each of the module definitions encountered. If the Blueprints
1081// file contains an assignment to the "subdirs" variable, then the
1082// subdirectories listed are searched for Blueprints files returned in the
1083// subBlueprints return value. If the Blueprints file contains an assignment
1084// to the "build" variable, then the file listed are returned in the
1085// subBlueprints return value.
1086//
1087// rootDir specifies the path to the root directory of the source tree, while
1088// filename specifies the path to the Blueprints file. These paths are used for
1089// error reporting and for determining the module's directory.
1090func (c *Context) parseOne(rootDir, filename string, reader io.Reader,
Jeff Gaston656870f2017-11-29 18:37:31 -08001091 scope *parser.Scope, parent *fileParseContext) (file *parser.File, subBlueprints []fileParseContext, errs []error) {
Jeff Gastona12f22f2017-08-08 14:45:56 -07001092
1093 relBlueprintsFile, err := filepath.Rel(rootDir, filename)
1094 if err != nil {
1095 return nil, nil, []error{err}
1096 }
1097
Jeff Gastona12f22f2017-08-08 14:45:56 -07001098 scope.Remove("subdirs")
1099 scope.Remove("optional_subdirs")
1100 scope.Remove("build")
1101 file, errs = parser.ParseAndEval(filename, reader, scope)
1102 if len(errs) > 0 {
1103 for i, err := range errs {
1104 if parseErr, ok := err.(*parser.ParseError); ok {
1105 err = &BlueprintError{
1106 Err: parseErr.Err,
1107 Pos: parseErr.Pos,
1108 }
1109 errs[i] = err
1110 }
1111 }
1112
1113 // If there were any parse errors don't bother trying to interpret the
1114 // result.
1115 return nil, nil, errs
1116 }
1117 file.Name = relBlueprintsFile
1118
Jeff Gastona12f22f2017-08-08 14:45:56 -07001119 build, buildPos, err := getLocalStringListFromScope(scope, "build")
1120 if err != nil {
1121 errs = append(errs, err)
1122 }
Jeff Gastonf23e3662017-11-30 17:31:43 -08001123 for _, buildEntry := range build {
1124 if strings.Contains(buildEntry, "/") {
1125 errs = append(errs, &BlueprintError{
1126 Err: fmt.Errorf("illegal value %v. The '/' character is not permitted", buildEntry),
1127 Pos: buildPos,
1128 })
1129 }
1130 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001131
Jeff Gastona12f22f2017-08-08 14:45:56 -07001132 if err != nil {
1133 errs = append(errs, err)
1134 }
1135
Jeff Gastona12f22f2017-08-08 14:45:56 -07001136 var blueprints []string
1137
1138 newBlueprints, newErrs := c.findBuildBlueprints(filepath.Dir(filename), build, buildPos)
1139 blueprints = append(blueprints, newBlueprints...)
1140 errs = append(errs, newErrs...)
1141
Jeff Gaston656870f2017-11-29 18:37:31 -08001142 subBlueprintsAndScope := make([]fileParseContext, len(blueprints))
Jeff Gastona12f22f2017-08-08 14:45:56 -07001143 for i, b := range blueprints {
Jeff Gaston656870f2017-11-29 18:37:31 -08001144 subBlueprintsAndScope[i] = fileParseContext{b, parser.NewScope(scope), parent, make(chan struct{})}
Jeff Gastona12f22f2017-08-08 14:45:56 -07001145 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001146 return file, subBlueprintsAndScope, errs
1147}
1148
Colin Cross7f507402015-12-16 13:03:41 -08001149func (c *Context) findBuildBlueprints(dir string, build []string,
Colin Cross127d2ea2016-11-01 11:10:51 -07001150 buildPos scanner.Position) ([]string, []error) {
1151
1152 var blueprints []string
1153 var errs []error
Colin Cross7f507402015-12-16 13:03:41 -08001154
1155 for _, file := range build {
Colin Cross127d2ea2016-11-01 11:10:51 -07001156 pattern := filepath.Join(dir, file)
1157 var matches []string
1158 var err error
1159
Colin Cross08e49542016-11-14 15:23:33 -08001160 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001161
Colin Cross7f507402015-12-16 13:03:41 -08001162 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001163 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001164 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross7f507402015-12-16 13:03:41 -08001165 Pos: buildPos,
1166 })
1167 continue
1168 }
1169
1170 if len(matches) == 0 {
Colin Cross2c628442016-10-07 17:13:10 -07001171 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001172 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross7f507402015-12-16 13:03:41 -08001173 Pos: buildPos,
1174 })
1175 }
1176
Colin Cross7f507402015-12-16 13:03:41 -08001177 for _, foundBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001178 if strings.HasSuffix(foundBlueprints, "/") {
1179 errs = append(errs, &BlueprintError{
1180 Err: fmt.Errorf("%q: is a directory", foundBlueprints),
1181 Pos: buildPos,
1182 })
1183 }
Colin Cross7f507402015-12-16 13:03:41 -08001184 blueprints = append(blueprints, foundBlueprints)
1185 }
1186 }
1187
Colin Cross127d2ea2016-11-01 11:10:51 -07001188 return blueprints, errs
Colin Cross7f507402015-12-16 13:03:41 -08001189}
1190
1191func (c *Context) findSubdirBlueprints(dir string, subdirs []string, subdirsPos scanner.Position,
Colin Cross127d2ea2016-11-01 11:10:51 -07001192 subBlueprintsName string, optional bool) ([]string, []error) {
1193
1194 var blueprints []string
1195 var errs []error
Colin Cross7ad621c2015-01-07 16:22:45 -08001196
1197 for _, subdir := range subdirs {
Colin Cross127d2ea2016-11-01 11:10:51 -07001198 pattern := filepath.Join(dir, subdir, subBlueprintsName)
1199 var matches []string
1200 var err error
1201
Colin Cross08e49542016-11-14 15:23:33 -08001202 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001203
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001204 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001205 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001206 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross1fef5362015-04-20 16:50:54 -07001207 Pos: subdirsPos,
1208 })
1209 continue
1210 }
1211
Colin Cross7f507402015-12-16 13:03:41 -08001212 if len(matches) == 0 && !optional {
Colin Cross2c628442016-10-07 17:13:10 -07001213 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001214 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross1fef5362015-04-20 16:50:54 -07001215 Pos: subdirsPos,
1216 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001217 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001218
Colin Cross127d2ea2016-11-01 11:10:51 -07001219 for _, subBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001220 if strings.HasSuffix(subBlueprints, "/") {
1221 errs = append(errs, &BlueprintError{
1222 Err: fmt.Errorf("%q: is a directory", subBlueprints),
1223 Pos: subdirsPos,
1224 })
1225 }
Colin Cross127d2ea2016-11-01 11:10:51 -07001226 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -08001227 }
1228 }
Colin Cross1fef5362015-04-20 16:50:54 -07001229
Colin Cross127d2ea2016-11-01 11:10:51 -07001230 return blueprints, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001231}
1232
Colin Cross6d8780f2015-07-10 17:51:55 -07001233func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
1234 if assignment, local := scope.Get(v); assignment == nil || !local {
1235 return nil, scanner.Position{}, nil
1236 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001237 switch value := assignment.Value.Eval().(type) {
1238 case *parser.List:
1239 ret := make([]string, 0, len(value.Values))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001240
Colin Crosse32cc802016-06-07 12:28:16 -07001241 for _, listValue := range value.Values {
1242 s, ok := listValue.(*parser.String)
1243 if !ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001244 // The parser should not produce this.
1245 panic("non-string value found in list")
1246 }
1247
Colin Crosse32cc802016-06-07 12:28:16 -07001248 ret = append(ret, s.Value)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001249 }
1250
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001251 return ret, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001252 case *parser.Bool, *parser.String:
Colin Cross2c628442016-10-07 17:13:10 -07001253 return nil, scanner.Position{}, &BlueprintError{
Colin Cross1fef5362015-04-20 16:50:54 -07001254 Err: fmt.Errorf("%q must be a list of strings", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001255 Pos: assignment.EqualsPos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001256 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001257 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001258 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001259 }
1260 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001261}
1262
Colin Cross29394222015-04-27 13:18:21 -07001263func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -07001264 if assignment, _ := scope.Get(v); assignment == nil {
1265 return "", scanner.Position{}, nil
1266 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001267 switch value := assignment.Value.Eval().(type) {
1268 case *parser.String:
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001269 return value.Value, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001270 case *parser.Bool, *parser.List:
Colin Cross2c628442016-10-07 17:13:10 -07001271 return "", scanner.Position{}, &BlueprintError{
Colin Cross29394222015-04-27 13:18:21 -07001272 Err: fmt.Errorf("%q must be a string", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001273 Pos: assignment.EqualsPos,
Colin Cross29394222015-04-27 13:18:21 -07001274 }
1275 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001276 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Colin Cross29394222015-04-27 13:18:21 -07001277 }
1278 }
Colin Cross29394222015-04-27 13:18:21 -07001279}
1280
Colin Cross910242b2016-04-11 15:41:52 -07001281// Clones a build logic module by calling the factory method for its module type, and then cloning
1282// property values. Any values stored in the module object that are not stored in properties
1283// structs will be lost.
1284func (c *Context) cloneLogicModule(origModule *moduleInfo) (Module, []interface{}) {
Colin Crossaf4fd212017-07-28 14:32:36 -07001285 newLogicModule, newProperties := origModule.factory()
Colin Cross910242b2016-04-11 15:41:52 -07001286
Colin Crossd2f4ac12017-07-28 14:31:03 -07001287 if len(newProperties) != len(origModule.properties) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001288 panic("mismatched properties array length in " + origModule.Name())
Colin Cross910242b2016-04-11 15:41:52 -07001289 }
1290
1291 for i := range newProperties {
Colin Cross5d57b2d2020-01-27 16:14:31 -08001292 dst := reflect.ValueOf(newProperties[i])
1293 src := reflect.ValueOf(origModule.properties[i])
Colin Cross910242b2016-04-11 15:41:52 -07001294
1295 proptools.CopyProperties(dst, src)
1296 }
1297
1298 return newLogicModule, newProperties
1299}
1300
Colin Crossedc41762020-08-13 12:07:30 -07001301func newVariant(module *moduleInfo, mutatorName string, variationName string,
1302 local bool) variant {
1303
1304 newVariantName := module.variant.name
1305 if variationName != "" {
1306 if newVariantName == "" {
1307 newVariantName = variationName
1308 } else {
1309 newVariantName += "_" + variationName
1310 }
1311 }
1312
1313 newVariations := module.variant.variations.clone()
1314 if newVariations == nil {
1315 newVariations = make(variationMap)
1316 }
1317 newVariations[mutatorName] = variationName
1318
1319 newDependencyVariations := module.variant.dependencyVariations.clone()
1320 if !local {
1321 if newDependencyVariations == nil {
1322 newDependencyVariations = make(variationMap)
1323 }
1324 newDependencyVariations[mutatorName] = variationName
1325 }
1326
1327 return variant{newVariantName, newVariations, newDependencyVariations}
1328}
1329
Colin Crossf5e34b92015-03-13 16:02:36 -07001330func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
Colin Cross5df74a82020-08-24 16:18:21 -07001331 defaultVariationName *string, variationNames []string, local bool) (modulesOrAliases, []error) {
Colin Crossc9028482014-12-18 16:28:54 -08001332
Colin Crossf4d18a62015-03-18 17:43:15 -07001333 if len(variationNames) == 0 {
1334 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001335 mutatorName, origModule.Name()))
Colin Crossf4d18a62015-03-18 17:43:15 -07001336 }
1337
Colin Cross5df74a82020-08-24 16:18:21 -07001338 var newModules modulesOrAliases
Colin Crossc9028482014-12-18 16:28:54 -08001339
Colin Cross174ae052015-03-03 17:37:03 -08001340 var errs []error
1341
Colin Crossf5e34b92015-03-13 16:02:36 -07001342 for i, variationName := range variationNames {
Colin Crossc9028482014-12-18 16:28:54 -08001343 var newLogicModule Module
1344 var newProperties []interface{}
1345
1346 if i == 0 {
1347 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -07001348 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
1349 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossd2f4ac12017-07-28 14:31:03 -07001350 newLogicModule, newProperties = origModule.logicModule, origModule.properties
Colin Crossc9028482014-12-18 16:28:54 -08001351 } else {
Colin Cross910242b2016-04-11 15:41:52 -07001352 newLogicModule, newProperties = c.cloneLogicModule(origModule)
Colin Crossc9028482014-12-18 16:28:54 -08001353 }
1354
Colin Crossed342d92015-03-11 00:57:25 -07001355 m := *origModule
1356 newModule := &m
Colin Cross2da84922020-07-02 10:08:12 -07001357 newModule.directDeps = append([]depInfo(nil), origModule.directDeps...)
Colin Cross7ff2e8d2021-01-21 22:39:28 -08001358 newModule.reverseDeps = nil
1359 newModule.forwardDeps = nil
Colin Crossed342d92015-03-11 00:57:25 -07001360 newModule.logicModule = newLogicModule
Colin Crossedc41762020-08-13 12:07:30 -07001361 newModule.variant = newVariant(origModule, mutatorName, variationName, local)
Colin Crossd2f4ac12017-07-28 14:31:03 -07001362 newModule.properties = newProperties
Colin Cross2da84922020-07-02 10:08:12 -07001363 newModule.providers = append([]interface{}(nil), origModule.providers...)
Colin Crossc9028482014-12-18 16:28:54 -08001364
1365 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -07001366
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001367 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName, defaultVariationName)
Colin Cross174ae052015-03-03 17:37:03 -08001368 if len(newErrs) > 0 {
1369 errs = append(errs, newErrs...)
1370 }
Colin Crossc9028482014-12-18 16:28:54 -08001371 }
1372
1373 // Mark original variant as invalid. Modules that depend on this module will still
1374 // depend on origModule, but we'll fix it when the mutator is called on them.
1375 origModule.logicModule = nil
1376 origModule.splitModules = newModules
1377
Colin Cross3702ac72016-08-11 11:09:00 -07001378 atomic.AddUint32(&c.depsModified, 1)
1379
Colin Cross174ae052015-03-03 17:37:03 -08001380 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -08001381}
1382
Colin Crossf5e34b92015-03-13 16:02:36 -07001383func (c *Context) convertDepsToVariation(module *moduleInfo,
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001384 mutatorName, variationName string, defaultVariationName *string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -08001385
Colin Crossc9028482014-12-18 16:28:54 -08001386 for i, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001387 if dep.module.logicModule == nil {
Colin Crossc9028482014-12-18 16:28:54 -08001388 var newDep *moduleInfo
Colin Cross2c1f3d12016-04-11 15:47:28 -07001389 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001390 if m.moduleOrAliasVariant().variations[mutatorName] == variationName {
1391 newDep = m.moduleOrAliasTarget()
Colin Crossc9028482014-12-18 16:28:54 -08001392 break
1393 }
1394 }
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001395 if newDep == nil && defaultVariationName != nil {
1396 // give it a second chance; match with defaultVariationName
1397 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001398 if m.moduleOrAliasVariant().variations[mutatorName] == *defaultVariationName {
1399 newDep = m.moduleOrAliasTarget()
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001400 break
1401 }
1402 }
1403 }
Colin Crossc9028482014-12-18 16:28:54 -08001404 if newDep == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001405 errs = append(errs, &BlueprintError{
Colin Crossf5e34b92015-03-13 16:02:36 -07001406 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001407 variationName, dep.module.Name(), module.Name()),
Colin Crossed342d92015-03-11 00:57:25 -07001408 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -08001409 })
1410 continue
Colin Crossc9028482014-12-18 16:28:54 -08001411 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001412 module.directDeps[i].module = newDep
Colin Crossc9028482014-12-18 16:28:54 -08001413 }
1414 }
Colin Cross174ae052015-03-03 17:37:03 -08001415
1416 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001417}
1418
Colin Crossedc41762020-08-13 12:07:30 -07001419func (c *Context) prettyPrintVariant(variations variationMap) string {
1420 names := make([]string, 0, len(variations))
Colin Cross65569e42015-03-10 20:08:19 -07001421 for _, m := range c.variantMutatorNames {
Colin Crossedc41762020-08-13 12:07:30 -07001422 if v, ok := variations[m]; ok {
Colin Cross65569e42015-03-10 20:08:19 -07001423 names = append(names, m+":"+v)
1424 }
1425 }
1426
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001427 return strings.Join(names, ",")
Colin Cross65569e42015-03-10 20:08:19 -07001428}
1429
Colin Crossd03b59d2019-11-13 20:10:12 -08001430func (c *Context) prettyPrintGroupVariants(group *moduleGroup) string {
1431 var variants []string
Colin Cross5df74a82020-08-24 16:18:21 -07001432 for _, moduleOrAlias := range group.modules {
1433 if mod := moduleOrAlias.module(); mod != nil {
1434 variants = append(variants, c.prettyPrintVariant(mod.variant.variations))
1435 } else if alias := moduleOrAlias.alias(); alias != nil {
1436 variants = append(variants, c.prettyPrintVariant(alias.variant.variations)+
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001437 " (alias to "+c.prettyPrintVariant(alias.target.variant.variations)+")")
Colin Cross5df74a82020-08-24 16:18:21 -07001438 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001439 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001440 return strings.Join(variants, "\n ")
1441}
1442
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001443func newModule(factory ModuleFactory) *moduleInfo {
Colin Crossaf4fd212017-07-28 14:32:36 -07001444 logicModule, properties := factory()
1445
1446 module := &moduleInfo{
1447 logicModule: logicModule,
1448 factory: factory,
1449 }
1450
1451 module.properties = properties
1452
1453 return module
1454}
1455
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001456func processModuleDef(moduleDef *parser.Module,
1457 relBlueprintsFile string, moduleFactories, scopedModuleFactories map[string]ModuleFactory, ignoreUnknownModuleTypes bool) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001458
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001459 factory, ok := moduleFactories[moduleDef.Type]
Colin Cross9672d862019-12-30 18:38:20 -08001460 if !ok && scopedModuleFactories != nil {
1461 factory, ok = scopedModuleFactories[moduleDef.Type]
1462 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001463 if !ok {
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001464 if ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001465 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001466 }
1467
Colin Cross7ad621c2015-01-07 16:22:45 -08001468 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001469 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001470 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1471 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001472 },
1473 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001474 }
1475
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001476 module := newModule(factory)
Colin Crossaf4fd212017-07-28 14:32:36 -07001477 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001478
Colin Crossaf4fd212017-07-28 14:32:36 -07001479 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001480
Colin Crossf27c5e42020-01-02 09:37:49 -08001481 propertyMap, errs := proptools.UnpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001482 if len(errs) > 0 {
Colin Crossf27c5e42020-01-02 09:37:49 -08001483 for i, err := range errs {
1484 if unpackErr, ok := err.(*proptools.UnpackError); ok {
1485 err = &BlueprintError{
1486 Err: unpackErr.Err,
1487 Pos: unpackErr.Pos,
1488 }
1489 errs[i] = err
1490 }
1491 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001492 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001493 }
1494
Colin Crossc32c4792016-06-09 15:52:30 -07001495 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001496 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001497 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001498 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001499 }
1500
Colin Cross7ad621c2015-01-07 16:22:45 -08001501 return module, nil
1502}
1503
Colin Cross23d7aa12015-06-30 16:05:22 -07001504func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001505 name := module.logicModule.Name()
Jaewoong Jungccc34942018-10-11 13:01:05 -07001506 if name == "" {
1507 return []error{
1508 &BlueprintError{
1509 Err: fmt.Errorf("property 'name' is missing from a module"),
1510 Pos: module.pos,
1511 },
1512 }
1513 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001514 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001515
Colin Cross0b7e83e2016-05-17 14:58:05 -07001516 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001517 name: name,
Colin Cross5df74a82020-08-24 16:18:21 -07001518 modules: modulesOrAliases{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001519 }
1520 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001521 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001522 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001523 ModuleGroup{moduleGroup: group},
1524 module.logicModule)
1525 if len(errs) > 0 {
1526 for i := range errs {
1527 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1528 }
1529 return errs
1530 }
1531 group.namespace = namespace
1532
Colin Cross0b7e83e2016-05-17 14:58:05 -07001533 c.moduleGroups = append(c.moduleGroups, group)
1534
Colin Cross23d7aa12015-06-30 16:05:22 -07001535 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001536}
1537
Jamie Gennisd4e10182014-06-12 20:06:50 -07001538// ResolveDependencies checks that the dependencies specified by all of the
1539// modules defined in the parsed Blueprints files are valid. This means that
1540// the modules depended upon are defined and that no circular dependencies
1541// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001542func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08001543 return c.resolveDependencies(c.Context, config)
1544}
Colin Cross5f03f112017-11-07 13:29:54 -08001545
Colin Cross3a8c0252019-01-23 13:21:48 -08001546func (c *Context) resolveDependencies(ctx context.Context, config interface{}) (deps []string, errs []error) {
1547 pprof.Do(ctx, pprof.Labels("blueprint", "ResolveDependencies"), func(ctx context.Context) {
Colin Cross2da84922020-07-02 10:08:12 -07001548 c.initProviders()
1549
Colin Cross3a8c0252019-01-23 13:21:48 -08001550 c.liveGlobals = newLiveTracker(config)
1551
1552 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1553 if len(errs) > 0 {
1554 return
1555 }
1556
1557 errs = c.updateDependencies()
1558 if len(errs) > 0 {
1559 return
1560 }
1561
1562 var mutatorDeps []string
1563 mutatorDeps, errs = c.runMutators(ctx, config)
1564 if len(errs) > 0 {
1565 return
1566 }
1567 deps = append(deps, mutatorDeps...)
1568
Colin Cross2da84922020-07-02 10:08:12 -07001569 if !c.skipCloneModulesAfterMutators {
1570 c.cloneModules()
1571 }
Colin Cross3a8c0252019-01-23 13:21:48 -08001572
1573 c.dependenciesReady = true
1574 })
1575
Colin Cross5f03f112017-11-07 13:29:54 -08001576 if len(errs) > 0 {
1577 return nil, errs
1578 }
1579
Colin Cross874a3462017-07-31 17:26:06 -07001580 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001581}
1582
Colin Cross763b6f12015-10-29 15:32:56 -07001583// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001584// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001585// module names returned by its DynamicDependencies method and those added by calling
1586// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001587func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001588 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001589 func() {
1590 defer func() {
1591 if r := recover(); r != nil {
1592 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1593 }
1594 }()
1595 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001596
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001597 if ctx.Failed() {
1598 return
1599 }
Colin Cross763b6f12015-10-29 15:32:56 -07001600
Colin Cross2c1f3d12016-04-11 15:47:28 -07001601 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001602 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001603 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001604}
1605
Colin Cross39644c02020-08-21 18:20:38 -07001606// findExactVariantOrSingle searches the moduleGroup for a module with the same variant as module,
1607// and returns the matching module, or nil if one is not found. A group with exactly one module
1608// is always considered matching.
1609func findExactVariantOrSingle(module *moduleInfo, possible *moduleGroup, reverse bool) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07001610 found, _ := findVariant(module, possible, nil, false, reverse)
1611 if found == nil {
1612 for _, moduleOrAlias := range possible.modules {
1613 if m := moduleOrAlias.module(); m != nil {
1614 if found != nil {
1615 // more than one possible match, give up
1616 return nil
1617 }
1618 found = m
1619 }
1620 }
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001621 }
Colin Cross5df74a82020-08-24 16:18:21 -07001622 return found
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001623}
1624
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001625func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) (*moduleInfo, []error) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001626 if _, ok := tag.(BaseDependencyTag); ok {
1627 panic("BaseDependencyTag is not allowed to be used directly!")
1628 }
1629
Colin Cross0b7e83e2016-05-17 14:58:05 -07001630 if depName == module.Name() {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001631 return nil, []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001632 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001633 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001634 }}
1635 }
1636
Colin Crossd03b59d2019-11-13 20:10:12 -08001637 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001638 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001639 return nil, c.discoveredMissingDependencies(module, depName, nil)
Colin Crossc9028482014-12-18 16:28:54 -08001640 }
1641
Colin Cross39644c02020-08-21 18:20:38 -07001642 if m := findExactVariantOrSingle(module, possibleDeps, false); m != nil {
Colin Cross99bdb2a2019-03-29 16:35:02 -07001643 module.newDirectDeps = append(module.newDirectDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001644 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001645 return m, nil
Colin Cross65569e42015-03-10 20:08:19 -07001646 }
Colin Crossc9028482014-12-18 16:28:54 -08001647
Paul Duffinb77556b2020-03-24 19:01:20 +00001648 if c.allowMissingDependencies {
1649 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001650 return nil, c.discoveredMissingDependencies(module, depName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001651 }
1652
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001653 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001654 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001655 depName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001656 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001657 c.prettyPrintGroupVariants(possibleDeps)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001658 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001659 }}
1660}
1661
Colin Cross8d8a7af2015-11-03 16:41:29 -08001662func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001663 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001664 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001665 Err: fmt.Errorf("%q depends on itself", destName),
1666 Pos: module.pos,
1667 }}
1668 }
1669
Colin Crossd03b59d2019-11-13 20:10:12 -08001670 possibleDeps := c.moduleGroupFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001671 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001672 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001673 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001674 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001675 Pos: module.pos,
1676 }}
1677 }
1678
Colin Cross39644c02020-08-21 18:20:38 -07001679 if m := findExactVariantOrSingle(module, possibleDeps, true); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001680 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001681 }
1682
Paul Duffinb77556b2020-03-24 19:01:20 +00001683 if c.allowMissingDependencies {
1684 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001685 return module, c.discoveredMissingDependencies(module, destName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001686 }
1687
Colin Cross2c628442016-10-07 17:13:10 -07001688 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001689 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001690 destName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001691 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001692 c.prettyPrintGroupVariants(possibleDeps)),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001693 Pos: module.pos,
1694 }}
1695}
1696
Colin Cross39644c02020-08-21 18:20:38 -07001697func findVariant(module *moduleInfo, possibleDeps *moduleGroup, variations []Variation, far bool, reverse bool) (*moduleInfo, variationMap) {
Colin Crossedc41762020-08-13 12:07:30 -07001698 // We can't just append variant.Variant to module.dependencyVariant.variantName and
Colin Cross65569e42015-03-10 20:08:19 -07001699 // compare the strings because the result won't be in mutator registration order.
1700 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001701 var newVariant variationMap
1702 if !far {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001703 if !reverse {
1704 // For forward dependency, ignore local variants by matching against
1705 // dependencyVariant which doesn't have the local variants
Colin Crossedc41762020-08-13 12:07:30 -07001706 newVariant = module.variant.dependencyVariations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001707 } else {
1708 // For reverse dependency, use all the variants
Colin Crossedc41762020-08-13 12:07:30 -07001709 newVariant = module.variant.variations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001710 }
Colin Cross89486232015-05-08 11:14:54 -07001711 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001712 for _, v := range variations {
Colin Cross9403b5a2019-11-13 20:11:04 -08001713 if newVariant == nil {
1714 newVariant = make(variationMap)
1715 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001716 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001717 }
1718
Colin Crossd03b59d2019-11-13 20:10:12 -08001719 check := func(variant variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -07001720 if far {
Colin Cross5dc67592020-08-24 14:46:13 -07001721 return newVariant.subsetOf(variant)
Colin Cross89486232015-05-08 11:14:54 -07001722 } else {
Colin Crossd03b59d2019-11-13 20:10:12 -08001723 return variant.equal(newVariant)
Colin Cross65569e42015-03-10 20:08:19 -07001724 }
1725 }
1726
Colin Crossd03b59d2019-11-13 20:10:12 -08001727 var foundDep *moduleInfo
1728 for _, m := range possibleDeps.modules {
Colin Cross5df74a82020-08-24 16:18:21 -07001729 if check(m.moduleOrAliasVariant().variations) {
1730 foundDep = m.moduleOrAliasTarget()
Colin Crossd03b59d2019-11-13 20:10:12 -08001731 break
1732 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001733 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001734
Martin Stjernholm2f212472020-03-06 00:29:24 +00001735 return foundDep, newVariant
1736}
1737
1738func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001739 tag DependencyTag, depName string, far bool) (*moduleInfo, []error) {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001740 if _, ok := tag.(BaseDependencyTag); ok {
1741 panic("BaseDependencyTag is not allowed to be used directly!")
1742 }
1743
1744 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
1745 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001746 return nil, c.discoveredMissingDependencies(module, depName, nil)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001747 }
1748
Colin Cross5df74a82020-08-24 16:18:21 -07001749 foundDep, newVariant := findVariant(module, possibleDeps, variations, far, false)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001750
Colin Crossf7beb892019-11-13 20:11:14 -08001751 if foundDep == nil {
Paul Duffinb77556b2020-03-24 19:01:20 +00001752 if c.allowMissingDependencies {
1753 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001754 return nil, c.discoveredMissingDependencies(module, depName, newVariant)
Paul Duffinb77556b2020-03-24 19:01:20 +00001755 }
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001756 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001757 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
1758 depName, module.Name(),
1759 c.prettyPrintVariant(newVariant),
1760 c.prettyPrintGroupVariants(possibleDeps)),
1761 Pos: module.pos,
1762 }}
1763 }
1764
1765 if module == foundDep {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001766 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001767 Err: fmt.Errorf("%q depends on itself", depName),
1768 Pos: module.pos,
1769 }}
1770 }
1771 // AddVariationDependency allows adding a dependency on itself, but only if
1772 // that module is earlier in the module list than this one, since we always
1773 // run GenerateBuildActions in order for the variants of a module
1774 if foundDep.group == module.group && beforeInModuleList(module, foundDep, module.group.modules) {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001775 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001776 Err: fmt.Errorf("%q depends on later version of itself", depName),
1777 Pos: module.pos,
1778 }}
1779 }
1780 module.newDirectDeps = append(module.newDirectDeps, depInfo{foundDep, tag})
1781 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001782 return foundDep, nil
Colin Crossc9028482014-12-18 16:28:54 -08001783}
1784
Colin Crossf1875462016-04-11 17:33:13 -07001785func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001786 from, to Module) *moduleInfo {
Nan Zhang346b2d02017-03-10 16:39:27 -08001787 if _, ok := tag.(BaseDependencyTag); ok {
1788 panic("BaseDependencyTag is not allowed to be used directly!")
1789 }
Colin Crossf1875462016-04-11 17:33:13 -07001790
1791 var fromInfo, toInfo *moduleInfo
Colin Cross5df74a82020-08-24 16:18:21 -07001792 for _, moduleOrAlias := range origModule.splitModules {
1793 if m := moduleOrAlias.module(); m != nil {
1794 if m.logicModule == from {
1795 fromInfo = m
1796 }
1797 if m.logicModule == to {
1798 toInfo = m
1799 if fromInfo != nil {
1800 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
1801 }
Colin Crossf1875462016-04-11 17:33:13 -07001802 }
1803 }
1804 }
1805
1806 if fromInfo == nil || toInfo == nil {
1807 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001808 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001809 }
1810
Colin Cross99bdb2a2019-03-29 16:35:02 -07001811 fromInfo.newDirectDeps = append(fromInfo.newDirectDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001812 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001813 return toInfo
Colin Crossf1875462016-04-11 17:33:13 -07001814}
1815
Lukacs T. Berkieef56852021-09-02 11:34:06 +02001816// findBlueprintDescendants returns a map linking parent Blueprint files to child Blueprints files
1817// For example, if paths = []string{"a/b/c/Android.bp", "a/Android.bp"},
1818// then descendants = {"":[]string{"a/Android.bp"}, "a/Android.bp":[]string{"a/b/c/Android.bp"}}
Jeff Gastonc3e28442017-08-09 15:13:12 -07001819func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1820 // make mapping from dir path to file path
1821 filesByDir := make(map[string]string, len(paths))
1822 for _, path := range paths {
1823 dir := filepath.Dir(path)
1824 _, alreadyFound := filesByDir[dir]
1825 if alreadyFound {
1826 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1827 }
1828 filesByDir[dir] = path
1829 }
1830
Jeff Gaston656870f2017-11-29 18:37:31 -08001831 findAncestor := func(childFile string) (ancestor string) {
1832 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001833 for {
1834 ancestorDir := filepath.Dir(prevAncestorDir)
1835 if ancestorDir == prevAncestorDir {
1836 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001837 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001838 }
1839
1840 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1841 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001842 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001843 }
1844 prevAncestorDir = ancestorDir
1845 }
1846 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001847 // generate the descendants map
1848 descendants = make(map[string][]string, len(filesByDir))
1849 for _, childFile := range filesByDir {
1850 ancestorFile := findAncestor(childFile)
1851 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1852 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001853 return descendants, nil
1854}
1855
Colin Cross3702ac72016-08-11 11:09:00 -07001856type visitOrderer interface {
1857 // returns the number of modules that this module needs to wait for
1858 waitCount(module *moduleInfo) int
1859 // returns the list of modules that are waiting for this module
1860 propagate(module *moduleInfo) []*moduleInfo
1861 // visit modules in order
Colin Crossc4773d92020-08-25 17:12:59 -07001862 visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool)
Colin Cross3702ac72016-08-11 11:09:00 -07001863}
1864
Colin Cross7e723372018-03-28 11:50:12 -07001865type unorderedVisitorImpl struct{}
1866
1867func (unorderedVisitorImpl) waitCount(module *moduleInfo) int {
1868 return 0
1869}
1870
1871func (unorderedVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1872 return nil
1873}
1874
Colin Crossc4773d92020-08-25 17:12:59 -07001875func (unorderedVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross7e723372018-03-28 11:50:12 -07001876 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001877 if visit(module, nil) {
Colin Cross7e723372018-03-28 11:50:12 -07001878 return
1879 }
1880 }
1881}
1882
Colin Cross3702ac72016-08-11 11:09:00 -07001883type bottomUpVisitorImpl struct{}
1884
1885func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1886 return len(module.forwardDeps)
1887}
1888
1889func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1890 return module.reverseDeps
1891}
1892
Colin Crossc4773d92020-08-25 17:12:59 -07001893func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001894 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001895 if visit(module, nil) {
Colin Cross49c279a2016-08-05 22:30:44 -07001896 return
1897 }
1898 }
1899}
1900
Colin Cross3702ac72016-08-11 11:09:00 -07001901type topDownVisitorImpl struct{}
1902
1903func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1904 return len(module.reverseDeps)
1905}
1906
1907func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1908 return module.forwardDeps
1909}
1910
Colin Crossc4773d92020-08-25 17:12:59 -07001911func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001912 for i := 0; i < len(modules); i++ {
1913 module := modules[len(modules)-1-i]
Colin Crossc4773d92020-08-25 17:12:59 -07001914 if visit(module, nil) {
Colin Cross3702ac72016-08-11 11:09:00 -07001915 return
1916 }
1917 }
1918}
1919
1920var (
1921 bottomUpVisitor bottomUpVisitorImpl
1922 topDownVisitor topDownVisitorImpl
1923)
1924
Colin Crossc4773d92020-08-25 17:12:59 -07001925// pauseSpec describes a pause that a module needs to occur until another module has been visited,
1926// at which point the unpause channel will be closed.
1927type pauseSpec struct {
1928 paused *moduleInfo
1929 until *moduleInfo
1930 unpause unpause
1931}
1932
1933type unpause chan struct{}
1934
1935const parallelVisitLimit = 1000
1936
Colin Cross49c279a2016-08-05 22:30:44 -07001937// Calls visit on each module, guaranteeing that visit is not called on a module until visit on all
Colin Crossc4773d92020-08-25 17:12:59 -07001938// of its dependencies has finished. A visit function can write a pauseSpec to the pause channel
1939// to wait for another dependency to be visited. If a visit function returns true to cancel
1940// while another visitor is paused, the paused visitor will never be resumed and its goroutine
1941// will stay paused forever.
1942func parallelVisit(modules []*moduleInfo, order visitOrderer, limit int,
1943 visit func(module *moduleInfo, pause chan<- pauseSpec) bool) []error {
1944
Colin Cross7addea32015-03-11 15:43:52 -07001945 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001946 cancelCh := make(chan bool)
Colin Crossc4773d92020-08-25 17:12:59 -07001947 pauseCh := make(chan pauseSpec)
Colin Cross8900e9b2015-03-02 14:03:01 -08001948 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001949
Colin Crossc4773d92020-08-25 17:12:59 -07001950 var backlog []*moduleInfo // Visitors that are ready to start but backlogged due to limit.
1951 var unpauseBacklog []pauseSpec // Visitors that are ready to unpause but backlogged due to limit.
1952
1953 active := 0 // Number of visitors running, not counting paused visitors.
1954 visited := 0 // Number of finished visitors.
1955
1956 pauseMap := make(map[*moduleInfo][]pauseSpec)
1957
1958 for _, module := range modules {
Colin Cross3702ac72016-08-11 11:09:00 -07001959 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001960 }
1961
Colin Crossc4773d92020-08-25 17:12:59 -07001962 // Call the visitor on a module if there are fewer active visitors than the parallelism
1963 // limit, otherwise add it to the backlog.
1964 startOrBacklog := func(module *moduleInfo) {
1965 if active < limit {
1966 active++
Colin Cross7e723372018-03-28 11:50:12 -07001967 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07001968 ret := visit(module, pauseCh)
Colin Cross7e723372018-03-28 11:50:12 -07001969 if ret {
1970 cancelCh <- true
1971 }
1972 doneCh <- module
1973 }()
1974 } else {
1975 backlog = append(backlog, module)
1976 }
Colin Cross691a60d2015-01-07 18:08:56 -08001977 }
1978
Colin Crossc4773d92020-08-25 17:12:59 -07001979 // Unpause the already-started but paused visitor on a module if there are fewer active
1980 // visitors than the parallelism limit, otherwise add it to the backlog.
1981 unpauseOrBacklog := func(pauseSpec pauseSpec) {
1982 if active < limit {
1983 active++
1984 close(pauseSpec.unpause)
1985 } else {
1986 unpauseBacklog = append(unpauseBacklog, pauseSpec)
Colin Cross691a60d2015-01-07 18:08:56 -08001987 }
1988 }
1989
Colin Crossc4773d92020-08-25 17:12:59 -07001990 // Start any modules in the backlog up to the parallelism limit. Unpause paused modules first
1991 // since they may already be holding resources.
1992 unpauseOrStartFromBacklog := func() {
1993 for active < limit && len(unpauseBacklog) > 0 {
1994 unpause := unpauseBacklog[0]
1995 unpauseBacklog = unpauseBacklog[1:]
1996 unpauseOrBacklog(unpause)
1997 }
1998 for active < limit && len(backlog) > 0 {
1999 toVisit := backlog[0]
2000 backlog = backlog[1:]
2001 startOrBacklog(toVisit)
2002 }
2003 }
2004
2005 toVisit := len(modules)
2006
2007 // Start or backlog any modules that are not waiting for any other modules.
2008 for _, module := range modules {
2009 if module.waitingCount == 0 {
2010 startOrBacklog(module)
2011 }
2012 }
2013
2014 for active > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08002015 select {
Colin Cross7e723372018-03-28 11:50:12 -07002016 case <-cancelCh:
2017 cancel = true
2018 backlog = nil
Colin Cross7addea32015-03-11 15:43:52 -07002019 case doneModule := <-doneCh:
Colin Crossc4773d92020-08-25 17:12:59 -07002020 active--
Colin Cross8900e9b2015-03-02 14:03:01 -08002021 if !cancel {
Colin Crossc4773d92020-08-25 17:12:59 -07002022 // Mark this module as done.
2023 doneModule.waitingCount = -1
2024 visited++
2025
2026 // Unpause or backlog any modules that were waiting for this one.
2027 if unpauses, ok := pauseMap[doneModule]; ok {
2028 delete(pauseMap, doneModule)
2029 for _, unpause := range unpauses {
2030 unpauseOrBacklog(unpause)
2031 }
Colin Cross7e723372018-03-28 11:50:12 -07002032 }
Colin Crossc4773d92020-08-25 17:12:59 -07002033
2034 // Start any backlogged modules up to limit.
2035 unpauseOrStartFromBacklog()
2036
2037 // Decrement waitingCount on the next modules in the tree based
2038 // on propagation order, and start or backlog them if they are
2039 // ready to start.
Colin Cross3702ac72016-08-11 11:09:00 -07002040 for _, module := range order.propagate(doneModule) {
2041 module.waitingCount--
2042 if module.waitingCount == 0 {
Colin Crossc4773d92020-08-25 17:12:59 -07002043 startOrBacklog(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08002044 }
Colin Cross691a60d2015-01-07 18:08:56 -08002045 }
2046 }
Colin Crossc4773d92020-08-25 17:12:59 -07002047 case pauseSpec := <-pauseCh:
2048 if pauseSpec.until.waitingCount == -1 {
2049 // Module being paused for is already finished, resume immediately.
2050 close(pauseSpec.unpause)
2051 } else {
2052 // Register for unpausing.
2053 pauseMap[pauseSpec.until] = append(pauseMap[pauseSpec.until], pauseSpec)
2054
2055 // Don't count paused visitors as active so that this can't deadlock
2056 // if 1000 visitors are paused simultaneously.
2057 active--
2058 unpauseOrStartFromBacklog()
2059 }
Colin Cross691a60d2015-01-07 18:08:56 -08002060 }
2061 }
Colin Crossc4773d92020-08-25 17:12:59 -07002062
2063 if !cancel {
2064 // Invariant check: no backlogged modules, these weren't waiting on anything except
2065 // the parallelism limit so they should have run.
2066 if len(backlog) > 0 {
2067 panic(fmt.Errorf("parallelVisit finished with %d backlogged visitors", len(backlog)))
2068 }
2069
2070 // Invariant check: no backlogged paused modules, these weren't waiting on anything
2071 // except the parallelism limit so they should have run.
2072 if len(unpauseBacklog) > 0 {
2073 panic(fmt.Errorf("parallelVisit finished with %d backlogged unpaused visitors", len(unpauseBacklog)))
2074 }
2075
2076 if len(pauseMap) > 0 {
Colin Cross7d4958d2021-02-08 15:34:08 -08002077 // Probably a deadlock due to a newly added dependency cycle. Start from each module in
2078 // the order of the input modules list and perform a depth-first search for the module
2079 // it is paused on, ignoring modules that are marked as done. Note this traverses from
2080 // modules to the modules that would have been unblocked when that module finished, i.e
2081 // the reverse of the visitOrderer.
Colin Crossc4773d92020-08-25 17:12:59 -07002082
Colin Cross9793b0a2021-04-27 15:20:15 -07002083 // In order to reduce duplicated work, once a module has been checked and determined
2084 // not to be part of a cycle add it and everything that depends on it to the checked
2085 // map.
2086 checked := make(map[*moduleInfo]struct{})
2087
Colin Cross7d4958d2021-02-08 15:34:08 -08002088 var check func(module, end *moduleInfo) []*moduleInfo
2089 check = func(module, end *moduleInfo) []*moduleInfo {
Colin Crossc4773d92020-08-25 17:12:59 -07002090 if module.waitingCount == -1 {
2091 // This module was finished, it can't be part of a loop.
2092 return nil
2093 }
2094 if module == end {
2095 // This module is the end of the loop, start rolling up the cycle.
2096 return []*moduleInfo{module}
2097 }
2098
Colin Cross9793b0a2021-04-27 15:20:15 -07002099 if _, alreadyChecked := checked[module]; alreadyChecked {
2100 return nil
2101 }
2102
Colin Crossc4773d92020-08-25 17:12:59 -07002103 for _, dep := range order.propagate(module) {
Colin Cross7d4958d2021-02-08 15:34:08 -08002104 cycle := check(dep, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002105 if cycle != nil {
2106 return append([]*moduleInfo{module}, cycle...)
2107 }
2108 }
2109 for _, depPauseSpec := range pauseMap[module] {
Colin Cross7d4958d2021-02-08 15:34:08 -08002110 cycle := check(depPauseSpec.paused, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002111 if cycle != nil {
2112 return append([]*moduleInfo{module}, cycle...)
2113 }
2114 }
2115
Colin Cross9793b0a2021-04-27 15:20:15 -07002116 checked[module] = struct{}{}
Colin Crossc4773d92020-08-25 17:12:59 -07002117 return nil
2118 }
2119
Colin Cross7d4958d2021-02-08 15:34:08 -08002120 // Iterate over the modules list instead of pauseMap to provide deterministic ordering.
2121 for _, module := range modules {
2122 for _, pauseSpec := range pauseMap[module] {
2123 cycle := check(pauseSpec.paused, pauseSpec.until)
2124 if len(cycle) > 0 {
2125 return cycleError(cycle)
2126 }
2127 }
Colin Crossc4773d92020-08-25 17:12:59 -07002128 }
2129 }
2130
2131 // Invariant check: if there was no deadlock and no cancellation every module
2132 // should have been visited.
2133 if visited != toVisit {
2134 panic(fmt.Errorf("parallelVisit ran %d visitors, expected %d", visited, toVisit))
2135 }
2136
2137 // Invariant check: if there was no deadlock and no cancellation every module
2138 // should have been visited, so there is nothing left to be paused on.
2139 if len(pauseMap) > 0 {
2140 panic(fmt.Errorf("parallelVisit finished with %d paused visitors", len(pauseMap)))
2141 }
2142 }
2143
2144 return nil
2145}
2146
2147func cycleError(cycle []*moduleInfo) (errs []error) {
2148 // The cycle list is in reverse order because all the 'check' calls append
2149 // their own module to the list.
2150 errs = append(errs, &BlueprintError{
2151 Err: fmt.Errorf("encountered dependency cycle:"),
2152 Pos: cycle[len(cycle)-1].pos,
2153 })
2154
2155 // Iterate backwards through the cycle list.
2156 curModule := cycle[0]
2157 for i := len(cycle) - 1; i >= 0; i-- {
2158 nextModule := cycle[i]
2159 errs = append(errs, &BlueprintError{
Colin Crosse5ff7702021-04-27 15:33:49 -07002160 Err: fmt.Errorf(" %s depends on %s",
2161 curModule, nextModule),
Colin Crossc4773d92020-08-25 17:12:59 -07002162 Pos: curModule.pos,
2163 })
2164 curModule = nextModule
2165 }
2166
2167 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002168}
2169
2170// updateDependencies recursively walks the module dependency graph and updates
2171// additional fields based on the dependencies. It builds a sorted list of modules
2172// such that dependencies of a module always appear first, and populates reverse
2173// dependency links and counts of total dependencies. It also reports errors when
2174// it encounters dependency cycles. This should called after resolveDependencies,
2175// as well as after any mutator pass has called addDependency
2176func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002177 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002178 visited := make(map[*moduleInfo]bool) // modules that were already checked
2179 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002180
Colin Cross7addea32015-03-11 15:43:52 -07002181 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002182
Colin Cross7addea32015-03-11 15:43:52 -07002183 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002184
Colin Cross7addea32015-03-11 15:43:52 -07002185 check = func(module *moduleInfo) []*moduleInfo {
2186 visited[module] = true
2187 checking[module] = true
2188 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002189
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002190 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2191 module.reverseDeps = module.reverseDeps[:0]
2192 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002193
2194 // Add an implicit dependency ordering on all earlier modules in the same module group
2195 for _, dep := range module.group.modules {
2196 if dep == module {
2197 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002198 }
Colin Cross5df74a82020-08-24 16:18:21 -07002199 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002200 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002201 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002202 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002203
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002204 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002205 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002206 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2207 for _, exists := range module.forwardDeps {
2208 if dep.module == exists {
2209 continue outer
2210 }
2211 }
2212 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002213 }
2214
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002215 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002216 if checking[dep] {
2217 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002218 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002219 }
2220
2221 if !visited[dep] {
2222 cycle := check(dep)
2223 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002224 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002225 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002226 // for generating the errors.
2227 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002228
2229 // We can continue processing this module's children to
2230 // find more cycles. Since all the modules that were
2231 // part of the found cycle were marked as visited we
2232 // won't run into that cycle again.
2233 } else {
2234 // We're not the "start" of the cycle, so we just append
2235 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002236 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002237 }
2238 }
2239 }
Colin Cross691a60d2015-01-07 18:08:56 -08002240
Colin Cross7addea32015-03-11 15:43:52 -07002241 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002242 }
2243
Colin Cross7addea32015-03-11 15:43:52 -07002244 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002245
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002246 return nil
2247 }
2248
Colin Cross7addea32015-03-11 15:43:52 -07002249 for _, module := range c.moduleInfo {
2250 if !visited[module] {
2251 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002252 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002253 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002254 panic("inconceivable!")
2255 }
Colin Crossc4773d92020-08-25 17:12:59 -07002256 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002257 }
2258 }
2259 }
2260
Colin Cross7addea32015-03-11 15:43:52 -07002261 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002262
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002263 return
2264}
2265
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002266type jsonVariationMap map[string]string
2267
2268type jsonModuleName struct {
2269 Name string
2270 Variations jsonVariationMap
2271 DependencyVariations jsonVariationMap
2272}
2273
2274type jsonDep struct {
2275 jsonModuleName
2276 Tag string
2277}
2278
Lukacs T. Berki16022262021-06-25 09:10:56 +02002279type JsonModule struct {
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002280 jsonModuleName
2281 Deps []jsonDep
2282 Type string
2283 Blueprint string
Lukacs T. Berki16022262021-06-25 09:10:56 +02002284 Module map[string]interface{}
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002285}
2286
2287func toJsonVariationMap(vm variationMap) jsonVariationMap {
2288 return jsonVariationMap(vm)
2289}
2290
2291func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2292 return &jsonModuleName{
2293 Name: m.Name(),
2294 Variations: toJsonVariationMap(m.variant.variations),
2295 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2296 }
2297}
2298
Lukacs T. Berki16022262021-06-25 09:10:56 +02002299type JSONDataSupplier interface {
2300 AddJSONData(d *map[string]interface{})
2301}
2302
2303func jsonModuleFromModuleInfo(m *moduleInfo) *JsonModule {
2304 result := &JsonModule{
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002305 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2306 Deps: make([]jsonDep, 0),
2307 Type: m.typeName,
2308 Blueprint: m.relBlueprintsFile,
Lukacs T. Berki16022262021-06-25 09:10:56 +02002309 Module: make(map[string]interface{}),
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002310 }
Lukacs T. Berki16022262021-06-25 09:10:56 +02002311
2312 if j, ok := m.logicModule.(JSONDataSupplier); ok {
2313 j.AddJSONData(&result.Module)
2314 }
2315
2316 for _, p := range m.providers {
2317 if j, ok := p.(JSONDataSupplier); ok {
2318 j.AddJSONData(&result.Module)
2319 }
2320 }
2321 return result
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002322}
2323
2324func (c *Context) PrintJSONGraph(w io.Writer) {
Lukacs T. Berki16022262021-06-25 09:10:56 +02002325 modules := make([]*JsonModule, 0)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002326 for _, m := range c.modulesSorted {
2327 jm := jsonModuleFromModuleInfo(m)
2328 for _, d := range m.directDeps {
2329 jm.Deps = append(jm.Deps, jsonDep{
2330 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2331 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2332 })
2333 }
2334
2335 modules = append(modules, jm)
2336 }
2337
Liz Kammer6e4ee8d2021-08-17 17:32:42 -04002338 e := json.NewEncoder(w)
2339 e.SetIndent("", "\t")
2340 e.Encode(modules)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002341}
2342
Jamie Gennisd4e10182014-06-12 20:06:50 -07002343// PrepareBuildActions generates an internal representation of all the build
2344// actions that need to be performed. This process involves invoking the
2345// GenerateBuildActions method on each of the Module objects created during the
2346// parse phase and then on each of the registered Singleton objects.
2347//
2348// If the ResolveDependencies method has not already been called it is called
2349// automatically by this method.
2350//
2351// The config argument is made available to all of the Module and Singleton
2352// objects via the Config method on the ModuleContext and SingletonContext
2353// objects passed to GenerateBuildActions. It is also passed to the functions
2354// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2355// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002356//
2357// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002358// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2359// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2360// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002361
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002362func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002363 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2364 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002365
Colin Cross3a8c0252019-01-23 13:21:48 -08002366 if !c.dependenciesReady {
2367 var extraDeps []string
2368 extraDeps, errs = c.resolveDependencies(ctx, config)
2369 if len(errs) > 0 {
2370 return
2371 }
2372 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002373 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002374
Colin Cross3a8c0252019-01-23 13:21:48 -08002375 var depsModules []string
2376 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2377 if len(errs) > 0 {
2378 return
2379 }
2380
2381 var depsSingletons []string
2382 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2383 if len(errs) > 0 {
2384 return
2385 }
2386
2387 deps = append(deps, depsModules...)
2388 deps = append(deps, depsSingletons...)
2389
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02002390 if c.outDir != nil {
2391 err := c.liveGlobals.addNinjaStringDeps(c.outDir)
Colin Cross3a8c0252019-01-23 13:21:48 -08002392 if err != nil {
2393 errs = []error{err}
2394 return
2395 }
2396 }
2397
2398 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2399
2400 deps = append(deps, depsPackages...)
2401
Colin Cross92054a42021-01-21 16:49:25 -08002402 c.memoizeFullNames(c.liveGlobals, pkgNames)
2403
Colin Cross3a8c0252019-01-23 13:21:48 -08002404 // This will panic if it finds a problem since it's a programming error.
2405 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2406
2407 c.pkgNames = pkgNames
2408 c.globalVariables = c.liveGlobals.variables
2409 c.globalPools = c.liveGlobals.pools
2410 c.globalRules = c.liveGlobals.rules
2411
2412 c.buildActionsReady = true
2413 })
2414
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002415 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002416 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002417 }
2418
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002419 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002420}
2421
Colin Cross3a8c0252019-01-23 13:21:48 -08002422func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002423 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002424
Colin Cross3a8c0252019-01-23 13:21:48 -08002425 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2426 mutators = append(mutators, c.earlyMutatorInfo...)
2427 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002428
Colin Cross3a8c0252019-01-23 13:21:48 -08002429 for _, mutator := range mutators {
2430 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2431 var newDeps []string
2432 if mutator.topDownMutator != nil {
2433 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2434 } else if mutator.bottomUpMutator != nil {
2435 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2436 } else {
2437 panic("no mutator set on " + mutator.name)
2438 }
2439 if len(errs) > 0 {
2440 return
2441 }
2442 deps = append(deps, newDeps...)
2443 })
2444 if len(errs) > 0 {
2445 return
2446 }
Colin Crossc9028482014-12-18 16:28:54 -08002447 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002448 })
2449
2450 if len(errs) > 0 {
2451 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002452 }
2453
Colin Cross874a3462017-07-31 17:26:06 -07002454 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002455}
2456
Colin Cross3702ac72016-08-11 11:09:00 -07002457type mutatorDirection interface {
2458 run(mutator *mutatorInfo, ctx *mutatorContext)
2459 orderer() visitOrderer
2460 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002461}
2462
Colin Cross3702ac72016-08-11 11:09:00 -07002463type bottomUpMutatorImpl struct{}
2464
2465func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2466 mutator.bottomUpMutator(ctx)
2467}
2468
2469func (bottomUpMutatorImpl) orderer() visitOrderer {
2470 return bottomUpVisitor
2471}
2472
2473func (bottomUpMutatorImpl) String() string {
2474 return "bottom up mutator"
2475}
2476
2477type topDownMutatorImpl struct{}
2478
2479func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2480 mutator.topDownMutator(ctx)
2481}
2482
2483func (topDownMutatorImpl) orderer() visitOrderer {
2484 return topDownVisitor
2485}
2486
2487func (topDownMutatorImpl) String() string {
2488 return "top down mutator"
2489}
2490
2491var (
2492 topDownMutator topDownMutatorImpl
2493 bottomUpMutator bottomUpMutatorImpl
2494)
2495
Colin Cross49c279a2016-08-05 22:30:44 -07002496type reverseDep struct {
2497 module *moduleInfo
2498 dep depInfo
2499}
2500
Colin Cross3702ac72016-08-11 11:09:00 -07002501func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002502 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002503
2504 newModuleInfo := make(map[Module]*moduleInfo)
2505 for k, v := range c.moduleInfo {
2506 newModuleInfo[k] = v
2507 }
Colin Crossc9028482014-12-18 16:28:54 -08002508
Colin Cross0ce142c2016-12-09 10:29:05 -08002509 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002510 reverse []reverseDep
2511 rename []rename
2512 replace []replace
2513 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002514 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002515 }
2516
Colin Cross2c1f3d12016-04-11 15:47:28 -07002517 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002518 var rename []rename
2519 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002520 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002521
Colin Cross49c279a2016-08-05 22:30:44 -07002522 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002523 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002524 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002525 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002526
Colin Cross3702ac72016-08-11 11:09:00 -07002527 c.depsModified = 0
2528
Colin Crossc4773d92020-08-25 17:12:59 -07002529 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002530 if module.splitModules != nil {
2531 panic("split module found in sorted module list")
2532 }
2533
Colin Cross7addea32015-03-11 15:43:52 -07002534 mctx := &mutatorContext{
2535 baseModuleContext: baseModuleContext{
2536 context: c,
2537 config: config,
2538 module: module,
2539 },
Colin Crossc4773d92020-08-25 17:12:59 -07002540 name: mutator.name,
2541 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002542 }
Colin Crossc9028482014-12-18 16:28:54 -08002543
Colin Cross2da84922020-07-02 10:08:12 -07002544 module.startedMutator = mutator
2545
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002546 func() {
2547 defer func() {
2548 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002549 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002550 if err, ok := r.(panicError); ok {
2551 err.addIn(in)
2552 mctx.error(err)
2553 } else {
2554 mctx.error(newPanicErrorf(r, in))
2555 }
2556 }
2557 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002558 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002559 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002560
Colin Cross2da84922020-07-02 10:08:12 -07002561 module.finishedMutator = mutator
2562
Colin Cross7addea32015-03-11 15:43:52 -07002563 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002564 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002565 return true
Colin Cross7addea32015-03-11 15:43:52 -07002566 }
Colin Crossc9028482014-12-18 16:28:54 -08002567
Colin Cross5fe225f2017-07-28 15:22:46 -07002568 if len(mctx.newVariations) > 0 {
2569 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002570 }
2571
Colin Crossab0a83f2020-03-03 14:23:27 -08002572 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 -08002573 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002574 reverse: mctx.reverseDeps,
2575 replace: mctx.replace,
2576 rename: mctx.rename,
2577 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002578 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002579 }
Colin Cross49c279a2016-08-05 22:30:44 -07002580 }
2581
2582 return false
2583 }
2584
2585 // Process errs and reverseDeps in a single goroutine
2586 go func() {
2587 for {
2588 select {
2589 case newErrs := <-errsCh:
2590 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002591 case globalStateChange := <-globalStateCh:
2592 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002593 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2594 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002595 replace = append(replace, globalStateChange.replace...)
2596 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002597 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002598 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002599 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002600 for _, moduleOrAlias := range newVariations {
2601 if m := moduleOrAlias.module(); m != nil {
2602 newModuleInfo[m.logicModule] = m
2603 }
Colin Cross49c279a2016-08-05 22:30:44 -07002604 }
2605 case <-done:
2606 return
Colin Crossc9028482014-12-18 16:28:54 -08002607 }
2608 }
Colin Cross49c279a2016-08-05 22:30:44 -07002609 }()
Colin Crossc9028482014-12-18 16:28:54 -08002610
Colin Cross2da84922020-07-02 10:08:12 -07002611 c.startedMutator = mutator
2612
Colin Crossc4773d92020-08-25 17:12:59 -07002613 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002614 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002615 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002616 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002617 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002618 }
2619
Colin Crossc4773d92020-08-25 17:12:59 -07002620 if len(visitErrs) > 0 {
2621 return nil, visitErrs
2622 }
2623
Colin Cross2da84922020-07-02 10:08:12 -07002624 c.finishedMutators[mutator] = true
2625
Colin Cross49c279a2016-08-05 22:30:44 -07002626 done <- true
2627
2628 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002629 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002630 }
2631
2632 c.moduleInfo = newModuleInfo
2633
2634 for _, group := range c.moduleGroups {
2635 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002636 module := group.modules[i].module()
2637 if module == nil {
2638 // Existing alias, skip it
2639 continue
2640 }
Colin Cross49c279a2016-08-05 22:30:44 -07002641
2642 // Update module group to contain newly split variants
2643 if module.splitModules != nil {
2644 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2645 }
2646
2647 // Fix up any remaining dependencies on modules that were split into variants
2648 // by replacing them with the first variant
2649 for j, dep := range module.directDeps {
2650 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002651 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002652 }
2653 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002654
Colin Cross322cc012019-05-20 13:55:14 -07002655 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002656 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002657 }
2658
Colin Cross99bdb2a2019-03-29 16:35:02 -07002659 // Add in any new direct dependencies that were added by the mutator
2660 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2661 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002662 }
Colin Crossf7beb892019-11-13 20:11:14 -08002663
Colin Cross279489c2020-08-13 12:11:52 -07002664 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002665 for _, moduleOrAlias := range group.modules {
2666 if alias := moduleOrAlias.alias(); alias != nil {
2667 if alias.variant.variations.equal(variant.variations) {
2668 return alias.target
2669 }
Colin Cross279489c2020-08-13 12:11:52 -07002670 }
2671 }
2672 return nil
2673 }
2674
Colin Crossf7beb892019-11-13 20:11:14 -08002675 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002676 // Use a manual loop instead of range because len(group.modules) can
2677 // change inside the loop
2678 for i := 0; i < len(group.modules); i++ {
2679 if alias := group.modules[i].alias(); alias != nil {
2680 if alias.target.logicModule == nil {
2681 newTarget := findAliasTarget(alias.target.variant)
2682 if newTarget != nil {
2683 alias.target = newTarget
2684 } else {
2685 // The alias was left dangling, remove it.
2686 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2687 i--
2688 }
Colin Crossf7beb892019-11-13 20:11:14 -08002689 }
2690 }
2691 }
Colin Crossc9028482014-12-18 16:28:54 -08002692 }
2693
Colin Cross99bdb2a2019-03-29 16:35:02 -07002694 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002695 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002696 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002697 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002698 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002699 }
2700
Colin Crossaf4fd212017-07-28 14:32:36 -07002701 for _, module := range newModules {
2702 errs = c.addModule(module)
2703 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002704 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002705 }
2706 atomic.AddUint32(&c.depsModified, 1)
2707 }
2708
Colin Cross0ce142c2016-12-09 10:29:05 -08002709 errs = c.handleRenames(rename)
2710 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002711 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002712 }
2713
2714 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002715 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002716 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002717 }
2718
Colin Cross3702ac72016-08-11 11:09:00 -07002719 if c.depsModified > 0 {
2720 errs = c.updateDependencies()
2721 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002722 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002723 }
Colin Crossc9028482014-12-18 16:28:54 -08002724 }
2725
Colin Cross874a3462017-07-31 17:26:06 -07002726 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002727}
2728
Colin Cross910242b2016-04-11 15:41:52 -07002729// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2730// a mutator sets a non-property member variable on a module, which works until a later mutator
2731// creates variants of that module.
2732func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002733 type update struct {
2734 orig Module
2735 clone *moduleInfo
2736 }
Colin Cross7e723372018-03-28 11:50:12 -07002737 ch := make(chan update)
2738 doneCh := make(chan bool)
2739 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002740 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2741 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2742 origLogicModule := m.logicModule
2743 m.logicModule, m.properties = c.cloneLogicModule(m)
2744 ch <- update{origLogicModule, m}
2745 return false
2746 })
2747 if len(errs) > 0 {
2748 panic(errs)
2749 }
Colin Cross7e723372018-03-28 11:50:12 -07002750 doneCh <- true
2751 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002752
Colin Cross7e723372018-03-28 11:50:12 -07002753 done := false
2754 for !done {
2755 select {
2756 case <-doneCh:
2757 done = true
2758 case update := <-ch:
2759 delete(c.moduleInfo, update.orig)
2760 c.moduleInfo[update.clone.logicModule] = update.clone
2761 }
Colin Cross910242b2016-04-11 15:41:52 -07002762 }
2763}
2764
Colin Cross49c279a2016-08-05 22:30:44 -07002765// Removes modules[i] from the list and inserts newModules... where it was located, returning
2766// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002767func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002768 spliceSize := len(newModules)
2769 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002770 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002771 if cap(modules) >= len(modules)-1+len(newModules) {
2772 // We can fit the splice in the existing capacity, do everything in place
2773 dest = modules[:newLen]
2774 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002775 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002776 copy(dest, modules[:i])
2777 }
2778
2779 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002780 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002781
2782 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002783 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002784
Colin Cross49c279a2016-08-05 22:30:44 -07002785 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002786}
2787
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002788func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002789 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002790
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002791 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002792 var errs []error
2793
Colin Cross691a60d2015-01-07 18:08:56 -08002794 cancelCh := make(chan struct{})
2795 errsCh := make(chan []error)
2796 depsCh := make(chan []string)
2797
2798 go func() {
2799 for {
2800 select {
2801 case <-cancelCh:
2802 close(cancelCh)
2803 return
2804 case newErrs := <-errsCh:
2805 errs = append(errs, newErrs...)
2806 case newDeps := <-depsCh:
2807 deps = append(deps, newDeps...)
2808
2809 }
2810 }
2811 }()
2812
Colin Crossc4773d92020-08-25 17:12:59 -07002813 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2814 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2815 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2816 sanitizedName := toNinjaName(uniqueName)
Jeff Gaston0e907592017-12-01 17:10:52 -08002817
Colin Crossc4773d92020-08-25 17:12:59 -07002818 prefix := moduleNamespacePrefix(sanitizedName + "_" + module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002819
Colin Crossc4773d92020-08-25 17:12:59 -07002820 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2821 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2822 // just set it to nil.
2823 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002824
Colin Crossc4773d92020-08-25 17:12:59 -07002825 mctx := &moduleContext{
2826 baseModuleContext: baseModuleContext{
2827 context: c,
2828 config: config,
2829 module: module,
2830 },
2831 scope: scope,
2832 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002833 }
Colin Cross036a1df2015-12-17 15:49:30 -08002834
Colin Cross2da84922020-07-02 10:08:12 -07002835 mctx.module.startedGenerateBuildActions = true
2836
Colin Crossc4773d92020-08-25 17:12:59 -07002837 func() {
2838 defer func() {
2839 if r := recover(); r != nil {
2840 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2841 if err, ok := r.(panicError); ok {
2842 err.addIn(in)
2843 mctx.error(err)
2844 } else {
2845 mctx.error(newPanicErrorf(r, in))
2846 }
2847 }
2848 }()
2849 mctx.module.logicModule.GenerateBuildActions(mctx)
2850 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002851
Colin Cross2da84922020-07-02 10:08:12 -07002852 mctx.module.finishedGenerateBuildActions = true
2853
Colin Crossc4773d92020-08-25 17:12:59 -07002854 if len(mctx.errs) > 0 {
2855 errsCh <- mctx.errs
2856 return true
2857 }
2858
2859 if module.missingDeps != nil && !mctx.handledMissingDeps {
2860 var errs []error
2861 for _, depName := range module.missingDeps {
2862 errs = append(errs, c.missingDependencyError(module, depName))
2863 }
2864 errsCh <- errs
2865 return true
2866 }
2867
2868 depsCh <- mctx.ninjaFileDeps
2869
2870 newErrs := c.processLocalBuildActions(&module.actionDefs,
2871 &mctx.actionDefs, liveGlobals)
2872 if len(newErrs) > 0 {
2873 errsCh <- newErrs
2874 return true
2875 }
2876 return false
2877 })
Colin Cross691a60d2015-01-07 18:08:56 -08002878
2879 cancelCh <- struct{}{}
2880 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002881
Colin Crossc4773d92020-08-25 17:12:59 -07002882 errs = append(errs, visitErrs...)
2883
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002884 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002885}
2886
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002887func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002888 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002889
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002890 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002891 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002892
Colin Cross5f03f112017-11-07 13:29:54 -08002893 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002894 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2895 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2896 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002897 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002898
2899 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002900 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002901 context: c,
2902 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002903 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002904 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002905 }
2906
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002907 func() {
2908 defer func() {
2909 if r := recover(); r != nil {
2910 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2911 if err, ok := r.(panicError); ok {
2912 err.addIn(in)
2913 sctx.error(err)
2914 } else {
2915 sctx.error(newPanicErrorf(r, in))
2916 }
2917 }
2918 }()
2919 info.singleton.GenerateBuildActions(sctx)
2920 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002921
2922 if len(sctx.errs) > 0 {
2923 errs = append(errs, sctx.errs...)
2924 if len(errs) > maxErrors {
2925 break
2926 }
2927 continue
2928 }
2929
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002930 deps = append(deps, sctx.ninjaFileDeps...)
2931
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002932 newErrs := c.processLocalBuildActions(&info.actionDefs,
2933 &sctx.actionDefs, liveGlobals)
2934 errs = append(errs, newErrs...)
2935 if len(errs) > maxErrors {
2936 break
2937 }
2938 }
2939
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002940 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002941}
2942
2943func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2944 liveGlobals *liveTracker) []error {
2945
2946 var errs []error
2947
2948 // First we go through and add everything referenced by the module's
2949 // buildDefs to the live globals set. This will end up adding the live
2950 // locals to the set as well, but we'll take them out after.
2951 for _, def := range in.buildDefs {
2952 err := liveGlobals.AddBuildDefDeps(def)
2953 if err != nil {
2954 errs = append(errs, err)
2955 }
2956 }
2957
2958 if len(errs) > 0 {
2959 return errs
2960 }
2961
Colin Crossc9028482014-12-18 16:28:54 -08002962 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002963
2964 // We use the now-incorrect set of live "globals" to determine which local
2965 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002966 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002967 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002968 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002969 if isLive {
2970 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002971 }
2972 }
2973
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002974 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002975 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002976 if isLive {
2977 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002978 }
2979 }
2980
2981 return nil
2982}
2983
Colin Cross9607a9f2018-06-20 11:16:37 -07002984func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07002985 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07002986
2987 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002988 var visiting *moduleInfo
2989
2990 defer func() {
2991 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07002992 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
2993 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002994 }
2995 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07002996
2997 var walk func(module *moduleInfo)
2998 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002999 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07003000 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003001 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07003002 recurse := true
3003 if visitDown != nil {
3004 recurse = visitDown(dep, module)
3005 }
Colin Cross526e02f2018-06-21 13:31:53 -07003006 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003007 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01003008 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07003009 }
Colin Crossbafd5f52016-08-06 22:52:01 -07003010 if visitUp != nil {
3011 visitUp(dep, module)
3012 }
Yuchen Wu222e2452015-10-06 14:03:27 -07003013 }
3014 }
3015 }
3016
3017 walk(topModule)
3018}
3019
Colin Cross9cfd1982016-10-11 09:58:53 -07003020type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003021 from, to *moduleInfo
3022 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003023}
3024
Colin Crossc4e5b812016-10-12 10:45:05 -07003025type rename struct {
3026 group *moduleGroup
3027 name string
3028}
3029
Colin Cross0ce142c2016-12-09 10:29:05 -08003030func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003031 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003032
Colin Crossd03b59d2019-11-13 20:10:12 -08003033 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003034 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003035 }
3036
Colin Crossd03b59d2019-11-13 20:10:12 -08003037 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003038 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003039 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003040 }
3041 }
3042
Colin Cross0ce142c2016-12-09 10:29:05 -08003043 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003044}
3045
Colin Cross0ce142c2016-12-09 10:29:05 -08003046func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003047 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003048 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003049 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003050 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003051 continue
3052 }
3053
Jeff Gastond70bf752017-11-10 15:12:08 -08003054 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003055 }
3056
Colin Cross0ce142c2016-12-09 10:29:05 -08003057 return errs
3058}
3059
3060func (c *Context) handleReplacements(replacements []replace) []error {
3061 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003062 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003063 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003064 for _, m := range replace.from.reverseDeps {
3065 for i, d := range m.directDeps {
3066 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003067 // If the replacement has a predicate then check it.
3068 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3069 m.directDeps[i].module = replace.to
3070 changedDeps = true
3071 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003072 }
3073 }
3074 }
3075
Colin Cross9cfd1982016-10-11 09:58:53 -07003076 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003077
Paul Duffin8969cb62020-06-30 12:15:26 +01003078 if changedDeps {
3079 atomic.AddUint32(&c.depsModified, 1)
3080 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003081 return errs
3082}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003083
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003084func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3085 if depVariations != nil {
3086 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3087 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003088 if c.allowMissingDependencies {
3089 module.missingDeps = append(module.missingDeps, depName)
3090 return nil
3091 }
3092 return []error{c.missingDependencyError(module, depName)}
3093}
3094
3095func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3096 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3097
3098 return &BlueprintError{
3099 Err: err,
3100 Pos: module.pos,
3101 }
3102}
3103
Colin Crossd03b59d2019-11-13 20:10:12 -08003104func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003105 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3106 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003107 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003108 }
3109 return nil
3110}
3111
Jeff Gastond70bf752017-11-10 15:12:08 -08003112func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003113 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003114 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3115 result := make([]*moduleGroup, 0, len(wrappers))
3116 for _, group := range wrappers {
3117 result = append(result, group.moduleGroup)
3118 }
3119 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003120 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003121
3122 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003123 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003124 }
3125
Jeff Gastond70bf752017-11-10 15:12:08 -08003126 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003127}
3128
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003129func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003130 var module *moduleInfo
3131
3132 defer func() {
3133 if r := recover(); r != nil {
3134 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3135 funcName(visit), module))
3136 }
3137 }()
3138
Jeff Gastond70bf752017-11-10 15:12:08 -08003139 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003140 for _, moduleOrAlias := range moduleGroup.modules {
3141 if module = moduleOrAlias.module(); module != nil {
3142 visit(module.logicModule)
3143 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003144 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003145 }
3146}
3147
3148func (c *Context) visitAllModulesIf(pred func(Module) bool,
3149 visit func(Module)) {
3150
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003151 var module *moduleInfo
3152
3153 defer func() {
3154 if r := recover(); r != nil {
3155 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3156 funcName(pred), funcName(visit), module))
3157 }
3158 }()
3159
Jeff Gastond70bf752017-11-10 15:12:08 -08003160 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003161 for _, moduleOrAlias := range moduleGroup.modules {
3162 if module = moduleOrAlias.module(); module != nil {
3163 if pred(module.logicModule) {
3164 visit(module.logicModule)
3165 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003166 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003167 }
3168 }
3169}
3170
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003171func (c *Context) visitAllModuleVariants(module *moduleInfo,
3172 visit func(Module)) {
3173
3174 var variant *moduleInfo
3175
3176 defer func() {
3177 if r := recover(); r != nil {
3178 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3179 module, funcName(visit), variant))
3180 }
3181 }()
3182
Colin Cross5df74a82020-08-24 16:18:21 -07003183 for _, moduleOrAlias := range module.group.modules {
3184 if variant = moduleOrAlias.module(); variant != nil {
3185 visit(variant.logicModule)
3186 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003187 }
3188}
3189
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003190func (c *Context) requireNinjaVersion(major, minor, micro int) {
3191 if major != 1 {
3192 panic("ninja version with major version != 1 not supported")
3193 }
3194 if c.requiredNinjaMinor < minor {
3195 c.requiredNinjaMinor = minor
3196 c.requiredNinjaMicro = micro
3197 }
3198 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3199 c.requiredNinjaMicro = micro
3200 }
3201}
3202
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003203func (c *Context) setOutDir(value ninjaString) {
3204 if c.outDir == nil {
3205 c.outDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003206 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003207}
3208
3209func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003210 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003211
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003212 pkgs := make(map[string]*packageContext)
3213 pkgNames := make(map[*packageContext]string)
3214 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003215
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003216 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003217 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003218 // This is a built-in rule and has no package.
3219 return
3220 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003221 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003222 // We've already processed this package.
3223 return
3224 }
3225
Jamie Gennis2fb20952014-10-03 02:49:58 -07003226 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003227 if present {
3228 // Short name collision. Both this package and the one that's
3229 // already there need to use their full names. We leave the short
3230 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003231 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003232 longPkgNames[otherPkg] = true
3233 } else {
3234 // No collision so far. Tentatively set the package's name to be
3235 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003236 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003237 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003238 }
3239 }
3240
3241 // We try to give all packages their short name, but when we get collisions
3242 // we need to use the full unique package name.
3243 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003244 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003245 }
3246 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003247 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003248 }
3249 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003250 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003251 }
3252
3253 // Add the packages that had collisions using their full unique names. This
3254 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003255 for pctx := range longPkgNames {
3256 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003257 }
3258
Dan Willemsena481ae22015-12-18 15:18:03 -08003259 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3260 deps := []string{}
3261 for _, pkg := range pkgs {
3262 deps = append(deps, pkg.ninjaFileDeps...)
3263 }
3264
3265 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003266}
3267
Colin Cross92054a42021-01-21 16:49:25 -08003268// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3269// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3270// are used much more than once.
3271func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3272 for v := range liveGlobals.variables {
3273 v.memoizeFullName(pkgNames)
3274 }
3275 for r := range liveGlobals.rules {
3276 r.memoizeFullName(pkgNames)
3277 }
3278 for p := range liveGlobals.pools {
3279 p.memoizeFullName(pkgNames)
3280 }
3281}
3282
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003283func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003284 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003285
3286 visited := make(map[Variable]bool) // variables that were already checked
3287 checking := make(map[Variable]bool) // variables actively being checked
3288
3289 var check func(v Variable) []Variable
3290
3291 check = func(v Variable) []Variable {
3292 visited[v] = true
3293 checking[v] = true
3294 defer delete(checking, v)
3295
3296 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003297 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003298 if checking[dep] {
3299 // This is a cycle.
3300 return []Variable{dep, v}
3301 }
3302
3303 if !visited[dep] {
3304 cycle := check(dep)
3305 if cycle != nil {
3306 if cycle[0] == v {
3307 // We are the "start" of the cycle, so we're responsible
3308 // for generating the errors. The cycle list is in
3309 // reverse order because all the 'check' calls append
3310 // their own module to the list.
3311 msgs := []string{"detected variable reference cycle:"}
3312
3313 // Iterate backwards through the cycle list.
3314 curName := v.fullName(pkgNames)
3315 curValue := value.Value(pkgNames)
3316 for i := len(cycle) - 1; i >= 0; i-- {
3317 next := cycle[i]
3318 nextName := next.fullName(pkgNames)
3319 nextValue := variables[next].Value(pkgNames)
3320
3321 msgs = append(msgs, fmt.Sprintf(
3322 " %q depends on %q", curName, nextName))
3323 msgs = append(msgs, fmt.Sprintf(
3324 " [%s = %s]", curName, curValue))
3325
3326 curName = nextName
3327 curValue = nextValue
3328 }
3329
3330 // Variable reference cycles are a programming error,
3331 // not the fault of the Blueprint file authors.
3332 panic(strings.Join(msgs, "\n"))
3333 } else {
3334 // We're not the "start" of the cycle, so we just append
3335 // our module to the list and return it.
3336 return append(cycle, v)
3337 }
3338 }
3339 }
3340 }
3341
3342 return nil
3343 }
3344
3345 for v := range variables {
3346 if !visited[v] {
3347 cycle := check(v)
3348 if cycle != nil {
3349 panic("inconceivable!")
3350 }
3351 }
3352 }
3353}
3354
Jamie Gennisaf435562014-10-27 22:34:56 -07003355// AllTargets returns a map all the build target names to the rule used to build
3356// them. This is the same information that is output by running 'ninja -t
3357// targets all'. If this is called before PrepareBuildActions successfully
3358// completes then ErrbuildActionsNotReady is returned.
3359func (c *Context) AllTargets() (map[string]string, error) {
3360 if !c.buildActionsReady {
3361 return nil, ErrBuildActionsNotReady
3362 }
3363
3364 targets := map[string]string{}
3365
3366 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003367 for _, module := range c.moduleInfo {
3368 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003369 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003370 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003371 outputValue, err := output.Eval(c.globalVariables)
3372 if err != nil {
3373 return nil, err
3374 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003375 targets[outputValue] = ruleName
3376 }
3377 }
3378 }
3379
3380 // Collect all the singleton build targets.
3381 for _, info := range c.singletonInfo {
3382 for _, buildDef := range info.actionDefs.buildDefs {
3383 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003384 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003385 outputValue, err := output.Eval(c.globalVariables)
3386 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003387 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003388 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003389 targets[outputValue] = ruleName
3390 }
3391 }
3392 }
3393
3394 return targets, nil
3395}
3396
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003397func (c *Context) OutDir() (string, error) {
3398 if c.outDir != nil {
3399 return c.outDir.Eval(c.globalVariables)
Colin Crossa2599452015-11-18 16:01:01 -08003400 } else {
3401 return "", nil
3402 }
3403}
3404
Colin Cross4572edd2015-05-13 14:36:24 -07003405// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3406// property structs returned by the factory for that module type.
3407func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3408 ret := make(map[string][]interface{})
3409 for moduleType, factory := range c.moduleFactories {
3410 _, ret[moduleType] = factory()
3411 }
3412
3413 return ret
3414}
3415
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003416func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3417 ret := make(map[string]ModuleFactory)
3418 for k, v := range c.moduleFactories {
3419 ret[k] = v
3420 }
3421 return ret
3422}
3423
Colin Cross4572edd2015-05-13 14:36:24 -07003424func (c *Context) ModuleName(logicModule Module) string {
3425 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003426 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003427}
3428
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003429func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003430 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003431}
3432
Colin Cross8c602f72015-12-17 18:02:11 -08003433func (c *Context) ModuleSubDir(logicModule Module) string {
3434 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003435 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003436}
3437
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003438func (c *Context) ModuleType(logicModule Module) string {
3439 module := c.moduleInfo[logicModule]
3440 return module.typeName
3441}
3442
Colin Cross2da84922020-07-02 10:08:12 -07003443// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3444// provider was not set it returns the zero value of the type of the provider, which means the
3445// return value can always be type-asserted to the type of the provider. The return value should
3446// always be considered read-only. It panics if called before the appropriate mutator or
3447// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3448// copy of the value originally passed to SetProvider.
3449func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3450 module := c.moduleInfo[logicModule]
3451 value, _ := c.provider(module, provider)
3452 return value
3453}
3454
3455// ModuleHasProvider returns true if the provider for the given module has been set.
3456func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3457 module := c.moduleInfo[logicModule]
3458 _, ok := c.provider(module, provider)
3459 return ok
3460}
3461
Colin Cross4572edd2015-05-13 14:36:24 -07003462func (c *Context) BlueprintFile(logicModule Module) string {
3463 module := c.moduleInfo[logicModule]
3464 return module.relBlueprintsFile
3465}
3466
3467func (c *Context) ModuleErrorf(logicModule Module, format string,
3468 args ...interface{}) error {
3469
3470 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003471 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003472 Err: fmt.Errorf(format, args...),
3473 Pos: module.pos,
3474 }
3475}
3476
3477func (c *Context) VisitAllModules(visit func(Module)) {
3478 c.visitAllModules(visit)
3479}
3480
3481func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3482 visit func(Module)) {
3483
3484 c.visitAllModulesIf(pred, visit)
3485}
3486
Colin Cross080c1332017-03-17 13:09:05 -07003487func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3488 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003489
Colin Cross080c1332017-03-17 13:09:05 -07003490 var visiting *moduleInfo
3491
3492 defer func() {
3493 if r := recover(); r != nil {
3494 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3495 topModule, funcName(visit), visiting))
3496 }
3497 }()
3498
3499 for _, dep := range topModule.directDeps {
3500 visiting = dep.module
3501 visit(dep.module.logicModule)
3502 }
3503}
3504
3505func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3506 topModule := c.moduleInfo[module]
3507
3508 var visiting *moduleInfo
3509
3510 defer func() {
3511 if r := recover(); r != nil {
3512 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3513 topModule, funcName(pred), funcName(visit), visiting))
3514 }
3515 }()
3516
3517 for _, dep := range topModule.directDeps {
3518 visiting = dep.module
3519 if pred(dep.module.logicModule) {
3520 visit(dep.module.logicModule)
3521 }
3522 }
3523}
3524
3525func (c *Context) VisitDepsDepthFirst(module Module, 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, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3533 topModule, 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 visiting = dep.module
3539 visit(dep.module.logicModule)
3540 })
Colin Cross4572edd2015-05-13 14:36:24 -07003541}
3542
Colin Cross080c1332017-03-17 13:09:05 -07003543func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003544 topModule := c.moduleInfo[module]
3545
3546 var visiting *moduleInfo
3547
3548 defer func() {
3549 if r := recover(); r != nil {
3550 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3551 topModule, funcName(pred), funcName(visit), visiting))
3552 }
3553 }()
3554
Colin Cross9607a9f2018-06-20 11:16:37 -07003555 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003556 if pred(dep.module.logicModule) {
3557 visiting = dep.module
3558 visit(dep.module.logicModule)
3559 }
3560 })
Colin Cross4572edd2015-05-13 14:36:24 -07003561}
3562
Colin Cross24ad5872015-11-17 16:22:29 -08003563func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003564 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003565}
3566
3567func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003568 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003569}
3570
3571func (c *Context) VisitAllModuleVariants(module Module,
3572 visit func(Module)) {
3573
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003574 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003575}
3576
Colin Cross9226d6c2019-02-25 18:07:44 -08003577// Singletons returns a list of all registered Singletons.
3578func (c *Context) Singletons() []Singleton {
3579 var ret []Singleton
3580 for _, s := range c.singletonInfo {
3581 ret = append(ret, s.singleton)
3582 }
3583 return ret
3584}
3585
3586// SingletonName returns the name that the given singleton was registered with.
3587func (c *Context) SingletonName(singleton Singleton) string {
3588 for _, s := range c.singletonInfo {
3589 if s.singleton == singleton {
3590 return s.name
3591 }
3592 }
3593 return ""
3594}
3595
Jamie Gennisd4e10182014-06-12 20:06:50 -07003596// WriteBuildFile writes the Ninja manifeset text for the generated build
3597// actions to w. If this is called before PrepareBuildActions successfully
3598// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003599func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003600 var err error
3601 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3602 if !c.buildActionsReady {
3603 err = ErrBuildActionsNotReady
3604 return
3605 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003606
Colin Cross3a8c0252019-01-23 13:21:48 -08003607 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003608
Colin Cross3a8c0252019-01-23 13:21:48 -08003609 err = c.writeBuildFileHeader(nw)
3610 if err != nil {
3611 return
3612 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003613
Colin Cross3a8c0252019-01-23 13:21:48 -08003614 err = c.writeNinjaRequiredVersion(nw)
3615 if err != nil {
3616 return
3617 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003618
Colin Cross3a8c0252019-01-23 13:21:48 -08003619 err = c.writeSubninjas(nw)
3620 if err != nil {
3621 return
3622 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003623
Colin Cross3a8c0252019-01-23 13:21:48 -08003624 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003625
Colin Cross3a8c0252019-01-23 13:21:48 -08003626 err = c.writeGlobalVariables(nw)
3627 if err != nil {
3628 return
3629 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003630
Colin Cross3a8c0252019-01-23 13:21:48 -08003631 err = c.writeGlobalPools(nw)
3632 if err != nil {
3633 return
3634 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003635
Colin Cross3a8c0252019-01-23 13:21:48 -08003636 err = c.writeBuildDir(nw)
3637 if err != nil {
3638 return
3639 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003640
Colin Cross3a8c0252019-01-23 13:21:48 -08003641 err = c.writeGlobalRules(nw)
3642 if err != nil {
3643 return
3644 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003645
Colin Cross3a8c0252019-01-23 13:21:48 -08003646 err = c.writeAllModuleActions(nw)
3647 if err != nil {
3648 return
3649 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003650
Colin Cross3a8c0252019-01-23 13:21:48 -08003651 err = c.writeAllSingletonActions(nw)
3652 if err != nil {
3653 return
3654 }
3655 })
3656
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003657 if err != nil {
3658 return err
3659 }
3660
3661 return nil
3662}
3663
Jamie Gennisc15544d2014-09-24 20:26:52 -07003664type pkgAssociation struct {
3665 PkgName string
3666 PkgPath string
3667}
3668
3669type pkgAssociationSorter struct {
3670 pkgs []pkgAssociation
3671}
3672
3673func (s *pkgAssociationSorter) Len() int {
3674 return len(s.pkgs)
3675}
3676
3677func (s *pkgAssociationSorter) Less(i, j int) bool {
3678 iName := s.pkgs[i].PkgName
3679 jName := s.pkgs[j].PkgName
3680 return iName < jName
3681}
3682
3683func (s *pkgAssociationSorter) Swap(i, j int) {
3684 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3685}
3686
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003687func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3688 headerTemplate := template.New("fileHeader")
3689 _, err := headerTemplate.Parse(fileHeaderTemplate)
3690 if err != nil {
3691 // This is a programming error.
3692 panic(err)
3693 }
3694
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003695 var pkgs []pkgAssociation
3696 maxNameLen := 0
3697 for pkg, name := range c.pkgNames {
3698 pkgs = append(pkgs, pkgAssociation{
3699 PkgName: name,
3700 PkgPath: pkg.pkgPath,
3701 })
3702 if len(name) > maxNameLen {
3703 maxNameLen = len(name)
3704 }
3705 }
3706
3707 for i := range pkgs {
3708 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3709 }
3710
Jamie Gennisc15544d2014-09-24 20:26:52 -07003711 sort.Sort(&pkgAssociationSorter{pkgs})
3712
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003713 params := map[string]interface{}{
3714 "Pkgs": pkgs,
3715 }
3716
3717 buf := bytes.NewBuffer(nil)
3718 err = headerTemplate.Execute(buf, params)
3719 if err != nil {
3720 return err
3721 }
3722
3723 return nw.Comment(buf.String())
3724}
3725
3726func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3727 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3728 c.requiredNinjaMicro)
3729
3730 err := nw.Assign("ninja_required_version", value)
3731 if err != nil {
3732 return err
3733 }
3734
3735 return nw.BlankLine()
3736}
3737
Dan Willemsenab223a52018-07-05 21:56:59 -07003738func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3739 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003740 err := nw.Subninja(subninja)
3741 if err != nil {
3742 return err
3743 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003744 }
3745 return nw.BlankLine()
3746}
3747
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003748func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Lukacs T. Berki5c4abb12021-08-26 15:08:09 +02003749 if c.outDir != nil {
3750 err := nw.Assign("builddir", c.outDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003751 if err != nil {
3752 return err
3753 }
3754
3755 err = nw.BlankLine()
3756 if err != nil {
3757 return err
3758 }
3759 }
3760 return nil
3761}
3762
Jamie Gennisc15544d2014-09-24 20:26:52 -07003763type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003764 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003765}
3766
Jamie Gennisc15544d2014-09-24 20:26:52 -07003767type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003768 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003769 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003770}
3771
Jamie Gennisc15544d2014-09-24 20:26:52 -07003772func (s *globalEntitySorter) Len() int {
3773 return len(s.entities)
3774}
3775
3776func (s *globalEntitySorter) Less(i, j int) bool {
3777 iName := s.entities[i].fullName(s.pkgNames)
3778 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003779 return iName < jName
3780}
3781
Jamie Gennisc15544d2014-09-24 20:26:52 -07003782func (s *globalEntitySorter) Swap(i, j int) {
3783 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003784}
3785
3786func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3787 visited := make(map[Variable]bool)
3788
3789 var walk func(v Variable) error
3790 walk = func(v Variable) error {
3791 visited[v] = true
3792
3793 // First visit variables on which this variable depends.
3794 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003795 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003796 if !visited[dep] {
3797 err := walk(dep)
3798 if err != nil {
3799 return err
3800 }
3801 }
3802 }
3803
3804 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3805 if err != nil {
3806 return err
3807 }
3808
3809 err = nw.BlankLine()
3810 if err != nil {
3811 return err
3812 }
3813
3814 return nil
3815 }
3816
Jamie Gennisc15544d2014-09-24 20:26:52 -07003817 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3818 for variable := range c.globalVariables {
3819 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003820 }
3821
Jamie Gennisc15544d2014-09-24 20:26:52 -07003822 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003823
Jamie Gennisc15544d2014-09-24 20:26:52 -07003824 for _, entity := range globalVariables {
3825 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003826 if !visited[v] {
3827 err := walk(v)
3828 if err != nil {
3829 return nil
3830 }
3831 }
3832 }
3833
3834 return nil
3835}
3836
3837func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003838 globalPools := make([]globalEntity, 0, len(c.globalPools))
3839 for pool := range c.globalPools {
3840 globalPools = append(globalPools, pool)
3841 }
3842
3843 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3844
3845 for _, entity := range globalPools {
3846 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003847 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003848 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003849 err := def.WriteTo(nw, name)
3850 if err != nil {
3851 return err
3852 }
3853
3854 err = nw.BlankLine()
3855 if err != nil {
3856 return err
3857 }
3858 }
3859
3860 return nil
3861}
3862
3863func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003864 globalRules := make([]globalEntity, 0, len(c.globalRules))
3865 for rule := range c.globalRules {
3866 globalRules = append(globalRules, rule)
3867 }
3868
3869 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3870
3871 for _, entity := range globalRules {
3872 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003873 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003874 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003875 err := def.WriteTo(nw, name, c.pkgNames)
3876 if err != nil {
3877 return err
3878 }
3879
3880 err = nw.BlankLine()
3881 if err != nil {
3882 return err
3883 }
3884 }
3885
3886 return nil
3887}
3888
Colin Cross2c1f3d12016-04-11 15:47:28 -07003889type depSorter []depInfo
3890
3891func (s depSorter) Len() int {
3892 return len(s)
3893}
3894
3895func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003896 iName := s[i].module.Name()
3897 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003898 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003899 iName = s[i].module.variant.name
3900 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003901 }
3902 return iName < jName
3903}
3904
3905func (s depSorter) Swap(i, j int) {
3906 s[i], s[j] = s[j], s[i]
3907}
3908
Jeff Gaston0e907592017-12-01 17:10:52 -08003909type moduleSorter struct {
3910 modules []*moduleInfo
3911 nameInterface NameInterface
3912}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003913
Colin Crossab6d7902015-03-11 16:17:52 -07003914func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003915 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003916}
3917
Colin Crossab6d7902015-03-11 16:17:52 -07003918func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003919 iMod := s.modules[i]
3920 jMod := s.modules[j]
3921 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3922 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003923 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003924 iVariantName := s.modules[i].variant.name
3925 jVariantName := s.modules[j].variant.name
3926 if iVariantName == jVariantName {
3927 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3928 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3929 } else {
3930 return iVariantName < jVariantName
3931 }
3932 } else {
3933 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003934 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003935}
3936
Colin Crossab6d7902015-03-11 16:17:52 -07003937func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003938 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003939}
3940
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003941func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3942 headerTemplate := template.New("moduleHeader")
3943 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3944 if err != nil {
3945 // This is a programming error.
3946 panic(err)
3947 }
3948
Colin Crossab6d7902015-03-11 16:17:52 -07003949 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3950 for _, module := range c.moduleInfo {
3951 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003952 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003953 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003954
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003955 buf := bytes.NewBuffer(nil)
3956
Colin Crossab6d7902015-03-11 16:17:52 -07003957 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003958 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3959 continue
3960 }
3961
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003962 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003963
3964 // In order to make the bootstrap build manifest independent of the
3965 // build dir we need to output the Blueprints file locations in the
3966 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003967 relPos := module.pos
3968 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003969
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003970 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003971 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003972 factoryName := factoryFunc.Name()
3973
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003974 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003975 "name": module.Name(),
3976 "typeName": module.typeName,
3977 "goFactory": factoryName,
3978 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07003979 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003980 }
3981 err = headerTemplate.Execute(buf, infoMap)
3982 if err != nil {
3983 return err
3984 }
3985
3986 err = nw.Comment(buf.String())
3987 if err != nil {
3988 return err
3989 }
3990
3991 err = nw.BlankLine()
3992 if err != nil {
3993 return err
3994 }
3995
Colin Crossab6d7902015-03-11 16:17:52 -07003996 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003997 if err != nil {
3998 return err
3999 }
4000
4001 err = nw.BlankLine()
4002 if err != nil {
4003 return err
4004 }
4005 }
4006
4007 return nil
4008}
4009
4010func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
4011 headerTemplate := template.New("singletonHeader")
4012 _, err := headerTemplate.Parse(singletonHeaderTemplate)
4013 if err != nil {
4014 // This is a programming error.
4015 panic(err)
4016 }
4017
4018 buf := bytes.NewBuffer(nil)
4019
Yuchen Wub9103ef2015-08-25 17:58:17 -07004020 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004021 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4022 continue
4023 }
4024
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004025 // Get the name of the factory function for the module.
4026 factory := info.factory
4027 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4028 factoryName := factoryFunc.Name()
4029
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004030 buf.Reset()
4031 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004032 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004033 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004034 }
4035 err = headerTemplate.Execute(buf, infoMap)
4036 if err != nil {
4037 return err
4038 }
4039
4040 err = nw.Comment(buf.String())
4041 if err != nil {
4042 return err
4043 }
4044
4045 err = nw.BlankLine()
4046 if err != nil {
4047 return err
4048 }
4049
4050 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4051 if err != nil {
4052 return err
4053 }
4054
4055 err = nw.BlankLine()
4056 if err != nil {
4057 return err
4058 }
4059 }
4060
4061 return nil
4062}
4063
4064func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4065 defs *localBuildActions) error {
4066
4067 // Write the local variable assignments.
4068 for _, v := range defs.variables {
4069 // A localVariable doesn't need the package names or config to
4070 // determine its name or value.
4071 name := v.fullName(nil)
4072 value, err := v.value(nil)
4073 if err != nil {
4074 panic(err)
4075 }
4076 err = nw.Assign(name, value.Value(c.pkgNames))
4077 if err != nil {
4078 return err
4079 }
4080 }
4081
4082 if len(defs.variables) > 0 {
4083 err := nw.BlankLine()
4084 if err != nil {
4085 return err
4086 }
4087 }
4088
4089 // Write the local rules.
4090 for _, r := range defs.rules {
4091 // A localRule doesn't need the package names or config to determine
4092 // its name or definition.
4093 name := r.fullName(nil)
4094 def, err := r.def(nil)
4095 if err != nil {
4096 panic(err)
4097 }
4098
4099 err = def.WriteTo(nw, name, c.pkgNames)
4100 if err != nil {
4101 return err
4102 }
4103
4104 err = nw.BlankLine()
4105 if err != nil {
4106 return err
4107 }
4108 }
4109
4110 // Write the build definitions.
4111 for _, buildDef := range defs.buildDefs {
4112 err := buildDef.WriteTo(nw, c.pkgNames)
4113 if err != nil {
4114 return err
4115 }
4116
4117 if len(buildDef.Args) > 0 {
4118 err = nw.BlankLine()
4119 if err != nil {
4120 return err
4121 }
4122 }
4123 }
4124
4125 return nil
4126}
4127
Colin Cross5df74a82020-08-24 16:18:21 -07004128func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004129 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004130 if a == b {
4131 return false
4132 }
Colin Cross65569e42015-03-10 20:08:19 -07004133 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004134 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004135 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004136 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004137 return found
4138 }
4139 }
4140
4141 missing := a
4142 if found {
4143 missing = b
4144 }
4145 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4146}
4147
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004148type panicError struct {
4149 panic interface{}
4150 stack []byte
4151 in string
4152}
4153
4154func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4155 buf := make([]byte, 4096)
4156 count := runtime.Stack(buf, false)
4157 return panicError{
4158 panic: panic,
4159 in: fmt.Sprintf(in, a...),
4160 stack: buf[:count],
4161 }
4162}
4163
4164func (p panicError) Error() string {
4165 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4166}
4167
4168func (p *panicError) addIn(in string) {
4169 p.in += " in " + in
4170}
4171
4172func funcName(f interface{}) string {
4173 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4174}
4175
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004176var fileHeaderTemplate = `******************************************************************************
4177*** This file is generated and should not be edited ***
4178******************************************************************************
4179{{if .Pkgs}}
4180This file contains variables, rules, and pools with name prefixes indicating
4181they were generated by the following Go packages:
4182{{range .Pkgs}}
4183 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4184
4185`
4186
4187var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004188Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004189Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004190Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004191Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004192Defined: {{.pos}}
4193`
4194
4195var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4196Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004197Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004198`