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