Newer
Older
AlgebraicDataflowArchitectureModel / AlgebraicDataflowArchitectureModel / src / models / dataConstraintModel / MapTerm.java
package models.dataConstraintModel;

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

import models.algebra.Constant;
import models.algebra.Expression;
import models.algebra.Symbol;
import models.algebra.Term;
import parser.Parser;

public class MapTerm extends Term {
	private Map<String, Integer> keyToIndex = new HashMap<>();

	public MapTerm() {
		super(new Symbol("map", -1));
		setType(DataConstraintModel.typeMap);
	}
	
	public void insert(String key, Expression value) {
		if (keyToIndex.containsKey(key)) {
			setChild(keyToIndex.get(key), value);
		} else {
			keyToIndex.put(key, getChildren().size());
			addChild(value);
		}
	}
	
	public Set<String> keySet() {
		return keyToIndex.keySet();
	}

	public Expression get(String key) {
		return getChild(keyToIndex.get(key));
	}

	public Expression get(Constant key) {
		if (keyToIndex.get(key.getValue()) == null) return null;
		return getChild(keyToIndex.get(key.getValue()));
	}
	
	@Override
	public Object clone() {
		MapTerm newTerm = new MapTerm();
		for (Expression e: children) {
			newTerm.addChild((Expression) e.clone());
		}
		newTerm.keyToIndex = new HashMap<String, Integer>(keyToIndex);
		return newTerm;
	}
	
	public String toString() {
		String mapStr = "{";
		String delim = "";
		for (String key: keyToIndex.keySet()) {
			mapStr += delim + Parser.DOUBLE_QUOT + key + Parser.DOUBLE_QUOT + ": " + getChild(keyToIndex.get(key)).toString();
			delim = ", ";
		}
		return mapStr + "}";
	}
}