blob: cc6e8e1b00fd0349d4f2f63f725ae9b58765b644 [file] [log] [blame]
Colin Cross8e0c5112015-01-23 14:15:10 -08001// Copyright 2014 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Jamie Gennis1bc967e2014-05-27 16:34:41 -070015package blueprint
16
17import (
Jamie Gennis1bc967e2014-05-27 16:34:41 -070018 "bytes"
Colin Cross3a8c0252019-01-23 13:21:48 -080019 "context"
Lukacs T. Berki6f682822021-04-01 18:27:31 +020020 "encoding/json"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070021 "errors"
22 "fmt"
23 "io"
Jeff Gastonc3e28442017-08-09 15:13:12 -070024 "io/ioutil"
Jeff Gastonaca42202017-08-23 17:30:05 -070025 "os"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070026 "path/filepath"
27 "reflect"
Romain Guy28529652014-08-12 17:50:11 -070028 "runtime"
Colin Cross3a8c0252019-01-23 13:21:48 -080029 "runtime/pprof"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070030 "sort"
31 "strings"
Colin Cross127d2ea2016-11-01 11:10:51 -070032 "sync"
Colin Cross23d7aa12015-06-30 16:05:22 -070033 "sync/atomic"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070034 "text/scanner"
35 "text/template"
Colin Cross1fef5362015-04-20 16:50:54 -070036
37 "github.com/google/blueprint/parser"
Colin Crossb519a7e2017-02-01 13:21:35 -080038 "github.com/google/blueprint/pathtools"
Colin Cross1fef5362015-04-20 16:50:54 -070039 "github.com/google/blueprint/proptools"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070040)
41
42var ErrBuildActionsNotReady = errors.New("build actions are not ready")
43
44const maxErrors = 10
Jeff Gaston9f630902017-11-15 14:49:48 -080045const MockModuleListFile = "bplist"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070046
Jamie Gennisd4e10182014-06-12 20:06:50 -070047// A Context contains all the state needed to parse a set of Blueprints files
48// and generate a Ninja file. The process of generating a Ninja file proceeds
49// through a series of four phases. Each phase corresponds with a some methods
50// on the Context object
51//
52// Phase Methods
53// ------------ -------------------------------------------
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070054// 1. Registration RegisterModuleType, RegisterSingletonType
Jamie Gennisd4e10182014-06-12 20:06:50 -070055//
56// 2. Parse ParseBlueprintsFiles, Parse
57//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070058// 3. Generate ResolveDependencies, PrepareBuildActions
Jamie Gennisd4e10182014-06-12 20:06:50 -070059//
60// 4. Write WriteBuildFile
61//
62// The registration phase prepares the context to process Blueprints files
63// containing various types of modules. The parse phase reads in one or more
64// Blueprints files and validates their contents against the module types that
65// have been registered. The generate phase then analyzes the parsed Blueprints
66// contents to create an internal representation for the build actions that must
67// be performed. This phase also performs validation of the module dependencies
68// and property values defined in the parsed Blueprints files. Finally, the
69// write phase generates the Ninja manifest text based on the generated build
70// actions.
Jamie Gennis1bc967e2014-05-27 16:34:41 -070071type Context struct {
Colin Cross3a8c0252019-01-23 13:21:48 -080072 context.Context
73
Jamie Gennis1bc967e2014-05-27 16:34:41 -070074 // set at instantiation
Colin Cross65569e42015-03-10 20:08:19 -070075 moduleFactories map[string]ModuleFactory
Jeff Gastond70bf752017-11-10 15:12:08 -080076 nameInterface NameInterface
Colin Cross0b7e83e2016-05-17 14:58:05 -070077 moduleGroups []*moduleGroup
Colin Cross65569e42015-03-10 20:08:19 -070078 moduleInfo map[Module]*moduleInfo
79 modulesSorted []*moduleInfo
Colin Cross5f03f112017-11-07 13:29:54 -080080 preSingletonInfo []*singletonInfo
Yuchen Wub9103ef2015-08-25 17:58:17 -070081 singletonInfo []*singletonInfo
Colin Cross65569e42015-03-10 20:08:19 -070082 mutatorInfo []*mutatorInfo
Colin Crossf8b50422016-08-10 12:56:40 -070083 earlyMutatorInfo []*mutatorInfo
Colin Cross65569e42015-03-10 20:08:19 -070084 variantMutatorNames []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070085
Colin Cross3702ac72016-08-11 11:09:00 -070086 depsModified uint32 // positive if a mutator modified the dependencies
87
Jamie Gennis1bc967e2014-05-27 16:34:41 -070088 dependenciesReady bool // set to true on a successful ResolveDependencies
89 buildActionsReady bool // set to true on a successful PrepareBuildActions
90
91 // set by SetIgnoreUnknownModuleTypes
92 ignoreUnknownModuleTypes bool
93
Colin Cross036a1df2015-12-17 15:49:30 -080094 // set by SetAllowMissingDependencies
95 allowMissingDependencies bool
96
Jamie Gennis1bc967e2014-05-27 16:34:41 -070097 // set during PrepareBuildActions
Dan Willemsenaeffbf72015-11-25 15:29:32 -080098 pkgNames map[*packageContext]string
Colin Cross5f03f112017-11-07 13:29:54 -080099 liveGlobals *liveTracker
Colin Cross2ce594e2020-01-29 12:58:03 -0800100 globalVariables map[Variable]ninjaString
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700101 globalPools map[Pool]*poolDef
102 globalRules map[Rule]*ruleDef
103
104 // set during PrepareBuildActions
Colin Cross2ce594e2020-01-29 12:58:03 -0800105 ninjaBuildDir ninjaString // The builddir special Ninja variable
106 requiredNinjaMajor int // For the ninja_required_version variable
107 requiredNinjaMinor int // For the ninja_required_version variable
108 requiredNinjaMicro int // For the ninja_required_version variable
Jamie Gennisc15544d2014-09-24 20:26:52 -0700109
Dan Willemsenab223a52018-07-05 21:56:59 -0700110 subninjas []string
111
Jeff Gastond70bf752017-11-10 15:12:08 -0800112 // set lazily by sortedModuleGroups
113 cachedSortedModuleGroups []*moduleGroup
Liz Kammer9ae14f12020-11-30 16:30:45 -0700114 // cache deps modified to determine whether cachedSortedModuleGroups needs to be recalculated
115 cachedDepsModified bool
Colin Crossd7b0f602016-06-02 15:30:20 -0700116
Colin Cross25236982021-04-05 17:20:34 -0700117 globs map[globKey]pathtools.GlobResult
Colin Cross127d2ea2016-11-01 11:10:51 -0700118 globLock sync.Mutex
119
Colin Crossc5fa50e2019-12-17 13:12:35 -0800120 srcDir string
Jeff Gastonc3e28442017-08-09 15:13:12 -0700121 fs pathtools.FileSystem
122 moduleListFile string
Colin Cross2da84922020-07-02 10:08:12 -0700123
124 // Mutators indexed by the ID of the provider associated with them. Not all mutators will
125 // have providers, and not all providers will have a mutator, or if they do the mutator may
126 // not be registered in this Context.
127 providerMutators []*mutatorInfo
128
129 // The currently running mutator
130 startedMutator *mutatorInfo
131 // True for any mutators that have already run over all modules
132 finishedMutators map[*mutatorInfo]bool
133
134 // Can be set by tests to avoid invalidating Module values after mutators.
135 skipCloneModulesAfterMutators bool
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700136}
137
Jamie Gennisd4e10182014-06-12 20:06:50 -0700138// An Error describes a problem that was encountered that is related to a
139// particular location in a Blueprints file.
Colin Cross2c628442016-10-07 17:13:10 -0700140type BlueprintError struct {
Jamie Gennisd4e10182014-06-12 20:06:50 -0700141 Err error // the error that occurred
142 Pos scanner.Position // the relevant Blueprints file location
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700143}
144
Colin Cross2c628442016-10-07 17:13:10 -0700145// A ModuleError describes a problem that was encountered that is related to a
146// particular module in a Blueprints file
147type ModuleError struct {
148 BlueprintError
149 module *moduleInfo
150}
151
152// A PropertyError describes a problem that was encountered that is related to a
153// particular property in a Blueprints file
154type PropertyError struct {
155 ModuleError
156 property string
157}
158
159func (e *BlueprintError) Error() string {
160 return fmt.Sprintf("%s: %s", e.Pos, e.Err)
161}
162
163func (e *ModuleError) Error() string {
164 return fmt.Sprintf("%s: %s: %s", e.Pos, e.module, e.Err)
165}
166
167func (e *PropertyError) Error() string {
168 return fmt.Sprintf("%s: %s: %s: %s", e.Pos, e.module, e.property, e.Err)
169}
170
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700171type localBuildActions struct {
172 variables []*localVariable
173 rules []*localRule
174 buildDefs []*buildDef
175}
176
Colin Crossf7beb892019-11-13 20:11:14 -0800177type moduleAlias struct {
Colin Crossedc41762020-08-13 12:07:30 -0700178 variant variant
179 target *moduleInfo
Colin Crossf7beb892019-11-13 20:11:14 -0800180}
181
Colin Cross5df74a82020-08-24 16:18:21 -0700182func (m *moduleAlias) alias() *moduleAlias { return m }
183func (m *moduleAlias) module() *moduleInfo { return nil }
184func (m *moduleAlias) moduleOrAliasTarget() *moduleInfo { return m.target }
185func (m *moduleAlias) moduleOrAliasVariant() variant { return m.variant }
186
187func (m *moduleInfo) alias() *moduleAlias { return nil }
188func (m *moduleInfo) module() *moduleInfo { return m }
189func (m *moduleInfo) moduleOrAliasTarget() *moduleInfo { return m }
190func (m *moduleInfo) moduleOrAliasVariant() variant { return m.variant }
191
192type moduleOrAlias interface {
193 alias() *moduleAlias
194 module() *moduleInfo
195 moduleOrAliasTarget() *moduleInfo
196 moduleOrAliasVariant() variant
197}
198
199type modulesOrAliases []moduleOrAlias
200
201func (l modulesOrAliases) firstModule() *moduleInfo {
202 for _, moduleOrAlias := range l {
203 if m := moduleOrAlias.module(); m != nil {
204 return m
205 }
206 }
207 panic(fmt.Errorf("no first module!"))
208}
209
210func (l modulesOrAliases) lastModule() *moduleInfo {
211 for i := range l {
212 if m := l[len(l)-1-i].module(); m != nil {
213 return m
214 }
215 }
216 panic(fmt.Errorf("no last module!"))
217}
218
Colin Crossbbfa51a2014-12-17 16:12:41 -0800219type moduleGroup struct {
Colin Crossed342d92015-03-11 00:57:25 -0700220 name string
221 ninjaName string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700222
Colin Cross5df74a82020-08-24 16:18:21 -0700223 modules modulesOrAliases
Jeff Gastond70bf752017-11-10 15:12:08 -0800224
225 namespace Namespace
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700226}
227
Colin Cross5df74a82020-08-24 16:18:21 -0700228func (group *moduleGroup) moduleOrAliasByVariantName(name string) moduleOrAlias {
229 for _, module := range group.modules {
230 if module.moduleOrAliasVariant().name == name {
231 return module
232 }
233 }
234 return nil
235}
236
237func (group *moduleGroup) moduleByVariantName(name string) *moduleInfo {
238 return group.moduleOrAliasByVariantName(name).module()
239}
240
Colin Crossbbfa51a2014-12-17 16:12:41 -0800241type moduleInfo struct {
Colin Crossed342d92015-03-11 00:57:25 -0700242 // set during Parse
243 typeName string
Colin Crossaf4fd212017-07-28 14:32:36 -0700244 factory ModuleFactory
Colin Crossed342d92015-03-11 00:57:25 -0700245 relBlueprintsFile string
246 pos scanner.Position
247 propertyPos map[string]scanner.Position
Colin Cross322cc012019-05-20 13:55:14 -0700248 createdBy *moduleInfo
Colin Crossed342d92015-03-11 00:57:25 -0700249
Colin Crossedc41762020-08-13 12:07:30 -0700250 variant variant
Colin Crosse7daa222015-03-11 14:35:41 -0700251
Colin Crossd2f4ac12017-07-28 14:31:03 -0700252 logicModule Module
253 group *moduleGroup
254 properties []interface{}
Colin Crossc9028482014-12-18 16:28:54 -0800255
256 // set during ResolveDependencies
Colin Cross99bdb2a2019-03-29 16:35:02 -0700257 missingDeps []string
258 newDirectDeps []depInfo
Colin Crossc9028482014-12-18 16:28:54 -0800259
Colin Cross7addea32015-03-11 15:43:52 -0700260 // set during updateDependencies
261 reverseDeps []*moduleInfo
Colin Cross3702ac72016-08-11 11:09:00 -0700262 forwardDeps []*moduleInfo
Colin Cross99bdb2a2019-03-29 16:35:02 -0700263 directDeps []depInfo
Colin Cross7addea32015-03-11 15:43:52 -0700264
Colin Crossc4773d92020-08-25 17:12:59 -0700265 // used by parallelVisit
Colin Cross7addea32015-03-11 15:43:52 -0700266 waitingCount int
267
Colin Crossc9028482014-12-18 16:28:54 -0800268 // set during each runMutator
Colin Cross5df74a82020-08-24 16:18:21 -0700269 splitModules modulesOrAliases
Colin Crossab6d7902015-03-11 16:17:52 -0700270
271 // set during PrepareBuildActions
272 actionDefs localBuildActions
Colin Cross2da84922020-07-02 10:08:12 -0700273
274 providers []interface{}
275
276 startedMutator *mutatorInfo
277 finishedMutator *mutatorInfo
278
279 startedGenerateBuildActions bool
280 finishedGenerateBuildActions bool
Colin Crossc9028482014-12-18 16:28:54 -0800281}
282
Colin Crossedc41762020-08-13 12:07:30 -0700283type variant struct {
284 name string
285 variations variationMap
286 dependencyVariations variationMap
287}
288
Colin Cross2c1f3d12016-04-11 15:47:28 -0700289type depInfo struct {
290 module *moduleInfo
291 tag DependencyTag
292}
293
Colin Cross0b7e83e2016-05-17 14:58:05 -0700294func (module *moduleInfo) Name() string {
Paul Duffin244033b2020-05-04 11:00:03 +0100295 // If this is called from a LoadHook (which is run before the module has been registered)
296 // then group will not be set and so the name is retrieved from logicModule.Name().
297 // Usually, using that method is not safe as it does not track renames (group.name does).
298 // However, when called from LoadHook it is safe as there is no way to rename a module
299 // until after the LoadHook has run and the module has been registered.
300 if module.group != nil {
301 return module.group.name
302 } else {
303 return module.logicModule.Name()
304 }
Colin Cross0b7e83e2016-05-17 14:58:05 -0700305}
306
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800307func (module *moduleInfo) String() string {
Colin Cross0b7e83e2016-05-17 14:58:05 -0700308 s := fmt.Sprintf("module %q", module.Name())
Colin Crossedc41762020-08-13 12:07:30 -0700309 if module.variant.name != "" {
310 s += fmt.Sprintf(" variant %q", module.variant.name)
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800311 }
Colin Cross322cc012019-05-20 13:55:14 -0700312 if module.createdBy != nil {
313 s += fmt.Sprintf(" (created by %s)", module.createdBy)
314 }
315
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800316 return s
317}
318
Jeff Gastond70bf752017-11-10 15:12:08 -0800319func (module *moduleInfo) namespace() Namespace {
320 return module.group.namespace
321}
322
Colin Crossf5e34b92015-03-13 16:02:36 -0700323// A Variation is a way that a variant of a module differs from other variants of the same module.
324// For example, two variants of the same module might have Variation{"arch","arm"} and
325// Variation{"arch","arm64"}
326type Variation struct {
327 // Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Colin Cross65569e42015-03-10 20:08:19 -0700328 Mutator string
Colin Crossf5e34b92015-03-13 16:02:36 -0700329 // Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
330 // "shared" or "static" for link.
331 Variation string
Colin Cross65569e42015-03-10 20:08:19 -0700332}
333
Colin Crossf5e34b92015-03-13 16:02:36 -0700334// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
335type variationMap map[string]string
Colin Crosse7daa222015-03-11 14:35:41 -0700336
Colin Crossf5e34b92015-03-13 16:02:36 -0700337func (vm variationMap) clone() variationMap {
Colin Cross9403b5a2019-11-13 20:11:04 -0800338 if vm == nil {
339 return nil
340 }
Colin Crossf5e34b92015-03-13 16:02:36 -0700341 newVm := make(variationMap)
Colin Crosse7daa222015-03-11 14:35:41 -0700342 for k, v := range vm {
343 newVm[k] = v
344 }
345
346 return newVm
Colin Crossc9028482014-12-18 16:28:54 -0800347}
348
Colin Cross89486232015-05-08 11:14:54 -0700349// Compare this variationMap to another one. Returns true if the every entry in this map
Colin Cross5dc67592020-08-24 14:46:13 -0700350// exists and has the same value in the other map.
351func (vm variationMap) subsetOf(other variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -0700352 for k, v1 := range vm {
Colin Cross5dc67592020-08-24 14:46:13 -0700353 if v2, ok := other[k]; !ok || v1 != v2 {
Colin Cross89486232015-05-08 11:14:54 -0700354 return false
355 }
356 }
357 return true
358}
359
Colin Crossf5e34b92015-03-13 16:02:36 -0700360func (vm variationMap) equal(other variationMap) bool {
Colin Crosse7daa222015-03-11 14:35:41 -0700361 return reflect.DeepEqual(vm, other)
Colin Crossbbfa51a2014-12-17 16:12:41 -0800362}
363
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700364type singletonInfo struct {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700365 // set during RegisterSingletonType
366 factory SingletonFactory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700367 singleton Singleton
Yuchen Wub9103ef2015-08-25 17:58:17 -0700368 name string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700369
370 // set during PrepareBuildActions
371 actionDefs localBuildActions
372}
373
Colin Crossc9028482014-12-18 16:28:54 -0800374type mutatorInfo struct {
375 // set during RegisterMutator
Colin Crossc0dbc552015-01-02 15:19:28 -0800376 topDownMutator TopDownMutator
377 bottomUpMutator BottomUpMutator
378 name string
Colin Cross49c279a2016-08-05 22:30:44 -0700379 parallel bool
Colin Crossc9028482014-12-18 16:28:54 -0800380}
381
Colin Crossaf4fd212017-07-28 14:32:36 -0700382func newContext() *Context {
383 return &Context{
Colin Cross3a8c0252019-01-23 13:21:48 -0800384 Context: context.Background(),
Colin Cross5f03f112017-11-07 13:29:54 -0800385 moduleFactories: make(map[string]ModuleFactory),
Jeff Gastond70bf752017-11-10 15:12:08 -0800386 nameInterface: NewSimpleNameInterface(),
Colin Cross5f03f112017-11-07 13:29:54 -0800387 moduleInfo: make(map[Module]*moduleInfo),
Colin Cross25236982021-04-05 17:20:34 -0700388 globs: make(map[globKey]pathtools.GlobResult),
Colin Cross5f03f112017-11-07 13:29:54 -0800389 fs: pathtools.OsFs,
Colin Cross2da84922020-07-02 10:08:12 -0700390 finishedMutators: make(map[*mutatorInfo]bool),
Colin Cross5f03f112017-11-07 13:29:54 -0800391 ninjaBuildDir: nil,
392 requiredNinjaMajor: 1,
393 requiredNinjaMinor: 7,
394 requiredNinjaMicro: 0,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700395 }
Colin Crossaf4fd212017-07-28 14:32:36 -0700396}
397
398// NewContext creates a new Context object. The created context initially has
399// no module or singleton factories registered, so the RegisterModuleFactory and
400// RegisterSingletonFactory methods must be called before it can do anything
401// useful.
402func NewContext() *Context {
403 ctx := newContext()
Colin Cross763b6f12015-10-29 15:32:56 -0700404
405 ctx.RegisterBottomUpMutator("blueprint_deps", blueprintDepsMutator)
406
407 return ctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700408}
409
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700410// A ModuleFactory function creates a new Module object. See the
411// Context.RegisterModuleType method for details about how a registered
412// ModuleFactory is used by a Context.
413type ModuleFactory func() (m Module, propertyStructs []interface{})
414
Jamie Gennisd4e10182014-06-12 20:06:50 -0700415// RegisterModuleType associates a module type name (which can appear in a
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700416// Blueprints file) with a Module factory function. When the given module type
417// name is encountered in a Blueprints file during parsing, the Module factory
418// is invoked to instantiate a new Module object to handle the build action
Colin Crossc9028482014-12-18 16:28:54 -0800419// generation for the module. If a Mutator splits a module into multiple variants,
420// the factory is invoked again to create a new Module for each variant.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700421//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700422// The module type names given here must be unique for the context. The factory
423// function should be a named function so that its package and name can be
424// included in the generated Ninja file for debugging purposes.
425//
426// The factory function returns two values. The first is the newly created
427// Module object. The second is a slice of pointers to that Module object's
428// properties structs. Each properties struct is examined when parsing a module
429// definition of this type in a Blueprints file. Exported fields of the
430// properties structs are automatically set to the property values specified in
431// the Blueprints file. The properties struct field names determine the name of
432// the Blueprints file properties that are used - the Blueprints property name
433// matches that of the properties struct field name with the first letter
434// converted to lower-case.
435//
436// The fields of the properties struct must be either []string, a string, or
437// bool. The Context will panic if a Module gets instantiated with a properties
438// struct containing a field that is not one these supported types.
439//
440// Any properties that appear in the Blueprints files that are not built-in
441// module properties (such as "name" and "deps") and do not have a corresponding
442// field in the returned module properties struct result in an error during the
443// Context's parse phase.
444//
445// As an example, the follow code:
446//
447// type myModule struct {
448// properties struct {
449// Foo string
450// Bar []string
451// }
452// }
453//
454// func NewMyModule() (blueprint.Module, []interface{}) {
455// module := new(myModule)
456// properties := &module.properties
457// return module, []interface{}{properties}
458// }
459//
460// func main() {
461// ctx := blueprint.NewContext()
462// ctx.RegisterModuleType("my_module", NewMyModule)
463// // ...
464// }
465//
466// would support parsing a module defined in a Blueprints file as follows:
467//
468// my_module {
469// name: "myName",
470// foo: "my foo string",
471// bar: ["my", "bar", "strings"],
472// }
473//
Colin Cross7ad621c2015-01-07 16:22:45 -0800474// The factory function may be called from multiple goroutines. Any accesses
475// to global variables must be synchronized.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700476func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
477 if _, present := c.moduleFactories[name]; present {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700478 panic(errors.New("module type name is already registered"))
479 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700480 c.moduleFactories[name] = factory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700481}
482
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700483// A SingletonFactory function creates a new Singleton object. See the
484// Context.RegisterSingletonType method for details about how a registered
485// SingletonFactory is used by a Context.
486type SingletonFactory func() Singleton
487
488// RegisterSingletonType registers a singleton type that will be invoked to
489// generate build actions. Each registered singleton type is instantiated and
Yuchen Wub9103ef2015-08-25 17:58:17 -0700490// and invoked exactly once as part of the generate phase. Each registered
491// singleton is invoked in registration order.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700492//
493// The singleton type names given here must be unique for the context. The
494// factory function should be a named function so that its package and name can
495// be included in the generated Ninja file for debugging purposes.
496func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
Yuchen Wub9103ef2015-08-25 17:58:17 -0700497 for _, s := range c.singletonInfo {
498 if s.name == name {
499 panic(errors.New("singleton name is already registered"))
500 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700501 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700502
Yuchen Wub9103ef2015-08-25 17:58:17 -0700503 c.singletonInfo = append(c.singletonInfo, &singletonInfo{
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700504 factory: factory,
505 singleton: factory(),
Yuchen Wub9103ef2015-08-25 17:58:17 -0700506 name: name,
507 })
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700508}
509
Colin Cross5f03f112017-11-07 13:29:54 -0800510// RegisterPreSingletonType registers a presingleton type that will be invoked to
511// generate build actions before any Blueprint files have been read. Each registered
512// presingleton type is instantiated and invoked exactly once at the beginning of the
513// parse phase. Each registered presingleton is invoked in registration order.
514//
515// The presingleton type names given here must be unique for the context. The
516// factory function should be a named function so that its package and name can
517// be included in the generated Ninja file for debugging purposes.
518func (c *Context) RegisterPreSingletonType(name string, factory SingletonFactory) {
519 for _, s := range c.preSingletonInfo {
520 if s.name == name {
521 panic(errors.New("presingleton name is already registered"))
522 }
523 }
524
525 c.preSingletonInfo = append(c.preSingletonInfo, &singletonInfo{
526 factory: factory,
527 singleton: factory(),
528 name: name,
529 })
530}
531
Jeff Gastond70bf752017-11-10 15:12:08 -0800532func (c *Context) SetNameInterface(i NameInterface) {
533 c.nameInterface = i
534}
535
Colin Crossc5fa50e2019-12-17 13:12:35 -0800536func (c *Context) SetSrcDir(path string) {
537 c.srcDir = path
538 c.fs = pathtools.NewOsFs(path)
539}
540
541func (c *Context) SrcDir() string {
542 return c.srcDir
543}
544
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700545func singletonPkgPath(singleton Singleton) string {
546 typ := reflect.TypeOf(singleton)
547 for typ.Kind() == reflect.Ptr {
548 typ = typ.Elem()
549 }
550 return typ.PkgPath()
551}
552
553func singletonTypeName(singleton Singleton) string {
554 typ := reflect.TypeOf(singleton)
555 for typ.Kind() == reflect.Ptr {
556 typ = typ.Elem()
557 }
558 return typ.PkgPath() + "." + typ.Name()
559}
560
Colin Cross3702ac72016-08-11 11:09:00 -0700561// RegisterTopDownMutator registers a mutator that will be invoked to propagate dependency info
562// top-down between Modules. Each registered mutator is invoked in registration order (mixing
563// TopDownMutators and BottomUpMutators) once per Module, and the invocation on any module will
564// have returned before it is in invoked on any of its dependencies.
Colin Crossc9028482014-12-18 16:28:54 -0800565//
Colin Cross65569e42015-03-10 20:08:19 -0700566// The mutator type names given here must be unique to all top down mutators in
567// the Context.
Colin Cross3702ac72016-08-11 11:09:00 -0700568//
569// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
570// parallel while maintaining ordering.
571func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) MutatorHandle {
Colin Crossc9028482014-12-18 16:28:54 -0800572 for _, m := range c.mutatorInfo {
573 if m.name == name && m.topDownMutator != nil {
574 panic(fmt.Errorf("mutator name %s is already registered", name))
575 }
576 }
577
Colin Cross3702ac72016-08-11 11:09:00 -0700578 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800579 topDownMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800580 name: name,
Colin Cross3702ac72016-08-11 11:09:00 -0700581 }
582
583 c.mutatorInfo = append(c.mutatorInfo, info)
584
585 return info
Colin Crossc9028482014-12-18 16:28:54 -0800586}
587
Colin Cross3702ac72016-08-11 11:09:00 -0700588// RegisterBottomUpMutator registers a mutator that will be invoked to split Modules into variants.
589// Each registered mutator is invoked in registration order (mixing TopDownMutators and
590// BottomUpMutators) once per Module, will not be invoked on a module until the invocations on all
591// of the modules dependencies have returned.
Colin Crossc9028482014-12-18 16:28:54 -0800592//
Colin Cross65569e42015-03-10 20:08:19 -0700593// The mutator type names given here must be unique to all bottom up or early
594// mutators in the Context.
Colin Cross49c279a2016-08-05 22:30:44 -0700595//
Colin Cross3702ac72016-08-11 11:09:00 -0700596// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
597// parallel while maintaining ordering.
598func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) MutatorHandle {
Colin Cross65569e42015-03-10 20:08:19 -0700599 for _, m := range c.variantMutatorNames {
600 if m == name {
Colin Crossc9028482014-12-18 16:28:54 -0800601 panic(fmt.Errorf("mutator name %s is already registered", name))
602 }
603 }
604
Colin Cross49c279a2016-08-05 22:30:44 -0700605 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800606 bottomUpMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800607 name: name,
Colin Cross49c279a2016-08-05 22:30:44 -0700608 }
609 c.mutatorInfo = append(c.mutatorInfo, info)
Colin Cross65569e42015-03-10 20:08:19 -0700610
611 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Cross49c279a2016-08-05 22:30:44 -0700612
613 return info
614}
615
Colin Cross3702ac72016-08-11 11:09:00 -0700616type MutatorHandle interface {
617 // Set the mutator to visit modules in parallel while maintaining ordering. Calling any
618 // method on the mutator context is thread-safe, but the mutator must handle synchronization
619 // for any modifications to global state or any modules outside the one it was invoked on.
620 Parallel() MutatorHandle
Colin Cross49c279a2016-08-05 22:30:44 -0700621}
622
Colin Cross3702ac72016-08-11 11:09:00 -0700623func (mutator *mutatorInfo) Parallel() MutatorHandle {
Colin Cross49c279a2016-08-05 22:30:44 -0700624 mutator.parallel = true
625 return mutator
Colin Cross65569e42015-03-10 20:08:19 -0700626}
627
628// RegisterEarlyMutator registers a mutator that will be invoked to split
629// Modules into multiple variant Modules before any dependencies have been
630// created. Each registered mutator is invoked in registration order once
631// per Module (including each variant from previous early mutators). Module
632// order is unpredictable.
633//
634// In order for dependencies to be satisifed in a later pass, all dependencies
Colin Crossf5e34b92015-03-13 16:02:36 -0700635// of a module either must have an identical variant or must have no variations.
Colin Cross65569e42015-03-10 20:08:19 -0700636//
637// The mutator type names given here must be unique to all bottom up or early
638// mutators in the Context.
Colin Cross763b6f12015-10-29 15:32:56 -0700639//
640// Deprecated, use a BottomUpMutator instead. The only difference between
641// EarlyMutator and BottomUpMutator is that EarlyMutator runs before the
642// deprecated DynamicDependencies.
Colin Cross65569e42015-03-10 20:08:19 -0700643func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
644 for _, m := range c.variantMutatorNames {
645 if m == name {
646 panic(fmt.Errorf("mutator name %s is already registered", name))
647 }
648 }
649
Colin Crossf8b50422016-08-10 12:56:40 -0700650 c.earlyMutatorInfo = append(c.earlyMutatorInfo, &mutatorInfo{
651 bottomUpMutator: func(mctx BottomUpMutatorContext) {
652 mutator(mctx)
653 },
654 name: name,
Colin Cross65569e42015-03-10 20:08:19 -0700655 })
656
657 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Crossc9028482014-12-18 16:28:54 -0800658}
659
Jamie Gennisd4e10182014-06-12 20:06:50 -0700660// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
661// where it encounters an unknown module type while parsing Blueprints files. By
662// default, the context will report unknown module types as an error. If this
663// method is called with ignoreUnknownModuleTypes set to true then the context
664// will silently ignore unknown module types.
665//
666// This method should generally not be used. It exists to facilitate the
667// bootstrapping process.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700668func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
669 c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
670}
671
Colin Cross036a1df2015-12-17 15:49:30 -0800672// SetAllowMissingDependencies changes the behavior of Blueprint to ignore
673// unresolved dependencies. If the module's GenerateBuildActions calls
674// ModuleContext.GetMissingDependencies Blueprint will not emit any errors
675// for missing dependencies.
676func (c *Context) SetAllowMissingDependencies(allowMissingDependencies bool) {
677 c.allowMissingDependencies = allowMissingDependencies
678}
679
Jeff Gastonc3e28442017-08-09 15:13:12 -0700680func (c *Context) SetModuleListFile(listFile string) {
681 c.moduleListFile = listFile
682}
683
684func (c *Context) ListModulePaths(baseDir string) (paths []string, err error) {
685 reader, err := c.fs.Open(c.moduleListFile)
686 if err != nil {
687 return nil, err
688 }
689 bytes, err := ioutil.ReadAll(reader)
690 if err != nil {
691 return nil, err
692 }
693 text := string(bytes)
694
695 text = strings.Trim(text, "\n")
696 lines := strings.Split(text, "\n")
697 for i := range lines {
698 lines[i] = filepath.Join(baseDir, lines[i])
699 }
700
701 return lines, nil
702}
703
Jeff Gaston656870f2017-11-29 18:37:31 -0800704// a fileParseContext tells the status of parsing a particular file
705type fileParseContext struct {
706 // name of file
707 fileName string
708
709 // scope to use when resolving variables
710 Scope *parser.Scope
711
712 // pointer to the one in the parent directory
713 parent *fileParseContext
714
715 // is closed once FileHandler has completed for this file
716 doneVisiting chan struct{}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700717}
718
Jamie Gennisd4e10182014-06-12 20:06:50 -0700719// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
720// at rootFile. When it encounters a Blueprints file with a set of subdirs
721// listed it recursively parses any Blueprints files found in those
722// subdirectories.
723//
724// If no errors are encountered while parsing the files, the list of paths on
725// which the future output will depend is returned. This list will include both
726// Blueprints file paths as well as directory paths for cases where wildcard
727// subdirs are found.
Colin Crossda70fd02019-12-30 18:40:09 -0800728func (c *Context) ParseBlueprintsFiles(rootFile string,
729 config interface{}) (deps []string, errs []error) {
730
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800731 baseDir := filepath.Dir(rootFile)
732 pathsToParse, err := c.ListModulePaths(baseDir)
733 if err != nil {
734 return nil, []error{err}
735 }
Colin Crossda70fd02019-12-30 18:40:09 -0800736 return c.ParseFileList(baseDir, pathsToParse, config)
Patrice Arrudab0a40a72019-03-08 13:42:29 -0800737}
738
Colin Crossda70fd02019-12-30 18:40:09 -0800739func (c *Context) ParseFileList(rootDir string, filePaths []string,
740 config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700741
Jeff Gastonc3e28442017-08-09 15:13:12 -0700742 if len(filePaths) < 1 {
743 return nil, []error{fmt.Errorf("no paths provided to parse")}
744 }
745
Colin Cross7ad621c2015-01-07 16:22:45 -0800746 c.dependenciesReady = false
747
Colin Crossda70fd02019-12-30 18:40:09 -0800748 type newModuleInfo struct {
749 *moduleInfo
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 {
1011 if filepath.Base(candidate) == "Blueprints" {
1012 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
1132 subBlueprintsName, _, err := getStringFromScope(scope, "subname")
1133 if err != nil {
1134 errs = append(errs, err)
1135 }
1136
1137 if subBlueprintsName == "" {
1138 subBlueprintsName = "Blueprints"
1139 }
1140
1141 var blueprints []string
1142
1143 newBlueprints, newErrs := c.findBuildBlueprints(filepath.Dir(filename), build, buildPos)
1144 blueprints = append(blueprints, newBlueprints...)
1145 errs = append(errs, newErrs...)
1146
Jeff Gaston656870f2017-11-29 18:37:31 -08001147 subBlueprintsAndScope := make([]fileParseContext, len(blueprints))
Jeff Gastona12f22f2017-08-08 14:45:56 -07001148 for i, b := range blueprints {
Jeff Gaston656870f2017-11-29 18:37:31 -08001149 subBlueprintsAndScope[i] = fileParseContext{b, parser.NewScope(scope), parent, make(chan struct{})}
Jeff Gastona12f22f2017-08-08 14:45:56 -07001150 }
Jeff Gastona12f22f2017-08-08 14:45:56 -07001151 return file, subBlueprintsAndScope, errs
1152}
1153
Colin Cross7f507402015-12-16 13:03:41 -08001154func (c *Context) findBuildBlueprints(dir string, build []string,
Colin Cross127d2ea2016-11-01 11:10:51 -07001155 buildPos scanner.Position) ([]string, []error) {
1156
1157 var blueprints []string
1158 var errs []error
Colin Cross7f507402015-12-16 13:03:41 -08001159
1160 for _, file := range build {
Colin Cross127d2ea2016-11-01 11:10:51 -07001161 pattern := filepath.Join(dir, file)
1162 var matches []string
1163 var err error
1164
Colin Cross08e49542016-11-14 15:23:33 -08001165 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001166
Colin Cross7f507402015-12-16 13:03:41 -08001167 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001168 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001169 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross7f507402015-12-16 13:03:41 -08001170 Pos: buildPos,
1171 })
1172 continue
1173 }
1174
1175 if len(matches) == 0 {
Colin Cross2c628442016-10-07 17:13:10 -07001176 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001177 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross7f507402015-12-16 13:03:41 -08001178 Pos: buildPos,
1179 })
1180 }
1181
Colin Cross7f507402015-12-16 13:03:41 -08001182 for _, foundBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001183 if strings.HasSuffix(foundBlueprints, "/") {
1184 errs = append(errs, &BlueprintError{
1185 Err: fmt.Errorf("%q: is a directory", foundBlueprints),
1186 Pos: buildPos,
1187 })
1188 }
Colin Cross7f507402015-12-16 13:03:41 -08001189 blueprints = append(blueprints, foundBlueprints)
1190 }
1191 }
1192
Colin Cross127d2ea2016-11-01 11:10:51 -07001193 return blueprints, errs
Colin Cross7f507402015-12-16 13:03:41 -08001194}
1195
1196func (c *Context) findSubdirBlueprints(dir string, subdirs []string, subdirsPos scanner.Position,
Colin Cross127d2ea2016-11-01 11:10:51 -07001197 subBlueprintsName string, optional bool) ([]string, []error) {
1198
1199 var blueprints []string
1200 var errs []error
Colin Cross7ad621c2015-01-07 16:22:45 -08001201
1202 for _, subdir := range subdirs {
Colin Cross127d2ea2016-11-01 11:10:51 -07001203 pattern := filepath.Join(dir, subdir, subBlueprintsName)
1204 var matches []string
1205 var err error
1206
Colin Cross08e49542016-11-14 15:23:33 -08001207 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001208
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001209 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001210 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001211 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross1fef5362015-04-20 16:50:54 -07001212 Pos: subdirsPos,
1213 })
1214 continue
1215 }
1216
Colin Cross7f507402015-12-16 13:03:41 -08001217 if len(matches) == 0 && !optional {
Colin Cross2c628442016-10-07 17:13:10 -07001218 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001219 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross1fef5362015-04-20 16:50:54 -07001220 Pos: subdirsPos,
1221 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001222 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001223
Colin Cross127d2ea2016-11-01 11:10:51 -07001224 for _, subBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001225 if strings.HasSuffix(subBlueprints, "/") {
1226 errs = append(errs, &BlueprintError{
1227 Err: fmt.Errorf("%q: is a directory", subBlueprints),
1228 Pos: subdirsPos,
1229 })
1230 }
Colin Cross127d2ea2016-11-01 11:10:51 -07001231 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -08001232 }
1233 }
Colin Cross1fef5362015-04-20 16:50:54 -07001234
Colin Cross127d2ea2016-11-01 11:10:51 -07001235 return blueprints, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001236}
1237
Colin Cross6d8780f2015-07-10 17:51:55 -07001238func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
1239 if assignment, local := scope.Get(v); assignment == nil || !local {
1240 return nil, scanner.Position{}, nil
1241 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001242 switch value := assignment.Value.Eval().(type) {
1243 case *parser.List:
1244 ret := make([]string, 0, len(value.Values))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001245
Colin Crosse32cc802016-06-07 12:28:16 -07001246 for _, listValue := range value.Values {
1247 s, ok := listValue.(*parser.String)
1248 if !ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001249 // The parser should not produce this.
1250 panic("non-string value found in list")
1251 }
1252
Colin Crosse32cc802016-06-07 12:28:16 -07001253 ret = append(ret, s.Value)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001254 }
1255
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001256 return ret, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001257 case *parser.Bool, *parser.String:
Colin Cross2c628442016-10-07 17:13:10 -07001258 return nil, scanner.Position{}, &BlueprintError{
Colin Cross1fef5362015-04-20 16:50:54 -07001259 Err: fmt.Errorf("%q must be a list of strings", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001260 Pos: assignment.EqualsPos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001261 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001262 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001263 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001264 }
1265 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001266}
1267
Colin Cross29394222015-04-27 13:18:21 -07001268func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -07001269 if assignment, _ := scope.Get(v); assignment == nil {
1270 return "", scanner.Position{}, nil
1271 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001272 switch value := assignment.Value.Eval().(type) {
1273 case *parser.String:
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001274 return value.Value, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001275 case *parser.Bool, *parser.List:
Colin Cross2c628442016-10-07 17:13:10 -07001276 return "", scanner.Position{}, &BlueprintError{
Colin Cross29394222015-04-27 13:18:21 -07001277 Err: fmt.Errorf("%q must be a string", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001278 Pos: assignment.EqualsPos,
Colin Cross29394222015-04-27 13:18:21 -07001279 }
1280 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001281 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Colin Cross29394222015-04-27 13:18:21 -07001282 }
1283 }
Colin Cross29394222015-04-27 13:18:21 -07001284}
1285
Colin Cross910242b2016-04-11 15:41:52 -07001286// Clones a build logic module by calling the factory method for its module type, and then cloning
1287// property values. Any values stored in the module object that are not stored in properties
1288// structs will be lost.
1289func (c *Context) cloneLogicModule(origModule *moduleInfo) (Module, []interface{}) {
Colin Crossaf4fd212017-07-28 14:32:36 -07001290 newLogicModule, newProperties := origModule.factory()
Colin Cross910242b2016-04-11 15:41:52 -07001291
Colin Crossd2f4ac12017-07-28 14:31:03 -07001292 if len(newProperties) != len(origModule.properties) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001293 panic("mismatched properties array length in " + origModule.Name())
Colin Cross910242b2016-04-11 15:41:52 -07001294 }
1295
1296 for i := range newProperties {
Colin Cross5d57b2d2020-01-27 16:14:31 -08001297 dst := reflect.ValueOf(newProperties[i])
1298 src := reflect.ValueOf(origModule.properties[i])
Colin Cross910242b2016-04-11 15:41:52 -07001299
1300 proptools.CopyProperties(dst, src)
1301 }
1302
1303 return newLogicModule, newProperties
1304}
1305
Colin Crossedc41762020-08-13 12:07:30 -07001306func newVariant(module *moduleInfo, mutatorName string, variationName string,
1307 local bool) variant {
1308
1309 newVariantName := module.variant.name
1310 if variationName != "" {
1311 if newVariantName == "" {
1312 newVariantName = variationName
1313 } else {
1314 newVariantName += "_" + variationName
1315 }
1316 }
1317
1318 newVariations := module.variant.variations.clone()
1319 if newVariations == nil {
1320 newVariations = make(variationMap)
1321 }
1322 newVariations[mutatorName] = variationName
1323
1324 newDependencyVariations := module.variant.dependencyVariations.clone()
1325 if !local {
1326 if newDependencyVariations == nil {
1327 newDependencyVariations = make(variationMap)
1328 }
1329 newDependencyVariations[mutatorName] = variationName
1330 }
1331
1332 return variant{newVariantName, newVariations, newDependencyVariations}
1333}
1334
Colin Crossf5e34b92015-03-13 16:02:36 -07001335func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
Colin Cross5df74a82020-08-24 16:18:21 -07001336 defaultVariationName *string, variationNames []string, local bool) (modulesOrAliases, []error) {
Colin Crossc9028482014-12-18 16:28:54 -08001337
Colin Crossf4d18a62015-03-18 17:43:15 -07001338 if len(variationNames) == 0 {
1339 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001340 mutatorName, origModule.Name()))
Colin Crossf4d18a62015-03-18 17:43:15 -07001341 }
1342
Colin Cross5df74a82020-08-24 16:18:21 -07001343 var newModules modulesOrAliases
Colin Crossc9028482014-12-18 16:28:54 -08001344
Colin Cross174ae052015-03-03 17:37:03 -08001345 var errs []error
1346
Colin Crossf5e34b92015-03-13 16:02:36 -07001347 for i, variationName := range variationNames {
Colin Crossc9028482014-12-18 16:28:54 -08001348 var newLogicModule Module
1349 var newProperties []interface{}
1350
1351 if i == 0 {
1352 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -07001353 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
1354 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossd2f4ac12017-07-28 14:31:03 -07001355 newLogicModule, newProperties = origModule.logicModule, origModule.properties
Colin Crossc9028482014-12-18 16:28:54 -08001356 } else {
Colin Cross910242b2016-04-11 15:41:52 -07001357 newLogicModule, newProperties = c.cloneLogicModule(origModule)
Colin Crossc9028482014-12-18 16:28:54 -08001358 }
1359
Colin Crossed342d92015-03-11 00:57:25 -07001360 m := *origModule
1361 newModule := &m
Colin Cross2da84922020-07-02 10:08:12 -07001362 newModule.directDeps = append([]depInfo(nil), origModule.directDeps...)
Colin Cross7ff2e8d2021-01-21 22:39:28 -08001363 newModule.reverseDeps = nil
1364 newModule.forwardDeps = nil
Colin Crossed342d92015-03-11 00:57:25 -07001365 newModule.logicModule = newLogicModule
Colin Crossedc41762020-08-13 12:07:30 -07001366 newModule.variant = newVariant(origModule, mutatorName, variationName, local)
Colin Crossd2f4ac12017-07-28 14:31:03 -07001367 newModule.properties = newProperties
Colin Cross2da84922020-07-02 10:08:12 -07001368 newModule.providers = append([]interface{}(nil), origModule.providers...)
Colin Crossc9028482014-12-18 16:28:54 -08001369
1370 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -07001371
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001372 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName, defaultVariationName)
Colin Cross174ae052015-03-03 17:37:03 -08001373 if len(newErrs) > 0 {
1374 errs = append(errs, newErrs...)
1375 }
Colin Crossc9028482014-12-18 16:28:54 -08001376 }
1377
1378 // Mark original variant as invalid. Modules that depend on this module will still
1379 // depend on origModule, but we'll fix it when the mutator is called on them.
1380 origModule.logicModule = nil
1381 origModule.splitModules = newModules
1382
Colin Cross3702ac72016-08-11 11:09:00 -07001383 atomic.AddUint32(&c.depsModified, 1)
1384
Colin Cross174ae052015-03-03 17:37:03 -08001385 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -08001386}
1387
Colin Crossf5e34b92015-03-13 16:02:36 -07001388func (c *Context) convertDepsToVariation(module *moduleInfo,
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001389 mutatorName, variationName string, defaultVariationName *string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -08001390
Colin Crossc9028482014-12-18 16:28:54 -08001391 for i, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001392 if dep.module.logicModule == nil {
Colin Crossc9028482014-12-18 16:28:54 -08001393 var newDep *moduleInfo
Colin Cross2c1f3d12016-04-11 15:47:28 -07001394 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001395 if m.moduleOrAliasVariant().variations[mutatorName] == variationName {
1396 newDep = m.moduleOrAliasTarget()
Colin Crossc9028482014-12-18 16:28:54 -08001397 break
1398 }
1399 }
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001400 if newDep == nil && defaultVariationName != nil {
1401 // give it a second chance; match with defaultVariationName
1402 for _, m := range dep.module.splitModules {
Colin Cross5df74a82020-08-24 16:18:21 -07001403 if m.moduleOrAliasVariant().variations[mutatorName] == *defaultVariationName {
1404 newDep = m.moduleOrAliasTarget()
Jiyong Park1e2e56d2019-07-29 19:59:15 +09001405 break
1406 }
1407 }
1408 }
Colin Crossc9028482014-12-18 16:28:54 -08001409 if newDep == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001410 errs = append(errs, &BlueprintError{
Colin Crossf5e34b92015-03-13 16:02:36 -07001411 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001412 variationName, dep.module.Name(), module.Name()),
Colin Crossed342d92015-03-11 00:57:25 -07001413 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -08001414 })
1415 continue
Colin Crossc9028482014-12-18 16:28:54 -08001416 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001417 module.directDeps[i].module = newDep
Colin Crossc9028482014-12-18 16:28:54 -08001418 }
1419 }
Colin Cross174ae052015-03-03 17:37:03 -08001420
1421 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001422}
1423
Colin Crossedc41762020-08-13 12:07:30 -07001424func (c *Context) prettyPrintVariant(variations variationMap) string {
1425 names := make([]string, 0, len(variations))
Colin Cross65569e42015-03-10 20:08:19 -07001426 for _, m := range c.variantMutatorNames {
Colin Crossedc41762020-08-13 12:07:30 -07001427 if v, ok := variations[m]; ok {
Colin Cross65569e42015-03-10 20:08:19 -07001428 names = append(names, m+":"+v)
1429 }
1430 }
1431
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001432 return strings.Join(names, ",")
Colin Cross65569e42015-03-10 20:08:19 -07001433}
1434
Colin Crossd03b59d2019-11-13 20:10:12 -08001435func (c *Context) prettyPrintGroupVariants(group *moduleGroup) string {
1436 var variants []string
Colin Cross5df74a82020-08-24 16:18:21 -07001437 for _, moduleOrAlias := range group.modules {
1438 if mod := moduleOrAlias.module(); mod != nil {
1439 variants = append(variants, c.prettyPrintVariant(mod.variant.variations))
1440 } else if alias := moduleOrAlias.alias(); alias != nil {
1441 variants = append(variants, c.prettyPrintVariant(alias.variant.variations)+
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001442 " (alias to "+c.prettyPrintVariant(alias.target.variant.variations)+")")
Colin Cross5df74a82020-08-24 16:18:21 -07001443 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001444 }
Colin Crossd03b59d2019-11-13 20:10:12 -08001445 return strings.Join(variants, "\n ")
1446}
1447
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001448func newModule(factory ModuleFactory) *moduleInfo {
Colin Crossaf4fd212017-07-28 14:32:36 -07001449 logicModule, properties := factory()
1450
1451 module := &moduleInfo{
1452 logicModule: logicModule,
1453 factory: factory,
1454 }
1455
1456 module.properties = properties
1457
1458 return module
1459}
1460
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001461func processModuleDef(moduleDef *parser.Module,
1462 relBlueprintsFile string, moduleFactories, scopedModuleFactories map[string]ModuleFactory, ignoreUnknownModuleTypes bool) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001463
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001464 factory, ok := moduleFactories[moduleDef.Type]
Colin Cross9672d862019-12-30 18:38:20 -08001465 if !ok && scopedModuleFactories != nil {
1466 factory, ok = scopedModuleFactories[moduleDef.Type]
1467 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001468 if !ok {
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001469 if ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001470 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001471 }
1472
Colin Cross7ad621c2015-01-07 16:22:45 -08001473 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001474 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001475 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1476 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001477 },
1478 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001479 }
1480
Paul Duffin2a2c58e2020-05-13 09:06:17 +01001481 module := newModule(factory)
Colin Crossaf4fd212017-07-28 14:32:36 -07001482 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001483
Colin Crossaf4fd212017-07-28 14:32:36 -07001484 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001485
Colin Crossf27c5e42020-01-02 09:37:49 -08001486 propertyMap, errs := proptools.UnpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001487 if len(errs) > 0 {
Colin Crossf27c5e42020-01-02 09:37:49 -08001488 for i, err := range errs {
1489 if unpackErr, ok := err.(*proptools.UnpackError); ok {
1490 err = &BlueprintError{
1491 Err: unpackErr.Err,
1492 Pos: unpackErr.Pos,
1493 }
1494 errs[i] = err
1495 }
1496 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001497 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001498 }
1499
Colin Crossc32c4792016-06-09 15:52:30 -07001500 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001501 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001502 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001503 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001504 }
1505
Colin Cross7ad621c2015-01-07 16:22:45 -08001506 return module, nil
1507}
1508
Colin Cross23d7aa12015-06-30 16:05:22 -07001509func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001510 name := module.logicModule.Name()
Jaewoong Jungccc34942018-10-11 13:01:05 -07001511 if name == "" {
1512 return []error{
1513 &BlueprintError{
1514 Err: fmt.Errorf("property 'name' is missing from a module"),
1515 Pos: module.pos,
1516 },
1517 }
1518 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001519 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001520
Colin Cross0b7e83e2016-05-17 14:58:05 -07001521 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001522 name: name,
Colin Cross5df74a82020-08-24 16:18:21 -07001523 modules: modulesOrAliases{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001524 }
1525 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001526 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001527 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001528 ModuleGroup{moduleGroup: group},
1529 module.logicModule)
1530 if len(errs) > 0 {
1531 for i := range errs {
1532 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1533 }
1534 return errs
1535 }
1536 group.namespace = namespace
1537
Colin Cross0b7e83e2016-05-17 14:58:05 -07001538 c.moduleGroups = append(c.moduleGroups, group)
1539
Colin Cross23d7aa12015-06-30 16:05:22 -07001540 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001541}
1542
Jamie Gennisd4e10182014-06-12 20:06:50 -07001543// ResolveDependencies checks that the dependencies specified by all of the
1544// modules defined in the parsed Blueprints files are valid. This means that
1545// the modules depended upon are defined and that no circular dependencies
1546// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001547func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08001548 return c.resolveDependencies(c.Context, config)
1549}
Colin Cross5f03f112017-11-07 13:29:54 -08001550
Colin Cross3a8c0252019-01-23 13:21:48 -08001551func (c *Context) resolveDependencies(ctx context.Context, config interface{}) (deps []string, errs []error) {
1552 pprof.Do(ctx, pprof.Labels("blueprint", "ResolveDependencies"), func(ctx context.Context) {
Colin Cross2da84922020-07-02 10:08:12 -07001553 c.initProviders()
1554
Colin Cross3a8c0252019-01-23 13:21:48 -08001555 c.liveGlobals = newLiveTracker(config)
1556
1557 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1558 if len(errs) > 0 {
1559 return
1560 }
1561
1562 errs = c.updateDependencies()
1563 if len(errs) > 0 {
1564 return
1565 }
1566
1567 var mutatorDeps []string
1568 mutatorDeps, errs = c.runMutators(ctx, config)
1569 if len(errs) > 0 {
1570 return
1571 }
1572 deps = append(deps, mutatorDeps...)
1573
Colin Cross2da84922020-07-02 10:08:12 -07001574 if !c.skipCloneModulesAfterMutators {
1575 c.cloneModules()
1576 }
Colin Cross3a8c0252019-01-23 13:21:48 -08001577
1578 c.dependenciesReady = true
1579 })
1580
Colin Cross5f03f112017-11-07 13:29:54 -08001581 if len(errs) > 0 {
1582 return nil, errs
1583 }
1584
Colin Cross874a3462017-07-31 17:26:06 -07001585 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001586}
1587
Colin Cross763b6f12015-10-29 15:32:56 -07001588// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001589// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001590// module names returned by its DynamicDependencies method and those added by calling
1591// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001592func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001593 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001594 func() {
1595 defer func() {
1596 if r := recover(); r != nil {
1597 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1598 }
1599 }()
1600 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001601
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001602 if ctx.Failed() {
1603 return
1604 }
Colin Cross763b6f12015-10-29 15:32:56 -07001605
Colin Cross2c1f3d12016-04-11 15:47:28 -07001606 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001607 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001608 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001609}
1610
Colin Cross39644c02020-08-21 18:20:38 -07001611// findExactVariantOrSingle searches the moduleGroup for a module with the same variant as module,
1612// and returns the matching module, or nil if one is not found. A group with exactly one module
1613// is always considered matching.
1614func findExactVariantOrSingle(module *moduleInfo, possible *moduleGroup, reverse bool) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07001615 found, _ := findVariant(module, possible, nil, false, reverse)
1616 if found == nil {
1617 for _, moduleOrAlias := range possible.modules {
1618 if m := moduleOrAlias.module(); m != nil {
1619 if found != nil {
1620 // more than one possible match, give up
1621 return nil
1622 }
1623 found = m
1624 }
1625 }
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001626 }
Colin Cross5df74a82020-08-24 16:18:21 -07001627 return found
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001628}
1629
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001630func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) (*moduleInfo, []error) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001631 if _, ok := tag.(BaseDependencyTag); ok {
1632 panic("BaseDependencyTag is not allowed to be used directly!")
1633 }
1634
Colin Cross0b7e83e2016-05-17 14:58:05 -07001635 if depName == module.Name() {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001636 return nil, []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001637 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001638 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001639 }}
1640 }
1641
Colin Crossd03b59d2019-11-13 20:10:12 -08001642 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001643 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001644 return nil, c.discoveredMissingDependencies(module, depName, nil)
Colin Crossc9028482014-12-18 16:28:54 -08001645 }
1646
Colin Cross39644c02020-08-21 18:20:38 -07001647 if m := findExactVariantOrSingle(module, possibleDeps, false); m != nil {
Colin Cross99bdb2a2019-03-29 16:35:02 -07001648 module.newDirectDeps = append(module.newDirectDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001649 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001650 return m, nil
Colin Cross65569e42015-03-10 20:08:19 -07001651 }
Colin Crossc9028482014-12-18 16:28:54 -08001652
Paul Duffinb77556b2020-03-24 19:01:20 +00001653 if c.allowMissingDependencies {
1654 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001655 return nil, c.discoveredMissingDependencies(module, depName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001656 }
1657
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001658 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001659 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001660 depName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001661 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001662 c.prettyPrintGroupVariants(possibleDeps)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001663 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001664 }}
1665}
1666
Colin Cross8d8a7af2015-11-03 16:41:29 -08001667func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001668 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001669 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001670 Err: fmt.Errorf("%q depends on itself", destName),
1671 Pos: module.pos,
1672 }}
1673 }
1674
Colin Crossd03b59d2019-11-13 20:10:12 -08001675 possibleDeps := c.moduleGroupFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001676 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001677 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001678 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001679 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001680 Pos: module.pos,
1681 }}
1682 }
1683
Colin Cross39644c02020-08-21 18:20:38 -07001684 if m := findExactVariantOrSingle(module, possibleDeps, true); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001685 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001686 }
1687
Paul Duffinb77556b2020-03-24 19:01:20 +00001688 if c.allowMissingDependencies {
1689 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001690 return module, c.discoveredMissingDependencies(module, destName, module.variant.dependencyVariations)
Paul Duffinb77556b2020-03-24 19:01:20 +00001691 }
1692
Colin Cross2c628442016-10-07 17:13:10 -07001693 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001694 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001695 destName, module.Name(),
Colin Crossedc41762020-08-13 12:07:30 -07001696 c.prettyPrintVariant(module.variant.dependencyVariations),
Colin Crossd03b59d2019-11-13 20:10:12 -08001697 c.prettyPrintGroupVariants(possibleDeps)),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001698 Pos: module.pos,
1699 }}
1700}
1701
Colin Cross39644c02020-08-21 18:20:38 -07001702func findVariant(module *moduleInfo, possibleDeps *moduleGroup, variations []Variation, far bool, reverse bool) (*moduleInfo, variationMap) {
Colin Crossedc41762020-08-13 12:07:30 -07001703 // We can't just append variant.Variant to module.dependencyVariant.variantName and
Colin Cross65569e42015-03-10 20:08:19 -07001704 // compare the strings because the result won't be in mutator registration order.
1705 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001706 var newVariant variationMap
1707 if !far {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001708 if !reverse {
1709 // For forward dependency, ignore local variants by matching against
1710 // dependencyVariant which doesn't have the local variants
Colin Crossedc41762020-08-13 12:07:30 -07001711 newVariant = module.variant.dependencyVariations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001712 } else {
1713 // For reverse dependency, use all the variants
Colin Crossedc41762020-08-13 12:07:30 -07001714 newVariant = module.variant.variations.clone()
Martin Stjernholm2f212472020-03-06 00:29:24 +00001715 }
Colin Cross89486232015-05-08 11:14:54 -07001716 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001717 for _, v := range variations {
Colin Cross9403b5a2019-11-13 20:11:04 -08001718 if newVariant == nil {
1719 newVariant = make(variationMap)
1720 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001721 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001722 }
1723
Colin Crossd03b59d2019-11-13 20:10:12 -08001724 check := func(variant variationMap) bool {
Colin Cross89486232015-05-08 11:14:54 -07001725 if far {
Colin Cross5dc67592020-08-24 14:46:13 -07001726 return newVariant.subsetOf(variant)
Colin Cross89486232015-05-08 11:14:54 -07001727 } else {
Colin Crossd03b59d2019-11-13 20:10:12 -08001728 return variant.equal(newVariant)
Colin Cross65569e42015-03-10 20:08:19 -07001729 }
1730 }
1731
Colin Crossd03b59d2019-11-13 20:10:12 -08001732 var foundDep *moduleInfo
1733 for _, m := range possibleDeps.modules {
Colin Cross5df74a82020-08-24 16:18:21 -07001734 if check(m.moduleOrAliasVariant().variations) {
1735 foundDep = m.moduleOrAliasTarget()
Colin Crossd03b59d2019-11-13 20:10:12 -08001736 break
1737 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001738 }
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001739
Martin Stjernholm2f212472020-03-06 00:29:24 +00001740 return foundDep, newVariant
1741}
1742
1743func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001744 tag DependencyTag, depName string, far bool) (*moduleInfo, []error) {
Martin Stjernholm2f212472020-03-06 00:29:24 +00001745 if _, ok := tag.(BaseDependencyTag); ok {
1746 panic("BaseDependencyTag is not allowed to be used directly!")
1747 }
1748
1749 possibleDeps := c.moduleGroupFromName(depName, module.namespace())
1750 if possibleDeps == nil {
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001751 return nil, c.discoveredMissingDependencies(module, depName, nil)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001752 }
1753
Colin Cross5df74a82020-08-24 16:18:21 -07001754 foundDep, newVariant := findVariant(module, possibleDeps, variations, far, false)
Martin Stjernholm2f212472020-03-06 00:29:24 +00001755
Colin Crossf7beb892019-11-13 20:11:14 -08001756 if foundDep == nil {
Paul Duffinb77556b2020-03-24 19:01:20 +00001757 if c.allowMissingDependencies {
1758 // Allow missing variants.
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00001759 return nil, c.discoveredMissingDependencies(module, depName, newVariant)
Paul Duffinb77556b2020-03-24 19:01:20 +00001760 }
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001761 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001762 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
1763 depName, module.Name(),
1764 c.prettyPrintVariant(newVariant),
1765 c.prettyPrintGroupVariants(possibleDeps)),
1766 Pos: module.pos,
1767 }}
1768 }
1769
1770 if module == foundDep {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001771 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001772 Err: fmt.Errorf("%q depends on itself", depName),
1773 Pos: module.pos,
1774 }}
1775 }
1776 // AddVariationDependency allows adding a dependency on itself, but only if
1777 // that module is earlier in the module list than this one, since we always
1778 // run GenerateBuildActions in order for the variants of a module
1779 if foundDep.group == module.group && beforeInModuleList(module, foundDep, module.group.modules) {
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001780 return nil, []error{&BlueprintError{
Colin Crossd03b59d2019-11-13 20:10:12 -08001781 Err: fmt.Errorf("%q depends on later version of itself", depName),
1782 Pos: module.pos,
1783 }}
1784 }
1785 module.newDirectDeps = append(module.newDirectDeps, depInfo{foundDep, tag})
1786 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001787 return foundDep, nil
Colin Crossc9028482014-12-18 16:28:54 -08001788}
1789
Colin Crossf1875462016-04-11 17:33:13 -07001790func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001791 from, to Module) *moduleInfo {
Nan Zhang346b2d02017-03-10 16:39:27 -08001792 if _, ok := tag.(BaseDependencyTag); ok {
1793 panic("BaseDependencyTag is not allowed to be used directly!")
1794 }
Colin Crossf1875462016-04-11 17:33:13 -07001795
1796 var fromInfo, toInfo *moduleInfo
Colin Cross5df74a82020-08-24 16:18:21 -07001797 for _, moduleOrAlias := range origModule.splitModules {
1798 if m := moduleOrAlias.module(); m != nil {
1799 if m.logicModule == from {
1800 fromInfo = m
1801 }
1802 if m.logicModule == to {
1803 toInfo = m
1804 if fromInfo != nil {
1805 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
1806 }
Colin Crossf1875462016-04-11 17:33:13 -07001807 }
1808 }
1809 }
1810
1811 if fromInfo == nil || toInfo == nil {
1812 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001813 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001814 }
1815
Colin Cross99bdb2a2019-03-29 16:35:02 -07001816 fromInfo.newDirectDeps = append(fromInfo.newDirectDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001817 atomic.AddUint32(&c.depsModified, 1)
Ulya Trafimovich9577bbc2020-08-27 11:20:23 +01001818 return toInfo
Colin Crossf1875462016-04-11 17:33:13 -07001819}
1820
Jeff Gastonc3e28442017-08-09 15:13:12 -07001821// findBlueprintDescendants returns a map linking parent Blueprints files to child Blueprints files
1822// For example, if paths = []string{"a/b/c/Android.bp", "a/Blueprints"},
1823// then descendants = {"":[]string{"a/Blueprints"}, "a/Blueprints":[]string{"a/b/c/Android.bp"}}
1824func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1825 // make mapping from dir path to file path
1826 filesByDir := make(map[string]string, len(paths))
1827 for _, path := range paths {
1828 dir := filepath.Dir(path)
1829 _, alreadyFound := filesByDir[dir]
1830 if alreadyFound {
1831 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1832 }
1833 filesByDir[dir] = path
1834 }
1835
Jeff Gaston656870f2017-11-29 18:37:31 -08001836 findAncestor := func(childFile string) (ancestor string) {
1837 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001838 for {
1839 ancestorDir := filepath.Dir(prevAncestorDir)
1840 if ancestorDir == prevAncestorDir {
1841 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001842 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001843 }
1844
1845 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1846 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001847 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001848 }
1849 prevAncestorDir = ancestorDir
1850 }
1851 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001852 // generate the descendants map
1853 descendants = make(map[string][]string, len(filesByDir))
1854 for _, childFile := range filesByDir {
1855 ancestorFile := findAncestor(childFile)
1856 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1857 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001858 return descendants, nil
1859}
1860
Colin Cross3702ac72016-08-11 11:09:00 -07001861type visitOrderer interface {
1862 // returns the number of modules that this module needs to wait for
1863 waitCount(module *moduleInfo) int
1864 // returns the list of modules that are waiting for this module
1865 propagate(module *moduleInfo) []*moduleInfo
1866 // visit modules in order
Colin Crossc4773d92020-08-25 17:12:59 -07001867 visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool)
Colin Cross3702ac72016-08-11 11:09:00 -07001868}
1869
Colin Cross7e723372018-03-28 11:50:12 -07001870type unorderedVisitorImpl struct{}
1871
1872func (unorderedVisitorImpl) waitCount(module *moduleInfo) int {
1873 return 0
1874}
1875
1876func (unorderedVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1877 return nil
1878}
1879
Colin Crossc4773d92020-08-25 17:12:59 -07001880func (unorderedVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross7e723372018-03-28 11:50:12 -07001881 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001882 if visit(module, nil) {
Colin Cross7e723372018-03-28 11:50:12 -07001883 return
1884 }
1885 }
1886}
1887
Colin Cross3702ac72016-08-11 11:09:00 -07001888type bottomUpVisitorImpl struct{}
1889
1890func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1891 return len(module.forwardDeps)
1892}
1893
1894func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1895 return module.reverseDeps
1896}
1897
Colin Crossc4773d92020-08-25 17:12:59 -07001898func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001899 for _, module := range modules {
Colin Crossc4773d92020-08-25 17:12:59 -07001900 if visit(module, nil) {
Colin Cross49c279a2016-08-05 22:30:44 -07001901 return
1902 }
1903 }
1904}
1905
Colin Cross3702ac72016-08-11 11:09:00 -07001906type topDownVisitorImpl struct{}
1907
1908func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1909 return len(module.reverseDeps)
1910}
1911
1912func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1913 return module.forwardDeps
1914}
1915
Colin Crossc4773d92020-08-25 17:12:59 -07001916func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo, chan<- pauseSpec) bool) {
Colin Cross3702ac72016-08-11 11:09:00 -07001917 for i := 0; i < len(modules); i++ {
1918 module := modules[len(modules)-1-i]
Colin Crossc4773d92020-08-25 17:12:59 -07001919 if visit(module, nil) {
Colin Cross3702ac72016-08-11 11:09:00 -07001920 return
1921 }
1922 }
1923}
1924
1925var (
1926 bottomUpVisitor bottomUpVisitorImpl
1927 topDownVisitor topDownVisitorImpl
1928)
1929
Colin Crossc4773d92020-08-25 17:12:59 -07001930// pauseSpec describes a pause that a module needs to occur until another module has been visited,
1931// at which point the unpause channel will be closed.
1932type pauseSpec struct {
1933 paused *moduleInfo
1934 until *moduleInfo
1935 unpause unpause
1936}
1937
1938type unpause chan struct{}
1939
1940const parallelVisitLimit = 1000
1941
Colin Cross49c279a2016-08-05 22:30:44 -07001942// 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 -07001943// of its dependencies has finished. A visit function can write a pauseSpec to the pause channel
1944// to wait for another dependency to be visited. If a visit function returns true to cancel
1945// while another visitor is paused, the paused visitor will never be resumed and its goroutine
1946// will stay paused forever.
1947func parallelVisit(modules []*moduleInfo, order visitOrderer, limit int,
1948 visit func(module *moduleInfo, pause chan<- pauseSpec) bool) []error {
1949
Colin Cross7addea32015-03-11 15:43:52 -07001950 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001951 cancelCh := make(chan bool)
Colin Crossc4773d92020-08-25 17:12:59 -07001952 pauseCh := make(chan pauseSpec)
Colin Cross8900e9b2015-03-02 14:03:01 -08001953 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001954
Colin Crossc4773d92020-08-25 17:12:59 -07001955 var backlog []*moduleInfo // Visitors that are ready to start but backlogged due to limit.
1956 var unpauseBacklog []pauseSpec // Visitors that are ready to unpause but backlogged due to limit.
1957
1958 active := 0 // Number of visitors running, not counting paused visitors.
1959 visited := 0 // Number of finished visitors.
1960
1961 pauseMap := make(map[*moduleInfo][]pauseSpec)
1962
1963 for _, module := range modules {
Colin Cross3702ac72016-08-11 11:09:00 -07001964 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001965 }
1966
Colin Crossc4773d92020-08-25 17:12:59 -07001967 // Call the visitor on a module if there are fewer active visitors than the parallelism
1968 // limit, otherwise add it to the backlog.
1969 startOrBacklog := func(module *moduleInfo) {
1970 if active < limit {
1971 active++
Colin Cross7e723372018-03-28 11:50:12 -07001972 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07001973 ret := visit(module, pauseCh)
Colin Cross7e723372018-03-28 11:50:12 -07001974 if ret {
1975 cancelCh <- true
1976 }
1977 doneCh <- module
1978 }()
1979 } else {
1980 backlog = append(backlog, module)
1981 }
Colin Cross691a60d2015-01-07 18:08:56 -08001982 }
1983
Colin Crossc4773d92020-08-25 17:12:59 -07001984 // Unpause the already-started but paused visitor on a module if there are fewer active
1985 // visitors than the parallelism limit, otherwise add it to the backlog.
1986 unpauseOrBacklog := func(pauseSpec pauseSpec) {
1987 if active < limit {
1988 active++
1989 close(pauseSpec.unpause)
1990 } else {
1991 unpauseBacklog = append(unpauseBacklog, pauseSpec)
Colin Cross691a60d2015-01-07 18:08:56 -08001992 }
1993 }
1994
Colin Crossc4773d92020-08-25 17:12:59 -07001995 // Start any modules in the backlog up to the parallelism limit. Unpause paused modules first
1996 // since they may already be holding resources.
1997 unpauseOrStartFromBacklog := func() {
1998 for active < limit && len(unpauseBacklog) > 0 {
1999 unpause := unpauseBacklog[0]
2000 unpauseBacklog = unpauseBacklog[1:]
2001 unpauseOrBacklog(unpause)
2002 }
2003 for active < limit && len(backlog) > 0 {
2004 toVisit := backlog[0]
2005 backlog = backlog[1:]
2006 startOrBacklog(toVisit)
2007 }
2008 }
2009
2010 toVisit := len(modules)
2011
2012 // Start or backlog any modules that are not waiting for any other modules.
2013 for _, module := range modules {
2014 if module.waitingCount == 0 {
2015 startOrBacklog(module)
2016 }
2017 }
2018
2019 for active > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08002020 select {
Colin Cross7e723372018-03-28 11:50:12 -07002021 case <-cancelCh:
2022 cancel = true
2023 backlog = nil
Colin Cross7addea32015-03-11 15:43:52 -07002024 case doneModule := <-doneCh:
Colin Crossc4773d92020-08-25 17:12:59 -07002025 active--
Colin Cross8900e9b2015-03-02 14:03:01 -08002026 if !cancel {
Colin Crossc4773d92020-08-25 17:12:59 -07002027 // Mark this module as done.
2028 doneModule.waitingCount = -1
2029 visited++
2030
2031 // Unpause or backlog any modules that were waiting for this one.
2032 if unpauses, ok := pauseMap[doneModule]; ok {
2033 delete(pauseMap, doneModule)
2034 for _, unpause := range unpauses {
2035 unpauseOrBacklog(unpause)
2036 }
Colin Cross7e723372018-03-28 11:50:12 -07002037 }
Colin Crossc4773d92020-08-25 17:12:59 -07002038
2039 // Start any backlogged modules up to limit.
2040 unpauseOrStartFromBacklog()
2041
2042 // Decrement waitingCount on the next modules in the tree based
2043 // on propagation order, and start or backlog them if they are
2044 // ready to start.
Colin Cross3702ac72016-08-11 11:09:00 -07002045 for _, module := range order.propagate(doneModule) {
2046 module.waitingCount--
2047 if module.waitingCount == 0 {
Colin Crossc4773d92020-08-25 17:12:59 -07002048 startOrBacklog(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08002049 }
Colin Cross691a60d2015-01-07 18:08:56 -08002050 }
2051 }
Colin Crossc4773d92020-08-25 17:12:59 -07002052 case pauseSpec := <-pauseCh:
2053 if pauseSpec.until.waitingCount == -1 {
2054 // Module being paused for is already finished, resume immediately.
2055 close(pauseSpec.unpause)
2056 } else {
2057 // Register for unpausing.
2058 pauseMap[pauseSpec.until] = append(pauseMap[pauseSpec.until], pauseSpec)
2059
2060 // Don't count paused visitors as active so that this can't deadlock
2061 // if 1000 visitors are paused simultaneously.
2062 active--
2063 unpauseOrStartFromBacklog()
2064 }
Colin Cross691a60d2015-01-07 18:08:56 -08002065 }
2066 }
Colin Crossc4773d92020-08-25 17:12:59 -07002067
2068 if !cancel {
2069 // Invariant check: no backlogged modules, these weren't waiting on anything except
2070 // the parallelism limit so they should have run.
2071 if len(backlog) > 0 {
2072 panic(fmt.Errorf("parallelVisit finished with %d backlogged visitors", len(backlog)))
2073 }
2074
2075 // Invariant check: no backlogged paused modules, these weren't waiting on anything
2076 // except the parallelism limit so they should have run.
2077 if len(unpauseBacklog) > 0 {
2078 panic(fmt.Errorf("parallelVisit finished with %d backlogged unpaused visitors", len(unpauseBacklog)))
2079 }
2080
2081 if len(pauseMap) > 0 {
Colin Cross7d4958d2021-02-08 15:34:08 -08002082 // Probably a deadlock due to a newly added dependency cycle. Start from each module in
2083 // the order of the input modules list and perform a depth-first search for the module
2084 // it is paused on, ignoring modules that are marked as done. Note this traverses from
2085 // modules to the modules that would have been unblocked when that module finished, i.e
2086 // the reverse of the visitOrderer.
Colin Crossc4773d92020-08-25 17:12:59 -07002087
Colin Cross9793b0a2021-04-27 15:20:15 -07002088 // In order to reduce duplicated work, once a module has been checked and determined
2089 // not to be part of a cycle add it and everything that depends on it to the checked
2090 // map.
2091 checked := make(map[*moduleInfo]struct{})
2092
Colin Cross7d4958d2021-02-08 15:34:08 -08002093 var check func(module, end *moduleInfo) []*moduleInfo
2094 check = func(module, end *moduleInfo) []*moduleInfo {
Colin Crossc4773d92020-08-25 17:12:59 -07002095 if module.waitingCount == -1 {
2096 // This module was finished, it can't be part of a loop.
2097 return nil
2098 }
2099 if module == end {
2100 // This module is the end of the loop, start rolling up the cycle.
2101 return []*moduleInfo{module}
2102 }
2103
Colin Cross9793b0a2021-04-27 15:20:15 -07002104 if _, alreadyChecked := checked[module]; alreadyChecked {
2105 return nil
2106 }
2107
Colin Crossc4773d92020-08-25 17:12:59 -07002108 for _, dep := range order.propagate(module) {
Colin Cross7d4958d2021-02-08 15:34:08 -08002109 cycle := check(dep, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002110 if cycle != nil {
2111 return append([]*moduleInfo{module}, cycle...)
2112 }
2113 }
2114 for _, depPauseSpec := range pauseMap[module] {
Colin Cross7d4958d2021-02-08 15:34:08 -08002115 cycle := check(depPauseSpec.paused, end)
Colin Crossc4773d92020-08-25 17:12:59 -07002116 if cycle != nil {
2117 return append([]*moduleInfo{module}, cycle...)
2118 }
2119 }
2120
Colin Cross9793b0a2021-04-27 15:20:15 -07002121 checked[module] = struct{}{}
Colin Crossc4773d92020-08-25 17:12:59 -07002122 return nil
2123 }
2124
Colin Cross7d4958d2021-02-08 15:34:08 -08002125 // Iterate over the modules list instead of pauseMap to provide deterministic ordering.
2126 for _, module := range modules {
2127 for _, pauseSpec := range pauseMap[module] {
2128 cycle := check(pauseSpec.paused, pauseSpec.until)
2129 if len(cycle) > 0 {
2130 return cycleError(cycle)
2131 }
2132 }
Colin Crossc4773d92020-08-25 17:12:59 -07002133 }
2134 }
2135
2136 // Invariant check: if there was no deadlock and no cancellation every module
2137 // should have been visited.
2138 if visited != toVisit {
2139 panic(fmt.Errorf("parallelVisit ran %d visitors, expected %d", visited, toVisit))
2140 }
2141
2142 // Invariant check: if there was no deadlock and no cancellation every module
2143 // should have been visited, so there is nothing left to be paused on.
2144 if len(pauseMap) > 0 {
2145 panic(fmt.Errorf("parallelVisit finished with %d paused visitors", len(pauseMap)))
2146 }
2147 }
2148
2149 return nil
2150}
2151
2152func cycleError(cycle []*moduleInfo) (errs []error) {
2153 // The cycle list is in reverse order because all the 'check' calls append
2154 // their own module to the list.
2155 errs = append(errs, &BlueprintError{
2156 Err: fmt.Errorf("encountered dependency cycle:"),
2157 Pos: cycle[len(cycle)-1].pos,
2158 })
2159
2160 // Iterate backwards through the cycle list.
2161 curModule := cycle[0]
2162 for i := len(cycle) - 1; i >= 0; i-- {
2163 nextModule := cycle[i]
2164 errs = append(errs, &BlueprintError{
Colin Crosse5ff7702021-04-27 15:33:49 -07002165 Err: fmt.Errorf(" %s depends on %s",
2166 curModule, nextModule),
Colin Crossc4773d92020-08-25 17:12:59 -07002167 Pos: curModule.pos,
2168 })
2169 curModule = nextModule
2170 }
2171
2172 return errs
Colin Cross691a60d2015-01-07 18:08:56 -08002173}
2174
2175// updateDependencies recursively walks the module dependency graph and updates
2176// additional fields based on the dependencies. It builds a sorted list of modules
2177// such that dependencies of a module always appear first, and populates reverse
2178// dependency links and counts of total dependencies. It also reports errors when
2179// it encounters dependency cycles. This should called after resolveDependencies,
2180// as well as after any mutator pass has called addDependency
2181func (c *Context) updateDependencies() (errs []error) {
Liz Kammer9ae14f12020-11-30 16:30:45 -07002182 c.cachedDepsModified = true
Colin Cross7addea32015-03-11 15:43:52 -07002183 visited := make(map[*moduleInfo]bool) // modules that were already checked
2184 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002185
Colin Cross7addea32015-03-11 15:43:52 -07002186 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08002187
Colin Cross7addea32015-03-11 15:43:52 -07002188 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002189
Colin Cross7addea32015-03-11 15:43:52 -07002190 check = func(module *moduleInfo) []*moduleInfo {
2191 visited[module] = true
2192 checking[module] = true
2193 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002194
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002195 // Reset the forward and reverse deps without reducing their capacity to avoid reallocation.
2196 module.reverseDeps = module.reverseDeps[:0]
2197 module.forwardDeps = module.forwardDeps[:0]
Colin Cross7addea32015-03-11 15:43:52 -07002198
2199 // Add an implicit dependency ordering on all earlier modules in the same module group
2200 for _, dep := range module.group.modules {
2201 if dep == module {
2202 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08002203 }
Colin Cross5df74a82020-08-24 16:18:21 -07002204 if depModule := dep.module(); depModule != nil {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002205 module.forwardDeps = append(module.forwardDeps, depModule)
Colin Cross5df74a82020-08-24 16:18:21 -07002206 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08002207 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002208
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002209 outer:
Colin Cross7addea32015-03-11 15:43:52 -07002210 for _, dep := range module.directDeps {
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002211 // use a loop to check for duplicates, average number of directDeps measured to be 9.5.
2212 for _, exists := range module.forwardDeps {
2213 if dep.module == exists {
2214 continue outer
2215 }
2216 }
2217 module.forwardDeps = append(module.forwardDeps, dep.module)
Colin Cross7addea32015-03-11 15:43:52 -07002218 }
2219
Colin Cross7ff2e8d2021-01-21 22:39:28 -08002220 for _, dep := range module.forwardDeps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002221 if checking[dep] {
2222 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07002223 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002224 }
2225
2226 if !visited[dep] {
2227 cycle := check(dep)
2228 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002229 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002230 // We are the "start" of the cycle, so we're responsible
Colin Crossc4773d92020-08-25 17:12:59 -07002231 // for generating the errors.
2232 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002233
2234 // We can continue processing this module's children to
2235 // find more cycles. Since all the modules that were
2236 // part of the found cycle were marked as visited we
2237 // won't run into that cycle again.
2238 } else {
2239 // We're not the "start" of the cycle, so we just append
2240 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07002241 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002242 }
2243 }
2244 }
Colin Cross691a60d2015-01-07 18:08:56 -08002245
Colin Cross7addea32015-03-11 15:43:52 -07002246 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002247 }
2248
Colin Cross7addea32015-03-11 15:43:52 -07002249 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08002250
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002251 return nil
2252 }
2253
Colin Cross7addea32015-03-11 15:43:52 -07002254 for _, module := range c.moduleInfo {
2255 if !visited[module] {
2256 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002257 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07002258 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07002259 panic("inconceivable!")
2260 }
Colin Crossc4773d92020-08-25 17:12:59 -07002261 errs = append(errs, cycleError(cycle)...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002262 }
2263 }
2264 }
2265
Colin Cross7addea32015-03-11 15:43:52 -07002266 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08002267
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002268 return
2269}
2270
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002271type jsonVariationMap map[string]string
2272
2273type jsonModuleName struct {
2274 Name string
2275 Variations jsonVariationMap
2276 DependencyVariations jsonVariationMap
2277}
2278
2279type jsonDep struct {
2280 jsonModuleName
2281 Tag string
2282}
2283
Lukacs T. Berki16022262021-06-25 09:10:56 +02002284type JsonModule struct {
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002285 jsonModuleName
2286 Deps []jsonDep
2287 Type string
2288 Blueprint string
Lukacs T. Berki16022262021-06-25 09:10:56 +02002289 Module map[string]interface{}
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002290}
2291
2292func toJsonVariationMap(vm variationMap) jsonVariationMap {
2293 return jsonVariationMap(vm)
2294}
2295
2296func jsonModuleNameFromModuleInfo(m *moduleInfo) *jsonModuleName {
2297 return &jsonModuleName{
2298 Name: m.Name(),
2299 Variations: toJsonVariationMap(m.variant.variations),
2300 DependencyVariations: toJsonVariationMap(m.variant.dependencyVariations),
2301 }
2302}
2303
Lukacs T. Berki16022262021-06-25 09:10:56 +02002304type JSONDataSupplier interface {
2305 AddJSONData(d *map[string]interface{})
2306}
2307
2308func jsonModuleFromModuleInfo(m *moduleInfo) *JsonModule {
2309 result := &JsonModule{
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002310 jsonModuleName: *jsonModuleNameFromModuleInfo(m),
2311 Deps: make([]jsonDep, 0),
2312 Type: m.typeName,
2313 Blueprint: m.relBlueprintsFile,
Lukacs T. Berki16022262021-06-25 09:10:56 +02002314 Module: make(map[string]interface{}),
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002315 }
Lukacs T. Berki16022262021-06-25 09:10:56 +02002316
2317 if j, ok := m.logicModule.(JSONDataSupplier); ok {
2318 j.AddJSONData(&result.Module)
2319 }
2320
2321 for _, p := range m.providers {
2322 if j, ok := p.(JSONDataSupplier); ok {
2323 j.AddJSONData(&result.Module)
2324 }
2325 }
2326 return result
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002327}
2328
2329func (c *Context) PrintJSONGraph(w io.Writer) {
Lukacs T. Berki16022262021-06-25 09:10:56 +02002330 modules := make([]*JsonModule, 0)
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002331 for _, m := range c.modulesSorted {
2332 jm := jsonModuleFromModuleInfo(m)
2333 for _, d := range m.directDeps {
2334 jm.Deps = append(jm.Deps, jsonDep{
2335 jsonModuleName: *jsonModuleNameFromModuleInfo(d.module),
2336 Tag: fmt.Sprintf("%T %+v", d.tag, d.tag),
2337 })
2338 }
2339
2340 modules = append(modules, jm)
2341 }
2342
2343 json.NewEncoder(w).Encode(modules)
2344}
2345
Jamie Gennisd4e10182014-06-12 20:06:50 -07002346// PrepareBuildActions generates an internal representation of all the build
2347// actions that need to be performed. This process involves invoking the
2348// GenerateBuildActions method on each of the Module objects created during the
2349// parse phase and then on each of the registered Singleton objects.
2350//
2351// If the ResolveDependencies method has not already been called it is called
2352// automatically by this method.
2353//
2354// The config argument is made available to all of the Module and Singleton
2355// objects via the Config method on the ModuleContext and SingletonContext
2356// objects passed to GenerateBuildActions. It is also passed to the functions
2357// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
2358// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002359//
2360// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08002361// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
2362// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
2363// methods.
Lukacs T. Berki6f682822021-04-01 18:27:31 +02002364
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002365func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Colin Cross3a8c0252019-01-23 13:21:48 -08002366 pprof.Do(c.Context, pprof.Labels("blueprint", "PrepareBuildActions"), func(ctx context.Context) {
2367 c.buildActionsReady = false
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002368
Colin Cross3a8c0252019-01-23 13:21:48 -08002369 if !c.dependenciesReady {
2370 var extraDeps []string
2371 extraDeps, errs = c.resolveDependencies(ctx, config)
2372 if len(errs) > 0 {
2373 return
2374 }
2375 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002376 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002377
Colin Cross3a8c0252019-01-23 13:21:48 -08002378 var depsModules []string
2379 depsModules, errs = c.generateModuleBuildActions(config, c.liveGlobals)
2380 if len(errs) > 0 {
2381 return
2382 }
2383
2384 var depsSingletons []string
2385 depsSingletons, errs = c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
2386 if len(errs) > 0 {
2387 return
2388 }
2389
2390 deps = append(deps, depsModules...)
2391 deps = append(deps, depsSingletons...)
2392
2393 if c.ninjaBuildDir != nil {
2394 err := c.liveGlobals.addNinjaStringDeps(c.ninjaBuildDir)
2395 if err != nil {
2396 errs = []error{err}
2397 return
2398 }
2399 }
2400
2401 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
2402
2403 deps = append(deps, depsPackages...)
2404
Colin Cross92054a42021-01-21 16:49:25 -08002405 c.memoizeFullNames(c.liveGlobals, pkgNames)
2406
Colin Cross3a8c0252019-01-23 13:21:48 -08002407 // This will panic if it finds a problem since it's a programming error.
2408 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
2409
2410 c.pkgNames = pkgNames
2411 c.globalVariables = c.liveGlobals.variables
2412 c.globalPools = c.liveGlobals.pools
2413 c.globalRules = c.liveGlobals.rules
2414
2415 c.buildActionsReady = true
2416 })
2417
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002418 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002419 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002420 }
2421
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002422 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002423}
2424
Colin Cross3a8c0252019-01-23 13:21:48 -08002425func (c *Context) runMutators(ctx context.Context, config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07002426 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07002427
Colin Cross3a8c0252019-01-23 13:21:48 -08002428 pprof.Do(ctx, pprof.Labels("blueprint", "runMutators"), func(ctx context.Context) {
2429 mutators = append(mutators, c.earlyMutatorInfo...)
2430 mutators = append(mutators, c.mutatorInfo...)
Colin Crossf8b50422016-08-10 12:56:40 -07002431
Colin Cross3a8c0252019-01-23 13:21:48 -08002432 for _, mutator := range mutators {
2433 pprof.Do(ctx, pprof.Labels("mutator", mutator.name), func(context.Context) {
2434 var newDeps []string
2435 if mutator.topDownMutator != nil {
2436 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
2437 } else if mutator.bottomUpMutator != nil {
2438 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
2439 } else {
2440 panic("no mutator set on " + mutator.name)
2441 }
2442 if len(errs) > 0 {
2443 return
2444 }
2445 deps = append(deps, newDeps...)
2446 })
2447 if len(errs) > 0 {
2448 return
2449 }
Colin Crossc9028482014-12-18 16:28:54 -08002450 }
Colin Cross3a8c0252019-01-23 13:21:48 -08002451 })
2452
2453 if len(errs) > 0 {
2454 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08002455 }
2456
Colin Cross874a3462017-07-31 17:26:06 -07002457 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08002458}
2459
Colin Cross3702ac72016-08-11 11:09:00 -07002460type mutatorDirection interface {
2461 run(mutator *mutatorInfo, ctx *mutatorContext)
2462 orderer() visitOrderer
2463 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08002464}
2465
Colin Cross3702ac72016-08-11 11:09:00 -07002466type bottomUpMutatorImpl struct{}
2467
2468func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2469 mutator.bottomUpMutator(ctx)
2470}
2471
2472func (bottomUpMutatorImpl) orderer() visitOrderer {
2473 return bottomUpVisitor
2474}
2475
2476func (bottomUpMutatorImpl) String() string {
2477 return "bottom up mutator"
2478}
2479
2480type topDownMutatorImpl struct{}
2481
2482func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
2483 mutator.topDownMutator(ctx)
2484}
2485
2486func (topDownMutatorImpl) orderer() visitOrderer {
2487 return topDownVisitor
2488}
2489
2490func (topDownMutatorImpl) String() string {
2491 return "top down mutator"
2492}
2493
2494var (
2495 topDownMutator topDownMutatorImpl
2496 bottomUpMutator bottomUpMutatorImpl
2497)
2498
Colin Cross49c279a2016-08-05 22:30:44 -07002499type reverseDep struct {
2500 module *moduleInfo
2501 dep depInfo
2502}
2503
Colin Cross3702ac72016-08-11 11:09:00 -07002504func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07002505 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07002506
2507 newModuleInfo := make(map[Module]*moduleInfo)
2508 for k, v := range c.moduleInfo {
2509 newModuleInfo[k] = v
2510 }
Colin Crossc9028482014-12-18 16:28:54 -08002511
Colin Cross0ce142c2016-12-09 10:29:05 -08002512 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07002513 reverse []reverseDep
2514 rename []rename
2515 replace []replace
2516 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07002517 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08002518 }
2519
Colin Cross2c1f3d12016-04-11 15:47:28 -07002520 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08002521 var rename []rename
2522 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07002523 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08002524
Colin Cross49c279a2016-08-05 22:30:44 -07002525 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08002526 globalStateCh := make(chan globalStateChange)
Colin Cross5df74a82020-08-24 16:18:21 -07002527 newVariationsCh := make(chan modulesOrAliases)
Colin Cross49c279a2016-08-05 22:30:44 -07002528 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08002529
Colin Cross3702ac72016-08-11 11:09:00 -07002530 c.depsModified = 0
2531
Colin Crossc4773d92020-08-25 17:12:59 -07002532 visit := func(module *moduleInfo, pause chan<- pauseSpec) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04002533 if module.splitModules != nil {
2534 panic("split module found in sorted module list")
2535 }
2536
Colin Cross7addea32015-03-11 15:43:52 -07002537 mctx := &mutatorContext{
2538 baseModuleContext: baseModuleContext{
2539 context: c,
2540 config: config,
2541 module: module,
2542 },
Colin Crossc4773d92020-08-25 17:12:59 -07002543 name: mutator.name,
2544 pauseCh: pause,
Colin Cross7addea32015-03-11 15:43:52 -07002545 }
Colin Crossc9028482014-12-18 16:28:54 -08002546
Colin Cross2da84922020-07-02 10:08:12 -07002547 module.startedMutator = mutator
2548
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002549 func() {
2550 defer func() {
2551 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07002552 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002553 if err, ok := r.(panicError); ok {
2554 err.addIn(in)
2555 mctx.error(err)
2556 } else {
2557 mctx.error(newPanicErrorf(r, in))
2558 }
2559 }
2560 }()
Colin Cross3702ac72016-08-11 11:09:00 -07002561 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002562 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002563
Colin Cross2da84922020-07-02 10:08:12 -07002564 module.finishedMutator = mutator
2565
Colin Cross7addea32015-03-11 15:43:52 -07002566 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002567 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002568 return true
Colin Cross7addea32015-03-11 15:43:52 -07002569 }
Colin Crossc9028482014-12-18 16:28:54 -08002570
Colin Cross5fe225f2017-07-28 15:22:46 -07002571 if len(mctx.newVariations) > 0 {
2572 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002573 }
2574
Colin Crossab0a83f2020-03-03 14:23:27 -08002575 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 -08002576 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002577 reverse: mctx.reverseDeps,
2578 replace: mctx.replace,
2579 rename: mctx.rename,
2580 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002581 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002582 }
Colin Cross49c279a2016-08-05 22:30:44 -07002583 }
2584
2585 return false
2586 }
2587
2588 // Process errs and reverseDeps in a single goroutine
2589 go func() {
2590 for {
2591 select {
2592 case newErrs := <-errsCh:
2593 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002594 case globalStateChange := <-globalStateCh:
2595 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002596 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2597 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002598 replace = append(replace, globalStateChange.replace...)
2599 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002600 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002601 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002602 case newVariations := <-newVariationsCh:
Colin Cross5df74a82020-08-24 16:18:21 -07002603 for _, moduleOrAlias := range newVariations {
2604 if m := moduleOrAlias.module(); m != nil {
2605 newModuleInfo[m.logicModule] = m
2606 }
Colin Cross49c279a2016-08-05 22:30:44 -07002607 }
2608 case <-done:
2609 return
Colin Crossc9028482014-12-18 16:28:54 -08002610 }
2611 }
Colin Cross49c279a2016-08-05 22:30:44 -07002612 }()
Colin Crossc9028482014-12-18 16:28:54 -08002613
Colin Cross2da84922020-07-02 10:08:12 -07002614 c.startedMutator = mutator
2615
Colin Crossc4773d92020-08-25 17:12:59 -07002616 var visitErrs []error
Colin Cross49c279a2016-08-05 22:30:44 -07002617 if mutator.parallel {
Colin Crossc4773d92020-08-25 17:12:59 -07002618 visitErrs = parallelVisit(c.modulesSorted, direction.orderer(), parallelVisitLimit, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002619 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002620 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002621 }
2622
Colin Crossc4773d92020-08-25 17:12:59 -07002623 if len(visitErrs) > 0 {
2624 return nil, visitErrs
2625 }
2626
Colin Cross2da84922020-07-02 10:08:12 -07002627 c.finishedMutators[mutator] = true
2628
Colin Cross49c279a2016-08-05 22:30:44 -07002629 done <- true
2630
2631 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002632 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002633 }
2634
2635 c.moduleInfo = newModuleInfo
2636
2637 for _, group := range c.moduleGroups {
2638 for i := 0; i < len(group.modules); i++ {
Colin Cross5df74a82020-08-24 16:18:21 -07002639 module := group.modules[i].module()
2640 if module == nil {
2641 // Existing alias, skip it
2642 continue
2643 }
Colin Cross49c279a2016-08-05 22:30:44 -07002644
2645 // Update module group to contain newly split variants
2646 if module.splitModules != nil {
2647 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2648 }
2649
2650 // Fix up any remaining dependencies on modules that were split into variants
2651 // by replacing them with the first variant
2652 for j, dep := range module.directDeps {
2653 if dep.module.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002654 module.directDeps[j].module = dep.module.splitModules.firstModule()
Colin Cross49c279a2016-08-05 22:30:44 -07002655 }
2656 }
Colin Cross99bdb2a2019-03-29 16:35:02 -07002657
Colin Cross322cc012019-05-20 13:55:14 -07002658 if module.createdBy != nil && module.createdBy.logicModule == nil {
Colin Cross5df74a82020-08-24 16:18:21 -07002659 module.createdBy = module.createdBy.splitModules.firstModule()
Colin Cross322cc012019-05-20 13:55:14 -07002660 }
2661
Colin Cross99bdb2a2019-03-29 16:35:02 -07002662 // Add in any new direct dependencies that were added by the mutator
2663 module.directDeps = append(module.directDeps, module.newDirectDeps...)
2664 module.newDirectDeps = nil
Colin Cross7addea32015-03-11 15:43:52 -07002665 }
Colin Crossf7beb892019-11-13 20:11:14 -08002666
Colin Cross279489c2020-08-13 12:11:52 -07002667 findAliasTarget := func(variant variant) *moduleInfo {
Colin Cross5df74a82020-08-24 16:18:21 -07002668 for _, moduleOrAlias := range group.modules {
2669 if alias := moduleOrAlias.alias(); alias != nil {
2670 if alias.variant.variations.equal(variant.variations) {
2671 return alias.target
2672 }
Colin Cross279489c2020-08-13 12:11:52 -07002673 }
2674 }
2675 return nil
2676 }
2677
Colin Crossf7beb892019-11-13 20:11:14 -08002678 // Forward or delete any dangling aliases.
Colin Cross5df74a82020-08-24 16:18:21 -07002679 // Use a manual loop instead of range because len(group.modules) can
2680 // change inside the loop
2681 for i := 0; i < len(group.modules); i++ {
2682 if alias := group.modules[i].alias(); alias != nil {
2683 if alias.target.logicModule == nil {
2684 newTarget := findAliasTarget(alias.target.variant)
2685 if newTarget != nil {
2686 alias.target = newTarget
2687 } else {
2688 // The alias was left dangling, remove it.
2689 group.modules = append(group.modules[:i], group.modules[i+1:]...)
2690 i--
2691 }
Colin Crossf7beb892019-11-13 20:11:14 -08002692 }
2693 }
2694 }
Colin Crossc9028482014-12-18 16:28:54 -08002695 }
2696
Colin Cross99bdb2a2019-03-29 16:35:02 -07002697 // Add in any new reverse dependencies that were added by the mutator
Colin Cross8d8a7af2015-11-03 16:41:29 -08002698 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002699 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002700 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002701 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002702 }
2703
Colin Crossaf4fd212017-07-28 14:32:36 -07002704 for _, module := range newModules {
2705 errs = c.addModule(module)
2706 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002707 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002708 }
2709 atomic.AddUint32(&c.depsModified, 1)
2710 }
2711
Colin Cross0ce142c2016-12-09 10:29:05 -08002712 errs = c.handleRenames(rename)
2713 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002714 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002715 }
2716
2717 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002718 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002719 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002720 }
2721
Colin Cross3702ac72016-08-11 11:09:00 -07002722 if c.depsModified > 0 {
2723 errs = c.updateDependencies()
2724 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002725 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002726 }
Colin Crossc9028482014-12-18 16:28:54 -08002727 }
2728
Colin Cross874a3462017-07-31 17:26:06 -07002729 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002730}
2731
Colin Cross910242b2016-04-11 15:41:52 -07002732// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2733// a mutator sets a non-property member variable on a module, which works until a later mutator
2734// creates variants of that module.
2735func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002736 type update struct {
2737 orig Module
2738 clone *moduleInfo
2739 }
Colin Cross7e723372018-03-28 11:50:12 -07002740 ch := make(chan update)
2741 doneCh := make(chan bool)
2742 go func() {
Colin Crossc4773d92020-08-25 17:12:59 -07002743 errs := parallelVisit(c.modulesSorted, unorderedVisitorImpl{}, parallelVisitLimit,
2744 func(m *moduleInfo, pause chan<- pauseSpec) bool {
2745 origLogicModule := m.logicModule
2746 m.logicModule, m.properties = c.cloneLogicModule(m)
2747 ch <- update{origLogicModule, m}
2748 return false
2749 })
2750 if len(errs) > 0 {
2751 panic(errs)
2752 }
Colin Cross7e723372018-03-28 11:50:12 -07002753 doneCh <- true
2754 }()
Colin Crossc93490c2016-08-09 14:21:02 -07002755
Colin Cross7e723372018-03-28 11:50:12 -07002756 done := false
2757 for !done {
2758 select {
2759 case <-doneCh:
2760 done = true
2761 case update := <-ch:
2762 delete(c.moduleInfo, update.orig)
2763 c.moduleInfo[update.clone.logicModule] = update.clone
2764 }
Colin Cross910242b2016-04-11 15:41:52 -07002765 }
2766}
2767
Colin Cross49c279a2016-08-05 22:30:44 -07002768// Removes modules[i] from the list and inserts newModules... where it was located, returning
2769// the new slice and the index of the last inserted element
Colin Cross5df74a82020-08-24 16:18:21 -07002770func spliceModules(modules modulesOrAliases, i int, newModules modulesOrAliases) (modulesOrAliases, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002771 spliceSize := len(newModules)
2772 newLen := len(modules) + spliceSize - 1
Colin Cross5df74a82020-08-24 16:18:21 -07002773 var dest modulesOrAliases
Colin Cross7addea32015-03-11 15:43:52 -07002774 if cap(modules) >= len(modules)-1+len(newModules) {
2775 // We can fit the splice in the existing capacity, do everything in place
2776 dest = modules[:newLen]
2777 } else {
Colin Cross5df74a82020-08-24 16:18:21 -07002778 dest = make(modulesOrAliases, newLen)
Colin Cross7addea32015-03-11 15:43:52 -07002779 copy(dest, modules[:i])
2780 }
2781
2782 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002783 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002784
2785 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002786 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002787
Colin Cross49c279a2016-08-05 22:30:44 -07002788 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002789}
2790
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002791func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002792 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002793
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002794 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002795 var errs []error
2796
Colin Cross691a60d2015-01-07 18:08:56 -08002797 cancelCh := make(chan struct{})
2798 errsCh := make(chan []error)
2799 depsCh := make(chan []string)
2800
2801 go func() {
2802 for {
2803 select {
2804 case <-cancelCh:
2805 close(cancelCh)
2806 return
2807 case newErrs := <-errsCh:
2808 errs = append(errs, newErrs...)
2809 case newDeps := <-depsCh:
2810 deps = append(deps, newDeps...)
2811
2812 }
2813 }
2814 }()
2815
Colin Crossc4773d92020-08-25 17:12:59 -07002816 visitErrs := parallelVisit(c.modulesSorted, bottomUpVisitor, parallelVisitLimit,
2817 func(module *moduleInfo, pause chan<- pauseSpec) bool {
2818 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2819 sanitizedName := toNinjaName(uniqueName)
Jeff Gaston0e907592017-12-01 17:10:52 -08002820
Colin Crossc4773d92020-08-25 17:12:59 -07002821 prefix := moduleNamespacePrefix(sanitizedName + "_" + module.variant.name)
Jeff Gaston0e907592017-12-01 17:10:52 -08002822
Colin Crossc4773d92020-08-25 17:12:59 -07002823 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2824 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2825 // just set it to nil.
2826 scope := newLocalScope(nil, prefix)
Jeff Gaston0e907592017-12-01 17:10:52 -08002827
Colin Crossc4773d92020-08-25 17:12:59 -07002828 mctx := &moduleContext{
2829 baseModuleContext: baseModuleContext{
2830 context: c,
2831 config: config,
2832 module: module,
2833 },
2834 scope: scope,
2835 handledMissingDeps: module.missingDeps == nil,
Colin Cross036a1df2015-12-17 15:49:30 -08002836 }
Colin Cross036a1df2015-12-17 15:49:30 -08002837
Colin Cross2da84922020-07-02 10:08:12 -07002838 mctx.module.startedGenerateBuildActions = true
2839
Colin Crossc4773d92020-08-25 17:12:59 -07002840 func() {
2841 defer func() {
2842 if r := recover(); r != nil {
2843 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2844 if err, ok := r.(panicError); ok {
2845 err.addIn(in)
2846 mctx.error(err)
2847 } else {
2848 mctx.error(newPanicErrorf(r, in))
2849 }
2850 }
2851 }()
2852 mctx.module.logicModule.GenerateBuildActions(mctx)
2853 }()
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002854
Colin Cross2da84922020-07-02 10:08:12 -07002855 mctx.module.finishedGenerateBuildActions = true
2856
Colin Crossc4773d92020-08-25 17:12:59 -07002857 if len(mctx.errs) > 0 {
2858 errsCh <- mctx.errs
2859 return true
2860 }
2861
2862 if module.missingDeps != nil && !mctx.handledMissingDeps {
2863 var errs []error
2864 for _, depName := range module.missingDeps {
2865 errs = append(errs, c.missingDependencyError(module, depName))
2866 }
2867 errsCh <- errs
2868 return true
2869 }
2870
2871 depsCh <- mctx.ninjaFileDeps
2872
2873 newErrs := c.processLocalBuildActions(&module.actionDefs,
2874 &mctx.actionDefs, liveGlobals)
2875 if len(newErrs) > 0 {
2876 errsCh <- newErrs
2877 return true
2878 }
2879 return false
2880 })
Colin Cross691a60d2015-01-07 18:08:56 -08002881
2882 cancelCh <- struct{}{}
2883 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002884
Colin Crossc4773d92020-08-25 17:12:59 -07002885 errs = append(errs, visitErrs...)
2886
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002887 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002888}
2889
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002890func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002891 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002892
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002893 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002894 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002895
Colin Cross5f03f112017-11-07 13:29:54 -08002896 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002897 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2898 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2899 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002900 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002901
2902 sctx := &singletonContext{
Colin Cross9226d6c2019-02-25 18:07:44 -08002903 name: info.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002904 context: c,
2905 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002906 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002907 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002908 }
2909
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002910 func() {
2911 defer func() {
2912 if r := recover(); r != nil {
2913 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2914 if err, ok := r.(panicError); ok {
2915 err.addIn(in)
2916 sctx.error(err)
2917 } else {
2918 sctx.error(newPanicErrorf(r, in))
2919 }
2920 }
2921 }()
2922 info.singleton.GenerateBuildActions(sctx)
2923 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002924
2925 if len(sctx.errs) > 0 {
2926 errs = append(errs, sctx.errs...)
2927 if len(errs) > maxErrors {
2928 break
2929 }
2930 continue
2931 }
2932
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002933 deps = append(deps, sctx.ninjaFileDeps...)
2934
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002935 newErrs := c.processLocalBuildActions(&info.actionDefs,
2936 &sctx.actionDefs, liveGlobals)
2937 errs = append(errs, newErrs...)
2938 if len(errs) > maxErrors {
2939 break
2940 }
2941 }
2942
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002943 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002944}
2945
2946func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2947 liveGlobals *liveTracker) []error {
2948
2949 var errs []error
2950
2951 // First we go through and add everything referenced by the module's
2952 // buildDefs to the live globals set. This will end up adding the live
2953 // locals to the set as well, but we'll take them out after.
2954 for _, def := range in.buildDefs {
2955 err := liveGlobals.AddBuildDefDeps(def)
2956 if err != nil {
2957 errs = append(errs, err)
2958 }
2959 }
2960
2961 if len(errs) > 0 {
2962 return errs
2963 }
2964
Colin Crossc9028482014-12-18 16:28:54 -08002965 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002966
2967 // We use the now-incorrect set of live "globals" to determine which local
2968 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002969 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002970 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002971 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002972 if isLive {
2973 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002974 }
2975 }
2976
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002977 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002978 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002979 if isLive {
2980 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002981 }
2982 }
2983
2984 return nil
2985}
2986
Colin Cross9607a9f2018-06-20 11:16:37 -07002987func (c *Context) walkDeps(topModule *moduleInfo, allowDuplicates bool,
Colin Crossbafd5f52016-08-06 22:52:01 -07002988 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07002989
2990 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002991 var visiting *moduleInfo
2992
2993 defer func() {
2994 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07002995 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
2996 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002997 }
2998 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07002999
3000 var walk func(module *moduleInfo)
3001 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003002 for _, dep := range module.directDeps {
Colin Cross9607a9f2018-06-20 11:16:37 -07003003 if allowDuplicates || !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003004 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07003005 recurse := true
3006 if visitDown != nil {
3007 recurse = visitDown(dep, module)
3008 }
Colin Cross526e02f2018-06-21 13:31:53 -07003009 if recurse && !visited[dep.module] {
Colin Cross2c1f3d12016-04-11 15:47:28 -07003010 walk(dep.module)
Paul Duffin72bab172020-04-02 10:51:33 +01003011 visited[dep.module] = true
Yuchen Wu222e2452015-10-06 14:03:27 -07003012 }
Colin Crossbafd5f52016-08-06 22:52:01 -07003013 if visitUp != nil {
3014 visitUp(dep, module)
3015 }
Yuchen Wu222e2452015-10-06 14:03:27 -07003016 }
3017 }
3018 }
3019
3020 walk(topModule)
3021}
3022
Colin Cross9cfd1982016-10-11 09:58:53 -07003023type replace struct {
Paul Duffin8969cb62020-06-30 12:15:26 +01003024 from, to *moduleInfo
3025 predicate ReplaceDependencyPredicate
Colin Cross9cfd1982016-10-11 09:58:53 -07003026}
3027
Colin Crossc4e5b812016-10-12 10:45:05 -07003028type rename struct {
3029 group *moduleGroup
3030 name string
3031}
3032
Colin Cross0ce142c2016-12-09 10:29:05 -08003033func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Colin Crossd03b59d2019-11-13 20:10:12 -08003034 group := c.moduleGroupFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07003035
Colin Crossd03b59d2019-11-13 20:10:12 -08003036 if group == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08003037 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003038 }
3039
Colin Crossd03b59d2019-11-13 20:10:12 -08003040 for _, m := range group.modules {
Colin Crossedbdb8c2020-09-11 19:22:27 -07003041 if module.variant.name == m.moduleOrAliasVariant().name {
Colin Cross5df74a82020-08-24 16:18:21 -07003042 return m.moduleOrAliasTarget()
Colin Crossf7beb892019-11-13 20:11:14 -08003043 }
3044 }
3045
Colin Cross0ce142c2016-12-09 10:29:05 -08003046 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07003047}
3048
Colin Cross0ce142c2016-12-09 10:29:05 -08003049func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07003050 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08003051 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07003052 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08003053 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07003054 continue
3055 }
3056
Jeff Gastond70bf752017-11-10 15:12:08 -08003057 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07003058 }
3059
Colin Cross0ce142c2016-12-09 10:29:05 -08003060 return errs
3061}
3062
3063func (c *Context) handleReplacements(replacements []replace) []error {
3064 var errs []error
Paul Duffin8969cb62020-06-30 12:15:26 +01003065 changedDeps := false
Colin Cross0ce142c2016-12-09 10:29:05 -08003066 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07003067 for _, m := range replace.from.reverseDeps {
3068 for i, d := range m.directDeps {
3069 if d.module == replace.from {
Paul Duffin8969cb62020-06-30 12:15:26 +01003070 // If the replacement has a predicate then check it.
3071 if replace.predicate == nil || replace.predicate(m.logicModule, d.tag, d.module.logicModule) {
3072 m.directDeps[i].module = replace.to
3073 changedDeps = true
3074 }
Colin Cross9cfd1982016-10-11 09:58:53 -07003075 }
3076 }
3077 }
3078
Colin Cross9cfd1982016-10-11 09:58:53 -07003079 }
Colin Cross0ce142c2016-12-09 10:29:05 -08003080
Paul Duffin8969cb62020-06-30 12:15:26 +01003081 if changedDeps {
3082 atomic.AddUint32(&c.depsModified, 1)
3083 }
Colin Crossc4e5b812016-10-12 10:45:05 -07003084 return errs
3085}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003086
Martin Stjernholm0f1637b2020-11-16 20:15:36 +00003087func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string, depVariations variationMap) (errs []error) {
3088 if depVariations != nil {
3089 depName = depName + "{" + c.prettyPrintVariant(depVariations) + "}"
3090 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003091 if c.allowMissingDependencies {
3092 module.missingDeps = append(module.missingDeps, depName)
3093 return nil
3094 }
3095 return []error{c.missingDependencyError(module, depName)}
3096}
3097
3098func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
3099 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
3100
3101 return &BlueprintError{
3102 Err: err,
3103 Pos: module.pos,
3104 }
3105}
3106
Colin Crossd03b59d2019-11-13 20:10:12 -08003107func (c *Context) moduleGroupFromName(name string, namespace Namespace) *moduleGroup {
Jeff Gastond70bf752017-11-10 15:12:08 -08003108 group, exists := c.nameInterface.ModuleFromName(name, namespace)
3109 if exists {
Colin Crossd03b59d2019-11-13 20:10:12 -08003110 return group.moduleGroup
Colin Cross0b7e83e2016-05-17 14:58:05 -07003111 }
3112 return nil
3113}
3114
Jeff Gastond70bf752017-11-10 15:12:08 -08003115func (c *Context) sortedModuleGroups() []*moduleGroup {
Liz Kammer9ae14f12020-11-30 16:30:45 -07003116 if c.cachedSortedModuleGroups == nil || c.cachedDepsModified {
Jeff Gastond70bf752017-11-10 15:12:08 -08003117 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
3118 result := make([]*moduleGroup, 0, len(wrappers))
3119 for _, group := range wrappers {
3120 result = append(result, group.moduleGroup)
3121 }
3122 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07003123 }
Jeff Gastond70bf752017-11-10 15:12:08 -08003124
3125 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Liz Kammer9ae14f12020-11-30 16:30:45 -07003126 c.cachedDepsModified = false
Jamie Gennisc15544d2014-09-24 20:26:52 -07003127 }
3128
Jeff Gastond70bf752017-11-10 15:12:08 -08003129 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07003130}
3131
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003132func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003133 var module *moduleInfo
3134
3135 defer func() {
3136 if r := recover(); r != nil {
3137 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
3138 funcName(visit), module))
3139 }
3140 }()
3141
Jeff Gastond70bf752017-11-10 15:12:08 -08003142 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003143 for _, moduleOrAlias := range moduleGroup.modules {
3144 if module = moduleOrAlias.module(); module != nil {
3145 visit(module.logicModule)
3146 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003147 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003148 }
3149}
3150
3151func (c *Context) visitAllModulesIf(pred func(Module) bool,
3152 visit func(Module)) {
3153
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003154 var module *moduleInfo
3155
3156 defer func() {
3157 if r := recover(); r != nil {
3158 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
3159 funcName(pred), funcName(visit), module))
3160 }
3161 }()
3162
Jeff Gastond70bf752017-11-10 15:12:08 -08003163 for _, moduleGroup := range c.sortedModuleGroups() {
Colin Cross5df74a82020-08-24 16:18:21 -07003164 for _, moduleOrAlias := range moduleGroup.modules {
3165 if module = moduleOrAlias.module(); module != nil {
3166 if pred(module.logicModule) {
3167 visit(module.logicModule)
3168 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08003169 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003170 }
3171 }
3172}
3173
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003174func (c *Context) visitAllModuleVariants(module *moduleInfo,
3175 visit func(Module)) {
3176
3177 var variant *moduleInfo
3178
3179 defer func() {
3180 if r := recover(); r != nil {
3181 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
3182 module, funcName(visit), variant))
3183 }
3184 }()
3185
Colin Cross5df74a82020-08-24 16:18:21 -07003186 for _, moduleOrAlias := range module.group.modules {
3187 if variant = moduleOrAlias.module(); variant != nil {
3188 visit(variant.logicModule)
3189 }
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003190 }
3191}
3192
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003193func (c *Context) requireNinjaVersion(major, minor, micro int) {
3194 if major != 1 {
3195 panic("ninja version with major version != 1 not supported")
3196 }
3197 if c.requiredNinjaMinor < minor {
3198 c.requiredNinjaMinor = minor
3199 c.requiredNinjaMicro = micro
3200 }
3201 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
3202 c.requiredNinjaMicro = micro
3203 }
3204}
3205
Colin Cross2ce594e2020-01-29 12:58:03 -08003206func (c *Context) setNinjaBuildDir(value ninjaString) {
Colin Crossa2599452015-11-18 16:01:01 -08003207 if c.ninjaBuildDir == nil {
3208 c.ninjaBuildDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003209 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003210}
3211
3212func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08003213 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003214
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003215 pkgs := make(map[string]*packageContext)
3216 pkgNames := make(map[*packageContext]string)
3217 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003218
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003219 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003220 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003221 // This is a built-in rule and has no package.
3222 return
3223 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07003224 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003225 // We've already processed this package.
3226 return
3227 }
3228
Jamie Gennis2fb20952014-10-03 02:49:58 -07003229 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003230 if present {
3231 // Short name collision. Both this package and the one that's
3232 // already there need to use their full names. We leave the short
3233 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003234 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003235 longPkgNames[otherPkg] = true
3236 } else {
3237 // No collision so far. Tentatively set the package's name to be
3238 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003239 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07003240 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003241 }
3242 }
3243
3244 // We try to give all packages their short name, but when we get collisions
3245 // we need to use the full unique package name.
3246 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003247 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003248 }
3249 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003250 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003251 }
3252 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07003253 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003254 }
3255
3256 // Add the packages that had collisions using their full unique names. This
3257 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07003258 for pctx := range longPkgNames {
3259 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003260 }
3261
Dan Willemsena481ae22015-12-18 15:18:03 -08003262 // Create deps list from calls to PackageContext.AddNinjaFileDeps
3263 deps := []string{}
3264 for _, pkg := range pkgs {
3265 deps = append(deps, pkg.ninjaFileDeps...)
3266 }
3267
3268 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003269}
3270
Colin Cross92054a42021-01-21 16:49:25 -08003271// memoizeFullNames stores the full name of each live global variable, rule and pool since each is
3272// guaranteed to be used at least twice, once in the definition and once for each usage, and many
3273// are used much more than once.
3274func (c *Context) memoizeFullNames(liveGlobals *liveTracker, pkgNames map[*packageContext]string) {
3275 for v := range liveGlobals.variables {
3276 v.memoizeFullName(pkgNames)
3277 }
3278 for r := range liveGlobals.rules {
3279 r.memoizeFullName(pkgNames)
3280 }
3281 for p := range liveGlobals.pools {
3282 p.memoizeFullName(pkgNames)
3283 }
3284}
3285
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003286func (c *Context) checkForVariableReferenceCycles(
Colin Cross2ce594e2020-01-29 12:58:03 -08003287 variables map[Variable]ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003288
3289 visited := make(map[Variable]bool) // variables that were already checked
3290 checking := make(map[Variable]bool) // variables actively being checked
3291
3292 var check func(v Variable) []Variable
3293
3294 check = func(v Variable) []Variable {
3295 visited[v] = true
3296 checking[v] = true
3297 defer delete(checking, v)
3298
3299 value := variables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003300 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003301 if checking[dep] {
3302 // This is a cycle.
3303 return []Variable{dep, v}
3304 }
3305
3306 if !visited[dep] {
3307 cycle := check(dep)
3308 if cycle != nil {
3309 if cycle[0] == v {
3310 // We are the "start" of the cycle, so we're responsible
3311 // for generating the errors. The cycle list is in
3312 // reverse order because all the 'check' calls append
3313 // their own module to the list.
3314 msgs := []string{"detected variable reference cycle:"}
3315
3316 // Iterate backwards through the cycle list.
3317 curName := v.fullName(pkgNames)
3318 curValue := value.Value(pkgNames)
3319 for i := len(cycle) - 1; i >= 0; i-- {
3320 next := cycle[i]
3321 nextName := next.fullName(pkgNames)
3322 nextValue := variables[next].Value(pkgNames)
3323
3324 msgs = append(msgs, fmt.Sprintf(
3325 " %q depends on %q", curName, nextName))
3326 msgs = append(msgs, fmt.Sprintf(
3327 " [%s = %s]", curName, curValue))
3328
3329 curName = nextName
3330 curValue = nextValue
3331 }
3332
3333 // Variable reference cycles are a programming error,
3334 // not the fault of the Blueprint file authors.
3335 panic(strings.Join(msgs, "\n"))
3336 } else {
3337 // We're not the "start" of the cycle, so we just append
3338 // our module to the list and return it.
3339 return append(cycle, v)
3340 }
3341 }
3342 }
3343 }
3344
3345 return nil
3346 }
3347
3348 for v := range variables {
3349 if !visited[v] {
3350 cycle := check(v)
3351 if cycle != nil {
3352 panic("inconceivable!")
3353 }
3354 }
3355 }
3356}
3357
Jamie Gennisaf435562014-10-27 22:34:56 -07003358// AllTargets returns a map all the build target names to the rule used to build
3359// them. This is the same information that is output by running 'ninja -t
3360// targets all'. If this is called before PrepareBuildActions successfully
3361// completes then ErrbuildActionsNotReady is returned.
3362func (c *Context) AllTargets() (map[string]string, error) {
3363 if !c.buildActionsReady {
3364 return nil, ErrBuildActionsNotReady
3365 }
3366
3367 targets := map[string]string{}
3368
3369 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07003370 for _, module := range c.moduleInfo {
3371 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07003372 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003373 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003374 outputValue, err := output.Eval(c.globalVariables)
3375 if err != nil {
3376 return nil, err
3377 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003378 targets[outputValue] = ruleName
3379 }
3380 }
3381 }
3382
3383 // Collect all the singleton build targets.
3384 for _, info := range c.singletonInfo {
3385 for _, buildDef := range info.actionDefs.buildDefs {
3386 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07003387 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08003388 outputValue, err := output.Eval(c.globalVariables)
3389 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08003390 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08003391 }
Jamie Gennisaf435562014-10-27 22:34:56 -07003392 targets[outputValue] = ruleName
3393 }
3394 }
3395 }
3396
3397 return targets, nil
3398}
3399
Colin Crossa2599452015-11-18 16:01:01 -08003400func (c *Context) NinjaBuildDir() (string, error) {
3401 if c.ninjaBuildDir != nil {
3402 return c.ninjaBuildDir.Eval(c.globalVariables)
3403 } else {
3404 return "", nil
3405 }
3406}
3407
Colin Cross4572edd2015-05-13 14:36:24 -07003408// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
3409// property structs returned by the factory for that module type.
3410func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
3411 ret := make(map[string][]interface{})
3412 for moduleType, factory := range c.moduleFactories {
3413 _, ret[moduleType] = factory()
3414 }
3415
3416 return ret
3417}
3418
Jaewoong Jung781f6b22019-02-06 16:20:17 -08003419func (c *Context) ModuleTypeFactories() map[string]ModuleFactory {
3420 ret := make(map[string]ModuleFactory)
3421 for k, v := range c.moduleFactories {
3422 ret[k] = v
3423 }
3424 return ret
3425}
3426
Colin Cross4572edd2015-05-13 14:36:24 -07003427func (c *Context) ModuleName(logicModule Module) string {
3428 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07003429 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07003430}
3431
Jeff Gaston3c8c3342017-11-30 17:30:42 -08003432func (c *Context) ModuleDir(logicModule Module) string {
Colin Cross8e454c52020-07-06 12:18:59 -07003433 return filepath.Dir(c.BlueprintFile(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07003434}
3435
Colin Cross8c602f72015-12-17 18:02:11 -08003436func (c *Context) ModuleSubDir(logicModule Module) string {
3437 module := c.moduleInfo[logicModule]
Colin Crossedc41762020-08-13 12:07:30 -07003438 return module.variant.name
Colin Cross8c602f72015-12-17 18:02:11 -08003439}
3440
Dan Willemsenc98e55b2016-07-25 15:51:50 -07003441func (c *Context) ModuleType(logicModule Module) string {
3442 module := c.moduleInfo[logicModule]
3443 return module.typeName
3444}
3445
Colin Cross2da84922020-07-02 10:08:12 -07003446// ModuleProvider returns the value, if any, for the provider for a module. If the value for the
3447// provider was not set it returns the zero value of the type of the provider, which means the
3448// return value can always be type-asserted to the type of the provider. The return value should
3449// always be considered read-only. It panics if called before the appropriate mutator or
3450// GenerateBuildActions pass for the provider on the module. The value returned may be a deep
3451// copy of the value originally passed to SetProvider.
3452func (c *Context) ModuleProvider(logicModule Module, provider ProviderKey) interface{} {
3453 module := c.moduleInfo[logicModule]
3454 value, _ := c.provider(module, provider)
3455 return value
3456}
3457
3458// ModuleHasProvider returns true if the provider for the given module has been set.
3459func (c *Context) ModuleHasProvider(logicModule Module, provider ProviderKey) bool {
3460 module := c.moduleInfo[logicModule]
3461 _, ok := c.provider(module, provider)
3462 return ok
3463}
3464
Colin Cross4572edd2015-05-13 14:36:24 -07003465func (c *Context) BlueprintFile(logicModule Module) string {
3466 module := c.moduleInfo[logicModule]
3467 return module.relBlueprintsFile
3468}
3469
3470func (c *Context) ModuleErrorf(logicModule Module, format string,
3471 args ...interface{}) error {
3472
3473 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07003474 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07003475 Err: fmt.Errorf(format, args...),
3476 Pos: module.pos,
3477 }
3478}
3479
3480func (c *Context) VisitAllModules(visit func(Module)) {
3481 c.visitAllModules(visit)
3482}
3483
3484func (c *Context) VisitAllModulesIf(pred func(Module) bool,
3485 visit func(Module)) {
3486
3487 c.visitAllModulesIf(pred, visit)
3488}
3489
Colin Cross080c1332017-03-17 13:09:05 -07003490func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
3491 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07003492
Colin Cross080c1332017-03-17 13:09:05 -07003493 var visiting *moduleInfo
3494
3495 defer func() {
3496 if r := recover(); r != nil {
3497 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
3498 topModule, funcName(visit), visiting))
3499 }
3500 }()
3501
3502 for _, dep := range topModule.directDeps {
3503 visiting = dep.module
3504 visit(dep.module.logicModule)
3505 }
3506}
3507
3508func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
3509 topModule := c.moduleInfo[module]
3510
3511 var visiting *moduleInfo
3512
3513 defer func() {
3514 if r := recover(); r != nil {
3515 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
3516 topModule, funcName(pred), funcName(visit), visiting))
3517 }
3518 }()
3519
3520 for _, dep := range topModule.directDeps {
3521 visiting = dep.module
3522 if pred(dep.module.logicModule) {
3523 visit(dep.module.logicModule)
3524 }
3525 }
3526}
3527
3528func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003529 topModule := c.moduleInfo[module]
3530
3531 var visiting *moduleInfo
3532
3533 defer func() {
3534 if r := recover(); r != nil {
3535 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
3536 topModule, funcName(visit), visiting))
3537 }
3538 }()
3539
Colin Cross9607a9f2018-06-20 11:16:37 -07003540 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003541 visiting = dep.module
3542 visit(dep.module.logicModule)
3543 })
Colin Cross4572edd2015-05-13 14:36:24 -07003544}
3545
Colin Cross080c1332017-03-17 13:09:05 -07003546func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003547 topModule := c.moduleInfo[module]
3548
3549 var visiting *moduleInfo
3550
3551 defer func() {
3552 if r := recover(); r != nil {
3553 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
3554 topModule, funcName(pred), funcName(visit), visiting))
3555 }
3556 }()
3557
Colin Cross9607a9f2018-06-20 11:16:37 -07003558 c.walkDeps(topModule, false, nil, func(dep depInfo, parent *moduleInfo) {
Colin Crossbafd5f52016-08-06 22:52:01 -07003559 if pred(dep.module.logicModule) {
3560 visiting = dep.module
3561 visit(dep.module.logicModule)
3562 }
3563 })
Colin Cross4572edd2015-05-13 14:36:24 -07003564}
3565
Colin Cross24ad5872015-11-17 16:22:29 -08003566func (c *Context) PrimaryModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003567 return c.moduleInfo[module].group.modules.firstModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003568}
3569
3570func (c *Context) FinalModule(module Module) Module {
Colin Cross5df74a82020-08-24 16:18:21 -07003571 return c.moduleInfo[module].group.modules.lastModule().logicModule
Colin Cross24ad5872015-11-17 16:22:29 -08003572}
3573
3574func (c *Context) VisitAllModuleVariants(module Module,
3575 visit func(Module)) {
3576
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003577 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08003578}
3579
Colin Cross9226d6c2019-02-25 18:07:44 -08003580// Singletons returns a list of all registered Singletons.
3581func (c *Context) Singletons() []Singleton {
3582 var ret []Singleton
3583 for _, s := range c.singletonInfo {
3584 ret = append(ret, s.singleton)
3585 }
3586 return ret
3587}
3588
3589// SingletonName returns the name that the given singleton was registered with.
3590func (c *Context) SingletonName(singleton Singleton) string {
3591 for _, s := range c.singletonInfo {
3592 if s.singleton == singleton {
3593 return s.name
3594 }
3595 }
3596 return ""
3597}
3598
Jamie Gennisd4e10182014-06-12 20:06:50 -07003599// WriteBuildFile writes the Ninja manifeset text for the generated build
3600// actions to w. If this is called before PrepareBuildActions successfully
3601// completes then ErrBuildActionsNotReady is returned.
Colin Cross0335e092021-01-21 15:26:21 -08003602func (c *Context) WriteBuildFile(w io.StringWriter) error {
Colin Cross3a8c0252019-01-23 13:21:48 -08003603 var err error
3604 pprof.Do(c.Context, pprof.Labels("blueprint", "WriteBuildFile"), func(ctx context.Context) {
3605 if !c.buildActionsReady {
3606 err = ErrBuildActionsNotReady
3607 return
3608 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003609
Colin Cross3a8c0252019-01-23 13:21:48 -08003610 nw := newNinjaWriter(w)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003611
Colin Cross3a8c0252019-01-23 13:21:48 -08003612 err = c.writeBuildFileHeader(nw)
3613 if err != nil {
3614 return
3615 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003616
Colin Cross3a8c0252019-01-23 13:21:48 -08003617 err = c.writeNinjaRequiredVersion(nw)
3618 if err != nil {
3619 return
3620 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003621
Colin Cross3a8c0252019-01-23 13:21:48 -08003622 err = c.writeSubninjas(nw)
3623 if err != nil {
3624 return
3625 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003626
Colin Cross3a8c0252019-01-23 13:21:48 -08003627 // TODO: Group the globals by package.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003628
Colin Cross3a8c0252019-01-23 13:21:48 -08003629 err = c.writeGlobalVariables(nw)
3630 if err != nil {
3631 return
3632 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003633
Colin Cross3a8c0252019-01-23 13:21:48 -08003634 err = c.writeGlobalPools(nw)
3635 if err != nil {
3636 return
3637 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003638
Colin Cross3a8c0252019-01-23 13:21:48 -08003639 err = c.writeBuildDir(nw)
3640 if err != nil {
3641 return
3642 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003643
Colin Cross3a8c0252019-01-23 13:21:48 -08003644 err = c.writeGlobalRules(nw)
3645 if err != nil {
3646 return
3647 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003648
Colin Cross3a8c0252019-01-23 13:21:48 -08003649 err = c.writeAllModuleActions(nw)
3650 if err != nil {
3651 return
3652 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003653
Colin Cross3a8c0252019-01-23 13:21:48 -08003654 err = c.writeAllSingletonActions(nw)
3655 if err != nil {
3656 return
3657 }
3658 })
3659
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003660 if err != nil {
3661 return err
3662 }
3663
3664 return nil
3665}
3666
Jamie Gennisc15544d2014-09-24 20:26:52 -07003667type pkgAssociation struct {
3668 PkgName string
3669 PkgPath string
3670}
3671
3672type pkgAssociationSorter struct {
3673 pkgs []pkgAssociation
3674}
3675
3676func (s *pkgAssociationSorter) Len() int {
3677 return len(s.pkgs)
3678}
3679
3680func (s *pkgAssociationSorter) Less(i, j int) bool {
3681 iName := s.pkgs[i].PkgName
3682 jName := s.pkgs[j].PkgName
3683 return iName < jName
3684}
3685
3686func (s *pkgAssociationSorter) Swap(i, j int) {
3687 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
3688}
3689
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003690func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
3691 headerTemplate := template.New("fileHeader")
3692 _, err := headerTemplate.Parse(fileHeaderTemplate)
3693 if err != nil {
3694 // This is a programming error.
3695 panic(err)
3696 }
3697
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003698 var pkgs []pkgAssociation
3699 maxNameLen := 0
3700 for pkg, name := range c.pkgNames {
3701 pkgs = append(pkgs, pkgAssociation{
3702 PkgName: name,
3703 PkgPath: pkg.pkgPath,
3704 })
3705 if len(name) > maxNameLen {
3706 maxNameLen = len(name)
3707 }
3708 }
3709
3710 for i := range pkgs {
3711 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
3712 }
3713
Jamie Gennisc15544d2014-09-24 20:26:52 -07003714 sort.Sort(&pkgAssociationSorter{pkgs})
3715
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003716 params := map[string]interface{}{
3717 "Pkgs": pkgs,
3718 }
3719
3720 buf := bytes.NewBuffer(nil)
3721 err = headerTemplate.Execute(buf, params)
3722 if err != nil {
3723 return err
3724 }
3725
3726 return nw.Comment(buf.String())
3727}
3728
3729func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3730 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3731 c.requiredNinjaMicro)
3732
3733 err := nw.Assign("ninja_required_version", value)
3734 if err != nil {
3735 return err
3736 }
3737
3738 return nw.BlankLine()
3739}
3740
Dan Willemsenab223a52018-07-05 21:56:59 -07003741func (c *Context) writeSubninjas(nw *ninjaWriter) error {
3742 for _, subninja := range c.subninjas {
Colin Crossde7afaa2019-01-23 13:23:00 -08003743 err := nw.Subninja(subninja)
3744 if err != nil {
3745 return err
3746 }
Dan Willemsenab223a52018-07-05 21:56:59 -07003747 }
3748 return nw.BlankLine()
3749}
3750
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003751func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Colin Crossa2599452015-11-18 16:01:01 -08003752 if c.ninjaBuildDir != nil {
3753 err := nw.Assign("builddir", c.ninjaBuildDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003754 if err != nil {
3755 return err
3756 }
3757
3758 err = nw.BlankLine()
3759 if err != nil {
3760 return err
3761 }
3762 }
3763 return nil
3764}
3765
Jamie Gennisc15544d2014-09-24 20:26:52 -07003766type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003767 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003768}
3769
Jamie Gennisc15544d2014-09-24 20:26:52 -07003770type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003771 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003772 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003773}
3774
Jamie Gennisc15544d2014-09-24 20:26:52 -07003775func (s *globalEntitySorter) Len() int {
3776 return len(s.entities)
3777}
3778
3779func (s *globalEntitySorter) Less(i, j int) bool {
3780 iName := s.entities[i].fullName(s.pkgNames)
3781 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003782 return iName < jName
3783}
3784
Jamie Gennisc15544d2014-09-24 20:26:52 -07003785func (s *globalEntitySorter) Swap(i, j int) {
3786 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003787}
3788
3789func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3790 visited := make(map[Variable]bool)
3791
3792 var walk func(v Variable) error
3793 walk = func(v Variable) error {
3794 visited[v] = true
3795
3796 // First visit variables on which this variable depends.
3797 value := c.globalVariables[v]
Colin Cross2ce594e2020-01-29 12:58:03 -08003798 for _, dep := range value.Variables() {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003799 if !visited[dep] {
3800 err := walk(dep)
3801 if err != nil {
3802 return err
3803 }
3804 }
3805 }
3806
3807 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3808 if err != nil {
3809 return err
3810 }
3811
3812 err = nw.BlankLine()
3813 if err != nil {
3814 return err
3815 }
3816
3817 return nil
3818 }
3819
Jamie Gennisc15544d2014-09-24 20:26:52 -07003820 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3821 for variable := range c.globalVariables {
3822 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003823 }
3824
Jamie Gennisc15544d2014-09-24 20:26:52 -07003825 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003826
Jamie Gennisc15544d2014-09-24 20:26:52 -07003827 for _, entity := range globalVariables {
3828 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003829 if !visited[v] {
3830 err := walk(v)
3831 if err != nil {
3832 return nil
3833 }
3834 }
3835 }
3836
3837 return nil
3838}
3839
3840func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003841 globalPools := make([]globalEntity, 0, len(c.globalPools))
3842 for pool := range c.globalPools {
3843 globalPools = append(globalPools, pool)
3844 }
3845
3846 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3847
3848 for _, entity := range globalPools {
3849 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003850 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003851 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003852 err := def.WriteTo(nw, name)
3853 if err != nil {
3854 return err
3855 }
3856
3857 err = nw.BlankLine()
3858 if err != nil {
3859 return err
3860 }
3861 }
3862
3863 return nil
3864}
3865
3866func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003867 globalRules := make([]globalEntity, 0, len(c.globalRules))
3868 for rule := range c.globalRules {
3869 globalRules = append(globalRules, rule)
3870 }
3871
3872 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3873
3874 for _, entity := range globalRules {
3875 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003876 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003877 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003878 err := def.WriteTo(nw, name, c.pkgNames)
3879 if err != nil {
3880 return err
3881 }
3882
3883 err = nw.BlankLine()
3884 if err != nil {
3885 return err
3886 }
3887 }
3888
3889 return nil
3890}
3891
Colin Cross2c1f3d12016-04-11 15:47:28 -07003892type depSorter []depInfo
3893
3894func (s depSorter) Len() int {
3895 return len(s)
3896}
3897
3898func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003899 iName := s[i].module.Name()
3900 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003901 if iName == jName {
Colin Crossedc41762020-08-13 12:07:30 -07003902 iName = s[i].module.variant.name
3903 jName = s[j].module.variant.name
Colin Cross2c1f3d12016-04-11 15:47:28 -07003904 }
3905 return iName < jName
3906}
3907
3908func (s depSorter) Swap(i, j int) {
3909 s[i], s[j] = s[j], s[i]
3910}
3911
Jeff Gaston0e907592017-12-01 17:10:52 -08003912type moduleSorter struct {
3913 modules []*moduleInfo
3914 nameInterface NameInterface
3915}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003916
Colin Crossab6d7902015-03-11 16:17:52 -07003917func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003918 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003919}
3920
Colin Crossab6d7902015-03-11 16:17:52 -07003921func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003922 iMod := s.modules[i]
3923 jMod := s.modules[j]
3924 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3925 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003926 if iName == jName {
Colin Cross279489c2020-08-13 12:11:52 -07003927 iVariantName := s.modules[i].variant.name
3928 jVariantName := s.modules[j].variant.name
3929 if iVariantName == jVariantName {
3930 panic(fmt.Sprintf("duplicate module name: %s %s: %#v and %#v\n",
3931 iName, iVariantName, iMod.variant.variations, jMod.variant.variations))
3932 } else {
3933 return iVariantName < jVariantName
3934 }
3935 } else {
3936 return iName < jName
Jeff Gaston0e907592017-12-01 17:10:52 -08003937 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003938}
3939
Colin Crossab6d7902015-03-11 16:17:52 -07003940func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003941 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003942}
3943
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003944func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3945 headerTemplate := template.New("moduleHeader")
3946 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3947 if err != nil {
3948 // This is a programming error.
3949 panic(err)
3950 }
3951
Colin Crossab6d7902015-03-11 16:17:52 -07003952 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3953 for _, module := range c.moduleInfo {
3954 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003955 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003956 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003957
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003958 buf := bytes.NewBuffer(nil)
3959
Colin Crossab6d7902015-03-11 16:17:52 -07003960 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003961 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3962 continue
3963 }
3964
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003965 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003966
3967 // In order to make the bootstrap build manifest independent of the
3968 // build dir we need to output the Blueprints file locations in the
3969 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003970 relPos := module.pos
3971 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003972
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003973 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003974 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003975 factoryName := factoryFunc.Name()
3976
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003977 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003978 "name": module.Name(),
3979 "typeName": module.typeName,
3980 "goFactory": factoryName,
3981 "pos": relPos,
Colin Crossedc41762020-08-13 12:07:30 -07003982 "variant": module.variant.name,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003983 }
3984 err = headerTemplate.Execute(buf, infoMap)
3985 if err != nil {
3986 return err
3987 }
3988
3989 err = nw.Comment(buf.String())
3990 if err != nil {
3991 return err
3992 }
3993
3994 err = nw.BlankLine()
3995 if err != nil {
3996 return err
3997 }
3998
Colin Crossab6d7902015-03-11 16:17:52 -07003999 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004000 if err != nil {
4001 return err
4002 }
4003
4004 err = nw.BlankLine()
4005 if err != nil {
4006 return err
4007 }
4008 }
4009
4010 return nil
4011}
4012
4013func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
4014 headerTemplate := template.New("singletonHeader")
4015 _, err := headerTemplate.Parse(singletonHeaderTemplate)
4016 if err != nil {
4017 // This is a programming error.
4018 panic(err)
4019 }
4020
4021 buf := bytes.NewBuffer(nil)
4022
Yuchen Wub9103ef2015-08-25 17:58:17 -07004023 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07004024 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
4025 continue
4026 }
4027
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004028 // Get the name of the factory function for the module.
4029 factory := info.factory
4030 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
4031 factoryName := factoryFunc.Name()
4032
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004033 buf.Reset()
4034 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07004035 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004036 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004037 }
4038 err = headerTemplate.Execute(buf, infoMap)
4039 if err != nil {
4040 return err
4041 }
4042
4043 err = nw.Comment(buf.String())
4044 if err != nil {
4045 return err
4046 }
4047
4048 err = nw.BlankLine()
4049 if err != nil {
4050 return err
4051 }
4052
4053 err = c.writeLocalBuildActions(nw, &info.actionDefs)
4054 if err != nil {
4055 return err
4056 }
4057
4058 err = nw.BlankLine()
4059 if err != nil {
4060 return err
4061 }
4062 }
4063
4064 return nil
4065}
4066
4067func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
4068 defs *localBuildActions) error {
4069
4070 // Write the local variable assignments.
4071 for _, v := range defs.variables {
4072 // A localVariable doesn't need the package names or config to
4073 // determine its name or value.
4074 name := v.fullName(nil)
4075 value, err := v.value(nil)
4076 if err != nil {
4077 panic(err)
4078 }
4079 err = nw.Assign(name, value.Value(c.pkgNames))
4080 if err != nil {
4081 return err
4082 }
4083 }
4084
4085 if len(defs.variables) > 0 {
4086 err := nw.BlankLine()
4087 if err != nil {
4088 return err
4089 }
4090 }
4091
4092 // Write the local rules.
4093 for _, r := range defs.rules {
4094 // A localRule doesn't need the package names or config to determine
4095 // its name or definition.
4096 name := r.fullName(nil)
4097 def, err := r.def(nil)
4098 if err != nil {
4099 panic(err)
4100 }
4101
4102 err = def.WriteTo(nw, name, c.pkgNames)
4103 if err != nil {
4104 return err
4105 }
4106
4107 err = nw.BlankLine()
4108 if err != nil {
4109 return err
4110 }
4111 }
4112
4113 // Write the build definitions.
4114 for _, buildDef := range defs.buildDefs {
4115 err := buildDef.WriteTo(nw, c.pkgNames)
4116 if err != nil {
4117 return err
4118 }
4119
4120 if len(buildDef.Args) > 0 {
4121 err = nw.BlankLine()
4122 if err != nil {
4123 return err
4124 }
4125 }
4126 }
4127
4128 return nil
4129}
4130
Colin Cross5df74a82020-08-24 16:18:21 -07004131func beforeInModuleList(a, b *moduleInfo, list modulesOrAliases) bool {
Colin Cross65569e42015-03-10 20:08:19 -07004132 found := false
Colin Cross045a5972015-11-03 16:58:48 -08004133 if a == b {
4134 return false
4135 }
Colin Cross65569e42015-03-10 20:08:19 -07004136 for _, l := range list {
Colin Cross5df74a82020-08-24 16:18:21 -07004137 if l.module() == a {
Colin Cross65569e42015-03-10 20:08:19 -07004138 found = true
Colin Cross5df74a82020-08-24 16:18:21 -07004139 } else if l.module() == b {
Colin Cross65569e42015-03-10 20:08:19 -07004140 return found
4141 }
4142 }
4143
4144 missing := a
4145 if found {
4146 missing = b
4147 }
4148 panic(fmt.Errorf("element %v not found in list %v", missing, list))
4149}
4150
Colin Cross0aa6a5f2016-01-07 13:43:09 -08004151type panicError struct {
4152 panic interface{}
4153 stack []byte
4154 in string
4155}
4156
4157func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
4158 buf := make([]byte, 4096)
4159 count := runtime.Stack(buf, false)
4160 return panicError{
4161 panic: panic,
4162 in: fmt.Sprintf(in, a...),
4163 stack: buf[:count],
4164 }
4165}
4166
4167func (p panicError) Error() string {
4168 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
4169}
4170
4171func (p *panicError) addIn(in string) {
4172 p.in += " in " + in
4173}
4174
4175func funcName(f interface{}) string {
4176 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
4177}
4178
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004179var fileHeaderTemplate = `******************************************************************************
4180*** This file is generated and should not be edited ***
4181******************************************************************************
4182{{if .Pkgs}}
4183This file contains variables, rules, and pools with name prefixes indicating
4184they were generated by the following Go packages:
4185{{range .Pkgs}}
4186 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
4187
4188`
4189
4190var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07004191Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07004192Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004193Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004194Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004195Defined: {{.pos}}
4196`
4197
4198var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
4199Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07004200Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07004201`