Skip to main content
summaryrefslogtreecommitdiffstats
blob: 6ae114e318567517076d46ad2b606ebdd81b2d03 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
Copyright (c) 2008 Arno Haase.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/epl-v10.html

Contributors:
    Arno Haase - initial API and implementation
 */
package org.eclipse.xtend.backend.functions.internal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.eclipse.xtend.backend.common.BackendType;
import org.eclipse.xtend.backend.common.BackendTypesystem;
import org.eclipse.xtend.backend.common.ExecutionContext;
import org.eclipse.xtend.backend.common.Function;
import org.eclipse.xtend.backend.common.NamedFunction;
import org.eclipse.xtend.backend.functions.DuplicateAwareFunctionCollection;
import org.eclipse.xtend.backend.functions.DuplicateAwareNamedFunctionCollection;
import org.eclipse.xtend.backend.functions.FunctionDefContextInternal;
import org.eclipse.xtend.backend.util.Cache;
import org.eclipse.xtend.backend.util.DoubleKeyCache;
import org.eclipse.xtend.backend.util.ErrorHandler;
import org.eclipse.xtend.backend.util.StringHelper;


/**
 * 
 * @author Arno Haase (http://www.haase-consulting.com)
 */
public final class FunctionDefContextImpl implements FunctionDefContextInternal {
	
	private final Cache<BackendType, Collection<NamedFunction>> _byFirstParameterType = new Cache<BackendType, Collection<NamedFunction>>() {
        @Override
        protected Collection<NamedFunction> create (BackendType key) {
            return new ArrayList<NamedFunction>();
        }
	};
	
    private final DoubleKeyCache<String, Integer, DuplicateAwareNamedFunctionCollection> _functions = new DoubleKeyCache<String, Integer, DuplicateAwareNamedFunctionCollection>() {
        @Override
        protected DuplicateAwareNamedFunctionCollection create(String key1, Integer key2) {
            return new DuplicateAwareNamedFunctionCollection ();
        }
    };
    
    private final DoubleKeyCache<String, List<BackendType>, Collection<Function>> _byParamTypes = new DoubleKeyCache<String, List<BackendType>, Collection<Function>>() {
    	
        @Override
        protected Collection<Function> create (String functionName, List<BackendType> paramTypes) {
            return new PolymorphicResolver(functionName).getBestFitCandidates (findCandidates (functionName, paramTypes)); // TODO go around this cache if there is a dynamically provided function 
        }
        
        private Collection<Function> findCandidates (String functionName, List<BackendType> paramTypes) {
            final int paramCount = paramTypes.size();
            final BackendType firstParamType = paramTypes.isEmpty() ? null : paramTypes.get(0);
            
            final DuplicateAwareFunctionCollection result = new DuplicateAwareFunctionCollection ();
            
            // get built-in operations of the typesystem
            if (firstParamType != null) {
                for (NamedFunction f: firstParamType.getBuiltinOperations())
                    if (functionName.equals (f.getName()) && matchesParamTypes(f.getFunction(), paramTypes))
                        result.register (f.getFunction());
            }
            
            // merge with registered functions
            for (NamedFunction f: _functions.get (functionName, paramCount).getFunctions())
                if (matchesParamTypes (f.getFunction(), paramTypes))
                    result.register (f.getFunction());
            
            return result.getFunctions();
        }
        
        private boolean matchesParamTypes (Function f, List<BackendType> paramTypes) {
            if (f.getParameterTypes().size() != paramTypes.size())
                return false;
            
            for (int i=0; i<f.getParameterTypes().size(); i++) {
                if (! f.getParameterTypes().get(i).isAssignableFrom(paramTypes.get(i)))
                    return false;
            }
            
            return true;
        }
    };

    private final DuplicateAwareNamedFunctionCollection _publicFunctions = new DuplicateAwareNamedFunctionCollection ();
    
    public void register (NamedFunction f, boolean isPublic) {
        if (isPublic)
            _publicFunctions.register (f);
        
        final NamedFunction old = _functions.get (f.getName(), f.getFunction().getParameterTypes().size()).register (f);
        if (old != null && old.getFunction().getParameterTypes().size() > 0)
            _byFirstParameterType.get (old.getFunction().getParameterTypes().get (0)).remove (old);
        
        if (f.getFunction().getParameterTypes().size() > 0)
            _byFirstParameterType.get (f.getFunction().getParameterTypes().get(0)).add (f);
    }
    
    public Object invoke (ExecutionContext ctx, String functionName, List<? extends Object> params) {
    	final Collection<Function> candidates = findFunctionCandidates (functionName, typesForParameters (ctx.getTypesystem(), params));
    	
    	Function f = null;
    	try {
    	    f = new PolymorphicResolver (functionName).evaluateGuards (ctx, candidates);
    	}
    	catch (Exception exc) {
    	    ErrorHandler.handle ("could not resolve function '" + functionName + "' for parameter types " + StringHelper.getTypesAsString (params) + " - candidates were " + candidates, exc);
    	}
    	
    	return ctx.getAdviceContext().getAdvice (functionName, f).evaluate(ctx, params);
    }

    /**
     * is public only for testing purposes
     */
    public List<BackendType> typesForParameters (BackendTypesystem ts, List<?> params) {
        final List<BackendType> paramTypes = new ArrayList<BackendType>();
        for (Object o: params)
            paramTypes.add (ts.findType(o));
        
        return paramTypes;
    }
    
    /**
     * is public only for testing purposes
     */
    public Collection<Function> findFunctionCandidates (String functionName, List<BackendType> paramTypes) {
        try {
            return _byParamTypes.get (functionName, paramTypes);
        } catch (RuntimeException e) {
            ErrorHandler.handle ("Failed to resolve function '" + functionName + "' for parameter types " + paramTypes + ".", e);
            return null; // to make the compiler happy - this is never executed
        }
    }
    
    public Collection<NamedFunction> getByFirstParameterType (BackendType firstParameterType) {
        if (firstParameterType.getBuiltinOperations().isEmpty())
            return _byFirstParameterType.get (firstParameterType);
        
        final List<NamedFunction> result = new ArrayList<NamedFunction> (firstParameterType.getBuiltinOperations());
        result.addAll (_byFirstParameterType.get (firstParameterType));
        return result;
    }

    public Function getMatch (ExecutionContext ctx, String name, List<BackendType> params) {
        final Collection<Function> candidates = findFunctionCandidates (name, params);
        if (candidates.isEmpty())
            return null;
        if (candidates.size() > 1)
            throw new IllegalArgumentException ("several matches for function '" + name + "' and parameter types " + params + ".");
        
        return candidates.iterator().next();
    }
    
    public boolean hasMatch (ExecutionContext ctx, String functionName, List<? extends Object> params) {
        return findFunctionCandidates (functionName, typesForParameters (ctx.getTypesystem(), params)).size() > 0;
    }
    
    @Override
    public String toString () {
        return "FunctionDefContextImpl [" + _functions.getMap().values() + "]";
    }

    public Collection<NamedFunction> getPublicFunctions () {
        return _publicFunctions.getFunctions();
    }
}





Back to the top