All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.snapscript.tree.variable.LocalPointer Maven / Gradle / Ivy

There is a newer version: 1.4.6
Show newest version
package org.snapscript.tree.variable;

import java.util.concurrent.atomic.AtomicReference;

import org.snapscript.core.Scope;
import org.snapscript.core.State;
import org.snapscript.core.Value;

public class LocalPointer implements VariablePointer {
   
   private final AtomicReference reference;
   private final ConstantResolver resolver;
   private final String name;
   
   public LocalPointer(ConstantResolver resolver, String name) {
      this.reference = new AtomicReference();
      this.resolver = resolver;
      this.name = name;
   }
   
   @Override
   public Value get(Scope scope, Object left) {
      Object result = reference.get();
      
      if(result == null) {
         State state = scope.getState();
         Value variable = state.get(name);
         
         if(variable == null) { 
            Object value = resolver.resolve(scope, name);
            
            if(value != null) {
               reference.set(value);
               return Value.getTransient(value);
            }
         }
         return variable;
      }
      return Value.getTransient(result);
   }
}