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