blob: ee9beb6cc2ce609ad87fe107ab691992679222e9 [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
Dan Willemsenfdeb7242015-07-24 16:53:27 -07001152func (c *Context) addReverseDependency(module *moduleInfo, destName string) []error {
1153 if destName == module.properties.Name {
1154 return []error{&Error{
1155 Err: fmt.Errorf("%q depends on itself", destName),
1156 Pos: module.pos,
1157 }}
1158 }
1159
1160 destInfo, ok := c.moduleGroups[destName]
1161 if !ok {
1162 return []error{&Error{
1163 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 {
1170 m.directDeps = append(m.directDeps, module)
1171 return nil
1172 }
1173
1174 return []error{&Error{
1175 Err: fmt.Errorf("reverse dependency %q of %q missing variant %q",
1176 destName, module.properties.Name,
1177 c.prettyPrintVariant(module.dependencyVariant)),
1178 Pos: module.pos,
1179 }}
1180}
1181
Colin Crossf5e34b92015-03-13 16:02:36 -07001182func (c *Context) addVariationDependency(module *moduleInfo, variations []Variation,
Colin Cross89486232015-05-08 11:14:54 -07001183 depName string, far bool) []error {
Colin Cross65569e42015-03-10 20:08:19 -07001184
1185 depsPos := module.propertyPos["deps"]
1186
1187 depInfo, ok := c.moduleGroups[depName]
1188 if !ok {
1189 return []error{&Error{
1190 Err: fmt.Errorf("%q depends on undefined module %q",
1191 module.properties.Name, depName),
1192 Pos: depsPos,
1193 }}
1194 }
1195
1196 // We can't just append variant.Variant to module.dependencyVariants.variantName and
1197 // compare the strings because the result won't be in mutator registration order.
1198 // Create a new map instead, and then deep compare the maps.
Colin Cross89486232015-05-08 11:14:54 -07001199 var newVariant variationMap
1200 if !far {
1201 newVariant = module.dependencyVariant.clone()
1202 } else {
1203 newVariant = make(variationMap)
1204 }
Colin Crossf5e34b92015-03-13 16:02:36 -07001205 for _, v := range variations {
1206 newVariant[v.Mutator] = v.Variation
Colin Cross65569e42015-03-10 20:08:19 -07001207 }
1208
1209 for _, m := range depInfo.modules {
Colin Cross89486232015-05-08 11:14:54 -07001210 var found bool
1211 if far {
1212 found = m.variant.subset(newVariant)
1213 } else {
1214 found = m.variant.equal(newVariant)
1215 }
1216 if found {
Colin Crossf5e34b92015-03-13 16:02:36 -07001217 // AddVariationDependency allows adding a dependency on itself, but only if
Colin Cross65569e42015-03-10 20:08:19 -07001218 // that module is earlier in the module list than this one, since we always
Colin Crossf5e34b92015-03-13 16:02:36 -07001219 // run GenerateBuildActions in order for the variants of a module
Colin Cross65569e42015-03-10 20:08:19 -07001220 if depInfo == module.group && beforeInModuleList(module, m, module.group.modules) {
1221 return []error{&Error{
1222 Err: fmt.Errorf("%q depends on later version of itself", depName),
1223 Pos: depsPos,
1224 }}
1225 }
1226 module.directDeps = append(module.directDeps, m)
1227 return nil
1228 }
1229 }
1230
1231 return []error{&Error{
1232 Err: fmt.Errorf("dependency %q of %q missing variant %q",
1233 depInfo.modules[0].properties.Name, module.properties.Name,
Colin Crossf5e34b92015-03-13 16:02:36 -07001234 c.prettyPrintVariant(newVariant)),
Colin Cross65569e42015-03-10 20:08:19 -07001235 Pos: depsPos,
1236 }}
Colin Crossc9028482014-12-18 16:28:54 -08001237}
1238
Colin Cross7addea32015-03-11 15:43:52 -07001239func (c *Context) parallelVisitAllBottomUp(visit func(group *moduleInfo) bool) {
1240 doneCh := make(chan *moduleInfo)
Colin Cross691a60d2015-01-07 18:08:56 -08001241 count := 0
Colin Cross8900e9b2015-03-02 14:03:01 -08001242 cancel := false
Colin Cross691a60d2015-01-07 18:08:56 -08001243
Colin Cross7addea32015-03-11 15:43:52 -07001244 for _, module := range c.modulesSorted {
1245 module.waitingCount = module.depsCount
Colin Cross691a60d2015-01-07 18:08:56 -08001246 }
1247
Colin Cross7addea32015-03-11 15:43:52 -07001248 visitOne := func(module *moduleInfo) {
Colin Cross691a60d2015-01-07 18:08:56 -08001249 count++
1250 go func() {
Colin Cross7addea32015-03-11 15:43:52 -07001251 ret := visit(module)
Colin Cross8900e9b2015-03-02 14:03:01 -08001252 if ret {
1253 cancel = true
1254 }
Colin Cross7addea32015-03-11 15:43:52 -07001255 doneCh <- module
Colin Cross691a60d2015-01-07 18:08:56 -08001256 }()
1257 }
1258
Colin Cross7addea32015-03-11 15:43:52 -07001259 for _, module := range c.modulesSorted {
1260 if module.waitingCount == 0 {
1261 visitOne(module)
Colin Cross691a60d2015-01-07 18:08:56 -08001262 }
1263 }
1264
Colin Cross11e3b0d2015-02-04 10:41:00 -08001265 for count > 0 {
Colin Cross691a60d2015-01-07 18:08:56 -08001266 select {
Colin Cross7addea32015-03-11 15:43:52 -07001267 case doneModule := <-doneCh:
Colin Cross8900e9b2015-03-02 14:03:01 -08001268 if !cancel {
Colin Cross7addea32015-03-11 15:43:52 -07001269 for _, parent := range doneModule.reverseDeps {
Colin Cross8900e9b2015-03-02 14:03:01 -08001270 parent.waitingCount--
1271 if parent.waitingCount == 0 {
1272 visitOne(parent)
1273 }
Colin Cross691a60d2015-01-07 18:08:56 -08001274 }
1275 }
1276 count--
Colin Cross691a60d2015-01-07 18:08:56 -08001277 }
1278 }
1279}
1280
1281// updateDependencies recursively walks the module dependency graph and updates
1282// additional fields based on the dependencies. It builds a sorted list of modules
1283// such that dependencies of a module always appear first, and populates reverse
1284// dependency links and counts of total dependencies. It also reports errors when
1285// it encounters dependency cycles. This should called after resolveDependencies,
1286// as well as after any mutator pass has called addDependency
1287func (c *Context) updateDependencies() (errs []error) {
Colin Cross7addea32015-03-11 15:43:52 -07001288 visited := make(map[*moduleInfo]bool) // modules that were already checked
1289 checking := make(map[*moduleInfo]bool) // modules actively being checked
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001290
Colin Cross7addea32015-03-11 15:43:52 -07001291 sorted := make([]*moduleInfo, 0, len(c.moduleInfo))
Colin Cross573a2fd2014-12-17 14:16:51 -08001292
Colin Cross7addea32015-03-11 15:43:52 -07001293 var check func(group *moduleInfo) []*moduleInfo
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001294
Colin Cross7addea32015-03-11 15:43:52 -07001295 cycleError := func(cycle []*moduleInfo) {
Colin Cross10b54db2015-03-11 14:40:30 -07001296 // We are the "start" of the cycle, so we're responsible
1297 // for generating the errors. The cycle list is in
1298 // reverse order because all the 'check' calls append
1299 // their own module to the list.
1300 errs = append(errs, &Error{
1301 Err: fmt.Errorf("encountered dependency cycle:"),
Colin Cross7addea32015-03-11 15:43:52 -07001302 Pos: cycle[len(cycle)-1].pos,
Colin Cross10b54db2015-03-11 14:40:30 -07001303 })
1304
1305 // Iterate backwards through the cycle list.
Colin Cross0e4607e2015-03-24 16:42:56 -07001306 curModule := cycle[0]
Colin Cross10b54db2015-03-11 14:40:30 -07001307 for i := len(cycle) - 1; i >= 0; i-- {
Colin Cross7addea32015-03-11 15:43:52 -07001308 nextModule := cycle[i]
Colin Cross10b54db2015-03-11 14:40:30 -07001309 errs = append(errs, &Error{
1310 Err: fmt.Errorf(" %q depends on %q",
Colin Cross7addea32015-03-11 15:43:52 -07001311 curModule.properties.Name,
1312 nextModule.properties.Name),
1313 Pos: curModule.propertyPos["deps"],
Colin Cross10b54db2015-03-11 14:40:30 -07001314 })
Colin Cross7addea32015-03-11 15:43:52 -07001315 curModule = nextModule
Colin Cross10b54db2015-03-11 14:40:30 -07001316 }
1317 }
1318
Colin Cross7addea32015-03-11 15:43:52 -07001319 check = func(module *moduleInfo) []*moduleInfo {
1320 visited[module] = true
1321 checking[module] = true
1322 defer delete(checking, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001323
Colin Cross7addea32015-03-11 15:43:52 -07001324 deps := make(map[*moduleInfo]bool)
1325
1326 // Add an implicit dependency ordering on all earlier modules in the same module group
1327 for _, dep := range module.group.modules {
1328 if dep == module {
1329 break
Colin Crossbbfa51a2014-12-17 16:12:41 -08001330 }
Colin Cross7addea32015-03-11 15:43:52 -07001331 deps[dep] = true
Colin Crossbbfa51a2014-12-17 16:12:41 -08001332 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001333
Colin Cross7addea32015-03-11 15:43:52 -07001334 for _, dep := range module.directDeps {
1335 deps[dep] = true
1336 }
1337
1338 module.reverseDeps = []*moduleInfo{}
1339 module.depsCount = len(deps)
Colin Cross691a60d2015-01-07 18:08:56 -08001340
Colin Crossbbfa51a2014-12-17 16:12:41 -08001341 for dep := range deps {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001342 if checking[dep] {
1343 // This is a cycle.
Colin Cross7addea32015-03-11 15:43:52 -07001344 return []*moduleInfo{dep, module}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001345 }
1346
1347 if !visited[dep] {
1348 cycle := check(dep)
1349 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001350 if cycle[0] == module {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001351 // We are the "start" of the cycle, so we're responsible
1352 // for generating the errors. The cycle list is in
1353 // reverse order because all the 'check' calls append
1354 // their own module to the list.
Colin Cross10b54db2015-03-11 14:40:30 -07001355 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001356
1357 // We can continue processing this module's children to
1358 // find more cycles. Since all the modules that were
1359 // part of the found cycle were marked as visited we
1360 // won't run into that cycle again.
1361 } else {
1362 // We're not the "start" of the cycle, so we just append
1363 // our module to the list and return it.
Colin Cross7addea32015-03-11 15:43:52 -07001364 return append(cycle, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001365 }
1366 }
1367 }
Colin Cross691a60d2015-01-07 18:08:56 -08001368
Colin Cross7addea32015-03-11 15:43:52 -07001369 dep.reverseDeps = append(dep.reverseDeps, module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001370 }
1371
Colin Cross7addea32015-03-11 15:43:52 -07001372 sorted = append(sorted, module)
Colin Cross573a2fd2014-12-17 14:16:51 -08001373
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001374 return nil
1375 }
1376
Colin Cross7addea32015-03-11 15:43:52 -07001377 for _, module := range c.moduleInfo {
1378 if !visited[module] {
1379 cycle := check(module)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001380 if cycle != nil {
Colin Cross7addea32015-03-11 15:43:52 -07001381 if cycle[len(cycle)-1] != module {
Colin Cross10b54db2015-03-11 14:40:30 -07001382 panic("inconceivable!")
1383 }
1384 cycleError(cycle)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001385 }
1386 }
1387 }
1388
Colin Cross7addea32015-03-11 15:43:52 -07001389 c.modulesSorted = sorted
Colin Cross573a2fd2014-12-17 14:16:51 -08001390
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001391 return
1392}
1393
Jamie Gennisd4e10182014-06-12 20:06:50 -07001394// PrepareBuildActions generates an internal representation of all the build
1395// actions that need to be performed. This process involves invoking the
1396// GenerateBuildActions method on each of the Module objects created during the
1397// parse phase and then on each of the registered Singleton objects.
1398//
1399// If the ResolveDependencies method has not already been called it is called
1400// automatically by this method.
1401//
1402// The config argument is made available to all of the Module and Singleton
1403// objects via the Config method on the ModuleContext and SingletonContext
1404// objects passed to GenerateBuildActions. It is also passed to the functions
1405// specified via PoolFunc, RuleFunc, and VariableFunc so that they can compute
1406// config-specific values.
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001407//
1408// The returned deps is a list of the ninja files dependencies that were added
1409// by the modules and singletons via the ModuleContext.AddNinjaFileDeps() and
1410// SingletonContext.AddNinjaFileDeps() methods.
1411func (c *Context) PrepareBuildActions(config interface{}) (deps []string, errs []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001412 c.buildActionsReady = false
1413
1414 if !c.dependenciesReady {
Jamie Gennisb9e87f62014-09-24 20:28:11 -07001415 errs := c.ResolveDependencies(config)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001416 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001417 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001418 }
1419 }
1420
1421 liveGlobals := newLiveTracker(config)
1422
1423 c.initSpecialVariables()
1424
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001425 depsModules, errs := c.generateModuleBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001426 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001427 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001428 }
1429
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001430 depsSingletons, errs := c.generateSingletonBuildActions(config, liveGlobals)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001431 if len(errs) > 0 {
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001432 return nil, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001433 }
1434
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001435 deps = append(depsModules, depsSingletons...)
1436
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001437 if c.buildDir != nil {
1438 liveGlobals.addNinjaStringDeps(c.buildDir)
1439 }
1440
1441 pkgNames := c.makeUniquePackageNames(liveGlobals)
1442
1443 // This will panic if it finds a problem since it's a programming error.
1444 c.checkForVariableReferenceCycles(liveGlobals.variables, pkgNames)
1445
1446 c.pkgNames = pkgNames
1447 c.globalVariables = liveGlobals.variables
1448 c.globalPools = liveGlobals.pools
1449 c.globalRules = liveGlobals.rules
1450
1451 c.buildActionsReady = true
1452
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001453 return deps, nil
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001454}
1455
Colin Cross65569e42015-03-10 20:08:19 -07001456func (c *Context) runEarlyMutators(config interface{}) (errs []error) {
1457 for _, mutator := range c.earlyMutatorInfo {
1458 for _, group := range c.moduleGroups {
1459 newModules := make([]*moduleInfo, 0, len(group.modules))
1460
1461 for _, module := range group.modules {
1462 mctx := &mutatorContext{
1463 baseModuleContext: baseModuleContext{
1464 context: c,
1465 config: config,
1466 module: module,
1467 },
1468 name: mutator.name,
1469 }
1470 mutator.mutator(mctx)
1471 if len(mctx.errs) > 0 {
1472 errs = append(errs, mctx.errs...)
1473 return errs
1474 }
1475
1476 if module.splitModules != nil {
1477 newModules = append(newModules, module.splitModules...)
1478 } else {
1479 newModules = append(newModules, module)
1480 }
1481 }
1482
1483 group.modules = newModules
1484 }
1485 }
1486
Colin Cross763b6f12015-10-29 15:32:56 -07001487 errs = c.updateDependencies()
1488 if len(errs) > 0 {
1489 return errs
1490 }
1491
Colin Cross65569e42015-03-10 20:08:19 -07001492 return nil
1493}
1494
Colin Crossc9028482014-12-18 16:28:54 -08001495func (c *Context) runMutators(config interface{}) (errs []error) {
Colin Cross763b6f12015-10-29 15:32:56 -07001496 errs = c.runEarlyMutators(config)
1497 if len(errs) > 0 {
1498 return errs
1499 }
1500
Colin Crossc9028482014-12-18 16:28:54 -08001501 for _, mutator := range c.mutatorInfo {
1502 if mutator.topDownMutator != nil {
1503 errs = c.runTopDownMutator(config, mutator.name, mutator.topDownMutator)
1504 } else if mutator.bottomUpMutator != nil {
1505 errs = c.runBottomUpMutator(config, mutator.name, mutator.bottomUpMutator)
1506 } else {
1507 panic("no mutator set on " + mutator.name)
1508 }
1509 if len(errs) > 0 {
1510 return errs
1511 }
1512 }
1513
1514 return nil
1515}
1516
1517func (c *Context) runTopDownMutator(config interface{},
1518 name string, mutator TopDownMutator) (errs []error) {
1519
Colin Cross7addea32015-03-11 15:43:52 -07001520 for i := 0; i < len(c.modulesSorted); i++ {
1521 module := c.modulesSorted[len(c.modulesSorted)-1-i]
1522 mctx := &mutatorContext{
1523 baseModuleContext: baseModuleContext{
1524 context: c,
1525 config: config,
1526 module: module,
1527 },
1528 name: name,
1529 }
Colin Crossc9028482014-12-18 16:28:54 -08001530
Colin Cross7addea32015-03-11 15:43:52 -07001531 mutator(mctx)
1532 if len(mctx.errs) > 0 {
1533 errs = append(errs, mctx.errs...)
1534 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001535 }
1536 }
1537
1538 return errs
1539}
1540
1541func (c *Context) runBottomUpMutator(config interface{},
1542 name string, mutator BottomUpMutator) (errs []error) {
1543
Colin Cross7addea32015-03-11 15:43:52 -07001544 for _, module := range c.modulesSorted {
1545 newModules := make([]*moduleInfo, 0, 1)
Colin Crossc9028482014-12-18 16:28:54 -08001546
Jamie Gennisc7988252015-04-14 23:28:10 -04001547 if module.splitModules != nil {
1548 panic("split module found in sorted module list")
1549 }
1550
Colin Cross7addea32015-03-11 15:43:52 -07001551 mctx := &mutatorContext{
1552 baseModuleContext: baseModuleContext{
1553 context: c,
1554 config: config,
1555 module: module,
1556 },
1557 name: name,
1558 }
Colin Crossc9028482014-12-18 16:28:54 -08001559
Colin Cross7addea32015-03-11 15:43:52 -07001560 mutator(mctx)
1561 if len(mctx.errs) > 0 {
1562 errs = append(errs, mctx.errs...)
1563 return errs
1564 }
Colin Crossc9028482014-12-18 16:28:54 -08001565
Colin Cross7addea32015-03-11 15:43:52 -07001566 // Fix up any remaining dependencies on modules that were split into variants
1567 // by replacing them with the first variant
1568 for i, dep := range module.directDeps {
1569 if dep.logicModule == nil {
1570 module.directDeps[i] = dep.splitModules[0]
Colin Crossc9028482014-12-18 16:28:54 -08001571 }
1572 }
1573
Colin Cross7addea32015-03-11 15:43:52 -07001574 if module.splitModules != nil {
1575 newModules = append(newModules, module.splitModules...)
1576 } else {
1577 newModules = append(newModules, module)
1578 }
1579
1580 module.group.modules = spliceModules(module.group.modules, module, newModules)
Colin Crossc9028482014-12-18 16:28:54 -08001581 }
1582
Jamie Gennisc7988252015-04-14 23:28:10 -04001583 errs = c.updateDependencies()
1584 if len(errs) > 0 {
1585 return errs
Colin Crossc9028482014-12-18 16:28:54 -08001586 }
1587
1588 return errs
1589}
1590
Colin Cross7addea32015-03-11 15:43:52 -07001591func spliceModules(modules []*moduleInfo, origModule *moduleInfo,
1592 newModules []*moduleInfo) []*moduleInfo {
1593 for i, m := range modules {
1594 if m == origModule {
1595 return spliceModulesAtIndex(modules, i, newModules)
1596 }
1597 }
1598
1599 panic("failed to find original module to splice")
1600}
1601
1602func spliceModulesAtIndex(modules []*moduleInfo, i int, newModules []*moduleInfo) []*moduleInfo {
1603 spliceSize := len(newModules)
1604 newLen := len(modules) + spliceSize - 1
1605 var dest []*moduleInfo
1606 if cap(modules) >= len(modules)-1+len(newModules) {
1607 // We can fit the splice in the existing capacity, do everything in place
1608 dest = modules[:newLen]
1609 } else {
1610 dest = make([]*moduleInfo, newLen)
1611 copy(dest, modules[:i])
1612 }
1613
1614 // Move the end of the slice over by spliceSize-1
Colin Cross72bd1932015-03-16 00:13:59 -07001615 copy(dest[i+spliceSize:], modules[i+1:])
Colin Cross7addea32015-03-11 15:43:52 -07001616
1617 // Copy the new modules into the slice
Colin Cross72bd1932015-03-16 00:13:59 -07001618 copy(dest[i:], newModules)
Colin Cross7addea32015-03-11 15:43:52 -07001619
Colin Cross72bd1932015-03-16 00:13:59 -07001620 return dest
Colin Cross7addea32015-03-11 15:43:52 -07001621}
1622
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001623func (c *Context) initSpecialVariables() {
1624 c.buildDir = nil
1625 c.requiredNinjaMajor = 1
Dan Willemsen21b6f372015-07-22 12:58:01 -07001626 c.requiredNinjaMinor = 6
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001627 c.requiredNinjaMicro = 0
1628}
1629
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001630func (c *Context) generateModuleBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001631 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001632
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001633 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001634 var errs []error
1635
Colin Cross691a60d2015-01-07 18:08:56 -08001636 cancelCh := make(chan struct{})
1637 errsCh := make(chan []error)
1638 depsCh := make(chan []string)
1639
1640 go func() {
1641 for {
1642 select {
1643 case <-cancelCh:
1644 close(cancelCh)
1645 return
1646 case newErrs := <-errsCh:
1647 errs = append(errs, newErrs...)
1648 case newDeps := <-depsCh:
1649 deps = append(deps, newDeps...)
1650
1651 }
1652 }
1653 }()
1654
Colin Cross7addea32015-03-11 15:43:52 -07001655 c.parallelVisitAllBottomUp(func(module *moduleInfo) bool {
1656 // The parent scope of the moduleContext's local scope gets overridden to be that of the
1657 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1658 // just set it to nil.
1659 prefix := moduleNamespacePrefix(module.group.ninjaName + "_" + module.variantName)
1660 scope := newLocalScope(nil, prefix)
Colin Cross6134a5c2015-02-10 11:26:26 -08001661
Colin Cross7addea32015-03-11 15:43:52 -07001662 mctx := &moduleContext{
1663 baseModuleContext: baseModuleContext{
1664 context: c,
1665 config: config,
1666 module: module,
1667 },
1668 scope: scope,
1669 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001670
Colin Cross7addea32015-03-11 15:43:52 -07001671 mctx.module.logicModule.GenerateBuildActions(mctx)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001672
Colin Cross7addea32015-03-11 15:43:52 -07001673 if len(mctx.errs) > 0 {
1674 errsCh <- mctx.errs
1675 return true
1676 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001677
Colin Cross7addea32015-03-11 15:43:52 -07001678 depsCh <- mctx.ninjaFileDeps
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001679
Colin Crossab6d7902015-03-11 16:17:52 -07001680 newErrs := c.processLocalBuildActions(&module.actionDefs,
Colin Cross7addea32015-03-11 15:43:52 -07001681 &mctx.actionDefs, liveGlobals)
1682 if len(newErrs) > 0 {
1683 errsCh <- newErrs
1684 return true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001685 }
Colin Cross8900e9b2015-03-02 14:03:01 -08001686 return false
Colin Cross691a60d2015-01-07 18:08:56 -08001687 })
1688
1689 cancelCh <- struct{}{}
1690 <-cancelCh
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001691
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001692 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001693}
1694
Jamie Gennis6eb4d242014-06-11 18:31:16 -07001695func (c *Context) generateSingletonBuildActions(config interface{},
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001696 liveGlobals *liveTracker) ([]string, []error) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001697
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001698 var deps []string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001699 var errs []error
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001700
Yuchen Wub9103ef2015-08-25 17:58:17 -07001701 for _, info := range c.singletonInfo {
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001702 // The parent scope of the singletonContext's local scope gets overridden to be that of the
1703 // calling Go package on a per-call basis. Since the initial parent scope doesn't matter we
1704 // just set it to nil.
Yuchen Wub9103ef2015-08-25 17:58:17 -07001705 scope := newLocalScope(nil, singletonNamespacePrefix(info.name))
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001706
1707 sctx := &singletonContext{
1708 context: c,
1709 config: config,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07001710 scope: scope,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001711 }
1712
1713 info.singleton.GenerateBuildActions(sctx)
1714
1715 if len(sctx.errs) > 0 {
1716 errs = append(errs, sctx.errs...)
1717 if len(errs) > maxErrors {
1718 break
1719 }
1720 continue
1721 }
1722
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001723 deps = append(deps, sctx.ninjaFileDeps...)
1724
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001725 newErrs := c.processLocalBuildActions(&info.actionDefs,
1726 &sctx.actionDefs, liveGlobals)
1727 errs = append(errs, newErrs...)
1728 if len(errs) > maxErrors {
1729 break
1730 }
1731 }
1732
Mathias Agopian5b8477d2014-06-25 17:21:54 -07001733 return deps, errs
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001734}
1735
1736func (c *Context) processLocalBuildActions(out, in *localBuildActions,
1737 liveGlobals *liveTracker) []error {
1738
1739 var errs []error
1740
1741 // First we go through and add everything referenced by the module's
1742 // buildDefs to the live globals set. This will end up adding the live
1743 // locals to the set as well, but we'll take them out after.
1744 for _, def := range in.buildDefs {
1745 err := liveGlobals.AddBuildDefDeps(def)
1746 if err != nil {
1747 errs = append(errs, err)
1748 }
1749 }
1750
1751 if len(errs) > 0 {
1752 return errs
1753 }
1754
Colin Crossc9028482014-12-18 16:28:54 -08001755 out.buildDefs = append(out.buildDefs, in.buildDefs...)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001756
1757 // We use the now-incorrect set of live "globals" to determine which local
1758 // definitions are live. As we go through copying those live locals to the
Colin Crossc9028482014-12-18 16:28:54 -08001759 // moduleGroup we remove them from the live globals set.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001760 for _, v := range in.variables {
Colin Crossab6d7902015-03-11 16:17:52 -07001761 isLive := liveGlobals.RemoveVariableIfLive(v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001762 if isLive {
1763 out.variables = append(out.variables, v)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001764 }
1765 }
1766
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001767 for _, r := range in.rules {
Colin Crossab6d7902015-03-11 16:17:52 -07001768 isLive := liveGlobals.RemoveRuleIfLive(r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001769 if isLive {
1770 out.rules = append(out.rules, r)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001771 }
1772 }
1773
1774 return nil
1775}
1776
Yuchen Wu222e2452015-10-06 14:03:27 -07001777func (c *Context) walkDeps(topModule *moduleInfo,
1778 visit func(Module, Module) bool) {
1779
1780 visited := make(map[*moduleInfo]bool)
1781
1782 var walk func(module *moduleInfo)
1783 walk = func(module *moduleInfo) {
1784 visited[module] = true
1785
1786 for _, moduleDep := range module.directDeps {
1787 if !visited[moduleDep] {
1788 if visit(moduleDep.logicModule, module.logicModule) {
1789 walk(moduleDep)
1790 }
1791 }
1792 }
1793 }
1794
1795 walk(topModule)
1796}
1797
Colin Crossbbfa51a2014-12-17 16:12:41 -08001798func (c *Context) visitDepsDepthFirst(topModule *moduleInfo, visit func(Module)) {
1799 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001800
Colin Crossbbfa51a2014-12-17 16:12:41 -08001801 var walk func(module *moduleInfo)
1802 walk = func(module *moduleInfo) {
1803 visited[module] = true
1804 for _, moduleDep := range module.directDeps {
1805 if !visited[moduleDep] {
1806 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001807 }
1808 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001809
Colin Crossbbfa51a2014-12-17 16:12:41 -08001810 if module != topModule {
1811 visit(module.logicModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001812 }
1813 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001814
1815 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001816}
1817
Colin Crossbbfa51a2014-12-17 16:12:41 -08001818func (c *Context) visitDepsDepthFirstIf(topModule *moduleInfo, pred func(Module) bool,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001819 visit func(Module)) {
1820
Colin Crossbbfa51a2014-12-17 16:12:41 -08001821 visited := make(map[*moduleInfo]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001822
Colin Crossbbfa51a2014-12-17 16:12:41 -08001823 var walk func(module *moduleInfo)
1824 walk = func(module *moduleInfo) {
1825 visited[module] = true
1826 for _, moduleDep := range module.directDeps {
1827 if !visited[moduleDep] {
1828 walk(moduleDep)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001829 }
Jamie Gennis0bb5d8a2014-11-26 14:45:37 -08001830 }
Colin Crossbbfa51a2014-12-17 16:12:41 -08001831
1832 if module != topModule {
1833 if pred(module.logicModule) {
1834 visit(module.logicModule)
1835 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001836 }
1837 }
1838
Colin Crossbbfa51a2014-12-17 16:12:41 -08001839 walk(topModule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001840}
1841
Colin Crossc9028482014-12-18 16:28:54 -08001842func (c *Context) visitDirectDeps(module *moduleInfo, visit func(Module)) {
1843 for _, dep := range module.directDeps {
1844 visit(dep.logicModule)
1845 }
1846}
1847
1848func (c *Context) visitDirectDepsIf(module *moduleInfo, pred func(Module) bool,
1849 visit func(Module)) {
1850
1851 for _, dep := range module.directDeps {
1852 if pred(dep.logicModule) {
1853 visit(dep.logicModule)
1854 }
1855 }
1856}
1857
Jamie Gennisc15544d2014-09-24 20:26:52 -07001858func (c *Context) sortedModuleNames() []string {
1859 if c.cachedSortedModuleNames == nil {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001860 c.cachedSortedModuleNames = make([]string, 0, len(c.moduleGroups))
1861 for moduleName := range c.moduleGroups {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001862 c.cachedSortedModuleNames = append(c.cachedSortedModuleNames,
1863 moduleName)
1864 }
1865 sort.Strings(c.cachedSortedModuleNames)
1866 }
1867
1868 return c.cachedSortedModuleNames
1869}
1870
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001871func (c *Context) visitAllModules(visit func(Module)) {
Jamie Gennisc15544d2014-09-24 20:26:52 -07001872 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001873 group := c.moduleGroups[moduleName]
1874 for _, module := range group.modules {
1875 visit(module.logicModule)
1876 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001877 }
1878}
1879
1880func (c *Context) visitAllModulesIf(pred func(Module) bool,
1881 visit func(Module)) {
1882
Jamie Gennisc15544d2014-09-24 20:26:52 -07001883 for _, moduleName := range c.sortedModuleNames() {
Colin Crossbbfa51a2014-12-17 16:12:41 -08001884 group := c.moduleGroups[moduleName]
1885 for _, module := range group.modules {
1886 if pred(module.logicModule) {
1887 visit(module.logicModule)
1888 }
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001889 }
1890 }
1891}
1892
1893func (c *Context) requireNinjaVersion(major, minor, micro int) {
1894 if major != 1 {
1895 panic("ninja version with major version != 1 not supported")
1896 }
1897 if c.requiredNinjaMinor < minor {
1898 c.requiredNinjaMinor = minor
1899 c.requiredNinjaMicro = micro
1900 }
1901 if c.requiredNinjaMinor == minor && c.requiredNinjaMicro < micro {
1902 c.requiredNinjaMicro = micro
1903 }
1904}
1905
1906func (c *Context) setBuildDir(value *ninjaString) {
1907 if c.buildDir != nil {
1908 panic("buildDir set multiple times")
1909 }
1910 c.buildDir = value
1911}
1912
1913func (c *Context) makeUniquePackageNames(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001914 liveGlobals *liveTracker) map[*PackageContext]string {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001915
Jamie Gennis2fb20952014-10-03 02:49:58 -07001916 pkgs := make(map[string]*PackageContext)
1917 pkgNames := make(map[*PackageContext]string)
1918 longPkgNames := make(map[*PackageContext]bool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001919
Jamie Gennis2fb20952014-10-03 02:49:58 -07001920 processPackage := func(pctx *PackageContext) {
1921 if pctx == nil {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001922 // This is a built-in rule and has no package.
1923 return
1924 }
Jamie Gennis2fb20952014-10-03 02:49:58 -07001925 if _, ok := pkgNames[pctx]; ok {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001926 // We've already processed this package.
1927 return
1928 }
1929
Jamie Gennis2fb20952014-10-03 02:49:58 -07001930 otherPkg, present := pkgs[pctx.shortName]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001931 if present {
1932 // Short name collision. Both this package and the one that's
1933 // already there need to use their full names. We leave the short
1934 // name in pkgNames for now so future collisions still get caught.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001935 longPkgNames[pctx] = true
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001936 longPkgNames[otherPkg] = true
1937 } else {
1938 // No collision so far. Tentatively set the package's name to be
1939 // its short name.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001940 pkgNames[pctx] = pctx.shortName
Colin Cross0d441252015-04-14 18:02:20 -07001941 pkgs[pctx.shortName] = pctx
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001942 }
1943 }
1944
1945 // We try to give all packages their short name, but when we get collisions
1946 // we need to use the full unique package name.
1947 for v, _ := range liveGlobals.variables {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001948 processPackage(v.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001949 }
1950 for p, _ := range liveGlobals.pools {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001951 processPackage(p.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001952 }
1953 for r, _ := range liveGlobals.rules {
Jamie Gennis2fb20952014-10-03 02:49:58 -07001954 processPackage(r.packageContext())
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001955 }
1956
1957 // Add the packages that had collisions using their full unique names. This
1958 // will overwrite any short names that were added in the previous step.
Jamie Gennis2fb20952014-10-03 02:49:58 -07001959 for pctx := range longPkgNames {
1960 pkgNames[pctx] = pctx.fullName
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001961 }
1962
1963 return pkgNames
1964}
1965
1966func (c *Context) checkForVariableReferenceCycles(
Jamie Gennis2fb20952014-10-03 02:49:58 -07001967 variables map[Variable]*ninjaString, pkgNames map[*PackageContext]string) {
Jamie Gennis1bc967e2014-05-27 16:34:41 -07001968
1969 visited := make(map[Variable]bool) // variables that were already checked
1970 checking := make(map[Variable]bool) // variables actively being checked
1971
1972 var check func(v Variable) []Variable
1973
1974 check = func(v Variable) []Variable {
1975 visited[v] = true
1976 checking[v] = true
1977 defer delete(checking, v)
1978
1979 value := variables[v]
1980 for _, dep := range value.variables {
1981 if checking[dep] {
1982 // This is a cycle.
1983 return []Variable{dep, v}
1984 }
1985
1986 if !visited[dep] {
1987 cycle := check(dep)
1988 if cycle != nil {
1989 if cycle[0] == v {
1990 // We are the "start" of the cycle, so we're responsible
1991 // for generating the errors. The cycle list is in
1992 // reverse order because all the 'check' calls append
1993 // their own module to the list.
1994 msgs := []string{"detected variable reference cycle:"}
1995
1996 // Iterate backwards through the cycle list.
1997 curName := v.fullName(pkgNames)
1998 curValue := value.Value(pkgNames)
1999 for i := len(cycle) - 1; i >= 0; i-- {
2000 next := cycle[i]
2001 nextName := next.fullName(pkgNames)
2002 nextValue := variables[next].Value(pkgNames)
2003
2004 msgs = append(msgs, fmt.Sprintf(
2005 " %q depends on %q", curName, nextName))
2006 msgs = append(msgs, fmt.Sprintf(
2007 " [%s = %s]", curName, curValue))
2008
2009 curName = nextName
2010 curValue = nextValue
2011 }
2012
2013 // Variable reference cycles are a programming error,
2014 // not the fault of the Blueprint file authors.
2015 panic(strings.Join(msgs, "\n"))
2016 } else {
2017 // We're not the "start" of the cycle, so we just append
2018 // our module to the list and return it.
2019 return append(cycle, v)
2020 }
2021 }
2022 }
2023 }
2024
2025 return nil
2026 }
2027
2028 for v := range variables {
2029 if !visited[v] {
2030 cycle := check(v)
2031 if cycle != nil {
2032 panic("inconceivable!")
2033 }
2034 }
2035 }
2036}
2037
Jamie Gennisaf435562014-10-27 22:34:56 -07002038// AllTargets returns a map all the build target names to the rule used to build
2039// them. This is the same information that is output by running 'ninja -t
2040// targets all'. If this is called before PrepareBuildActions successfully
2041// completes then ErrbuildActionsNotReady is returned.
2042func (c *Context) AllTargets() (map[string]string, error) {
2043 if !c.buildActionsReady {
2044 return nil, ErrBuildActionsNotReady
2045 }
2046
2047 targets := map[string]string{}
2048
2049 // Collect all the module build targets.
Colin Crossab6d7902015-03-11 16:17:52 -07002050 for _, module := range c.moduleInfo {
2051 for _, buildDef := range module.actionDefs.buildDefs {
Jamie Gennisaf435562014-10-27 22:34:56 -07002052 ruleName := buildDef.Rule.fullName(c.pkgNames)
2053 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002054 outputValue, err := output.Eval(c.globalVariables)
2055 if err != nil {
2056 return nil, err
2057 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002058 targets[outputValue] = ruleName
2059 }
2060 }
2061 }
2062
2063 // Collect all the singleton build targets.
2064 for _, info := range c.singletonInfo {
2065 for _, buildDef := range info.actionDefs.buildDefs {
2066 ruleName := buildDef.Rule.fullName(c.pkgNames)
2067 for _, output := range buildDef.Outputs {
Christian Zander6e2b2322014-11-21 15:12:08 -08002068 outputValue, err := output.Eval(c.globalVariables)
2069 if err != nil {
Colin Crossfea2b752014-12-30 16:05:02 -08002070 return nil, err
Christian Zander6e2b2322014-11-21 15:12:08 -08002071 }
Jamie Gennisaf435562014-10-27 22:34:56 -07002072 targets[outputValue] = ruleName
2073 }
2074 }
2075 }
2076
2077 return targets, nil
2078}
2079
Colin Cross4572edd2015-05-13 14:36:24 -07002080// ModuleTypePropertyStructs returns a mapping from module type name to a list of pointers to
2081// property structs returned by the factory for that module type.
2082func (c *Context) ModuleTypePropertyStructs() map[string][]interface{} {
2083 ret := make(map[string][]interface{})
2084 for moduleType, factory := range c.moduleFactories {
2085 _, ret[moduleType] = factory()
2086 }
2087
2088 return ret
2089}
2090
2091func (c *Context) ModuleName(logicModule Module) string {
2092 module := c.moduleInfo[logicModule]
2093 return module.properties.Name
2094}
2095
2096func (c *Context) ModuleDir(logicModule Module) string {
2097 module := c.moduleInfo[logicModule]
2098 return filepath.Dir(module.relBlueprintsFile)
2099}
2100
2101func (c *Context) BlueprintFile(logicModule Module) string {
2102 module := c.moduleInfo[logicModule]
2103 return module.relBlueprintsFile
2104}
2105
2106func (c *Context) ModuleErrorf(logicModule Module, format string,
2107 args ...interface{}) error {
2108
2109 module := c.moduleInfo[logicModule]
2110 return &Error{
2111 Err: fmt.Errorf(format, args...),
2112 Pos: module.pos,
2113 }
2114}
2115
2116func (c *Context) VisitAllModules(visit func(Module)) {
2117 c.visitAllModules(visit)
2118}
2119
2120func (c *Context) VisitAllModulesIf(pred func(Module) bool,
2121 visit func(Module)) {
2122
2123 c.visitAllModulesIf(pred, visit)
2124}
2125
2126func (c *Context) VisitDepsDepthFirst(module Module,
2127 visit func(Module)) {
2128
2129 c.visitDepsDepthFirst(c.moduleInfo[module], visit)
2130}
2131
2132func (c *Context) VisitDepsDepthFirstIf(module Module,
2133 pred func(Module) bool, visit func(Module)) {
2134
2135 c.visitDepsDepthFirstIf(c.moduleInfo[module], pred, visit)
2136}
2137
Jamie Gennisd4e10182014-06-12 20:06:50 -07002138// WriteBuildFile writes the Ninja manifeset text for the generated build
2139// actions to w. If this is called before PrepareBuildActions successfully
2140// completes then ErrBuildActionsNotReady is returned.
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002141func (c *Context) WriteBuildFile(w io.Writer) error {
2142 if !c.buildActionsReady {
2143 return ErrBuildActionsNotReady
2144 }
2145
2146 nw := newNinjaWriter(w)
2147
2148 err := c.writeBuildFileHeader(nw)
2149 if err != nil {
2150 return err
2151 }
2152
2153 err = c.writeNinjaRequiredVersion(nw)
2154 if err != nil {
2155 return err
2156 }
2157
2158 // TODO: Group the globals by package.
2159
2160 err = c.writeGlobalVariables(nw)
2161 if err != nil {
2162 return err
2163 }
2164
2165 err = c.writeGlobalPools(nw)
2166 if err != nil {
2167 return err
2168 }
2169
2170 err = c.writeBuildDir(nw)
2171 if err != nil {
2172 return err
2173 }
2174
2175 err = c.writeGlobalRules(nw)
2176 if err != nil {
2177 return err
2178 }
2179
2180 err = c.writeAllModuleActions(nw)
2181 if err != nil {
2182 return err
2183 }
2184
2185 err = c.writeAllSingletonActions(nw)
2186 if err != nil {
2187 return err
2188 }
2189
2190 return nil
2191}
2192
Jamie Gennisc15544d2014-09-24 20:26:52 -07002193type pkgAssociation struct {
2194 PkgName string
2195 PkgPath string
2196}
2197
2198type pkgAssociationSorter struct {
2199 pkgs []pkgAssociation
2200}
2201
2202func (s *pkgAssociationSorter) Len() int {
2203 return len(s.pkgs)
2204}
2205
2206func (s *pkgAssociationSorter) Less(i, j int) bool {
2207 iName := s.pkgs[i].PkgName
2208 jName := s.pkgs[j].PkgName
2209 return iName < jName
2210}
2211
2212func (s *pkgAssociationSorter) Swap(i, j int) {
2213 s.pkgs[i], s.pkgs[j] = s.pkgs[j], s.pkgs[i]
2214}
2215
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002216func (c *Context) writeBuildFileHeader(nw *ninjaWriter) error {
2217 headerTemplate := template.New("fileHeader")
2218 _, err := headerTemplate.Parse(fileHeaderTemplate)
2219 if err != nil {
2220 // This is a programming error.
2221 panic(err)
2222 }
2223
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002224 var pkgs []pkgAssociation
2225 maxNameLen := 0
2226 for pkg, name := range c.pkgNames {
2227 pkgs = append(pkgs, pkgAssociation{
2228 PkgName: name,
2229 PkgPath: pkg.pkgPath,
2230 })
2231 if len(name) > maxNameLen {
2232 maxNameLen = len(name)
2233 }
2234 }
2235
2236 for i := range pkgs {
2237 pkgs[i].PkgName += strings.Repeat(" ", maxNameLen-len(pkgs[i].PkgName))
2238 }
2239
Jamie Gennisc15544d2014-09-24 20:26:52 -07002240 sort.Sort(&pkgAssociationSorter{pkgs})
2241
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002242 params := map[string]interface{}{
2243 "Pkgs": pkgs,
2244 }
2245
2246 buf := bytes.NewBuffer(nil)
2247 err = headerTemplate.Execute(buf, params)
2248 if err != nil {
2249 return err
2250 }
2251
2252 return nw.Comment(buf.String())
2253}
2254
2255func (c *Context) writeNinjaRequiredVersion(nw *ninjaWriter) error {
2256 value := fmt.Sprintf("%d.%d.%d", c.requiredNinjaMajor, c.requiredNinjaMinor,
2257 c.requiredNinjaMicro)
2258
2259 err := nw.Assign("ninja_required_version", value)
2260 if err != nil {
2261 return err
2262 }
2263
2264 return nw.BlankLine()
2265}
2266
2267func (c *Context) writeBuildDir(nw *ninjaWriter) error {
2268 if c.buildDir != nil {
2269 err := nw.Assign("builddir", c.buildDir.Value(c.pkgNames))
2270 if err != nil {
2271 return err
2272 }
2273
2274 err = nw.BlankLine()
2275 if err != nil {
2276 return err
2277 }
2278 }
2279 return nil
2280}
2281
Jamie Gennisc15544d2014-09-24 20:26:52 -07002282type globalEntity interface {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002283 fullName(pkgNames map[*PackageContext]string) string
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002284}
2285
Jamie Gennisc15544d2014-09-24 20:26:52 -07002286type globalEntitySorter struct {
Jamie Gennis2fb20952014-10-03 02:49:58 -07002287 pkgNames map[*PackageContext]string
Jamie Gennisc15544d2014-09-24 20:26:52 -07002288 entities []globalEntity
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002289}
2290
Jamie Gennisc15544d2014-09-24 20:26:52 -07002291func (s *globalEntitySorter) Len() int {
2292 return len(s.entities)
2293}
2294
2295func (s *globalEntitySorter) Less(i, j int) bool {
2296 iName := s.entities[i].fullName(s.pkgNames)
2297 jName := s.entities[j].fullName(s.pkgNames)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002298 return iName < jName
2299}
2300
Jamie Gennisc15544d2014-09-24 20:26:52 -07002301func (s *globalEntitySorter) Swap(i, j int) {
2302 s.entities[i], s.entities[j] = s.entities[j], s.entities[i]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002303}
2304
2305func (c *Context) writeGlobalVariables(nw *ninjaWriter) error {
2306 visited := make(map[Variable]bool)
2307
2308 var walk func(v Variable) error
2309 walk = func(v Variable) error {
2310 visited[v] = true
2311
2312 // First visit variables on which this variable depends.
2313 value := c.globalVariables[v]
2314 for _, dep := range value.variables {
2315 if !visited[dep] {
2316 err := walk(dep)
2317 if err != nil {
2318 return err
2319 }
2320 }
2321 }
2322
2323 err := nw.Assign(v.fullName(c.pkgNames), value.Value(c.pkgNames))
2324 if err != nil {
2325 return err
2326 }
2327
2328 err = nw.BlankLine()
2329 if err != nil {
2330 return err
2331 }
2332
2333 return nil
2334 }
2335
Jamie Gennisc15544d2014-09-24 20:26:52 -07002336 globalVariables := make([]globalEntity, 0, len(c.globalVariables))
2337 for variable := range c.globalVariables {
2338 globalVariables = append(globalVariables, variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002339 }
2340
Jamie Gennisc15544d2014-09-24 20:26:52 -07002341 sort.Sort(&globalEntitySorter{c.pkgNames, globalVariables})
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002342
Jamie Gennisc15544d2014-09-24 20:26:52 -07002343 for _, entity := range globalVariables {
2344 v := entity.(Variable)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002345 if !visited[v] {
2346 err := walk(v)
2347 if err != nil {
2348 return nil
2349 }
2350 }
2351 }
2352
2353 return nil
2354}
2355
2356func (c *Context) writeGlobalPools(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002357 globalPools := make([]globalEntity, 0, len(c.globalPools))
2358 for pool := range c.globalPools {
2359 globalPools = append(globalPools, pool)
2360 }
2361
2362 sort.Sort(&globalEntitySorter{c.pkgNames, globalPools})
2363
2364 for _, entity := range globalPools {
2365 pool := entity.(Pool)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002366 name := pool.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002367 def := c.globalPools[pool]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002368 err := def.WriteTo(nw, name)
2369 if err != nil {
2370 return err
2371 }
2372
2373 err = nw.BlankLine()
2374 if err != nil {
2375 return err
2376 }
2377 }
2378
2379 return nil
2380}
2381
2382func (c *Context) writeGlobalRules(nw *ninjaWriter) error {
Jamie Gennisc15544d2014-09-24 20:26:52 -07002383 globalRules := make([]globalEntity, 0, len(c.globalRules))
2384 for rule := range c.globalRules {
2385 globalRules = append(globalRules, rule)
2386 }
2387
2388 sort.Sort(&globalEntitySorter{c.pkgNames, globalRules})
2389
2390 for _, entity := range globalRules {
2391 rule := entity.(Rule)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002392 name := rule.fullName(c.pkgNames)
Jamie Gennisc15544d2014-09-24 20:26:52 -07002393 def := c.globalRules[rule]
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002394 err := def.WriteTo(nw, name, c.pkgNames)
2395 if err != nil {
2396 return err
2397 }
2398
2399 err = nw.BlankLine()
2400 if err != nil {
2401 return err
2402 }
2403 }
2404
2405 return nil
2406}
2407
Colin Crossab6d7902015-03-11 16:17:52 -07002408type moduleSorter []*moduleInfo
Jamie Gennis86179fe2014-06-11 16:27:16 -07002409
Colin Crossab6d7902015-03-11 16:17:52 -07002410func (s moduleSorter) Len() int {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002411 return len(s)
2412}
2413
Colin Crossab6d7902015-03-11 16:17:52 -07002414func (s moduleSorter) Less(i, j int) bool {
2415 iName := s[i].properties.Name
2416 jName := s[j].properties.Name
2417 if iName == jName {
Colin Cross65569e42015-03-10 20:08:19 -07002418 iName = s[i].variantName
2419 jName = s[j].variantName
Colin Crossab6d7902015-03-11 16:17:52 -07002420 }
Jamie Gennis86179fe2014-06-11 16:27:16 -07002421 return iName < jName
2422}
2423
Colin Crossab6d7902015-03-11 16:17:52 -07002424func (s moduleSorter) Swap(i, j int) {
Jamie Gennis86179fe2014-06-11 16:27:16 -07002425 s[i], s[j] = s[j], s[i]
2426}
2427
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002428func (c *Context) writeAllModuleActions(nw *ninjaWriter) error {
2429 headerTemplate := template.New("moduleHeader")
2430 _, err := headerTemplate.Parse(moduleHeaderTemplate)
2431 if err != nil {
2432 // This is a programming error.
2433 panic(err)
2434 }
2435
Colin Crossab6d7902015-03-11 16:17:52 -07002436 modules := make([]*moduleInfo, 0, len(c.moduleInfo))
2437 for _, module := range c.moduleInfo {
2438 modules = append(modules, module)
Jamie Gennis86179fe2014-06-11 16:27:16 -07002439 }
Colin Crossab6d7902015-03-11 16:17:52 -07002440 sort.Sort(moduleSorter(modules))
Jamie Gennis86179fe2014-06-11 16:27:16 -07002441
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002442 buf := bytes.NewBuffer(nil)
2443
Colin Crossab6d7902015-03-11 16:17:52 -07002444 for _, module := range modules {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002445 if len(module.actionDefs.variables)+len(module.actionDefs.rules)+len(module.actionDefs.buildDefs) == 0 {
2446 continue
2447 }
2448
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002449 buf.Reset()
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002450
2451 // In order to make the bootstrap build manifest independent of the
2452 // build dir we need to output the Blueprints file locations in the
2453 // comments as paths relative to the source directory.
Colin Crossab6d7902015-03-11 16:17:52 -07002454 relPos := module.pos
2455 relPos.Filename = module.relBlueprintsFile
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002456
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002457 // Get the name and location of the factory function for the module.
Colin Crossab6d7902015-03-11 16:17:52 -07002458 factory := c.moduleFactories[module.typeName]
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002459 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2460 factoryName := factoryFunc.Name()
2461
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002462 infoMap := map[string]interface{}{
Colin Crossab6d7902015-03-11 16:17:52 -07002463 "properties": module.properties,
2464 "typeName": module.typeName,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002465 "goFactory": factoryName,
Jamie Gennis1ebd3b82014-06-04 15:33:08 -07002466 "pos": relPos,
Colin Cross65569e42015-03-10 20:08:19 -07002467 "variant": module.variantName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002468 }
2469 err = headerTemplate.Execute(buf, infoMap)
2470 if err != nil {
2471 return err
2472 }
2473
2474 err = nw.Comment(buf.String())
2475 if err != nil {
2476 return err
2477 }
2478
2479 err = nw.BlankLine()
2480 if err != nil {
2481 return err
2482 }
2483
Colin Crossab6d7902015-03-11 16:17:52 -07002484 err = c.writeLocalBuildActions(nw, &module.actionDefs)
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002485 if err != nil {
2486 return err
2487 }
2488
2489 err = nw.BlankLine()
2490 if err != nil {
2491 return err
2492 }
2493 }
2494
2495 return nil
2496}
2497
2498func (c *Context) writeAllSingletonActions(nw *ninjaWriter) error {
2499 headerTemplate := template.New("singletonHeader")
2500 _, err := headerTemplate.Parse(singletonHeaderTemplate)
2501 if err != nil {
2502 // This is a programming error.
2503 panic(err)
2504 }
2505
2506 buf := bytes.NewBuffer(nil)
2507
Yuchen Wub9103ef2015-08-25 17:58:17 -07002508 for _, info := range c.singletonInfo {
Dan Willemsen958b3ac2015-07-20 15:55:37 -07002509 if len(info.actionDefs.variables)+len(info.actionDefs.rules)+len(info.actionDefs.buildDefs) == 0 {
2510 continue
2511 }
2512
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002513 // Get the name of the factory function for the module.
2514 factory := info.factory
2515 factoryFunc := runtime.FuncForPC(reflect.ValueOf(factory).Pointer())
2516 factoryName := factoryFunc.Name()
2517
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002518 buf.Reset()
2519 infoMap := map[string]interface{}{
Yuchen Wub9103ef2015-08-25 17:58:17 -07002520 "name": info.name,
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002521 "goFactory": factoryName,
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002522 }
2523 err = headerTemplate.Execute(buf, infoMap)
2524 if err != nil {
2525 return err
2526 }
2527
2528 err = nw.Comment(buf.String())
2529 if err != nil {
2530 return err
2531 }
2532
2533 err = nw.BlankLine()
2534 if err != nil {
2535 return err
2536 }
2537
2538 err = c.writeLocalBuildActions(nw, &info.actionDefs)
2539 if err != nil {
2540 return err
2541 }
2542
2543 err = nw.BlankLine()
2544 if err != nil {
2545 return err
2546 }
2547 }
2548
2549 return nil
2550}
2551
2552func (c *Context) writeLocalBuildActions(nw *ninjaWriter,
2553 defs *localBuildActions) error {
2554
2555 // Write the local variable assignments.
2556 for _, v := range defs.variables {
2557 // A localVariable doesn't need the package names or config to
2558 // determine its name or value.
2559 name := v.fullName(nil)
2560 value, err := v.value(nil)
2561 if err != nil {
2562 panic(err)
2563 }
2564 err = nw.Assign(name, value.Value(c.pkgNames))
2565 if err != nil {
2566 return err
2567 }
2568 }
2569
2570 if len(defs.variables) > 0 {
2571 err := nw.BlankLine()
2572 if err != nil {
2573 return err
2574 }
2575 }
2576
2577 // Write the local rules.
2578 for _, r := range defs.rules {
2579 // A localRule doesn't need the package names or config to determine
2580 // its name or definition.
2581 name := r.fullName(nil)
2582 def, err := r.def(nil)
2583 if err != nil {
2584 panic(err)
2585 }
2586
2587 err = def.WriteTo(nw, name, c.pkgNames)
2588 if err != nil {
2589 return err
2590 }
2591
2592 err = nw.BlankLine()
2593 if err != nil {
2594 return err
2595 }
2596 }
2597
2598 // Write the build definitions.
2599 for _, buildDef := range defs.buildDefs {
2600 err := buildDef.WriteTo(nw, c.pkgNames)
2601 if err != nil {
2602 return err
2603 }
2604
2605 if len(buildDef.Args) > 0 {
2606 err = nw.BlankLine()
2607 if err != nil {
2608 return err
2609 }
2610 }
2611 }
2612
2613 return nil
2614}
2615
Colin Cross65569e42015-03-10 20:08:19 -07002616func beforeInModuleList(a, b *moduleInfo, list []*moduleInfo) bool {
2617 found := false
2618 for _, l := range list {
2619 if l == a {
2620 found = true
2621 } else if l == b {
2622 return found
2623 }
2624 }
2625
2626 missing := a
2627 if found {
2628 missing = b
2629 }
2630 panic(fmt.Errorf("element %v not found in list %v", missing, list))
2631}
2632
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002633var fileHeaderTemplate = `******************************************************************************
2634*** This file is generated and should not be edited ***
2635******************************************************************************
2636{{if .Pkgs}}
2637This file contains variables, rules, and pools with name prefixes indicating
2638they were generated by the following Go packages:
2639{{range .Pkgs}}
2640 {{.PkgName}} [from Go package {{.PkgPath}}]{{end}}{{end}}
2641
2642`
2643
2644var moduleHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2645Module: {{.properties.Name}}
Colin Crossab6d7902015-03-11 16:17:52 -07002646Variant: {{.variant}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002647Type: {{.typeName}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002648Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002649Defined: {{.pos}}
2650`
2651
2652var singletonHeaderTemplate = `# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2653Singleton: {{.name}}
Jamie Gennis7d5b2f82014-09-24 17:51:52 -07002654Factory: {{.goFactory}}
Jamie Gennis1bc967e2014-05-27 16:34:41 -07002655`