]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.scl.compiler/src/org/simantics/scl/compiler/internal/types/ast/TypeAst.java
Migrated source code from Simantics SVN
[simantics/platform.git] / bundles / org.simantics.scl.compiler / src / org / simantics / scl / compiler / internal / types / ast / TypeAst.java
1 package org.simantics.scl.compiler.internal.types.ast;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5
6 import org.simantics.scl.compiler.internal.types.TypeElaborationContext;
7 import org.simantics.scl.compiler.types.TCon;
8 import org.simantics.scl.compiler.types.TPred;
9 import org.simantics.scl.compiler.types.Type;
10 import org.simantics.scl.compiler.types.Types;
11 import org.simantics.scl.compiler.types.exceptions.Problem;
12 import org.simantics.scl.compiler.types.exceptions.SCLTypeParseException;
13
14 public abstract class TypeAst {
15     @Override
16     public String toString() {
17         StringBuilder b = new StringBuilder();
18         toString(b);
19         return b.toString();
20     }
21
22     public abstract void toString(StringBuilder b);
23     
24     public void toString(StringBuilder b, int outerPrecedence) {
25         if(getPrecedence() >= outerPrecedence) {
26             b.append('(');
27             toString(b);
28             b.append(')');
29         }
30         else
31             toString(b);
32     }
33     
34     public abstract Type toType(TypeElaborationContext context) throws SCLTypeParseException;
35     
36     public static Type[] toTypes(TypeElaborationContext context, TypeAst[] typeAsts) throws SCLTypeParseException {
37         Type[] result = new Type[typeAsts.length];
38         for(int i=0;i<typeAsts.length;++i)
39             result[i] = typeAsts[i].toType(context);
40         return result;
41     }
42
43     public TPred toTFuncApply(TypeElaborationContext context) throws SCLTypeParseException {
44         ArrayList<Type> parameters = new ArrayList<Type>();
45         TypeAst cur = this;
46         while(true) {
47             if(cur instanceof TApplyAst) {
48                 TApplyAst apply = (TApplyAst)cur;
49                 parameters.add(apply.parameter.toType(context));
50                 cur = apply.function;
51             }
52             else if(cur instanceof TConAst) {
53                 TConAst con = (TConAst)cur;
54                 Collections.reverse(parameters);
55                 return Types.pred(
56                         (TCon)con.toType(context),
57                         parameters.toArray(new Type[parameters.size()]));
58             }
59             else
60                 throw new SCLTypeParseException(
61                         new Problem(0, 0, "Invalid constraint."));
62         }
63     }
64     
65     public abstract int getPrecedence();
66 }