munificent / craftinginterpreters

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

Why use classCompiler in the code? Section 29.2 #941

Closed cm1776 closed 3 years ago

cm1776 commented 3 years ago

The variable currentClass tracks the class declaration currently being compiled.

In theclassDeclaration()function, aclassCompilervariable is initialized and its address is assigned to thecurrentClassvariable. Several lines of code later, we come across the following:

classCompiler.hasSuperclass = true; and if (classCompiler.hasSuperclass) { endScope(); }

Is there a specific reason for usingclassCompilerin the 2 lines of code above rather than thecurrentClassvariable? I expected the use of the later i.e.

currentClass.hasSuperclass = true; and if (currentClass.hasSuperclass) { endScope() }

Granted, in this particular case, the results seem to be the same.

ceronman commented 3 years ago

In the context of the classDeclaration() function, classCompiler and currentClass are the same thing (currentClass is just a pointer to classCompiler:

ClassCompiler classCompiler;
classCompiler.name = parser.previous;
classCompiler.enclosing = currentClass;
currentClass = &classCompiler;

So it's fine to use both, but my guess is that classCompiler is used because it's one less indirection, which might bring a tiny performance improvement. Although probably the compiler is smart enough to not make any difference.

munificent commented 3 years ago

No real reason that I recall. Some choices are just arbitrary. :)