munificent / craftinginterpreters

Repository for the book "Crafting Interpreters"
http://www.craftinginterpreters.com/
Other
8.79k stars 1.03k forks source link

Why not compare type with TYPE_METHOD? (Section 28.3) #935

Closed cm1776 closed 3 years ago

cm1776 commented 3 years ago

Consider the following excerpt:

For function calls, that slot ends up holding the function being called. Since the slot has no name, the function body never accesses it. You can guess where this is going. For method calls, we can repurpose that slot to store the receiver. Slot zero will store the instance that this is bound to. In order to compile this expressions, the compiler simply needs to give the correct name to that local variable.

  if (type != TYPE_FUNCTION) {
    local->name.start = "this";
    local->name.length = 4;
  } else {
    local->name.start = "";
    local->name.length = 0;
  }

We want to do this only for methods. Function declarations don’t have a this. And, in fact, they must not declare a variable named “this”, so that if you write a this expression inside a function declaration which is itself inside a method, the this correctly resolves to the outer method’s receiver.

Why not use if (type == TYPE_METHOD) ... in the code above? Only methods will thus satisfy the condition. Such a test will clearly show that:

We want to do this only for methods.

cm1776 commented 3 years ago

Since later in the same chapter a TYPE_INITIALIZER is declared, a better test would be:

if ((type != TYPE_SCRIPT) && (type != TYPE_FUNCTION)) ...