• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/scoped_ptr.h"
14 #include "tools/gn/err.h"
15 #include "tools/gn/pattern.h"
16 #include "tools/gn/source_dir.h"
17 #include "tools/gn/value.h"
18 
19 class FunctionCallNode;
20 class ImportManager;
21 class ParseNode;
22 class Settings;
23 class TargetManager;
24 
25 // Scope for the script execution.
26 //
27 // Scopes are nested. Writing goes into the toplevel scope, reading checks
28 // values resursively down the stack until a match is found or there are no
29 // more containing scopes.
30 //
31 // A containing scope can be const or non-const. The const containing scope is
32 // used primarily to refer to the master build config which is shared across
33 // many invocations. A const containing scope, however, prevents us from
34 // marking variables "used" which prevents us from issuing errors on unused
35 // variables. So you should use a non-const containing scope whenever possible.
36 class Scope {
37  public:
38   typedef base::hash_map<base::StringPiece, Value> KeyValueMap;
39 
40   // Allows code to provide values for built-in variables. This class will
41   // automatically register itself on construction and deregister itself on
42   // destruction.
43   class ProgrammaticProvider {
44    public:
ProgrammaticProvider(Scope * scope)45     ProgrammaticProvider(Scope* scope) : scope_(scope) {
46       scope_->AddProvider(this);
47     }
~ProgrammaticProvider()48     ~ProgrammaticProvider() {
49       scope_->RemoveProvider(this);
50     }
51 
52     // Returns a non-null value if the given value can be programmatically
53     // generated, or NULL if there is none.
54     virtual const Value* GetProgrammaticValue(
55         const base::StringPiece& ident) = 0;
56 
57    protected:
58     Scope* scope_;
59   };
60 
61   // Creates an empty toplevel scope.
62   Scope(const Settings* settings);
63 
64   // Creates a dependent scope.
65   Scope(Scope* parent);
66   Scope(const Scope* parent);
67 
68   ~Scope();
69 
settings()70   const Settings* settings() const { return settings_; }
71 
72   // See the const_/mutable_containing_ var declaraions below. Yes, it's a
73   // bit weird that we can have a const pointer to the "mutable" one.
mutable_containing()74   Scope* mutable_containing() { return mutable_containing_; }
mutable_containing()75   const Scope* mutable_containing() const { return mutable_containing_; }
const_containing()76   const Scope* const_containing() const { return const_containing_; }
containing()77   const Scope* containing() const {
78     return mutable_containing_ ? mutable_containing_ : const_containing_;
79   }
80 
81   // Returns NULL if there's no such value.
82   //
83   // counts_as_used should be set if the variable is being read in a way that
84   // should count for unused variable checking.
85   const Value* GetValue(const base::StringPiece& ident,
86                         bool counts_as_used);
87   const Value* GetValue(const base::StringPiece& ident) const;
88 
89   // Same as GetValue, but if the value exists in a parent scope, we'll copy
90   // it to the current scope. If the return value is non-null, the value is
91   // guaranteed to be set in the current scope. Generatlly this will be used
92   // if the calling code is planning on modifying the value in-place.
93   //
94   // Since this is used when doing read-modifies, we never count this access
95   // as reading the variable, since we assume it will be written to.
96   Value* GetValueForcedToCurrentScope(const base::StringPiece& ident,
97                                       const ParseNode* set_node);
98 
99   // The set_node indicates the statement that caused the set, for displaying
100   // errors later. Returns a pointer to the value in the current scope (a copy
101   // is made for storage).
102   Value* SetValue(const base::StringPiece& ident,
103                   const Value& v,
104                   const ParseNode* set_node);
105 
106   // Templates associated with this scope. A template can only be set once, so
107   // AddTemplate will fail and return NULL if a rule with that name already
108   // exists. GetTemplate returns NULL if the rule doesn't exist, and it will
109   // check all containing scoped rescursively.
110   bool AddTemplate(const std::string& name, const FunctionCallNode* decl);
111   const FunctionCallNode* GetTemplate(const std::string& name) const;
112 
113   // Marks the given identifier as (un)used in the current scope.
114   void MarkUsed(const base::StringPiece& ident);
115   void MarkUnused(const base::StringPiece& ident);
116 
117   // Checks to see if the scope has a var set that hasn't been used. This is
118   // called before replacing the var with a different one. It does not check
119   // containing scopes.
120   //
121   // If the identifier is present but hasnn't been used, return true.
122   bool IsSetButUnused(const base::StringPiece& ident) const;
123 
124   // Checks the scope to see if any values were set but not used, and fills in
125   // the error and returns false if they were.
126   bool CheckForUnusedVars(Err* err) const;
127 
128   // Returns all values set in the current scope, without going to the parent
129   // scopes.
130   void GetCurrentScopeValues(KeyValueMap* output) const;
131 
132   // Copies this scope's values into the destination. Values from the
133   // containing scope(s) (normally shadowed into the current one) will not be
134   // copied, neither will the reference to the containing scope (this is why
135   // it's "non-recursive").
136   //
137   // It is an error to merge a variable into a scope that already has something
138   // with that name in scope (meaning in that scope or in any of its containing
139   // scopes). If this happens, the error will be set and the function will
140   // return false.
141   //
142   // This is used in different contexts. When generating the error, the given
143   // parse node will be blamed, and the given desc will be used to describe
144   // the operation that doesn't support doing this. For example, desc_for_err
145   // would be "import" when doing an import, and the error string would say
146   // something like "The import contains...".
147   bool NonRecursiveMergeTo(Scope* dest,
148                            const ParseNode* node_for_err,
149                            const char* desc_for_err,
150                            Err* err) const;
151 
152   // Makes an empty scope with the given name. Returns NULL if the name is
153   // already set.
154   Scope* MakeTargetDefaults(const std::string& target_type);
155 
156   // Gets the scope associated with the given target name, or null if it hasn't
157   // been set.
158   const Scope* GetTargetDefaults(const std::string& target_type) const;
159 
160   // Filter to apply when the sources variable is assigned. May return NULL.
161   const PatternList* GetSourcesAssignmentFilter() const;
set_sources_assignment_filter(scoped_ptr<PatternList> f)162   void set_sources_assignment_filter(
163       scoped_ptr<PatternList> f) {
164     sources_assignment_filter_ = f.Pass();
165   }
166 
167   // Indicates if we're currently processing the build configuration file.
168   // This is true when processing the config file for any toolchain.
169   //
170   // To set or clear the flag, it must currently be in the opposite state in
171   // the current scope. Note that querying the state of the flag recursively
172   // checks all containing scopes until it reaches the top or finds the flag
173   // set.
174   void SetProcessingBuildConfig();
175   void ClearProcessingBuildConfig();
176   bool IsProcessingBuildConfig() const;
177 
178   // Indicates if we're currently processing an import file.
179   //
180   // See SetProcessingBaseConfig for how flags work.
181   void SetProcessingImport();
182   void ClearProcessingImport();
183   bool IsProcessingImport() const;
184 
185   // The source directory associated with this scope. This will check embedded
186   // scopes until it finds a nonempty source directory. This will default to
187   // an empty dir if no containing scope has a source dir set.
188   const SourceDir& GetSourceDir() const;
set_source_dir(const SourceDir & d)189   void set_source_dir(const SourceDir& d) { source_dir_ = d; }
190 
191   // Properties are opaque pointers that code can use to set state on a Scope
192   // that it can retrieve later.
193   //
194   // The key should be a pointer to some use-case-specific object (to avoid
195   // collisions, otherwise it doesn't matter). Memory management is up to the
196   // setter. Setting the value to NULL will delete the property.
197   //
198   // Getting a property recursively searches all scopes, and the optional
199   // |found_on_scope| variable will be filled with the actual scope containing
200   // the key (if the pointer is non-NULL).
201   void SetProperty(const void* key, void* value);
202   void* GetProperty(const void* key, const Scope** found_on_scope) const;
203 
204  private:
205   friend class ProgrammaticProvider;
206 
207   struct Record {
RecordRecord208     Record() : used(false) {}
RecordRecord209     Record(const Value& v) : used(false), value(v) {}
210 
211     bool used;  // Set to true when the variable is used.
212     Value value;
213   };
214 
215   void AddProvider(ProgrammaticProvider* p);
216   void RemoveProvider(ProgrammaticProvider* p);
217 
218   // Scopes can have no containing scope (both null), a mutable containing
219   // scope, or a const containing scope. The reason is that when we're doing
220   // a new target, we want to refer to the base_config scope which will be read
221   // by multiple threads at the same time, so we REALLY want it to be const.
222   // When you jsut do a nested {}, however, we sometimes want to be able to
223   // change things (especially marking unused vars).
224   const Scope* const_containing_;
225   Scope* mutable_containing_;
226 
227   const Settings* settings_;
228 
229   // Bits set for different modes. See the flag definitions in the .cc file
230   // for more.
231   unsigned mode_flags_;
232 
233   typedef base::hash_map<base::StringPiece, Record> RecordMap;
234   RecordMap values_;
235 
236   // Owning pointers. Note that this can't use string pieces since the names
237   // are constructed from Values which might be deallocated before this goes
238   // out of scope.
239   typedef base::hash_map<std::string, Scope*> NamedScopeMap;
240   NamedScopeMap target_defaults_;
241 
242   // Null indicates not set and that we should fallback to the containing
243   // scope's filter.
244   scoped_ptr<PatternList> sources_assignment_filter_;
245 
246   // Non-owning pointers, the function calls are owned by the input file which
247   // should be kept around by the input file manager.
248   typedef std::map<std::string, const FunctionCallNode*> TemplateMap;
249   TemplateMap templates_;
250 
251   // Opaque pointers. See SetProperty() above.
252   typedef std::map<const void*, void*> PropertyMap;
253   PropertyMap properties_;
254 
255   typedef std::set<ProgrammaticProvider*> ProviderSet;
256   ProviderSet programmatic_providers_;
257 
258   SourceDir source_dir_;
259 
260   DISALLOW_COPY_AND_ASSIGN(Scope);
261 };
262 
263 #endif  // TOOLS_GN_SCOPE_H_
264