1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef TOOLS_GN_SCOPE_H_
6 #define TOOLS_GN_SCOPE_H_
11 #include "base/basictypes.h"
12 #include "base/containers/hash_tables.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/scoped_vector.h"
16 #include "tools/gn/err.h"
17 #include "tools/gn/pattern.h"
18 #include "tools/gn/source_dir.h"
19 #include "tools/gn/value.h"
21 class FunctionCallNode
;
29 // Scope for the script execution.
31 // Scopes are nested. Writing goes into the toplevel scope, reading checks
32 // values resursively down the stack until a match is found or there are no
33 // more containing scopes.
35 // A containing scope can be const or non-const. The const containing scope is
36 // used primarily to refer to the master build config which is shared across
37 // many invocations. A const containing scope, however, prevents us from
38 // marking variables "used" which prevents us from issuing errors on unused
39 // variables. So you should use a non-const containing scope whenever possible.
42 typedef base::hash_map
<base::StringPiece
, Value
> KeyValueMap
;
43 // Holds an owning list of Items.
44 typedef ScopedVector
<Item
> ItemVector
;
46 // Allows code to provide values for built-in variables. This class will
47 // automatically register itself on construction and deregister itself on
49 class ProgrammaticProvider
{
51 ProgrammaticProvider(Scope
* scope
) : scope_(scope
) {
52 scope_
->AddProvider(this);
54 ~ProgrammaticProvider() {
55 scope_
->RemoveProvider(this);
58 // Returns a non-null value if the given value can be programmatically
59 // generated, or NULL if there is none.
60 virtual const Value
* GetProgrammaticValue(
61 const base::StringPiece
& ident
) = 0;
67 // Options for configuring scope merges.
69 // Defaults to all false, which are the things least likely to cause errors.
71 : clobber_existing(false),
72 skip_private_vars(false),
76 // When set, all existing avlues in the destination scope will be
79 // When false, it will be an error to merge a variable into another scope
80 // where a variable with the same name is already set. The exception is
81 // if both of the variables have the same value (which happens if you
82 // somehow multiply import the same file, for example). This case will be
83 // ignored since there is nothing getting lost.
84 bool clobber_existing
;
86 // When true, private variables (names beginning with an underscore) will
87 // be copied to the destination scope. When false, private values will be
89 bool skip_private_vars
;
91 // When set, values copied to the destination scope will be marked as used
92 // so won't trigger an unused variable warning. You want this when doing an
93 // import, for example, or files that don't need a variable from the .gni
94 // file will throw an error.
98 // Creates an empty toplevel scope.
99 Scope(const Settings
* settings
);
101 // Creates a dependent scope.
102 Scope(Scope
* parent
);
103 Scope(const Scope
* parent
);
107 const Settings
* settings() const { return settings_
; }
109 // See the const_/mutable_containing_ var declaraions below. Yes, it's a
110 // bit weird that we can have a const pointer to the "mutable" one.
111 Scope
* mutable_containing() { return mutable_containing_
; }
112 const Scope
* mutable_containing() const { return mutable_containing_
; }
113 const Scope
* const_containing() const { return const_containing_
; }
114 const Scope
* containing() const {
115 return mutable_containing_
? mutable_containing_
: const_containing_
;
118 // Returns NULL if there's no such value.
120 // counts_as_used should be set if the variable is being read in a way that
121 // should count for unused variable checking.
122 const Value
* GetValue(const base::StringPiece
& ident
,
123 bool counts_as_used
);
124 const Value
* GetValue(const base::StringPiece
& ident
) const;
126 // Returns the requested value as a mutable one if possible. If the value
127 // is not found in a mutable scope, then returns null. Note that the value
128 // could still exist in a const scope, so GetValue() could still return
129 // non-null in this case.
131 // Say you have a local scope that then refers to the const root scope from
132 // the master build config. You can't change the values from the master
133 // build config (it's read-only so it can be read from multiple threads
134 // without locking). Read-only operations would work on values from the root
135 // scope, but write operations would only work on values in the derived
138 // Be careful when calling this. It's not normally correct to modify values,
139 // but you should instead do a new Set each time.
141 // Consider this code:
146 // The 6 should get set on the nested scope rather than modify the value
148 Value
* GetMutableValue(const base::StringPiece
& ident
, bool counts_as_used
);
150 // Same as GetValue, but if the value exists in a parent scope, we'll copy
151 // it to the current scope. If the return value is non-null, the value is
152 // guaranteed to be set in the current scope. Generatlly this will be used
153 // if the calling code is planning on modifying the value in-place.
155 // Since this is used when doing read-modifies, we never count this access
156 // as reading the variable, since we assume it will be written to.
157 Value
* GetValueForcedToCurrentScope(const base::StringPiece
& ident
,
158 const ParseNode
* set_node
);
160 // The set_node indicates the statement that caused the set, for displaying
161 // errors later. Returns a pointer to the value in the current scope (a copy
162 // is made for storage).
163 Value
* SetValue(const base::StringPiece
& ident
,
165 const ParseNode
* set_node
);
167 // Removes the value with the given identifier if it exists on the current
168 // scope. This does not search recursive scopes. Does nothing if not found.
169 void RemoveIdentifier(const base::StringPiece
& ident
);
171 // Removes from this scope all identifiers and templates that are considered
173 void RemovePrivateIdentifiers();
175 // Templates associated with this scope. A template can only be set once, so
176 // AddTemplate will fail and return false if a rule with that name already
177 // exists. GetTemplate returns NULL if the rule doesn't exist, and it will
178 // check all containing scoped rescursively.
179 bool AddTemplate(const std::string
& name
, const Template
* templ
);
180 const Template
* GetTemplate(const std::string
& name
) const;
182 // Marks the given identifier as (un)used in the current scope.
183 void MarkUsed(const base::StringPiece
& ident
);
184 void MarkUnused(const base::StringPiece
& ident
);
186 // Checks to see if the scope has a var set that hasn't been used. This is
187 // called before replacing the var with a different one. It does not check
188 // containing scopes.
190 // If the identifier is present but hasnn't been used, return true.
191 bool IsSetButUnused(const base::StringPiece
& ident
) const;
193 // Checks the scope to see if any values were set but not used, and fills in
194 // the error and returns false if they were.
195 bool CheckForUnusedVars(Err
* err
) const;
197 // Returns all values set in the current scope, without going to the parent
199 void GetCurrentScopeValues(KeyValueMap
* output
) const;
201 // Copies this scope's values into the destination. Values from the
202 // containing scope(s) (normally shadowed into the current one) will not be
203 // copied, neither will the reference to the containing scope (this is why
204 // it's "non-recursive").
206 // This is used in different contexts. When generating the error, the given
207 // parse node will be blamed, and the given desc will be used to describe
208 // the operation that doesn't support doing this. For example, desc_for_err
209 // would be "import" when doing an import, and the error string would say
210 // something like "The import contains...".
211 bool NonRecursiveMergeTo(Scope
* dest
,
212 const MergeOptions
& options
,
213 const ParseNode
* node_for_err
,
214 const char* desc_for_err
,
217 // Constructs a scope that is a copy of the current one. Nested scopes will
218 // be collapsed until we reach a const containing scope. Private values will
219 // be included. The resulting closure will reference the const containing
220 // scope as its containing scope (since we assume the const scope won't
221 // change, we don't have to copy its values).
222 scoped_ptr
<Scope
> MakeClosure() const;
224 // Makes an empty scope with the given name. Returns NULL if the name is
226 Scope
* MakeTargetDefaults(const std::string
& target_type
);
228 // Gets the scope associated with the given target name, or null if it hasn't
230 const Scope
* GetTargetDefaults(const std::string
& target_type
) const;
232 // Filter to apply when the sources variable is assigned. May return NULL.
233 const PatternList
* GetSourcesAssignmentFilter() const;
234 void set_sources_assignment_filter(
235 scoped_ptr
<PatternList
> f
) {
236 sources_assignment_filter_
= f
.Pass();
239 // Indicates if we're currently processing the build configuration file.
240 // This is true when processing the config file for any toolchain.
242 // To set or clear the flag, it must currently be in the opposite state in
243 // the current scope. Note that querying the state of the flag recursively
244 // checks all containing scopes until it reaches the top or finds the flag
246 void SetProcessingBuildConfig();
247 void ClearProcessingBuildConfig();
248 bool IsProcessingBuildConfig() const;
250 // Indicates if we're currently processing an import file.
252 // See SetProcessingBaseConfig for how flags work.
253 void SetProcessingImport();
254 void ClearProcessingImport();
255 bool IsProcessingImport() const;
257 // The source directory associated with this scope. This will check embedded
258 // scopes until it finds a nonempty source directory. This will default to
259 // an empty dir if no containing scope has a source dir set.
260 const SourceDir
& GetSourceDir() const;
261 void set_source_dir(const SourceDir
& d
) { source_dir_
= d
; }
263 // The item collector is where Items (Targets, Configs, etc.) go that have
264 // been defined. If a scope can generate items, this non-owning pointer will
265 // point to the storage for such items. The creator of this scope will be
266 // responsible for setting up the collector and then dealing with the
267 // collected items once execution of the context is complete.
269 // The items in a scope are collected as we go and then dispatched at the end
270 // of execution of a scope so that we can query the previously-generated
271 // targets (like getting the outputs).
273 // This can be null if the current scope can not generate items (like for
274 // imports and such).
276 // When retrieving the collector, the non-const scopes are recursively
277 // queried. The collector is not copied for closures, etc.
278 void set_item_collector(ItemVector
* collector
) {
279 item_collector_
= collector
;
281 ItemVector
* GetItemCollector();
283 // Properties are opaque pointers that code can use to set state on a Scope
284 // that it can retrieve later.
286 // The key should be a pointer to some use-case-specific object (to avoid
287 // collisions, otherwise it doesn't matter). Memory management is up to the
288 // setter. Setting the value to NULL will delete the property.
290 // Getting a property recursively searches all scopes, and the optional
291 // |found_on_scope| variable will be filled with the actual scope containing
292 // the key (if the pointer is non-NULL).
293 void SetProperty(const void* key
, void* value
);
294 void* GetProperty(const void* key
, const Scope
** found_on_scope
) const;
297 friend class ProgrammaticProvider
;
300 Record() : used(false) {}
301 Record(const Value
& v
) : used(false), value(v
) {}
303 bool used
; // Set to true when the variable is used.
307 void AddProvider(ProgrammaticProvider
* p
);
308 void RemoveProvider(ProgrammaticProvider
* p
);
310 // Scopes can have no containing scope (both null), a mutable containing
311 // scope, or a const containing scope. The reason is that when we're doing
312 // a new target, we want to refer to the base_config scope which will be read
313 // by multiple threads at the same time, so we REALLY want it to be const.
314 // When you jsut do a nested {}, however, we sometimes want to be able to
315 // change things (especially marking unused vars).
316 const Scope
* const_containing_
;
317 Scope
* mutable_containing_
;
319 const Settings
* settings_
;
321 // Bits set for different modes. See the flag definitions in the .cc file
323 unsigned mode_flags_
;
325 typedef base::hash_map
<base::StringPiece
, Record
> RecordMap
;
328 // Owning pointers. Note that this can't use string pieces since the names
329 // are constructed from Values which might be deallocated before this goes
331 typedef base::hash_map
<std::string
, Scope
*> NamedScopeMap
;
332 NamedScopeMap target_defaults_
;
334 // Null indicates not set and that we should fallback to the containing
336 scoped_ptr
<PatternList
> sources_assignment_filter_
;
338 // Owning pointers, must be deleted.
339 typedef std::map
<std::string
, scoped_refptr
<const Template
> > TemplateMap
;
340 TemplateMap templates_
;
342 ItemVector
* item_collector_
;
344 // Opaque pointers. See SetProperty() above.
345 typedef std::map
<const void*, void*> PropertyMap
;
346 PropertyMap properties_
;
348 typedef std::set
<ProgrammaticProvider
*> ProviderSet
;
349 ProviderSet programmatic_providers_
;
351 SourceDir source_dir_
;
353 DISALLOW_COPY_AND_ASSIGN(Scope
);
356 #endif // TOOLS_GN_SCOPE_H_