blob: f131024c756a9ed4d67ec499b0f00032106f7100 [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"
19 "errors"
20 "fmt"
21 "io"
Jeff Gastonc3e28442017-08-09 15:13:12 -070022 "io/ioutil"
Jeff Gastonaca42202017-08-23 17:30:05 -070023 "os"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070024 "path/filepath"
25 "reflect"
Romain Guy28529652014-08-12 17:50:11 -070026 "runtime"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070027 "sort"
28 "strings"
Colin Cross127d2ea2016-11-01 11:10:51 -070029 "sync"
Colin Cross23d7aa12015-06-30 16:05:22 -070030 "sync/atomic"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070031 "text/scanner"
32 "text/template"
Colin Cross1fef5362015-04-20 16:50:54 -070033
34 "github.com/google/blueprint/parser"
Colin Crossb519a7e2017-02-01 13:21:35 -080035 "github.com/google/blueprint/pathtools"
Colin Cross1fef5362015-04-20 16:50:54 -070036 "github.com/google/blueprint/proptools"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070037)
38
39var ErrBuildActionsNotReady = errors.New("build actions are not ready")
40
41const maxErrors = 10
Jeff Gaston9f630902017-11-15 14:49:48 -080042const MockModuleListFile = "bplist"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070043
Jamie Gennisd4e10182014-06-12 20:06:50 -070044// A Context contains all the state needed to parse a set of Blueprints files
45// and generate a Ninja file. The process of generating a Ninja file proceeds
46// through a series of four phases. Each phase corresponds with a some methods
47// on the Context object
48//
49// Phase Methods
50// ------------ -------------------------------------------
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070051// 1. Registration RegisterModuleType, RegisterSingletonType
Jamie Gennisd4e10182014-06-12 20:06:50 -070052//
53// 2. Parse ParseBlueprintsFiles, Parse
54//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070055// 3. Generate ResolveDependencies, PrepareBuildActions
Jamie Gennisd4e10182014-06-12 20:06:50 -070056//
57// 4. Write WriteBuildFile
58//
59// The registration phase prepares the context to process Blueprints files
60// containing various types of modules. The parse phase reads in one or more
61// Blueprints files and validates their contents against the module types that
62// have been registered. The generate phase then analyzes the parsed Blueprints
63// contents to create an internal representation for the build actions that must
64// be performed. This phase also performs validation of the module dependencies
65// and property values defined in the parsed Blueprints files. Finally, the
66// write phase generates the Ninja manifest text based on the generated build
67// actions.
Jamie Gennis1bc967e2014-05-27 16:34:41 -070068type Context struct {
69 // set at instantiation
Colin Cross65569e42015-03-10 20:08:19 -070070 moduleFactories map[string]ModuleFactory
Jeff Gastond70bf752017-11-10 15:12:08 -080071 nameInterface NameInterface
Colin Cross0b7e83e2016-05-17 14:58:05 -070072 moduleGroups []*moduleGroup
Colin Cross65569e42015-03-10 20:08:19 -070073 moduleInfo map[Module]*moduleInfo
74 modulesSorted []*moduleInfo
Colin Cross5f03f112017-11-07 13:29:54 -080075 preSingletonInfo []*singletonInfo
Yuchen Wub9103ef2015-08-25 17:58:17 -070076 singletonInfo []*singletonInfo
Colin Cross65569e42015-03-10 20:08:19 -070077 mutatorInfo []*mutatorInfo
Colin Crossf8b50422016-08-10 12:56:40 -070078 earlyMutatorInfo []*mutatorInfo
Colin Cross65569e42015-03-10 20:08:19 -070079 variantMutatorNames []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070080
Colin Cross3702ac72016-08-11 11:09:00 -070081 depsModified uint32 // positive if a mutator modified the dependencies
82
Jamie Gennis1bc967e2014-05-27 16:34:41 -070083 dependenciesReady bool // set to true on a successful ResolveDependencies
84 buildActionsReady bool // set to true on a successful PrepareBuildActions
85
86 // set by SetIgnoreUnknownModuleTypes
87 ignoreUnknownModuleTypes bool
88
Colin Cross036a1df2015-12-17 15:49:30 -080089 // set by SetAllowMissingDependencies
90 allowMissingDependencies bool
91
Jamie Gennis1bc967e2014-05-27 16:34:41 -070092 // set during PrepareBuildActions
Dan Willemsenaeffbf72015-11-25 15:29:32 -080093 pkgNames map[*packageContext]string
Colin Cross5f03f112017-11-07 13:29:54 -080094 liveGlobals *liveTracker
Jamie Gennis1bc967e2014-05-27 16:34:41 -070095 globalVariables map[Variable]*ninjaString
96 globalPools map[Pool]*poolDef
97 globalRules map[Rule]*ruleDef
98
99 // set during PrepareBuildActions
Colin Crossa2599452015-11-18 16:01:01 -0800100 ninjaBuildDir *ninjaString // The builddir special Ninja variable
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700101 requiredNinjaMajor int // For the ninja_required_version variable
102 requiredNinjaMinor int // For the ninja_required_version variable
103 requiredNinjaMicro int // For the ninja_required_version variable
Jamie Gennisc15544d2014-09-24 20:26:52 -0700104
Jeff Gastond70bf752017-11-10 15:12:08 -0800105 // set lazily by sortedModuleGroups
106 cachedSortedModuleGroups []*moduleGroup
Colin Crossd7b0f602016-06-02 15:30:20 -0700107
Colin Cross127d2ea2016-11-01 11:10:51 -0700108 globs map[string]GlobPath
109 globLock sync.Mutex
110
Jeff Gastonc3e28442017-08-09 15:13:12 -0700111 fs pathtools.FileSystem
112 moduleListFile string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700113}
114
Jamie Gennisd4e10182014-06-12 20:06:50 -0700115// An Error describes a problem that was encountered that is related to a
116// particular location in a Blueprints file.
Colin Cross2c628442016-10-07 17:13:10 -0700117type BlueprintError struct {
Jamie Gennisd4e10182014-06-12 20:06:50 -0700118 Err error // the error that occurred
119 Pos scanner.Position // the relevant Blueprints file location
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700120}
121
Colin Cross2c628442016-10-07 17:13:10 -0700122// A ModuleError describes a problem that was encountered that is related to a
123// particular module in a Blueprints file
124type ModuleError struct {
125 BlueprintError
126 module *moduleInfo
127}
128
129// A PropertyError describes a problem that was encountered that is related to a
130// particular property in a Blueprints file
131type PropertyError struct {
132 ModuleError
133 property string
134}
135
136func (e *BlueprintError) Error() string {
137 return fmt.Sprintf("%s: %s", e.Pos, e.Err)
138}
139
140func (e *ModuleError) Error() string {
141 return fmt.Sprintf("%s: %s: %s", e.Pos, e.module, e.Err)
142}
143
144func (e *PropertyError) Error() string {
145 return fmt.Sprintf("%s: %s: %s: %s", e.Pos, e.module, e.property, e.Err)
146}
147
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700148type localBuildActions struct {
149 variables []*localVariable
150 rules []*localRule
151 buildDefs []*buildDef
152}
153
Colin Crossbbfa51a2014-12-17 16:12:41 -0800154type moduleGroup struct {
Colin Crossed342d92015-03-11 00:57:25 -0700155 name string
156 ninjaName string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700157
Colin Crossbbfa51a2014-12-17 16:12:41 -0800158 modules []*moduleInfo
Jeff Gastond70bf752017-11-10 15:12:08 -0800159
160 namespace Namespace
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700161}
162
Colin Crossbbfa51a2014-12-17 16:12:41 -0800163type moduleInfo struct {
Colin Crossed342d92015-03-11 00:57:25 -0700164 // set during Parse
165 typeName string
Colin Crossaf4fd212017-07-28 14:32:36 -0700166 factory ModuleFactory
Colin Crossed342d92015-03-11 00:57:25 -0700167 relBlueprintsFile string
168 pos scanner.Position
169 propertyPos map[string]scanner.Position
Colin Crossed342d92015-03-11 00:57:25 -0700170
Colin Crossf5e34b92015-03-13 16:02:36 -0700171 variantName string
172 variant variationMap
173 dependencyVariant variationMap
Colin Crosse7daa222015-03-11 14:35:41 -0700174
Colin Crossd2f4ac12017-07-28 14:31:03 -0700175 logicModule Module
176 group *moduleGroup
177 properties []interface{}
Colin Crossc9028482014-12-18 16:28:54 -0800178
179 // set during ResolveDependencies
Colin Cross2c1f3d12016-04-11 15:47:28 -0700180 directDeps []depInfo
Colin Cross036a1df2015-12-17 15:49:30 -0800181 missingDeps []string
Colin Crossc9028482014-12-18 16:28:54 -0800182
Colin Cross7addea32015-03-11 15:43:52 -0700183 // set during updateDependencies
184 reverseDeps []*moduleInfo
Colin Cross3702ac72016-08-11 11:09:00 -0700185 forwardDeps []*moduleInfo
Colin Cross7addea32015-03-11 15:43:52 -0700186
187 // used by parallelVisitAllBottomUp
188 waitingCount int
189
Colin Crossc9028482014-12-18 16:28:54 -0800190 // set during each runMutator
191 splitModules []*moduleInfo
Colin Crossab6d7902015-03-11 16:17:52 -0700192
193 // set during PrepareBuildActions
194 actionDefs localBuildActions
Colin Crossc9028482014-12-18 16:28:54 -0800195}
196
Colin Cross2c1f3d12016-04-11 15:47:28 -0700197type depInfo struct {
198 module *moduleInfo
199 tag DependencyTag
200}
201
Colin Cross0b7e83e2016-05-17 14:58:05 -0700202func (module *moduleInfo) Name() string {
203 return module.group.name
204}
205
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800206func (module *moduleInfo) String() string {
Colin Cross0b7e83e2016-05-17 14:58:05 -0700207 s := fmt.Sprintf("module %q", module.Name())
Colin Cross0aa6a5f2016-01-07 13:43:09 -0800208 if module.variantName != "" {
209 s += fmt.Sprintf(" variant %q", module.variantName)
210 }
211 return s
212}
213
Jeff Gastond70bf752017-11-10 15:12:08 -0800214func (module *moduleInfo) namespace() Namespace {
215 return module.group.namespace
216}
217
Colin Crossf5e34b92015-03-13 16:02:36 -0700218// A Variation is a way that a variant of a module differs from other variants of the same module.
219// For example, two variants of the same module might have Variation{"arch","arm"} and
220// Variation{"arch","arm64"}
221type Variation struct {
222 // Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Colin Cross65569e42015-03-10 20:08:19 -0700223 Mutator string
Colin Crossf5e34b92015-03-13 16:02:36 -0700224 // Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
225 // "shared" or "static" for link.
226 Variation string
Colin Cross65569e42015-03-10 20:08:19 -0700227}
228
Colin Crossf5e34b92015-03-13 16:02:36 -0700229// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
230type variationMap map[string]string
Colin Crosse7daa222015-03-11 14:35:41 -0700231
Colin Crossf5e34b92015-03-13 16:02:36 -0700232func (vm variationMap) clone() variationMap {
233 newVm := make(variationMap)
Colin Crosse7daa222015-03-11 14:35:41 -0700234 for k, v := range vm {
235 newVm[k] = v
236 }
237
238 return newVm
Colin Crossc9028482014-12-18 16:28:54 -0800239}
240
Colin Cross89486232015-05-08 11:14:54 -0700241// Compare this variationMap to another one. Returns true if the every entry in this map
242// is either the same in the other map or doesn't exist in the other map.
243func (vm variationMap) subset(other variationMap) bool {
244 for k, v1 := range vm {
245 if v2, ok := other[k]; ok && v1 != v2 {
246 return false
247 }
248 }
249 return true
250}
251
Colin Crossf5e34b92015-03-13 16:02:36 -0700252func (vm variationMap) equal(other variationMap) bool {
Colin Crosse7daa222015-03-11 14:35:41 -0700253 return reflect.DeepEqual(vm, other)
Colin Crossbbfa51a2014-12-17 16:12:41 -0800254}
255
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700256type singletonInfo struct {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700257 // set during RegisterSingletonType
258 factory SingletonFactory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700259 singleton Singleton
Yuchen Wub9103ef2015-08-25 17:58:17 -0700260 name string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700261
262 // set during PrepareBuildActions
263 actionDefs localBuildActions
264}
265
Colin Crossc9028482014-12-18 16:28:54 -0800266type mutatorInfo struct {
267 // set during RegisterMutator
Colin Crossc0dbc552015-01-02 15:19:28 -0800268 topDownMutator TopDownMutator
269 bottomUpMutator BottomUpMutator
270 name string
Colin Cross49c279a2016-08-05 22:30:44 -0700271 parallel bool
Colin Crossc9028482014-12-18 16:28:54 -0800272}
273
Colin Crossaf4fd212017-07-28 14:32:36 -0700274func newContext() *Context {
275 return &Context{
Colin Cross5f03f112017-11-07 13:29:54 -0800276 moduleFactories: make(map[string]ModuleFactory),
Jeff Gastond70bf752017-11-10 15:12:08 -0800277 nameInterface: NewSimpleNameInterface(),
Colin Cross5f03f112017-11-07 13:29:54 -0800278 moduleInfo: make(map[Module]*moduleInfo),
Colin Cross5f03f112017-11-07 13:29:54 -0800279 globs: make(map[string]GlobPath),
280 fs: pathtools.OsFs,
281 ninjaBuildDir: nil,
282 requiredNinjaMajor: 1,
283 requiredNinjaMinor: 7,
284 requiredNinjaMicro: 0,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700285 }
Colin Crossaf4fd212017-07-28 14:32:36 -0700286}
287
288// NewContext creates a new Context object. The created context initially has
289// no module or singleton factories registered, so the RegisterModuleFactory and
290// RegisterSingletonFactory methods must be called before it can do anything
291// useful.
292func NewContext() *Context {
293 ctx := newContext()
Colin Cross763b6f12015-10-29 15:32:56 -0700294
295 ctx.RegisterBottomUpMutator("blueprint_deps", blueprintDepsMutator)
296
297 return ctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700298}
299
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700300// A ModuleFactory function creates a new Module object. See the
301// Context.RegisterModuleType method for details about how a registered
302// ModuleFactory is used by a Context.
303type ModuleFactory func() (m Module, propertyStructs []interface{})
304
Jamie Gennisd4e10182014-06-12 20:06:50 -0700305// RegisterModuleType associates a module type name (which can appear in a
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700306// Blueprints file) with a Module factory function. When the given module type
307// name is encountered in a Blueprints file during parsing, the Module factory
308// is invoked to instantiate a new Module object to handle the build action
Colin Crossc9028482014-12-18 16:28:54 -0800309// generation for the module. If a Mutator splits a module into multiple variants,
310// the factory is invoked again to create a new Module for each variant.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700311//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700312// The module type names given here must be unique for the context. The factory
313// function should be a named function so that its package and name can be
314// included in the generated Ninja file for debugging purposes.
315//
316// The factory function returns two values. The first is the newly created
317// Module object. The second is a slice of pointers to that Module object's
318// properties structs. Each properties struct is examined when parsing a module
319// definition of this type in a Blueprints file. Exported fields of the
320// properties structs are automatically set to the property values specified in
321// the Blueprints file. The properties struct field names determine the name of
322// the Blueprints file properties that are used - the Blueprints property name
323// matches that of the properties struct field name with the first letter
324// converted to lower-case.
325//
326// The fields of the properties struct must be either []string, a string, or
327// bool. The Context will panic if a Module gets instantiated with a properties
328// struct containing a field that is not one these supported types.
329//
330// Any properties that appear in the Blueprints files that are not built-in
331// module properties (such as "name" and "deps") and do not have a corresponding
332// field in the returned module properties struct result in an error during the
333// Context's parse phase.
334//
335// As an example, the follow code:
336//
337// type myModule struct {
338// properties struct {
339// Foo string
340// Bar []string
341// }
342// }
343//
344// func NewMyModule() (blueprint.Module, []interface{}) {
345// module := new(myModule)
346// properties := &module.properties
347// return module, []interface{}{properties}
348// }
349//
350// func main() {
351// ctx := blueprint.NewContext()
352// ctx.RegisterModuleType("my_module", NewMyModule)
353// // ...
354// }
355//
356// would support parsing a module defined in a Blueprints file as follows:
357//
358// my_module {
359// name: "myName",
360// foo: "my foo string",
361// bar: ["my", "bar", "strings"],
362// }
363//
Colin Cross7ad621c2015-01-07 16:22:45 -0800364// The factory function may be called from multiple goroutines. Any accesses
365// to global variables must be synchronized.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700366func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
367 if _, present := c.moduleFactories[name]; present {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700368 panic(errors.New("module type name is already registered"))
369 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700370 c.moduleFactories[name] = factory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700371}
372
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700373// A SingletonFactory function creates a new Singleton object. See the
374// Context.RegisterSingletonType method for details about how a registered
375// SingletonFactory is used by a Context.
376type SingletonFactory func() Singleton
377
378// RegisterSingletonType registers a singleton type that will be invoked to
379// generate build actions. Each registered singleton type is instantiated and
Yuchen Wub9103ef2015-08-25 17:58:17 -0700380// and invoked exactly once as part of the generate phase. Each registered
381// singleton is invoked in registration order.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700382//
383// The singleton type names given here must be unique for the context. The
384// factory function should be a named function so that its package and name can
385// be included in the generated Ninja file for debugging purposes.
386func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
Yuchen Wub9103ef2015-08-25 17:58:17 -0700387 for _, s := range c.singletonInfo {
388 if s.name == name {
389 panic(errors.New("singleton name is already registered"))
390 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700391 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700392
Yuchen Wub9103ef2015-08-25 17:58:17 -0700393 c.singletonInfo = append(c.singletonInfo, &singletonInfo{
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700394 factory: factory,
395 singleton: factory(),
Yuchen Wub9103ef2015-08-25 17:58:17 -0700396 name: name,
397 })
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700398}
399
Colin Cross5f03f112017-11-07 13:29:54 -0800400// RegisterPreSingletonType registers a presingleton type that will be invoked to
401// generate build actions before any Blueprint files have been read. Each registered
402// presingleton type is instantiated and invoked exactly once at the beginning of the
403// parse phase. Each registered presingleton is invoked in registration order.
404//
405// The presingleton type names given here must be unique for the context. The
406// factory function should be a named function so that its package and name can
407// be included in the generated Ninja file for debugging purposes.
408func (c *Context) RegisterPreSingletonType(name string, factory SingletonFactory) {
409 for _, s := range c.preSingletonInfo {
410 if s.name == name {
411 panic(errors.New("presingleton name is already registered"))
412 }
413 }
414
415 c.preSingletonInfo = append(c.preSingletonInfo, &singletonInfo{
416 factory: factory,
417 singleton: factory(),
418 name: name,
419 })
420}
421
Jeff Gastond70bf752017-11-10 15:12:08 -0800422func (c *Context) SetNameInterface(i NameInterface) {
423 c.nameInterface = i
424}
425
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700426func singletonPkgPath(singleton Singleton) string {
427 typ := reflect.TypeOf(singleton)
428 for typ.Kind() == reflect.Ptr {
429 typ = typ.Elem()
430 }
431 return typ.PkgPath()
432}
433
434func singletonTypeName(singleton Singleton) string {
435 typ := reflect.TypeOf(singleton)
436 for typ.Kind() == reflect.Ptr {
437 typ = typ.Elem()
438 }
439 return typ.PkgPath() + "." + typ.Name()
440}
441
Colin Cross3702ac72016-08-11 11:09:00 -0700442// RegisterTopDownMutator registers a mutator that will be invoked to propagate dependency info
443// top-down between Modules. Each registered mutator is invoked in registration order (mixing
444// TopDownMutators and BottomUpMutators) once per Module, and the invocation on any module will
445// have returned before it is in invoked on any of its dependencies.
Colin Crossc9028482014-12-18 16:28:54 -0800446//
Colin Cross65569e42015-03-10 20:08:19 -0700447// The mutator type names given here must be unique to all top down mutators in
448// the Context.
Colin Cross3702ac72016-08-11 11:09:00 -0700449//
450// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
451// parallel while maintaining ordering.
452func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) MutatorHandle {
Colin Crossc9028482014-12-18 16:28:54 -0800453 for _, m := range c.mutatorInfo {
454 if m.name == name && m.topDownMutator != nil {
455 panic(fmt.Errorf("mutator name %s is already registered", name))
456 }
457 }
458
Colin Cross3702ac72016-08-11 11:09:00 -0700459 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800460 topDownMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800461 name: name,
Colin Cross3702ac72016-08-11 11:09:00 -0700462 }
463
464 c.mutatorInfo = append(c.mutatorInfo, info)
465
466 return info
Colin Crossc9028482014-12-18 16:28:54 -0800467}
468
Colin Cross3702ac72016-08-11 11:09:00 -0700469// RegisterBottomUpMutator registers a mutator that will be invoked to split Modules into variants.
470// Each registered mutator is invoked in registration order (mixing TopDownMutators and
471// BottomUpMutators) once per Module, will not be invoked on a module until the invocations on all
472// of the modules dependencies have returned.
Colin Crossc9028482014-12-18 16:28:54 -0800473//
Colin Cross65569e42015-03-10 20:08:19 -0700474// The mutator type names given here must be unique to all bottom up or early
475// mutators in the Context.
Colin Cross49c279a2016-08-05 22:30:44 -0700476//
Colin Cross3702ac72016-08-11 11:09:00 -0700477// Returns a MutatorHandle, on which Parallel can be called to set the mutator to visit modules in
478// parallel while maintaining ordering.
479func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) MutatorHandle {
Colin Cross65569e42015-03-10 20:08:19 -0700480 for _, m := range c.variantMutatorNames {
481 if m == name {
Colin Crossc9028482014-12-18 16:28:54 -0800482 panic(fmt.Errorf("mutator name %s is already registered", name))
483 }
484 }
485
Colin Cross49c279a2016-08-05 22:30:44 -0700486 info := &mutatorInfo{
Colin Crossc9028482014-12-18 16:28:54 -0800487 bottomUpMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800488 name: name,
Colin Cross49c279a2016-08-05 22:30:44 -0700489 }
490 c.mutatorInfo = append(c.mutatorInfo, info)
Colin Cross65569e42015-03-10 20:08:19 -0700491
492 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Cross49c279a2016-08-05 22:30:44 -0700493
494 return info
495}
496
Colin Cross3702ac72016-08-11 11:09:00 -0700497type MutatorHandle interface {
498 // Set the mutator to visit modules in parallel while maintaining ordering. Calling any
499 // method on the mutator context is thread-safe, but the mutator must handle synchronization
500 // for any modifications to global state or any modules outside the one it was invoked on.
501 Parallel() MutatorHandle
Colin Cross49c279a2016-08-05 22:30:44 -0700502}
503
Colin Cross3702ac72016-08-11 11:09:00 -0700504func (mutator *mutatorInfo) Parallel() MutatorHandle {
Colin Cross49c279a2016-08-05 22:30:44 -0700505 mutator.parallel = true
506 return mutator
Colin Cross65569e42015-03-10 20:08:19 -0700507}
508
509// RegisterEarlyMutator registers a mutator that will be invoked to split
510// Modules into multiple variant Modules before any dependencies have been
511// created. Each registered mutator is invoked in registration order once
512// per Module (including each variant from previous early mutators). Module
513// order is unpredictable.
514//
515// In order for dependencies to be satisifed in a later pass, all dependencies
Colin Crossf5e34b92015-03-13 16:02:36 -0700516// of a module either must have an identical variant or must have no variations.
Colin Cross65569e42015-03-10 20:08:19 -0700517//
518// The mutator type names given here must be unique to all bottom up or early
519// mutators in the Context.
Colin Cross763b6f12015-10-29 15:32:56 -0700520//
521// Deprecated, use a BottomUpMutator instead. The only difference between
522// EarlyMutator and BottomUpMutator is that EarlyMutator runs before the
523// deprecated DynamicDependencies.
Colin Cross65569e42015-03-10 20:08:19 -0700524func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
525 for _, m := range c.variantMutatorNames {
526 if m == name {
527 panic(fmt.Errorf("mutator name %s is already registered", name))
528 }
529 }
530
Colin Crossf8b50422016-08-10 12:56:40 -0700531 c.earlyMutatorInfo = append(c.earlyMutatorInfo, &mutatorInfo{
532 bottomUpMutator: func(mctx BottomUpMutatorContext) {
533 mutator(mctx)
534 },
535 name: name,
Colin Cross65569e42015-03-10 20:08:19 -0700536 })
537
538 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Crossc9028482014-12-18 16:28:54 -0800539}
540
Jamie Gennisd4e10182014-06-12 20:06:50 -0700541// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
542// where it encounters an unknown module type while parsing Blueprints files. By
543// default, the context will report unknown module types as an error. If this
544// method is called with ignoreUnknownModuleTypes set to true then the context
545// will silently ignore unknown module types.
546//
547// This method should generally not be used. It exists to facilitate the
548// bootstrapping process.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700549func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
550 c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
551}
552
Colin Cross036a1df2015-12-17 15:49:30 -0800553// SetAllowMissingDependencies changes the behavior of Blueprint to ignore
554// unresolved dependencies. If the module's GenerateBuildActions calls
555// ModuleContext.GetMissingDependencies Blueprint will not emit any errors
556// for missing dependencies.
557func (c *Context) SetAllowMissingDependencies(allowMissingDependencies bool) {
558 c.allowMissingDependencies = allowMissingDependencies
559}
560
Jeff Gastonc3e28442017-08-09 15:13:12 -0700561func (c *Context) SetModuleListFile(listFile string) {
562 c.moduleListFile = listFile
563}
564
565func (c *Context) ListModulePaths(baseDir string) (paths []string, err error) {
566 reader, err := c.fs.Open(c.moduleListFile)
567 if err != nil {
568 return nil, err
569 }
570 bytes, err := ioutil.ReadAll(reader)
571 if err != nil {
572 return nil, err
573 }
574 text := string(bytes)
575
576 text = strings.Trim(text, "\n")
577 lines := strings.Split(text, "\n")
578 for i := range lines {
579 lines[i] = filepath.Join(baseDir, lines[i])
580 }
581
582 return lines, nil
583}
584
Jeff Gaston656870f2017-11-29 18:37:31 -0800585// a fileParseContext tells the status of parsing a particular file
586type fileParseContext struct {
587 // name of file
588 fileName string
589
590 // scope to use when resolving variables
591 Scope *parser.Scope
592
593 // pointer to the one in the parent directory
594 parent *fileParseContext
595
596 // is closed once FileHandler has completed for this file
597 doneVisiting chan struct{}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700598}
599
Jeff Gastonc3e28442017-08-09 15:13:12 -0700600func (c *Context) ParseBlueprintsFiles(rootFile string) (deps []string, errs []error) {
601 baseDir := filepath.Dir(rootFile)
602 pathsToParse, err := c.ListModulePaths(baseDir)
603 if err != nil {
604 return nil, []error{err}
605 }
606 return c.ParseFileList(baseDir, pathsToParse)
607}
608
Jamie Gennisd4e10182014-06-12 20:06:50 -0700609// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
610// at rootFile. When it encounters a Blueprints file with a set of subdirs
611// listed it recursively parses any Blueprints files found in those
612// subdirectories.
613//
614// If no errors are encountered while parsing the files, the list of paths on
615// which the future output will depend is returned. This list will include both
616// Blueprints file paths as well as directory paths for cases where wildcard
617// subdirs are found.
Jeff Gastonc3e28442017-08-09 15:13:12 -0700618func (c *Context) ParseFileList(rootDir string, filePaths []string) (deps []string,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700619 errs []error) {
620
Jeff Gastonc3e28442017-08-09 15:13:12 -0700621 if len(filePaths) < 1 {
622 return nil, []error{fmt.Errorf("no paths provided to parse")}
623 }
624
Colin Cross7ad621c2015-01-07 16:22:45 -0800625 c.dependenciesReady = false
626
Colin Cross23d7aa12015-06-30 16:05:22 -0700627 moduleCh := make(chan *moduleInfo)
628 errsCh := make(chan []error)
629 doneCh := make(chan struct{})
630 var numErrs uint32
631 var numGoroutines int32
632
633 // handler must be reentrant
Jeff Gaston5f763d02017-08-08 14:43:58 -0700634 handleOneFile := func(file *parser.File) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700635 if atomic.LoadUint32(&numErrs) > maxErrors {
636 return
637 }
638
Jeff Gaston656870f2017-11-29 18:37:31 -0800639 for _, def := range file.Defs {
640 var module *moduleInfo
641 var errs []error
642 switch def := def.(type) {
643 case *parser.Module:
644 module, errs = c.processModuleDef(def, file.Name)
645 case *parser.Assignment:
646 // Already handled via Scope object
647 default:
648 panic("unknown definition type")
Colin Cross23d7aa12015-06-30 16:05:22 -0700649 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800650
651 if len(errs) > 0 {
652 atomic.AddUint32(&numErrs, uint32(len(errs)))
653 errsCh <- errs
654 } else if module != nil {
655 moduleCh <- module
656 }
657 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700658 }
659
660 atomic.AddInt32(&numGoroutines, 1)
661 go func() {
662 var errs []error
Jeff Gastonc3e28442017-08-09 15:13:12 -0700663 deps, errs = c.WalkBlueprintsFiles(rootDir, filePaths, handleOneFile)
Colin Cross23d7aa12015-06-30 16:05:22 -0700664 if len(errs) > 0 {
665 errsCh <- errs
666 }
667 doneCh <- struct{}{}
668 }()
669
670loop:
671 for {
672 select {
673 case newErrs := <-errsCh:
674 errs = append(errs, newErrs...)
675 case module := <-moduleCh:
676 newErrs := c.addModule(module)
677 if len(newErrs) > 0 {
678 errs = append(errs, newErrs...)
679 }
680 case <-doneCh:
681 n := atomic.AddInt32(&numGoroutines, -1)
682 if n == 0 {
683 break loop
684 }
685 }
686 }
687
688 return deps, errs
689}
690
691type FileHandler func(*parser.File)
692
Jeff Gastonc3e28442017-08-09 15:13:12 -0700693// WalkBlueprintsFiles walks a set of Blueprints files starting with the given filepaths,
694// calling the given file handler on each
695//
696// When WalkBlueprintsFiles encounters a Blueprints file with a set of subdirs listed,
697// it recursively parses any Blueprints files found in those subdirectories.
698//
699// If any of the file paths is an ancestor directory of any other of file path, the ancestor
700// will be parsed and visited first.
701//
702// the file handler will be called from a goroutine, so it must be reentrant.
Colin Cross23d7aa12015-06-30 16:05:22 -0700703//
704// If no errors are encountered while parsing the files, the list of paths on
705// which the future output will depend is returned. This list will include both
706// Blueprints file paths as well as directory paths for cases where wildcard
707// subdirs are found.
Jeff Gaston656870f2017-11-29 18:37:31 -0800708//
709// visitor will be called asynchronously, and will only be called once visitor for each
710// ancestor directory has completed.
711//
712// WalkBlueprintsFiles will not return until all calls to visitor have returned.
Jeff Gastonc3e28442017-08-09 15:13:12 -0700713func (c *Context) WalkBlueprintsFiles(rootDir string, filePaths []string,
714 visitor FileHandler) (deps []string, errs []error) {
Colin Cross23d7aa12015-06-30 16:05:22 -0700715
Jeff Gastonc3e28442017-08-09 15:13:12 -0700716 // make a mapping from ancestors to their descendants to facilitate parsing ancestors first
717 descendantsMap, err := findBlueprintDescendants(filePaths)
718 if err != nil {
719 panic(err.Error())
720 return nil, []error{err}
721 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800722 blueprintsSet := make(map[string]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700723
Jeff Gaston5800d042017-12-05 14:57:58 -0800724 // Channels to receive data back from openAndParse goroutines
Jeff Gaston656870f2017-11-29 18:37:31 -0800725 blueprintsCh := make(chan fileParseContext)
Colin Cross7ad621c2015-01-07 16:22:45 -0800726 errsCh := make(chan []error)
Colin Cross7ad621c2015-01-07 16:22:45 -0800727 depsCh := make(chan string)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700728
Jeff Gaston5800d042017-12-05 14:57:58 -0800729 // Channel to notify main loop that a openAndParse goroutine has finished
Jeff Gaston656870f2017-11-29 18:37:31 -0800730 doneParsingCh := make(chan fileParseContext)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700731
Colin Cross7ad621c2015-01-07 16:22:45 -0800732 // Number of outstanding goroutines to wait for
Jeff Gaston5f763d02017-08-08 14:43:58 -0700733 activeCount := 0
Jeff Gaston656870f2017-11-29 18:37:31 -0800734 var pending []fileParseContext
Jeff Gastonc3e28442017-08-09 15:13:12 -0700735 tooManyErrors := false
736
737 // Limit concurrent calls to parseBlueprintFiles to 200
738 // Darwin has a default limit of 256 open files
739 maxActiveCount := 200
Colin Cross7ad621c2015-01-07 16:22:45 -0800740
Jeff Gaston656870f2017-11-29 18:37:31 -0800741 // count the number of pending calls to visitor()
742 visitorWaitGroup := sync.WaitGroup{}
743
744 startParseBlueprintsFile := func(blueprint fileParseContext) {
745 if blueprintsSet[blueprint.fileName] {
Colin Cross4a02a302017-05-16 10:33:58 -0700746 return
747 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800748 blueprintsSet[blueprint.fileName] = true
Jeff Gaston5f763d02017-08-08 14:43:58 -0700749 activeCount++
Jeff Gaston656870f2017-11-29 18:37:31 -0800750 deps = append(deps, blueprint.fileName)
751 visitorWaitGroup.Add(1)
Colin Cross7ad621c2015-01-07 16:22:45 -0800752 go func() {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800753 file, blueprints, deps, errs := c.openAndParse(blueprint.fileName, blueprint.Scope, rootDir,
754 &blueprint)
755 if len(errs) > 0 {
756 errsCh <- errs
757 }
758 for _, blueprint := range blueprints {
759 blueprintsCh <- blueprint
760 }
761 for _, dep := range deps {
762 depsCh <- dep
763 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800764 doneParsingCh <- blueprint
Jeff Gaston5f763d02017-08-08 14:43:58 -0700765
Jeff Gaston656870f2017-11-29 18:37:31 -0800766 if blueprint.parent != nil && blueprint.parent.doneVisiting != nil {
767 // wait for visitor() of parent to complete
768 <-blueprint.parent.doneVisiting
769 }
770
Jeff Gastona7e408a2017-12-05 15:11:55 -0800771 if len(errs) == 0 {
772 // process this file
773 visitor(file)
774 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800775 if blueprint.doneVisiting != nil {
776 close(blueprint.doneVisiting)
777 }
778 visitorWaitGroup.Done()
Colin Cross7ad621c2015-01-07 16:22:45 -0800779 }()
780 }
781
Jeff Gaston656870f2017-11-29 18:37:31 -0800782 foundParseableBlueprint := func(blueprint fileParseContext) {
Jeff Gastonc3e28442017-08-09 15:13:12 -0700783 if activeCount >= maxActiveCount {
784 pending = append(pending, blueprint)
785 } else {
786 startParseBlueprintsFile(blueprint)
787 }
788 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800789
Jeff Gaston656870f2017-11-29 18:37:31 -0800790 startParseDescendants := func(blueprint fileParseContext) {
791 descendants, hasDescendants := descendantsMap[blueprint.fileName]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700792 if hasDescendants {
793 for _, descendant := range descendants {
Jeff Gaston656870f2017-11-29 18:37:31 -0800794 foundParseableBlueprint(fileParseContext{descendant, parser.NewScope(blueprint.Scope), &blueprint, make(chan struct{})})
Jeff Gastonc3e28442017-08-09 15:13:12 -0700795 }
796 }
797 }
Colin Cross4a02a302017-05-16 10:33:58 -0700798
Jeff Gastonc3e28442017-08-09 15:13:12 -0700799 // begin parsing any files that have no ancestors
Jeff Gaston656870f2017-11-29 18:37:31 -0800800 startParseDescendants(fileParseContext{"", parser.NewScope(nil), nil, nil})
Colin Cross7ad621c2015-01-07 16:22:45 -0800801
802loop:
803 for {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700804 if len(errs) > maxErrors {
Colin Cross7ad621c2015-01-07 16:22:45 -0800805 tooManyErrors = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700806 }
807
Colin Cross7ad621c2015-01-07 16:22:45 -0800808 select {
809 case newErrs := <-errsCh:
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700810 errs = append(errs, newErrs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800811 case dep := <-depsCh:
812 deps = append(deps, dep)
Colin Cross7ad621c2015-01-07 16:22:45 -0800813 case blueprint := <-blueprintsCh:
814 if tooManyErrors {
815 continue
816 }
Jeff Gastonc3e28442017-08-09 15:13:12 -0700817 foundParseableBlueprint(blueprint)
Jeff Gaston656870f2017-11-29 18:37:31 -0800818 case blueprint := <-doneParsingCh:
Jeff Gaston5f763d02017-08-08 14:43:58 -0700819 activeCount--
Jeff Gastonc3e28442017-08-09 15:13:12 -0700820 if !tooManyErrors {
821 startParseDescendants(blueprint)
822 }
823 if activeCount < maxActiveCount && len(pending) > 0 {
824 // start to process the next one from the queue
825 next := pending[len(pending)-1]
Colin Cross4a02a302017-05-16 10:33:58 -0700826 pending = pending[:len(pending)-1]
Jeff Gastonc3e28442017-08-09 15:13:12 -0700827 startParseBlueprintsFile(next)
Colin Cross4a02a302017-05-16 10:33:58 -0700828 }
Jeff Gaston5f763d02017-08-08 14:43:58 -0700829 if activeCount == 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -0800830 break loop
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700831 }
832 }
833 }
834
Jeff Gastonc3e28442017-08-09 15:13:12 -0700835 sort.Strings(deps)
836
Jeff Gaston656870f2017-11-29 18:37:31 -0800837 // wait for every visitor() to complete
838 visitorWaitGroup.Wait()
839
Colin Cross7ad621c2015-01-07 16:22:45 -0800840 return
841}
842
Colin Crossd7b0f602016-06-02 15:30:20 -0700843// MockFileSystem causes the Context to replace all reads with accesses to the provided map of
844// filenames to contents stored as a byte slice.
845func (c *Context) MockFileSystem(files map[string][]byte) {
Jeff Gaston9f630902017-11-15 14:49:48 -0800846 // look for a module list file
847 _, ok := files[MockModuleListFile]
848 if !ok {
849 // no module list file specified; find every file named Blueprints
850 pathsToParse := []string{}
851 for candidate := range files {
852 if filepath.Base(candidate) == "Blueprints" {
853 pathsToParse = append(pathsToParse, candidate)
854 }
Jeff Gastonc3e28442017-08-09 15:13:12 -0700855 }
Jeff Gaston9f630902017-11-15 14:49:48 -0800856 if len(pathsToParse) < 1 {
857 panic(fmt.Sprintf("No Blueprints files found in mock filesystem: %v\n", files))
858 }
859 // put the list of Blueprints files into a list file
860 files[MockModuleListFile] = []byte(strings.Join(pathsToParse, "\n"))
Jeff Gastonc3e28442017-08-09 15:13:12 -0700861 }
Jeff Gaston9f630902017-11-15 14:49:48 -0800862 c.SetModuleListFile(MockModuleListFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -0700863
864 // mock the filesystem
Colin Crossb519a7e2017-02-01 13:21:35 -0800865 c.fs = pathtools.MockFs(files)
Colin Crossd7b0f602016-06-02 15:30:20 -0700866}
867
Jeff Gaston8fd95782017-12-05 15:03:51 -0800868// openAndParse opens and parses a single Blueprints file, and returns the results
Jeff Gaston5800d042017-12-05 14:57:58 -0800869func (c *Context) openAndParse(filename string, scope *parser.Scope, rootDir string,
Jeff Gaston8fd95782017-12-05 15:03:51 -0800870 parent *fileParseContext) (file *parser.File,
871 subBlueprints []fileParseContext, deps []string, errs []error) {
Colin Cross7ad621c2015-01-07 16:22:45 -0800872
Colin Crossd7b0f602016-06-02 15:30:20 -0700873 f, err := c.fs.Open(filename)
Colin Cross7ad621c2015-01-07 16:22:45 -0800874 if err != nil {
Jeff Gastonaca42202017-08-23 17:30:05 -0700875 // couldn't open the file; see if we can provide a clearer error than "could not open file"
876 stats, statErr := c.fs.Lstat(filename)
877 if statErr == nil {
878 isSymlink := stats.Mode()&os.ModeSymlink != 0
879 if isSymlink {
880 err = fmt.Errorf("could not open symlink %v : %v", filename, err)
881 target, readlinkErr := os.Readlink(filename)
882 if readlinkErr == nil {
883 _, targetStatsErr := c.fs.Lstat(target)
884 if targetStatsErr != nil {
885 err = fmt.Errorf("could not open symlink %v; its target (%v) cannot be opened", filename, target)
886 }
887 }
888 } else {
889 err = fmt.Errorf("%v exists but could not be opened: %v", filename, err)
890 }
891 }
Jeff Gaston8fd95782017-12-05 15:03:51 -0800892 return nil, nil, nil, []error{err}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700893 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800894
Jeff Gaston8fd95782017-12-05 15:03:51 -0800895 func() {
896 defer func() {
897 err = f.Close()
898 if err != nil {
899 errs = append(errs, err)
900 }
901 }()
902 file, subBlueprints, errs = c.parseOne(rootDir, filename, f, scope, parent)
Colin Cross23d7aa12015-06-30 16:05:22 -0700903 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700904
Colin Cross7ad621c2015-01-07 16:22:45 -0800905 if len(errs) > 0 {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800906 return nil, nil, nil, errs
Colin Cross7ad621c2015-01-07 16:22:45 -0800907 }
908
Colin Cross1fef5362015-04-20 16:50:54 -0700909 for _, b := range subBlueprints {
Jeff Gaston8fd95782017-12-05 15:03:51 -0800910 deps = append(deps, b.fileName)
Colin Cross1fef5362015-04-20 16:50:54 -0700911 }
Jeff Gaston656870f2017-11-29 18:37:31 -0800912
Jeff Gaston8fd95782017-12-05 15:03:51 -0800913 return file, subBlueprints, deps, nil
Colin Cross1fef5362015-04-20 16:50:54 -0700914}
915
Jeff Gastona12f22f2017-08-08 14:45:56 -0700916// parseOne parses a single Blueprints file from the given reader, creating Module
917// objects for each of the module definitions encountered. If the Blueprints
918// file contains an assignment to the "subdirs" variable, then the
919// subdirectories listed are searched for Blueprints files returned in the
920// subBlueprints return value. If the Blueprints file contains an assignment
921// to the "build" variable, then the file listed are returned in the
922// subBlueprints return value.
923//
924// rootDir specifies the path to the root directory of the source tree, while
925// filename specifies the path to the Blueprints file. These paths are used for
926// error reporting and for determining the module's directory.
927func (c *Context) parseOne(rootDir, filename string, reader io.Reader,
Jeff Gaston656870f2017-11-29 18:37:31 -0800928 scope *parser.Scope, parent *fileParseContext) (file *parser.File, subBlueprints []fileParseContext, errs []error) {
Jeff Gastona12f22f2017-08-08 14:45:56 -0700929
930 relBlueprintsFile, err := filepath.Rel(rootDir, filename)
931 if err != nil {
932 return nil, nil, []error{err}
933 }
934
Jeff Gastona12f22f2017-08-08 14:45:56 -0700935 scope.Remove("subdirs")
936 scope.Remove("optional_subdirs")
937 scope.Remove("build")
938 file, errs = parser.ParseAndEval(filename, reader, scope)
939 if len(errs) > 0 {
940 for i, err := range errs {
941 if parseErr, ok := err.(*parser.ParseError); ok {
942 err = &BlueprintError{
943 Err: parseErr.Err,
944 Pos: parseErr.Pos,
945 }
946 errs[i] = err
947 }
948 }
949
950 // If there were any parse errors don't bother trying to interpret the
951 // result.
952 return nil, nil, errs
953 }
954 file.Name = relBlueprintsFile
955
Jeff Gastona12f22f2017-08-08 14:45:56 -0700956 build, buildPos, err := getLocalStringListFromScope(scope, "build")
957 if err != nil {
958 errs = append(errs, err)
959 }
Jeff Gastonf23e3662017-11-30 17:31:43 -0800960 for _, buildEntry := range build {
961 if strings.Contains(buildEntry, "/") {
962 errs = append(errs, &BlueprintError{
963 Err: fmt.Errorf("illegal value %v. The '/' character is not permitted", buildEntry),
964 Pos: buildPos,
965 })
966 }
967 }
Jeff Gastona12f22f2017-08-08 14:45:56 -0700968
969 subBlueprintsName, _, err := getStringFromScope(scope, "subname")
970 if err != nil {
971 errs = append(errs, err)
972 }
973
974 if subBlueprintsName == "" {
975 subBlueprintsName = "Blueprints"
976 }
977
978 var blueprints []string
979
980 newBlueprints, newErrs := c.findBuildBlueprints(filepath.Dir(filename), build, buildPos)
981 blueprints = append(blueprints, newBlueprints...)
982 errs = append(errs, newErrs...)
983
Jeff Gaston656870f2017-11-29 18:37:31 -0800984 subBlueprintsAndScope := make([]fileParseContext, len(blueprints))
Jeff Gastona12f22f2017-08-08 14:45:56 -0700985 for i, b := range blueprints {
Jeff Gaston656870f2017-11-29 18:37:31 -0800986 subBlueprintsAndScope[i] = fileParseContext{b, parser.NewScope(scope), parent, make(chan struct{})}
Jeff Gastona12f22f2017-08-08 14:45:56 -0700987 }
Jeff Gastona12f22f2017-08-08 14:45:56 -0700988 return file, subBlueprintsAndScope, errs
989}
990
Colin Cross7f507402015-12-16 13:03:41 -0800991func (c *Context) findBuildBlueprints(dir string, build []string,
Colin Cross127d2ea2016-11-01 11:10:51 -0700992 buildPos scanner.Position) ([]string, []error) {
993
994 var blueprints []string
995 var errs []error
Colin Cross7f507402015-12-16 13:03:41 -0800996
997 for _, file := range build {
Colin Cross127d2ea2016-11-01 11:10:51 -0700998 pattern := filepath.Join(dir, file)
999 var matches []string
1000 var err error
1001
Colin Cross08e49542016-11-14 15:23:33 -08001002 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001003
Colin Cross7f507402015-12-16 13:03:41 -08001004 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001005 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001006 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross7f507402015-12-16 13:03:41 -08001007 Pos: buildPos,
1008 })
1009 continue
1010 }
1011
1012 if len(matches) == 0 {
Colin Cross2c628442016-10-07 17:13:10 -07001013 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001014 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross7f507402015-12-16 13:03:41 -08001015 Pos: buildPos,
1016 })
1017 }
1018
Colin Cross7f507402015-12-16 13:03:41 -08001019 for _, foundBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001020 if strings.HasSuffix(foundBlueprints, "/") {
1021 errs = append(errs, &BlueprintError{
1022 Err: fmt.Errorf("%q: is a directory", foundBlueprints),
1023 Pos: buildPos,
1024 })
1025 }
Colin Cross7f507402015-12-16 13:03:41 -08001026 blueprints = append(blueprints, foundBlueprints)
1027 }
1028 }
1029
Colin Cross127d2ea2016-11-01 11:10:51 -07001030 return blueprints, errs
Colin Cross7f507402015-12-16 13:03:41 -08001031}
1032
1033func (c *Context) findSubdirBlueprints(dir string, subdirs []string, subdirsPos scanner.Position,
Colin Cross127d2ea2016-11-01 11:10:51 -07001034 subBlueprintsName string, optional bool) ([]string, []error) {
1035
1036 var blueprints []string
1037 var errs []error
Colin Cross7ad621c2015-01-07 16:22:45 -08001038
1039 for _, subdir := range subdirs {
Colin Cross127d2ea2016-11-01 11:10:51 -07001040 pattern := filepath.Join(dir, subdir, subBlueprintsName)
1041 var matches []string
1042 var err error
1043
Colin Cross08e49542016-11-14 15:23:33 -08001044 matches, err = c.glob(pattern, nil)
Colin Cross127d2ea2016-11-01 11:10:51 -07001045
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001046 if err != nil {
Colin Cross2c628442016-10-07 17:13:10 -07001047 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001048 Err: fmt.Errorf("%q: %s", pattern, err.Error()),
Colin Cross1fef5362015-04-20 16:50:54 -07001049 Pos: subdirsPos,
1050 })
1051 continue
1052 }
1053
Colin Cross7f507402015-12-16 13:03:41 -08001054 if len(matches) == 0 && !optional {
Colin Cross2c628442016-10-07 17:13:10 -07001055 errs = append(errs, &BlueprintError{
Colin Cross127d2ea2016-11-01 11:10:51 -07001056 Err: fmt.Errorf("%q: not found", pattern),
Colin Cross1fef5362015-04-20 16:50:54 -07001057 Pos: subdirsPos,
1058 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -07001059 }
Colin Cross7ad621c2015-01-07 16:22:45 -08001060
Colin Cross127d2ea2016-11-01 11:10:51 -07001061 for _, subBlueprints := range matches {
Dan Willemsenb6c90232018-02-23 14:49:45 -08001062 if strings.HasSuffix(subBlueprints, "/") {
1063 errs = append(errs, &BlueprintError{
1064 Err: fmt.Errorf("%q: is a directory", subBlueprints),
1065 Pos: subdirsPos,
1066 })
1067 }
Colin Cross127d2ea2016-11-01 11:10:51 -07001068 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -08001069 }
1070 }
Colin Cross1fef5362015-04-20 16:50:54 -07001071
Colin Cross127d2ea2016-11-01 11:10:51 -07001072 return blueprints, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001073}
1074
Colin Cross6d8780f2015-07-10 17:51:55 -07001075func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
1076 if assignment, local := scope.Get(v); assignment == nil || !local {
1077 return nil, scanner.Position{}, nil
1078 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001079 switch value := assignment.Value.Eval().(type) {
1080 case *parser.List:
1081 ret := make([]string, 0, len(value.Values))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001082
Colin Crosse32cc802016-06-07 12:28:16 -07001083 for _, listValue := range value.Values {
1084 s, ok := listValue.(*parser.String)
1085 if !ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001086 // The parser should not produce this.
1087 panic("non-string value found in list")
1088 }
1089
Colin Crosse32cc802016-06-07 12:28:16 -07001090 ret = append(ret, s.Value)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001091 }
1092
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001093 return ret, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001094 case *parser.Bool, *parser.String:
Colin Cross2c628442016-10-07 17:13:10 -07001095 return nil, scanner.Position{}, &BlueprintError{
Colin Cross1fef5362015-04-20 16:50:54 -07001096 Err: fmt.Errorf("%q must be a list of strings", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001097 Pos: assignment.EqualsPos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001098 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001099 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001100 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001101 }
1102 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001103}
1104
Colin Cross29394222015-04-27 13:18:21 -07001105func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -07001106 if assignment, _ := scope.Get(v); assignment == nil {
1107 return "", scanner.Position{}, nil
1108 } else {
Colin Crosse32cc802016-06-07 12:28:16 -07001109 switch value := assignment.Value.Eval().(type) {
1110 case *parser.String:
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001111 return value.Value, assignment.EqualsPos, nil
Colin Crosse32cc802016-06-07 12:28:16 -07001112 case *parser.Bool, *parser.List:
Colin Cross2c628442016-10-07 17:13:10 -07001113 return "", scanner.Position{}, &BlueprintError{
Colin Cross29394222015-04-27 13:18:21 -07001114 Err: fmt.Errorf("%q must be a string", v),
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001115 Pos: assignment.EqualsPos,
Colin Cross29394222015-04-27 13:18:21 -07001116 }
1117 default:
Dan Willemsene6d45fe2018-02-27 01:38:08 -08001118 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type()))
Colin Cross29394222015-04-27 13:18:21 -07001119 }
1120 }
Colin Cross29394222015-04-27 13:18:21 -07001121}
1122
Colin Cross910242b2016-04-11 15:41:52 -07001123// Clones a build logic module by calling the factory method for its module type, and then cloning
1124// property values. Any values stored in the module object that are not stored in properties
1125// structs will be lost.
1126func (c *Context) cloneLogicModule(origModule *moduleInfo) (Module, []interface{}) {
Colin Crossaf4fd212017-07-28 14:32:36 -07001127 newLogicModule, newProperties := origModule.factory()
Colin Cross910242b2016-04-11 15:41:52 -07001128
Colin Crossd2f4ac12017-07-28 14:31:03 -07001129 if len(newProperties) != len(origModule.properties) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001130 panic("mismatched properties array length in " + origModule.Name())
Colin Cross910242b2016-04-11 15:41:52 -07001131 }
1132
1133 for i := range newProperties {
1134 dst := reflect.ValueOf(newProperties[i]).Elem()
Colin Crossd2f4ac12017-07-28 14:31:03 -07001135 src := reflect.ValueOf(origModule.properties[i]).Elem()
Colin Cross910242b2016-04-11 15:41:52 -07001136
1137 proptools.CopyProperties(dst, src)
1138 }
1139
1140 return newLogicModule, newProperties
1141}
1142
Colin Crossf5e34b92015-03-13 16:02:36 -07001143func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
1144 variationNames []string) ([]*moduleInfo, []error) {
Colin Crossc9028482014-12-18 16:28:54 -08001145
Colin Crossf4d18a62015-03-18 17:43:15 -07001146 if len(variationNames) == 0 {
1147 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001148 mutatorName, origModule.Name()))
Colin Crossf4d18a62015-03-18 17:43:15 -07001149 }
1150
Colin Crossc9028482014-12-18 16:28:54 -08001151 newModules := []*moduleInfo{}
Colin Crossc9028482014-12-18 16:28:54 -08001152
Colin Cross174ae052015-03-03 17:37:03 -08001153 var errs []error
1154
Colin Crossf5e34b92015-03-13 16:02:36 -07001155 for i, variationName := range variationNames {
Colin Crossc9028482014-12-18 16:28:54 -08001156 var newLogicModule Module
1157 var newProperties []interface{}
1158
1159 if i == 0 {
1160 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -07001161 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
1162 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossd2f4ac12017-07-28 14:31:03 -07001163 newLogicModule, newProperties = origModule.logicModule, origModule.properties
Colin Crossc9028482014-12-18 16:28:54 -08001164 } else {
Colin Cross910242b2016-04-11 15:41:52 -07001165 newLogicModule, newProperties = c.cloneLogicModule(origModule)
Colin Crossc9028482014-12-18 16:28:54 -08001166 }
1167
Colin Crossf5e34b92015-03-13 16:02:36 -07001168 newVariant := origModule.variant.clone()
1169 newVariant[mutatorName] = variationName
Colin Crossc9028482014-12-18 16:28:54 -08001170
Colin Crossed342d92015-03-11 00:57:25 -07001171 m := *origModule
1172 newModule := &m
Colin Cross2c1f3d12016-04-11 15:47:28 -07001173 newModule.directDeps = append([]depInfo{}, origModule.directDeps...)
Colin Crossed342d92015-03-11 00:57:25 -07001174 newModule.logicModule = newLogicModule
Colin Crossf5e34b92015-03-13 16:02:36 -07001175 newModule.variant = newVariant
1176 newModule.dependencyVariant = origModule.dependencyVariant.clone()
Colin Crossd2f4ac12017-07-28 14:31:03 -07001177 newModule.properties = newProperties
Colin Crossc9028482014-12-18 16:28:54 -08001178
Colin Crossbadc8812016-08-11 17:01:46 -07001179 if variationName != "" {
1180 if newModule.variantName == "" {
1181 newModule.variantName = variationName
1182 } else {
1183 newModule.variantName += "_" + variationName
1184 }
Colin Crosse7daa222015-03-11 14:35:41 -07001185 }
1186
Colin Crossc9028482014-12-18 16:28:54 -08001187 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -07001188
Colin Crossf5e34b92015-03-13 16:02:36 -07001189 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName)
Colin Cross174ae052015-03-03 17:37:03 -08001190 if len(newErrs) > 0 {
1191 errs = append(errs, newErrs...)
1192 }
Colin Crossc9028482014-12-18 16:28:54 -08001193 }
1194
1195 // Mark original variant as invalid. Modules that depend on this module will still
1196 // depend on origModule, but we'll fix it when the mutator is called on them.
1197 origModule.logicModule = nil
1198 origModule.splitModules = newModules
1199
Colin Cross3702ac72016-08-11 11:09:00 -07001200 atomic.AddUint32(&c.depsModified, 1)
1201
Colin Cross174ae052015-03-03 17:37:03 -08001202 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -08001203}
1204
Colin Crossf5e34b92015-03-13 16:02:36 -07001205func (c *Context) convertDepsToVariation(module *moduleInfo,
1206 mutatorName, variationName string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -08001207
Colin Crossc9028482014-12-18 16:28:54 -08001208 for i, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001209 if dep.module.logicModule == nil {
Colin Crossc9028482014-12-18 16:28:54 -08001210 var newDep *moduleInfo
Colin Cross2c1f3d12016-04-11 15:47:28 -07001211 for _, m := range dep.module.splitModules {
Colin Crossf5e34b92015-03-13 16:02:36 -07001212 if m.variant[mutatorName] == variationName {
Colin Crossc9028482014-12-18 16:28:54 -08001213 newDep = m
1214 break
1215 }
1216 }
1217 if newDep == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001218 errs = append(errs, &BlueprintError{
Colin Crossf5e34b92015-03-13 16:02:36 -07001219 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001220 variationName, dep.module.Name(), module.Name()),
Colin Crossed342d92015-03-11 00:57:25 -07001221 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -08001222 })
1223 continue
Colin Crossc9028482014-12-18 16:28:54 -08001224 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001225 module.directDeps[i].module = newDep
Colin Crossc9028482014-12-18 16:28:54 -08001226 }
1227 }
Colin Cross174ae052015-03-03 17:37:03 -08001228
1229 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001230}
1231
Colin Crossf5e34b92015-03-13 16:02:36 -07001232func (c *Context) prettyPrintVariant(variant variationMap) string {
Colin Cross65569e42015-03-10 20:08:19 -07001233 names := make([]string, 0, len(variant))
1234 for _, m := range c.variantMutatorNames {
1235 if v, ok := variant[m]; ok {
1236 names = append(names, m+":"+v)
1237 }
1238 }
1239
1240 return strings.Join(names, ", ")
1241}
1242
Colin Crossaf4fd212017-07-28 14:32:36 -07001243func (c *Context) newModule(factory ModuleFactory) *moduleInfo {
1244 logicModule, properties := factory()
1245
1246 module := &moduleInfo{
1247 logicModule: logicModule,
1248 factory: factory,
1249 }
1250
1251 module.properties = properties
1252
1253 return module
1254}
1255
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001256func (c *Context) processModuleDef(moduleDef *parser.Module,
Colin Cross7ad621c2015-01-07 16:22:45 -08001257 relBlueprintsFile string) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001258
Colin Crossc32c4792016-06-09 15:52:30 -07001259 factory, ok := c.moduleFactories[moduleDef.Type]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001260 if !ok {
1261 if c.ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -08001262 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001263 }
1264
Colin Cross7ad621c2015-01-07 16:22:45 -08001265 return nil, []error{
Colin Cross2c628442016-10-07 17:13:10 -07001266 &BlueprintError{
Colin Crossc32c4792016-06-09 15:52:30 -07001267 Err: fmt.Errorf("unrecognized module type %q", moduleDef.Type),
1268 Pos: moduleDef.TypePos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001269 },
1270 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001271 }
1272
Colin Crossaf4fd212017-07-28 14:32:36 -07001273 module := c.newModule(factory)
1274 module.typeName = moduleDef.Type
Colin Crossed342d92015-03-11 00:57:25 -07001275
Colin Crossaf4fd212017-07-28 14:32:36 -07001276 module.relBlueprintsFile = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001277
Colin Crossaf4fd212017-07-28 14:32:36 -07001278 propertyMap, errs := unpackProperties(moduleDef.Properties, module.properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001279 if len(errs) > 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -08001280 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001281 }
1282
Colin Crossc32c4792016-06-09 15:52:30 -07001283 module.pos = moduleDef.TypePos
Colin Crossed342d92015-03-11 00:57:25 -07001284 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001285 for name, propertyDef := range propertyMap {
Colin Crossb3d0b8d2016-06-09 17:03:57 -07001286 module.propertyPos[name] = propertyDef.ColonPos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001287 }
1288
Colin Cross7ad621c2015-01-07 16:22:45 -08001289 return module, nil
1290}
1291
Colin Cross23d7aa12015-06-30 16:05:22 -07001292func (c *Context) addModule(module *moduleInfo) []error {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001293 name := module.logicModule.Name()
Colin Cross23d7aa12015-06-30 16:05:22 -07001294 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001295
Colin Cross0b7e83e2016-05-17 14:58:05 -07001296 group := &moduleGroup{
Jeff Gaston0e907592017-12-01 17:10:52 -08001297 name: name,
1298 modules: []*moduleInfo{module},
Colin Cross0b7e83e2016-05-17 14:58:05 -07001299 }
1300 module.group = group
Jeff Gastond70bf752017-11-10 15:12:08 -08001301 namespace, errs := c.nameInterface.NewModule(
Jeff Gaston0e907592017-12-01 17:10:52 -08001302 newNamespaceContext(module),
Jeff Gastond70bf752017-11-10 15:12:08 -08001303 ModuleGroup{moduleGroup: group},
1304 module.logicModule)
1305 if len(errs) > 0 {
1306 for i := range errs {
1307 errs[i] = &BlueprintError{Err: errs[i], Pos: module.pos}
1308 }
1309 return errs
1310 }
1311 group.namespace = namespace
1312
Colin Cross0b7e83e2016-05-17 14:58:05 -07001313 c.moduleGroups = append(c.moduleGroups, group)
1314
Colin Cross23d7aa12015-06-30 16:05:22 -07001315 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001316}
1317
Jamie Gennisd4e10182014-06-12 20:06:50 -07001318// ResolveDependencies checks that the dependencies specified by all of the
1319// modules defined in the parsed Blueprints files are valid. This means that
1320// the modules depended upon are defined and that no circular dependencies
1321// exist.
Colin Cross874a3462017-07-31 17:26:06 -07001322func (c *Context) ResolveDependencies(config interface{}) (deps []string, errs []error) {
Colin Cross5f03f112017-11-07 13:29:54 -08001323 c.liveGlobals = newLiveTracker(config)
1324
1325 deps, errs = c.generateSingletonBuildActions(config, c.preSingletonInfo, c.liveGlobals)
1326 if len(errs) > 0 {
1327 return nil, errs
1328 }
1329
Colin Cross874a3462017-07-31 17:26:06 -07001330 errs = c.updateDependencies()
Colin Crossf8b50422016-08-10 12:56:40 -07001331 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07001332 return nil, errs
Colin Crossf8b50422016-08-10 12:56:40 -07001333 }
1334
Colin Cross5f03f112017-11-07 13:29:54 -08001335 mutatorDeps, errs := c.runMutators(config)
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001336 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07001337 return nil, errs
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001338 }
Colin Cross5f03f112017-11-07 13:29:54 -08001339 deps = append(deps, mutatorDeps...)
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001340
Colin Cross910242b2016-04-11 15:41:52 -07001341 c.cloneModules()
1342
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001343 c.dependenciesReady = true
Colin Cross874a3462017-07-31 17:26:06 -07001344 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001345}
1346
Colin Cross763b6f12015-10-29 15:32:56 -07001347// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001348// DynamicDependerModule interface then this set consists of the union of those
Colin Cross0b7e83e2016-05-17 14:58:05 -07001349// module names returned by its DynamicDependencies method and those added by calling
1350// AddDependencies or AddVariationDependencies on DynamicDependencyModuleContext.
Colin Cross763b6f12015-10-29 15:32:56 -07001351func blueprintDepsMutator(ctx BottomUpMutatorContext) {
Colin Cross763b6f12015-10-29 15:32:56 -07001352 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001353 func() {
1354 defer func() {
1355 if r := recover(); r != nil {
1356 ctx.error(newPanicErrorf(r, "DynamicDependencies for %s", ctx.moduleInfo()))
1357 }
1358 }()
1359 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001360
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001361 if ctx.Failed() {
1362 return
1363 }
Colin Cross763b6f12015-10-29 15:32:56 -07001364
Colin Cross2c1f3d12016-04-11 15:47:28 -07001365 ctx.AddDependency(ctx.Module(), nil, dynamicDeps...)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001366 }()
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001367 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001368}
1369
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001370// findMatchingVariant searches the moduleGroup for a module with the same variant as module,
1371// and returns the matching module, or nil if one is not found.
Colin Cross0b7e83e2016-05-17 14:58:05 -07001372func (c *Context) findMatchingVariant(module *moduleInfo, possible []*moduleInfo) *moduleInfo {
1373 if len(possible) == 1 {
1374 return possible[0]
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001375 } else {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001376 for _, m := range possible {
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001377 if m.variant.equal(module.dependencyVariant) {
1378 return m
1379 }
1380 }
1381 }
1382
1383 return nil
1384}
1385
Colin Cross2c1f3d12016-04-11 15:47:28 -07001386func (c *Context) addDependency(module *moduleInfo, tag DependencyTag, depName string) []error {
Nan Zhang346b2d02017-03-10 16:39:27 -08001387 if _, ok := tag.(BaseDependencyTag); ok {
1388 panic("BaseDependencyTag is not allowed to be used directly!")
1389 }
1390
Colin Cross0b7e83e2016-05-17 14:58:05 -07001391 if depName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001392 return []error{&BlueprintError{
Colin Crossc9028482014-12-18 16:28:54 -08001393 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001394 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001395 }}
1396 }
1397
Jeff Gastond70bf752017-11-10 15:12:08 -08001398 possibleDeps := c.modulesFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001399 if possibleDeps == nil {
Jeff Gastond70bf752017-11-10 15:12:08 -08001400 return c.discoveredMissingDependencies(module, depName)
Colin Crossc9028482014-12-18 16:28:54 -08001401 }
1402
Colin Cross0b7e83e2016-05-17 14:58:05 -07001403 if m := c.findMatchingVariant(module, possibleDeps); m != nil {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001404 for _, dep := range module.directDeps {
1405 if m == dep.module {
1406 // TODO(ccross): what if adding a dependency with a different tag?
1407 return nil
1408 }
Colin Cross65569e42015-03-10 20:08:19 -07001409 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001410 module.directDeps = append(module.directDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001411 atomic.AddUint32(&c.depsModified, 1)
Colin Cross65569e42015-03-10 20:08:19 -07001412 return nil
Colin Cross65569e42015-03-10 20:08:19 -07001413 }
Colin Crossc9028482014-12-18 16:28:54 -08001414
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001415 variants := make([]string, len(possibleDeps))
1416 for i, mod := range possibleDeps {
1417 variants[i] = c.prettyPrintVariant(mod.variant)
1418 }
1419 sort.Strings(variants)
1420
Colin Cross2c628442016-10-07 17:13:10 -07001421 return []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001422 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001423 depName, module.Name(),
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001424 c.prettyPrintVariant(module.dependencyVariant),
1425 strings.Join(variants, "\n ")),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001426 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001427 }}
1428}
1429
Colin Cross8d8a7af2015-11-03 16:41:29 -08001430func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001431 if destName == module.Name() {
Colin Cross2c628442016-10-07 17:13:10 -07001432 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001433 Err: fmt.Errorf("%q depends on itself", destName),
1434 Pos: module.pos,
1435 }}
1436 }
1437
Jeff Gastond70bf752017-11-10 15:12:08 -08001438 possibleDeps := c.modulesFromName(destName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001439 if possibleDeps == nil {
Colin Cross2c628442016-10-07 17:13:10 -07001440 return nil, []error{&BlueprintError{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001441 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001442 module.Name(), destName),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001443 Pos: module.pos,
1444 }}
1445 }
1446
Colin Cross0b7e83e2016-05-17 14:58:05 -07001447 if m := c.findMatchingVariant(module, possibleDeps); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001448 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001449 }
1450
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001451 variants := make([]string, len(possibleDeps))
1452 for i, mod := range possibleDeps {
1453 variants[i] = c.prettyPrintVariant(mod.variant)
1454 }
1455 sort.Strings(variants)
1456
Colin Cross2c628442016-10-07 17:13:10 -07001457 return nil, []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001458 Err: fmt.Errorf("reverse dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001459 destName, module.Name(),
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001460 c.prettyPrintVariant(module.dependencyVariant),
1461 strings.Join(variants, "\n ")),
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001462 Pos: module.pos,
1463 }}
1464}
1465
Colin Crossf5e34b92015-03-13 16:02:36 -07001466func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Colin Cross2c1f3d12016-04-11 15:47:28 -07001467 tag DependencyTag, depName string, far bool) []error {
Nan Zhang346b2d02017-03-10 16:39:27 -08001468 if _, ok := tag.(BaseDependencyTag); ok {
1469 panic("BaseDependencyTag is not allowed to be used directly!")
1470 }
Colin Cross65569e42015-03-10 20:08:19 -07001471
Jeff Gastond70bf752017-11-10 15:12:08 -08001472 possibleDeps := c.modulesFromName(depName, module.namespace())
Colin Cross0b7e83e2016-05-17 14:58:05 -07001473 if possibleDeps == nil {
Jeff Gastond70bf752017-11-10 15:12:08 -08001474 return c.discoveredMissingDependencies(module, depName)
Colin Cross65569e42015-03-10 20:08:19 -07001475 }
1476
1477 // We can't just append variant.Variant to module.dependencyVariants.variantName and
1478 // compare the strings because the result won't be in mutator registration order.
1479 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001480 var newVariant variationMap
1481 if !far {
1482 newVariant = module.dependencyVariant.clone()
1483 } else {
1484 newVariant = make(variationMap)
1485 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001486 for _, v := range variations {
1487 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001488 }
1489
Colin Cross0b7e83e2016-05-17 14:58:05 -07001490 for _, m := range possibleDeps {
Colin Cross89486232015-05-08 11:14:54 -07001491 var found bool
1492 if far {
1493 found = m.variant.subset(newVariant)
1494 } else {
1495 found = m.variant.equal(newVariant)
1496 }
1497 if found {
Colin Cross045a5972015-11-03 16:58:48 -08001498 if module == m {
Colin Cross2c628442016-10-07 17:13:10 -07001499 return []error{&BlueprintError{
Colin Cross045a5972015-11-03 16:58:48 -08001500 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001501 Pos: module.pos,
Colin Cross045a5972015-11-03 16:58:48 -08001502 }}
1503 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001504 // AddVariationDependency allows adding a dependency on itself, but only if
Colin Cross65569e42015-03-10 20:08:19 -07001505 // that module is earlier in the module list than this one, since we always
Colin Crossf5e34b92015-03-13 16:02:36 -07001506 // run GenerateBuildActions in order for the variants of a module
Colin Cross0b7e83e2016-05-17 14:58:05 -07001507 if m.group == module.group && beforeInModuleList(module, m, module.group.modules) {
Colin Cross2c628442016-10-07 17:13:10 -07001508 return []error{&BlueprintError{
Colin Cross65569e42015-03-10 20:08:19 -07001509 Err: fmt.Errorf("%q depends on later version of itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001510 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001511 }}
1512 }
Colin Cross2c1f3d12016-04-11 15:47:28 -07001513 module.directDeps = append(module.directDeps, depInfo{m, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001514 atomic.AddUint32(&c.depsModified, 1)
Colin Cross65569e42015-03-10 20:08:19 -07001515 return nil
1516 }
1517 }
1518
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001519 variants := make([]string, len(possibleDeps))
1520 for i, mod := range possibleDeps {
1521 variants[i] = c.prettyPrintVariant(mod.variant)
1522 }
1523 sort.Strings(variants)
1524
Colin Cross2c628442016-10-07 17:13:10 -07001525 return []error{&BlueprintError{
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001526 Err: fmt.Errorf("dependency %q of %q missing variant:\n %s\navailable variants:\n %s",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001527 depName, module.Name(),
Dan Willemsen978c4aa2017-03-20 14:11:38 -07001528 c.prettyPrintVariant(newVariant),
1529 strings.Join(variants, "\n ")),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001530 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001531 }}
Colin Crossc9028482014-12-18 16:28:54 -08001532}
1533
Colin Crossf1875462016-04-11 17:33:13 -07001534func (c *Context) addInterVariantDependency(origModule *moduleInfo, tag DependencyTag,
1535 from, to Module) {
Nan Zhang346b2d02017-03-10 16:39:27 -08001536 if _, ok := tag.(BaseDependencyTag); ok {
1537 panic("BaseDependencyTag is not allowed to be used directly!")
1538 }
Colin Crossf1875462016-04-11 17:33:13 -07001539
1540 var fromInfo, toInfo *moduleInfo
1541 for _, m := range origModule.splitModules {
1542 if m.logicModule == from {
1543 fromInfo = m
1544 }
1545 if m.logicModule == to {
1546 toInfo = m
1547 if fromInfo != nil {
Colin Cross0b7e83e2016-05-17 14:58:05 -07001548 panic(fmt.Errorf("%q depends on later version of itself", origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001549 }
1550 }
1551 }
1552
1553 if fromInfo == nil || toInfo == nil {
1554 panic(fmt.Errorf("AddInterVariantDependency called for module %q on invalid variant",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001555 origModule.Name()))
Colin Crossf1875462016-04-11 17:33:13 -07001556 }
1557
1558 fromInfo.directDeps = append(fromInfo.directDeps, depInfo{toInfo, tag})
Colin Cross3702ac72016-08-11 11:09:00 -07001559 atomic.AddUint32(&c.depsModified, 1)
Colin Crossf1875462016-04-11 17:33:13 -07001560}
1561
Jeff Gastonc3e28442017-08-09 15:13:12 -07001562// findBlueprintDescendants returns a map linking parent Blueprints files to child Blueprints files
1563// For example, if paths = []string{"a/b/c/Android.bp", "a/Blueprints"},
1564// then descendants = {"":[]string{"a/Blueprints"}, "a/Blueprints":[]string{"a/b/c/Android.bp"}}
1565func findBlueprintDescendants(paths []string) (descendants map[string][]string, err error) {
1566 // make mapping from dir path to file path
1567 filesByDir := make(map[string]string, len(paths))
1568 for _, path := range paths {
1569 dir := filepath.Dir(path)
1570 _, alreadyFound := filesByDir[dir]
1571 if alreadyFound {
1572 return nil, fmt.Errorf("Found two Blueprint files in directory %v : %v and %v", dir, filesByDir[dir], path)
1573 }
1574 filesByDir[dir] = path
1575 }
1576
Jeff Gaston656870f2017-11-29 18:37:31 -08001577 findAncestor := func(childFile string) (ancestor string) {
1578 prevAncestorDir := filepath.Dir(childFile)
Jeff Gastonc3e28442017-08-09 15:13:12 -07001579 for {
1580 ancestorDir := filepath.Dir(prevAncestorDir)
1581 if ancestorDir == prevAncestorDir {
1582 // reached the root dir without any matches; assign this as a descendant of ""
Jeff Gaston656870f2017-11-29 18:37:31 -08001583 return ""
Jeff Gastonc3e28442017-08-09 15:13:12 -07001584 }
1585
1586 ancestorFile, ancestorExists := filesByDir[ancestorDir]
1587 if ancestorExists {
Jeff Gaston656870f2017-11-29 18:37:31 -08001588 return ancestorFile
Jeff Gastonc3e28442017-08-09 15:13:12 -07001589 }
1590 prevAncestorDir = ancestorDir
1591 }
1592 }
Jeff Gaston656870f2017-11-29 18:37:31 -08001593 // generate the descendants map
1594 descendants = make(map[string][]string, len(filesByDir))
1595 for _, childFile := range filesByDir {
1596 ancestorFile := findAncestor(childFile)
1597 descendants[ancestorFile] = append(descendants[ancestorFile], childFile)
1598 }
Jeff Gastonc3e28442017-08-09 15:13:12 -07001599 return descendants, nil
1600}
1601
Colin Cross3702ac72016-08-11 11:09:00 -07001602type visitOrderer interface {
1603 // returns the number of modules that this module needs to wait for
1604 waitCount(module *moduleInfo) int
1605 // returns the list of modules that are waiting for this module
1606 propagate(module *moduleInfo) []*moduleInfo
1607 // visit modules in order
1608 visit(modules []*moduleInfo, visit func(*moduleInfo) bool)
1609}
1610
1611type bottomUpVisitorImpl struct{}
1612
1613func (bottomUpVisitorImpl) waitCount(module *moduleInfo) int {
1614 return len(module.forwardDeps)
1615}
1616
1617func (bottomUpVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1618 return module.reverseDeps
1619}
1620
1621func (bottomUpVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo) bool) {
1622 for _, module := range modules {
Colin Cross49c279a2016-08-05 22:30:44 -07001623 if visit(module) {
1624 return
1625 }
1626 }
1627}
1628
Colin Cross3702ac72016-08-11 11:09:00 -07001629type topDownVisitorImpl struct{}
1630
1631func (topDownVisitorImpl) waitCount(module *moduleInfo) int {
1632 return len(module.reverseDeps)
1633}
1634
1635func (topDownVisitorImpl) propagate(module *moduleInfo) []*moduleInfo {
1636 return module.forwardDeps
1637}
1638
1639func (topDownVisitorImpl) visit(modules []*moduleInfo, visit func(*moduleInfo) bool) {
1640 for i := 0; i < len(modules); i++ {
1641 module := modules[len(modules)-1-i]
1642 if visit(module) {
1643 return
1644 }
1645 }
1646}
1647
1648var (
1649 bottomUpVisitor bottomUpVisitorImpl
1650 topDownVisitor topDownVisitorImpl
1651)
1652
Colin Cross49c279a2016-08-05 22:30:44 -07001653// Calls visit on each module, guaranteeing that visit is not called on a module until visit on all
1654// of its dependencies has finished.
Colin Cross3702ac72016-08-11 11:09:00 -07001655func (c *Context) parallelVisit(order visitOrderer, visit func(group *moduleInfo) bool) {
Colin Cross7addea32015-03-11 15:43:52 -07001656 doneCh := make(chan *moduleInfo)
Colin Cross0fff7422016-08-11 15:37:45 -07001657 cancelCh := make(chan bool)
Colin Cross691a60d2015-01-07 18:08:56 -08001658 count := 0
Colin Cross8900e9b2015-03-02 14:03:01 -08001659 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001660
Colin Cross7addea32015-03-11 15:43:52 -07001661 for _, module := range c.modulesSorted {
Colin Cross3702ac72016-08-11 11:09:00 -07001662 module.waitingCount = order.waitCount(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001663 }
1664
Colin Cross7addea32015-03-11 15:43:52 -07001665 visitOne := func(module *moduleInfo) {
Colin Cross691a60d2015-01-07 18:08:56 -08001666 count++
1667 go func() {
Colin Cross7addea32015-03-11 15:43:52 -07001668 ret := visit(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08001669 if ret {
Colin Cross0fff7422016-08-11 15:37:45 -07001670 cancelCh <- true
Colin Cross8900e9b2015-03-02 14:03:01 -08001671 }
Colin Cross7addea32015-03-11 15:43:52 -07001672 doneCh <- module
Colin Cross691a60d2015-01-07 18:08:56 -08001673 }()
1674 }
1675
Colin Cross7addea32015-03-11 15:43:52 -07001676 for _, module := range c.modulesSorted {
1677 if module.waitingCount == 0 {
1678 visitOne(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001679 }
1680 }
1681
Colin Cross11e3b0d2015-02-04 10:41:00 -08001682 for count > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08001683 select {
Colin Cross0fff7422016-08-11 15:37:45 -07001684 case cancel = <-cancelCh:
Colin Cross7addea32015-03-11 15:43:52 -07001685 case doneModule := <-doneCh:
Colin Cross8900e9b2015-03-02 14:03:01 -08001686 if !cancel {
Colin Cross3702ac72016-08-11 11:09:00 -07001687 for _, module := range order.propagate(doneModule) {
1688 module.waitingCount--
1689 if module.waitingCount == 0 {
1690 visitOne(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08001691 }
Colin Cross691a60d2015-01-07 18:08:56 -08001692 }
1693 }
1694 count--
Colin Cross691a60d2015-01-07 18:08:56 -08001695 }
1696 }
1697}
1698
1699// updateDependencies recursively walks the module dependency graph and updates
1700// additional fields based on the dependencies. It builds a sorted list of modules
1701// such that dependencies of a module always appear first, and populates reverse
1702// dependency links and counts of total dependencies. It also reports errors when
1703// it encounters dependency cycles. This should called after resolveDependencies,
1704// as well as after any mutator pass has called addDependency
1705func (c *Context) updateDependencies() (errs []error) {
Colin Cross7addea32015-03-11 15:43:52 -07001706 visited := make(map[*moduleInfo]bool) // modules that were already checked
1707 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001708
Colin Cross7addea32015-03-11 15:43:52 -07001709 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08001710
Colin Cross7addea32015-03-11 15:43:52 -07001711 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001712
Colin Cross7addea32015-03-11 15:43:52 -07001713 cycleError := func(cycle []*moduleInfo) {
Colin Cross10b54db2015-03-11 14:40:30 -07001714 // We are the "start" of the cycle, so we're responsible
1715 // for generating the errors. The cycle list is in
1716 // reverse order because all the 'check' calls append
1717 // their own module to the list.
Colin Cross2c628442016-10-07 17:13:10 -07001718 errs = append(errs, &BlueprintError{
Colin Cross10b54db2015-03-11 14:40:30 -07001719 Err: fmt.Errorf("encountered dependency cycle:"),
Colin Cross7addea32015-03-11 15:43:52 -07001720 Pos: cycle[len(cycle)-1].pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001721 })
1722
1723 // Iterate backwards through the cycle list.
Colin Cross0e4607e2015-03-24 16:42:56 -07001724 curModule := cycle[0]
Colin Cross10b54db2015-03-11 14:40:30 -07001725 for i := len(cycle) - 1; i >= 0; i-- {
Colin Cross7addea32015-03-11 15:43:52 -07001726 nextModule := cycle[i]
Colin Cross2c628442016-10-07 17:13:10 -07001727 errs = append(errs, &BlueprintError{
Colin Cross10b54db2015-03-11 14:40:30 -07001728 Err: fmt.Errorf(" %q depends on %q",
Colin Cross0b7e83e2016-05-17 14:58:05 -07001729 curModule.Name(),
1730 nextModule.Name()),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001731 Pos: curModule.pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001732 })
Colin Cross7addea32015-03-11 15:43:52 -07001733 curModule = nextModule
Colin Cross10b54db2015-03-11 14:40:30 -07001734 }
1735 }
1736
Colin Cross7addea32015-03-11 15:43:52 -07001737 check = func(module *moduleInfo) []*moduleInfo {
1738 visited[module] = true
1739 checking[module] = true
1740 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001741
Colin Cross7addea32015-03-11 15:43:52 -07001742 deps := make(map[*moduleInfo]bool)
1743
1744 // Add an implicit dependency ordering on all earlier modules in the same module group
1745 for _, dep := range module.group.modules {
1746 if dep == module {
1747 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08001748 }
Colin Cross7addea32015-03-11 15:43:52 -07001749 deps[dep] = true
Colin Crossbbfa51a2014-12-17 16:12:41 -08001750 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001751
Colin Cross7addea32015-03-11 15:43:52 -07001752 for _, dep := range module.directDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07001753 deps[dep.module] = true
Colin Cross7addea32015-03-11 15:43:52 -07001754 }
1755
1756 module.reverseDeps = []*moduleInfo{}
Colin Cross3702ac72016-08-11 11:09:00 -07001757 module.forwardDeps = []*moduleInfo{}
Colin Cross691a60d2015-01-07 18:08:56 -08001758
Colin Crossbbfa51a2014-12-17 16:12:41 -08001759 for dep := range deps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001760 if checking[dep] {
1761 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07001762 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001763 }
1764
1765 if !visited[dep] {
1766 cycle := check(dep)
1767 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001768 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001769 // We are the "start" of the cycle, so we're responsible
1770 // for generating the errors. The cycle list is in
1771 // reverse order because all the 'check' calls append
1772 // their own module to the list.
Colin Cross10b54db2015-03-11 14:40:30 -07001773 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001774
1775 // We can continue processing this module's children to
1776 // find more cycles. Since all the modules that were
1777 // part of the found cycle were marked as visited we
1778 // won't run into that cycle again.
1779 } else {
1780 // We're not the "start" of the cycle, so we just append
1781 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07001782 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001783 }
1784 }
1785 }
Colin Cross691a60d2015-01-07 18:08:56 -08001786
Colin Cross3702ac72016-08-11 11:09:00 -07001787 module.forwardDeps = append(module.forwardDeps, dep)
Colin Cross7addea32015-03-11 15:43:52 -07001788 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001789 }
1790
Colin Cross7addea32015-03-11 15:43:52 -07001791 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08001792
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001793 return nil
1794 }
1795
Colin Cross7addea32015-03-11 15:43:52 -07001796 for _, module := range c.moduleInfo {
1797 if !visited[module] {
1798 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001799 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001800 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07001801 panic("inconceivable!")
1802 }
1803 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001804 }
1805 }
1806 }
1807
Colin Cross7addea32015-03-11 15:43:52 -07001808 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08001809
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001810 return
1811}
1812
Jamie Gennisd4e10182014-06-12 20:06:50 -07001813// PrepareBuildActions generates an internal representation of all the build
1814// actions that need to be performed. This process involves invoking the
1815// GenerateBuildActions method on each of the Module objects created during the
1816// parse phase and then on each of the registered Singleton objects.
1817//
1818// If the ResolveDependencies method has not already been called it is called
1819// automatically by this method.
1820//
1821// The config argument is made available to all of the Module and Singleton
1822// objects via the Config method on the ModuleContext and SingletonContext
1823// objects passed to GenerateBuildActions. It is also passed to the functions
1824// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
1825// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001826//
1827// The returned deps is a list of the ninja files dependencies that were added
Dan Willemsena481ae22015-12-18 15:18:03 -08001828// by the modules and singletons via the ModuleContext.AddNinjaFileDeps(),
1829// SingletonContext.AddNinjaFileDeps(), and PackageContext.AddNinjaFileDeps()
1830// methods.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001831func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001832 c.buildActionsReady = false
1833
1834 if !c.dependenciesReady {
Colin Cross874a3462017-07-31 17:26:06 -07001835 extraDeps, errs := c.ResolveDependencies(config)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001836 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001837 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001838 }
Colin Cross874a3462017-07-31 17:26:06 -07001839 deps = append(deps, extraDeps...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001840 }
1841
Colin Cross5f03f112017-11-07 13:29:54 -08001842 depsModules, errs := c.generateModuleBuildActions(config, c.liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001843 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001844 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001845 }
1846
Colin Cross5f03f112017-11-07 13:29:54 -08001847 depsSingletons, errs := c.generateSingletonBuildActions(config, c.singletonInfo, c.liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001848 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001849 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001850 }
1851
Colin Cross874a3462017-07-31 17:26:06 -07001852 deps = append(deps, depsModules...)
1853 deps = append(deps, depsSingletons...)
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001854
Colin Crossa2599452015-11-18 16:01:01 -08001855 if c.ninjaBuildDir != nil {
Colin Cross5f03f112017-11-07 13:29:54 -08001856 c.liveGlobals.addNinjaStringDeps(c.ninjaBuildDir)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001857 }
1858
Colin Cross5f03f112017-11-07 13:29:54 -08001859 pkgNames, depsPackages := c.makeUniquePackageNames(c.liveGlobals)
Dan Willemsena481ae22015-12-18 15:18:03 -08001860
1861 deps = append(deps, depsPackages...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001862
1863 // This will panic if it finds a problem since it's a programming error.
Colin Cross5f03f112017-11-07 13:29:54 -08001864 c.checkForVariableReferenceCycles(c.liveGlobals.variables, pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001865
1866 c.pkgNames = pkgNames
Colin Cross5f03f112017-11-07 13:29:54 -08001867 c.globalVariables = c.liveGlobals.variables
1868 c.globalPools = c.liveGlobals.pools
1869 c.globalRules = c.liveGlobals.rules
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001870
1871 c.buildActionsReady = true
1872
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001873 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001874}
1875
Colin Cross874a3462017-07-31 17:26:06 -07001876func (c *Context) runMutators(config interface{}) (deps []string, errs []error) {
Colin Crossf8b50422016-08-10 12:56:40 -07001877 var mutators []*mutatorInfo
Colin Cross763b6f12015-10-29 15:32:56 -07001878
Colin Crossf8b50422016-08-10 12:56:40 -07001879 mutators = append(mutators, c.earlyMutatorInfo...)
1880 mutators = append(mutators, c.mutatorInfo...)
1881
1882 for _, mutator := range mutators {
Colin Cross874a3462017-07-31 17:26:06 -07001883 var newDeps []string
Colin Crossc9028482014-12-18 16:28:54 -08001884 if mutator.topDownMutator != nil {
Colin Cross874a3462017-07-31 17:26:06 -07001885 newDeps, errs = c.runMutator(config, mutator, topDownMutator)
Colin Crossc9028482014-12-18 16:28:54 -08001886 } else if mutator.bottomUpMutator != nil {
Colin Cross874a3462017-07-31 17:26:06 -07001887 newDeps, errs = c.runMutator(config, mutator, bottomUpMutator)
Colin Crossc9028482014-12-18 16:28:54 -08001888 } else {
1889 panic("no mutator set on " + mutator.name)
1890 }
1891 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07001892 return nil, errs
Colin Crossc9028482014-12-18 16:28:54 -08001893 }
Colin Cross874a3462017-07-31 17:26:06 -07001894 deps = append(deps, newDeps...)
Colin Crossc9028482014-12-18 16:28:54 -08001895 }
1896
Colin Cross874a3462017-07-31 17:26:06 -07001897 return deps, nil
Colin Crossc9028482014-12-18 16:28:54 -08001898}
1899
Colin Cross3702ac72016-08-11 11:09:00 -07001900type mutatorDirection interface {
1901 run(mutator *mutatorInfo, ctx *mutatorContext)
1902 orderer() visitOrderer
1903 fmt.Stringer
Colin Crossc9028482014-12-18 16:28:54 -08001904}
1905
Colin Cross3702ac72016-08-11 11:09:00 -07001906type bottomUpMutatorImpl struct{}
1907
1908func (bottomUpMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
1909 mutator.bottomUpMutator(ctx)
1910}
1911
1912func (bottomUpMutatorImpl) orderer() visitOrderer {
1913 return bottomUpVisitor
1914}
1915
1916func (bottomUpMutatorImpl) String() string {
1917 return "bottom up mutator"
1918}
1919
1920type topDownMutatorImpl struct{}
1921
1922func (topDownMutatorImpl) run(mutator *mutatorInfo, ctx *mutatorContext) {
1923 mutator.topDownMutator(ctx)
1924}
1925
1926func (topDownMutatorImpl) orderer() visitOrderer {
1927 return topDownVisitor
1928}
1929
1930func (topDownMutatorImpl) String() string {
1931 return "top down mutator"
1932}
1933
1934var (
1935 topDownMutator topDownMutatorImpl
1936 bottomUpMutator bottomUpMutatorImpl
1937)
1938
Colin Cross49c279a2016-08-05 22:30:44 -07001939type reverseDep struct {
1940 module *moduleInfo
1941 dep depInfo
1942}
1943
Colin Cross3702ac72016-08-11 11:09:00 -07001944func (c *Context) runMutator(config interface{}, mutator *mutatorInfo,
Colin Cross874a3462017-07-31 17:26:06 -07001945 direction mutatorDirection) (deps []string, errs []error) {
Colin Cross49c279a2016-08-05 22:30:44 -07001946
1947 newModuleInfo := make(map[Module]*moduleInfo)
1948 for k, v := range c.moduleInfo {
1949 newModuleInfo[k] = v
1950 }
Colin Crossc9028482014-12-18 16:28:54 -08001951
Colin Cross0ce142c2016-12-09 10:29:05 -08001952 type globalStateChange struct {
Colin Crossaf4fd212017-07-28 14:32:36 -07001953 reverse []reverseDep
1954 rename []rename
1955 replace []replace
1956 newModules []*moduleInfo
Colin Cross874a3462017-07-31 17:26:06 -07001957 deps []string
Colin Cross0ce142c2016-12-09 10:29:05 -08001958 }
1959
Colin Cross2c1f3d12016-04-11 15:47:28 -07001960 reverseDeps := make(map[*moduleInfo][]depInfo)
Colin Cross0ce142c2016-12-09 10:29:05 -08001961 var rename []rename
1962 var replace []replace
Colin Crossaf4fd212017-07-28 14:32:36 -07001963 var newModules []*moduleInfo
Colin Cross8d8a7af2015-11-03 16:41:29 -08001964
Colin Cross49c279a2016-08-05 22:30:44 -07001965 errsCh := make(chan []error)
Colin Cross0ce142c2016-12-09 10:29:05 -08001966 globalStateCh := make(chan globalStateChange)
Colin Cross5fe225f2017-07-28 15:22:46 -07001967 newVariationsCh := make(chan []*moduleInfo)
Colin Cross49c279a2016-08-05 22:30:44 -07001968 done := make(chan bool)
Colin Crossc9028482014-12-18 16:28:54 -08001969
Colin Cross3702ac72016-08-11 11:09:00 -07001970 c.depsModified = 0
1971
Colin Cross49c279a2016-08-05 22:30:44 -07001972 visit := func(module *moduleInfo) bool {
Jamie Gennisc7988252015-04-14 23:28:10 -04001973 if module.splitModules != nil {
1974 panic("split module found in sorted module list")
1975 }
1976
Colin Cross7addea32015-03-11 15:43:52 -07001977 mctx := &mutatorContext{
1978 baseModuleContext: baseModuleContext{
1979 context: c,
1980 config: config,
1981 module: module,
1982 },
Colin Cross49c279a2016-08-05 22:30:44 -07001983 name: mutator.name,
Colin Cross7addea32015-03-11 15:43:52 -07001984 }
Colin Crossc9028482014-12-18 16:28:54 -08001985
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001986 func() {
1987 defer func() {
1988 if r := recover(); r != nil {
Colin Cross3702ac72016-08-11 11:09:00 -07001989 in := fmt.Sprintf("%s %q for %s", direction, mutator.name, module)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001990 if err, ok := r.(panicError); ok {
1991 err.addIn(in)
1992 mctx.error(err)
1993 } else {
1994 mctx.error(newPanicErrorf(r, in))
1995 }
1996 }
1997 }()
Colin Cross3702ac72016-08-11 11:09:00 -07001998 direction.run(mutator, mctx)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08001999 }()
Colin Cross49c279a2016-08-05 22:30:44 -07002000
Colin Cross7addea32015-03-11 15:43:52 -07002001 if len(mctx.errs) > 0 {
Colin Cross0fff7422016-08-11 15:37:45 -07002002 errsCh <- mctx.errs
Colin Cross49c279a2016-08-05 22:30:44 -07002003 return true
Colin Cross7addea32015-03-11 15:43:52 -07002004 }
Colin Crossc9028482014-12-18 16:28:54 -08002005
Colin Cross5fe225f2017-07-28 15:22:46 -07002006 if len(mctx.newVariations) > 0 {
2007 newVariationsCh <- mctx.newVariations
Colin Cross49c279a2016-08-05 22:30:44 -07002008 }
2009
Colin Crossaf4fd212017-07-28 14:32:36 -07002010 if len(mctx.reverseDeps) > 0 || len(mctx.replace) > 0 || len(mctx.rename) > 0 || len(mctx.newModules) > 0 {
Colin Cross0ce142c2016-12-09 10:29:05 -08002011 globalStateCh <- globalStateChange{
Colin Crossaf4fd212017-07-28 14:32:36 -07002012 reverse: mctx.reverseDeps,
2013 replace: mctx.replace,
2014 rename: mctx.rename,
2015 newModules: mctx.newModules,
Colin Cross874a3462017-07-31 17:26:06 -07002016 deps: mctx.ninjaFileDeps,
Colin Cross0ce142c2016-12-09 10:29:05 -08002017 }
Colin Cross49c279a2016-08-05 22:30:44 -07002018 }
2019
2020 return false
2021 }
2022
2023 // Process errs and reverseDeps in a single goroutine
2024 go func() {
2025 for {
2026 select {
2027 case newErrs := <-errsCh:
2028 errs = append(errs, newErrs...)
Colin Cross0ce142c2016-12-09 10:29:05 -08002029 case globalStateChange := <-globalStateCh:
2030 for _, r := range globalStateChange.reverse {
Colin Cross49c279a2016-08-05 22:30:44 -07002031 reverseDeps[r.module] = append(reverseDeps[r.module], r.dep)
2032 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002033 replace = append(replace, globalStateChange.replace...)
2034 rename = append(rename, globalStateChange.rename...)
Colin Crossaf4fd212017-07-28 14:32:36 -07002035 newModules = append(newModules, globalStateChange.newModules...)
Colin Cross874a3462017-07-31 17:26:06 -07002036 deps = append(deps, globalStateChange.deps...)
Colin Cross5fe225f2017-07-28 15:22:46 -07002037 case newVariations := <-newVariationsCh:
2038 for _, m := range newVariations {
Colin Cross49c279a2016-08-05 22:30:44 -07002039 newModuleInfo[m.logicModule] = m
2040 }
2041 case <-done:
2042 return
Colin Crossc9028482014-12-18 16:28:54 -08002043 }
2044 }
Colin Cross49c279a2016-08-05 22:30:44 -07002045 }()
Colin Crossc9028482014-12-18 16:28:54 -08002046
Colin Cross49c279a2016-08-05 22:30:44 -07002047 if mutator.parallel {
Colin Cross3702ac72016-08-11 11:09:00 -07002048 c.parallelVisit(direction.orderer(), visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002049 } else {
Colin Cross3702ac72016-08-11 11:09:00 -07002050 direction.orderer().visit(c.modulesSorted, visit)
Colin Cross49c279a2016-08-05 22:30:44 -07002051 }
2052
2053 done <- true
2054
2055 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002056 return nil, errs
Colin Cross49c279a2016-08-05 22:30:44 -07002057 }
2058
2059 c.moduleInfo = newModuleInfo
2060
2061 for _, group := range c.moduleGroups {
2062 for i := 0; i < len(group.modules); i++ {
2063 module := group.modules[i]
2064
2065 // Update module group to contain newly split variants
2066 if module.splitModules != nil {
2067 group.modules, i = spliceModules(group.modules, i, module.splitModules)
2068 }
2069
2070 // Fix up any remaining dependencies on modules that were split into variants
2071 // by replacing them with the first variant
2072 for j, dep := range module.directDeps {
2073 if dep.module.logicModule == nil {
2074 module.directDeps[j].module = dep.module.splitModules[0]
2075 }
2076 }
Colin Cross7addea32015-03-11 15:43:52 -07002077 }
Colin Crossc9028482014-12-18 16:28:54 -08002078 }
2079
Colin Cross8d8a7af2015-11-03 16:41:29 -08002080 for module, deps := range reverseDeps {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002081 sort.Sort(depSorter(deps))
Colin Cross8d8a7af2015-11-03 16:41:29 -08002082 module.directDeps = append(module.directDeps, deps...)
Colin Cross3702ac72016-08-11 11:09:00 -07002083 c.depsModified++
Colin Cross8d8a7af2015-11-03 16:41:29 -08002084 }
2085
Colin Crossaf4fd212017-07-28 14:32:36 -07002086 for _, module := range newModules {
2087 errs = c.addModule(module)
2088 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002089 return nil, errs
Colin Crossaf4fd212017-07-28 14:32:36 -07002090 }
2091 atomic.AddUint32(&c.depsModified, 1)
2092 }
2093
Colin Cross0ce142c2016-12-09 10:29:05 -08002094 errs = c.handleRenames(rename)
2095 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002096 return nil, errs
Colin Cross0ce142c2016-12-09 10:29:05 -08002097 }
2098
2099 errs = c.handleReplacements(replace)
Colin Crossc4e5b812016-10-12 10:45:05 -07002100 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002101 return nil, errs
Colin Crossc4e5b812016-10-12 10:45:05 -07002102 }
2103
Colin Cross3702ac72016-08-11 11:09:00 -07002104 if c.depsModified > 0 {
2105 errs = c.updateDependencies()
2106 if len(errs) > 0 {
Colin Cross874a3462017-07-31 17:26:06 -07002107 return nil, errs
Colin Cross3702ac72016-08-11 11:09:00 -07002108 }
Colin Crossc9028482014-12-18 16:28:54 -08002109 }
2110
Colin Cross874a3462017-07-31 17:26:06 -07002111 return deps, errs
Colin Crossc9028482014-12-18 16:28:54 -08002112}
2113
Colin Cross910242b2016-04-11 15:41:52 -07002114// Replaces every build logic module with a clone of itself. Prevents introducing problems where
2115// a mutator sets a non-property member variable on a module, which works until a later mutator
2116// creates variants of that module.
2117func (c *Context) cloneModules() {
Colin Crossc93490c2016-08-09 14:21:02 -07002118 type update struct {
2119 orig Module
2120 clone *moduleInfo
2121 }
2122 ch := make(chan update, 100)
2123
Colin Cross910242b2016-04-11 15:41:52 -07002124 for _, m := range c.modulesSorted {
Colin Crossc93490c2016-08-09 14:21:02 -07002125 go func(m *moduleInfo) {
2126 origLogicModule := m.logicModule
Colin Crossd2f4ac12017-07-28 14:31:03 -07002127 m.logicModule, m.properties = c.cloneLogicModule(m)
Colin Crossc93490c2016-08-09 14:21:02 -07002128 ch <- update{origLogicModule, m}
2129 }(m)
2130 }
2131
2132 for i := 0; i < len(c.modulesSorted); i++ {
2133 update := <-ch
2134 delete(c.moduleInfo, update.orig)
2135 c.moduleInfo[update.clone.logicModule] = update.clone
Colin Cross910242b2016-04-11 15:41:52 -07002136 }
2137}
2138
Colin Cross49c279a2016-08-05 22:30:44 -07002139// Removes modules[i] from the list and inserts newModules... where it was located, returning
2140// the new slice and the index of the last inserted element
2141func spliceModules(modules []*moduleInfo, i int, newModules []*moduleInfo) ([]*moduleInfo, int) {
Colin Cross7addea32015-03-11 15:43:52 -07002142 spliceSize := len(newModules)
2143 newLen := len(modules) + spliceSize - 1
2144 var dest []*moduleInfo
2145 if cap(modules) >= len(modules)-1+len(newModules) {
2146 // We can fit the splice in the existing capacity, do everything in place
2147 dest = modules[:newLen]
2148 } else {
2149 dest = make([]*moduleInfo, newLen)
2150 copy(dest, modules[:i])
2151 }
2152
2153 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07002154 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07002155
2156 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07002157 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07002158
Colin Cross49c279a2016-08-05 22:30:44 -07002159 return dest, i + spliceSize - 1
Colin Cross7addea32015-03-11 15:43:52 -07002160}
2161
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002162func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002163 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002164
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002165 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002166 var errs []error
2167
Colin Cross691a60d2015-01-07 18:08:56 -08002168 cancelCh := make(chan struct{})
2169 errsCh := make(chan []error)
2170 depsCh := make(chan []string)
2171
2172 go func() {
2173 for {
2174 select {
2175 case <-cancelCh:
2176 close(cancelCh)
2177 return
2178 case newErrs := <-errsCh:
2179 errs = append(errs, newErrs...)
2180 case newDeps := <-depsCh:
2181 deps = append(deps, newDeps...)
2182
2183 }
2184 }
2185 }()
2186
Colin Cross3702ac72016-08-11 11:09:00 -07002187 c.parallelVisit(bottomUpVisitor, func(module *moduleInfo) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08002188
2189 uniqueName := c.nameInterface.UniqueName(newNamespaceContext(module), module.group.name)
2190 sanitizedName := toNinjaName(uniqueName)
2191
2192 prefix := moduleNamespacePrefix(sanitizedName + "_" + module.variantName)
2193
Colin Cross7addea32015-03-11 15:43:52 -07002194 // The parent scope of the moduleContext's local scope gets overridden to be that of the
2195 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2196 // just set it to nil.
Colin Cross7addea32015-03-11 15:43:52 -07002197 scope := newLocalScope(nil, prefix)
Colin Cross6134a5c2015-02-10 11:26:26 -08002198
Colin Cross7addea32015-03-11 15:43:52 -07002199 mctx := &moduleContext{
2200 baseModuleContext: baseModuleContext{
2201 context: c,
2202 config: config,
2203 module: module,
2204 },
Colin Cross036a1df2015-12-17 15:49:30 -08002205 scope: scope,
2206 handledMissingDeps: module.missingDeps == nil,
Colin Cross7addea32015-03-11 15:43:52 -07002207 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002208
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002209 func() {
2210 defer func() {
2211 if r := recover(); r != nil {
2212 in := fmt.Sprintf("GenerateBuildActions for %s", module)
2213 if err, ok := r.(panicError); ok {
2214 err.addIn(in)
2215 mctx.error(err)
2216 } else {
2217 mctx.error(newPanicErrorf(r, in))
2218 }
2219 }
2220 }()
2221 mctx.module.logicModule.GenerateBuildActions(mctx)
2222 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002223
Colin Cross7addea32015-03-11 15:43:52 -07002224 if len(mctx.errs) > 0 {
2225 errsCh <- mctx.errs
2226 return true
2227 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002228
Colin Cross036a1df2015-12-17 15:49:30 -08002229 if module.missingDeps != nil && !mctx.handledMissingDeps {
2230 var errs []error
2231 for _, depName := range module.missingDeps {
Jeff Gastond70bf752017-11-10 15:12:08 -08002232 errs = append(errs, c.missingDependencyError(module, depName))
Colin Cross036a1df2015-12-17 15:49:30 -08002233 }
2234 errsCh <- errs
2235 return true
2236 }
2237
Colin Cross7addea32015-03-11 15:43:52 -07002238 depsCh <- mctx.ninjaFileDeps
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002239
Colin Crossab6d7902015-03-11 16:17:52 -07002240 newErrs := c.processLocalBuildActions(&module.actionDefs,
Colin Cross7addea32015-03-11 15:43:52 -07002241 &mctx.actionDefs, liveGlobals)
2242 if len(newErrs) > 0 {
2243 errsCh <- newErrs
2244 return true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002245 }
Colin Cross8900e9b2015-03-02 14:03:01 -08002246 return false
Colin Cross691a60d2015-01-07 18:08:56 -08002247 })
2248
2249 cancelCh <- struct{}{}
2250 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002251
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002252 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002253}
2254
Jamie Gennis6eb4d242014-06-11 18:31:16 -07002255func (c *Context) generateSingletonBuildActions(config interface{},
Colin Cross5f03f112017-11-07 13:29:54 -08002256 singletons []*singletonInfo, liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002257
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002258 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002259 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002260
Colin Cross5f03f112017-11-07 13:29:54 -08002261 for _, info := range singletons {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002262 // The parent scope of the singletonContext's local scope gets overridden to be that of the
2263 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
2264 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07002265 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002266
2267 sctx := &singletonContext{
2268 context: c,
2269 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002270 scope: scope,
Dan Willemsen4bb62762016-01-14 15:42:54 -08002271 globals: liveGlobals,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002272 }
2273
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002274 func() {
2275 defer func() {
2276 if r := recover(); r != nil {
2277 in := fmt.Sprintf("GenerateBuildActions for singleton %s", info.name)
2278 if err, ok := r.(panicError); ok {
2279 err.addIn(in)
2280 sctx.error(err)
2281 } else {
2282 sctx.error(newPanicErrorf(r, in))
2283 }
2284 }
2285 }()
2286 info.singleton.GenerateBuildActions(sctx)
2287 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002288
2289 if len(sctx.errs) > 0 {
2290 errs = append(errs, sctx.errs...)
2291 if len(errs) > maxErrors {
2292 break
2293 }
2294 continue
2295 }
2296
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002297 deps = append(deps, sctx.ninjaFileDeps...)
2298
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002299 newErrs := c.processLocalBuildActions(&info.actionDefs,
2300 &sctx.actionDefs, liveGlobals)
2301 errs = append(errs, newErrs...)
2302 if len(errs) > maxErrors {
2303 break
2304 }
2305 }
2306
Mathias Agopian5b8477d2014-06-25 17:21:54 -07002307 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002308}
2309
2310func (c *Context) processLocalBuildActions(out, in *localBuildActions,
2311 liveGlobals *liveTracker) []error {
2312
2313 var errs []error
2314
2315 // First we go through and add everything referenced by the module's
2316 // buildDefs to the live globals set. This will end up adding the live
2317 // locals to the set as well, but we'll take them out after.
2318 for _, def := range in.buildDefs {
2319 err := liveGlobals.AddBuildDefDeps(def)
2320 if err != nil {
2321 errs = append(errs, err)
2322 }
2323 }
2324
2325 if len(errs) > 0 {
2326 return errs
2327 }
2328
Colin Crossc9028482014-12-18 16:28:54 -08002329 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002330
2331 // We use the now-incorrect set of live "globals" to determine which local
2332 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08002333 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002334 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07002335 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002336 if isLive {
2337 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002338 }
2339 }
2340
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002341 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07002342 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002343 if isLive {
2344 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002345 }
2346 }
2347
2348 return nil
2349}
2350
Yuchen Wu222e2452015-10-06 14:03:27 -07002351func (c *Context) walkDeps(topModule *moduleInfo,
Colin Crossbafd5f52016-08-06 22:52:01 -07002352 visitDown func(depInfo, *moduleInfo) bool, visitUp func(depInfo, *moduleInfo)) {
Yuchen Wu222e2452015-10-06 14:03:27 -07002353
2354 visited := make(map[*moduleInfo]bool)
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002355 var visiting *moduleInfo
2356
2357 defer func() {
2358 if r := recover(); r != nil {
Colin Crossbafd5f52016-08-06 22:52:01 -07002359 panic(newPanicErrorf(r, "WalkDeps(%s, %s, %s) for dependency %s",
2360 topModule, funcName(visitDown), funcName(visitUp), visiting))
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002361 }
2362 }()
Yuchen Wu222e2452015-10-06 14:03:27 -07002363
2364 var walk func(module *moduleInfo)
2365 walk = func(module *moduleInfo) {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002366 for _, dep := range module.directDeps {
2367 if !visited[dep.module] {
2368 visited[dep.module] = true
2369 visiting = dep.module
Colin Crossbafd5f52016-08-06 22:52:01 -07002370 recurse := true
2371 if visitDown != nil {
2372 recurse = visitDown(dep, module)
2373 }
2374 if recurse {
Colin Cross2c1f3d12016-04-11 15:47:28 -07002375 walk(dep.module)
Yuchen Wu222e2452015-10-06 14:03:27 -07002376 }
Colin Crossbafd5f52016-08-06 22:52:01 -07002377 if visitUp != nil {
2378 visitUp(dep, module)
2379 }
Yuchen Wu222e2452015-10-06 14:03:27 -07002380 }
2381 }
2382 }
2383
2384 walk(topModule)
2385}
2386
Colin Cross9cfd1982016-10-11 09:58:53 -07002387type replace struct {
2388 from, to *moduleInfo
2389}
2390
Colin Crossc4e5b812016-10-12 10:45:05 -07002391type rename struct {
2392 group *moduleGroup
2393 name string
2394}
2395
Colin Cross0ce142c2016-12-09 10:29:05 -08002396func (c *Context) moduleMatchingVariant(module *moduleInfo, name string) *moduleInfo {
Jeff Gastond70bf752017-11-10 15:12:08 -08002397 targets := c.modulesFromName(name, module.namespace())
Colin Cross9cfd1982016-10-11 09:58:53 -07002398
2399 if targets == nil {
Colin Cross0ce142c2016-12-09 10:29:05 -08002400 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07002401 }
2402
Colin Cross9cfd1982016-10-11 09:58:53 -07002403 for _, m := range targets {
2404 if module.variantName == m.variantName {
Colin Cross0ce142c2016-12-09 10:29:05 -08002405 return m
Colin Cross9cfd1982016-10-11 09:58:53 -07002406 }
2407 }
2408
Colin Cross0ce142c2016-12-09 10:29:05 -08002409 return nil
Colin Cross9cfd1982016-10-11 09:58:53 -07002410}
2411
Colin Cross0ce142c2016-12-09 10:29:05 -08002412func (c *Context) handleRenames(renames []rename) []error {
Colin Crossc4e5b812016-10-12 10:45:05 -07002413 var errs []error
Colin Cross0ce142c2016-12-09 10:29:05 -08002414 for _, rename := range renames {
Colin Crossc4e5b812016-10-12 10:45:05 -07002415 group, name := rename.group, rename.name
Jeff Gastond70bf752017-11-10 15:12:08 -08002416 if name == group.name || len(group.modules) < 1 {
Colin Crossc4e5b812016-10-12 10:45:05 -07002417 continue
2418 }
2419
Jeff Gastond70bf752017-11-10 15:12:08 -08002420 errs = append(errs, c.nameInterface.Rename(group.name, rename.name, group.namespace)...)
Colin Crossc4e5b812016-10-12 10:45:05 -07002421 }
2422
Colin Cross0ce142c2016-12-09 10:29:05 -08002423 return errs
2424}
2425
2426func (c *Context) handleReplacements(replacements []replace) []error {
2427 var errs []error
2428 for _, replace := range replacements {
Colin Cross9cfd1982016-10-11 09:58:53 -07002429 for _, m := range replace.from.reverseDeps {
2430 for i, d := range m.directDeps {
2431 if d.module == replace.from {
2432 m.directDeps[i].module = replace.to
2433 }
2434 }
2435 }
2436
2437 atomic.AddUint32(&c.depsModified, 1)
2438 }
Colin Cross0ce142c2016-12-09 10:29:05 -08002439
Colin Crossc4e5b812016-10-12 10:45:05 -07002440 return errs
2441}
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002442
Jeff Gastond70bf752017-11-10 15:12:08 -08002443func (c *Context) discoveredMissingDependencies(module *moduleInfo, depName string) (errs []error) {
2444 if c.allowMissingDependencies {
2445 module.missingDeps = append(module.missingDeps, depName)
2446 return nil
2447 }
2448 return []error{c.missingDependencyError(module, depName)}
2449}
2450
2451func (c *Context) missingDependencyError(module *moduleInfo, depName string) (errs error) {
2452 err := c.nameInterface.MissingDependencyError(module.Name(), module.namespace(), depName)
2453
2454 return &BlueprintError{
2455 Err: err,
2456 Pos: module.pos,
2457 }
2458}
2459
2460func (c *Context) modulesFromName(name string, namespace Namespace) []*moduleInfo {
2461 group, exists := c.nameInterface.ModuleFromName(name, namespace)
2462 if exists {
Colin Cross0b7e83e2016-05-17 14:58:05 -07002463 return group.modules
2464 }
2465 return nil
2466}
2467
Jeff Gastond70bf752017-11-10 15:12:08 -08002468func (c *Context) sortedModuleGroups() []*moduleGroup {
2469 if c.cachedSortedModuleGroups == nil {
2470 unwrap := func(wrappers []ModuleGroup) []*moduleGroup {
2471 result := make([]*moduleGroup, 0, len(wrappers))
2472 for _, group := range wrappers {
2473 result = append(result, group.moduleGroup)
2474 }
2475 return result
Jamie Gennisc15544d2014-09-24 20:26:52 -07002476 }
Jeff Gastond70bf752017-11-10 15:12:08 -08002477
2478 c.cachedSortedModuleGroups = unwrap(c.nameInterface.AllModules())
Jamie Gennisc15544d2014-09-24 20:26:52 -07002479 }
2480
Jeff Gastond70bf752017-11-10 15:12:08 -08002481 return c.cachedSortedModuleGroups
Jamie Gennisc15544d2014-09-24 20:26:52 -07002482}
2483
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002484func (c *Context) visitAllModules(visit func(Module)) {
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002485 var module *moduleInfo
2486
2487 defer func() {
2488 if r := recover(); r != nil {
2489 panic(newPanicErrorf(r, "VisitAllModules(%s) for %s",
2490 funcName(visit), module))
2491 }
2492 }()
2493
Jeff Gastond70bf752017-11-10 15:12:08 -08002494 for _, moduleGroup := range c.sortedModuleGroups() {
2495 for _, module = range moduleGroup.modules {
Colin Crossbbfa51a2014-12-17 16:12:41 -08002496 visit(module.logicModule)
2497 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002498 }
2499}
2500
2501func (c *Context) visitAllModulesIf(pred func(Module) bool,
2502 visit func(Module)) {
2503
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002504 var module *moduleInfo
2505
2506 defer func() {
2507 if r := recover(); r != nil {
2508 panic(newPanicErrorf(r, "VisitAllModulesIf(%s, %s) for %s",
2509 funcName(pred), funcName(visit), module))
2510 }
2511 }()
2512
Jeff Gastond70bf752017-11-10 15:12:08 -08002513 for _, moduleGroup := range c.sortedModuleGroups() {
2514 for _, module := range moduleGroup.modules {
Colin Crossbbfa51a2014-12-17 16:12:41 -08002515 if pred(module.logicModule) {
2516 visit(module.logicModule)
2517 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002518 }
2519 }
2520}
2521
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002522func (c *Context) visitAllModuleVariants(module *moduleInfo,
2523 visit func(Module)) {
2524
2525 var variant *moduleInfo
2526
2527 defer func() {
2528 if r := recover(); r != nil {
2529 panic(newPanicErrorf(r, "VisitAllModuleVariants(%s, %s) for %s",
2530 module, funcName(visit), variant))
2531 }
2532 }()
2533
2534 for _, variant = range module.group.modules {
2535 visit(variant.logicModule)
2536 }
2537}
2538
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002539func (c *Context) requireNinjaVersion(major, minor, micro int) {
2540 if major != 1 {
2541 panic("ninja version with major version != 1 not supported")
2542 }
2543 if c.requiredNinjaMinor < minor {
2544 c.requiredNinjaMinor = minor
2545 c.requiredNinjaMicro = micro
2546 }
2547 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
2548 c.requiredNinjaMicro = micro
2549 }
2550}
2551
Colin Crossa2599452015-11-18 16:01:01 -08002552func (c *Context) setNinjaBuildDir(value *ninjaString) {
2553 if c.ninjaBuildDir == nil {
2554 c.ninjaBuildDir = value
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002555 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002556}
2557
2558func (c *Context) makeUniquePackageNames(
Dan Willemsena481ae22015-12-18 15:18:03 -08002559 liveGlobals *liveTracker) (map[*packageContext]string, []string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002560
Dan Willemsenaeffbf72015-11-25 15:29:32 -08002561 pkgs := make(map[string]*packageContext)
2562 pkgNames := make(map[*packageContext]string)
2563 longPkgNames := make(map[*packageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002564
Dan Willemsenaeffbf72015-11-25 15:29:32 -08002565 processPackage := func(pctx *packageContext) {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002566 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002567 // This is a built-in rule and has no package.
2568 return
2569 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07002570 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002571 // We've already processed this package.
2572 return
2573 }
2574
Jamie Gennis2fb20952014-10-03 02:49:58 -07002575 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002576 if present {
2577 // Short name collision. Both this package and the one that's
2578 // already there need to use their full names. We leave the short
2579 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07002580 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002581 longPkgNames[otherPkg] = true
2582 } else {
2583 // No collision so far. Tentatively set the package's name to be
2584 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07002585 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07002586 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002587 }
2588 }
2589
2590 // We try to give all packages their short name, but when we get collisions
2591 // we need to use the full unique package name.
2592 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002593 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002594 }
2595 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002596 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002597 }
2598 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002599 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002600 }
2601
2602 // Add the packages that had collisions using their full unique names. This
2603 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07002604 for pctx := range longPkgNames {
2605 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002606 }
2607
Dan Willemsena481ae22015-12-18 15:18:03 -08002608 // Create deps list from calls to PackageContext.AddNinjaFileDeps
2609 deps := []string{}
2610 for _, pkg := range pkgs {
2611 deps = append(deps, pkg.ninjaFileDeps...)
2612 }
2613
2614 return pkgNames, deps
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002615}
2616
2617func (c *Context) checkForVariableReferenceCycles(
Dan Willemsenaeffbf72015-11-25 15:29:32 -08002618 variables map[Variable]*ninjaString, pkgNames map[*packageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002619
2620 visited := make(map[Variable]bool) // variables that were already checked
2621 checking := make(map[Variable]bool) // variables actively being checked
2622
2623 var check func(v Variable) []Variable
2624
2625 check = func(v Variable) []Variable {
2626 visited[v] = true
2627 checking[v] = true
2628 defer delete(checking, v)
2629
2630 value := variables[v]
2631 for _, dep := range value.variables {
2632 if checking[dep] {
2633 // This is a cycle.
2634 return []Variable{dep, v}
2635 }
2636
2637 if !visited[dep] {
2638 cycle := check(dep)
2639 if cycle != nil {
2640 if cycle[0] == v {
2641 // We are the "start" of the cycle, so we're responsible
2642 // for generating the errors. The cycle list is in
2643 // reverse order because all the 'check' calls append
2644 // their own module to the list.
2645 msgs := []string{"detected variable reference cycle:"}
2646
2647 // Iterate backwards through the cycle list.
2648 curName := v.fullName(pkgNames)
2649 curValue := value.Value(pkgNames)
2650 for i := len(cycle) - 1; i >= 0; i-- {
2651 next := cycle[i]
2652 nextName := next.fullName(pkgNames)
2653 nextValue := variables[next].Value(pkgNames)
2654
2655 msgs = append(msgs, fmt.Sprintf(
2656 " %q depends on %q", curName, nextName))
2657 msgs = append(msgs, fmt.Sprintf(
2658 " [%s = %s]", curName, curValue))
2659
2660 curName = nextName
2661 curValue = nextValue
2662 }
2663
2664 // Variable reference cycles are a programming error,
2665 // not the fault of the Blueprint file authors.
2666 panic(strings.Join(msgs, "\n"))
2667 } else {
2668 // We're not the "start" of the cycle, so we just append
2669 // our module to the list and return it.
2670 return append(cycle, v)
2671 }
2672 }
2673 }
2674 }
2675
2676 return nil
2677 }
2678
2679 for v := range variables {
2680 if !visited[v] {
2681 cycle := check(v)
2682 if cycle != nil {
2683 panic("inconceivable!")
2684 }
2685 }
2686 }
2687}
2688
Jamie Gennisaf435562014-10-27 22:34:56 -07002689// AllTargets returns a map all the build target names to the rule used to build
2690// them. This is the same information that is output by running 'ninja -t
2691// targets all'. If this is called before PrepareBuildActions successfully
2692// completes then ErrbuildActionsNotReady is returned.
2693func (c *Context) AllTargets() (map[string]string, error) {
2694 if !c.buildActionsReady {
2695 return nil, ErrBuildActionsNotReady
2696 }
2697
2698 targets := map[string]string{}
2699
2700 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07002701 for _, module := range c.moduleInfo {
2702 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07002703 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07002704 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08002705 outputValue, err := output.Eval(c.globalVariables)
2706 if err != nil {
2707 return nil, err
2708 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002709 targets[outputValue] = ruleName
2710 }
2711 }
2712 }
2713
2714 // Collect all the singleton build targets.
2715 for _, info := range c.singletonInfo {
2716 for _, buildDef := range info.actionDefs.buildDefs {
2717 ruleName := buildDef.Rule.fullName(c.pkgNames)
Dan Willemsen5c43e072016-10-25 21:26:12 -07002718 for _, output := range append(buildDef.Outputs, buildDef.ImplicitOutputs...) {
Christian Zander6e2b2322014-11-21 15:12:08 -08002719 outputValue, err := output.Eval(c.globalVariables)
2720 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08002721 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08002722 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002723 targets[outputValue] = ruleName
2724 }
2725 }
2726 }
2727
2728 return targets, nil
2729}
2730
Colin Crossa2599452015-11-18 16:01:01 -08002731func (c *Context) NinjaBuildDir() (string, error) {
2732 if c.ninjaBuildDir != nil {
2733 return c.ninjaBuildDir.Eval(c.globalVariables)
2734 } else {
2735 return "", nil
2736 }
2737}
2738
Colin Cross4572edd2015-05-13 14:36:24 -07002739// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
2740// property structs returned by the factory for that module type.
2741func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
2742 ret := make(map[string][]interface{})
2743 for moduleType, factory := range c.moduleFactories {
2744 _, ret[moduleType] = factory()
2745 }
2746
2747 return ret
2748}
2749
2750func (c *Context) ModuleName(logicModule Module) string {
2751 module := c.moduleInfo[logicModule]
Colin Cross0b7e83e2016-05-17 14:58:05 -07002752 return module.Name()
Colin Cross4572edd2015-05-13 14:36:24 -07002753}
2754
Jeff Gaston3c8c3342017-11-30 17:30:42 -08002755func (c *Context) ModulePath(logicModule Module) string {
Colin Cross4572edd2015-05-13 14:36:24 -07002756 module := c.moduleInfo[logicModule]
Jeff Gaston3c8c3342017-11-30 17:30:42 -08002757 return module.relBlueprintsFile
2758}
2759
2760func (c *Context) ModuleDir(logicModule Module) string {
2761 return filepath.Dir(c.ModulePath(logicModule))
Colin Cross4572edd2015-05-13 14:36:24 -07002762}
2763
Colin Cross8c602f72015-12-17 18:02:11 -08002764func (c *Context) ModuleSubDir(logicModule Module) string {
2765 module := c.moduleInfo[logicModule]
2766 return module.variantName
2767}
2768
Dan Willemsenc98e55b2016-07-25 15:51:50 -07002769func (c *Context) ModuleType(logicModule Module) string {
2770 module := c.moduleInfo[logicModule]
2771 return module.typeName
2772}
2773
Colin Cross4572edd2015-05-13 14:36:24 -07002774func (c *Context) BlueprintFile(logicModule Module) string {
2775 module := c.moduleInfo[logicModule]
2776 return module.relBlueprintsFile
2777}
2778
2779func (c *Context) ModuleErrorf(logicModule Module, format string,
2780 args ...interface{}) error {
2781
2782 module := c.moduleInfo[logicModule]
Colin Cross2c628442016-10-07 17:13:10 -07002783 return &BlueprintError{
Colin Cross4572edd2015-05-13 14:36:24 -07002784 Err: fmt.Errorf(format, args...),
2785 Pos: module.pos,
2786 }
2787}
2788
2789func (c *Context) VisitAllModules(visit func(Module)) {
2790 c.visitAllModules(visit)
2791}
2792
2793func (c *Context) VisitAllModulesIf(pred func(Module) bool,
2794 visit func(Module)) {
2795
2796 c.visitAllModulesIf(pred, visit)
2797}
2798
Colin Cross080c1332017-03-17 13:09:05 -07002799func (c *Context) VisitDirectDeps(module Module, visit func(Module)) {
2800 topModule := c.moduleInfo[module]
Colin Cross4572edd2015-05-13 14:36:24 -07002801
Colin Cross080c1332017-03-17 13:09:05 -07002802 var visiting *moduleInfo
2803
2804 defer func() {
2805 if r := recover(); r != nil {
2806 panic(newPanicErrorf(r, "VisitDirectDeps(%s, %s) for dependency %s",
2807 topModule, funcName(visit), visiting))
2808 }
2809 }()
2810
2811 for _, dep := range topModule.directDeps {
2812 visiting = dep.module
2813 visit(dep.module.logicModule)
2814 }
2815}
2816
2817func (c *Context) VisitDirectDepsIf(module Module, pred func(Module) bool, visit func(Module)) {
2818 topModule := c.moduleInfo[module]
2819
2820 var visiting *moduleInfo
2821
2822 defer func() {
2823 if r := recover(); r != nil {
2824 panic(newPanicErrorf(r, "VisitDirectDepsIf(%s, %s, %s) for dependency %s",
2825 topModule, funcName(pred), funcName(visit), visiting))
2826 }
2827 }()
2828
2829 for _, dep := range topModule.directDeps {
2830 visiting = dep.module
2831 if pred(dep.module.logicModule) {
2832 visit(dep.module.logicModule)
2833 }
2834 }
2835}
2836
2837func (c *Context) VisitDepsDepthFirst(module Module, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07002838 topModule := c.moduleInfo[module]
2839
2840 var visiting *moduleInfo
2841
2842 defer func() {
2843 if r := recover(); r != nil {
2844 panic(newPanicErrorf(r, "VisitDepsDepthFirst(%s, %s) for dependency %s",
2845 topModule, funcName(visit), visiting))
2846 }
2847 }()
2848
2849 c.walkDeps(topModule, nil, func(dep depInfo, parent *moduleInfo) {
2850 visiting = dep.module
2851 visit(dep.module.logicModule)
2852 })
Colin Cross4572edd2015-05-13 14:36:24 -07002853}
2854
Colin Cross080c1332017-03-17 13:09:05 -07002855func (c *Context) VisitDepsDepthFirstIf(module Module, pred func(Module) bool, visit func(Module)) {
Colin Crossbafd5f52016-08-06 22:52:01 -07002856 topModule := c.moduleInfo[module]
2857
2858 var visiting *moduleInfo
2859
2860 defer func() {
2861 if r := recover(); r != nil {
2862 panic(newPanicErrorf(r, "VisitDepsDepthFirstIf(%s, %s, %s) for dependency %s",
2863 topModule, funcName(pred), funcName(visit), visiting))
2864 }
2865 }()
2866
2867 c.walkDeps(topModule, nil, func(dep depInfo, parent *moduleInfo) {
2868 if pred(dep.module.logicModule) {
2869 visiting = dep.module
2870 visit(dep.module.logicModule)
2871 }
2872 })
Colin Cross4572edd2015-05-13 14:36:24 -07002873}
2874
Colin Cross24ad5872015-11-17 16:22:29 -08002875func (c *Context) PrimaryModule(module Module) Module {
2876 return c.moduleInfo[module].group.modules[0].logicModule
2877}
2878
2879func (c *Context) FinalModule(module Module) Module {
2880 modules := c.moduleInfo[module].group.modules
2881 return modules[len(modules)-1].logicModule
2882}
2883
2884func (c *Context) VisitAllModuleVariants(module Module,
2885 visit func(Module)) {
2886
Colin Cross0aa6a5f2016-01-07 13:43:09 -08002887 c.visitAllModuleVariants(c.moduleInfo[module], visit)
Colin Cross24ad5872015-11-17 16:22:29 -08002888}
2889
Jamie Gennisd4e10182014-06-12 20:06:50 -07002890// WriteBuildFile writes the Ninja manifeset text for the generated build
2891// actions to w. If this is called before PrepareBuildActions successfully
2892// completes then ErrBuildActionsNotReady is returned.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002893func (c *Context) WriteBuildFile(w io.Writer) error {
2894 if !c.buildActionsReady {
2895 return ErrBuildActionsNotReady
2896 }
2897
2898 nw := newNinjaWriter(w)
2899
2900 err := c.writeBuildFileHeader(nw)
2901 if err != nil {
2902 return err
2903 }
2904
2905 err = c.writeNinjaRequiredVersion(nw)
2906 if err != nil {
2907 return err
2908 }
2909
2910 // TODO: Group the globals by package.
2911
2912 err = c.writeGlobalVariables(nw)
2913 if err != nil {
2914 return err
2915 }
2916
2917 err = c.writeGlobalPools(nw)
2918 if err != nil {
2919 return err
2920 }
2921
2922 err = c.writeBuildDir(nw)
2923 if err != nil {
2924 return err
2925 }
2926
2927 err = c.writeGlobalRules(nw)
2928 if err != nil {
2929 return err
2930 }
2931
2932 err = c.writeAllModuleActions(nw)
2933 if err != nil {
2934 return err
2935 }
2936
2937 err = c.writeAllSingletonActions(nw)
2938 if err != nil {
2939 return err
2940 }
2941
2942 return nil
2943}
2944
Jamie Gennisc15544d2014-09-24 20:26:52 -07002945type pkgAssociation struct {
2946 PkgName string
2947 PkgPath string
2948}
2949
2950type pkgAssociationSorter struct {
2951 pkgs []pkgAssociation
2952}
2953
2954func (s *pkgAssociationSorter) Len() int {
2955 return len(s.pkgs)
2956}
2957
2958func (s *pkgAssociationSorter) Less(i, j int) bool {
2959 iName := s.pkgs[i].PkgName
2960 jName := s.pkgs[j].PkgName
2961 return iName < jName
2962}
2963
2964func (s *pkgAssociationSorter) Swap(i, j int) {
2965 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
2966}
2967
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002968func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
2969 headerTemplate := template.New("fileHeader")
2970 _, err := headerTemplate.Parse(fileHeaderTemplate)
2971 if err != nil {
2972 // This is a programming error.
2973 panic(err)
2974 }
2975
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002976 var pkgs []pkgAssociation
2977 maxNameLen := 0
2978 for pkg, name := range c.pkgNames {
2979 pkgs = append(pkgs, pkgAssociation{
2980 PkgName: name,
2981 PkgPath: pkg.pkgPath,
2982 })
2983 if len(name) > maxNameLen {
2984 maxNameLen = len(name)
2985 }
2986 }
2987
2988 for i := range pkgs {
2989 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
2990 }
2991
Jamie Gennisc15544d2014-09-24 20:26:52 -07002992 sort.Sort(&pkgAssociationSorter{pkgs})
2993
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002994 params := map[string]interface{}{
2995 "Pkgs": pkgs,
2996 }
2997
2998 buf := bytes.NewBuffer(nil)
2999 err = headerTemplate.Execute(buf, params)
3000 if err != nil {
3001 return err
3002 }
3003
3004 return nw.Comment(buf.String())
3005}
3006
3007func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
3008 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
3009 c.requiredNinjaMicro)
3010
3011 err := nw.Assign("ninja_required_version", value)
3012 if err != nil {
3013 return err
3014 }
3015
3016 return nw.BlankLine()
3017}
3018
3019func (c *Context) writeBuildDir(nw *ninjaWriter) error {
Colin Crossa2599452015-11-18 16:01:01 -08003020 if c.ninjaBuildDir != nil {
3021 err := nw.Assign("builddir", c.ninjaBuildDir.Value(c.pkgNames))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003022 if err != nil {
3023 return err
3024 }
3025
3026 err = nw.BlankLine()
3027 if err != nil {
3028 return err
3029 }
3030 }
3031 return nil
3032}
3033
Jamie Gennisc15544d2014-09-24 20:26:52 -07003034type globalEntity interface {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003035 fullName(pkgNames map[*packageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003036}
3037
Jamie Gennisc15544d2014-09-24 20:26:52 -07003038type globalEntitySorter struct {
Dan Willemsenaeffbf72015-11-25 15:29:32 -08003039 pkgNames map[*packageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07003040 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003041}
3042
Jamie Gennisc15544d2014-09-24 20:26:52 -07003043func (s *globalEntitySorter) Len() int {
3044 return len(s.entities)
3045}
3046
3047func (s *globalEntitySorter) Less(i, j int) bool {
3048 iName := s.entities[i].fullName(s.pkgNames)
3049 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003050 return iName < jName
3051}
3052
Jamie Gennisc15544d2014-09-24 20:26:52 -07003053func (s *globalEntitySorter) Swap(i, j int) {
3054 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003055}
3056
3057func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
3058 visited := make(map[Variable]bool)
3059
3060 var walk func(v Variable) error
3061 walk = func(v Variable) error {
3062 visited[v] = true
3063
3064 // First visit variables on which this variable depends.
3065 value := c.globalVariables[v]
3066 for _, dep := range value.variables {
3067 if !visited[dep] {
3068 err := walk(dep)
3069 if err != nil {
3070 return err
3071 }
3072 }
3073 }
3074
3075 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
3076 if err != nil {
3077 return err
3078 }
3079
3080 err = nw.BlankLine()
3081 if err != nil {
3082 return err
3083 }
3084
3085 return nil
3086 }
3087
Jamie Gennisc15544d2014-09-24 20:26:52 -07003088 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
3089 for variable := range c.globalVariables {
3090 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003091 }
3092
Jamie Gennisc15544d2014-09-24 20:26:52 -07003093 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003094
Jamie Gennisc15544d2014-09-24 20:26:52 -07003095 for _, entity := range globalVariables {
3096 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003097 if !visited[v] {
3098 err := walk(v)
3099 if err != nil {
3100 return nil
3101 }
3102 }
3103 }
3104
3105 return nil
3106}
3107
3108func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003109 globalPools := make([]globalEntity, 0, len(c.globalPools))
3110 for pool := range c.globalPools {
3111 globalPools = append(globalPools, pool)
3112 }
3113
3114 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
3115
3116 for _, entity := range globalPools {
3117 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003118 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003119 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003120 err := def.WriteTo(nw, name)
3121 if err != nil {
3122 return err
3123 }
3124
3125 err = nw.BlankLine()
3126 if err != nil {
3127 return err
3128 }
3129 }
3130
3131 return nil
3132}
3133
3134func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07003135 globalRules := make([]globalEntity, 0, len(c.globalRules))
3136 for rule := range c.globalRules {
3137 globalRules = append(globalRules, rule)
3138 }
3139
3140 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
3141
3142 for _, entity := range globalRules {
3143 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003144 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07003145 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003146 err := def.WriteTo(nw, name, c.pkgNames)
3147 if err != nil {
3148 return err
3149 }
3150
3151 err = nw.BlankLine()
3152 if err != nil {
3153 return err
3154 }
3155 }
3156
3157 return nil
3158}
3159
Colin Cross2c1f3d12016-04-11 15:47:28 -07003160type depSorter []depInfo
3161
3162func (s depSorter) Len() int {
3163 return len(s)
3164}
3165
3166func (s depSorter) Less(i, j int) bool {
Colin Cross0b7e83e2016-05-17 14:58:05 -07003167 iName := s[i].module.Name()
3168 jName := s[j].module.Name()
Colin Cross2c1f3d12016-04-11 15:47:28 -07003169 if iName == jName {
3170 iName = s[i].module.variantName
3171 jName = s[j].module.variantName
3172 }
3173 return iName < jName
3174}
3175
3176func (s depSorter) Swap(i, j int) {
3177 s[i], s[j] = s[j], s[i]
3178}
3179
Jeff Gaston0e907592017-12-01 17:10:52 -08003180type moduleSorter struct {
3181 modules []*moduleInfo
3182 nameInterface NameInterface
3183}
Jamie Gennis86179fe2014-06-11 16:27:16 -07003184
Colin Crossab6d7902015-03-11 16:17:52 -07003185func (s moduleSorter) Len() int {
Jeff Gaston0e907592017-12-01 17:10:52 -08003186 return len(s.modules)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003187}
3188
Colin Crossab6d7902015-03-11 16:17:52 -07003189func (s moduleSorter) Less(i, j int) bool {
Jeff Gaston0e907592017-12-01 17:10:52 -08003190 iMod := s.modules[i]
3191 jMod := s.modules[j]
3192 iName := s.nameInterface.UniqueName(newNamespaceContext(iMod), iMod.group.name)
3193 jName := s.nameInterface.UniqueName(newNamespaceContext(jMod), jMod.group.name)
Colin Crossab6d7902015-03-11 16:17:52 -07003194 if iName == jName {
Jeff Gaston0e907592017-12-01 17:10:52 -08003195 iName = s.modules[i].variantName
3196 jName = s.modules[j].variantName
3197 }
3198
3199 if iName == jName {
3200 panic(fmt.Sprintf("duplicate module name: %s: %#v and %#v\n", iName, iMod, jMod))
Colin Crossab6d7902015-03-11 16:17:52 -07003201 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07003202 return iName < jName
3203}
3204
Colin Crossab6d7902015-03-11 16:17:52 -07003205func (s moduleSorter) Swap(i, j int) {
Jeff Gaston0e907592017-12-01 17:10:52 -08003206 s.modules[i], s.modules[j] = s.modules[j], s.modules[i]
Jamie Gennis86179fe2014-06-11 16:27:16 -07003207}
3208
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003209func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
3210 headerTemplate := template.New("moduleHeader")
3211 _, err := headerTemplate.Parse(moduleHeaderTemplate)
3212 if err != nil {
3213 // This is a programming error.
3214 panic(err)
3215 }
3216
Colin Crossab6d7902015-03-11 16:17:52 -07003217 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
3218 for _, module := range c.moduleInfo {
3219 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07003220 }
Jeff Gaston0e907592017-12-01 17:10:52 -08003221 sort.Sort(moduleSorter{modules, c.nameInterface})
Jamie Gennis86179fe2014-06-11 16:27:16 -07003222
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003223 buf := bytes.NewBuffer(nil)
3224
Colin Crossab6d7902015-03-11 16:17:52 -07003225 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003226 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
3227 continue
3228 }
3229
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003230 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003231
3232 // In order to make the bootstrap build manifest independent of the
3233 // build dir we need to output the Blueprints file locations in the
3234 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07003235 relPos := module.pos
3236 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07003237
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003238 // Get the name and location of the factory function for the module.
Colin Crossaf4fd212017-07-28 14:32:36 -07003239 factoryFunc := runtime.FuncForPC(reflect.ValueOf(module.factory).Pointer())
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003240 factoryName := factoryFunc.Name()
3241
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003242 infoMap := map[string]interface{}{
Colin Cross0b7e83e2016-05-17 14:58:05 -07003243 "name": module.Name(),
3244 "typeName": module.typeName,
3245 "goFactory": factoryName,
3246 "pos": relPos,
3247 "variant": module.variantName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003248 }
3249 err = headerTemplate.Execute(buf, infoMap)
3250 if err != nil {
3251 return err
3252 }
3253
3254 err = nw.Comment(buf.String())
3255 if err != nil {
3256 return err
3257 }
3258
3259 err = nw.BlankLine()
3260 if err != nil {
3261 return err
3262 }
3263
Colin Crossab6d7902015-03-11 16:17:52 -07003264 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003265 if err != nil {
3266 return err
3267 }
3268
3269 err = nw.BlankLine()
3270 if err != nil {
3271 return err
3272 }
3273 }
3274
3275 return nil
3276}
3277
3278func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
3279 headerTemplate := template.New("singletonHeader")
3280 _, err := headerTemplate.Parse(singletonHeaderTemplate)
3281 if err != nil {
3282 // This is a programming error.
3283 panic(err)
3284 }
3285
3286 buf := bytes.NewBuffer(nil)
3287
Yuchen Wub9103ef2015-08-25 17:58:17 -07003288 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07003289 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
3290 continue
3291 }
3292
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003293 // Get the name of the factory function for the module.
3294 factory := info.factory
3295 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
3296 factoryName := factoryFunc.Name()
3297
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003298 buf.Reset()
3299 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07003300 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003301 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003302 }
3303 err = headerTemplate.Execute(buf, infoMap)
3304 if err != nil {
3305 return err
3306 }
3307
3308 err = nw.Comment(buf.String())
3309 if err != nil {
3310 return err
3311 }
3312
3313 err = nw.BlankLine()
3314 if err != nil {
3315 return err
3316 }
3317
3318 err = c.writeLocalBuildActions(nw, &info.actionDefs)
3319 if err != nil {
3320 return err
3321 }
3322
3323 err = nw.BlankLine()
3324 if err != nil {
3325 return err
3326 }
3327 }
3328
3329 return nil
3330}
3331
3332func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
3333 defs *localBuildActions) error {
3334
3335 // Write the local variable assignments.
3336 for _, v := range defs.variables {
3337 // A localVariable doesn't need the package names or config to
3338 // determine its name or value.
3339 name := v.fullName(nil)
3340 value, err := v.value(nil)
3341 if err != nil {
3342 panic(err)
3343 }
3344 err = nw.Assign(name, value.Value(c.pkgNames))
3345 if err != nil {
3346 return err
3347 }
3348 }
3349
3350 if len(defs.variables) > 0 {
3351 err := nw.BlankLine()
3352 if err != nil {
3353 return err
3354 }
3355 }
3356
3357 // Write the local rules.
3358 for _, r := range defs.rules {
3359 // A localRule doesn't need the package names or config to determine
3360 // its name or definition.
3361 name := r.fullName(nil)
3362 def, err := r.def(nil)
3363 if err != nil {
3364 panic(err)
3365 }
3366
3367 err = def.WriteTo(nw, name, c.pkgNames)
3368 if err != nil {
3369 return err
3370 }
3371
3372 err = nw.BlankLine()
3373 if err != nil {
3374 return err
3375 }
3376 }
3377
3378 // Write the build definitions.
3379 for _, buildDef := range defs.buildDefs {
3380 err := buildDef.WriteTo(nw, c.pkgNames)
3381 if err != nil {
3382 return err
3383 }
3384
3385 if len(buildDef.Args) > 0 {
3386 err = nw.BlankLine()
3387 if err != nil {
3388 return err
3389 }
3390 }
3391 }
3392
3393 return nil
3394}
3395
Colin Cross65569e42015-03-10 20:08:19 -07003396func beforeInModuleList(a, b *moduleInfo, list []*moduleInfo) bool {
3397 found := false
Colin Cross045a5972015-11-03 16:58:48 -08003398 if a == b {
3399 return false
3400 }
Colin Cross65569e42015-03-10 20:08:19 -07003401 for _, l := range list {
3402 if l == a {
3403 found = true
3404 } else if l == b {
3405 return found
3406 }
3407 }
3408
3409 missing := a
3410 if found {
3411 missing = b
3412 }
3413 panic(fmt.Errorf("element %v not found in list %v", missing, list))
3414}
3415
Colin Cross0aa6a5f2016-01-07 13:43:09 -08003416type panicError struct {
3417 panic interface{}
3418 stack []byte
3419 in string
3420}
3421
3422func newPanicErrorf(panic interface{}, in string, a ...interface{}) error {
3423 buf := make([]byte, 4096)
3424 count := runtime.Stack(buf, false)
3425 return panicError{
3426 panic: panic,
3427 in: fmt.Sprintf(in, a...),
3428 stack: buf[:count],
3429 }
3430}
3431
3432func (p panicError) Error() string {
3433 return fmt.Sprintf("panic in %s\n%s\n%s\n", p.in, p.panic, p.stack)
3434}
3435
3436func (p *panicError) addIn(in string) {
3437 p.in += " in " + in
3438}
3439
3440func funcName(f interface{}) string {
3441 return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
3442}
3443
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003444var fileHeaderTemplate = `******************************************************************************
3445*** This file is generated and should not be edited ***
3446******************************************************************************
3447{{if .Pkgs}}
3448This file contains variables, rules, and pools with name prefixes indicating
3449they were generated by the following Go packages:
3450{{range .Pkgs}}
3451 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
3452
3453`
3454
3455var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Colin Cross0b7e83e2016-05-17 14:58:05 -07003456Module: {{.name}}
Colin Crossab6d7902015-03-11 16:17:52 -07003457Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003458Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003459Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003460Defined: {{.pos}}
3461`
3462
3463var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
3464Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07003465Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07003466`