Skip to content

Variable search semantic in Scope #3115

Closed
@wangkuiyi

Description

@wangkuiyi

Scope::CreateVarialbe(name) won't create a variable if there has been one with the given name in the scope or any of its ancestors:

  Variable* CreateVariable(const std::string& name) {
    auto var = GetVariable(name);
    if (var) {
      return var;
    } else {
      auto ptr = new Variable();
      name_to_var_[name] = std::unique_ptr<Variable>(ptr);
      var_to_name_[ptr] = name;
      return GetVariable(name);
    }
  }

  /**
   * @brief Get Variable.
   *
   * Get Variable from this Scope, this function will recursive find Variable
   * from it's parent scope. Return nullptr if not found.
   */
  Variable* GetVariable(const std::string& name) const {
    auto it = name_to_var_.find(name);
    if (it != name_to_var_.end()) {
      return it->second.get();
    } else if (parent_ != nullptr) {
      return parent_->GetVariable(name);
    } else {
      return nullptr;
    }
  }

This is a mistake because even if there has been one with the given name in an ancestor, we should still be able to create one in the current scope; otherwise, we couldn't implement variable shadowing.

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions