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

org.snapscript.core.LocalState Maven / Gradle / Ivy

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

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.snapscript.common.Cache;
import org.snapscript.common.CompoundIterator;
import org.snapscript.common.HashCache;

public class LocalState implements State {
   
   private final Cache values;
   private final Scope scope;

   public LocalState(Scope scope) {
      this(scope, null);
   }
   
   public LocalState(Scope scope, List stack) {
      this.values = new HashCache();
      this.scope = scope;
   }

   @Override
   public Iterator iterator() {
      Set keys = values.keySet();
      Iterator inner = keys.iterator();
      
      if(scope != null) {
         State state = scope.getState();
         Iterator outer = state.iterator();
         
         return new CompoundIterator(inner, outer);
      }
      return inner;
   }

   @Override
   public Value get(String name) {
      Value value = values.fetch(name);
      
      if(value == null && scope != null) {
         State state = scope.getState();
         
         if(state == null) {
            throw new InternalStateException("Scope for '" + name + "' does not exist");
         }
         return state.get(name);
      }
      return value;
   }
   
   @Override
   public void add(String name, Value value) {
      Value variable = values.fetch(name);

      if(variable != null) {
         throw new InternalStateException("Variable '" + name + "' already exists");
      }
      values.cache(name, value);  
   }
   
   @Override
   public String toString() {
      return String.valueOf(values);
   }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy