exclude PluginsFieldTrialTest.NoPrefLeftBehind from valgrind bot
[chromium-blink-merge.git] / tools / gn / scope.h
blob0b9bfbe48be1c3bf0dae3075ff434fc1b31c78cd
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_
8 #include <map>
9 #include <set>
11 #include "base/containers/hash_tables.h"
12 #include "base/macros.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;
22 class ImportManager;
23 class Item;
24 class ParseNode;
25 class Settings;
26 class TargetManager;
27 class Template;
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.
40 class Scope {
41 public:
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
48 // destruction.
49 class ProgrammaticProvider {
50 public:
51 explicit ProgrammaticProvider(Scope* scope) : scope_(scope) {
52 scope_->AddProvider(this);
54 virtual ~ProgrammaticProvider();
56 // Returns a non-null value if the given value can be programmatically
57 // generated, or NULL if there is none.
58 virtual const Value* GetProgrammaticValue(
59 const base::StringPiece& ident) = 0;
61 protected:
62 Scope* scope_;
65 // Options for configuring scope merges.
66 struct MergeOptions {
67 // Defaults to all false, which are the things least likely to cause errors.
68 MergeOptions()
69 : clobber_existing(false),
70 skip_private_vars(false),
71 mark_dest_used(false) {
74 // When set, all existing avlues in the destination scope will be
75 // overwritten.
77 // When false, it will be an error to merge a variable into another scope
78 // where a variable with the same name is already set. The exception is
79 // if both of the variables have the same value (which happens if you
80 // somehow multiply import the same file, for example). This case will be
81 // ignored since there is nothing getting lost.
82 bool clobber_existing;
84 // When true, private variables (names beginning with an underscore) will
85 // be copied to the destination scope. When false, private values will be
86 // skipped.
87 bool skip_private_vars;
89 // When set, values copied to the destination scope will be marked as used
90 // so won't trigger an unused variable warning. You want this when doing an
91 // import, for example, or files that don't need a variable from the .gni
92 // file will throw an error.
93 bool mark_dest_used;
96 // Creates an empty toplevel scope.
97 explicit Scope(const Settings* settings);
99 // Creates a dependent scope.
100 explicit Scope(Scope* parent);
101 explicit Scope(const Scope* parent);
103 ~Scope();
105 const Settings* settings() const { return settings_; }
107 // See the const_/mutable_containing_ var declaraions below. Yes, it's a
108 // bit weird that we can have a const pointer to the "mutable" one.
109 Scope* mutable_containing() { return mutable_containing_; }
110 const Scope* mutable_containing() const { return mutable_containing_; }
111 const Scope* const_containing() const { return const_containing_; }
112 const Scope* containing() const {
113 return mutable_containing_ ? mutable_containing_ : const_containing_;
116 // Returns NULL if there's no such value.
118 // counts_as_used should be set if the variable is being read in a way that
119 // should count for unused variable checking.
120 const Value* GetValue(const base::StringPiece& ident,
121 bool counts_as_used);
122 const Value* GetValue(const base::StringPiece& ident) const;
124 // Returns the requested value as a mutable one if possible. If the value
125 // is not found in a mutable scope, then returns null. Note that the value
126 // could still exist in a const scope, so GetValue() could still return
127 // non-null in this case.
129 // Say you have a local scope that then refers to the const root scope from
130 // the master build config. You can't change the values from the master
131 // build config (it's read-only so it can be read from multiple threads
132 // without locking). Read-only operations would work on values from the root
133 // scope, but write operations would only work on values in the derived
134 // scope(s).
136 // Be careful when calling this. It's not normally correct to modify values,
137 // but you should instead do a new Set each time.
139 // Consider this code:
140 // a = 5
141 // {
142 // a = 6
143 // }
144 // The 6 should get set on the nested scope rather than modify the value
145 // in the outer one.
146 Value* GetMutableValue(const base::StringPiece& ident, bool counts_as_used);
148 // Same as GetValue, but if the value exists in a parent scope, we'll copy
149 // it to the current scope. If the return value is non-null, the value is
150 // guaranteed to be set in the current scope. Generatlly this will be used
151 // if the calling code is planning on modifying the value in-place.
153 // Since this is used when doing read-modifies, we never count this access
154 // as reading the variable, since we assume it will be written to.
155 Value* GetValueForcedToCurrentScope(const base::StringPiece& ident,
156 const ParseNode* set_node);
158 // Returns the StringPiece used to identify the value. This string piece
159 // will have the same contents as "ident" passed in, but may point to a
160 // different underlying buffer. This is useful because this StringPiece is
161 // static and won't be deleted for the life of the program, so it can be used
162 // as keys in places that may outlive a temporary. It will return an empty
163 // string for programmatic and nonexistant values.
164 base::StringPiece GetStorageKey(const base::StringPiece& ident) const;
166 // The set_node indicates the statement that caused the set, for displaying
167 // errors later. Returns a pointer to the value in the current scope (a copy
168 // is made for storage).
169 Value* SetValue(const base::StringPiece& ident,
170 const Value& v,
171 const ParseNode* set_node);
173 // Removes the value with the given identifier if it exists on the current
174 // scope. This does not search recursive scopes. Does nothing if not found.
175 void RemoveIdentifier(const base::StringPiece& ident);
177 // Removes from this scope all identifiers and templates that are considered
178 // private.
179 void RemovePrivateIdentifiers();
181 // Templates associated with this scope. A template can only be set once, so
182 // AddTemplate will fail and return false if a rule with that name already
183 // exists. GetTemplate returns NULL if the rule doesn't exist, and it will
184 // check all containing scoped rescursively.
185 bool AddTemplate(const std::string& name, const Template* templ);
186 const Template* GetTemplate(const std::string& name) const;
188 // Marks the given identifier as (un)used in the current scope.
189 void MarkUsed(const base::StringPiece& ident);
190 void MarkAllUsed();
191 void MarkUnused(const base::StringPiece& ident);
193 // Checks to see if the scope has a var set that hasn't been used. This is
194 // called before replacing the var with a different one. It does not check
195 // containing scopes.
197 // If the identifier is present but hasnn't been used, return true.
198 bool IsSetButUnused(const base::StringPiece& ident) const;
200 // Checks the scope to see if any values were set but not used, and fills in
201 // the error and returns false if they were.
202 bool CheckForUnusedVars(Err* err) const;
204 // Returns all values set in the current scope, without going to the parent
205 // scopes.
206 void GetCurrentScopeValues(KeyValueMap* output) const;
208 // Copies this scope's values into the destination. Values from the
209 // containing scope(s) (normally shadowed into the current one) will not be
210 // copied, neither will the reference to the containing scope (this is why
211 // it's "non-recursive").
213 // This is used in different contexts. When generating the error, the given
214 // parse node will be blamed, and the given desc will be used to describe
215 // the operation that doesn't support doing this. For example, desc_for_err
216 // would be "import" when doing an import, and the error string would say
217 // something like "The import contains...".
218 bool NonRecursiveMergeTo(Scope* dest,
219 const MergeOptions& options,
220 const ParseNode* node_for_err,
221 const char* desc_for_err,
222 Err* err) const;
224 // Constructs a scope that is a copy of the current one. Nested scopes will
225 // be collapsed until we reach a const containing scope. Private values will
226 // be included. The resulting closure will reference the const containing
227 // scope as its containing scope (since we assume the const scope won't
228 // change, we don't have to copy its values).
229 scoped_ptr<Scope> MakeClosure() const;
231 // Makes an empty scope with the given name. Returns NULL if the name is
232 // already set.
233 Scope* MakeTargetDefaults(const std::string& target_type);
235 // Gets the scope associated with the given target name, or null if it hasn't
236 // been set.
237 const Scope* GetTargetDefaults(const std::string& target_type) const;
239 // Filter to apply when the sources variable is assigned. May return NULL.
240 const PatternList* GetSourcesAssignmentFilter() const;
241 void set_sources_assignment_filter(
242 scoped_ptr<PatternList> f) {
243 sources_assignment_filter_ = f.Pass();
246 // Indicates if we're currently processing the build configuration file.
247 // This is true when processing the config file for any toolchain.
249 // To set or clear the flag, it must currently be in the opposite state in
250 // the current scope. Note that querying the state of the flag recursively
251 // checks all containing scopes until it reaches the top or finds the flag
252 // set.
253 void SetProcessingBuildConfig();
254 void ClearProcessingBuildConfig();
255 bool IsProcessingBuildConfig() const;
257 // Indicates if we're currently processing an import file.
259 // See SetProcessingBaseConfig for how flags work.
260 void SetProcessingImport();
261 void ClearProcessingImport();
262 bool IsProcessingImport() const;
264 // The source directory associated with this scope. This will check embedded
265 // scopes until it finds a nonempty source directory. This will default to
266 // an empty dir if no containing scope has a source dir set.
267 const SourceDir& GetSourceDir() const;
268 void set_source_dir(const SourceDir& d) { source_dir_ = d; }
270 // The item collector is where Items (Targets, Configs, etc.) go that have
271 // been defined. If a scope can generate items, this non-owning pointer will
272 // point to the storage for such items. The creator of this scope will be
273 // responsible for setting up the collector and then dealing with the
274 // collected items once execution of the context is complete.
276 // The items in a scope are collected as we go and then dispatched at the end
277 // of execution of a scope so that we can query the previously-generated
278 // targets (like getting the outputs).
280 // This can be null if the current scope can not generate items (like for
281 // imports and such).
283 // When retrieving the collector, the non-const scopes are recursively
284 // queried. The collector is not copied for closures, etc.
285 void set_item_collector(ItemVector* collector) {
286 item_collector_ = collector;
288 ItemVector* GetItemCollector();
290 // Properties are opaque pointers that code can use to set state on a Scope
291 // that it can retrieve later.
293 // The key should be a pointer to some use-case-specific object (to avoid
294 // collisions, otherwise it doesn't matter). Memory management is up to the
295 // setter. Setting the value to NULL will delete the property.
297 // Getting a property recursively searches all scopes, and the optional
298 // |found_on_scope| variable will be filled with the actual scope containing
299 // the key (if the pointer is non-NULL).
300 void SetProperty(const void* key, void* value);
301 void* GetProperty(const void* key, const Scope** found_on_scope) const;
303 private:
304 friend class ProgrammaticProvider;
306 struct Record {
307 Record() : used(false) {}
308 explicit Record(const Value& v) : used(false), value(v) {}
310 bool used; // Set to true when the variable is used.
311 Value value;
314 void AddProvider(ProgrammaticProvider* p);
315 void RemoveProvider(ProgrammaticProvider* p);
317 // Scopes can have no containing scope (both null), a mutable containing
318 // scope, or a const containing scope. The reason is that when we're doing
319 // a new target, we want to refer to the base_config scope which will be read
320 // by multiple threads at the same time, so we REALLY want it to be const.
321 // When you jsut do a nested {}, however, we sometimes want to be able to
322 // change things (especially marking unused vars).
323 const Scope* const_containing_;
324 Scope* mutable_containing_;
326 const Settings* settings_;
328 // Bits set for different modes. See the flag definitions in the .cc file
329 // for more.
330 unsigned mode_flags_;
332 typedef base::hash_map<base::StringPiece, Record> RecordMap;
333 RecordMap values_;
335 // Owning pointers. Note that this can't use string pieces since the names
336 // are constructed from Values which might be deallocated before this goes
337 // out of scope.
338 typedef base::hash_map<std::string, Scope*> NamedScopeMap;
339 NamedScopeMap target_defaults_;
341 // Null indicates not set and that we should fallback to the containing
342 // scope's filter.
343 scoped_ptr<PatternList> sources_assignment_filter_;
345 // Owning pointers, must be deleted.
346 typedef std::map<std::string, scoped_refptr<const Template> > TemplateMap;
347 TemplateMap templates_;
349 ItemVector* item_collector_;
351 // Opaque pointers. See SetProperty() above.
352 typedef std::map<const void*, void*> PropertyMap;
353 PropertyMap properties_;
355 typedef std::set<ProgrammaticProvider*> ProviderSet;
356 ProviderSet programmatic_providers_;
358 SourceDir source_dir_;
360 DISALLOW_COPY_AND_ASSIGN(Scope);
363 #endif // TOOLS_GN_SCOPE_H_