Newer
Older
RDLProofSystem / src / main / java / models / terms / meta / MetaRDLTerm.java
package models.terms.meta;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import exceptions.IllegalTypeException;
import exceptions.SubstituteFailedException;
import exceptions.SyntaxException;
import lombok.Getter;
import models.algebra.Expression;
import models.algebra.Symbol;
import models.algebra.Variable;
import models.terms.Dependency;
import models.terms.DependencyTerm;
import models.terms.EvaluatableTerm;
import models.terms.LinearRightNormalizedType;
import models.terms.RDLTerm;
import models.terms.Resource;
import utils.Permutation;
@Getter
public class MetaRDLTerm extends RDLTerm {

	protected TermType termType;
	protected LinearRightNormalizedType linearRightNormalizedType = LinearRightNormalizedType.UNDEFINED;
	
	protected MetaRDLTerm(Symbol symbol, TermType termType, int size) {
		super(symbol, -1, size);
		this.termType = termType;
		if (isResourceVariable()) {
			linearRightNormalizedType = LinearRightNormalizedType.LINEAR_RIGHT_NORMALIZED;
		}
	}
	
	//dependency
	public MetaRDLTerm(MetaRDLTerm dependingTerm, Set<MetaRDLTerm> dependedTerms) {
		super(new Symbol(":", 1 + dependedTerms.size()), -1, -1);
		int size = dependingTerm.getSize();
		addChild(dependingTerm);
		for (MetaRDLTerm dependedTerm: new TreeSet<>(dependedTerms)) {
			addChild(dependedTerm);
			size += dependedTerm.getSize();
		}
		this.size = size;
		this.termType = TermType.META_DEPENDENCY;
	}
	
	public MetaRDLTerm(MetaRDLTerm dependingTerm, MetaRDLTerm dependedTerm) {
		this(dependingTerm, new TreeSet<>(Set.of(dependedTerm)));
	}
	
	//dependency term
	public MetaRDLTerm(MetaRDLTerm dependingTerm, List<MetaRDLTerm> terms) {
		super(new Symbol(":", terms.size() + 1), -1, -1);
		if (! EvaluatableTerm.class.isAssignableFrom(dependingTerm.getTermType().getBaseTermClass())) {
			throw new IllegalTypeException();
		}
		if (terms.size() % 2 != 0) {
			throw new SyntaxException("");
		}
		int size = dependingTerm.getSize();
		addChild(dependingTerm);
		TreeMap<MetaRDLTerm, MetaRDLTerm> sortedTerms = new TreeMap<>();
		for (int i = 0; i < terms.size() / 2; i++) {
			MetaRDLTerm dependedTerm = terms.get(2 * i);
			MetaRDLTerm argTerm = terms.get(2 * i + 1);
			size += dependedTerm.getSize();
			size += argTerm.getSize();
			if (! EvaluatableTerm.class.isAssignableFrom(dependedTerm.getTermType().getBaseTermClass())) {
				throw new IllegalTypeException();
			}
			if (! EvaluatableTerm.class.isAssignableFrom(argTerm.getTermType().getBaseTermClass())) {
				throw new IllegalTypeException();
			}
			sortedTerms.put(dependedTerm, argTerm);
		}
		this.size = size;
		for (MetaRDLTerm dependedTerm: sortedTerms.keySet()) {
			MetaRDLTerm argTerm = sortedTerms.get(dependedTerm);
			addChild(dependedTerm);
			addChild(argTerm);
 		}
		this.termType = TermType.META_DEPENDENCY_TERM;
	}
	
	public MetaRDLTerm(MetaRDLTerm dependingTerm, MetaRDLTerm ...terms) {
		this(dependingTerm, Arrays.asList(terms));
	}
	
	public RDLTerm substitute(Map<Variable, RDLTerm> binding) {
		return substitute(binding, 0);
	}
	
	protected RDLTerm substitute(Map<Variable, RDLTerm> binding, int depth) {
		RDLTerm dependingTerm = (RDLTerm) getChild(0);
		if (dependingTerm instanceof MetaRDLTerm) {
			dependingTerm = ((MetaRDLTerm) dependingTerm).substitute(binding, depth + 1);
		}
		if (isDependency()) {
			List<EvaluatableTerm> dependedTerms = new ArrayList<>();
			for (int i = 1; i < getChildren().size(); i++) {
				RDLTerm dependedTerm = (RDLTerm) getChild(i);
				if (dependedTerm instanceof MetaRDLTerm metaTerm) {
					dependedTerm = metaTerm.substitute(binding, depth + 1);
				}
				if (dependedTerm instanceof EvaluatableTerm te) {
					dependedTerms.add(te);
				} else {
					throw new SubstituteFailedException("Syntax error");
				}
			}
			try {
				return new Dependency(dependingTerm, dependedTerms);
			} catch (SyntaxException e) {
				throw new SubstituteFailedException(e.getMessage());
			}
		}
		else if (isDependencyTerm()) {
			List<EvaluatableTerm> termPairs = new ArrayList<>();
			for (int i = 0; i < (getChildren().size() - 1) / 2; i++) {
				RDLTerm dependedTerm = (RDLTerm) getChild(i * 2 + 1);
				RDLTerm argTerm = (RDLTerm) getChild(i * 2 + 2);
				if (dependedTerm instanceof MetaRDLTerm metaTerm) {
					dependedTerm = metaTerm.substitute(binding, depth + 1);
				}
				if (argTerm instanceof MetaRDLTerm metaTerm) {
					argTerm = metaTerm.substitute(binding, depth + 1);
				}
				termPairs.add((EvaluatableTerm) dependedTerm);
				termPairs.add((EvaluatableTerm) argTerm);
			}
			try {
				return new DependencyTerm((EvaluatableTerm) dependingTerm, termPairs);
			} catch (SyntaxException e) {
				throw new SubstituteFailedException(e.getMessage());
			}
		}
		throw new SubstituteFailedException();
	}
	
	public boolean isVariable() {
		return false;
	}
	
	public Set<MatchConstraint> isMatchedBy(RDLTerm another) {
		return isMatchedBy(another, MatchConstraint.createDefault(), 0);
	}
	
	public Set<MatchConstraint> isMatchedBy(RDLTerm another, MatchConstraint constraint) {
		return isMatchedBy(another, constraint, 0);
	}
	
	public Set<MatchConstraint> isMatchedBy(RDLTerm another, Set<MatchConstraint> constraints) {
		return isMatchedBy(another, constraints, 0);
	}
	
	protected Set<MatchConstraint> isMatchedBy(RDLTerm another, Set<MatchConstraint> constraints, int depth) {
		Set<MatchConstraint> result = new HashSet<>();
		for (MatchConstraint constraint : constraints) {
			result.addAll(isMatchedBy(another, constraint, depth + 1));
		}
		return result;
	}
	
	protected Set<MatchConstraint> isMatchedBy(RDLTerm another, MatchConstraint constraint, int depth) {
		Set<MatchConstraint> result = new HashSet<>();
		if (! another.getClass().isAssignableFrom(this.termType.getBaseTermClass())) {
			return result;
		}
		if (isDependencyTerm() && (! islinearRightNormalizedMatchedBy(another))) {
			return result;
		}
		RDLTerm dependingChild = (RDLTerm) this.getChild(0);
		RDLTerm anotherDependingChild = (RDLTerm) another.getChild(0);
		Set<MatchConstraint> res = new HashSet<>();
		if (dependingChild instanceof MetaRDLTerm) {
			MetaRDLTerm metaChild = (MetaRDLTerm) dependingChild;
			result = metaChild.isMatchedBy(anotherDependingChild, constraint, depth + 1);
		} else {
			if (!(dependingChild.equals(anotherDependingChild))) {
				return result;
			}
		}
		if (isDependencyTerm()) {
			return dependencyTermMatch(another, result, depth);
		} else if (isDependency()) {
			return dependencyMatch(another, result, depth);
		}
		return result;
	}
	
	private Set<MatchConstraint> dependencyMatch(RDLTerm another, Set<MatchConstraint> constraint, int depth) {
		Set<MatchConstraint> result = new HashSet<>();
		for (List<Integer> perm : Permutation.permutation(another.getChildren().size() - 1)) {
			Set<MatchConstraint> localResult = new HashSet<>(constraint);
			boolean flg = true;
			for (int metaTermIndex = 0; metaTermIndex < perm.size(); metaTermIndex++) {
				int anotherTermIndex = perm.get(metaTermIndex);
				RDLTerm metaDependedTerm = (RDLTerm) getChild(metaTermIndex + 1);
				RDLTerm anotherDependedTerm = (RDLTerm) another.getChild(anotherTermIndex + 1);
				if (metaDependedTerm instanceof MetaRDLTerm metaTerm) {
					localResult = metaTerm.isMatchedBy(anotherDependedTerm, localResult, depth + 1);
					if (localResult.isEmpty()) {
						flg = false;
						break;
					}
				} else {
					if (!(metaDependedTerm.equals(anotherDependedTerm))) {
						flg = false;
						break;
					}
				}
			}
			if (flg) {
				result.addAll(localResult);
			}
		}
		return result;
	}
	
	private Set<MatchConstraint> dependencyTermMatch(RDLTerm another, Set<MatchConstraint> constraint, int depth) {
		Set<MatchConstraint> result = new HashSet<>();
		for (List<Integer> perm : Permutation.permutation((another.getChildren().size() - 1) / 2)) {
			Set<MatchConstraint> localResult = new HashSet<>(constraint);
			boolean flg = true;;
			for (int metaTermIndex = 0; metaTermIndex < perm.size(); metaTermIndex++) {
				int anotherTermIndex = perm.get(metaTermIndex);
				RDLTerm metaDependedTerm = (RDLTerm) getChild(2 * metaTermIndex + 1);
				RDLTerm anotherDependedTerm = (RDLTerm) another.getChild(2 * anotherTermIndex + 1);
				RDLTerm metaArgTerm = (RDLTerm) getChild(2 * metaTermIndex + 2);
				RDLTerm anotherArgTerm = (RDLTerm) another.getChild(2 * anotherTermIndex + 2);
				if (metaDependedTerm instanceof MetaRDLTerm metaTerm) {
					localResult = metaTerm.isMatchedBy(anotherDependedTerm, localResult, depth + 1);
					if (localResult.isEmpty()) {
						flg = false;
						break;
					}
				} else {
					if (!(metaDependedTerm.equals(anotherDependedTerm))) {
						flg = false;
						break;
					}
				}
				if (metaArgTerm instanceof MetaRDLTerm metaTerm) {
					localResult = metaTerm.isMatchedBy(anotherArgTerm, localResult, depth + 1);
					if (localResult.isEmpty()) {
						flg = false;
						break;
					}
				} else {
					if (!(metaArgTerm.equals(anotherArgTerm))) {
						flg = false;
						break;
					}
				}
			}
			if (flg) {
				result.addAll(localResult);
			}
		}
		return result;
	}
	
	public boolean checkTermType(Class<? extends RDLTerm> clazz) {
		return clazz.isAssignableFrom(termType.getBaseTermClass());
	}
	
	public boolean isDependency() {
		return checkTermType(Dependency.class);
	}
	
	public boolean isEvaluatableTerm() {
		return checkTermType(EvaluatableTerm.class);
	}
	
	public boolean isDependencyTerm() {
		return checkTermType(DependencyTerm.class);
	}
	
	public boolean isResourceVariable() {
		return checkTermType(Resource.class);
	}
	
	public void setLinearRightNormalizedType(LinearRightNormalizedType next) {
		if (isDependency()) {
			return;
		}
		this.linearRightNormalizedType = next;
	}
	
	public Collection<MetaVariable> getAllVariables() {
		return getSubTerms(MetaVariable.class).values();
	}
	
	protected boolean islinearRightNormalizedMatchedBy(RDLTerm another) {
		if (linearRightNormalizedType != LinearRightNormalizedType.UNDEFINED) {
			if (another instanceof DependencyTerm) {
				if (((DependencyTerm) another).getLinearRightNormalizedType() != linearRightNormalizedType) {
					return false;
				}
			}
			else if (another instanceof MetaRDLTerm) {
				if (((MetaRDLTerm) another).getLinearRightNormalizedType() != linearRightNormalizedType) {
					return false;
				}
			}
		}
		return true;
	}
	
	
	@Override
	public String toString() {
		switch(termType) {
		case META_DEPENDENCY:
			return "[" + getChild(0).toString() + " : " + getChildren().stream().skip(1).map(Expression::toString).collect(Collectors.joining(",")) + "]";
		case META_DEPENDENCY_TERM:
			return "[" + getChild(0).toString() + " : " + IntStream.range(0, (getChildren().size() - 1) / 2)
					.mapToObj(i -> getChild(i * 2 + 1).toString() + " -> " + getChild(i * 2 + 2)).collect(Collectors.joining(",")) + "]";
		default:
			return "";
		}
	}

	@Override
	public String toStringWithOrder() {
		switch(termType) {
		case META_DEPENDENCY:
			return "[" + ((RDLTerm) getChild(0)).toStringWithOrder() + " : " + ((RDLTerm) getChild(1)).toStringWithOrder() + "]";
		case META_DEPENDENCY_LIST:
			return "[" + ((RDLTerm) getChild(0)).toStringWithOrder() + "]";
		case META_DEPENDENCY_TERM:
			return "[" + ((RDLTerm) getChild(0)).toStringWithOrder() + " : "
					+ ((RDLTerm) getChild(1)).toStringWithOrder() + " -> " + ((RDLTerm) getChild(2)).toStringWithOrder() + "]";
		default:
			return "";
		}
	}

	@Override
	public boolean equals(Object another) {
		if(! (another instanceof MetaRDLTerm)) {
			return false;
		}
		MetaRDLTerm anotherTerm = (MetaRDLTerm) another;
		return super.equals(another) && termType == anotherTerm.getTermType();
	}

	@Override
	public int hashCode() {
		return (termType.toString() + toStringWithOrder()).hashCode();
	}

	@Override
	public Object clone() {

		return null;
	}

	protected static enum TermType {
		META_RDL_TERM(RDLTerm.class),
		META_DEPENDENCY(Dependency.class),
		META_DEPENDENCY_LIST(Dependency.class),
		META_DEPENDENCY_VARIABLE(Dependency.class),
		META_DEPENDENCY_TERM(DependencyTerm.class),
		META_DEPENDENCY_TERM_VARIABLE(DependencyTerm.class),
		META_EVALUATABLE_TERM_VARIABLE(EvaluatableTerm.class),
		META_RESOURCE_VARIABLE(Resource.class);
		
		@Getter
		private Class<?> baseTermClass;
		
		private TermType(Class<?> clazz) {
			this.baseTermClass = clazz;
		}
		
	}
	
}