Class Environment

java.lang.Object
tech.ixor.calclox.Environment

public class Environment extends Object
Stores variables for one lexical scope in a CalcLox execution.

Environments form an enclosing chain. Normal lookup and assignment walk that chain, while resolved lookup uses a precomputed lexical distance.

  • Constructor Details

    • Environment

      public Environment()
      Creates a global environment with no enclosing scope.
    • Environment

      public Environment(Environment enclosing)
      Creates a nested lexical environment.
      Parameters:
      enclosing - immediately enclosing scope
  • Method Details

    • getValues

      public Map<String,Object> getValues()
      Returns the values declared directly in this scope.
      Returns:
      the live, mutable scope map
    • get

      public Object get(Token name)
      Looks up a variable in this scope or an enclosing scope.
      Parameters:
      name - variable token used for lookup and error location
      Returns:
      stored value, including null
      Throws:
      RuntimeError - if the variable is undefined
    • assign

      public void assign(Token name, Object value)
      Updates the nearest existing declaration in the environment chain.
      Parameters:
      name - variable token used for lookup and error location
      value - replacement value
      Throws:
      RuntimeError - if the variable is undefined
    • define

      public void define(String name, Object value)
      Declares or replaces a value directly in this scope.
      Parameters:
      name - variable name
      value - initial value
    • ancestor

      public Environment ancestor(int distance)
      Returns an enclosing environment at an exact lexical distance.
      Parameters:
      distance - number of enclosing links to traverse; zero returns this environment
      Returns:
      resolved ancestor
    • getAt

      public Object getAt(int distance, String name)
      Returns a resolved local value without performing a name search.
      Parameters:
      distance - lexical distance to the declaring environment
      name - variable name
      Returns:
      stored value, including null
    • assignAt

      public void assignAt(int distance, Token name, Object value)
      Updates a resolved local value without performing a name search.
      Parameters:
      distance - lexical distance to the declaring environment
      name - variable token
      value - replacement value
    • toString

      public String toString()
      Overrides:
      toString in class Object