Skip to content

Conversation

@nieuwmijnleven
Copy link

@nieuwmijnleven nieuwmijnleven commented Sep 21, 2025

This pull request is a suggestion to improve compiler internal safety and clarity.

It addresses an issue where the compiler assigns the local variable "this" to slot 0 even when compiling non-method functions. This behavior causes this to behave like a valid local variable outside of class methods, which is unintended and can hide runtime errors.

What was wrong?

The compiler code did not check whether the current function was inside a class (currentClass != NULL) before assigning "this" to slot 0. As a result, even functions that are not methods received "this" as a local variable.

What is fixed?

  • Added a check to ensure "this" is only assigned to slot 0 when compiling class methods.

  • This prevents this from being a local variable outside of methods, allowing the runtime to properly catch errors when this is misused.

Additional notes

  • This fix improves the safety and correctness of this handling in Lox.

  • Existing tests pass; additional test cases for this usage outside of classes can be added if desired.

Closes #1203

@nieuwmijnleven nieuwmijnleven changed the title Fix: Only assign 'this' to slot 0 if currentClass is not null Suggestion: Only assign 'this' to slot 0 if currentClass is not null Oct 3, 2025
@nieuwmijnleven nieuwmijnleven changed the title Suggestion: Only assign 'this' to slot 0 if currentClass is not null Suggestion : Assign 'this' to slot 0 only if the current context is a class, not the global scope Nov 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Suggestion : Assign 'this' to slot 0 only if the current context is a class, not the global scope

1 participant