Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / tools / gn / scope.h
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.
4
5 #ifndef TOOLS_GN_SCOPE_H_
6 #define TOOLS_GN_SCOPE_H_
7
8 #include <map>
9 #include <set>
10
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"
20
21 class FunctionCallNode;
22 class ImportManager;
23 class Item;
24 class ParseNode;
25 class Settings;
26 class TargetManager;
27 class Template;
28
29 // Scope for the script execution.
30 //
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.
34 //
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;
45
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     ProgrammaticProvider(Scope* scope) : scope_(scope) {
52       scope_->AddProvider(this);
53     }
54     ~ProgrammaticProvider() {
55       scope_->RemoveProvider(this);
56     }
57
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;
62
63    protected:
64     Scope* scope_;
65   };
66
67   // Options for configuring scope merges.
68   struct MergeOptions {
69     // Defaults to all false, which are the things least likely to cause errors.
70     MergeOptions()
71         : clobber_existing(false),
72           skip_private_vars(false),
73           mark_used(false) {
74     }
75
76     // When set, all existing avlues in the destination scope will be
77     // overwritten.
78     //
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;
85
86     // When true, private variables (names beginning with an underscore) will
87     // be copied to the destination scope. When false, private values will be
88     // skipped.
89     bool skip_private_vars;
90
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.
95     bool mark_used;
96   };
97
98   // Creates an empty toplevel scope.
99   Scope(const Settings* settings);
100
101   // Creates a dependent scope.
102   Scope(Scope* parent);
103   Scope(const Scope* parent);
104
105   ~Scope();
106
107   const Settings* settings() const { return settings_; }
108
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_;
116   }
117
118   // Returns NULL if there's no such value.
119   //
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;
125
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.
130   //
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
136   // scope(s).
137   //
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.
140   //
141   // Consider this code:
142   //   a = 5
143   //    {
144   //       a = 6
145   //    }
146   // The 6 should get set on the nested scope rather than modify the value
147   // in the outer one.
148   Value* GetMutableValue(const base::StringPiece& ident, bool counts_as_used);
149
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.
154   //
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);
159
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,
164                   const Value& v,
165                   const ParseNode* set_node);
166
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);
170
171   // Removes from this scope all identifiers and templates that are considered
172   // private.
173   void RemovePrivateIdentifiers();
174
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;
181
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);
185
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.
189   //
190   // If the identifier is present but hasnn't been used, return true.
191   bool IsSetButUnused(const base::StringPiece& ident) const;
192
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;
196
197   // Returns all values set in the current scope, without going to the parent
198   // scopes.
199   void GetCurrentScopeValues(KeyValueMap* output) const;
200
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").
205   //
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,
215                            Err* err) const;
216
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;
223
224   // Makes an empty scope with the given name. Returns NULL if the name is
225   // already set.
226   Scope* MakeTargetDefaults(const std::string& target_type);
227
228   // Gets the scope associated with the given target name, or null if it hasn't
229   // been set.
230   const Scope* GetTargetDefaults(const std::string& target_type) const;
231
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();
237   }
238
239   // Indicates if we're currently processing the build configuration file.
240   // This is true when processing the config file for any toolchain.
241   //
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
245   // set.
246   void SetProcessingBuildConfig();
247   void ClearProcessingBuildConfig();
248   bool IsProcessingBuildConfig() const;
249
250   // Indicates if we're currently processing an import file.
251   //
252   // See SetProcessingBaseConfig for how flags work.
253   void SetProcessingImport();
254   void ClearProcessingImport();
255   bool IsProcessingImport() const;
256
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; }
262
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.
268   //
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).
272   //
273   // This can be null if the current scope can not generate items (like for
274   // imports and such).
275   //
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;
280   }
281   ItemVector* GetItemCollector();
282
283   // Properties are opaque pointers that code can use to set state on a Scope
284   // that it can retrieve later.
285   //
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.
289   //
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;
295
296  private:
297   friend class ProgrammaticProvider;
298
299   struct Record {
300     Record() : used(false) {}
301     Record(const Value& v) : used(false), value(v) {}
302
303     bool used;  // Set to true when the variable is used.
304     Value value;
305   };
306
307   void AddProvider(ProgrammaticProvider* p);
308   void RemoveProvider(ProgrammaticProvider* p);
309
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_;
318
319   const Settings* settings_;
320
321   // Bits set for different modes. See the flag definitions in the .cc file
322   // for more.
323   unsigned mode_flags_;
324
325   typedef base::hash_map<base::StringPiece, Record> RecordMap;
326   RecordMap values_;
327
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
330   // out of scope.
331   typedef base::hash_map<std::string, Scope*> NamedScopeMap;
332   NamedScopeMap target_defaults_;
333
334   // Null indicates not set and that we should fallback to the containing
335   // scope's filter.
336   scoped_ptr<PatternList> sources_assignment_filter_;
337
338   // Owning pointers, must be deleted.
339   typedef std::map<std::string, scoped_refptr<const Template> > TemplateMap;
340   TemplateMap templates_;
341
342   ItemVector* item_collector_;
343
344   // Opaque pointers. See SetProperty() above.
345   typedef std::map<const void*, void*> PropertyMap;
346   PropertyMap properties_;
347
348   typedef std::set<ProgrammaticProvider*> ProviderSet;
349   ProviderSet programmatic_providers_;
350
351   SourceDir source_dir_;
352
353   DISALLOW_COPY_AND_ASSIGN(Scope);
354 };
355
356 #endif  // TOOLS_GN_SCOPE_H_