blob: 1460b1b11903f4506767457891aa410e57378d3a [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 depsPos := module.propertyPos["deps"]
Colin Crossc9028482014-12-18 16:28:54 -08001116
Colin Crossed342d92015-03-11 00:57:25 -07001117 if depName == module.properties.Name {
Colin Crossc9028482014-12-18 16:28:54 -08001118 return []error{&Error{
1119 Err: fmt.Errorf("%q depends on itself", depName),
1120 Pos: depsPos,
1121 }}
1122 }
1123
1124 depInfo, ok := c.moduleGroups[depName]
1125 if !ok {
1126 return []error{&Error{
1127 Err: fmt.Errorf("%q depends on undefined module %q",
Colin Crossed342d92015-03-11 00:57:25 -07001128 module.properties.Name, depName),
Colin Crossc9028482014-12-18 16:28:54 -08001129 Pos: depsPos,
1130 }}
1131 }
1132
Colin Cross65569e42015-03-10 20:08:19 -07001133 for _, m := range module.directDeps {
1134 if m.group == depInfo {
1135 return nil
1136 }
Colin Crossc9028482014-12-18 16:28:54 -08001137 }
1138
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001139 if m := c.findMatchingVariant(module, depInfo); m != nil {
1140 module.directDeps = append(module.directDeps, m)
Colin Cross65569e42015-03-10 20:08:19 -07001141 return nil
Colin Cross65569e42015-03-10 20:08:19 -07001142 }
Colin Crossc9028482014-12-18 16:28:54 -08001143
Colin Cross65569e42015-03-10 20:08:19 -07001144 return []error{&Error{
1145 Err: fmt.Errorf("dependency %q of %q missing variant %q",
1146 depInfo.modules[0].properties.Name, module.properties.Name,
Colin Crossf5e34b92015-03-13 16:02:36 -07001147 c.prettyPrintVariant(module.dependencyVariant)),
Colin Cross65569e42015-03-10 20:08:19 -07001148 Pos: depsPos,
1149 }}
1150}
1151
Colin Cross8d8a7af2015-11-03 16:41:29 -08001152func (c *Context) findReverseDependency(module *moduleInfo, destName string) (*moduleInfo, []error) {
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001153 if destName == module.properties.Name {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001154 return nil, []error{&Error{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001155 Err: fmt.Errorf("%q depends on itself", destName),
1156 Pos: module.pos,
1157 }}
1158 }
1159
1160 destInfo, ok := c.moduleGroups[destName]
1161 if !ok {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001162 return nil, []error{&Error{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001163 Err: fmt.Errorf("%q has a reverse dependency on undefined module %q",
1164 module.properties.Name, destName),
1165 Pos: module.pos,
1166 }}
1167 }
1168
1169 if m := c.findMatchingVariant(module, destInfo); m != nil {
Colin Cross8d8a7af2015-11-03 16:41:29 -08001170 return m, nil
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001171 }
1172
Colin Cross8d8a7af2015-11-03 16:41:29 -08001173 return nil, []error{&Error{
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001174 Err: fmt.Errorf("reverse dependency %q of %q missing variant %q",
1175 destName, module.properties.Name,
1176 c.prettyPrintVariant(module.dependencyVariant)),
1177 Pos: module.pos,
1178 }}
1179}
1180
Colin Crossf5e34b92015-03-13 16:02:36 -07001181func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Colin Cross89486232015-05-08 11:14:54 -07001182 depName string, far bool) []error {
Colin Cross65569e42015-03-10 20:08:19 -07001183
1184 depsPos := module.propertyPos["deps"]
1185
1186 depInfo, ok := c.moduleGroups[depName]
1187 if !ok {
1188 return []error{&Error{
1189 Err: fmt.Errorf("%q depends on undefined module %q",
1190 module.properties.Name, depName),
1191 Pos: depsPos,
1192 }}
1193 }
1194
1195 // We can't just append variant.Variant to module.dependencyVariants.variantName and
1196 // compare the strings because the result won't be in mutator registration order.
1197 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001198 var newVariant variationMap
1199 if !far {
1200 newVariant = module.dependencyVariant.clone()
1201 } else {
1202 newVariant = make(variationMap)
1203 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001204 for _, v := range variations {
1205 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001206 }
1207
1208 for _, m := range depInfo.modules {
Colin Cross89486232015-05-08 11:14:54 -07001209 var found bool
1210 if far {
1211 found = m.variant.subset(newVariant)
1212 } else {
1213 found = m.variant.equal(newVariant)
1214 }
1215 if found {
Colin Crossf5e34b92015-03-13 16:02:36 -07001216 // AddVariationDependency allows adding a dependency on itself, but only if
Colin Cross65569e42015-03-10 20:08:19 -07001217 // that module is earlier in the module list than this one, since we always
Colin Crossf5e34b92015-03-13 16:02:36 -07001218 // run GenerateBuildActions in order for the variants of a module
Colin Cross65569e42015-03-10 20:08:19 -07001219 if depInfo == module.group && beforeInModuleList(module, m, module.group.modules) {
1220 return []error{&Error{
1221 Err: fmt.Errorf("%q depends on later version of itself", depName),
1222 Pos: depsPos,
1223 }}
1224 }
1225 module.directDeps = append(module.directDeps, m)
1226 return nil
1227 }
1228 }
1229
1230 return []error{&Error{
1231 Err: fmt.Errorf("dependency %q of %q missing variant %q",
1232 depInfo.modules[0].properties.Name, module.properties.Name,
Colin Crossf5e34b92015-03-13 16:02:36 -07001233 c.prettyPrintVariant(newVariant)),
Colin Cross65569e42015-03-10 20:08:19 -07001234 Pos: depsPos,
1235 }}
Colin Crossc9028482014-12-18 16:28:54 -08001236}
1237
Colin Cross7addea32015-03-11 15:43:52 -07001238func (c *Context) parallelVisitAllBottomUp(visit func(group *moduleInfo) bool) {
1239 doneCh := make(chan *moduleInfo)
Colin Cross691a60d2015-01-07 18:08:56 -08001240 count := 0
Colin Cross8900e9b2015-03-02 14:03:01 -08001241 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001242
Colin Cross7addea32015-03-11 15:43:52 -07001243 for _, module := range c.modulesSorted {
1244 module.waitingCount = module.depsCount
Colin Cross691a60d2015-01-07 18:08:56 -08001245 }
1246
Colin Cross7addea32015-03-11 15:43:52 -07001247 visitOne := func(module *moduleInfo) {
Colin Cross691a60d2015-01-07 18:08:56 -08001248 count++
1249 go func() {
Colin Cross7addea32015-03-11 15:43:52 -07001250 ret := visit(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08001251 if ret {
1252 cancel = true
1253 }
Colin Cross7addea32015-03-11 15:43:52 -07001254 doneCh <- module
Colin Cross691a60d2015-01-07 18:08:56 -08001255 }()
1256 }
1257
Colin Cross7addea32015-03-11 15:43:52 -07001258 for _, module := range c.modulesSorted {
1259 if module.waitingCount == 0 {
1260 visitOne(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001261 }
1262 }
1263
Colin Cross11e3b0d2015-02-04 10:41:00 -08001264 for count > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08001265 select {
Colin Cross7addea32015-03-11 15:43:52 -07001266 case doneModule := <-doneCh:
Colin Cross8900e9b2015-03-02 14:03:01 -08001267 if !cancel {
Colin Cross7addea32015-03-11 15:43:52 -07001268 for _, parent := range doneModule.reverseDeps {
Colin Cross8900e9b2015-03-02 14:03:01 -08001269 parent.waitingCount--
1270 if parent.waitingCount == 0 {
1271 visitOne(parent)
1272 }
Colin Cross691a60d2015-01-07 18:08:56 -08001273 }
1274 }
1275 count--
Colin Cross691a60d2015-01-07 18:08:56 -08001276 }
1277 }
1278}
1279
1280// updateDependencies recursively walks the module dependency graph and updates
1281// additional fields based on the dependencies. It builds a sorted list of modules
1282// such that dependencies of a module always appear first, and populates reverse
1283// dependency links and counts of total dependencies. It also reports errors when
1284// it encounters dependency cycles. This should called after resolveDependencies,
1285// as well as after any mutator pass has called addDependency
1286func (c *Context) updateDependencies() (errs []error) {
Colin Cross7addea32015-03-11 15:43:52 -07001287 visited := make(map[*moduleInfo]bool) // modules that were already checked
1288 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001289
Colin Cross7addea32015-03-11 15:43:52 -07001290 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08001291
Colin Cross7addea32015-03-11 15:43:52 -07001292 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001293
Colin Cross7addea32015-03-11 15:43:52 -07001294 cycleError := func(cycle []*moduleInfo) {
Colin Cross10b54db2015-03-11 14:40:30 -07001295 // We are the "start" of the cycle, so we're responsible
1296 // for generating the errors. The cycle list is in
1297 // reverse order because all the 'check' calls append
1298 // their own module to the list.
1299 errs = append(errs, &Error{
1300 Err: fmt.Errorf("encountered dependency cycle:"),
Colin Cross7addea32015-03-11 15:43:52 -07001301 Pos: cycle[len(cycle)-1].pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001302 })
1303
1304 // Iterate backwards through the cycle list.
Colin Cross0e4607e2015-03-24 16:42:56 -07001305 curModule := cycle[0]
Colin Cross10b54db2015-03-11 14:40:30 -07001306 for i := len(cycle) - 1; i >= 0; i-- {
Colin Cross7addea32015-03-11 15:43:52 -07001307 nextModule := cycle[i]
Colin Cross10b54db2015-03-11 14:40:30 -07001308 errs = append(errs, &Error{
1309 Err: fmt.Errorf(" %q depends on %q",
Colin Cross7addea32015-03-11 15:43:52 -07001310 curModule.properties.Name,
1311 nextModule.properties.Name),
1312 Pos: curModule.propertyPos["deps"],
Colin Cross10b54db2015-03-11 14:40:30 -07001313 })
Colin Cross7addea32015-03-11 15:43:52 -07001314 curModule = nextModule
Colin Cross10b54db2015-03-11 14:40:30 -07001315 }
1316 }
1317
Colin Cross7addea32015-03-11 15:43:52 -07001318 check = func(module *moduleInfo) []*moduleInfo {
1319 visited[module] = true
1320 checking[module] = true
1321 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001322
Colin Cross7addea32015-03-11 15:43:52 -07001323 deps := make(map[*moduleInfo]bool)
1324
1325 // Add an implicit dependency ordering on all earlier modules in the same module group
1326 for _, dep := range module.group.modules {
1327 if dep == module {
1328 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08001329 }
Colin Cross7addea32015-03-11 15:43:52 -07001330 deps[dep] = true
Colin Crossbbfa51a2014-12-17 16:12:41 -08001331 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001332
Colin Cross7addea32015-03-11 15:43:52 -07001333 for _, dep := range module.directDeps {
1334 deps[dep] = true
1335 }
1336
1337 module.reverseDeps = []*moduleInfo{}
1338 module.depsCount = len(deps)
Colin Cross691a60d2015-01-07 18:08:56 -08001339
Colin Crossbbfa51a2014-12-17 16:12:41 -08001340 for dep := range deps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001341 if checking[dep] {
1342 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07001343 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001344 }
1345
1346 if !visited[dep] {
1347 cycle := check(dep)
1348 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001349 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001350 // We are the "start" of the cycle, so we're responsible
1351 // for generating the errors. The cycle list is in
1352 // reverse order because all the 'check' calls append
1353 // their own module to the list.
Colin Cross10b54db2015-03-11 14:40:30 -07001354 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001355
1356 // We can continue processing this module's children to
1357 // find more cycles. Since all the modules that were
1358 // part of the found cycle were marked as visited we
1359 // won't run into that cycle again.
1360 } else {
1361 // We're not the "start" of the cycle, so we just append
1362 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07001363 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001364 }
1365 }
1366 }
Colin Cross691a60d2015-01-07 18:08:56 -08001367
Colin Cross7addea32015-03-11 15:43:52 -07001368 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001369 }
1370
Colin Cross7addea32015-03-11 15:43:52 -07001371 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08001372
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001373 return nil
1374 }
1375
Colin Cross7addea32015-03-11 15:43:52 -07001376 for _, module := range c.moduleInfo {
1377 if !visited[module] {
1378 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001379 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001380 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07001381 panic("inconceivable!")
1382 }
1383 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001384 }
1385 }
1386 }
1387
Colin Cross7addea32015-03-11 15:43:52 -07001388 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08001389
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001390 return
1391}
1392
Jamie Gennisd4e10182014-06-12 20:06:50 -07001393// PrepareBuildActions generates an internal representation of all the build
1394// actions that need to be performed. This process involves invoking the
1395// GenerateBuildActions method on each of the Module objects created during the
1396// parse phase and then on each of the registered Singleton objects.
1397//
1398// If the ResolveDependencies method has not already been called it is called
1399// automatically by this method.
1400//
1401// The config argument is made available to all of the Module and Singleton
1402// objects via the Config method on the ModuleContext and SingletonContext
1403// objects passed to GenerateBuildActions. It is also passed to the functions
1404// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
1405// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001406//
1407// The returned deps is a list of the ninja files dependencies that were added
1408// by the modules and singletons via the ModuleContext.AddNinjaFileDeps() and
1409// SingletonContext.AddNinjaFileDeps() methods.
1410func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001411 c.buildActionsReady = false
1412
1413 if !c.dependenciesReady {
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001414 errs := c.ResolveDependencies(config)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001415 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001416 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001417 }
1418 }
1419
1420 liveGlobals := newLiveTracker(config)
1421
1422 c.initSpecialVariables()
1423
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001424 depsModules, errs := c.generateModuleBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001425 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001426 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001427 }
1428
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001429 depsSingletons, errs := c.generateSingletonBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001430 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001431 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001432 }
1433
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001434 deps = append(depsModules, depsSingletons...)
1435
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001436 if c.buildDir != nil {
1437 liveGlobals.addNinjaStringDeps(c.buildDir)
1438 }
1439
1440 pkgNames := c.makeUniquePackageNames(liveGlobals)
1441
1442 // This will panic if it finds a problem since it's a programming error.
1443 c.checkForVariableReferenceCycles(liveGlobals.variables, pkgNames)
1444
1445 c.pkgNames = pkgNames
1446 c.globalVariables = liveGlobals.variables
1447 c.globalPools = liveGlobals.pools
1448 c.globalRules = liveGlobals.rules
1449
1450 c.buildActionsReady = true
1451
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001452 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001453}
1454
Colin Cross65569e42015-03-10 20:08:19 -07001455func (c *Context) runEarlyMutators(config interface{}) (errs []error) {
1456 for _, mutator := range c.earlyMutatorInfo {
1457 for _, group := range c.moduleGroups {
1458 newModules := make([]*moduleInfo, 0, len(group.modules))
1459
1460 for _, module := range group.modules {
1461 mctx := &mutatorContext{
1462 baseModuleContext: baseModuleContext{
1463 context: c,
1464 config: config,
1465 module: module,
1466 },
1467 name: mutator.name,
1468 }
1469 mutator.mutator(mctx)
1470 if len(mctx.errs) > 0 {
1471 errs = append(errs, mctx.errs...)
1472 return errs
1473 }
1474
1475 if module.splitModules != nil {
1476 newModules = append(newModules, module.splitModules...)
1477 } else {
1478 newModules = append(newModules, module)
1479 }
1480 }
1481
1482 group.modules = newModules
1483 }
1484 }
1485
Colin Cross763b6f12015-10-29 15:32:56 -07001486 errs = c.updateDependencies()
1487 if len(errs) > 0 {
1488 return errs
1489 }
1490
Colin Cross65569e42015-03-10 20:08:19 -07001491 return nil
1492}
1493
Colin Crossc9028482014-12-18 16:28:54 -08001494func (c *Context) runMutators(config interface{}) (errs []error) {
Colin Cross763b6f12015-10-29 15:32:56 -07001495 errs = c.runEarlyMutators(config)
1496 if len(errs) > 0 {
1497 return errs
1498 }
1499
Colin Crossc9028482014-12-18 16:28:54 -08001500 for _, mutator := range c.mutatorInfo {
1501 if mutator.topDownMutator != nil {
1502 errs = c.runTopDownMutator(config, mutator.name, mutator.topDownMutator)
1503 } else if mutator.bottomUpMutator != nil {
1504 errs = c.runBottomUpMutator(config, mutator.name, mutator.bottomUpMutator)
1505 } else {
1506 panic("no mutator set on " + mutator.name)
1507 }
1508 if len(errs) > 0 {
1509 return errs
1510 }
1511 }
1512
1513 return nil
1514}
1515
1516func (c *Context) runTopDownMutator(config interface{},
1517 name string, mutator TopDownMutator) (errs []error) {
1518
Colin Cross7addea32015-03-11 15:43:52 -07001519 for i := 0; i < len(c.modulesSorted); i++ {
1520 module := c.modulesSorted[len(c.modulesSorted)-1-i]
1521 mctx := &mutatorContext{
1522 baseModuleContext: baseModuleContext{
1523 context: c,
1524 config: config,
1525 module: module,
1526 },
1527 name: name,
1528 }
Colin Crossc9028482014-12-18 16:28:54 -08001529
Colin Cross7addea32015-03-11 15:43:52 -07001530 mutator(mctx)
1531 if len(mctx.errs) > 0 {
1532 errs = append(errs, mctx.errs...)
1533 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001534 }
1535 }
1536
1537 return errs
1538}
1539
1540func (c *Context) runBottomUpMutator(config interface{},
1541 name string, mutator BottomUpMutator) (errs []error) {
1542
Colin Cross8d8a7af2015-11-03 16:41:29 -08001543 reverseDeps := make(map[*moduleInfo][]*moduleInfo)
1544
Colin Cross7addea32015-03-11 15:43:52 -07001545 for _, module := range c.modulesSorted {
1546 newModules := make([]*moduleInfo, 0, 1)
Colin Crossc9028482014-12-18 16:28:54 -08001547
Jamie Gennisc7988252015-04-14 23:28:10 -04001548 if module.splitModules != nil {
1549 panic("split module found in sorted module list")
1550 }
1551
Colin Cross7addea32015-03-11 15:43:52 -07001552 mctx := &mutatorContext{
1553 baseModuleContext: baseModuleContext{
1554 context: c,
1555 config: config,
1556 module: module,
1557 },
Colin Cross8d8a7af2015-11-03 16:41:29 -08001558 name: name,
1559 reverseDeps: reverseDeps,
Colin Cross7addea32015-03-11 15:43:52 -07001560 }
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
Colin Cross8d8a7af2015-11-03 16:41:29 -08001585 for module, deps := range reverseDeps {
1586 sort.Sort(moduleSorter(deps))
1587 module.directDeps = append(module.directDeps, deps...)
1588 }
1589
Jamie Gennisc7988252015-04-14 23:28:10 -04001590 errs = c.updateDependencies()
1591 if len(errs) > 0 {
1592 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001593 }
1594
1595 return errs
1596}
1597
Colin Cross7addea32015-03-11 15:43:52 -07001598func spliceModules(modules []*moduleInfo, origModule *moduleInfo,
1599 newModules []*moduleInfo) []*moduleInfo {
1600 for i, m := range modules {
1601 if m == origModule {
1602 return spliceModulesAtIndex(modules, i, newModules)
1603 }
1604 }
1605
1606 panic("failed to find original module to splice")
1607}
1608
1609func spliceModulesAtIndex(modules []*moduleInfo, i int, newModules []*moduleInfo) []*moduleInfo {
1610 spliceSize := len(newModules)
1611 newLen := len(modules) + spliceSize - 1
1612 var dest []*moduleInfo
1613 if cap(modules) >= len(modules)-1+len(newModules) {
1614 // We can fit the splice in the existing capacity, do everything in place
1615 dest = modules[:newLen]
1616 } else {
1617 dest = make([]*moduleInfo, newLen)
1618 copy(dest, modules[:i])
1619 }
1620
1621 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07001622 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07001623
1624 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07001625 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07001626
Colin Cross72bd1932015-03-16 00:13:59 -07001627 return dest
Colin Cross7addea32015-03-11 15:43:52 -07001628}
1629
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001630func (c *Context) initSpecialVariables() {
1631 c.buildDir = nil
1632 c.requiredNinjaMajor = 1
Dan Willemsen21b6f372015-07-22 12:58:01 -07001633 c.requiredNinjaMinor = 6
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001634 c.requiredNinjaMicro = 0
1635}
1636
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001637func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001638 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001639
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001640 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001641 var errs []error
1642
Colin Cross691a60d2015-01-07 18:08:56 -08001643 cancelCh := make(chan struct{})
1644 errsCh := make(chan []error)
1645 depsCh := make(chan []string)
1646
1647 go func() {
1648 for {
1649 select {
1650 case <-cancelCh:
1651 close(cancelCh)
1652 return
1653 case newErrs := <-errsCh:
1654 errs = append(errs, newErrs...)
1655 case newDeps := <-depsCh:
1656 deps = append(deps, newDeps...)
1657
1658 }
1659 }
1660 }()
1661
Colin Cross7addea32015-03-11 15:43:52 -07001662 c.parallelVisitAllBottomUp(func(module *moduleInfo) bool {
1663 // The parent scope of the moduleContext's local scope gets overridden to be that of the
1664 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1665 // just set it to nil.
1666 prefix := moduleNamespacePrefix(module.group.ninjaName + "_" + module.variantName)
1667 scope := newLocalScope(nil, prefix)
Colin Cross6134a5c2015-02-10 11:26:26 -08001668
Colin Cross7addea32015-03-11 15:43:52 -07001669 mctx := &moduleContext{
1670 baseModuleContext: baseModuleContext{
1671 context: c,
1672 config: config,
1673 module: module,
1674 },
1675 scope: scope,
1676 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001677
Colin Cross7addea32015-03-11 15:43:52 -07001678 mctx.module.logicModule.GenerateBuildActions(mctx)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001679
Colin Cross7addea32015-03-11 15:43:52 -07001680 if len(mctx.errs) > 0 {
1681 errsCh <- mctx.errs
1682 return true
1683 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001684
Colin Cross7addea32015-03-11 15:43:52 -07001685 depsCh <- mctx.ninjaFileDeps
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001686
Colin Crossab6d7902015-03-11 16:17:52 -07001687 newErrs := c.processLocalBuildActions(&module.actionDefs,
Colin Cross7addea32015-03-11 15:43:52 -07001688 &mctx.actionDefs, liveGlobals)
1689 if len(newErrs) > 0 {
1690 errsCh <- newErrs
1691 return true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001692 }
Colin Cross8900e9b2015-03-02 14:03:01 -08001693 return false
Colin Cross691a60d2015-01-07 18:08:56 -08001694 })
1695
1696 cancelCh <- struct{}{}
1697 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001698
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001699 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001700}
1701
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001702func (c *Context) generateSingletonBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001703 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001704
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001705 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001706 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001707
Yuchen Wub9103ef2015-08-25 17:58:17 -07001708 for _, info := range c.singletonInfo {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001709 // The parent scope of the singletonContext's local scope gets overridden to be that of the
1710 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1711 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07001712 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001713
1714 sctx := &singletonContext{
1715 context: c,
1716 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001717 scope: scope,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001718 }
1719
1720 info.singleton.GenerateBuildActions(sctx)
1721
1722 if len(sctx.errs) > 0 {
1723 errs = append(errs, sctx.errs...)
1724 if len(errs) > maxErrors {
1725 break
1726 }
1727 continue
1728 }
1729
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001730 deps = append(deps, sctx.ninjaFileDeps...)
1731
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001732 newErrs := c.processLocalBuildActions(&info.actionDefs,
1733 &sctx.actionDefs, liveGlobals)
1734 errs = append(errs, newErrs...)
1735 if len(errs) > maxErrors {
1736 break
1737 }
1738 }
1739
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001740 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001741}
1742
1743func (c *Context) processLocalBuildActions(out, in *localBuildActions,
1744 liveGlobals *liveTracker) []error {
1745
1746 var errs []error
1747
1748 // First we go through and add everything referenced by the module's
1749 // buildDefs to the live globals set. This will end up adding the live
1750 // locals to the set as well, but we'll take them out after.
1751 for _, def := range in.buildDefs {
1752 err := liveGlobals.AddBuildDefDeps(def)
1753 if err != nil {
1754 errs = append(errs, err)
1755 }
1756 }
1757
1758 if len(errs) > 0 {
1759 return errs
1760 }
1761
Colin Crossc9028482014-12-18 16:28:54 -08001762 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001763
1764 // We use the now-incorrect set of live "globals" to determine which local
1765 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08001766 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001767 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07001768 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001769 if isLive {
1770 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001771 }
1772 }
1773
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001774 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07001775 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001776 if isLive {
1777 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001778 }
1779 }
1780
1781 return nil
1782}
1783
Yuchen Wu222e2452015-10-06 14:03:27 -07001784func (c *Context) walkDeps(topModule *moduleInfo,
1785 visit func(Module, Module) bool) {
1786
1787 visited := make(map[*moduleInfo]bool)
1788
1789 var walk func(module *moduleInfo)
1790 walk = func(module *moduleInfo) {
1791 visited[module] = true
1792
1793 for _, moduleDep := range module.directDeps {
1794 if !visited[moduleDep] {
1795 if visit(moduleDep.logicModule, module.logicModule) {
1796 walk(moduleDep)
1797 }
1798 }
1799 }
1800 }
1801
1802 walk(topModule)
1803}
1804
Colin Crossbbfa51a2014-12-17 16:12:41 -08001805func (c *Context) visitDepsDepthFirst(topModule *moduleInfo, visit func(Module)) {
1806 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001807
Colin Crossbbfa51a2014-12-17 16:12:41 -08001808 var walk func(module *moduleInfo)
1809 walk = func(module *moduleInfo) {
1810 visited[module] = true
1811 for _, moduleDep := range module.directDeps {
1812 if !visited[moduleDep] {
1813 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001814 }
1815 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001816
Colin Crossbbfa51a2014-12-17 16:12:41 -08001817 if module != topModule {
1818 visit(module.logicModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001819 }
1820 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001821
1822 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001823}
1824
Colin Crossbbfa51a2014-12-17 16:12:41 -08001825func (c *Context) visitDepsDepthFirstIf(topModule *moduleInfo, pred func(Module) bool,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001826 visit func(Module)) {
1827
Colin Crossbbfa51a2014-12-17 16:12:41 -08001828 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001829
Colin Crossbbfa51a2014-12-17 16:12:41 -08001830 var walk func(module *moduleInfo)
1831 walk = func(module *moduleInfo) {
1832 visited[module] = true
1833 for _, moduleDep := range module.directDeps {
1834 if !visited[moduleDep] {
1835 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001836 }
Jamie Gennis0bb5d8a2014-11-26 14:45:37 -08001837 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001838
1839 if module != topModule {
1840 if pred(module.logicModule) {
1841 visit(module.logicModule)
1842 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001843 }
1844 }
1845
Colin Crossbbfa51a2014-12-17 16:12:41 -08001846 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001847}
1848
Colin Crossc9028482014-12-18 16:28:54 -08001849func (c *Context) visitDirectDeps(module *moduleInfo, visit func(Module)) {
1850 for _, dep := range module.directDeps {
1851 visit(dep.logicModule)
1852 }
1853}
1854
1855func (c *Context) visitDirectDepsIf(module *moduleInfo, pred func(Module) bool,
1856 visit func(Module)) {
1857
1858 for _, dep := range module.directDeps {
1859 if pred(dep.logicModule) {
1860 visit(dep.logicModule)
1861 }
1862 }
1863}
1864
Jamie Gennisc15544d2014-09-24 20:26:52 -07001865func (c *Context) sortedModuleNames() []string {
1866 if c.cachedSortedModuleNames == nil {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001867 c.cachedSortedModuleNames = make([]string, 0, len(c.moduleGroups))
1868 for moduleName := range c.moduleGroups {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001869 c.cachedSortedModuleNames = append(c.cachedSortedModuleNames,
1870 moduleName)
1871 }
1872 sort.Strings(c.cachedSortedModuleNames)
1873 }
1874
1875 return c.cachedSortedModuleNames
1876}
1877
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001878func (c *Context) visitAllModules(visit func(Module)) {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001879 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001880 group := c.moduleGroups[moduleName]
1881 for _, module := range group.modules {
1882 visit(module.logicModule)
1883 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001884 }
1885}
1886
1887func (c *Context) visitAllModulesIf(pred func(Module) bool,
1888 visit func(Module)) {
1889
Jamie Gennisc15544d2014-09-24 20:26:52 -07001890 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001891 group := c.moduleGroups[moduleName]
1892 for _, module := range group.modules {
1893 if pred(module.logicModule) {
1894 visit(module.logicModule)
1895 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001896 }
1897 }
1898}
1899
1900func (c *Context) requireNinjaVersion(major, minor, micro int) {
1901 if major != 1 {
1902 panic("ninja version with major version != 1 not supported")
1903 }
1904 if c.requiredNinjaMinor < minor {
1905 c.requiredNinjaMinor = minor
1906 c.requiredNinjaMicro = micro
1907 }
1908 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
1909 c.requiredNinjaMicro = micro
1910 }
1911}
1912
1913func (c *Context) setBuildDir(value *ninjaString) {
1914 if c.buildDir != nil {
1915 panic("buildDir set multiple times")
1916 }
1917 c.buildDir = value
1918}
1919
1920func (c *Context) makeUniquePackageNames(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001921 liveGlobals *liveTracker) map[*PackageContext]string {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001922
Jamie Gennis2fb20952014-10-03 02:49:58 -07001923 pkgs := make(map[string]*PackageContext)
1924 pkgNames := make(map[*PackageContext]string)
1925 longPkgNames := make(map[*PackageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001926
Jamie Gennis2fb20952014-10-03 02:49:58 -07001927 processPackage := func(pctx *PackageContext) {
1928 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001929 // This is a built-in rule and has no package.
1930 return
1931 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07001932 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001933 // We've already processed this package.
1934 return
1935 }
1936
Jamie Gennis2fb20952014-10-03 02:49:58 -07001937 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001938 if present {
1939 // Short name collision. Both this package and the one that's
1940 // already there need to use their full names. We leave the short
1941 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001942 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001943 longPkgNames[otherPkg] = true
1944 } else {
1945 // No collision so far. Tentatively set the package's name to be
1946 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001947 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07001948 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001949 }
1950 }
1951
1952 // We try to give all packages their short name, but when we get collisions
1953 // we need to use the full unique package name.
1954 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001955 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001956 }
1957 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001958 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001959 }
1960 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001961 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001962 }
1963
1964 // Add the packages that had collisions using their full unique names. This
1965 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001966 for pctx := range longPkgNames {
1967 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001968 }
1969
1970 return pkgNames
1971}
1972
1973func (c *Context) checkForVariableReferenceCycles(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001974 variables map[Variable]*ninjaString, pkgNames map[*PackageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001975
1976 visited := make(map[Variable]bool) // variables that were already checked
1977 checking := make(map[Variable]bool) // variables actively being checked
1978
1979 var check func(v Variable) []Variable
1980
1981 check = func(v Variable) []Variable {
1982 visited[v] = true
1983 checking[v] = true
1984 defer delete(checking, v)
1985
1986 value := variables[v]
1987 for _, dep := range value.variables {
1988 if checking[dep] {
1989 // This is a cycle.
1990 return []Variable{dep, v}
1991 }
1992
1993 if !visited[dep] {
1994 cycle := check(dep)
1995 if cycle != nil {
1996 if cycle[0] == v {
1997 // We are the "start" of the cycle, so we're responsible
1998 // for generating the errors. The cycle list is in
1999 // reverse order because all the 'check' calls append
2000 // their own module to the list.
2001 msgs := []string{"detected variable reference cycle:"}
2002
2003 // Iterate backwards through the cycle list.
2004 curName := v.fullName(pkgNames)
2005 curValue := value.Value(pkgNames)
2006 for i := len(cycle) - 1; i >= 0; i-- {
2007 next := cycle[i]
2008 nextName := next.fullName(pkgNames)
2009 nextValue := variables[next].Value(pkgNames)
2010
2011 msgs = append(msgs, fmt.Sprintf(
2012 " %q depends on %q", curName, nextName))
2013 msgs = append(msgs, fmt.Sprintf(
2014 " [%s = %s]", curName, curValue))
2015
2016 curName = nextName
2017 curValue = nextValue
2018 }
2019
2020 // Variable reference cycles are a programming error,
2021 // not the fault of the Blueprint file authors.
2022 panic(strings.Join(msgs, "\n"))
2023 } else {
2024 // We're not the "start" of the cycle, so we just append
2025 // our module to the list and return it.
2026 return append(cycle, v)
2027 }
2028 }
2029 }
2030 }
2031
2032 return nil
2033 }
2034
2035 for v := range variables {
2036 if !visited[v] {
2037 cycle := check(v)
2038 if cycle != nil {
2039 panic("inconceivable!")
2040 }
2041 }
2042 }
2043}
2044
Jamie Gennisaf435562014-10-27 22:34:56 -07002045// AllTargets returns a map all the build target names to the rule used to build
2046// them. This is the same information that is output by running 'ninja -t
2047// targets all'. If this is called before PrepareBuildActions successfully
2048// completes then ErrbuildActionsNotReady is returned.
2049func (c *Context) AllTargets() (map[string]string, error) {
2050 if !c.buildActionsReady {
2051 return nil, ErrBuildActionsNotReady
2052 }
2053
2054 targets := map[string]string{}
2055
2056 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07002057 for _, module := range c.moduleInfo {
2058 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07002059 ruleName := buildDef.Rule.fullName(c.pkgNames)
2060 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002061 outputValue, err := output.Eval(c.globalVariables)
2062 if err != nil {
2063 return nil, err
2064 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002065 targets[outputValue] = ruleName
2066 }
2067 }
2068 }
2069
2070 // Collect all the singleton build targets.
2071 for _, info := range c.singletonInfo {
2072 for _, buildDef := range info.actionDefs.buildDefs {
2073 ruleName := buildDef.Rule.fullName(c.pkgNames)
2074 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002075 outputValue, err := output.Eval(c.globalVariables)
2076 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08002077 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08002078 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002079 targets[outputValue] = ruleName
2080 }
2081 }
2082 }
2083
2084 return targets, nil
2085}
2086
Colin Cross4572edd2015-05-13 14:36:24 -07002087// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
2088// property structs returned by the factory for that module type.
2089func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
2090 ret := make(map[string][]interface{})
2091 for moduleType, factory := range c.moduleFactories {
2092 _, ret[moduleType] = factory()
2093 }
2094
2095 return ret
2096}
2097
2098func (c *Context) ModuleName(logicModule Module) string {
2099 module := c.moduleInfo[logicModule]
2100 return module.properties.Name
2101}
2102
2103func (c *Context) ModuleDir(logicModule Module) string {
2104 module := c.moduleInfo[logicModule]
2105 return filepath.Dir(module.relBlueprintsFile)
2106}
2107
2108func (c *Context) BlueprintFile(logicModule Module) string {
2109 module := c.moduleInfo[logicModule]
2110 return module.relBlueprintsFile
2111}
2112
2113func (c *Context) ModuleErrorf(logicModule Module, format string,
2114 args ...interface{}) error {
2115
2116 module := c.moduleInfo[logicModule]
2117 return &Error{
2118 Err: fmt.Errorf(format, args...),
2119 Pos: module.pos,
2120 }
2121}
2122
2123func (c *Context) VisitAllModules(visit func(Module)) {
2124 c.visitAllModules(visit)
2125}
2126
2127func (c *Context) VisitAllModulesIf(pred func(Module) bool,
2128 visit func(Module)) {
2129
2130 c.visitAllModulesIf(pred, visit)
2131}
2132
2133func (c *Context) VisitDepsDepthFirst(module Module,
2134 visit func(Module)) {
2135
2136 c.visitDepsDepthFirst(c.moduleInfo[module], visit)
2137}
2138
2139func (c *Context) VisitDepsDepthFirstIf(module Module,
2140 pred func(Module) bool, visit func(Module)) {
2141
2142 c.visitDepsDepthFirstIf(c.moduleInfo[module], pred, visit)
2143}
2144
Jamie Gennisd4e10182014-06-12 20:06:50 -07002145// WriteBuildFile writes the Ninja manifeset text for the generated build
2146// actions to w. If this is called before PrepareBuildActions successfully
2147// completes then ErrBuildActionsNotReady is returned.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002148func (c *Context) WriteBuildFile(w io.Writer) error {
2149 if !c.buildActionsReady {
2150 return ErrBuildActionsNotReady
2151 }
2152
2153 nw := newNinjaWriter(w)
2154
2155 err := c.writeBuildFileHeader(nw)
2156 if err != nil {
2157 return err
2158 }
2159
2160 err = c.writeNinjaRequiredVersion(nw)
2161 if err != nil {
2162 return err
2163 }
2164
2165 // TODO: Group the globals by package.
2166
2167 err = c.writeGlobalVariables(nw)
2168 if err != nil {
2169 return err
2170 }
2171
2172 err = c.writeGlobalPools(nw)
2173 if err != nil {
2174 return err
2175 }
2176
2177 err = c.writeBuildDir(nw)
2178 if err != nil {
2179 return err
2180 }
2181
2182 err = c.writeGlobalRules(nw)
2183 if err != nil {
2184 return err
2185 }
2186
2187 err = c.writeAllModuleActions(nw)
2188 if err != nil {
2189 return err
2190 }
2191
2192 err = c.writeAllSingletonActions(nw)
2193 if err != nil {
2194 return err
2195 }
2196
2197 return nil
2198}
2199
Jamie Gennisc15544d2014-09-24 20:26:52 -07002200type pkgAssociation struct {
2201 PkgName string
2202 PkgPath string
2203}
2204
2205type pkgAssociationSorter struct {
2206 pkgs []pkgAssociation
2207}
2208
2209func (s *pkgAssociationSorter) Len() int {
2210 return len(s.pkgs)
2211}
2212
2213func (s *pkgAssociationSorter) Less(i, j int) bool {
2214 iName := s.pkgs[i].PkgName
2215 jName := s.pkgs[j].PkgName
2216 return iName < jName
2217}
2218
2219func (s *pkgAssociationSorter) Swap(i, j int) {
2220 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
2221}
2222
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002223func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
2224 headerTemplate := template.New("fileHeader")
2225 _, err := headerTemplate.Parse(fileHeaderTemplate)
2226 if err != nil {
2227 // This is a programming error.
2228 panic(err)
2229 }
2230
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002231 var pkgs []pkgAssociation
2232 maxNameLen := 0
2233 for pkg, name := range c.pkgNames {
2234 pkgs = append(pkgs, pkgAssociation{
2235 PkgName: name,
2236 PkgPath: pkg.pkgPath,
2237 })
2238 if len(name) > maxNameLen {
2239 maxNameLen = len(name)
2240 }
2241 }
2242
2243 for i := range pkgs {
2244 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
2245 }
2246
Jamie Gennisc15544d2014-09-24 20:26:52 -07002247 sort.Sort(&pkgAssociationSorter{pkgs})
2248
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002249 params := map[string]interface{}{
2250 "Pkgs": pkgs,
2251 }
2252
2253 buf := bytes.NewBuffer(nil)
2254 err = headerTemplate.Execute(buf, params)
2255 if err != nil {
2256 return err
2257 }
2258
2259 return nw.Comment(buf.String())
2260}
2261
2262func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
2263 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
2264 c.requiredNinjaMicro)
2265
2266 err := nw.Assign("ninja_required_version", value)
2267 if err != nil {
2268 return err
2269 }
2270
2271 return nw.BlankLine()
2272}
2273
2274func (c *Context) writeBuildDir(nw *ninjaWriter) error {
2275 if c.buildDir != nil {
2276 err := nw.Assign("builddir", c.buildDir.Value(c.pkgNames))
2277 if err != nil {
2278 return err
2279 }
2280
2281 err = nw.BlankLine()
2282 if err != nil {
2283 return err
2284 }
2285 }
2286 return nil
2287}
2288
Jamie Gennisc15544d2014-09-24 20:26:52 -07002289type globalEntity interface {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002290 fullName(pkgNames map[*PackageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002291}
2292
Jamie Gennisc15544d2014-09-24 20:26:52 -07002293type globalEntitySorter struct {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002294 pkgNames map[*PackageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07002295 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002296}
2297
Jamie Gennisc15544d2014-09-24 20:26:52 -07002298func (s *globalEntitySorter) Len() int {
2299 return len(s.entities)
2300}
2301
2302func (s *globalEntitySorter) Less(i, j int) bool {
2303 iName := s.entities[i].fullName(s.pkgNames)
2304 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002305 return iName < jName
2306}
2307
Jamie Gennisc15544d2014-09-24 20:26:52 -07002308func (s *globalEntitySorter) Swap(i, j int) {
2309 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002310}
2311
2312func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
2313 visited := make(map[Variable]bool)
2314
2315 var walk func(v Variable) error
2316 walk = func(v Variable) error {
2317 visited[v] = true
2318
2319 // First visit variables on which this variable depends.
2320 value := c.globalVariables[v]
2321 for _, dep := range value.variables {
2322 if !visited[dep] {
2323 err := walk(dep)
2324 if err != nil {
2325 return err
2326 }
2327 }
2328 }
2329
2330 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
2331 if err != nil {
2332 return err
2333 }
2334
2335 err = nw.BlankLine()
2336 if err != nil {
2337 return err
2338 }
2339
2340 return nil
2341 }
2342
Jamie Gennisc15544d2014-09-24 20:26:52 -07002343 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
2344 for variable := range c.globalVariables {
2345 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002346 }
2347
Jamie Gennisc15544d2014-09-24 20:26:52 -07002348 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002349
Jamie Gennisc15544d2014-09-24 20:26:52 -07002350 for _, entity := range globalVariables {
2351 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002352 if !visited[v] {
2353 err := walk(v)
2354 if err != nil {
2355 return nil
2356 }
2357 }
2358 }
2359
2360 return nil
2361}
2362
2363func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002364 globalPools := make([]globalEntity, 0, len(c.globalPools))
2365 for pool := range c.globalPools {
2366 globalPools = append(globalPools, pool)
2367 }
2368
2369 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
2370
2371 for _, entity := range globalPools {
2372 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002373 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002374 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002375 err := def.WriteTo(nw, name)
2376 if err != nil {
2377 return err
2378 }
2379
2380 err = nw.BlankLine()
2381 if err != nil {
2382 return err
2383 }
2384 }
2385
2386 return nil
2387}
2388
2389func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002390 globalRules := make([]globalEntity, 0, len(c.globalRules))
2391 for rule := range c.globalRules {
2392 globalRules = append(globalRules, rule)
2393 }
2394
2395 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
2396
2397 for _, entity := range globalRules {
2398 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002399 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002400 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002401 err := def.WriteTo(nw, name, c.pkgNames)
2402 if err != nil {
2403 return err
2404 }
2405
2406 err = nw.BlankLine()
2407 if err != nil {
2408 return err
2409 }
2410 }
2411
2412 return nil
2413}
2414
Colin Crossab6d7902015-03-11 16:17:52 -07002415type moduleSorter []*moduleInfo
Jamie Gennis86179fe2014-06-11 16:27:16 -07002416
Colin Crossab6d7902015-03-11 16:17:52 -07002417func (s moduleSorter) Len() int {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002418 return len(s)
2419}
2420
Colin Crossab6d7902015-03-11 16:17:52 -07002421func (s moduleSorter) Less(i, j int) bool {
2422 iName := s[i].properties.Name
2423 jName := s[j].properties.Name
2424 if iName == jName {
Colin Cross65569e42015-03-10 20:08:19 -07002425 iName = s[i].variantName
2426 jName = s[j].variantName
Colin Crossab6d7902015-03-11 16:17:52 -07002427 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07002428 return iName < jName
2429}
2430
Colin Crossab6d7902015-03-11 16:17:52 -07002431func (s moduleSorter) Swap(i, j int) {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002432 s[i], s[j] = s[j], s[i]
2433}
2434
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002435func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
2436 headerTemplate := template.New("moduleHeader")
2437 _, err := headerTemplate.Parse(moduleHeaderTemplate)
2438 if err != nil {
2439 // This is a programming error.
2440 panic(err)
2441 }
2442
Colin Crossab6d7902015-03-11 16:17:52 -07002443 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
2444 for _, module := range c.moduleInfo {
2445 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07002446 }
Colin Crossab6d7902015-03-11 16:17:52 -07002447 sort.Sort(moduleSorter(modules))
Jamie Gennis86179fe2014-06-11 16:27:16 -07002448
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002449 buf := bytes.NewBuffer(nil)
2450
Colin Crossab6d7902015-03-11 16:17:52 -07002451 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002452 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
2453 continue
2454 }
2455
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002456 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002457
2458 // In order to make the bootstrap build manifest independent of the
2459 // build dir we need to output the Blueprints file locations in the
2460 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07002461 relPos := module.pos
2462 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002463
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002464 // Get the name and location of the factory function for the module.
Colin Crossab6d7902015-03-11 16:17:52 -07002465 factory := c.moduleFactories[module.typeName]
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002466 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2467 factoryName := factoryFunc.Name()
2468
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002469 infoMap := map[string]interface{}{
Colin Crossab6d7902015-03-11 16:17:52 -07002470 "properties": module.properties,
2471 "typeName": module.typeName,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002472 "goFactory": factoryName,
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002473 "pos": relPos,
Colin Cross65569e42015-03-10 20:08:19 -07002474 "variant": module.variantName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002475 }
2476 err = headerTemplate.Execute(buf, infoMap)
2477 if err != nil {
2478 return err
2479 }
2480
2481 err = nw.Comment(buf.String())
2482 if err != nil {
2483 return err
2484 }
2485
2486 err = nw.BlankLine()
2487 if err != nil {
2488 return err
2489 }
2490
Colin Crossab6d7902015-03-11 16:17:52 -07002491 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002492 if err != nil {
2493 return err
2494 }
2495
2496 err = nw.BlankLine()
2497 if err != nil {
2498 return err
2499 }
2500 }
2501
2502 return nil
2503}
2504
2505func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
2506 headerTemplate := template.New("singletonHeader")
2507 _, err := headerTemplate.Parse(singletonHeaderTemplate)
2508 if err != nil {
2509 // This is a programming error.
2510 panic(err)
2511 }
2512
2513 buf := bytes.NewBuffer(nil)
2514
Yuchen Wub9103ef2015-08-25 17:58:17 -07002515 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002516 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
2517 continue
2518 }
2519
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002520 // Get the name of the factory function for the module.
2521 factory := info.factory
2522 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2523 factoryName := factoryFunc.Name()
2524
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002525 buf.Reset()
2526 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07002527 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002528 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002529 }
2530 err = headerTemplate.Execute(buf, infoMap)
2531 if err != nil {
2532 return err
2533 }
2534
2535 err = nw.Comment(buf.String())
2536 if err != nil {
2537 return err
2538 }
2539
2540 err = nw.BlankLine()
2541 if err != nil {
2542 return err
2543 }
2544
2545 err = c.writeLocalBuildActions(nw, &info.actionDefs)
2546 if err != nil {
2547 return err
2548 }
2549
2550 err = nw.BlankLine()
2551 if err != nil {
2552 return err
2553 }
2554 }
2555
2556 return nil
2557}
2558
2559func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
2560 defs *localBuildActions) error {
2561
2562 // Write the local variable assignments.
2563 for _, v := range defs.variables {
2564 // A localVariable doesn't need the package names or config to
2565 // determine its name or value.
2566 name := v.fullName(nil)
2567 value, err := v.value(nil)
2568 if err != nil {
2569 panic(err)
2570 }
2571 err = nw.Assign(name, value.Value(c.pkgNames))
2572 if err != nil {
2573 return err
2574 }
2575 }
2576
2577 if len(defs.variables) > 0 {
2578 err := nw.BlankLine()
2579 if err != nil {
2580 return err
2581 }
2582 }
2583
2584 // Write the local rules.
2585 for _, r := range defs.rules {
2586 // A localRule doesn't need the package names or config to determine
2587 // its name or definition.
2588 name := r.fullName(nil)
2589 def, err := r.def(nil)
2590 if err != nil {
2591 panic(err)
2592 }
2593
2594 err = def.WriteTo(nw, name, c.pkgNames)
2595 if err != nil {
2596 return err
2597 }
2598
2599 err = nw.BlankLine()
2600 if err != nil {
2601 return err
2602 }
2603 }
2604
2605 // Write the build definitions.
2606 for _, buildDef := range defs.buildDefs {
2607 err := buildDef.WriteTo(nw, c.pkgNames)
2608 if err != nil {
2609 return err
2610 }
2611
2612 if len(buildDef.Args) > 0 {
2613 err = nw.BlankLine()
2614 if err != nil {
2615 return err
2616 }
2617 }
2618 }
2619
2620 return nil
2621}
2622
Colin Cross65569e42015-03-10 20:08:19 -07002623func beforeInModuleList(a, b *moduleInfo, list []*moduleInfo) bool {
2624 found := false
2625 for _, l := range list {
2626 if l == a {
2627 found = true
2628 } else if l == b {
2629 return found
2630 }
2631 }
2632
2633 missing := a
2634 if found {
2635 missing = b
2636 }
2637 panic(fmt.Errorf("element %v not found in list %v", missing, list))
2638}
2639
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002640var fileHeaderTemplate = `******************************************************************************
2641*** This file is generated and should not be edited ***
2642******************************************************************************
2643{{if .Pkgs}}
2644This file contains variables, rules, and pools with name prefixes indicating
2645they were generated by the following Go packages:
2646{{range .Pkgs}}
2647 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
2648
2649`
2650
2651var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2652Module: {{.properties.Name}}
Colin Crossab6d7902015-03-11 16:17:52 -07002653Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002654Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002655Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002656Defined: {{.pos}}
2657`
2658
2659var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2660Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002661Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002662`