Ninja
|
00001 // Copyright 2011 Google Inc. All Rights Reserved. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // http://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 00015 #include "eval_env.h" 00016 00017 string BindingEnv::LookupVariable(const string& var) { 00018 map<string, string>::iterator i = bindings_.find(var); 00019 if (i != bindings_.end()) 00020 return i->second; 00021 if (parent_) 00022 return parent_->LookupVariable(var); 00023 return ""; 00024 } 00025 00026 void BindingEnv::AddBinding(const string& key, const string& val) { 00027 bindings_[key] = val; 00028 } 00029 00030 string BindingEnv::LookupWithFallback(const string& var, 00031 const EvalString* eval, 00032 Env* env) { 00033 map<string, string>::iterator i = bindings_.find(var); 00034 if (i != bindings_.end()) 00035 return i->second; 00036 00037 if (eval) 00038 return eval->Evaluate(env); 00039 00040 if (parent_) 00041 return parent_->LookupVariable(var); 00042 00043 return ""; 00044 } 00045 00046 string EvalString::Evaluate(Env* env) const { 00047 string result; 00048 for (TokenList::const_iterator i = parsed_.begin(); i != parsed_.end(); ++i) { 00049 if (i->second == RAW) 00050 result.append(i->first); 00051 else 00052 result.append(env->LookupVariable(i->first)); 00053 } 00054 return result; 00055 } 00056 00057 void EvalString::AddText(StringPiece text) { 00058 // Add it to the end of an existing RAW token if possible. 00059 if (!parsed_.empty() && parsed_.back().second == RAW) { 00060 parsed_.back().first.append(text.str_, text.len_); 00061 } else { 00062 parsed_.push_back(make_pair(text.AsString(), RAW)); 00063 } 00064 } 00065 void EvalString::AddSpecial(StringPiece text) { 00066 parsed_.push_back(make_pair(text.AsString(), SPECIAL)); 00067 } 00068 00069 string EvalString::Serialize() const { 00070 string result; 00071 for (TokenList::const_iterator i = parsed_.begin(); 00072 i != parsed_.end(); ++i) { 00073 result.append("["); 00074 if (i->second == SPECIAL) 00075 result.append("$"); 00076 result.append(i->first); 00077 result.append("]"); 00078 } 00079 return result; 00080 }