scope.h 1.7 KB
Newer Older
朔-望's avatar
朔-望 已提交
1 2
#pragma once

朔-望's avatar
朔-望 已提交
3 4 5
#include <list>           //std::list
#include <mutex>          //std::mutex
#include <unordered_map>  //std::unordered_map
朔-望's avatar
朔-望 已提交
6 7 8
#include "variable.h"

namespace paddle_mobile {
朔-望's avatar
朔-望 已提交
9 10
namespace framework {
class Scope {
朔-望's avatar
朔-望 已提交
11
 public:
12 13
  Scope() {}
  ~Scope() {}
朔-望's avatar
朔-望 已提交
14

15
  Scope &NewScope() const;
朔-望's avatar
朔-望 已提交
16

17 18
  /// Create a variable with given name if it doesn't exist.
  Variable *Var(const std::string &name);
朔-望's avatar
朔-望 已提交
19

20 21
  /// Create a variable with a scope-unique name.
  Variable *Var(std::string *name = nullptr);
朔-望's avatar
朔-望 已提交
22

23
  void EraseVars(const std::vector<std::string> &var_names);
朔-望's avatar
朔-望 已提交
24

25 26 27
  /// Find a variable in the scope or any of its ancestors.  Returns
  /// nullptr if cannot find.
  Variable *FindVar(const std::string &name) const;
朔-望's avatar
朔-望 已提交
28

29
  const Scope *parent() const { return parent_; }
朔-望's avatar
朔-望 已提交
30

31 32 33
  /// Find the scope or an ancestor scope that contains the given
  /// variable.
  const Scope *FindScope(const Variable *var) const;
朔-望's avatar
朔-望 已提交
34

35
  void DeleteScope(Scope *scope) const;
朔-望's avatar
朔-望 已提交
36

37 38
  /// Drop all kids scopes belonged to this scope.
  void DropKids();
朔-望's avatar
朔-望 已提交
39

40 41
  // enumerate all the variables current contains.
  std::vector<std::string> LocalVarNames() const;
朔-望's avatar
朔-望 已提交
42

43 44 45
  // Rename variable to a new name
  void Rename(const std::string &origin_name,
              const std::string &new_name) const;
朔-望's avatar
朔-望 已提交
46

47 48
  // Rename variable to a new name and return the new name
  std::string Rename(const std::string &origin_name) const;
朔-望's avatar
朔-望 已提交
49

50
  Variable *FindVarLocally(const std::string &name) const;
朔-望's avatar
朔-望 已提交
51

朔-望's avatar
朔-望 已提交
52
 private:
53 54
  // Call Scope::NewScope for a sub-scope.
  explicit Scope(Scope const *parent) : parent_(parent) {}
朔-望's avatar
朔-望 已提交
55

56 57 58
  mutable std::unordered_map<std::string, Variable *> vars_;
  mutable std::list<Scope *> kids_;
  Scope const *parent_{nullptr};
朔-望's avatar
朔-望 已提交
59

60
  mutable std::mutex mutex_;
朔-望's avatar
朔-望 已提交
61
};
朔-望's avatar
朔-望 已提交
62 63
}  // namespace framework
}  // namespace paddle_mobile