• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2016 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_PARSE_NODE_VALUE_ADAPTER_H_
6 #define TOOLS_GN_PARSE_NODE_VALUE_ADAPTER_H_
7 
8 #include "base/macros.h"
9 #include "gn/value.h"
10 
11 class ParseNode;
12 
13 // Provides a means to convert a parse node to a value without causing a copy
14 // in the common case of an "Identifier" node. Normally to get a value from a
15 // parse node you have to call Execute(), and when an identifier is executed
16 // it just returns the current value of itself as a copy. But some variables
17 // are very large (lists of many strings for example).
18 //
19 // The reason you might not want to do this is that in the case of an
20 // identifier where the copy is optimized away, the origin will still be the
21 // original value. The result can be confusing because it will reference the
22 // original value rather than the place where the value was dereferenced, e.g.
23 // for a function call. The InitForType() function will verify type information
24 // and will fix up the origin so it's not confusing.
25 class ParseNodeValueAdapter {
26  public:
27   ParseNodeValueAdapter();
28   ~ParseNodeValueAdapter();
29 
get()30   const Value& get() {
31     if (ref_)
32       return *ref_;
33     return temporary_;
34   }
35 
36   // Initializes the adapter for the result of the given expression. Returns
37   // truen on success.
38   bool Init(Scope* scope, const ParseNode* node, Err* err);
39 
40   // Like Init() but additionally verifies that the type of the result matches.
41   bool InitForType(Scope* scope,
42                    const ParseNode* node,
43                    Value::Type type,
44                    Err* err);
45 
46  private:
47   // Holds either a reference to an existing item, or a temporary as a copy.
48   // If ref is non-null, it's valid, otherwise the temporary is used.
49   const Value* ref_;
50   Value temporary_;
51 
52   DISALLOW_COPY_AND_ASSIGN(ParseNodeValueAdapter);
53 };
54 
55 #endif  // TOOLS_GN_PARSE_NODE_VALUE_ADAPTER_H_
56