1 package org.simantics.scl.compiler.elaboration.expressions;
3 import java.util.ArrayList;
5 import org.simantics.scl.compiler.common.exceptions.InternalCompilerError;
6 import org.simantics.scl.compiler.common.precedence.Precedence;
7 import org.simantics.scl.compiler.compilation.CompilationContext;
8 import org.simantics.scl.compiler.constants.NoRepConstant;
9 import org.simantics.scl.compiler.elaboration.contexts.ReplaceContext;
10 import org.simantics.scl.compiler.elaboration.contexts.SimplificationContext;
11 import org.simantics.scl.compiler.elaboration.contexts.TranslationContext;
12 import org.simantics.scl.compiler.elaboration.contexts.TypingContext;
13 import org.simantics.scl.compiler.elaboration.errors.NotPatternException;
14 import org.simantics.scl.compiler.elaboration.expressions.lhstype.LhsType;
15 import org.simantics.scl.compiler.elaboration.expressions.lhstype.PatternMatchingLhs;
16 import org.simantics.scl.compiler.elaboration.expressions.printing.ExpressionToStringVisitor;
17 import org.simantics.scl.compiler.elaboration.expressions.visitors.CollectRefsVisitor;
18 import org.simantics.scl.compiler.elaboration.expressions.visitors.ForVariablesUsesVisitor;
19 import org.simantics.scl.compiler.elaboration.query.QAtom;
20 import org.simantics.scl.compiler.elaboration.relations.SCLRelation;
21 import org.simantics.scl.compiler.internal.codegen.references.IVal;
22 import org.simantics.scl.compiler.internal.codegen.writer.CodeWriter;
23 import org.simantics.scl.compiler.internal.elaboration.decomposed.DecomposedExpression;
24 import org.simantics.scl.compiler.internal.interpreted.IExpression;
25 import org.simantics.scl.compiler.internal.parsing.Symbol;
26 import org.simantics.scl.compiler.top.ExpressionInterpretationContext;
27 import org.simantics.scl.compiler.types.TForAll;
28 import org.simantics.scl.compiler.types.TFun;
29 import org.simantics.scl.compiler.types.TPred;
30 import org.simantics.scl.compiler.types.TVar;
31 import org.simantics.scl.compiler.types.Type;
32 import org.simantics.scl.compiler.types.Types;
33 import org.simantics.scl.compiler.types.exceptions.MatchException;
34 import org.simantics.scl.compiler.types.kinds.Kinds;
35 import org.simantics.scl.compiler.types.util.Typed;
37 import gnu.trove.map.hash.TObjectIntHashMap;
38 import gnu.trove.set.hash.THashSet;
39 import gnu.trove.set.hash.TIntHashSet;
41 public abstract class Expression extends Symbol implements Typed {
42 public static final Expression[] EMPTY_ARRAY = new Expression[0];
50 public Expression(long loc) {
55 public Type getType() {
59 } catch (MatchException e) {
60 throw new InternalCompilerError(e);
63 throw new InternalCompilerError(getClass().getSimpleName() +
64 ".updateType couldn't compute its type.");
69 public void setType(Type type) {
71 throw new NullPointerException();
76 * Infers the type of the expression without any context. Adds type
77 * applications and lambdas if needed.
79 public Expression inferType(TypingContext context) {
80 return checkBasicType(context, Types.metaVar(Kinds.STAR));
83 public Expression checkBasicType(TypingContext context, Type requiredType) {
84 return context.subsume(inferType(context), requiredType);
87 protected Expression applyPUnit(TypingContext context) {
88 Type type = Types.canonical(getType());
89 if(type instanceof TFun) {
90 TFun fun = (TFun)type;
91 if(fun.getCanonicalDomain() == Types.PUNIT) {
92 EApply result = new EApply(location, this, new ELiteral(NoRepConstant.PUNIT));
93 result.effect = fun.getCanonicalEffect();
94 context.declareEffect(this.location, result.effect);
101 public Expression checkIgnoredType(TypingContext context) {
102 Expression expression = inferType(context);
103 if(Types.canonical(expression.getType()) != Types.UNIT)
104 expression = new ESimpleLet(location, null, expression, new ELiteral(NoRepConstant.PUNIT));
109 * Checks the type of the expression against the given type. Adds type
110 * applications and lambdas if needed.
112 public final Expression checkType(TypingContext context, Type requiredType) {
113 //System.out.println("checkType: " + this + " :: " + requiredType);
114 if(!context.isInPattern()) {
115 requiredType = Types.canonical(requiredType);
116 if(requiredType instanceof TForAll) {
117 TForAll forAll = (TForAll)requiredType;
118 TVar var = forAll.var;
119 TVar newVar = Types.var(var.getKind());
120 requiredType = Types.canonical(forAll.type).replace(var, newVar);
121 return new ELambdaType(new TVar[] {newVar}, checkType(context, requiredType));
123 while(requiredType instanceof TFun) {
124 TFun fun = (TFun)requiredType;
125 if(fun.domain instanceof TPred) { // No need to canonicalize
126 ArrayList<Variable> constraints = new ArrayList<Variable>(2);
128 constraints.add(new Variable("constraint", fun.domain));
129 requiredType = Types.canonical(fun.range);
130 if(!(requiredType instanceof TFun))
132 fun = (TFun)requiredType;
133 if(!(fun.domain instanceof TPred))
136 context.pushConstraintFrame(constraints.toArray(new Variable[constraints.size()]));
137 Expression expression = checkType(context, requiredType);
138 context.popConstraintFrame();
139 for(int i=constraints.size()-1;i>=0;--i)
140 expression = new ESimpleLambda(constraints.get(i), expression);
143 else if(fun.domain == Types.PUNIT) {
144 context.pushEffectUpperBound(location, fun.effect);
145 Expression expr = checkType(context, fun.range);
146 context.popEffectUpperBound();
149 Variable var = new Variable("punit", Types.PUNIT);
150 return new ESimpleLambda(location, var, fun.effect, expr);
156 return checkBasicType(context, requiredType);
159 public final void collectRefs(TObjectIntHashMap<Object> allRefs, TIntHashSet refs) {
160 accept(new CollectRefsVisitor(allRefs, refs));
163 public abstract void collectVars(TObjectIntHashMap<Variable> allVars, TIntHashSet vars);
165 public final void forVariableUses(VariableProcedure procedure) {
166 accept(new ForVariablesUsesVisitor(procedure));
169 public Expression decomposeMatching() {
173 public String toString() {
174 StringBuilder b = new StringBuilder();
175 ExpressionToStringVisitor visitor = new ExpressionToStringVisitor(b);
180 protected abstract void updateType() throws MatchException;
182 public static class TypeValidationException extends Exception {
183 private static final long serialVersionUID = 3181298127162041248L;
187 public TypeValidationException(long loc) {
191 public long getLoc() {
195 public TypeValidationException(long loc, Throwable cause) {
201 public static void assertEquals(long loc, Type a, Type b) throws TypeValidationException {
202 if(!Types.equals(a, b))
203 throw new TypeValidationException(loc);
206 public abstract IVal toVal(CompilationContext context, CodeWriter w);
208 public Expression closure(TVar ... vars) {
211 return new ELambdaType(vars, this);
214 public abstract void collectFreeVariables(THashSet<Variable> vars);
216 public Expression simplify(SimplificationContext context) {
217 System.out.println("#############################");
218 System.out.println(this);
219 throw new InternalCompilerError(location, getClass().getSimpleName() + " does not support simplify method.");
222 public abstract Expression resolve(TranslationContext context);
225 * Returns head of the pattern.
227 public EVar getPatternHead() throws NotPatternException {
228 throw new NotPatternException(this);
231 public LhsType getLhsType() throws NotPatternException {
232 throw new NotPatternException(this);
235 protected void collectVariableNames(PatternMatchingLhs lhsType) throws NotPatternException {
236 throw new NotPatternException(this);
239 public void getParameters(TranslationContext translationContext,
240 ArrayList<Expression> parameters) {
241 throw new InternalCompilerError("Class " + getClass().getSimpleName() + " does not support getParameters.");
244 public Expression resolveAsPattern(TranslationContext context) {
245 context.getErrorLog().log(location, "Pattern was expected here.");
249 public void removeFreeVariables(THashSet<Variable> vars) {
250 throw new InternalCompilerError(getClass().getSimpleName() + " is not a pattern.");
253 public Expression checkTypeAsPattern(TypingContext context, Type requiredType) {
254 if(context.isInPattern())
255 throw new InternalCompilerError("Already in a pattern.");
256 context.setInPattern(true);
257 Expression expression = checkType(context, requiredType);
258 context.setInPattern(false);
263 * Used during simplification and in toIExpression
265 public THashSet<Variable> getFreeVariables() {
266 THashSet<Variable> result = new THashSet<Variable>();
267 collectFreeVariables(result);
271 public static Expression[] concat(Expression[] a, Expression[] b) {
276 Expression[] result = new Expression[a.length + b.length];
277 for(int i=0;i<a.length;++i)
279 for(int i=0;i<b.length;++i)
280 result[i+a.length] = b[i];
284 public Expression replace(ReplaceContext context) {
285 throw new InternalCompilerError(getClass().getSimpleName() + " does not support replace.");
288 public static Expression[] replace(ReplaceContext context, Expression[] expressions) {
289 Expression[] result = new Expression[expressions.length];
290 for(int i=0;i<expressions.length;++i)
291 result[i] = expressions[i].replace(context);
295 public Expression copy() {
296 return replace(new ReplaceContext(null));
299 public Expression copy(TypingContext typingContext) {
300 return replace(new ReplaceContext(typingContext));
303 public abstract void setLocationDeep(long loc);
305 public Expression replaceInPattern(ReplaceContext context) {
306 context.inPattern = true;
307 Expression result = replace(context);
308 context.inPattern = false;
312 public int getFunctionDefinitionPatternArity() throws NotPatternException {
313 throw new NotPatternException(this);
316 public IVal lambdaToVal(CompilationContext context, CodeWriter w) {
317 DecomposedExpression decomposed = DecomposedExpression.decompose(context.errorLog, this);
318 CodeWriter newW = w.createFunction(decomposed.typeParameters, decomposed.effect, decomposed.returnType, decomposed.parameterTypes);
319 IVal[] parameters = newW.getParameters();
320 IVal functionVal = newW.getFunction().getTarget();
321 for(int i=0;i<parameters.length;++i)
322 decomposed.parameters[i].setVal(parameters[i]);
323 newW.return_(decomposed.body.toVal(context, newW));
327 public IExpression toIExpression(ExpressionInterpretationContext context) {
328 throw new UnsupportedOperationException();
331 public static IExpression[] toIExpressions(ExpressionInterpretationContext target, Expression[] expressions) {
332 IExpression[] result = new IExpression[expressions.length];
333 for(int i=0;i<expressions.length;++i)
334 result[i] = expressions[i].toIExpression(target);
338 public Expression applyType(Type type) {
339 return new EApplyType(location, this, type);
342 public boolean isEffectful() {
346 public boolean isFunctionPattern() {
350 public boolean isConstructorApplication() {
354 public abstract void collectEffects(THashSet<Type> effects);
356 public Type getEffect() {
357 THashSet<Type> effects = new THashSet<Type>();
358 collectEffects(effects);
359 return Types.union(effects.toArray(new Type[effects.size()]));
362 public abstract void accept(ExpressionVisitor visitor);
364 public void collectRelationRefs(
365 final TObjectIntHashMap<SCLRelation> allRefs, final TIntHashSet refs) {
366 accept(new StandardExpressionVisitor() {
368 public void visit(QAtom query) {
369 int id = allRefs.get(query.relation);
376 public boolean isFunctionDefinitionLhs() {
380 public Precedence getPrecedence() {
381 return Precedence.DEFAULT;
384 public boolean isPattern(int arity) {
388 public abstract Expression accept(ExpressionTransformer transformer);
390 // TODO implement for all expressions
391 public boolean equalsExpression(Expression expression) {
396 * This method returns a lower bound for the function arity of the value this expression defines.
397 * The lower bound is calculated purely looking the syntax of the expression, not the
398 * types of the constants and variables the expression refers to.
400 public int getSyntacticFunctionArity() {