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

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

package org.snapscript.core;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.snapscript.common.CompoundIterator;

public class MapState implements State {
   
   private final Map values;
   private final Scope scope;
   private final Model model;
   
   public MapState() {
      this(null);
   }
  
   public MapState(Model model) {
      this(model, null);
   }
   
   public MapState(Model model, Scope scope) {
      this.values = new HashMap();
      this.model = model;
      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.get(name);
      
      if(value == null && scope != null) {
         State state = scope.getState();
         
         if(state == null) {
            throw new InternalStateException("Scope for '" + name + "' does not exist");
         }
         value = state.get(name);
      }
      if(value == null && model != null) {
         Object object = model.getAttribute(name);
         
         if(object != null) {
            return ValueType.getConstant(object);
         }
      }
      return value;
   }
   
   @Override
   public void add(String name, Value value) {
      Value variable = values.get(name);

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy