Method Lookup Rules.

无论对于什么语言,如何 lookup 这一规则都是核心的 semantic,值得我们仔细探讨。

  • variable-lookup: 如何“找到”定义的某个变量?
  • function/method-lookup: 如何“找到”某个需要调用的函数/方法?

在 Ruby 中,对于 local variables,blocks 的 lookup 与 ML 和 Racket 中没有区别;它们都遵循 lexical scope 定义的规则。但对于 instance variables,class variables 与 methods 的 lookup 牵扯到 self 这一特殊的指针。

In any environment. self maps to some object, which we think of as the “current object” — the object currently executing a method.

To look up an instance variable @x, use the object bound to self - each object has its own state and we use self‘s state. To look up a class variable @@x, use the state of the object bound to self.class.

methods 的 lookup 规则是最为复杂的:In class-based OOP languages like Ruby, the rule for evaluating a method call like e0.m(e1, ..., en) is:

  • Evaluate e0, e1, …, en to values, i.e., objects obj0, obj1, …, objn.

  • Get the class of obj0. Every object knows its class at run-time; think of the class as part of the state of obj0.

  • Suppose obj0 has class A. 从类 A 开始沿着 hierarchy 不断往上攀升:If m is defined in A, call that method. Otherwise recur with the superclass of A to see if it defines m.

  • We have now found the method to call. If the method has formal arguments x1, x2, …, xn, then the environment for evaluating the body will map x1 to obj1, x2 to obj2, etc.

    But there is one more thing that is the essence of OOP and has no real analogue in functional programming: We always have self in the environment. While evaluating the method body, self is bound to obj0, the object that is the receiver of the message.

selfobj0 进行绑定,这一规则就是所谓的 late-binding,或 dynamic dispatch 与 virtual method calls。这意味着,when the body of m calls a method on self, we use the class of obj0 to resolve someMethod, not necessarily the class of the method we are executing.

注意,我们仅仅使用最简洁的方式描述了 method lookup 的规则框架,Ruby 中存在许多其他的 features (如 mixins) 令我们在该框架下需要考虑更多的情况。此外,在 Java 与 C# 中,method lookup 的规则大致与 Ruby 相同,但更加复杂,我们还需要考虑 static overloading 所带来的影响。

Reference

Supplementry notes:

My notes in CnBlogs.

知乎 - 为什么语言要提供 “反射” 功能?.

Course info:

Programming Languages, Part C, University of Washington, Lecturer: Professor Dan Grossman.