]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/elaboration/expressions/EApply.java
(refs #7621) Fixed handling of $ in application ignoring return value
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / elaboration / expressions / EApply.java
1 package org.simantics.scl.compiler.elaboration.expressions;
2
3 import java.util.ArrayList;
4
5 import org.simantics.scl.compiler.common.names.Name;
6 import org.simantics.scl.compiler.common.names.Names;
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.java.ListConstructor;
17 import org.simantics.scl.compiler.elaboration.macros.MacroRule;
18 import org.simantics.scl.compiler.elaboration.modules.SCLValue;
19 import org.simantics.scl.compiler.errors.Locations;
20 import org.simantics.scl.compiler.internal.codegen.references.IVal;
21 import org.simantics.scl.compiler.internal.codegen.writer.CodeWriter;
22 import org.simantics.scl.compiler.internal.interpreted.IApply;
23 import org.simantics.scl.compiler.internal.interpreted.IExpression;
24 import org.simantics.scl.compiler.internal.interpreted.IListLiteral;
25 import org.simantics.scl.compiler.top.ExpressionInterpretationContext;
26 import org.simantics.scl.compiler.types.Skeletons;
27 import org.simantics.scl.compiler.types.TFun;
28 import org.simantics.scl.compiler.types.Type;
29 import org.simantics.scl.compiler.types.Types;
30 import org.simantics.scl.compiler.types.exceptions.MatchException;
31 import org.simantics.scl.compiler.types.exceptions.UnificationException;
32 import org.simantics.scl.compiler.types.kinds.Kinds;
33 import org.simantics.scl.compiler.types.util.MultiFunction;
34
35 public class EApply extends Expression {
36     public Expression function;
37     public Expression[] parameters;
38     public Type effect = Types.NO_EFFECTS;
39     
40     public EApply(Expression function, Expression ... parameters) {
41         this.function = function;
42         this.parameters = parameters;
43     }
44     
45     public EApply(Expression function, Expression parameter) {
46         this(function, new Expression[] {parameter});
47     }
48
49     public EApply(long loc, Expression function, Expression ... parameters) {
50         super(loc);
51         this.function = function;
52         this.parameters = parameters;
53     }
54     
55     public EApply(long loc, Type effect, Expression function, Expression ... parameters) {
56         super(loc);
57         this.effect = effect;
58         this.function = function;
59         this.parameters = parameters;
60     }
61     
62     public void set(Expression function, Expression[] parameters) {
63         this.function = function;
64         this.parameters = parameters;
65     }
66
67     public Expression getFunction() {
68         return function;
69     }
70     
71     public Expression[] getParameters() {
72         return parameters;
73     }
74
75     @Override
76     protected void updateType() throws MatchException {
77         MultiFunction mfun = Types.matchFunction(function.getType(), parameters.length);
78         /*for(int i=0;i<parameters.length;++i)
79             if(!Types.equals(parameters[i].getType(), mfun.parameterTypes[i]))
80                 throw new MatchException();*/
81         effect = mfun.effect;
82         setType(mfun.returnType);
83         }
84
85         @Override
86         public IVal toVal(CompilationContext context, CodeWriter w) {
87         IVal functionVal = function.toVal(context, w);
88         IVal[] parameterVals = new IVal[parameters.length];
89         for(int i=0;i<parameters.length;++i)
90             parameterVals[i] = parameters[i].toVal(context, w);
91         Type type = getType();
92         effect = Types.simplifyFinalEffect(effect);
93         return w.applyWithEffect(location, effect, type, functionVal, parameterVals);
94     }
95     
96     private void combineApplications() {
97         if(function instanceof EApply) {
98             EApply apply = (EApply)function;
99             if(Types.canonical(apply.effect) == Types.NO_EFFECTS) {
100                 function = apply.function;
101                 parameters = Expression.concat(apply.parameters, parameters); 
102             } 
103         }
104     }
105
106     @Override
107     public Expression simplify(SimplificationContext context) {
108         function = function.simplify(context);
109         for(int i=0;i<parameters.length;++i)
110             parameters[i] = parameters[i].simplify(context);
111         combineApplications();
112         
113         // Try to apply macro rule
114         if(function instanceof EConstant) {
115             EConstant constant = (EConstant)function;
116             MacroRule rule = constant.value.getMacroRule();
117             if(rule != null) {
118                 Expression simplified = rule.apply(context, constant.typeParameters, this);
119                 if(simplified != null)
120                     // There may be more to simplify after macro application
121                     // However this may cause performance problems (O(n^2) algorithm in pathologic cases)
122                     return simplified.simplify(context);
123             }
124         }
125         
126         return this;
127     }
128     
129     @Override
130     public EVar getPatternHead() throws NotPatternException {
131         return function.getPatternHead();
132     }
133
134     @Override
135     public LhsType getLhsType() throws NotPatternException {
136         LhsType lhsType = function.getLhsType();
137         if(lhsType instanceof PatternMatchingLhs)
138             for(Expression parameter : parameters)
139                 parameter.collectVariableNames((PatternMatchingLhs)lhsType);
140         return lhsType;
141     }
142     
143     @Override
144     public Expression resolve(TranslationContext context) {
145         function = function.resolve(context);
146         for(int i=0;i<parameters.length;++i)
147             parameters[i] = parameters[i].resolve(context);
148         //combineApplications();
149         return this;
150     }
151     
152     @Override
153     public Expression resolveAsPattern(TranslationContext context) {
154         function = function.resolveAsPattern(context);
155         for(int i=0;i<parameters.length;++i)
156             parameters[i] = parameters[i].resolveAsPattern(context);
157         combineApplications();
158         if(!(function instanceof EConstant || function instanceof EError)) {
159             context.getErrorLog().log(location, "Only constants can be applied in patterns.");
160             return new EError();
161         }
162         return this;
163     }
164     
165     @Override
166     public void getParameters(TranslationContext context,
167             ArrayList<Expression> parameters) {
168         function.getParameters(context, parameters);
169         for(Expression parameter : this.parameters)
170             parameters.add(parameter);
171     }
172
173     @Override
174     public Expression replace(ReplaceContext context) {
175         return new EApply(
176                 getLocation(),                
177                 effect.replace(context.tvarMap),
178                 function.replace(context),
179                 replace(context, parameters));
180     }
181     
182     @Override
183     public void setLocationDeep(long loc) {
184         if(location == Locations.NO_LOCATION) {
185             location = loc;
186             function.setLocationDeep(loc);
187             for(Expression parameter : parameters)
188                 parameter.setLocationDeep(loc);
189         }
190     }
191     
192     @Override
193     public int getFunctionDefinitionPatternArity() throws NotPatternException {
194         return function.getFunctionDefinitionPatternArity() + parameters.length;
195     }
196     
197     @Override
198     public IExpression toIExpression(ExpressionInterpretationContext target) {
199         IExpression[] parametersI = toIExpressions(target, parameters);
200         
201         Expression function = this.function;
202         while(function instanceof EApplyType)
203             function = ((EApplyType)function).expression;
204         
205         // Special cases
206         if(function instanceof EConstant) {
207             SCLValue functionValue = ((EConstant)function).value;
208             Name name = functionValue.getName();
209             if(name.module.equals("Builtin")) {
210                 IVal val = functionValue.getValue();
211                 if(val instanceof ListConstructor) {
212                     if(((ListConstructor)val).arity == parametersI.length)
213                         return new IListLiteral(parametersI);
214                 }
215             }
216         }
217         //System.out.println("--> " + function + " " + function.getClass().getSimpleName());
218         
219         // The basic case
220         return new IApply(function.toIExpression(target), parametersI);
221     }
222     
223     private void inferType(TypingContext context, boolean ignoreResult) {
224         function = function.inferType(context);
225         function = context.instantiate(function);
226         MultiFunction mfun;
227         try {
228             mfun = Types.unifyFunction(function.getType(), parameters.length);
229         } catch (UnificationException e) {
230             int arity = Types.getArity(function.getType());
231             if(arity == 0)
232                 context.getErrorLog().log(location, "Application of non-function.");
233             else
234                 context.getErrorLog().log(location, "Function of arity " + arity + 
235                         " is applied with " + parameters.length + " parameters.");
236             setType(Types.metaVar(Kinds.STAR));
237             for(int i=0;i<parameters.length;++i)
238                 parameters[i] = parameters[i].inferType(context);
239             return;
240         }
241         if((ignoreResult && Skeletons.canonicalSkeleton(mfun.returnType) instanceof TFun &&
242                 Types.canonical(mfun.effect) == Types.NO_EFFECTS) ||
243                 (context.isInPattern() && Skeletons.canonicalSkeleton(mfun.returnType) instanceof TFun)) {
244             context.getErrorLog().log(location, "The function is applied with too few parameters.");
245         }
246         
247         // Check parameter types
248         for(int i=0;i<parameters.length;++i)
249             parameters[i] = parameters[i].checkType(context, mfun.parameterTypes[i]);
250
251         effect = mfun.effect;
252         
253         context.declareEffect(location, mfun.effect);
254         setType(mfun.returnType);
255     }
256     
257     @Override
258     public Expression inferType(TypingContext context) {
259         if(parameters.length == 2 && function instanceof EConstant && ((EConstant)function).value.getName() == Names.Prelude_dollar)
260             return new EApply(location, parameters[0], parameters[1]).inferType(context);
261         inferType(context, false);
262         return this;
263     }
264     
265     @Override
266     public Expression checkIgnoredType(TypingContext context) {
267         if(parameters.length == 2 && function instanceof EConstant && ((EConstant)function).value.getName() == Names.Prelude_dollar)
268             return new EApply(location, parameters[0], parameters[1]).checkIgnoredType(context);
269         inferType(context, true);
270         if(Types.canonical(getType()) != Types.UNIT)
271             return new ESimpleLet(location, null, this, new ELiteral(NoRepConstant.PUNIT));
272         return this;
273     }
274     
275     public Type getLocalEffect() {
276         return effect;
277     }
278     
279     public Expression toANormalForm(Expression root) {
280         Expression expression = root;
281         for(int i=parameters.length-1;i>=0;--i) {
282                 Expression parameter = parameters[i];
283                 if(parameter.isEffectful()) {
284                         Variable var = new Variable("aNormalTemp" + i, parameter.getType());
285                         expression = new ESimpleLet(var, parameter, expression);
286                         parameters[i] = new EVariable(var);
287                 }
288         }
289         if(function.isEffectful()) {
290                 Variable var = new Variable("aNormalTempF", function.getType());
291                 expression = new ESimpleLet(var, function, expression);
292                 function = new EVariable(var);
293         }
294         return expression;
295     }
296     
297     @Override
298     public boolean isEffectful() {
299         if(effect != Types.NO_EFFECTS)
300                 return true;            
301         for(Expression parameter : parameters)
302                 if(parameter.isEffectful())
303                         return true;
304         if(function.isEffectful())
305                 return true;
306         return false;
307     }
308     
309     @Override
310     public boolean isFunctionPattern() {
311         return !isConstructorApplication();
312     }
313     
314     @Override
315     public boolean isConstructorApplication() {
316         return function.isConstructorApplication();
317     }
318
319     @Override
320     public void accept(ExpressionVisitor visitor) {
321         visitor.visit(this);
322     }
323     
324     @Override
325     public boolean isFunctionDefinitionLhs() {
326         try {
327             EVar patternHead = function.getPatternHead();
328             return !Character.isUpperCase(patternHead.name.charAt(0));
329         } catch(NotPatternException e) {
330             return false;
331         }
332     }
333     
334     @Override
335     public boolean isPattern(int arity) {
336         if(!function.isPattern(arity+parameters.length))
337             return false;
338         for(Expression parameter : parameters)
339             if(!parameter.isPattern(0))
340                 return false;
341         return true;
342     }
343
344     @Override
345     public Expression accept(ExpressionTransformer transformer) {
346         return transformer.transform(this);
347     }
348     
349     @Override
350     public boolean equalsExpression(Expression expression) {
351         if(expression.getClass() != getClass())
352             return false;
353         EApply other = (EApply)expression;
354         if(parameters.length != other.parameters.length)
355             return false;
356         if(!function.equalsExpression(other.function))
357             return false;
358         for(int i=0;i<parameters.length;++i)
359             if(!parameters[i].equalsExpression(other.parameters[i]))
360                 return false;
361         return true;
362     }
363 }