[Session restore] Rename group name Enabled to Restore.
[chromium-blink-merge.git] / tools / gn / scope.h
blobda3768bc13fa53cd45e29a480ec3602bec53400a
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/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;
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_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_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 // The set_node indicates the statement that caused the set, for displaying
159 // errors later. Returns a pointer to the value in the current scope (a copy
160 // is made for storage).
161 Value* SetValue(const base::StringPiece& ident,
162 const Value& v,
163 const ParseNode* set_node);
165 // Removes the value with the given identifier if it exists on the current
166 // scope. This does not search recursive scopes. Does nothing if not found.
167 void RemoveIdentifier(const base::StringPiece& ident);
169 // Removes from this scope all identifiers and templates that are considered
170 // private.
171 void RemovePrivateIdentifiers();
173 // Templates associated with this scope. A template can only be set once, so
174 // AddTemplate will fail and return false if a rule with that name already
175 // exists. GetTemplate returns NULL if the rule doesn't exist, and it will
176 // check all containing scoped rescursively.
177 bool AddTemplate(const std::string& name, const Template* templ);
178 const Template* GetTemplate(const std::string& name) const;
180 // Marks the given identifier as (un)used in the current scope.
181 void MarkUsed(const base::StringPiece& ident);
182 void MarkUnused(const base::StringPiece& ident);
184 // Checks to see if the scope has a var set that hasn't been used. This is
185 // called before replacing the var with a different one. It does not check
186 // containing scopes.
188 // If the identifier is present but hasnn't been used, return true.
189 bool IsSetButUnused(const base::StringPiece& ident) const;
191 // Checks the scope to see if any values were set but not used, and fills in
192 // the error and returns false if they were.
193 bool CheckForUnusedVars(Err* err) const;
195 // Returns all values set in the current scope, without going to the parent
196 // scopes.
197 void GetCurrentScopeValues(KeyValueMap* output) const;
199 // Copies this scope's values into the destination. Values from the
200 // containing scope(s) (normally shadowed into the current one) will not be
201 // copied, neither will the reference to the containing scope (this is why
202 // it's "non-recursive").
204 // This is used in different contexts. When generating the error, the given
205 // parse node will be blamed, and the given desc will be used to describe
206 // the operation that doesn't support doing this. For example, desc_for_err
207 // would be "import" when doing an import, and the error string would say
208 // something like "The import contains...".
209 bool NonRecursiveMergeTo(Scope* dest,
210 const MergeOptions& options,
211 const ParseNode* node_for_err,
212 const char* desc_for_err,
213 Err* err) const;
215 // Constructs a scope that is a copy of the current one. Nested scopes will
216 // be collapsed until we reach a const containing scope. Private values will
217 // be included. The resulting closure will reference the const containing
218 // scope as its containing scope (since we assume the const scope won't
219 // change, we don't have to copy its values).
220 scoped_ptr<Scope> MakeClosure() const;
222 // Makes an empty scope with the given name. Returns NULL if the name is
223 // already set.
224 Scope* MakeTargetDefaults(const std::string& target_type);
226 // Gets the scope associated with the given target name, or null if it hasn't
227 // been set.
228 const Scope* GetTargetDefaults(const std::string& target_type) const;
230 // Filter to apply when the sources variable is assigned. May return NULL.
231 const PatternList* GetSourcesAssignmentFilter() const;
232 void set_sources_assignment_filter(
233 scoped_ptr<PatternList> f) {
234 sources_assignment_filter_ = f.Pass();
237 // Indicates if we're currently processing the build configuration file.
238 // This is true when processing the config file for any toolchain.
240 // To set or clear the flag, it must currently be in the opposite state in
241 // the current scope. Note that querying the state of the flag recursively
242 // checks all containing scopes until it reaches the top or finds the flag
243 // set.
244 void SetProcessingBuildConfig();
245 void ClearProcessingBuildConfig();
246 bool IsProcessingBuildConfig() const;
248 // Indicates if we're currently processing an import file.
250 // See SetProcessingBaseConfig for how flags work.
251 void SetProcessingImport();
252 void ClearProcessingImport();
253 bool IsProcessingImport() const;
255 // The source directory associated with this scope. This will check embedded
256 // scopes until it finds a nonempty source directory. This will default to
257 // an empty dir if no containing scope has a source dir set.
258 const SourceDir& GetSourceDir() const;
259 void set_source_dir(const SourceDir& d) { source_dir_ = d; }
261 // The item collector is where Items (Targets, Configs, etc.) go that have
262 // been defined. If a scope can generate items, this non-owning pointer will
263 // point to the storage for such items. The creator of this scope will be
264 // responsible for setting up the collector and then dealing with the
265 // collected items once execution of the context is complete.
267 // The items in a scope are collected as we go and then dispatched at the end
268 // of execution of a scope so that we can query the previously-generated
269 // targets (like getting the outputs).
271 // This can be null if the current scope can not generate items (like for
272 // imports and such).
274 // When retrieving the collector, the non-const scopes are recursively
275 // queried. The collector is not copied for closures, etc.
276 void set_item_collector(ItemVector* collector) {
277 item_collector_ = collector;
279 ItemVector* GetItemCollector();
281 // Properties are opaque pointers that code can use to set state on a Scope
282 // that it can retrieve later.
284 // The key should be a pointer to some use-case-specific object (to avoid
285 // collisions, otherwise it doesn't matter). Memory management is up to the
286 // setter. Setting the value to NULL will delete the property.
288 // Getting a property recursively searches all scopes, and the optional
289 // |found_on_scope| variable will be filled with the actual scope containing
290 // the key (if the pointer is non-NULL).
291 void SetProperty(const void* key, void* value);
292 void* GetProperty(const void* key, const Scope** found_on_scope) const;
294 private:
295 friend class ProgrammaticProvider;
297 struct Record {
298 Record() : used(false) {}
299 explicit Record(const Value& v) : used(false), value(v) {}
301 bool used; // Set to true when the variable is used.
302 Value value;
305 void AddProvider(ProgrammaticProvider* p);
306 void RemoveProvider(ProgrammaticProvider* p);
308 // Scopes can have no containing scope (both null), a mutable containing
309 // scope, or a const containing scope. The reason is that when we're doing
310 // a new target, we want to refer to the base_config scope which will be read
311 // by multiple threads at the same time, so we REALLY want it to be const.
312 // When you jsut do a nested {}, however, we sometimes want to be able to
313 // change things (especially marking unused vars).
314 const Scope* const_containing_;
315 Scope* mutable_containing_;
317 const Settings* settings_;
319 // Bits set for different modes. See the flag definitions in the .cc file
320 // for more.
321 unsigned mode_flags_;
323 typedef base::hash_map<base::StringPiece, Record> RecordMap;
324 RecordMap values_;
326 // Owning pointers. Note that this can't use string pieces since the names
327 // are constructed from Values which might be deallocated before this goes
328 // out of scope.
329 typedef base::hash_map<std::string, Scope*> NamedScopeMap;
330 NamedScopeMap target_defaults_;
332 // Null indicates not set and that we should fallback to the containing
333 // scope's filter.
334 scoped_ptr<PatternList> sources_assignment_filter_;
336 // Owning pointers, must be deleted.
337 typedef std::map<std::string, scoped_refptr<const Template> > TemplateMap;
338 TemplateMap templates_;
340 ItemVector* item_collector_;
342 // Opaque pointers. See SetProperty() above.
343 typedef std::map<const void*, void*> PropertyMap;
344 PropertyMap properties_;
346 typedef std::set<ProgrammaticProvider*> ProviderSet;
347 ProviderSet programmatic_providers_;
349 SourceDir source_dir_;
351 DISALLOW_COPY_AND_ASSIGN(Scope);
354 #endif // TOOLS_GN_SCOPE_H_