Skip to main content
summaryrefslogtreecommitdiffstats
blob: 8c22e3f4541d426a14f52d5e5e3fb4076bdb73ff (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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*
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.middleend.javaannotations;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
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.ExpressionBase;
import org.eclipse.xtend.backend.common.Function;
import org.eclipse.xtend.backend.functions.java.internal.JavaBuiltinConverter;
import org.eclipse.xtend.backend.functions.java.internal.JavaBuiltinConverterFactory;
import org.eclipse.xtend.backend.functions.java.internal.ParameterConverter;
import org.eclipse.xtend.backend.util.ErrorHandler;


/**
 * This class represents a "helper" function that is defined in a Java class but for which the defining
 *  object is not an explicit parameter. It is used for "JAVA extension" style functions. <br>
 *  
 * If it represents a non-static method, a single instance of the underlying class is shared by all methods 
 *  of the class, and across all compilation units etc. from which they are referenced. This single instance
 *  is scoped with the ExecutionContext used.
 *  
 * @author Arno Haase (http://www.haase-consulting.com)
 */
public final class JavaDefinedFunction implements Function {
    private final Method _mtd;
    private final List<BackendType> _parameterTypes;
    private final ExpressionBase _guard;
    private final boolean _isStatic;

    private final List<ParameterConverter> _parameterConverters = new ArrayList<ParameterConverter>();
    private final JavaBuiltinConverter _returnValueConverter;
    
    
    //TODO move this factory to JavaFunctionClassContributor
    //TODO separate internal API
    /**
     * This is a convenience factory method that creates functions for all public methods for an entire class.
     */
    public static List<JavaDefinedFunction> createForEntireClass (Class<?> cls, BackendTypesystem ts) {
        final List<JavaDefinedFunction> result = new ArrayList<JavaDefinedFunction>();
        
        for (Method mtd: cls.getDeclaredMethods()) {
            // register only public methods
            if (! isPublic (mtd))
                continue;

            // do not register infrastructure methods inherited from ExecutionContextAware
            if (ExecutionContextAware.class.isAssignableFrom (cls)) {
                try {
                    ExecutionContextAware.class.getMethod (mtd.getName(), mtd.getParameterTypes());
                    continue;
                }
                catch (NoSuchMethodException e) {
                }
            }
            
            if (mtd.getAnnotation (M2tHidden.class) != null)
                continue;
            
            result.add (new JavaDefinedFunction (mtd, null, ts));
        }
        return result;
    }

    private static boolean isPublic (Method mtd) {
        return (mtd.getModifiers() & Modifier.PUBLIC) != 0;
    }

    
    /**
     *  shortcut constructor that attempts to derive the parameter types from the method's signature
     */
    public JavaDefinedFunction (Method mtd, ExpressionBase guard, BackendTypesystem ts) {
        this (mtd, guessParameterTypes(mtd, ts), guard);
    }
    
    
    /**
     * This constructor provides full control
     */
    public JavaDefinedFunction (Method mtd, List<BackendType> parameterTypes, ExpressionBase guard) {
        _mtd = mtd;
        _parameterTypes = parameterTypes;
        _guard = guard;
        
        for (int i=0; i<mtd.getParameterTypes().length; i++) {
            final ParameterConverter pc = JavaBuiltinConverterFactory.getParameterConverter (mtd.getParameterTypes()[i], i);
            if (pc != null)
                _parameterConverters.add(pc);
        }
        
        _returnValueConverter = JavaBuiltinConverterFactory.getConverter (mtd.getReturnType());
        
        _isStatic = (mtd.getModifiers() & Modifier.STATIC) != 0;
    }

    private Object getInstance (ExecutionContext ctx) {
        if (_isStatic)
            return null;

        try {
            Object result = ctx.getContributionStateContext().retrieveState (_mtd.getDeclaringClass());
            if (result == null) {
                result = _mtd.getDeclaringClass().newInstance();
                ctx.getContributionStateContext().storeState(_mtd.getDeclaringClass(), result);
            }
            return result;
        }
        catch (Exception exc) {
            ErrorHandler.handle (exc);
            return null; // just for the compiler - this is never executed
        }
    }
    
    public static List<BackendType> guessParameterTypes (Method mtd, BackendTypesystem ts) {
        final List<BackendType> result = new ArrayList<BackendType>();
        
        for (Class<?> cls: mtd.getParameterTypes()) 
            result.add (ts.findType (cls));
        
        return result;
    }
    
    public String getName () {
    	return _mtd.getName();
    }
    
    public boolean isCached () {
        return false;
    }
    
    public List<BackendType> getParameterTypes() {
        return _parameterTypes;
    }

    public Object invoke (ExecutionContext ctx, Object[] params) {
        for (ParameterConverter pc: _parameterConverters)
            pc.convert(params);
        
        Object o = getInstance (ctx);
        if (o instanceof ExecutionContextAware) {
            ((ExecutionContextAware) o).setExecutionContext (ctx);
        }
        
        try {
            final Object resultRaw = _mtd.invoke (o, params);
            return _returnValueConverter.javaToBackend (resultRaw);
            
        } catch (Exception e) {
            final List<String> paramTypes = new ArrayList<String> ();
            for (Object p: params) {
                if (p == null)
                    paramTypes.add (Void.TYPE.getName());
                else
                    paramTypes.add (p.getClass().getName());
            }
            
            ErrorHandler.handle ("could not invoke method " + _mtd + " with parameters " + Arrays.asList(params) + " of types " + paramTypes, e);
            return null; // to make the compiler happy - this is never executed
        }
    }
    
    public ExpressionBase getGuard () {
    	return _guard;
    }
	
	@Override
	public String toString () {
	    return "JavaDefinedFunction '" + getName() + "' " + _parameterTypes;
	}
}













Back to the top