Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(334)

Side by Side Diff: tools/gn/operators.cc

Issue 2187523003: Allow creation and modification of scopes in GN. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Cleanup Created 4 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "tools/gn/operators.h" 5 #include "tools/gn/operators.h"
6 6
7 #include <stddef.h> 7 #include <stddef.h>
8 #include <algorithm>
8 9
9 #include "base/strings/string_number_conversions.h" 10 #include "base/strings/string_number_conversions.h"
10 #include "tools/gn/err.h" 11 #include "tools/gn/err.h"
11 #include "tools/gn/parse_tree.h" 12 #include "tools/gn/parse_tree.h"
12 #include "tools/gn/scope.h" 13 #include "tools/gn/scope.h"
13 #include "tools/gn/token.h" 14 #include "tools/gn/token.h"
14 #include "tools/gn/value.h" 15 #include "tools/gn/value.h"
15 16
16 namespace { 17 namespace {
17 18
18 const char kSourcesName[] = "sources"; 19 const char kSourcesName[] = "sources";
19 20
20 // Applies the sources assignment filter from the given scope to each element 21 // Helper class used for assignment operations: =, +=, and -= to generalize
21 // of source (can be a list or a string), appending it to dest if it doesn't 22 // writing to various types of destinations.
22 // match. 23 class ValueDestination {
23 void AppendFilteredSourcesToValue(const Scope* scope, 24 public:
24 const Value& source, 25 ValueDestination();
25 Value* dest) { 26
26 const PatternList* filter = scope->GetSourcesAssignmentFilter(); 27 bool Init(Scope* exec_scope,
27 28 const ParseNode* dest,
28 if (source.type() == Value::STRING) { 29 const BinaryOpNode* op_node,
29 if (!filter || filter->is_empty() || 30 Err* err);
30 !filter->MatchesValue(source)) 31
31 dest->list_value().push_back(source); 32 // Returns the value in the destination scope if it already exists, or null
32 return; 33 // if it doesn't. This is for validation and does not count as a "use".
33 } 34 // Other nested scopes will be searched.
34 if (source.type() != Value::LIST) { 35 const Value* GetExistingValue() const;
35 // Any non-list and non-string being added to a list can just get appended, 36
36 // we're not going to filter it. 37 // Returns an existing version of the output if it can be modified. This will
37 dest->list_value().push_back(source); 38 // not search nested scopes since writes only go into the current scope.
38 return; 39 // Returns null if the value does not exist, or is not in the current scope.
39 } 40 // This is for implementing += and -=.
40 41 //
41 if (!filter || filter->is_empty()) { 42 // If it exists, this will mark the origin of the value to be the passed-in
42 // No filter, append everything. 43 // node, and the value will be also marked unused (if possible) under the
43 for (const auto& source_entry : source.list_value()) 44 // assumption that it will be modified in-place.
44 dest->list_value().push_back(source_entry); 45 Value* GetExistingMutableValue(const ParseNode* origin);
Dirk Pranke 2016/08/03 23:06:19 Nit: would GetExistingValueIfMutable() be a better
brettw 2016/08/03 23:23:00 Done.
45 return; 46
46 } 47 // Returns the sources assignment filter if it exists for the current
47 48 // scope and it should be applied to this assignment. Otherwise returns null.
48 // Note: don't reserve() the dest vector here since that actually hurts 49 const PatternList* GetAssignmentFilter(const Scope* exec_scope) const;
49 // the allocation pattern when the build script is doing multiple small 50
50 // additions. 51 // Returns a pointer to the value that was set.
51 for (const auto& source_entry : source.list_value()) { 52 Value* SetValue(Value value, const ParseNode* set_node);
52 if (!filter->MatchesValue(source_entry)) 53
53 dest->list_value().push_back(source_entry); 54 // Fills the Err with an undefined value error appropriate for modification
54 } 55 // operators: += and -= (where the source is also the dest).
56 void MakeUndefinedIdentifierForModifyError(Err* err);
57
58 private:
59 enum Type { UNINITIALIZED, SCOPE, LIST };
60
61 Type type_;
62
63 // Valid when type_ == SCOPE.
64 Scope* scope_;
65 const Token* name_token_;
66
67 // Valid when type_ == LIST.
68 Value* list_;
69 size_t index_; // Guaranteed in-range when Init() succeeds.
70 };
71
72 ValueDestination::ValueDestination()
73 : type_(UNINITIALIZED),
74 scope_(nullptr),
75 name_token_(nullptr),
76 list_(nullptr),
77 index_(0) {
78 }
79
80 bool ValueDestination::Init(Scope* exec_scope,
81 const ParseNode* dest,
82 const BinaryOpNode* op_node,
83 Err* err) {
84 // Check for standard variable set.
85 const IdentifierNode* dest_identifier = dest->AsIdentifier();
86 if (dest_identifier) {
87 type_ = SCOPE;
88 scope_ = exec_scope;
89 name_token_ = &dest_identifier->value();
90 return true;
91 }
92
93 // Check for array and scope accesses. The base (array or scope variable
94 // name) must always be defined ahead of time.
95 const AccessorNode* dest_accessor = dest->AsAccessor();
96 if (!dest_accessor) {
97 *err = Err(op_node, "Assignment requires a lvalue.",
98 "This thing on the left is not an identifier or accessor.");
99 err->AppendRange(dest->GetRange());
100 return false;
101 }
102
103 // Known to be an accessor.
104 base::StringPiece base_str = dest_accessor->base().value();
105 Value* base = exec_scope->GetMutableValue(
106 base_str, Scope::SEARCH_CURRENT, false);
107 if (!base) {
108 // Base is either undefined or it's defined but not in the current scope.
109 // Make a good error message.
110 if (exec_scope->GetValue(base_str, false)) {
111 *err = Err(dest_accessor->base(), "Suspicious in-place modification.",
112 "This variable exists in a containing scope. Normally, writing to it "
113 "would\nmake a copy of it into the current scope with the modified "
114 "version. But\nhere you're modifying only an element of a scope or "
115 "list object. It's unlikely\nyou meant to copy the entire thing just "
116 "to modify this part of it.\n"
117 "\n"
118 "If you really wanted to do this, do:\n"
119 " " + base_str.as_string() + " = " + base_str.as_string() + "\n"
120 "to copy it into the current scope before doing this operation.");
121 } else {
122 *err = Err(dest_accessor->base(), "Undefined identifier.");
123 }
124 return false;
125 }
126
127 if (dest_accessor->index()) {
128 // List access with an index.
129 if (!base->VerifyTypeIs(Value::LIST, err)) {
130 // Errors here will confusingly refer to the variable declaration (since
131 // that's all Value knows) rather than the list access. So rewrite the
132 // error location to refer to the base value's location.
133 *err = Err(dest_accessor->base(), err->message(), err->help_text());
134 return false;
135 }
136
137 type_ = LIST;
138 list_ = base;
139 return dest_accessor->ComputeAndValidateListIndex(
140 exec_scope, base->list_value().size(), &index_, err);
141 }
142
143 // Scope access with a dot.
144 if (!base->VerifyTypeIs(Value::SCOPE, err)) {
145 // As the for the list index case above, rewrite the error location.
146 *err = Err(dest_accessor->base(), err->message(), err->help_text());
147 return false;
148 }
149 type_ = SCOPE;
150 scope_ = base->scope_value();
151 name_token_ = &dest_accessor->member()->value();
152 return true;
153 }
154
155 const Value* ValueDestination::GetExistingValue() const {
156 if (type_ == SCOPE)
157 return scope_->GetValue(name_token_->value(), false);
158 else if (type_ == LIST)
159 return &list_->list_value()[index_];
160 return nullptr;
161 }
162
163 Value* ValueDestination::GetExistingMutableValue(const ParseNode* origin) {
164 if (type_ == SCOPE) {
165 Value* value = scope_->GetMutableValue(
166 name_token_->value(), Scope::SEARCH_CURRENT, false);
167 if (value) {
168 // The value will be written to, reset its tracking information.
169 value->set_origin(origin);
170 scope_->MarkUnused(name_token_->value());
171 }
172 }
173 if (type_ == LIST)
174 return &list_->list_value()[index_];
175 return nullptr;
176 }
177
178 const PatternList* ValueDestination::GetAssignmentFilter(
179 const Scope* exec_scope) const {
180 if (type_ != SCOPE)
181 return nullptr; // Destination can't be named, so no sources filtering.
182 if (name_token_->value() != kSourcesName)
183 return nullptr; // Destination not named "sources".
184
185 const PatternList* filter = exec_scope->GetSourcesAssignmentFilter();
186 if (!filter || filter->is_empty())
187 return nullptr; // No filter or empty filter, don't need to do anything.
188 return filter;
189 }
190
191 Value* ValueDestination::SetValue(Value value, const ParseNode* set_node) {
192 if (type_ == SCOPE) {
193 return scope_->SetValue(name_token_->value(), std::move(value), set_node);
194 } else if (type_ == LIST) {
195 Value* dest = &list_->list_value()[index_];
196 *dest = std::move(value);
197 return dest;
198 }
199 return nullptr;
200 }
201
202 void ValueDestination::MakeUndefinedIdentifierForModifyError(Err* err) {
203 // When Init() succeeds, the base of any accessor has already been resolved
204 // and that list indices are in-range. This means any undefined identifiers
205 // are for scope accesses.
206 DCHECK(type_ == SCOPE);
207 *err = Err(*name_token_, "Undefined identifier.");
208 }
209
210 // -----------------------------------------------------------------------------
211
212 Err MakeIncompatibleTypeError(const BinaryOpNode* op_node,
213 const Value& left,
214 const Value& right) {
215 std::string msg =
216 std::string("You can't do <") + Value::DescribeType(left.type()) + "> " +
217 op_node->op().value().as_string() +
218 " <" + Value::DescribeType(right.type()) + ">.";
219 if (left.type() == Value::LIST) {
220 // Append extra hint for list stuff.
221 msg += "\n\nHint: If you're attempting to add or remove a single item from "
222 " a list, use \"foo + [ bar ]\".";
223 }
224 return Err(op_node, "Incompatible types for binary operator.", msg);
55 } 225 }
56 226
57 Value GetValueOrFillError(const BinaryOpNode* op_node, 227 Value GetValueOrFillError(const BinaryOpNode* op_node,
58 const ParseNode* node, 228 const ParseNode* node,
59 const char* name, 229 const char* name,
60 Scope* scope, 230 Scope* scope,
61 Err* err) { 231 Err* err) {
62 Value value = node->Execute(scope, err); 232 Value value = node->Execute(scope, err);
63 if (err->has_error()) 233 if (err->has_error())
64 return Value(); 234 return Value();
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
111 281
112 default: 282 default:
113 break; 283 break;
114 } 284 }
115 } 285 }
116 286
117 // Assignment ----------------------------------------------------------------- 287 // Assignment -----------------------------------------------------------------
118 288
119 // We return a null value from this rather than the result of doing the append. 289 // We return a null value from this rather than the result of doing the append.
120 // See ValuePlusEquals for rationale. 290 // See ValuePlusEquals for rationale.
121 Value ExecuteEquals(Scope* scope, 291 Value ExecuteEquals(Scope* exec_scope,
122 const BinaryOpNode* op_node, 292 const BinaryOpNode* op_node,
123 const Token& left, 293 ValueDestination* dest,
124 const Value& right, 294 Value right,
125 Err* err) { 295 Err* err) {
126 const Value* old_value = scope->GetValue(left.value(), false); 296 const Value* old_value = dest->GetExistingValue();
127 if (old_value) { 297 if (old_value) {
128 // Throw an error when overwriting a nonempty list with another nonempty 298 // Throw an error when overwriting a nonempty list with another nonempty
129 // list item. This is to detect the case where you write 299 // list item. This is to detect the case where you write
130 // defines = ["FOO"] 300 // defines = ["FOO"]
131 // and you overwrote inherited ones, when instead you mean to append: 301 // and you overwrote inherited ones, when instead you mean to append:
132 // defines += ["FOO"] 302 // defines += ["FOO"]
133 if (old_value->type() == Value::LIST && 303 if (old_value->type() == Value::LIST &&
134 !old_value->list_value().empty() && 304 !old_value->list_value().empty() &&
135 right.type() == Value::LIST && 305 right.type() == Value::LIST &&
136 !right.list_value().empty()) { 306 !right.list_value().empty()) {
137 *err = Err(op_node->left()->GetRange(), "Replacing nonempty list.", 307 *err = Err(op_node->left()->GetRange(), "Replacing nonempty list.",
138 std::string("This overwrites a previously-defined nonempty list ") + 308 std::string("This overwrites a previously-defined nonempty list ") +
139 "(length " + 309 "(length " +
140 base::IntToString(static_cast<int>(old_value->list_value().size())) 310 base::IntToString(static_cast<int>(old_value->list_value().size()))
141 + ")."); 311 + ").");
142 err->AppendSubErr(Err(*old_value, "for previous definition", 312 err->AppendSubErr(Err(*old_value, "for previous definition",
143 "with another one (length " + 313 "with another one (length " +
144 base::IntToString(static_cast<int>(right.list_value().size())) + 314 base::IntToString(static_cast<int>(right.list_value().size())) +
145 "). Did you mean " + 315 "). Did you mean " +
146 "\"+=\" to append instead? If you\nreally want to do this, do\n " + 316 "\"+=\" to append instead? If you\nreally want to do this, do\n"
147 left.value().as_string() + " = []\nbefore reassigning.")); 317 " foo = []\nbefore reassigning."));
148 return Value(); 318 return Value();
149 } 319 }
150 } 320 }
151 if (err->has_error()) 321 if (err->has_error())
152 return Value(); 322 return Value();
153 323
154 if (right.type() == Value::LIST && left.value() == kSourcesName) { 324 Value* written_value = dest->SetValue(std::move(right), op_node->right());
155 // Assigning to sources, filter the list. Here we do the filtering and 325
156 // copying in one step to save an extra list copy (the lists may be 326 // Optionally apply the assignment filter in-place.
157 // long). 327 const PatternList* filter = dest->GetAssignmentFilter(exec_scope);
158 Value* set_value = scope->SetValue(left.value(), 328 if (filter) {
159 Value(op_node, Value::LIST), op_node); 329 std::vector<Value>& list_value = written_value->list_value();
160 set_value->list_value().reserve(right.list_value().size()); 330 auto first_deleted = std::remove_if(
161 AppendFilteredSourcesToValue(scope, right, set_value); 331 list_value.begin(), list_value.end(),
162 } else { 332 [filter](const Value& v) {
163 // Normal value set, just copy it. 333 return filter->MatchesValue(v);
164 scope->SetValue(left.value(), right, op_node->right()); 334 });
335 list_value.erase(first_deleted, list_value.end());
165 } 336 }
166 return Value(); 337 return Value();
167 } 338 }
168 339
169 // allow_type_conversion indicates if we're allowed to change the type of the 340 // Plus/minus ------------------------------------------------------------------
170 // left value. This is set to true when doing +, and false when doing +=. 341
171 // 342 // allow_left_type_conversion indicates if we're allowed to change the type of
172 // Note that we return Value() from here, which is different than C++. This 343 // the left value. This is set to true when doing +, and false when doing +=.
173 // means you can't do clever things like foo = [ bar += baz ] to simultaneously 344 Value ExecutePlus(const BinaryOpNode* op_node,
174 // append to and use a value. This is basically never needed in out build 345 Value left,
175 // scripts and is just as likely an error as the intended behavior, and it also 346 Value right,
176 // involves a copy of the value when it's returned. Many times we're appending 347 bool allow_left_type_conversion,
177 // to large lists, and copying the value to discard it for the next statement 348 Err* err) {
178 // is very wasteful. 349 // Left-hand-side integer.
179 void ValuePlusEquals(const Scope* scope, 350 if (left.type() == Value::INTEGER) {
180 const BinaryOpNode* op_node, 351 if (right.type() == Value::INTEGER) {
181 const Token& left_token, 352 // Int + int -> addition.
182 Value* left, 353 return Value(op_node, left.int_value() + right.int_value());
183 const Value& right, 354 } else if (right.type() == Value::STRING && allow_left_type_conversion) {
184 bool allow_type_conversion, 355 // Int + string -> string concat.
185 Err* err) { 356 return Value(
186 switch (left->type()) { 357 op_node,
187 // Left-hand-side int. 358 base::Int64ToString(left.int_value()) + right.string_value());
188 case Value::INTEGER: 359 }
189 switch (right.type()) { 360 *err = MakeIncompatibleTypeError(op_node, left, right);
190 case Value::INTEGER: // int + int -> addition. 361 return Value();
191 left->int_value() += right.int_value(); 362 }
192 return; 363
193 364 // Left-hand-side string.
194 case Value::STRING: // int + string -> string concat. 365 if (left.type() == Value::STRING) {
195 if (allow_type_conversion) { 366 if (right.type() == Value::INTEGER) {
196 *left = Value(op_node, 367 // String + int -> string concat.
197 base::Int64ToString(left->int_value()) + right.string_value()); 368 return Value(op_node,
198 return; 369 left.string_value() + base::Int64ToString(right.int_value()));
199 } 370 } else if (right.type() == Value::STRING) {
200 break; 371 // String + string -> string concat. Since the left is passed by copy
201 372 // we can avoid realloc if there is enough buffer by appending to left
202 default: 373 // and assigning.
203 break; 374 left.string_value().append(right.string_value());
375 return left; // FIXME(brettw) des this copy?
376 }
377 *err = MakeIncompatibleTypeError(op_node, left, right);
378 return Value();
379 }
380
381 // Left-hand-side list. The only valid thing is to add another list.
382 if (left.type() == Value::LIST && right.type() == Value::LIST) {
383 // Since left was passed by copy, avoid realloc by destructively appending
384 // to it and using that as the result.
385 for (Value& value : right.list_value())
386 left.list_value().push_back(std::move(value));
387 return left; // FIXME(brettw) does this copy?
388 }
389
390 *err = MakeIncompatibleTypeError(op_node, left, right);
391 return Value();
392 }
393
394 // Left is passed by value because it will be modified in-place and returned
395 // for the list case.
396 Value ExecuteMinus(const BinaryOpNode* op_node,
397 Value left,
398 const Value& right,
399 Err* err) {
400 // Left-hand-side int. The only thing to do is subtract another int.
401 if (left.type() == Value::INTEGER && right.type() != Value::INTEGER) {
402 // Int - int -> subtraction.
403 return Value(op_node, left.int_value() - right.int_value());
404 }
405
406 // Left-hand-side list. The only thing to do is subtract another list.
407 if (left.type() == Value::LIST && right.type() == Value::LIST) {
408 // In-place modify left and return it.
409 RemoveMatchesFromList(op_node, &left, right, err);
410 return left;
411 }
412
413 *err = MakeIncompatibleTypeError(op_node, left, right);
414 return Value();
415 }
416
417 // In-place plus/minus ---------------------------------------------------------
418
419 void ExecutePlusEquals(Scope* exec_scope,
420 const BinaryOpNode* op_node,
421 ValueDestination* dest,
422 Value right,
423 Err* err) {
424 // There are several cases. Some things we can convert "foo += bar" to
425 // "foo = foo + bar". Some cases we can't (the 'sources' variable won't
426 // get the right filtering on the list). Some cases we don't want to (lists
427 // and strings will get unnecessary copying so we can to optimize these).
428 //
429 // - Value is already mutable in the current scope:
430 // 1. List/string append: use it.
431 // 2. Other types: fall back to "foo = foo + bar"
432 //
433 // - Value is not mutable in the current scope:
434 // 3. List/string append: copy into current scope and append to that.
435 // 4. Other types: fall back to "foo = foo + bar"
436 //
437 // The common case is to use += for list and string appends in the local
438 // scope, so this is written to avoid multiple variable lookups in that case.
439 Value* mutable_dest = dest->GetExistingMutableValue(op_node);
440 if (!mutable_dest) {
441 const Value* existing_value = dest->GetExistingValue();
442 if (!existing_value) {
443 // Undefined left-hand-size for +=.
444 dest->MakeUndefinedIdentifierForModifyError(err);
445 return;
446 }
447
448 if (existing_value->type() != Value::STRING &&
449 existing_value->type() != Value::LIST) {
450 // Case #4 above.
451 dest->SetValue(ExecutePlus(op_node, *existing_value,
452 std::move(right), false, err), op_node);
453 return;
454 }
455
456 // Case #3 above, copy to current scope and fall-through to appending.
457 mutable_dest = dest->SetValue(*existing_value, op_node);
458 } else if (mutable_dest->type() != Value::STRING &&
459 mutable_dest->type() != Value::LIST) {
460 // Case #2 above.
461 dest->SetValue(ExecutePlus(op_node, *mutable_dest,
462 std::move(right), false, err), op_node);
463 return;
464 } // "else" is case #1 above.
465
466 if (mutable_dest->type() == Value::STRING) {
467 if (right.type() == Value::INTEGER) {
468 // String + int -> string concat.
469 mutable_dest->string_value().append(
470 base::Int64ToString(right.int_value()));
471 } else if (right.type() == Value::STRING) {
472 // String + string -> string concat.
473 mutable_dest->string_value().append(right.string_value());
474 } else {
475 *err = MakeIncompatibleTypeError(op_node, *mutable_dest, right);
476 }
477 } else if (mutable_dest->type() == Value::LIST) {
478 // List concat.
479 if (right.type() == Value::LIST) {
480 // Note: don't reserve() the dest vector here since that actually hurts
481 // the allocation pattern when the build script is doing multiple small
482 // additions.
483 const PatternList* filter = dest->GetAssignmentFilter(exec_scope);
484 if (filter) {
485 // Filtered list concat.
486 for (Value& value : right.list_value()) {
487 if (!filter->MatchesValue(value))
488 mutable_dest->list_value().push_back(std::move(value));
489 }
490 } else {
491 // Normal list concat. This is a destructive move.
492 for (Value& value : right.list_value())
493 mutable_dest->list_value().push_back(std::move(value));
204 } 494 }
205 break; 495 } else {
206 496 *err = Err(op_node->op(), "Incompatible types to add.",
207 // Left-hand-side string. 497 "To append a single item to a list do \"foo += [ bar ]\".");
208 case Value::STRING: 498 }
209 switch (right.type()) { 499 }
210 case Value::INTEGER: // string + int -> string concat. 500 }
211 left->string_value().append(base::Int64ToString(right.int_value())); 501
212 return; 502 void ExecuteMinusEquals(const BinaryOpNode* op_node,
213 503 ValueDestination* dest,
214 case Value::STRING: // string + string -> string contat.
215 left->string_value().append(right.string_value());
216 return;
217
218 default:
219 break;
220 }
221 break;
222
223 // Left-hand-side list.
224 case Value::LIST:
225 switch (right.type()) {
226 case Value::LIST: // list + list -> list concat.
227 if (left_token.value() == kSourcesName) {
228 // Filter additions through the assignment filter.
229 AppendFilteredSourcesToValue(scope, right, left);
230 } else {
231 // Normal list concat.
232 for (const auto& value : right.list_value())
233 left->list_value().push_back(value);
234 }
235 return;
236
237 default:
238 *err = Err(op_node->op(), "Incompatible types to add.",
239 "To append a single item to a list do \"foo += [ bar ]\".");
240 return;
241 }
242
243 default:
244 break;
245 }
246
247 *err = Err(op_node->op(), "Incompatible types to add.",
248 std::string("I see a ") + Value::DescribeType(left->type()) + " and a " +
249 Value::DescribeType(right.type()) + ".");
250 }
251
252 Value ExecutePlusEquals(Scope* scope,
253 const BinaryOpNode* op_node,
254 const Token& left,
255 const Value& right, 504 const Value& right,
256 Err* err) { 505 Err* err) {
257 // We modify in-place rather than doing read-modify-write to avoid 506 // Like the += case, we can convert "foo -= bar" to "foo = foo - bar". Since
258 // copying large lists. 507 // there is no sources filtering, this is always semantically valid. The
259 Value* left_value = 508 // only case we don't do it is for lists in the current scope which is the
260 scope->GetValueForcedToCurrentScope(left.value(), op_node); 509 // most common case, and also the one that can be optimized the most by
261 if (!left_value) { 510 // doing it in-place.
262 *err = Err(left, "Undefined variable for +=.", 511 Value* mutable_dest = dest->GetExistingMutableValue(op_node);
263 "I don't have something with this name in scope now."); 512 if (!mutable_dest ||
264 return Value(); 513 (mutable_dest->type() != Value::LIST || right.type() != Value::LIST)) {
265 } 514 const Value* existing_value = dest->GetExistingValue();
266 ValuePlusEquals(scope, op_node, left, left_value, right, false, err); 515 if (!existing_value) {
267 left_value->set_origin(op_node); 516 // Undefined left-hand-size for -=.
268 scope->MarkUnused(left.value()); 517 dest->MakeUndefinedIdentifierForModifyError(err);
269 return Value();
270 }
271
272 // We return a null value from this rather than the result of doing the append.
273 // See ValuePlusEquals for rationale.
274 void ValueMinusEquals(const BinaryOpNode* op_node,
275 Value* left,
276 const Value& right,
277 bool allow_type_conversion,
278 Err* err) {
279 switch (left->type()) {
280 // Left-hand-side int.
281 case Value::INTEGER:
282 switch (right.type()) {
283 case Value::INTEGER: // int - int -> subtraction.
284 left->int_value() -= right.int_value();
285 return;
286
287 default:
288 break;
289 }
290 break;
291
292 // Left-hand-side string.
293 case Value::STRING:
294 break; // All are errors.
295
296 // Left-hand-side list.
297 case Value::LIST:
298 if (right.type() != Value::LIST) {
299 *err = Err(op_node->op(), "Incompatible types to subtract.",
300 "To remove a single item from a list do \"foo -= [ bar ]\".");
301 } else {
302 RemoveMatchesFromList(op_node, left, right, err);
303 }
304 return; 518 return;
305 519 }
306 default: 520 dest->SetValue(ExecuteMinus(op_node, *existing_value, right, err), op_node);
307 break; 521 return;
308 } 522 }
309 523
310 *err = Err(op_node->op(), "Incompatible types to subtract.", 524 // In-place removal of items from "right".
311 std::string("I see a ") + Value::DescribeType(left->type()) + " and a " + 525 RemoveMatchesFromList(op_node, mutable_dest, right, err);
312 Value::DescribeType(right.type()) + ".");
313 }
314
315 Value ExecuteMinusEquals(Scope* scope,
316 const BinaryOpNode* op_node,
317 const Token& left,
318 const Value& right,
319 Err* err) {
320 Value* left_value =
321 scope->GetValueForcedToCurrentScope(left.value(), op_node);
322 if (!left_value) {
323 *err = Err(left, "Undefined variable for -=.",
324 "I don't have something with this name in scope now.");
325 return Value();
326 }
327 ValueMinusEquals(op_node, left_value, right, false, err);
328 left_value->set_origin(op_node);
329 scope->MarkUnused(left.value());
330 return Value();
331 }
332
333 // Plus/Minus -----------------------------------------------------------------
334
335 Value ExecutePlus(Scope* scope,
336 const BinaryOpNode* op_node,
337 const Value& left,
338 const Value& right,
339 Err* err) {
340 Value ret = left;
341 ValuePlusEquals(scope, op_node, Token(), &ret, right, true, err);
342 ret.set_origin(op_node);
343 return ret;
344 }
345
346 Value ExecuteMinus(Scope* scope,
347 const BinaryOpNode* op_node,
348 const Value& left,
349 const Value& right,
350 Err* err) {
351 Value ret = left;
352 ValueMinusEquals(op_node, &ret, right, true, err);
353 ret.set_origin(op_node);
354 return ret;
355 } 526 }
356 527
357 // Comparison ----------------------------------------------------------------- 528 // Comparison -----------------------------------------------------------------
358 529
359 Value ExecuteEqualsEquals(Scope* scope, 530 Value ExecuteEqualsEquals(Scope* scope,
360 const BinaryOpNode* op_node, 531 const BinaryOpNode* op_node,
361 const Value& left, 532 const Value& left,
362 const Value& right, 533 const Value& right,
363 Err* err) { 534 Err* err) {
364 if (left == right) 535 if (left == right)
(...skipping 148 matching lines...) Expand 10 before | Expand all | Expand 10 after
513 const BinaryOpNode* op_node, 684 const BinaryOpNode* op_node,
514 const ParseNode* left, 685 const ParseNode* left,
515 const ParseNode* right, 686 const ParseNode* right,
516 Err* err) { 687 Err* err) {
517 const Token& op = op_node->op(); 688 const Token& op = op_node->op();
518 689
519 // First handle the ones that take an lvalue. 690 // First handle the ones that take an lvalue.
520 if (op.type() == Token::EQUAL || 691 if (op.type() == Token::EQUAL ||
521 op.type() == Token::PLUS_EQUALS || 692 op.type() == Token::PLUS_EQUALS ||
522 op.type() == Token::MINUS_EQUALS) { 693 op.type() == Token::MINUS_EQUALS) {
523 const IdentifierNode* left_id = left->AsIdentifier(); 694 // Compute the left side.
524 if (!left_id) { 695 ValueDestination dest;
525 *err = Err(op, "Operator requires a lvalue.", 696 if (!dest.Init(scope, left, op_node, err))
526 "This thing on the left is not an identifier.");
527 err->AppendRange(left->GetRange());
528 return Value(); 697 return Value();
529 }
530 const Token& dest = left_id->value();
531 698
699 // Compute the right side.
532 Value right_value = right->Execute(scope, err); 700 Value right_value = right->Execute(scope, err);
533 if (err->has_error()) 701 if (err->has_error())
534 return Value(); 702 return Value();
535 if (right_value.type() == Value::NONE) { 703 if (right_value.type() == Value::NONE) {
536 *err = Err(op, "Operator requires a rvalue.", 704 *err = Err(op, "Operator requires a rvalue.",
537 "This thing on the right does not evaluate to a value."); 705 "This thing on the right does not evaluate to a value.");
538 err->AppendRange(right->GetRange()); 706 err->AppendRange(right->GetRange());
539 return Value(); 707 return Value();
540 } 708 }
541 709
542 if (op.type() == Token::EQUAL) 710 // "foo += bar" (same for "-=") is converted to "foo = foo + bar" here, but
543 return ExecuteEquals(scope, op_node, dest, right_value, err); 711 // we pass the original value of "foo" by pointer to avoid a copy.
544 if (op.type() == Token::PLUS_EQUALS) 712 if (op.type() == Token::EQUAL) {
545 return ExecutePlusEquals(scope, op_node, dest, right_value, err); 713 ExecuteEquals(scope, op_node, &dest, std::move(right_value), err);
546 if (op.type() == Token::MINUS_EQUALS) 714 } else if (op.type() == Token::PLUS_EQUALS) {
547 return ExecuteMinusEquals(scope, op_node, dest, right_value, err); 715 ExecutePlusEquals(scope, op_node, &dest, std::move(right_value), err);
548 NOTREACHED(); 716 } else if (op.type() == Token::MINUS_EQUALS) {
717 ExecuteMinusEquals(op_node, &dest, right_value, err);
718 } else {
719 NOTREACHED();
720 }
549 return Value(); 721 return Value();
550 } 722 }
551 723
552 // ||, &&. Passed the node instead of the value so that they can avoid 724 // ||, &&. Passed the node instead of the value so that they can avoid
553 // evaluating the RHS on early-out. 725 // evaluating the RHS on early-out.
554 if (op.type() == Token::BOOLEAN_OR) 726 if (op.type() == Token::BOOLEAN_OR)
555 return ExecuteOr(scope, op_node, left, right, err); 727 return ExecuteOr(scope, op_node, left, right, err);
556 if (op.type() == Token::BOOLEAN_AND) 728 if (op.type() == Token::BOOLEAN_AND)
557 return ExecuteAnd(scope, op_node, left, right, err); 729 return ExecuteAnd(scope, op_node, left, right, err);
558 730
731 // Everything else works on the evaluated left and right values.
559 Value left_value = GetValueOrFillError(op_node, left, "left", scope, err); 732 Value left_value = GetValueOrFillError(op_node, left, "left", scope, err);
560 if (err->has_error()) 733 if (err->has_error())
561 return Value(); 734 return Value();
562 Value right_value = GetValueOrFillError(op_node, right, "right", scope, err); 735 Value right_value = GetValueOrFillError(op_node, right, "right", scope, err);
563 if (err->has_error()) 736 if (err->has_error())
564 return Value(); 737 return Value();
565 738
566 // +, -. 739 // +, -.
567 if (op.type() == Token::MINUS) 740 if (op.type() == Token::MINUS)
568 return ExecuteMinus(scope, op_node, left_value, right_value, err); 741 return ExecuteMinus(op_node, std::move(left_value), right_value, err);
569 if (op.type() == Token::PLUS) 742 if (op.type() == Token::PLUS) {
570 return ExecutePlus(scope, op_node, left_value, right_value, err); 743 return ExecutePlus(op_node, std::move(left_value), std::move(right_value),
744 true, err);
745 }
571 746
572 // Comparisons. 747 // Comparisons.
573 if (op.type() == Token::EQUAL_EQUAL) 748 if (op.type() == Token::EQUAL_EQUAL)
574 return ExecuteEqualsEquals(scope, op_node, left_value, right_value, err); 749 return ExecuteEqualsEquals(scope, op_node, left_value, right_value, err);
575 if (op.type() == Token::NOT_EQUAL) 750 if (op.type() == Token::NOT_EQUAL)
576 return ExecuteNotEquals(scope, op_node, left_value, right_value, err); 751 return ExecuteNotEquals(scope, op_node, left_value, right_value, err);
577 if (op.type() == Token::GREATER_EQUAL) 752 if (op.type() == Token::GREATER_EQUAL)
578 return ExecuteGreaterEquals(scope, op_node, left_value, right_value, err); 753 return ExecuteGreaterEquals(scope, op_node, left_value, right_value, err);
579 if (op.type() == Token::LESS_EQUAL) 754 if (op.type() == Token::LESS_EQUAL)
580 return ExecuteLessEquals(scope, op_node, left_value, right_value, err); 755 return ExecuteLessEquals(scope, op_node, left_value, right_value, err);
581 if (op.type() == Token::GREATER_THAN) 756 if (op.type() == Token::GREATER_THAN)
582 return ExecuteGreater(scope, op_node, left_value, right_value, err); 757 return ExecuteGreater(scope, op_node, left_value, right_value, err);
583 if (op.type() == Token::LESS_THAN) 758 if (op.type() == Token::LESS_THAN)
584 return ExecuteLess(scope, op_node, left_value, right_value, err); 759 return ExecuteLess(scope, op_node, left_value, right_value, err);
585 760
586 return Value(); 761 return Value();
587 } 762 }
OLDNEW
« no previous file with comments | « tools/gn/loader_unittest.cc ('k') | tools/gn/operators_unittest.cc » ('j') | tools/gn/parser.cc » ('J')

Powered by Google App Engine
This is Rietveld 408576698