blob: adeea4a18bfa53ab87c75532f30478958c8dc2e4 [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"
22 "os"
23 "path/filepath"
24 "reflect"
Romain Guy28529652014-08-12 17:50:11 -070025 "runtime"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070026 "sort"
Colin Cross6134a5c2015-02-10 11:26:26 -080027 "strconv"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070028 "strings"
Colin Cross23d7aa12015-06-30 16:05:22 -070029 "sync/atomic"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070030 "text/scanner"
31 "text/template"
Colin Cross1fef5362015-04-20 16:50:54 -070032
33 "github.com/google/blueprint/parser"
34 "github.com/google/blueprint/pathtools"
35 "github.com/google/blueprint/proptools"
Jamie Gennis1bc967e2014-05-27 16:34:41 -070036)
37
38var ErrBuildActionsNotReady = errors.New("build actions are not ready")
39
40const maxErrors = 10
41
Jamie Gennisd4e10182014-06-12 20:06:50 -070042// A Context contains all the state needed to parse a set of Blueprints files
43// and generate a Ninja file. The process of generating a Ninja file proceeds
44// through a series of four phases. Each phase corresponds with a some methods
45// on the Context object
46//
47// Phase Methods
48// ------------ -------------------------------------------
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070049// 1. Registration RegisterModuleType, RegisterSingletonType
Jamie Gennisd4e10182014-06-12 20:06:50 -070050//
51// 2. Parse ParseBlueprintsFiles, Parse
52//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -070053// 3. Generate ResolveDependencies, PrepareBuildActions
Jamie Gennisd4e10182014-06-12 20:06:50 -070054//
55// 4. Write WriteBuildFile
56//
57// The registration phase prepares the context to process Blueprints files
58// containing various types of modules. The parse phase reads in one or more
59// Blueprints files and validates their contents against the module types that
60// have been registered. The generate phase then analyzes the parsed Blueprints
61// contents to create an internal representation for the build actions that must
62// be performed. This phase also performs validation of the module dependencies
63// and property values defined in the parsed Blueprints files. Finally, the
64// write phase generates the Ninja manifest text based on the generated build
65// actions.
Jamie Gennis1bc967e2014-05-27 16:34:41 -070066type Context struct {
67 // set at instantiation
Colin Cross65569e42015-03-10 20:08:19 -070068 moduleFactories map[string]ModuleFactory
69 moduleGroups map[string]*moduleGroup
70 moduleInfo map[Module]*moduleInfo
71 modulesSorted []*moduleInfo
Yuchen Wub9103ef2015-08-25 17:58:17 -070072 singletonInfo []*singletonInfo
Colin Cross65569e42015-03-10 20:08:19 -070073 mutatorInfo []*mutatorInfo
74 earlyMutatorInfo []*earlyMutatorInfo
75 variantMutatorNames []string
76 moduleNinjaNames map[string]*moduleGroup
Jamie Gennis1bc967e2014-05-27 16:34:41 -070077
78 dependenciesReady bool // set to true on a successful ResolveDependencies
79 buildActionsReady bool // set to true on a successful PrepareBuildActions
80
81 // set by SetIgnoreUnknownModuleTypes
82 ignoreUnknownModuleTypes bool
83
84 // set during PrepareBuildActions
Jamie Gennis2fb20952014-10-03 02:49:58 -070085 pkgNames map[*PackageContext]string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070086 globalVariables map[Variable]*ninjaString
87 globalPools map[Pool]*poolDef
88 globalRules map[Rule]*ruleDef
89
90 // set during PrepareBuildActions
91 buildDir *ninjaString // The builddir special Ninja variable
92 requiredNinjaMajor int // For the ninja_required_version variable
93 requiredNinjaMinor int // For the ninja_required_version variable
94 requiredNinjaMicro int // For the ninja_required_version variable
Jamie Gennisc15544d2014-09-24 20:26:52 -070095
96 // set lazily by sortedModuleNames
97 cachedSortedModuleNames []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -070098}
99
Jamie Gennisd4e10182014-06-12 20:06:50 -0700100// An Error describes a problem that was encountered that is related to a
101// particular location in a Blueprints file.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700102type Error struct {
Jamie Gennisd4e10182014-06-12 20:06:50 -0700103 Err error // the error that occurred
104 Pos scanner.Position // the relevant Blueprints file location
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700105}
106
107type localBuildActions struct {
108 variables []*localVariable
109 rules []*localRule
110 buildDefs []*buildDef
111}
112
Colin Crossbbfa51a2014-12-17 16:12:41 -0800113type moduleGroup struct {
Colin Crossed342d92015-03-11 00:57:25 -0700114 name string
115 ninjaName string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700116
Colin Crossbbfa51a2014-12-17 16:12:41 -0800117 modules []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700118}
119
Colin Crossbbfa51a2014-12-17 16:12:41 -0800120type moduleInfo struct {
Colin Crossed342d92015-03-11 00:57:25 -0700121 // set during Parse
122 typeName string
123 relBlueprintsFile string
124 pos scanner.Position
125 propertyPos map[string]scanner.Position
126 properties struct {
127 Name string
128 Deps []string
129 }
130
Colin Crossf5e34b92015-03-13 16:02:36 -0700131 variantName string
132 variant variationMap
133 dependencyVariant variationMap
Colin Crosse7daa222015-03-11 14:35:41 -0700134
Colin Crossc9028482014-12-18 16:28:54 -0800135 logicModule Module
136 group *moduleGroup
137 moduleProperties []interface{}
138
139 // set during ResolveDependencies
140 directDeps []*moduleInfo
141
Colin Cross7addea32015-03-11 15:43:52 -0700142 // set during updateDependencies
143 reverseDeps []*moduleInfo
144 depsCount int
145
146 // used by parallelVisitAllBottomUp
147 waitingCount int
148
Colin Crossc9028482014-12-18 16:28:54 -0800149 // set during each runMutator
150 splitModules []*moduleInfo
Colin Crossab6d7902015-03-11 16:17:52 -0700151
152 // set during PrepareBuildActions
153 actionDefs localBuildActions
Colin Crossc9028482014-12-18 16:28:54 -0800154}
155
Colin Crossf5e34b92015-03-13 16:02:36 -0700156// A Variation is a way that a variant of a module differs from other variants of the same module.
157// For example, two variants of the same module might have Variation{"arch","arm"} and
158// Variation{"arch","arm64"}
159type Variation struct {
160 // Mutator is the axis on which this variation applies, i.e. "arch" or "link"
Colin Cross65569e42015-03-10 20:08:19 -0700161 Mutator string
Colin Crossf5e34b92015-03-13 16:02:36 -0700162 // Variation is the name of the variation on the axis, i.e. "arm" or "arm64" for arch, or
163 // "shared" or "static" for link.
164 Variation string
Colin Cross65569e42015-03-10 20:08:19 -0700165}
166
Colin Crossf5e34b92015-03-13 16:02:36 -0700167// A variationMap stores a map of Mutator to Variation to specify a variant of a module.
168type variationMap map[string]string
Colin Crosse7daa222015-03-11 14:35:41 -0700169
Colin Crossf5e34b92015-03-13 16:02:36 -0700170func (vm variationMap) clone() variationMap {
171 newVm := make(variationMap)
Colin Crosse7daa222015-03-11 14:35:41 -0700172 for k, v := range vm {
173 newVm[k] = v
174 }
175
176 return newVm
Colin Crossc9028482014-12-18 16:28:54 -0800177}
178
Colin Cross89486232015-05-08 11:14:54 -0700179// Compare this variationMap to another one. Returns true if the every entry in this map
180// is either the same in the other map or doesn't exist in the other map.
181func (vm variationMap) subset(other variationMap) bool {
182 for k, v1 := range vm {
183 if v2, ok := other[k]; ok && v1 != v2 {
184 return false
185 }
186 }
187 return true
188}
189
Colin Crossf5e34b92015-03-13 16:02:36 -0700190func (vm variationMap) equal(other variationMap) bool {
Colin Crosse7daa222015-03-11 14:35:41 -0700191 return reflect.DeepEqual(vm, other)
Colin Crossbbfa51a2014-12-17 16:12:41 -0800192}
193
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700194type singletonInfo struct {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700195 // set during RegisterSingletonType
196 factory SingletonFactory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700197 singleton Singleton
Yuchen Wub9103ef2015-08-25 17:58:17 -0700198 name string
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700199
200 // set during PrepareBuildActions
201 actionDefs localBuildActions
202}
203
Colin Crossc9028482014-12-18 16:28:54 -0800204type mutatorInfo struct {
205 // set during RegisterMutator
Colin Crossc0dbc552015-01-02 15:19:28 -0800206 topDownMutator TopDownMutator
207 bottomUpMutator BottomUpMutator
208 name string
Colin Crossc9028482014-12-18 16:28:54 -0800209}
210
Colin Cross65569e42015-03-10 20:08:19 -0700211type earlyMutatorInfo struct {
212 // set during RegisterEarlyMutator
213 mutator EarlyMutator
214 name string
215}
216
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700217func (e *Error) Error() string {
218
219 return fmt.Sprintf("%s: %s", e.Pos, e.Err)
220}
221
Jamie Gennisd4e10182014-06-12 20:06:50 -0700222// NewContext creates a new Context object. The created context initially has
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700223// no module or singleton factories registered, so the RegisterModuleFactory and
224// RegisterSingletonFactory methods must be called before it can do anything
225// useful.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700226func NewContext() *Context {
Colin Cross763b6f12015-10-29 15:32:56 -0700227 ctx := &Context{
Colin Cross6134a5c2015-02-10 11:26:26 -0800228 moduleFactories: make(map[string]ModuleFactory),
229 moduleGroups: make(map[string]*moduleGroup),
230 moduleInfo: make(map[Module]*moduleInfo),
Colin Cross6134a5c2015-02-10 11:26:26 -0800231 moduleNinjaNames: make(map[string]*moduleGroup),
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700232 }
Colin Cross763b6f12015-10-29 15:32:56 -0700233
234 ctx.RegisterBottomUpMutator("blueprint_deps", blueprintDepsMutator)
235
236 return ctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700237}
238
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700239// A ModuleFactory function creates a new Module object. See the
240// Context.RegisterModuleType method for details about how a registered
241// ModuleFactory is used by a Context.
242type ModuleFactory func() (m Module, propertyStructs []interface{})
243
Jamie Gennisd4e10182014-06-12 20:06:50 -0700244// RegisterModuleType associates a module type name (which can appear in a
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700245// Blueprints file) with a Module factory function. When the given module type
246// name is encountered in a Blueprints file during parsing, the Module factory
247// is invoked to instantiate a new Module object to handle the build action
Colin Crossc9028482014-12-18 16:28:54 -0800248// generation for the module. If a Mutator splits a module into multiple variants,
249// the factory is invoked again to create a new Module for each variant.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700250//
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700251// The module type names given here must be unique for the context. The factory
252// function should be a named function so that its package and name can be
253// included in the generated Ninja file for debugging purposes.
254//
255// The factory function returns two values. The first is the newly created
256// Module object. The second is a slice of pointers to that Module object's
257// properties structs. Each properties struct is examined when parsing a module
258// definition of this type in a Blueprints file. Exported fields of the
259// properties structs are automatically set to the property values specified in
260// the Blueprints file. The properties struct field names determine the name of
261// the Blueprints file properties that are used - the Blueprints property name
262// matches that of the properties struct field name with the first letter
263// converted to lower-case.
264//
265// The fields of the properties struct must be either []string, a string, or
266// bool. The Context will panic if a Module gets instantiated with a properties
267// struct containing a field that is not one these supported types.
268//
269// Any properties that appear in the Blueprints files that are not built-in
270// module properties (such as "name" and "deps") and do not have a corresponding
271// field in the returned module properties struct result in an error during the
272// Context's parse phase.
273//
274// As an example, the follow code:
275//
276// type myModule struct {
277// properties struct {
278// Foo string
279// Bar []string
280// }
281// }
282//
283// func NewMyModule() (blueprint.Module, []interface{}) {
284// module := new(myModule)
285// properties := &module.properties
286// return module, []interface{}{properties}
287// }
288//
289// func main() {
290// ctx := blueprint.NewContext()
291// ctx.RegisterModuleType("my_module", NewMyModule)
292// // ...
293// }
294//
295// would support parsing a module defined in a Blueprints file as follows:
296//
297// my_module {
298// name: "myName",
299// foo: "my foo string",
300// bar: ["my", "bar", "strings"],
301// }
302//
Colin Cross7ad621c2015-01-07 16:22:45 -0800303// The factory function may be called from multiple goroutines. Any accesses
304// to global variables must be synchronized.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700305func (c *Context) RegisterModuleType(name string, factory ModuleFactory) {
306 if _, present := c.moduleFactories[name]; present {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700307 panic(errors.New("module type name is already registered"))
308 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700309 c.moduleFactories[name] = factory
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700310}
311
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700312// A SingletonFactory function creates a new Singleton object. See the
313// Context.RegisterSingletonType method for details about how a registered
314// SingletonFactory is used by a Context.
315type SingletonFactory func() Singleton
316
317// RegisterSingletonType registers a singleton type that will be invoked to
318// generate build actions. Each registered singleton type is instantiated and
Yuchen Wub9103ef2015-08-25 17:58:17 -0700319// and invoked exactly once as part of the generate phase. Each registered
320// singleton is invoked in registration order.
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700321//
322// The singleton type names given here must be unique for the context. The
323// factory function should be a named function so that its package and name can
324// be included in the generated Ninja file for debugging purposes.
325func (c *Context) RegisterSingletonType(name string, factory SingletonFactory) {
Yuchen Wub9103ef2015-08-25 17:58:17 -0700326 for _, s := range c.singletonInfo {
327 if s.name == name {
328 panic(errors.New("singleton name is already registered"))
329 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700330 }
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700331
Yuchen Wub9103ef2015-08-25 17:58:17 -0700332 c.singletonInfo = append(c.singletonInfo, &singletonInfo{
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700333 factory: factory,
334 singleton: factory(),
Yuchen Wub9103ef2015-08-25 17:58:17 -0700335 name: name,
336 })
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700337}
338
339func singletonPkgPath(singleton Singleton) string {
340 typ := reflect.TypeOf(singleton)
341 for typ.Kind() == reflect.Ptr {
342 typ = typ.Elem()
343 }
344 return typ.PkgPath()
345}
346
347func singletonTypeName(singleton Singleton) string {
348 typ := reflect.TypeOf(singleton)
349 for typ.Kind() == reflect.Ptr {
350 typ = typ.Elem()
351 }
352 return typ.PkgPath() + "." + typ.Name()
353}
354
Colin Crossc9028482014-12-18 16:28:54 -0800355// RegisterTopDownMutator registers a mutator that will be invoked to propagate
356// dependency info top-down between Modules. Each registered mutator
Colin Cross65569e42015-03-10 20:08:19 -0700357// is invoked in registration order (mixing TopDownMutators and BottomUpMutators)
358// once per Module, and is invoked on a module before being invoked on any of its
359// dependencies.
Colin Crossc9028482014-12-18 16:28:54 -0800360//
Colin Cross65569e42015-03-10 20:08:19 -0700361// The mutator type names given here must be unique to all top down mutators in
362// the Context.
Colin Crossc9028482014-12-18 16:28:54 -0800363func (c *Context) RegisterTopDownMutator(name string, mutator TopDownMutator) {
364 for _, m := range c.mutatorInfo {
365 if m.name == name && m.topDownMutator != nil {
366 panic(fmt.Errorf("mutator name %s is already registered", name))
367 }
368 }
369
370 c.mutatorInfo = append(c.mutatorInfo, &mutatorInfo{
371 topDownMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800372 name: name,
Colin Crossc9028482014-12-18 16:28:54 -0800373 })
374}
375
376// RegisterBottomUpMutator registers a mutator that will be invoked to split
Colin Cross65569e42015-03-10 20:08:19 -0700377// Modules into variants. Each registered mutator is invoked in registration
378// order (mixing TopDownMutators and BottomUpMutators) once per Module, and is
379// invoked on dependencies before being invoked on dependers.
Colin Crossc9028482014-12-18 16:28:54 -0800380//
Colin Cross65569e42015-03-10 20:08:19 -0700381// The mutator type names given here must be unique to all bottom up or early
382// mutators in the Context.
Colin Crossc9028482014-12-18 16:28:54 -0800383func (c *Context) RegisterBottomUpMutator(name string, mutator BottomUpMutator) {
Colin Cross65569e42015-03-10 20:08:19 -0700384 for _, m := range c.variantMutatorNames {
385 if m == name {
Colin Crossc9028482014-12-18 16:28:54 -0800386 panic(fmt.Errorf("mutator name %s is already registered", name))
387 }
388 }
389
390 c.mutatorInfo = append(c.mutatorInfo, &mutatorInfo{
391 bottomUpMutator: mutator,
Colin Crossc0dbc552015-01-02 15:19:28 -0800392 name: name,
Colin Crossc9028482014-12-18 16:28:54 -0800393 })
Colin Cross65569e42015-03-10 20:08:19 -0700394
395 c.variantMutatorNames = append(c.variantMutatorNames, name)
396}
397
398// RegisterEarlyMutator registers a mutator that will be invoked to split
399// Modules into multiple variant Modules before any dependencies have been
400// created. Each registered mutator is invoked in registration order once
401// per Module (including each variant from previous early mutators). Module
402// order is unpredictable.
403//
404// In order for dependencies to be satisifed in a later pass, all dependencies
Colin Crossf5e34b92015-03-13 16:02:36 -0700405// of a module either must have an identical variant or must have no variations.
Colin Cross65569e42015-03-10 20:08:19 -0700406//
407// The mutator type names given here must be unique to all bottom up or early
408// mutators in the Context.
Colin Cross763b6f12015-10-29 15:32:56 -0700409//
410// Deprecated, use a BottomUpMutator instead. The only difference between
411// EarlyMutator and BottomUpMutator is that EarlyMutator runs before the
412// deprecated DynamicDependencies.
Colin Cross65569e42015-03-10 20:08:19 -0700413func (c *Context) RegisterEarlyMutator(name string, mutator EarlyMutator) {
414 for _, m := range c.variantMutatorNames {
415 if m == name {
416 panic(fmt.Errorf("mutator name %s is already registered", name))
417 }
418 }
419
420 c.earlyMutatorInfo = append(c.earlyMutatorInfo, &earlyMutatorInfo{
421 mutator: mutator,
422 name: name,
423 })
424
425 c.variantMutatorNames = append(c.variantMutatorNames, name)
Colin Crossc9028482014-12-18 16:28:54 -0800426}
427
Jamie Gennisd4e10182014-06-12 20:06:50 -0700428// SetIgnoreUnknownModuleTypes sets the behavior of the context in the case
429// where it encounters an unknown module type while parsing Blueprints files. By
430// default, the context will report unknown module types as an error. If this
431// method is called with ignoreUnknownModuleTypes set to true then the context
432// will silently ignore unknown module types.
433//
434// This method should generally not be used. It exists to facilitate the
435// bootstrapping process.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700436func (c *Context) SetIgnoreUnknownModuleTypes(ignoreUnknownModuleTypes bool) {
437 c.ignoreUnknownModuleTypes = ignoreUnknownModuleTypes
438}
439
Jamie Gennisd4e10182014-06-12 20:06:50 -0700440// Parse parses a single Blueprints file from r, creating Module objects for
441// each of the module definitions encountered. If the Blueprints file contains
442// an assignment to the "subdirs" variable, then the subdirectories listed are
Colin Cross1fef5362015-04-20 16:50:54 -0700443// searched for Blueprints files returned in the subBlueprints return value.
444// If the Blueprints file contains an assignment to the "build" variable, then
445// the file listed are returned in the subBlueprints return value.
Jamie Gennisd4e10182014-06-12 20:06:50 -0700446//
447// rootDir specifies the path to the root directory of the source tree, while
448// filename specifies the path to the Blueprints file. These paths are used for
449// error reporting and for determining the module's directory.
Colin Cross7ad621c2015-01-07 16:22:45 -0800450func (c *Context) parse(rootDir, filename string, r io.Reader,
Colin Cross23d7aa12015-06-30 16:05:22 -0700451 scope *parser.Scope) (file *parser.File, subBlueprints []stringAndScope, deps []string,
Colin Cross1fef5362015-04-20 16:50:54 -0700452 errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700453
Jamie Gennisec701282014-06-12 20:06:31 -0700454 relBlueprintsFile, err := filepath.Rel(rootDir, filename)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700455 if err != nil {
Colin Cross1fef5362015-04-20 16:50:54 -0700456 return nil, nil, nil, []error{err}
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700457 }
458
Colin Crossc0dbc552015-01-02 15:19:28 -0800459 scope = parser.NewScope(scope)
460 scope.Remove("subdirs")
Colin Cross1fef5362015-04-20 16:50:54 -0700461 scope.Remove("build")
Colin Cross23d7aa12015-06-30 16:05:22 -0700462 file, errs = parser.ParseAndEval(filename, r, scope)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700463 if len(errs) > 0 {
464 for i, err := range errs {
465 if parseErr, ok := err.(*parser.ParseError); ok {
466 err = &Error{
467 Err: parseErr.Err,
468 Pos: parseErr.Pos,
469 }
470 errs[i] = err
471 }
472 }
473
474 // If there were any parse errors don't bother trying to interpret the
475 // result.
Colin Cross1fef5362015-04-20 16:50:54 -0700476 return nil, nil, nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700477 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700478 file.Name = relBlueprintsFile
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700479
Colin Cross6d8780f2015-07-10 17:51:55 -0700480 subdirs, subdirsPos, err := getLocalStringListFromScope(scope, "subdirs")
Colin Cross1fef5362015-04-20 16:50:54 -0700481 if err != nil {
482 errs = append(errs, err)
483 }
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700484
Colin Cross6d8780f2015-07-10 17:51:55 -0700485 build, buildPos, err := getLocalStringListFromScope(scope, "build")
Colin Cross1fef5362015-04-20 16:50:54 -0700486 if err != nil {
487 errs = append(errs, err)
488 }
489
Colin Cross29394222015-04-27 13:18:21 -0700490 subBlueprintsName, _, err := getStringFromScope(scope, "subname")
491
Colin Cross1fef5362015-04-20 16:50:54 -0700492 blueprints, deps, newErrs := c.findSubdirBlueprints(filepath.Dir(filename), subdirs, build,
Colin Cross29394222015-04-27 13:18:21 -0700493 subBlueprintsName, subdirsPos, buildPos)
Colin Crossc0dbc552015-01-02 15:19:28 -0800494 if len(newErrs) > 0 {
495 errs = append(errs, newErrs...)
496 }
497
Colin Cross1fef5362015-04-20 16:50:54 -0700498 subBlueprintsAndScope := make([]stringAndScope, len(blueprints))
499 for i, b := range blueprints {
500 subBlueprintsAndScope[i] = stringAndScope{b, scope}
501 }
502
Colin Cross23d7aa12015-06-30 16:05:22 -0700503 return file, subBlueprintsAndScope, deps, errs
Colin Crossc0dbc552015-01-02 15:19:28 -0800504}
505
Colin Cross7ad621c2015-01-07 16:22:45 -0800506type stringAndScope struct {
507 string
508 *parser.Scope
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700509}
510
Jamie Gennisd4e10182014-06-12 20:06:50 -0700511// ParseBlueprintsFiles parses a set of Blueprints files starting with the file
512// at rootFile. When it encounters a Blueprints file with a set of subdirs
513// listed it recursively parses any Blueprints files found in those
514// subdirectories.
515//
516// If no errors are encountered while parsing the files, the list of paths on
517// which the future output will depend is returned. This list will include both
518// Blueprints file paths as well as directory paths for cases where wildcard
519// subdirs are found.
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700520func (c *Context) ParseBlueprintsFiles(rootFile string) (deps []string,
521 errs []error) {
522
Colin Cross7ad621c2015-01-07 16:22:45 -0800523 c.dependenciesReady = false
524
Colin Cross23d7aa12015-06-30 16:05:22 -0700525 moduleCh := make(chan *moduleInfo)
526 errsCh := make(chan []error)
527 doneCh := make(chan struct{})
528 var numErrs uint32
529 var numGoroutines int32
530
531 // handler must be reentrant
532 handler := func(file *parser.File) {
533 if atomic.LoadUint32(&numErrs) > maxErrors {
534 return
535 }
536
537 atomic.AddInt32(&numGoroutines, 1)
538 go func() {
539 for _, def := range file.Defs {
540 var module *moduleInfo
541 var errs []error
542 switch def := def.(type) {
543 case *parser.Module:
544 module, errs = c.processModuleDef(def, file.Name)
545 case *parser.Assignment:
546 // Already handled via Scope object
547 default:
548 panic("unknown definition type")
549 }
550
551 if len(errs) > 0 {
552 atomic.AddUint32(&numErrs, uint32(len(errs)))
553 errsCh <- errs
554 } else if module != nil {
555 moduleCh <- module
556 }
557 }
558 doneCh <- struct{}{}
559 }()
560 }
561
562 atomic.AddInt32(&numGoroutines, 1)
563 go func() {
564 var errs []error
565 deps, errs = c.WalkBlueprintsFiles(rootFile, handler)
566 if len(errs) > 0 {
567 errsCh <- errs
568 }
569 doneCh <- struct{}{}
570 }()
571
572loop:
573 for {
574 select {
575 case newErrs := <-errsCh:
576 errs = append(errs, newErrs...)
577 case module := <-moduleCh:
578 newErrs := c.addModule(module)
579 if len(newErrs) > 0 {
580 errs = append(errs, newErrs...)
581 }
582 case <-doneCh:
583 n := atomic.AddInt32(&numGoroutines, -1)
584 if n == 0 {
585 break loop
586 }
587 }
588 }
589
590 return deps, errs
591}
592
593type FileHandler func(*parser.File)
594
595// Walk a set of Blueprints files starting with the file at rootFile, calling handler on each.
596// When it encounters a Blueprints file with a set of subdirs listed it recursively parses any
597// Blueprints files found in those subdirectories. handler will be called from a goroutine, so
598// it must be reentrant.
599//
600// If no errors are encountered while parsing the files, the list of paths on
601// which the future output will depend is returned. This list will include both
602// Blueprints file paths as well as directory paths for cases where wildcard
603// subdirs are found.
604func (c *Context) WalkBlueprintsFiles(rootFile string, handler FileHandler) (deps []string,
605 errs []error) {
606
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700607 rootDir := filepath.Dir(rootFile)
608
Colin Cross7ad621c2015-01-07 16:22:45 -0800609 blueprintsSet := make(map[string]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700610
Colin Cross7ad621c2015-01-07 16:22:45 -0800611 // Channels to receive data back from parseBlueprintsFile goroutines
612 blueprintsCh := make(chan stringAndScope)
613 errsCh := make(chan []error)
Colin Cross23d7aa12015-06-30 16:05:22 -0700614 fileCh := make(chan *parser.File)
Colin Cross7ad621c2015-01-07 16:22:45 -0800615 depsCh := make(chan string)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700616
Colin Cross7ad621c2015-01-07 16:22:45 -0800617 // Channel to notify main loop that a parseBlueprintsFile goroutine has finished
618 doneCh := make(chan struct{})
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700619
Colin Cross7ad621c2015-01-07 16:22:45 -0800620 // Number of outstanding goroutines to wait for
621 count := 0
622
623 startParseBlueprintsFile := func(filename string, scope *parser.Scope) {
624 count++
625 go func() {
626 c.parseBlueprintsFile(filename, scope, rootDir,
Colin Cross23d7aa12015-06-30 16:05:22 -0700627 errsCh, fileCh, blueprintsCh, depsCh)
Colin Cross7ad621c2015-01-07 16:22:45 -0800628 doneCh <- struct{}{}
629 }()
630 }
631
632 tooManyErrors := false
633
634 startParseBlueprintsFile(rootFile, nil)
635
636loop:
637 for {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700638 if len(errs) > maxErrors {
Colin Cross7ad621c2015-01-07 16:22:45 -0800639 tooManyErrors = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700640 }
641
Colin Cross7ad621c2015-01-07 16:22:45 -0800642 select {
643 case newErrs := <-errsCh:
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700644 errs = append(errs, newErrs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800645 case dep := <-depsCh:
646 deps = append(deps, dep)
Colin Cross23d7aa12015-06-30 16:05:22 -0700647 case file := <-fileCh:
648 handler(file)
Colin Cross7ad621c2015-01-07 16:22:45 -0800649 case blueprint := <-blueprintsCh:
650 if tooManyErrors {
651 continue
652 }
653 if blueprintsSet[blueprint.string] {
654 continue
655 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700656
Colin Cross7ad621c2015-01-07 16:22:45 -0800657 blueprintsSet[blueprint.string] = true
658 startParseBlueprintsFile(blueprint.string, blueprint.Scope)
659 case <-doneCh:
660 count--
661 if count == 0 {
662 break loop
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700663 }
664 }
665 }
666
Colin Cross7ad621c2015-01-07 16:22:45 -0800667 return
668}
669
670// parseBlueprintFile parses a single Blueprints file, returning any errors through
671// errsCh, any defined modules through modulesCh, any sub-Blueprints files through
672// blueprintsCh, and any dependencies on Blueprints files or directories through
673// depsCh.
674func (c *Context) parseBlueprintsFile(filename string, scope *parser.Scope, rootDir string,
Colin Cross23d7aa12015-06-30 16:05:22 -0700675 errsCh chan<- []error, fileCh chan<- *parser.File, blueprintsCh chan<- stringAndScope,
Colin Cross7ad621c2015-01-07 16:22:45 -0800676 depsCh chan<- string) {
677
Colin Cross23d7aa12015-06-30 16:05:22 -0700678 f, err := os.Open(filename)
Colin Cross7ad621c2015-01-07 16:22:45 -0800679 if err != nil {
680 errsCh <- []error{err}
681 return
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700682 }
Colin Cross23d7aa12015-06-30 16:05:22 -0700683 defer func() {
684 err = f.Close()
685 if err != nil {
686 errsCh <- []error{err}
687 }
688 }()
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700689
Colin Cross23d7aa12015-06-30 16:05:22 -0700690 file, subBlueprints, deps, errs := c.parse(rootDir, filename, f, scope)
Colin Cross7ad621c2015-01-07 16:22:45 -0800691 if len(errs) > 0 {
692 errsCh <- errs
Colin Cross23d7aa12015-06-30 16:05:22 -0700693 } else {
694 fileCh <- file
Colin Cross7ad621c2015-01-07 16:22:45 -0800695 }
696
Colin Cross1fef5362015-04-20 16:50:54 -0700697 for _, b := range subBlueprints {
698 blueprintsCh <- b
699 }
700
701 for _, d := range deps {
702 depsCh <- d
703 }
Colin Cross1fef5362015-04-20 16:50:54 -0700704}
705
Colin Cross29394222015-04-27 13:18:21 -0700706func (c *Context) findSubdirBlueprints(dir string, subdirs, build []string, subBlueprintsName string,
Colin Cross1fef5362015-04-20 16:50:54 -0700707 subdirsPos, buildPos scanner.Position) (blueprints, deps []string, errs []error) {
Colin Cross7ad621c2015-01-07 16:22:45 -0800708
709 for _, subdir := range subdirs {
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700710 globPattern := filepath.Join(dir, subdir)
711 matches, matchedDirs, err := pathtools.Glob(globPattern)
712 if err != nil {
Colin Cross1fef5362015-04-20 16:50:54 -0700713 errs = append(errs, &Error{
714 Err: fmt.Errorf("%q: %s", globPattern, err.Error()),
715 Pos: subdirsPos,
716 })
717 continue
718 }
719
720 if len(matches) == 0 {
721 errs = append(errs, &Error{
722 Err: fmt.Errorf("%q: not found", globPattern),
723 Pos: subdirsPos,
724 })
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700725 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800726
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700727 // Depend on all searched directories so we pick up future changes.
Colin Cross1fef5362015-04-20 16:50:54 -0700728 deps = append(deps, matchedDirs...)
Colin Cross7ad621c2015-01-07 16:22:45 -0800729
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700730 for _, foundSubdir := range matches {
731 fileInfo, subdirStatErr := os.Stat(foundSubdir)
732 if subdirStatErr != nil {
Colin Cross1fef5362015-04-20 16:50:54 -0700733 errs = append(errs, subdirStatErr)
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700734 continue
Colin Cross7ad621c2015-01-07 16:22:45 -0800735 }
736
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700737 // Skip files
738 if !fileInfo.IsDir() {
739 continue
740 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800741
Colin Cross29394222015-04-27 13:18:21 -0700742 var subBlueprints string
743 if subBlueprintsName != "" {
744 subBlueprints = filepath.Join(foundSubdir, subBlueprintsName)
745 _, err = os.Stat(subBlueprints)
746 }
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700747
Colin Cross29394222015-04-27 13:18:21 -0700748 if os.IsNotExist(err) || subBlueprints == "" {
749 subBlueprints = filepath.Join(foundSubdir, "Blueprints")
750 _, err = os.Stat(subBlueprints)
751 }
752
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700753 if os.IsNotExist(err) {
754 // There is no Blueprints file in this subdirectory. We
755 // need to add the directory to the list of dependencies
756 // so that if someone adds a Blueprints file in the
757 // future we'll pick it up.
Jamie Gennis7ccc2c22015-07-06 13:11:15 -0700758 deps = append(deps, foundSubdir)
Michael Beardsworth1ec44532015-03-31 20:39:02 -0700759 } else {
Colin Cross1fef5362015-04-20 16:50:54 -0700760 deps = append(deps, subBlueprints)
761 blueprints = append(blueprints, subBlueprints)
Colin Cross7ad621c2015-01-07 16:22:45 -0800762 }
Colin Cross7ad621c2015-01-07 16:22:45 -0800763 }
764 }
Colin Cross1fef5362015-04-20 16:50:54 -0700765
766 for _, file := range build {
767 globPattern := filepath.Join(dir, file)
768 matches, matchedDirs, err := pathtools.Glob(globPattern)
769 if err != nil {
770 errs = append(errs, &Error{
771 Err: fmt.Errorf("%q: %s", globPattern, err.Error()),
772 Pos: buildPos,
773 })
774 continue
775 }
776
777 if len(matches) == 0 {
778 errs = append(errs, &Error{
779 Err: fmt.Errorf("%q: not found", globPattern),
780 Pos: buildPos,
781 })
782 }
783
784 // Depend on all searched directories so we pick up future changes.
785 deps = append(deps, matchedDirs...)
786
787 for _, foundBlueprints := range matches {
788 fileInfo, err := os.Stat(foundBlueprints)
789 if os.IsNotExist(err) {
790 errs = append(errs, &Error{
791 Err: fmt.Errorf("%q not found", foundBlueprints),
792 })
793 continue
794 }
795
796 if fileInfo.IsDir() {
797 errs = append(errs, &Error{
798 Err: fmt.Errorf("%q is a directory", foundBlueprints),
799 })
800 continue
801 }
802
803 blueprints = append(blueprints, foundBlueprints)
804 }
805 }
806
807 return blueprints, deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700808}
809
Colin Cross6d8780f2015-07-10 17:51:55 -0700810func getLocalStringListFromScope(scope *parser.Scope, v string) ([]string, scanner.Position, error) {
811 if assignment, local := scope.Get(v); assignment == nil || !local {
812 return nil, scanner.Position{}, nil
813 } else {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700814 switch assignment.Value.Type {
815 case parser.List:
Colin Cross1fef5362015-04-20 16:50:54 -0700816 ret := make([]string, 0, len(assignment.Value.ListValue))
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700817
818 for _, value := range assignment.Value.ListValue {
819 if value.Type != parser.String {
820 // The parser should not produce this.
821 panic("non-string value found in list")
822 }
823
Colin Cross1fef5362015-04-20 16:50:54 -0700824 ret = append(ret, value.StringValue)
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700825 }
826
Colin Cross1fef5362015-04-20 16:50:54 -0700827 return ret, assignment.Pos, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700828 case parser.Bool, parser.String:
Colin Cross1fef5362015-04-20 16:50:54 -0700829 return nil, scanner.Position{}, &Error{
830 Err: fmt.Errorf("%q must be a list of strings", v),
831 Pos: assignment.Pos,
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700832 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700833 default:
834 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type))
835 }
836 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700837}
838
Colin Cross29394222015-04-27 13:18:21 -0700839func getStringFromScope(scope *parser.Scope, v string) (string, scanner.Position, error) {
Colin Cross6d8780f2015-07-10 17:51:55 -0700840 if assignment, _ := scope.Get(v); assignment == nil {
841 return "", scanner.Position{}, nil
842 } else {
Colin Cross29394222015-04-27 13:18:21 -0700843 switch assignment.Value.Type {
844 case parser.String:
845 return assignment.Value.StringValue, assignment.Pos, nil
846 case parser.Bool, parser.List:
847 return "", scanner.Position{}, &Error{
848 Err: fmt.Errorf("%q must be a string", v),
849 Pos: assignment.Pos,
850 }
851 default:
852 panic(fmt.Errorf("unknown value type: %d", assignment.Value.Type))
853 }
854 }
Colin Cross29394222015-04-27 13:18:21 -0700855}
856
Colin Crossf5e34b92015-03-13 16:02:36 -0700857func (c *Context) createVariations(origModule *moduleInfo, mutatorName string,
858 variationNames []string) ([]*moduleInfo, []error) {
Colin Crossc9028482014-12-18 16:28:54 -0800859
Colin Crossf4d18a62015-03-18 17:43:15 -0700860 if len(variationNames) == 0 {
861 panic(fmt.Errorf("mutator %q passed zero-length variation list for module %q",
Jamie Gennis6cafc2c2015-03-20 22:39:29 -0400862 mutatorName, origModule.properties.Name))
Colin Crossf4d18a62015-03-18 17:43:15 -0700863 }
864
Colin Crossc9028482014-12-18 16:28:54 -0800865 newModules := []*moduleInfo{}
Colin Crossc9028482014-12-18 16:28:54 -0800866
Colin Cross174ae052015-03-03 17:37:03 -0800867 var errs []error
868
Colin Crossf5e34b92015-03-13 16:02:36 -0700869 for i, variationName := range variationNames {
Colin Crossed342d92015-03-11 00:57:25 -0700870 typeName := origModule.typeName
Colin Crossc9028482014-12-18 16:28:54 -0800871 factory, ok := c.moduleFactories[typeName]
872 if !ok {
873 panic(fmt.Sprintf("unrecognized module type %q during cloning", typeName))
874 }
875
876 var newLogicModule Module
877 var newProperties []interface{}
878
879 if i == 0 {
880 // Reuse the existing module for the first new variant
Colin Cross21e078a2015-03-16 10:57:54 -0700881 // This both saves creating a new module, and causes the insertion in c.moduleInfo below
882 // with logicModule as the key to replace the original entry in c.moduleInfo
Colin Crossc9028482014-12-18 16:28:54 -0800883 newLogicModule = origModule.logicModule
884 newProperties = origModule.moduleProperties
885 } else {
886 props := []interface{}{
Colin Crossed342d92015-03-11 00:57:25 -0700887 &origModule.properties,
Colin Crossc9028482014-12-18 16:28:54 -0800888 }
889 newLogicModule, newProperties = factory()
890
891 newProperties = append(props, newProperties...)
892
893 if len(newProperties) != len(origModule.moduleProperties) {
Colin Crossed342d92015-03-11 00:57:25 -0700894 panic("mismatched properties array length in " + origModule.properties.Name)
Colin Crossc9028482014-12-18 16:28:54 -0800895 }
896
897 for i := range newProperties {
898 dst := reflect.ValueOf(newProperties[i]).Elem()
899 src := reflect.ValueOf(origModule.moduleProperties[i]).Elem()
900
901 proptools.CopyProperties(dst, src)
902 }
903 }
904
Colin Crossf5e34b92015-03-13 16:02:36 -0700905 newVariant := origModule.variant.clone()
906 newVariant[mutatorName] = variationName
Colin Crossc9028482014-12-18 16:28:54 -0800907
Colin Crossed342d92015-03-11 00:57:25 -0700908 m := *origModule
909 newModule := &m
910 newModule.directDeps = append([]*moduleInfo(nil), origModule.directDeps...)
911 newModule.logicModule = newLogicModule
Colin Crossf5e34b92015-03-13 16:02:36 -0700912 newModule.variant = newVariant
913 newModule.dependencyVariant = origModule.dependencyVariant.clone()
Colin Crossed342d92015-03-11 00:57:25 -0700914 newModule.moduleProperties = newProperties
Colin Crossc9028482014-12-18 16:28:54 -0800915
Colin Crosse7daa222015-03-11 14:35:41 -0700916 if newModule.variantName == "" {
Colin Crossf5e34b92015-03-13 16:02:36 -0700917 newModule.variantName = variationName
Colin Crosse7daa222015-03-11 14:35:41 -0700918 } else {
Colin Crossf5e34b92015-03-13 16:02:36 -0700919 newModule.variantName += "_" + variationName
Colin Crosse7daa222015-03-11 14:35:41 -0700920 }
921
Colin Crossc9028482014-12-18 16:28:54 -0800922 newModules = append(newModules, newModule)
Colin Cross21e078a2015-03-16 10:57:54 -0700923
924 // Insert the new variant into the global module map. If this is the first variant then
925 // it reuses logicModule from the original module, which causes this to replace the
926 // original module in the global module map.
Colin Crossc9028482014-12-18 16:28:54 -0800927 c.moduleInfo[newModule.logicModule] = newModule
928
Colin Crossf5e34b92015-03-13 16:02:36 -0700929 newErrs := c.convertDepsToVariation(newModule, mutatorName, variationName)
Colin Cross174ae052015-03-03 17:37:03 -0800930 if len(newErrs) > 0 {
931 errs = append(errs, newErrs...)
932 }
Colin Crossc9028482014-12-18 16:28:54 -0800933 }
934
935 // Mark original variant as invalid. Modules that depend on this module will still
936 // depend on origModule, but we'll fix it when the mutator is called on them.
937 origModule.logicModule = nil
938 origModule.splitModules = newModules
939
Colin Cross174ae052015-03-03 17:37:03 -0800940 return newModules, errs
Colin Crossc9028482014-12-18 16:28:54 -0800941}
942
Colin Crossf5e34b92015-03-13 16:02:36 -0700943func (c *Context) convertDepsToVariation(module *moduleInfo,
944 mutatorName, variationName string) (errs []error) {
Colin Cross174ae052015-03-03 17:37:03 -0800945
Colin Crossc9028482014-12-18 16:28:54 -0800946 for i, dep := range module.directDeps {
947 if dep.logicModule == nil {
948 var newDep *moduleInfo
949 for _, m := range dep.splitModules {
Colin Crossf5e34b92015-03-13 16:02:36 -0700950 if m.variant[mutatorName] == variationName {
Colin Crossc9028482014-12-18 16:28:54 -0800951 newDep = m
952 break
953 }
954 }
955 if newDep == nil {
Colin Cross174ae052015-03-03 17:37:03 -0800956 errs = append(errs, &Error{
Colin Crossf5e34b92015-03-13 16:02:36 -0700957 Err: fmt.Errorf("failed to find variation %q for module %q needed by %q",
958 variationName, dep.properties.Name, module.properties.Name),
Colin Crossed342d92015-03-11 00:57:25 -0700959 Pos: module.pos,
Colin Cross174ae052015-03-03 17:37:03 -0800960 })
961 continue
Colin Crossc9028482014-12-18 16:28:54 -0800962 }
963 module.directDeps[i] = newDep
964 }
965 }
Colin Cross174ae052015-03-03 17:37:03 -0800966
967 return errs
Colin Crossc9028482014-12-18 16:28:54 -0800968}
969
Colin Crossf5e34b92015-03-13 16:02:36 -0700970func (c *Context) prettyPrintVariant(variant variationMap) string {
Colin Cross65569e42015-03-10 20:08:19 -0700971 names := make([]string, 0, len(variant))
972 for _, m := range c.variantMutatorNames {
973 if v, ok := variant[m]; ok {
974 names = append(names, m+":"+v)
975 }
976 }
977
978 return strings.Join(names, ", ")
979}
980
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700981func (c *Context) processModuleDef(moduleDef *parser.Module,
Colin Cross7ad621c2015-01-07 16:22:45 -0800982 relBlueprintsFile string) (*moduleInfo, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700983
Colin Crossd1facc12015-01-08 14:56:03 -0800984 typeName := moduleDef.Type.Name
Jamie Gennis7d5b2f82014-09-24 17:51:52 -0700985 factory, ok := c.moduleFactories[typeName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700986 if !ok {
987 if c.ignoreUnknownModuleTypes {
Colin Cross7ad621c2015-01-07 16:22:45 -0800988 return nil, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700989 }
990
Colin Cross7ad621c2015-01-07 16:22:45 -0800991 return nil, []error{
Jamie Gennisd4c53d82014-06-22 17:02:55 -0700992 &Error{
993 Err: fmt.Errorf("unrecognized module type %q", typeName),
Colin Crossd1facc12015-01-08 14:56:03 -0800994 Pos: moduleDef.Type.Pos,
Jamie Gennisd4c53d82014-06-22 17:02:55 -0700995 },
996 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -0700997 }
998
Colin Crossbbfa51a2014-12-17 16:12:41 -0800999 logicModule, properties := factory()
Colin Crossed342d92015-03-11 00:57:25 -07001000
1001 module := &moduleInfo{
1002 logicModule: logicModule,
Jamie Gennisec701282014-06-12 20:06:31 -07001003 typeName: typeName,
Jamie Gennisec701282014-06-12 20:06:31 -07001004 relBlueprintsFile: relBlueprintsFile,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001005 }
1006
Jamie Gennis87622922014-09-30 11:38:25 -07001007 props := []interface{}{
Colin Crossed342d92015-03-11 00:57:25 -07001008 &module.properties,
Jamie Gennis87622922014-09-30 11:38:25 -07001009 }
1010 properties = append(props, properties...)
Colin Crossed342d92015-03-11 00:57:25 -07001011 module.moduleProperties = properties
Jamie Gennisd4c53d82014-06-22 17:02:55 -07001012
Jamie Gennis87622922014-09-30 11:38:25 -07001013 propertyMap, errs := unpackProperties(moduleDef.Properties, properties...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001014 if len(errs) > 0 {
Colin Cross7ad621c2015-01-07 16:22:45 -08001015 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001016 }
1017
Colin Crossed342d92015-03-11 00:57:25 -07001018 module.pos = moduleDef.Type.Pos
1019 module.propertyPos = make(map[string]scanner.Position)
Jamie Gennis87622922014-09-30 11:38:25 -07001020 for name, propertyDef := range propertyMap {
Colin Crossed342d92015-03-11 00:57:25 -07001021 module.propertyPos[name] = propertyDef.Pos
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001022 }
1023
Colin Cross7ad621c2015-01-07 16:22:45 -08001024 return module, nil
1025}
1026
Colin Cross23d7aa12015-06-30 16:05:22 -07001027func (c *Context) addModule(module *moduleInfo) []error {
1028 name := module.properties.Name
1029 c.moduleInfo[module.logicModule] = module
Colin Crossed342d92015-03-11 00:57:25 -07001030
Colin Cross23d7aa12015-06-30 16:05:22 -07001031 if group, present := c.moduleGroups[name]; present {
1032 return []error{
1033 &Error{
1034 Err: fmt.Errorf("module %q already defined", name),
1035 Pos: module.pos,
1036 },
1037 &Error{
1038 Err: fmt.Errorf("<-- previous definition here"),
1039 Pos: group.modules[0].pos,
1040 },
Colin Crossed342d92015-03-11 00:57:25 -07001041 }
Colin Cross23d7aa12015-06-30 16:05:22 -07001042 } else {
1043 ninjaName := toNinjaName(module.properties.Name)
1044
1045 // The sanitizing in toNinjaName can result in collisions, uniquify the name if it
1046 // already exists
1047 for i := 0; c.moduleNinjaNames[ninjaName] != nil; i++ {
1048 ninjaName = toNinjaName(module.properties.Name) + strconv.Itoa(i)
1049 }
1050
1051 group := &moduleGroup{
1052 name: module.properties.Name,
1053 ninjaName: ninjaName,
1054 modules: []*moduleInfo{module},
1055 }
1056 module.group = group
1057 c.moduleGroups[name] = group
1058 c.moduleNinjaNames[ninjaName] = group
Colin Cross7ad621c2015-01-07 16:22:45 -08001059 }
1060
Colin Cross23d7aa12015-06-30 16:05:22 -07001061 return nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001062}
1063
Jamie Gennisd4e10182014-06-12 20:06:50 -07001064// ResolveDependencies checks that the dependencies specified by all of the
1065// modules defined in the parsed Blueprints files are valid. This means that
1066// the modules depended upon are defined and that no circular dependencies
1067// exist.
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001068func (c *Context) ResolveDependencies(config interface{}) []error {
Colin Cross763b6f12015-10-29 15:32:56 -07001069 errs := c.runMutators(config)
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001070 if len(errs) > 0 {
1071 return errs
1072 }
1073
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001074 c.dependenciesReady = true
1075 return nil
1076}
1077
Colin Cross763b6f12015-10-29 15:32:56 -07001078// Default dependencies handling. If the module implements the (deprecated)
Colin Cross65569e42015-03-10 20:08:19 -07001079// DynamicDependerModule interface then this set consists of the union of those
1080// module names listed in its "deps" property, those returned by its
1081// DynamicDependencies method, and those added by calling AddDependencies or
Colin Crossf5e34b92015-03-13 16:02:36 -07001082// AddVariationDependencies on DynamicDependencyModuleContext. Otherwise it
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001083// is simply those names listed in its "deps" property.
Colin Cross763b6f12015-10-29 15:32:56 -07001084func blueprintDepsMutator(ctx BottomUpMutatorContext) {
1085 ctx.AddDependency(ctx.Module(), ctx.moduleInfo().properties.Deps...)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001086
Colin Cross763b6f12015-10-29 15:32:56 -07001087 if dynamicDepender, ok := ctx.Module().(DynamicDependerModule); ok {
1088 dynamicDeps := dynamicDepender.DynamicDependencies(ctx)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001089
Colin Cross763b6f12015-10-29 15:32:56 -07001090 if ctx.Failed() {
1091 return
Colin Crossa434b3f2015-01-13 10:59:52 -08001092 }
Colin Cross763b6f12015-10-29 15:32:56 -07001093
1094 ctx.AddDependency(ctx.Module(), dynamicDeps...)
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001095 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001096}
1097
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001098// findMatchingVariant searches the moduleGroup for a module with the same variant as module,
1099// and returns the matching module, or nil if one is not found.
1100func (c *Context) findMatchingVariant(module *moduleInfo, group *moduleGroup) *moduleInfo {
1101 if len(group.modules) == 1 {
1102 return group.modules[0]
1103 } else {
1104 for _, m := range group.modules {
1105 if m.variant.equal(module.dependencyVariant) {
1106 return m
1107 }
1108 }
1109 }
1110
1111 return nil
1112}
1113
Colin Crossc9028482014-12-18 16:28:54 -08001114func (c *Context) addDependency(module *moduleInfo, depName string) []error {
Colin Crossed342d92015-03-11 00:57:25 -07001115 if depName == module.properties.Name {
Colin Crossc9028482014-12-18 16:28:54 -08001116 return []error{&Error{
1117 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001118 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001119 }}
1120 }
1121
1122 depInfo, ok := c.moduleGroups[depName]
1123 if !ok {
1124 return []error{&Error{
1125 Err: fmt.Errorf("%q depends on undefined module %q",
Colin Crossed342d92015-03-11 00:57:25 -07001126 module.properties.Name, depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001127 Pos: module.pos,
Colin Crossc9028482014-12-18 16:28:54 -08001128 }}
1129 }
1130
Colin Cross65569e42015-03-10 20:08:19 -07001131 for _, m := range module.directDeps {
1132 if m.group == depInfo {
1133 return nil
1134 }
Colin Crossc9028482014-12-18 16:28:54 -08001135 }
1136
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001137 if m := c.findMatchingVariant(module, depInfo); m != nil {
1138 module.directDeps = append(module.directDeps, m)
Colin Cross65569e42015-03-10 20:08:19 -07001139 return nil
Colin Cross65569e42015-03-10 20:08:19 -07001140 }
Colin Crossc9028482014-12-18 16:28:54 -08001141
Colin Cross65569e42015-03-10 20:08:19 -07001142 return []error{&Error{
1143 Err: fmt.Errorf("dependency %q of %q missing variant %q",
1144 depInfo.modules[0].properties.Name, module.properties.Name,
Colin Crossf5e34b92015-03-13 16:02:36 -07001145 c.prettyPrintVariant(module.dependencyVariant)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001146 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001147 }}
1148}
1149
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001150func (c *Context) addReverseDependency(module *moduleInfo, destName string) []error {
1151 if destName == module.properties.Name {
1152 return []error{&Error{
1153 Err: fmt.Errorf("%q depends on itself", destName),
1154 Pos: module.pos,
1155 }}
1156 }
1157
1158 destInfo, ok := c.moduleGroups[destName]
1159 if !ok {
1160 return []error{&Error{
1161 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
1162 module.properties.Name, destName),
1163 Pos: module.pos,
1164 }}
1165 }
1166
1167 if m := c.findMatchingVariant(module, destInfo); m != nil {
1168 m.directDeps = append(m.directDeps, module)
1169 return nil
1170 }
1171
1172 return []error{&Error{
1173 Err: fmt.Errorf("reverse dependency %q of %q missing variant %q",
1174 destName, module.properties.Name,
1175 c.prettyPrintVariant(module.dependencyVariant)),
1176 Pos: module.pos,
1177 }}
1178}
1179
Colin Crossf5e34b92015-03-13 16:02:36 -07001180func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Colin Cross89486232015-05-08 11:14:54 -07001181 depName string, far bool) []error {
Colin Cross65569e42015-03-10 20:08:19 -07001182
Colin Cross65569e42015-03-10 20:08:19 -07001183 depInfo, ok := c.moduleGroups[depName]
1184 if !ok {
1185 return []error{&Error{
1186 Err: fmt.Errorf("%q depends on undefined module %q",
1187 module.properties.Name, depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001188 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001189 }}
1190 }
1191
1192 // We can't just append variant.Variant to module.dependencyVariants.variantName and
1193 // compare the strings because the result won't be in mutator registration order.
1194 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001195 var newVariant variationMap
1196 if !far {
1197 newVariant = module.dependencyVariant.clone()
1198 } else {
1199 newVariant = make(variationMap)
1200 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001201 for _, v := range variations {
1202 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001203 }
1204
1205 for _, m := range depInfo.modules {
Colin Cross89486232015-05-08 11:14:54 -07001206 var found bool
1207 if far {
1208 found = m.variant.subset(newVariant)
1209 } else {
1210 found = m.variant.equal(newVariant)
1211 }
1212 if found {
Colin Cross045a5972015-11-03 16:58:48 -08001213 if module == m {
1214 return []error{&Error{
1215 Err: fmt.Errorf("%q depends on itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001216 Pos: module.pos,
Colin Cross045a5972015-11-03 16:58:48 -08001217 }}
1218 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001219 // AddVariationDependency allows adding a dependency on itself, but only if
Colin Cross65569e42015-03-10 20:08:19 -07001220 // that module is earlier in the module list than this one, since we always
Colin Crossf5e34b92015-03-13 16:02:36 -07001221 // run GenerateBuildActions in order for the variants of a module
Colin Cross65569e42015-03-10 20:08:19 -07001222 if depInfo == module.group && beforeInModuleList(module, m, module.group.modules) {
1223 return []error{&Error{
1224 Err: fmt.Errorf("%q depends on later version of itself", depName),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001225 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001226 }}
1227 }
1228 module.directDeps = append(module.directDeps, m)
1229 return nil
1230 }
1231 }
1232
1233 return []error{&Error{
1234 Err: fmt.Errorf("dependency %q of %q missing variant %q",
1235 depInfo.modules[0].properties.Name, module.properties.Name,
Colin Crossf5e34b92015-03-13 16:02:36 -07001236 c.prettyPrintVariant(newVariant)),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001237 Pos: module.pos,
Colin Cross65569e42015-03-10 20:08:19 -07001238 }}
Colin Crossc9028482014-12-18 16:28:54 -08001239}
1240
Colin Cross7addea32015-03-11 15:43:52 -07001241func (c *Context) parallelVisitAllBottomUp(visit func(group *moduleInfo) bool) {
1242 doneCh := make(chan *moduleInfo)
Colin Cross691a60d2015-01-07 18:08:56 -08001243 count := 0
Colin Cross8900e9b2015-03-02 14:03:01 -08001244 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001245
Colin Cross7addea32015-03-11 15:43:52 -07001246 for _, module := range c.modulesSorted {
1247 module.waitingCount = module.depsCount
Colin Cross691a60d2015-01-07 18:08:56 -08001248 }
1249
Colin Cross7addea32015-03-11 15:43:52 -07001250 visitOne := func(module *moduleInfo) {
Colin Cross691a60d2015-01-07 18:08:56 -08001251 count++
1252 go func() {
Colin Cross7addea32015-03-11 15:43:52 -07001253 ret := visit(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08001254 if ret {
1255 cancel = true
1256 }
Colin Cross7addea32015-03-11 15:43:52 -07001257 doneCh <- module
Colin Cross691a60d2015-01-07 18:08:56 -08001258 }()
1259 }
1260
Colin Cross7addea32015-03-11 15:43:52 -07001261 for _, module := range c.modulesSorted {
1262 if module.waitingCount == 0 {
1263 visitOne(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001264 }
1265 }
1266
Colin Cross11e3b0d2015-02-04 10:41:00 -08001267 for count > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08001268 select {
Colin Cross7addea32015-03-11 15:43:52 -07001269 case doneModule := <-doneCh:
Colin Cross8900e9b2015-03-02 14:03:01 -08001270 if !cancel {
Colin Cross7addea32015-03-11 15:43:52 -07001271 for _, parent := range doneModule.reverseDeps {
Colin Cross8900e9b2015-03-02 14:03:01 -08001272 parent.waitingCount--
1273 if parent.waitingCount == 0 {
1274 visitOne(parent)
1275 }
Colin Cross691a60d2015-01-07 18:08:56 -08001276 }
1277 }
1278 count--
Colin Cross691a60d2015-01-07 18:08:56 -08001279 }
1280 }
1281}
1282
1283// updateDependencies recursively walks the module dependency graph and updates
1284// additional fields based on the dependencies. It builds a sorted list of modules
1285// such that dependencies of a module always appear first, and populates reverse
1286// dependency links and counts of total dependencies. It also reports errors when
1287// it encounters dependency cycles. This should called after resolveDependencies,
1288// as well as after any mutator pass has called addDependency
1289func (c *Context) updateDependencies() (errs []error) {
Colin Cross7addea32015-03-11 15:43:52 -07001290 visited := make(map[*moduleInfo]bool) // modules that were already checked
1291 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001292
Colin Cross7addea32015-03-11 15:43:52 -07001293 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08001294
Colin Cross7addea32015-03-11 15:43:52 -07001295 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001296
Colin Cross7addea32015-03-11 15:43:52 -07001297 cycleError := func(cycle []*moduleInfo) {
Colin Cross10b54db2015-03-11 14:40:30 -07001298 // We are the "start" of the cycle, so we're responsible
1299 // for generating the errors. The cycle list is in
1300 // reverse order because all the 'check' calls append
1301 // their own module to the list.
1302 errs = append(errs, &Error{
1303 Err: fmt.Errorf("encountered dependency cycle:"),
Colin Cross7addea32015-03-11 15:43:52 -07001304 Pos: cycle[len(cycle)-1].pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001305 })
1306
1307 // Iterate backwards through the cycle list.
Colin Cross0e4607e2015-03-24 16:42:56 -07001308 curModule := cycle[0]
Colin Cross10b54db2015-03-11 14:40:30 -07001309 for i := len(cycle) - 1; i >= 0; i-- {
Colin Cross7addea32015-03-11 15:43:52 -07001310 nextModule := cycle[i]
Colin Cross10b54db2015-03-11 14:40:30 -07001311 errs = append(errs, &Error{
1312 Err: fmt.Errorf(" %q depends on %q",
Colin Cross7addea32015-03-11 15:43:52 -07001313 curModule.properties.Name,
1314 nextModule.properties.Name),
Colin Cross7fcb7b02015-11-03 17:33:29 -08001315 Pos: curModule.pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001316 })
Colin Cross7addea32015-03-11 15:43:52 -07001317 curModule = nextModule
Colin Cross10b54db2015-03-11 14:40:30 -07001318 }
1319 }
1320
Colin Cross7addea32015-03-11 15:43:52 -07001321 check = func(module *moduleInfo) []*moduleInfo {
1322 visited[module] = true
1323 checking[module] = true
1324 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001325
Colin Cross7addea32015-03-11 15:43:52 -07001326 deps := make(map[*moduleInfo]bool)
1327
1328 // Add an implicit dependency ordering on all earlier modules in the same module group
1329 for _, dep := range module.group.modules {
1330 if dep == module {
1331 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08001332 }
Colin Cross7addea32015-03-11 15:43:52 -07001333 deps[dep] = true
Colin Crossbbfa51a2014-12-17 16:12:41 -08001334 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001335
Colin Cross7addea32015-03-11 15:43:52 -07001336 for _, dep := range module.directDeps {
1337 deps[dep] = true
1338 }
1339
1340 module.reverseDeps = []*moduleInfo{}
1341 module.depsCount = len(deps)
Colin Cross691a60d2015-01-07 18:08:56 -08001342
Colin Crossbbfa51a2014-12-17 16:12:41 -08001343 for dep := range deps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001344 if checking[dep] {
1345 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07001346 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001347 }
1348
1349 if !visited[dep] {
1350 cycle := check(dep)
1351 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001352 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001353 // We are the "start" of the cycle, so we're responsible
1354 // for generating the errors. The cycle list is in
1355 // reverse order because all the 'check' calls append
1356 // their own module to the list.
Colin Cross10b54db2015-03-11 14:40:30 -07001357 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001358
1359 // We can continue processing this module's children to
1360 // find more cycles. Since all the modules that were
1361 // part of the found cycle were marked as visited we
1362 // won't run into that cycle again.
1363 } else {
1364 // We're not the "start" of the cycle, so we just append
1365 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07001366 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001367 }
1368 }
1369 }
Colin Cross691a60d2015-01-07 18:08:56 -08001370
Colin Cross7addea32015-03-11 15:43:52 -07001371 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001372 }
1373
Colin Cross7addea32015-03-11 15:43:52 -07001374 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08001375
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001376 return nil
1377 }
1378
Colin Cross7addea32015-03-11 15:43:52 -07001379 for _, module := range c.moduleInfo {
1380 if !visited[module] {
1381 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001382 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001383 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07001384 panic("inconceivable!")
1385 }
1386 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001387 }
1388 }
1389 }
1390
Colin Cross7addea32015-03-11 15:43:52 -07001391 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08001392
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001393 return
1394}
1395
Jamie Gennisd4e10182014-06-12 20:06:50 -07001396// PrepareBuildActions generates an internal representation of all the build
1397// actions that need to be performed. This process involves invoking the
1398// GenerateBuildActions method on each of the Module objects created during the
1399// parse phase and then on each of the registered Singleton objects.
1400//
1401// If the ResolveDependencies method has not already been called it is called
1402// automatically by this method.
1403//
1404// The config argument is made available to all of the Module and Singleton
1405// objects via the Config method on the ModuleContext and SingletonContext
1406// objects passed to GenerateBuildActions. It is also passed to the functions
1407// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
1408// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001409//
1410// The returned deps is a list of the ninja files dependencies that were added
1411// by the modules and singletons via the ModuleContext.AddNinjaFileDeps() and
1412// SingletonContext.AddNinjaFileDeps() methods.
1413func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001414 c.buildActionsReady = false
1415
1416 if !c.dependenciesReady {
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001417 errs := c.ResolveDependencies(config)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001418 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001419 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001420 }
1421 }
1422
1423 liveGlobals := newLiveTracker(config)
1424
1425 c.initSpecialVariables()
1426
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001427 depsModules, errs := c.generateModuleBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001428 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001429 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001430 }
1431
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001432 depsSingletons, errs := c.generateSingletonBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001433 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001434 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001435 }
1436
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001437 deps = append(depsModules, depsSingletons...)
1438
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001439 if c.buildDir != nil {
1440 liveGlobals.addNinjaStringDeps(c.buildDir)
1441 }
1442
1443 pkgNames := c.makeUniquePackageNames(liveGlobals)
1444
1445 // This will panic if it finds a problem since it's a programming error.
1446 c.checkForVariableReferenceCycles(liveGlobals.variables, pkgNames)
1447
1448 c.pkgNames = pkgNames
1449 c.globalVariables = liveGlobals.variables
1450 c.globalPools = liveGlobals.pools
1451 c.globalRules = liveGlobals.rules
1452
1453 c.buildActionsReady = true
1454
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001455 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001456}
1457
Colin Cross65569e42015-03-10 20:08:19 -07001458func (c *Context) runEarlyMutators(config interface{}) (errs []error) {
1459 for _, mutator := range c.earlyMutatorInfo {
1460 for _, group := range c.moduleGroups {
1461 newModules := make([]*moduleInfo, 0, len(group.modules))
1462
1463 for _, module := range group.modules {
1464 mctx := &mutatorContext{
1465 baseModuleContext: baseModuleContext{
1466 context: c,
1467 config: config,
1468 module: module,
1469 },
1470 name: mutator.name,
1471 }
1472 mutator.mutator(mctx)
1473 if len(mctx.errs) > 0 {
1474 errs = append(errs, mctx.errs...)
1475 return errs
1476 }
1477
1478 if module.splitModules != nil {
1479 newModules = append(newModules, module.splitModules...)
1480 } else {
1481 newModules = append(newModules, module)
1482 }
1483 }
1484
1485 group.modules = newModules
1486 }
1487 }
1488
Colin Cross763b6f12015-10-29 15:32:56 -07001489 errs = c.updateDependencies()
1490 if len(errs) > 0 {
1491 return errs
1492 }
1493
Colin Cross65569e42015-03-10 20:08:19 -07001494 return nil
1495}
1496
Colin Crossc9028482014-12-18 16:28:54 -08001497func (c *Context) runMutators(config interface{}) (errs []error) {
Colin Cross763b6f12015-10-29 15:32:56 -07001498 errs = c.runEarlyMutators(config)
1499 if len(errs) > 0 {
1500 return errs
1501 }
1502
Colin Crossc9028482014-12-18 16:28:54 -08001503 for _, mutator := range c.mutatorInfo {
1504 if mutator.topDownMutator != nil {
1505 errs = c.runTopDownMutator(config, mutator.name, mutator.topDownMutator)
1506 } else if mutator.bottomUpMutator != nil {
1507 errs = c.runBottomUpMutator(config, mutator.name, mutator.bottomUpMutator)
1508 } else {
1509 panic("no mutator set on " + mutator.name)
1510 }
1511 if len(errs) > 0 {
1512 return errs
1513 }
1514 }
1515
1516 return nil
1517}
1518
1519func (c *Context) runTopDownMutator(config interface{},
1520 name string, mutator TopDownMutator) (errs []error) {
1521
Colin Cross7addea32015-03-11 15:43:52 -07001522 for i := 0; i < len(c.modulesSorted); i++ {
1523 module := c.modulesSorted[len(c.modulesSorted)-1-i]
1524 mctx := &mutatorContext{
1525 baseModuleContext: baseModuleContext{
1526 context: c,
1527 config: config,
1528 module: module,
1529 },
1530 name: name,
1531 }
Colin Crossc9028482014-12-18 16:28:54 -08001532
Colin Cross7addea32015-03-11 15:43:52 -07001533 mutator(mctx)
1534 if len(mctx.errs) > 0 {
1535 errs = append(errs, mctx.errs...)
1536 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001537 }
1538 }
1539
1540 return errs
1541}
1542
1543func (c *Context) runBottomUpMutator(config interface{},
1544 name string, mutator BottomUpMutator) (errs []error) {
1545
Colin Cross7addea32015-03-11 15:43:52 -07001546 for _, module := range c.modulesSorted {
1547 newModules := make([]*moduleInfo, 0, 1)
Colin Crossc9028482014-12-18 16:28:54 -08001548
Jamie Gennisc7988252015-04-14 23:28:10 -04001549 if module.splitModules != nil {
1550 panic("split module found in sorted module list")
1551 }
1552
Colin Cross7addea32015-03-11 15:43:52 -07001553 mctx := &mutatorContext{
1554 baseModuleContext: baseModuleContext{
1555 context: c,
1556 config: config,
1557 module: module,
1558 },
1559 name: name,
1560 }
Colin Crossc9028482014-12-18 16:28:54 -08001561
Colin Cross7addea32015-03-11 15:43:52 -07001562 mutator(mctx)
1563 if len(mctx.errs) > 0 {
1564 errs = append(errs, mctx.errs...)
1565 return errs
1566 }
Colin Crossc9028482014-12-18 16:28:54 -08001567
Colin Cross7addea32015-03-11 15:43:52 -07001568 // Fix up any remaining dependencies on modules that were split into variants
1569 // by replacing them with the first variant
1570 for i, dep := range module.directDeps {
1571 if dep.logicModule == nil {
1572 module.directDeps[i] = dep.splitModules[0]
Colin Crossc9028482014-12-18 16:28:54 -08001573 }
1574 }
1575
Colin Cross7addea32015-03-11 15:43:52 -07001576 if module.splitModules != nil {
1577 newModules = append(newModules, module.splitModules...)
1578 } else {
1579 newModules = append(newModules, module)
1580 }
1581
1582 module.group.modules = spliceModules(module.group.modules, module, newModules)
Colin Crossc9028482014-12-18 16:28:54 -08001583 }
1584
Jamie Gennisc7988252015-04-14 23:28:10 -04001585 errs = c.updateDependencies()
1586 if len(errs) > 0 {
1587 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001588 }
1589
1590 return errs
1591}
1592
Colin Cross7addea32015-03-11 15:43:52 -07001593func spliceModules(modules []*moduleInfo, origModule *moduleInfo,
1594 newModules []*moduleInfo) []*moduleInfo {
1595 for i, m := range modules {
1596 if m == origModule {
1597 return spliceModulesAtIndex(modules, i, newModules)
1598 }
1599 }
1600
1601 panic("failed to find original module to splice")
1602}
1603
1604func spliceModulesAtIndex(modules []*moduleInfo, i int, newModules []*moduleInfo) []*moduleInfo {
1605 spliceSize := len(newModules)
1606 newLen := len(modules) + spliceSize - 1
1607 var dest []*moduleInfo
1608 if cap(modules) >= len(modules)-1+len(newModules) {
1609 // We can fit the splice in the existing capacity, do everything in place
1610 dest = modules[:newLen]
1611 } else {
1612 dest = make([]*moduleInfo, newLen)
1613 copy(dest, modules[:i])
1614 }
1615
1616 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07001617 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07001618
1619 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07001620 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07001621
Colin Cross72bd1932015-03-16 00:13:59 -07001622 return dest
Colin Cross7addea32015-03-11 15:43:52 -07001623}
1624
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001625func (c *Context) initSpecialVariables() {
1626 c.buildDir = nil
1627 c.requiredNinjaMajor = 1
Dan Willemsen21b6f372015-07-22 12:58:01 -07001628 c.requiredNinjaMinor = 6
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001629 c.requiredNinjaMicro = 0
1630}
1631
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001632func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001633 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001634
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001635 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001636 var errs []error
1637
Colin Cross691a60d2015-01-07 18:08:56 -08001638 cancelCh := make(chan struct{})
1639 errsCh := make(chan []error)
1640 depsCh := make(chan []string)
1641
1642 go func() {
1643 for {
1644 select {
1645 case <-cancelCh:
1646 close(cancelCh)
1647 return
1648 case newErrs := <-errsCh:
1649 errs = append(errs, newErrs...)
1650 case newDeps := <-depsCh:
1651 deps = append(deps, newDeps...)
1652
1653 }
1654 }
1655 }()
1656
Colin Cross7addea32015-03-11 15:43:52 -07001657 c.parallelVisitAllBottomUp(func(module *moduleInfo) bool {
1658 // The parent scope of the moduleContext's local scope gets overridden to be that of the
1659 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1660 // just set it to nil.
1661 prefix := moduleNamespacePrefix(module.group.ninjaName + "_" + module.variantName)
1662 scope := newLocalScope(nil, prefix)
Colin Cross6134a5c2015-02-10 11:26:26 -08001663
Colin Cross7addea32015-03-11 15:43:52 -07001664 mctx := &moduleContext{
1665 baseModuleContext: baseModuleContext{
1666 context: c,
1667 config: config,
1668 module: module,
1669 },
1670 scope: scope,
1671 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001672
Colin Cross7addea32015-03-11 15:43:52 -07001673 mctx.module.logicModule.GenerateBuildActions(mctx)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001674
Colin Cross7addea32015-03-11 15:43:52 -07001675 if len(mctx.errs) > 0 {
1676 errsCh <- mctx.errs
1677 return true
1678 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001679
Colin Cross7addea32015-03-11 15:43:52 -07001680 depsCh <- mctx.ninjaFileDeps
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001681
Colin Crossab6d7902015-03-11 16:17:52 -07001682 newErrs := c.processLocalBuildActions(&module.actionDefs,
Colin Cross7addea32015-03-11 15:43:52 -07001683 &mctx.actionDefs, liveGlobals)
1684 if len(newErrs) > 0 {
1685 errsCh <- newErrs
1686 return true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001687 }
Colin Cross8900e9b2015-03-02 14:03:01 -08001688 return false
Colin Cross691a60d2015-01-07 18:08:56 -08001689 })
1690
1691 cancelCh <- struct{}{}
1692 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001693
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001694 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001695}
1696
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001697func (c *Context) generateSingletonBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001698 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001699
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001700 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001701 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001702
Yuchen Wub9103ef2015-08-25 17:58:17 -07001703 for _, info := range c.singletonInfo {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001704 // The parent scope of the singletonContext's local scope gets overridden to be that of the
1705 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1706 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07001707 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001708
1709 sctx := &singletonContext{
1710 context: c,
1711 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001712 scope: scope,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001713 }
1714
1715 info.singleton.GenerateBuildActions(sctx)
1716
1717 if len(sctx.errs) > 0 {
1718 errs = append(errs, sctx.errs...)
1719 if len(errs) > maxErrors {
1720 break
1721 }
1722 continue
1723 }
1724
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001725 deps = append(deps, sctx.ninjaFileDeps...)
1726
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001727 newErrs := c.processLocalBuildActions(&info.actionDefs,
1728 &sctx.actionDefs, liveGlobals)
1729 errs = append(errs, newErrs...)
1730 if len(errs) > maxErrors {
1731 break
1732 }
1733 }
1734
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001735 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001736}
1737
1738func (c *Context) processLocalBuildActions(out, in *localBuildActions,
1739 liveGlobals *liveTracker) []error {
1740
1741 var errs []error
1742
1743 // First we go through and add everything referenced by the module's
1744 // buildDefs to the live globals set. This will end up adding the live
1745 // locals to the set as well, but we'll take them out after.
1746 for _, def := range in.buildDefs {
1747 err := liveGlobals.AddBuildDefDeps(def)
1748 if err != nil {
1749 errs = append(errs, err)
1750 }
1751 }
1752
1753 if len(errs) > 0 {
1754 return errs
1755 }
1756
Colin Crossc9028482014-12-18 16:28:54 -08001757 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001758
1759 // We use the now-incorrect set of live "globals" to determine which local
1760 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08001761 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001762 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07001763 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001764 if isLive {
1765 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001766 }
1767 }
1768
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001769 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07001770 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001771 if isLive {
1772 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001773 }
1774 }
1775
1776 return nil
1777}
1778
Yuchen Wu222e2452015-10-06 14:03:27 -07001779func (c *Context) walkDeps(topModule *moduleInfo,
1780 visit func(Module, Module) bool) {
1781
1782 visited := make(map[*moduleInfo]bool)
1783
1784 var walk func(module *moduleInfo)
1785 walk = func(module *moduleInfo) {
1786 visited[module] = true
1787
1788 for _, moduleDep := range module.directDeps {
1789 if !visited[moduleDep] {
1790 if visit(moduleDep.logicModule, module.logicModule) {
1791 walk(moduleDep)
1792 }
1793 }
1794 }
1795 }
1796
1797 walk(topModule)
1798}
1799
Colin Crossbbfa51a2014-12-17 16:12:41 -08001800func (c *Context) visitDepsDepthFirst(topModule *moduleInfo, visit func(Module)) {
1801 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001802
Colin Crossbbfa51a2014-12-17 16:12:41 -08001803 var walk func(module *moduleInfo)
1804 walk = func(module *moduleInfo) {
1805 visited[module] = true
1806 for _, moduleDep := range module.directDeps {
1807 if !visited[moduleDep] {
1808 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001809 }
1810 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001811
Colin Crossbbfa51a2014-12-17 16:12:41 -08001812 if module != topModule {
1813 visit(module.logicModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001814 }
1815 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001816
1817 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001818}
1819
Colin Crossbbfa51a2014-12-17 16:12:41 -08001820func (c *Context) visitDepsDepthFirstIf(topModule *moduleInfo, pred func(Module) bool,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001821 visit func(Module)) {
1822
Colin Crossbbfa51a2014-12-17 16:12:41 -08001823 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001824
Colin Crossbbfa51a2014-12-17 16:12:41 -08001825 var walk func(module *moduleInfo)
1826 walk = func(module *moduleInfo) {
1827 visited[module] = true
1828 for _, moduleDep := range module.directDeps {
1829 if !visited[moduleDep] {
1830 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001831 }
Jamie Gennis0bb5d8a2014-11-26 14:45:37 -08001832 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001833
1834 if module != topModule {
1835 if pred(module.logicModule) {
1836 visit(module.logicModule)
1837 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001838 }
1839 }
1840
Colin Crossbbfa51a2014-12-17 16:12:41 -08001841 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001842}
1843
Colin Crossc9028482014-12-18 16:28:54 -08001844func (c *Context) visitDirectDeps(module *moduleInfo, visit func(Module)) {
1845 for _, dep := range module.directDeps {
1846 visit(dep.logicModule)
1847 }
1848}
1849
1850func (c *Context) visitDirectDepsIf(module *moduleInfo, pred func(Module) bool,
1851 visit func(Module)) {
1852
1853 for _, dep := range module.directDeps {
1854 if pred(dep.logicModule) {
1855 visit(dep.logicModule)
1856 }
1857 }
1858}
1859
Jamie Gennisc15544d2014-09-24 20:26:52 -07001860func (c *Context) sortedModuleNames() []string {
1861 if c.cachedSortedModuleNames == nil {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001862 c.cachedSortedModuleNames = make([]string, 0, len(c.moduleGroups))
1863 for moduleName := range c.moduleGroups {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001864 c.cachedSortedModuleNames = append(c.cachedSortedModuleNames,
1865 moduleName)
1866 }
1867 sort.Strings(c.cachedSortedModuleNames)
1868 }
1869
1870 return c.cachedSortedModuleNames
1871}
1872
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001873func (c *Context) visitAllModules(visit func(Module)) {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001874 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001875 group := c.moduleGroups[moduleName]
1876 for _, module := range group.modules {
1877 visit(module.logicModule)
1878 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001879 }
1880}
1881
1882func (c *Context) visitAllModulesIf(pred func(Module) bool,
1883 visit func(Module)) {
1884
Jamie Gennisc15544d2014-09-24 20:26:52 -07001885 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001886 group := c.moduleGroups[moduleName]
1887 for _, module := range group.modules {
1888 if pred(module.logicModule) {
1889 visit(module.logicModule)
1890 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001891 }
1892 }
1893}
1894
1895func (c *Context) requireNinjaVersion(major, minor, micro int) {
1896 if major != 1 {
1897 panic("ninja version with major version != 1 not supported")
1898 }
1899 if c.requiredNinjaMinor < minor {
1900 c.requiredNinjaMinor = minor
1901 c.requiredNinjaMicro = micro
1902 }
1903 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
1904 c.requiredNinjaMicro = micro
1905 }
1906}
1907
1908func (c *Context) setBuildDir(value *ninjaString) {
1909 if c.buildDir != nil {
1910 panic("buildDir set multiple times")
1911 }
1912 c.buildDir = value
1913}
1914
1915func (c *Context) makeUniquePackageNames(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001916 liveGlobals *liveTracker) map[*PackageContext]string {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001917
Jamie Gennis2fb20952014-10-03 02:49:58 -07001918 pkgs := make(map[string]*PackageContext)
1919 pkgNames := make(map[*PackageContext]string)
1920 longPkgNames := make(map[*PackageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001921
Jamie Gennis2fb20952014-10-03 02:49:58 -07001922 processPackage := func(pctx *PackageContext) {
1923 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001924 // This is a built-in rule and has no package.
1925 return
1926 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07001927 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001928 // We've already processed this package.
1929 return
1930 }
1931
Jamie Gennis2fb20952014-10-03 02:49:58 -07001932 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001933 if present {
1934 // Short name collision. Both this package and the one that's
1935 // already there need to use their full names. We leave the short
1936 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001937 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001938 longPkgNames[otherPkg] = true
1939 } else {
1940 // No collision so far. Tentatively set the package's name to be
1941 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001942 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07001943 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001944 }
1945 }
1946
1947 // We try to give all packages their short name, but when we get collisions
1948 // we need to use the full unique package name.
1949 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001950 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001951 }
1952 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001953 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001954 }
1955 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001956 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001957 }
1958
1959 // Add the packages that had collisions using their full unique names. This
1960 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001961 for pctx := range longPkgNames {
1962 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001963 }
1964
1965 return pkgNames
1966}
1967
1968func (c *Context) checkForVariableReferenceCycles(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001969 variables map[Variable]*ninjaString, pkgNames map[*PackageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001970
1971 visited := make(map[Variable]bool) // variables that were already checked
1972 checking := make(map[Variable]bool) // variables actively being checked
1973
1974 var check func(v Variable) []Variable
1975
1976 check = func(v Variable) []Variable {
1977 visited[v] = true
1978 checking[v] = true
1979 defer delete(checking, v)
1980
1981 value := variables[v]
1982 for _, dep := range value.variables {
1983 if checking[dep] {
1984 // This is a cycle.
1985 return []Variable{dep, v}
1986 }
1987
1988 if !visited[dep] {
1989 cycle := check(dep)
1990 if cycle != nil {
1991 if cycle[0] == v {
1992 // We are the "start" of the cycle, so we're responsible
1993 // for generating the errors. The cycle list is in
1994 // reverse order because all the 'check' calls append
1995 // their own module to the list.
1996 msgs := []string{"detected variable reference cycle:"}
1997
1998 // Iterate backwards through the cycle list.
1999 curName := v.fullName(pkgNames)
2000 curValue := value.Value(pkgNames)
2001 for i := len(cycle) - 1; i >= 0; i-- {
2002 next := cycle[i]
2003 nextName := next.fullName(pkgNames)
2004 nextValue := variables[next].Value(pkgNames)
2005
2006 msgs = append(msgs, fmt.Sprintf(
2007 " %q depends on %q", curName, nextName))
2008 msgs = append(msgs, fmt.Sprintf(
2009 " [%s = %s]", curName, curValue))
2010
2011 curName = nextName
2012 curValue = nextValue
2013 }
2014
2015 // Variable reference cycles are a programming error,
2016 // not the fault of the Blueprint file authors.
2017 panic(strings.Join(msgs, "\n"))
2018 } else {
2019 // We're not the "start" of the cycle, so we just append
2020 // our module to the list and return it.
2021 return append(cycle, v)
2022 }
2023 }
2024 }
2025 }
2026
2027 return nil
2028 }
2029
2030 for v := range variables {
2031 if !visited[v] {
2032 cycle := check(v)
2033 if cycle != nil {
2034 panic("inconceivable!")
2035 }
2036 }
2037 }
2038}
2039
Jamie Gennisaf435562014-10-27 22:34:56 -07002040// AllTargets returns a map all the build target names to the rule used to build
2041// them. This is the same information that is output by running 'ninja -t
2042// targets all'. If this is called before PrepareBuildActions successfully
2043// completes then ErrbuildActionsNotReady is returned.
2044func (c *Context) AllTargets() (map[string]string, error) {
2045 if !c.buildActionsReady {
2046 return nil, ErrBuildActionsNotReady
2047 }
2048
2049 targets := map[string]string{}
2050
2051 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07002052 for _, module := range c.moduleInfo {
2053 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07002054 ruleName := buildDef.Rule.fullName(c.pkgNames)
2055 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002056 outputValue, err := output.Eval(c.globalVariables)
2057 if err != nil {
2058 return nil, err
2059 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002060 targets[outputValue] = ruleName
2061 }
2062 }
2063 }
2064
2065 // Collect all the singleton build targets.
2066 for _, info := range c.singletonInfo {
2067 for _, buildDef := range info.actionDefs.buildDefs {
2068 ruleName := buildDef.Rule.fullName(c.pkgNames)
2069 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002070 outputValue, err := output.Eval(c.globalVariables)
2071 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08002072 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08002073 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002074 targets[outputValue] = ruleName
2075 }
2076 }
2077 }
2078
2079 return targets, nil
2080}
2081
Colin Cross4572edd2015-05-13 14:36:24 -07002082// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
2083// property structs returned by the factory for that module type.
2084func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
2085 ret := make(map[string][]interface{})
2086 for moduleType, factory := range c.moduleFactories {
2087 _, ret[moduleType] = factory()
2088 }
2089
2090 return ret
2091}
2092
2093func (c *Context) ModuleName(logicModule Module) string {
2094 module := c.moduleInfo[logicModule]
2095 return module.properties.Name
2096}
2097
2098func (c *Context) ModuleDir(logicModule Module) string {
2099 module := c.moduleInfo[logicModule]
2100 return filepath.Dir(module.relBlueprintsFile)
2101}
2102
2103func (c *Context) BlueprintFile(logicModule Module) string {
2104 module := c.moduleInfo[logicModule]
2105 return module.relBlueprintsFile
2106}
2107
2108func (c *Context) ModuleErrorf(logicModule Module, format string,
2109 args ...interface{}) error {
2110
2111 module := c.moduleInfo[logicModule]
2112 return &Error{
2113 Err: fmt.Errorf(format, args...),
2114 Pos: module.pos,
2115 }
2116}
2117
2118func (c *Context) VisitAllModules(visit func(Module)) {
2119 c.visitAllModules(visit)
2120}
2121
2122func (c *Context) VisitAllModulesIf(pred func(Module) bool,
2123 visit func(Module)) {
2124
2125 c.visitAllModulesIf(pred, visit)
2126}
2127
2128func (c *Context) VisitDepsDepthFirst(module Module,
2129 visit func(Module)) {
2130
2131 c.visitDepsDepthFirst(c.moduleInfo[module], visit)
2132}
2133
2134func (c *Context) VisitDepsDepthFirstIf(module Module,
2135 pred func(Module) bool, visit func(Module)) {
2136
2137 c.visitDepsDepthFirstIf(c.moduleInfo[module], pred, visit)
2138}
2139
Jamie Gennisd4e10182014-06-12 20:06:50 -07002140// WriteBuildFile writes the Ninja manifeset text for the generated build
2141// actions to w. If this is called before PrepareBuildActions successfully
2142// completes then ErrBuildActionsNotReady is returned.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002143func (c *Context) WriteBuildFile(w io.Writer) error {
2144 if !c.buildActionsReady {
2145 return ErrBuildActionsNotReady
2146 }
2147
2148 nw := newNinjaWriter(w)
2149
2150 err := c.writeBuildFileHeader(nw)
2151 if err != nil {
2152 return err
2153 }
2154
2155 err = c.writeNinjaRequiredVersion(nw)
2156 if err != nil {
2157 return err
2158 }
2159
2160 // TODO: Group the globals by package.
2161
2162 err = c.writeGlobalVariables(nw)
2163 if err != nil {
2164 return err
2165 }
2166
2167 err = c.writeGlobalPools(nw)
2168 if err != nil {
2169 return err
2170 }
2171
2172 err = c.writeBuildDir(nw)
2173 if err != nil {
2174 return err
2175 }
2176
2177 err = c.writeGlobalRules(nw)
2178 if err != nil {
2179 return err
2180 }
2181
2182 err = c.writeAllModuleActions(nw)
2183 if err != nil {
2184 return err
2185 }
2186
2187 err = c.writeAllSingletonActions(nw)
2188 if err != nil {
2189 return err
2190 }
2191
2192 return nil
2193}
2194
Jamie Gennisc15544d2014-09-24 20:26:52 -07002195type pkgAssociation struct {
2196 PkgName string
2197 PkgPath string
2198}
2199
2200type pkgAssociationSorter struct {
2201 pkgs []pkgAssociation
2202}
2203
2204func (s *pkgAssociationSorter) Len() int {
2205 return len(s.pkgs)
2206}
2207
2208func (s *pkgAssociationSorter) Less(i, j int) bool {
2209 iName := s.pkgs[i].PkgName
2210 jName := s.pkgs[j].PkgName
2211 return iName < jName
2212}
2213
2214func (s *pkgAssociationSorter) Swap(i, j int) {
2215 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
2216}
2217
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002218func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
2219 headerTemplate := template.New("fileHeader")
2220 _, err := headerTemplate.Parse(fileHeaderTemplate)
2221 if err != nil {
2222 // This is a programming error.
2223 panic(err)
2224 }
2225
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002226 var pkgs []pkgAssociation
2227 maxNameLen := 0
2228 for pkg, name := range c.pkgNames {
2229 pkgs = append(pkgs, pkgAssociation{
2230 PkgName: name,
2231 PkgPath: pkg.pkgPath,
2232 })
2233 if len(name) > maxNameLen {
2234 maxNameLen = len(name)
2235 }
2236 }
2237
2238 for i := range pkgs {
2239 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
2240 }
2241
Jamie Gennisc15544d2014-09-24 20:26:52 -07002242 sort.Sort(&pkgAssociationSorter{pkgs})
2243
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002244 params := map[string]interface{}{
2245 "Pkgs": pkgs,
2246 }
2247
2248 buf := bytes.NewBuffer(nil)
2249 err = headerTemplate.Execute(buf, params)
2250 if err != nil {
2251 return err
2252 }
2253
2254 return nw.Comment(buf.String())
2255}
2256
2257func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
2258 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
2259 c.requiredNinjaMicro)
2260
2261 err := nw.Assign("ninja_required_version", value)
2262 if err != nil {
2263 return err
2264 }
2265
2266 return nw.BlankLine()
2267}
2268
2269func (c *Context) writeBuildDir(nw *ninjaWriter) error {
2270 if c.buildDir != nil {
2271 err := nw.Assign("builddir", c.buildDir.Value(c.pkgNames))
2272 if err != nil {
2273 return err
2274 }
2275
2276 err = nw.BlankLine()
2277 if err != nil {
2278 return err
2279 }
2280 }
2281 return nil
2282}
2283
Jamie Gennisc15544d2014-09-24 20:26:52 -07002284type globalEntity interface {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002285 fullName(pkgNames map[*PackageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002286}
2287
Jamie Gennisc15544d2014-09-24 20:26:52 -07002288type globalEntitySorter struct {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002289 pkgNames map[*PackageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07002290 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002291}
2292
Jamie Gennisc15544d2014-09-24 20:26:52 -07002293func (s *globalEntitySorter) Len() int {
2294 return len(s.entities)
2295}
2296
2297func (s *globalEntitySorter) Less(i, j int) bool {
2298 iName := s.entities[i].fullName(s.pkgNames)
2299 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002300 return iName < jName
2301}
2302
Jamie Gennisc15544d2014-09-24 20:26:52 -07002303func (s *globalEntitySorter) Swap(i, j int) {
2304 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002305}
2306
2307func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
2308 visited := make(map[Variable]bool)
2309
2310 var walk func(v Variable) error
2311 walk = func(v Variable) error {
2312 visited[v] = true
2313
2314 // First visit variables on which this variable depends.
2315 value := c.globalVariables[v]
2316 for _, dep := range value.variables {
2317 if !visited[dep] {
2318 err := walk(dep)
2319 if err != nil {
2320 return err
2321 }
2322 }
2323 }
2324
2325 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
2326 if err != nil {
2327 return err
2328 }
2329
2330 err = nw.BlankLine()
2331 if err != nil {
2332 return err
2333 }
2334
2335 return nil
2336 }
2337
Jamie Gennisc15544d2014-09-24 20:26:52 -07002338 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
2339 for variable := range c.globalVariables {
2340 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002341 }
2342
Jamie Gennisc15544d2014-09-24 20:26:52 -07002343 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002344
Jamie Gennisc15544d2014-09-24 20:26:52 -07002345 for _, entity := range globalVariables {
2346 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002347 if !visited[v] {
2348 err := walk(v)
2349 if err != nil {
2350 return nil
2351 }
2352 }
2353 }
2354
2355 return nil
2356}
2357
2358func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002359 globalPools := make([]globalEntity, 0, len(c.globalPools))
2360 for pool := range c.globalPools {
2361 globalPools = append(globalPools, pool)
2362 }
2363
2364 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
2365
2366 for _, entity := range globalPools {
2367 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002368 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002369 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002370 err := def.WriteTo(nw, name)
2371 if err != nil {
2372 return err
2373 }
2374
2375 err = nw.BlankLine()
2376 if err != nil {
2377 return err
2378 }
2379 }
2380
2381 return nil
2382}
2383
2384func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002385 globalRules := make([]globalEntity, 0, len(c.globalRules))
2386 for rule := range c.globalRules {
2387 globalRules = append(globalRules, rule)
2388 }
2389
2390 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
2391
2392 for _, entity := range globalRules {
2393 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002394 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002395 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002396 err := def.WriteTo(nw, name, c.pkgNames)
2397 if err != nil {
2398 return err
2399 }
2400
2401 err = nw.BlankLine()
2402 if err != nil {
2403 return err
2404 }
2405 }
2406
2407 return nil
2408}
2409
Colin Crossab6d7902015-03-11 16:17:52 -07002410type moduleSorter []*moduleInfo
Jamie Gennis86179fe2014-06-11 16:27:16 -07002411
Colin Crossab6d7902015-03-11 16:17:52 -07002412func (s moduleSorter) Len() int {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002413 return len(s)
2414}
2415
Colin Crossab6d7902015-03-11 16:17:52 -07002416func (s moduleSorter) Less(i, j int) bool {
2417 iName := s[i].properties.Name
2418 jName := s[j].properties.Name
2419 if iName == jName {
Colin Cross65569e42015-03-10 20:08:19 -07002420 iName = s[i].variantName
2421 jName = s[j].variantName
Colin Crossab6d7902015-03-11 16:17:52 -07002422 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07002423 return iName < jName
2424}
2425
Colin Crossab6d7902015-03-11 16:17:52 -07002426func (s moduleSorter) Swap(i, j int) {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002427 s[i], s[j] = s[j], s[i]
2428}
2429
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002430func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
2431 headerTemplate := template.New("moduleHeader")
2432 _, err := headerTemplate.Parse(moduleHeaderTemplate)
2433 if err != nil {
2434 // This is a programming error.
2435 panic(err)
2436 }
2437
Colin Crossab6d7902015-03-11 16:17:52 -07002438 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
2439 for _, module := range c.moduleInfo {
2440 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07002441 }
Colin Crossab6d7902015-03-11 16:17:52 -07002442 sort.Sort(moduleSorter(modules))
Jamie Gennis86179fe2014-06-11 16:27:16 -07002443
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002444 buf := bytes.NewBuffer(nil)
2445
Colin Crossab6d7902015-03-11 16:17:52 -07002446 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002447 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
2448 continue
2449 }
2450
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002451 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002452
2453 // In order to make the bootstrap build manifest independent of the
2454 // build dir we need to output the Blueprints file locations in the
2455 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07002456 relPos := module.pos
2457 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002458
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002459 // Get the name and location of the factory function for the module.
Colin Crossab6d7902015-03-11 16:17:52 -07002460 factory := c.moduleFactories[module.typeName]
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002461 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2462 factoryName := factoryFunc.Name()
2463
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002464 infoMap := map[string]interface{}{
Colin Crossab6d7902015-03-11 16:17:52 -07002465 "properties": module.properties,
2466 "typeName": module.typeName,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002467 "goFactory": factoryName,
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002468 "pos": relPos,
Colin Cross65569e42015-03-10 20:08:19 -07002469 "variant": module.variantName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002470 }
2471 err = headerTemplate.Execute(buf, infoMap)
2472 if err != nil {
2473 return err
2474 }
2475
2476 err = nw.Comment(buf.String())
2477 if err != nil {
2478 return err
2479 }
2480
2481 err = nw.BlankLine()
2482 if err != nil {
2483 return err
2484 }
2485
Colin Crossab6d7902015-03-11 16:17:52 -07002486 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002487 if err != nil {
2488 return err
2489 }
2490
2491 err = nw.BlankLine()
2492 if err != nil {
2493 return err
2494 }
2495 }
2496
2497 return nil
2498}
2499
2500func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
2501 headerTemplate := template.New("singletonHeader")
2502 _, err := headerTemplate.Parse(singletonHeaderTemplate)
2503 if err != nil {
2504 // This is a programming error.
2505 panic(err)
2506 }
2507
2508 buf := bytes.NewBuffer(nil)
2509
Yuchen Wub9103ef2015-08-25 17:58:17 -07002510 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002511 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
2512 continue
2513 }
2514
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002515 // Get the name of the factory function for the module.
2516 factory := info.factory
2517 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2518 factoryName := factoryFunc.Name()
2519
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002520 buf.Reset()
2521 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07002522 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002523 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002524 }
2525 err = headerTemplate.Execute(buf, infoMap)
2526 if err != nil {
2527 return err
2528 }
2529
2530 err = nw.Comment(buf.String())
2531 if err != nil {
2532 return err
2533 }
2534
2535 err = nw.BlankLine()
2536 if err != nil {
2537 return err
2538 }
2539
2540 err = c.writeLocalBuildActions(nw, &info.actionDefs)
2541 if err != nil {
2542 return err
2543 }
2544
2545 err = nw.BlankLine()
2546 if err != nil {
2547 return err
2548 }
2549 }
2550
2551 return nil
2552}
2553
2554func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
2555 defs *localBuildActions) error {
2556
2557 // Write the local variable assignments.
2558 for _, v := range defs.variables {
2559 // A localVariable doesn't need the package names or config to
2560 // determine its name or value.
2561 name := v.fullName(nil)
2562 value, err := v.value(nil)
2563 if err != nil {
2564 panic(err)
2565 }
2566 err = nw.Assign(name, value.Value(c.pkgNames))
2567 if err != nil {
2568 return err
2569 }
2570 }
2571
2572 if len(defs.variables) > 0 {
2573 err := nw.BlankLine()
2574 if err != nil {
2575 return err
2576 }
2577 }
2578
2579 // Write the local rules.
2580 for _, r := range defs.rules {
2581 // A localRule doesn't need the package names or config to determine
2582 // its name or definition.
2583 name := r.fullName(nil)
2584 def, err := r.def(nil)
2585 if err != nil {
2586 panic(err)
2587 }
2588
2589 err = def.WriteTo(nw, name, c.pkgNames)
2590 if err != nil {
2591 return err
2592 }
2593
2594 err = nw.BlankLine()
2595 if err != nil {
2596 return err
2597 }
2598 }
2599
2600 // Write the build definitions.
2601 for _, buildDef := range defs.buildDefs {
2602 err := buildDef.WriteTo(nw, c.pkgNames)
2603 if err != nil {
2604 return err
2605 }
2606
2607 if len(buildDef.Args) > 0 {
2608 err = nw.BlankLine()
2609 if err != nil {
2610 return err
2611 }
2612 }
2613 }
2614
2615 return nil
2616}
2617
Colin Cross65569e42015-03-10 20:08:19 -07002618func beforeInModuleList(a, b *moduleInfo, list []*moduleInfo) bool {
2619 found := false
Colin Cross045a5972015-11-03 16:58:48 -08002620 if a == b {
2621 return false
2622 }
Colin Cross65569e42015-03-10 20:08:19 -07002623 for _, l := range list {
2624 if l == a {
2625 found = true
2626 } else if l == b {
2627 return found
2628 }
2629 }
2630
2631 missing := a
2632 if found {
2633 missing = b
2634 }
2635 panic(fmt.Errorf("element %v not found in list %v", missing, list))
2636}
2637
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002638var fileHeaderTemplate = `******************************************************************************
2639*** This file is generated and should not be edited ***
2640******************************************************************************
2641{{if .Pkgs}}
2642This file contains variables, rules, and pools with name prefixes indicating
2643they were generated by the following Go packages:
2644{{range .Pkgs}}
2645 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
2646
2647`
2648
2649var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2650Module: {{.properties.Name}}
Colin Crossab6d7902015-03-11 16:17:52 -07002651Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002652Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002653Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002654Defined: {{.pos}}
2655`
2656
2657var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2658Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002659Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002660`