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.query.QAtom;
18 import org.simantics.scl.compiler.elaboration.relations.SCLRelation;
19 import org.simantics.scl.compiler.internal.codegen.references.IVal;
20 import org.simantics.scl.compiler.internal.codegen.writer.CodeWriter;
21 import org.simantics.scl.compiler.internal.elaboration.decomposed.DecomposedExpression;
22 import org.simantics.scl.compiler.internal.interpreted.IExpression;
23 import org.simantics.scl.compiler.internal.parsing.Symbol;
24 import org.simantics.scl.compiler.top.ExpressionInterpretationContext;
25 import org.simantics.scl.compiler.types.TForAll;
26 import org.simantics.scl.compiler.types.TFun;
27 import org.simantics.scl.compiler.types.TPred;
28 import org.simantics.scl.compiler.types.TVar;
29 import org.simantics.scl.compiler.types.Type;
30 import org.simantics.scl.compiler.types.Types;
31 import org.simantics.scl.compiler.types.exceptions.MatchException;
32 import org.simantics.scl.compiler.types.kinds.Kinds;
33 import org.simantics.scl.compiler.types.util.Typed;
35 import gnu.trove.map.hash.TObjectIntHashMap;
36 import gnu.trove.set.hash.THashSet;
37 import gnu.trove.set.hash.TIntHashSet;
39 public abstract class Expression extends Symbol implements Typed {
40 public static final Expression[] EMPTY_ARRAY = new Expression[0];
48 public Expression(long loc) {
53 public Type getType() {
57 } catch (MatchException e) {
58 throw new InternalCompilerError(e);
61 throw new InternalCompilerError(getClass().getSimpleName() +
62 ".updateType couldn't compute its type.");
67 public void setType(Type type) {
69 throw new NullPointerException();
74 * Infers the type of the expression without any context. Adds type
75 * applications and lambdas if needed.
77 public Expression inferType(TypingContext context) {
78 return checkBasicType(context, Types.metaVar(Kinds.STAR));
81 public Expression checkBasicType(TypingContext context, Type requiredType) {
82 return context.subsume(inferType(context), requiredType);
85 protected Expression applyPUnit(TypingContext context) {
86 Type type = Types.canonical(getType());
87 if(type instanceof TFun) {
88 TFun fun = (TFun)type;
89 if(fun.getCanonicalDomain() == Types.PUNIT) {
90 EApply result = new EApply(location, this, new ELiteral(NoRepConstant.PUNIT));
91 result.effect = fun.getCanonicalEffect();
92 context.declareEffect(this.location, result.effect);
99 public Expression checkIgnoredType(TypingContext context) {
100 Expression expression = inferType(context);
101 if(Types.canonical(expression.getType()) != Types.UNIT)
102 expression = new ESimpleLet(location, null, expression, new ELiteral(NoRepConstant.PUNIT));
107 * Checks the type of the expression against the given type. Adds type
108 * applications and lambdas if needed.
110 public final Expression checkType(TypingContext context, Type requiredType) {
111 //System.out.println("checkType: " + this + " :: " + requiredType);
112 if(!context.isInPattern()) {
113 requiredType = Types.canonical(requiredType);
114 if(requiredType instanceof TForAll) {
115 TForAll forAll = (TForAll)requiredType;
116 TVar var = forAll.var;
117 TVar newVar = Types.var(var.getKind());
118 requiredType = Types.canonical(forAll.type).replace(var, newVar);
119 return new ELambdaType(new TVar[] {newVar}, checkType(context, requiredType));
121 while(requiredType instanceof TFun) {
122 TFun fun = (TFun)requiredType;
123 if(fun.domain instanceof TPred) { // No need to canonicalize
124 ArrayList<Variable> constraints = new ArrayList<Variable>(2);
126 constraints.add(new Variable("constraint", fun.domain));
127 requiredType = Types.canonical(fun.range);
128 if(!(requiredType instanceof TFun))
130 fun = (TFun)requiredType;
131 if(!(fun.domain instanceof TPred))
134 context.pushConstraintFrame(constraints.toArray(new Variable[constraints.size()]));
135 Expression expression = checkType(context, requiredType);
136 context.popConstraintFrame();
137 for(int i=constraints.size()-1;i>=0;--i)
138 expression = new ESimpleLambda(constraints.get(i), expression);
141 else if(fun.domain == Types.PUNIT) {
142 context.pushEffectUpperBound(location, fun.effect);
143 Expression expr = checkType(context, fun.range);
144 context.popEffectUpperBound();
147 Variable var = new Variable("punit", Types.PUNIT);
148 return new ESimpleLambda(location, var, fun.effect, expr);
154 return checkBasicType(context, requiredType);
157 public abstract void collectRefs(TObjectIntHashMap<Object> allRefs, TIntHashSet refs);
158 public abstract void collectVars(TObjectIntHashMap<Variable> allVars, TIntHashSet vars);
159 public abstract void forVariables(VariableProcedure procedure);
161 public Expression decomposeMatching() {
165 public String toString() {
166 StringBuilder b = new StringBuilder();
167 ExpressionToStringVisitor visitor = new ExpressionToStringVisitor(b);
172 protected abstract void updateType() throws MatchException;
174 public static class TypeValidationException extends Exception {
175 private static final long serialVersionUID = 3181298127162041248L;
179 public TypeValidationException(long loc) {
183 public long getLoc() {
187 public TypeValidationException(long loc, Throwable cause) {
193 public static void assertEquals(long loc, Type a, Type b) throws TypeValidationException {
194 if(!Types.equals(a, b))
195 throw new TypeValidationException(loc);
198 public abstract IVal toVal(CompilationContext context, CodeWriter w);
200 public Expression closure(TVar ... vars) {
203 return new ELambdaType(vars, this);
206 public abstract void collectFreeVariables(THashSet<Variable> vars);
208 public Expression simplify(SimplificationContext context) {
209 System.out.println("#############################");
210 System.out.println(this);
211 throw new InternalCompilerError(location, getClass().getSimpleName() + " does not support simplify method.");
214 public abstract Expression resolve(TranslationContext context);
217 * Returns head of the pattern.
219 public EVar getPatternHead() throws NotPatternException {
220 throw new NotPatternException(this);
223 public LhsType getLhsType() throws NotPatternException {
224 throw new NotPatternException(this);
227 protected void collectVariableNames(PatternMatchingLhs lhsType) throws NotPatternException {
228 throw new NotPatternException(this);
231 public void getParameters(TranslationContext translationContext,
232 ArrayList<Expression> parameters) {
233 throw new InternalCompilerError("Class " + getClass().getSimpleName() + " does not support getParameters.");
236 public Expression resolveAsPattern(TranslationContext context) {
237 context.getErrorLog().log(location, "Pattern was expected here.");
241 public void removeFreeVariables(THashSet<Variable> vars) {
242 throw new InternalCompilerError(getClass().getSimpleName() + " is not a pattern.");
245 public Expression checkTypeAsPattern(TypingContext context, Type requiredType) {
246 if(context.isInPattern())
247 throw new InternalCompilerError("Already in a pattern.");
248 context.setInPattern(true);
249 Expression expression = checkType(context, requiredType);
250 context.setInPattern(false);
255 * Used during simplification and in toIExpression
257 public THashSet<Variable> getFreeVariables() {
258 THashSet<Variable> result = new THashSet<Variable>();
259 collectFreeVariables(result);
263 public static Expression[] concat(Expression[] a, Expression[] b) {
268 Expression[] result = new Expression[a.length + b.length];
269 for(int i=0;i<a.length;++i)
271 for(int i=0;i<b.length;++i)
272 result[i+a.length] = b[i];
276 public Expression replace(ReplaceContext context) {
277 throw new InternalCompilerError(getClass().getSimpleName() + " does not support replace.");
280 public static Expression[] replace(ReplaceContext context, Expression[] expressions) {
281 Expression[] result = new Expression[expressions.length];
282 for(int i=0;i<expressions.length;++i)
283 result[i] = expressions[i].replace(context);
287 public Expression copy() {
288 return replace(new ReplaceContext(null));
291 public Expression copy(TypingContext typingContext) {
292 return replace(new ReplaceContext(typingContext));
295 public abstract void setLocationDeep(long loc);
297 public Expression replaceInPattern(ReplaceContext context) {
298 context.inPattern = true;
299 Expression result = replace(context);
300 context.inPattern = false;
304 public int getFunctionDefinitionPatternArity() throws NotPatternException {
305 throw new NotPatternException(this);
308 public IVal lambdaToVal(CompilationContext context, CodeWriter w) {
309 DecomposedExpression decomposed = DecomposedExpression.decompose(context.errorLog, this);
310 CodeWriter newW = w.createFunction(decomposed.typeParameters, decomposed.effect, decomposed.returnType, decomposed.parameterTypes);
311 IVal[] parameters = newW.getParameters();
312 IVal functionVal = newW.getFunction().getTarget();
313 for(int i=0;i<parameters.length;++i)
314 decomposed.parameters[i].setVal(parameters[i]);
315 newW.return_(decomposed.body.toVal(context, newW));
319 public IExpression toIExpression(ExpressionInterpretationContext context) {
320 throw new UnsupportedOperationException();
323 public static IExpression[] toIExpressions(ExpressionInterpretationContext target, Expression[] expressions) {
324 IExpression[] result = new IExpression[expressions.length];
325 for(int i=0;i<expressions.length;++i)
326 result[i] = expressions[i].toIExpression(target);
330 public Expression applyType(Type type) {
331 return new EApplyType(location, this, type);
334 public boolean isEffectful() {
338 public boolean isFunctionPattern() {
342 public boolean isConstructorApplication() {
346 public abstract void collectEffects(THashSet<Type> effects);
348 public Type getEffect() {
349 THashSet<Type> effects = new THashSet<Type>();
350 collectEffects(effects);
351 return Types.union(effects.toArray(new Type[effects.size()]));
354 public abstract void accept(ExpressionVisitor visitor);
356 public void collectRelationRefs(
357 final TObjectIntHashMap<SCLRelation> allRefs, final TIntHashSet refs) {
358 accept(new StandardExpressionVisitor() {
360 public void visit(QAtom query) {
361 int id = allRefs.get(query.relation);
368 public boolean isFunctionDefinitionLhs() {
372 public Precedence getPrecedence() {
373 return Precedence.DEFAULT;
376 public boolean isPattern(int arity) {
380 public abstract Expression accept(ExpressionTransformer transformer);
382 // TODO implement for all expressions
383 public boolean equalsExpression(Expression expression) {
388 * This method returns a lower bound for the function arity of the value this expression defines.
389 * The lower bound is calculated purely looking the syntax of the expression, not the
390 * types of the constants and variables the expression refers to.
392 public int getSyntacticFunctionArity() {