aboutsummaryrefslogtreecommitdiffstats
path: root/javaparser-symbol-solver-testing/src/test/java/com/github/javaparser/symbolsolver/resolution/GenericsResolutionTest.java
blob: 5bfe1dc82ff84d9edcc86f0b68328e06f39f5a21 (plain)
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/*
 * Copyright 2016 Federico Tomassetti
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.javaparser.symbolsolver.resolution;

import com.github.javaparser.ParseException;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.MethodCallExpr;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.ThisExpr;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.resolution.MethodUsage;
import com.github.javaparser.resolution.types.ResolvedReferenceType;
import com.github.javaparser.resolution.types.ResolvedType;
import com.github.javaparser.symbolsolver.javaparser.Navigator;
import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.model.resolution.Value;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import org.junit.Test;

import java.util.List;
import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class GenericsResolutionTest extends AbstractResolutionTest {

    @Test
    public void resolveFieldWithGenericTypeToString() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Generics");
        VariableDeclarator fieldS = Navigator.demandField(clazz, "s");

        SymbolSolver symbolSolver = new SymbolSolver(new ReflectionTypeSolver());
        Optional<Value> symbolReference = symbolSolver.solveSymbolAsValue("s", fieldS);

        assertEquals(true, symbolReference.isPresent());
        assertEquals("s", symbolReference.get().getName());

        ResolvedType type = symbolReference.get().getType();
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        assertEquals("java.lang.String", type.asReferenceType().typeParametersValues().get(0).describe());
    }

    @Test
    public void resolveFieldWithGenericTypeToDeclaredClass() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Generics");
        VariableDeclarator fieldS = Navigator.demandField(clazz, "g");

        SymbolSolver symbolSolver = new SymbolSolver(new ReflectionTypeSolver());
        Optional<Value> symbolReference = symbolSolver.solveSymbolAsValue("g", fieldS);

        assertEquals(true, symbolReference.isPresent());
        assertEquals("g", symbolReference.get().getName());

        ResolvedType type = symbolReference.get().getType();
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        assertEquals("me.tomassetti.symbolsolver.javaparser.Generics", type.asReferenceType().typeParametersValues().get(0).describe());
    }

    @Test
    public void resolveFieldWithGenericTypeToInteger() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Generics");
        VariableDeclarator fieldS = Navigator.demandField(clazz, "i");

        SymbolSolver symbolSolver = new SymbolSolver(new ReflectionTypeSolver());
        Optional<Value> symbolReference = symbolSolver.solveSymbolAsValue("i", fieldS);

        assertEquals(true, symbolReference.isPresent());
        assertEquals("i", symbolReference.get().getName());

        ResolvedType type = symbolReference.get().getType();
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        assertEquals("java.lang.Integer", type.asReferenceType().typeParametersValues().get(0).describe());
    }

    @Test
    public void resolveFieldOfVariableType() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "SomeCollection");
        VariableDeclarator field = Navigator.demandField(clazz, "a");

        SymbolSolver symbolSolver = new SymbolSolver(new ReflectionTypeSolver());
        Optional<Value> symbolReference = symbolSolver.solveSymbolAsValue("a", field);

        assertEquals(true, symbolReference.isPresent());
        assertEquals("a", symbolReference.get().getName());

        ResolvedType type = symbolReference.get().getType();
        assertEquals(true, type.isTypeVariable());
        assertEquals("A", type.describe());
    }

    @Test
    public void resolveFieldOfGenericReferringToVariableType() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "SomeCollection");
        VariableDeclarator field = Navigator.demandField(clazz, "as");

        SymbolSolver symbolSolver = new SymbolSolver(new ReflectionTypeSolver());
        Optional<Value> symbolReference = symbolSolver.solveSymbolAsValue("as", field);

        assertEquals(true, symbolReference.isPresent());
        assertEquals("as", symbolReference.get().getName());

        ResolvedType type = symbolReference.get().getType();
        assertEquals(false, type.isTypeVariable());
        assertEquals("java.util.List<A>", type.describe());
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        ResolvedType typeParam = type.asReferenceType().typeParametersValues().get(0);
        assertEquals(true, typeParam.isTypeVariable());
        assertEquals("A", typeParam.describe());
    }

    @Test
    public void resolveUsageOfGenericFieldSimpleCase() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "SomeCollection");

        MethodDeclaration method = Navigator.demandMethod(clazz, "foo1");

        ExpressionStmt stmt = (ExpressionStmt) method.getBody().get().getStatements().get(0);
        Expression expression = stmt.getExpression();
        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);

        assertEquals(false, type.isTypeVariable());
        assertEquals("java.lang.String", type.describe());
    }

    //PRIMA UN TEST CHE DICA CHE IL TIPO DEL CAMPO AS e' LIST<A> NON LIST<E>
    @Test
    public void resolveUsageOfGenericFieldIntermediateCase() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "SomeCollection");

        VariableDeclarator field = Navigator.demandField(clazz, "as");

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(field);

        assertEquals(false, type.isTypeVariable());
        assertEquals("java.util.List<A>", type.describe());
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        assertEquals(true, type.asReferenceType().typeParametersValues().get(0).isTypeVariable());
        assertEquals("A", type.asReferenceType().typeParametersValues().get(0).describe());
    }

    @Test
    public void resolveUsageOfGenericFieldAdvancedCase() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "SomeCollection");

        MethodDeclaration method = Navigator.demandMethod(clazz, "foo2");

        ExpressionStmt stmt = (ExpressionStmt) method.getBody().get().getStatements().get(0);
        Expression expression = stmt.getExpression();
        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);

        assertEquals(false, type.isTypeVariable());
        assertEquals("java.util.List<java.lang.String>", type.describe());
        assertEquals(1, type.asReferenceType().typeParametersValues().size());
        assertEquals(false, type.asReferenceType().typeParametersValues().get(0).isTypeVariable());
        assertEquals("java.lang.String", type.asReferenceType().typeParametersValues().get(0).describe());
    }

    @Test
    public void resolveUsageOfMethodOfGenericClass() throws ParseException {
        CompilationUnit cu = parseSample("Generics");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "GenericMethodCalls.Derived");
        MethodDeclaration method = Navigator.demandMethod(clazz, "caller");
        MethodCallExpr expression = Navigator.findMethodCall(method, "callee");

        MethodUsage methodUsage = JavaParserFacade.get(new ReflectionTypeSolver()).solveMethodAsUsage(expression);

        assertEquals("callee", methodUsage.getName());
    }

    @Test
    public void resolveElementOfList() throws ParseException {
        CompilationUnit cu = parseSample("ElementOfList");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ElementOfList");
        MethodDeclaration method = Navigator.demandMethod(clazz, "foo");
        VariableDeclarator variableDeclarator = Navigator.demandVariableDeclaration(method, "a");
        Expression expression = variableDeclarator.getInitializer().get();

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);

        assertEquals(false, type.isTypeVariable());
        assertEquals("Comment", type.describe());
    }

    @Test
    public void resolveElementOfListAdvancedExample() throws ParseException {
        CompilationUnit cu = parseSample("ElementOfList");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ElementOfList");
        MethodDeclaration method = Navigator.demandMethod(clazz, "annotations");
        VariableDeclarator variableDeclarator = Navigator.demandVariableDeclaration(method, "a");
        Expression expression = variableDeclarator.getInitializer().get();

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);

        assertEquals(false, type.isTypeVariable());
        assertEquals("AnnotationExpr", type.describe());
    }

    @Test
    public void genericsInheritance() throws ParseException {
        CompilationUnit cu = parseSample("MethodTypeParams");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "VoidVisitorAdapter");
        MethodDeclaration method = Navigator.demandMethod(clazz, "visit");
        MethodCallExpr call = Navigator.findMethodCall(method, "accept");
        Expression thisRef = call.getArguments().get(0);

        TypeSolver typeSolver = new ReflectionTypeSolver();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);

        ResolvedType voidVisitorAdapterOfA = javaParserFacade.getType(thisRef);
        List<ResolvedReferenceType> allAncestors = voidVisitorAdapterOfA.asReferenceType().getAllAncestors();
        assertEquals(2, allAncestors.size());
    }

    @Test
    public void methodTypeParams() throws ParseException {
        CompilationUnit cu = parseSample("MethodTypeParams");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "VoidVisitorAdapter");
        MethodDeclaration method = Navigator.demandMethod(clazz, "visit");
        MethodCallExpr call = Navigator.findMethodCall(method, "accept");

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(call);

        assertEquals(false, type.isTypeVariable());
        assertEquals("void", type.describe());
    }

    @Test
    public void classCastScope() throws ParseException {
        CompilationUnit cu = parseSample("ClassCast");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ClassCast");
        MethodDeclaration method = Navigator.demandMethod(clazz, "getNodesByType");
        MethodCallExpr call = Navigator.findMethodCall(method, "cast");

        TypeSolver typeSolver = new ReflectionTypeSolver();
        Expression scope = call.getScope().get();
        ResolvedType type = JavaParserFacade.get(typeSolver).getType(scope);

        //System.out.println(typeUsage);

        assertEquals(false, type.isTypeVariable());
        assertEquals("java.lang.Class<N>", type.describe());
    }

    @Test
    public void classCast() throws ParseException {
        CompilationUnit cu = parseSample("ClassCast");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "ClassCast");
        MethodDeclaration method = Navigator.demandMethod(clazz, "getNodesByType");
        ReturnStmt returnStmt = Navigator.findReturnStmt(method);

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(returnStmt.getExpression().get());

        assertEquals(true, type.isTypeVariable());
        assertEquals("N", type.describe());
    }

    @Test
    public void typeParamOnReturnTypeStep1() throws ParseException {
        CompilationUnit cu = parseSample("TypeParamOnReturnType");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "TypeParamOnReturnType");
        MethodDeclaration method = Navigator.demandMethod(clazz, "nodeEquals");
        ThisExpr thisExpr = Navigator.findNodeOfGivenClass(method, ThisExpr.class);

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(thisExpr);

        assertEquals(false, type.isTypeVariable());
        assertEquals("TypeParamOnReturnType", type.describe());
    }

    @Test
    public void typeParamOnReturnTypeStep2() throws ParseException {
        CompilationUnit cu = parseSample("TypeParamOnReturnType");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "TypeParamOnReturnType");
        MethodDeclaration method = Navigator.demandMethod(clazz, "nodeEquals");
        NameExpr n1 = Navigator.findNameExpression(method, "n1");

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(n1);

        assertEquals(true, type.isTypeVariable());
        assertEquals("T", type.describe());
    }

    @Test
    public void typeParamOnReturnTypeStep3() throws ParseException {
        CompilationUnit cu = parseSample("TypeParamOnReturnType");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "TypeParamOnReturnType");
        MethodDeclaration method = Navigator.demandMethod(clazz, "nodeEquals");
        MethodCallExpr call = Navigator.findMethodCall(method, "accept");

        JavaParserFacade javaParserFacade = JavaParserFacade.get(new ReflectionTypeSolver());
        ResolvedType type = javaParserFacade.getType(call);

        assertEquals(false, type.isTypeVariable());
        assertEquals("java.lang.Boolean", type.describe());
    }

    @Test
    public void typeParamOnReturnType() throws ParseException {
        CompilationUnit cu = parseSample("TypeParamOnReturnType");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "TypeParamOnReturnType");
        MethodDeclaration method = Navigator.demandMethod(clazz, "nodeEquals");
        ReturnStmt returnStmt = Navigator.findReturnStmt(method);

        ResolvedType type = JavaParserFacade.get(new ReflectionTypeSolver()).getType(returnStmt.getExpression().get());

        assertEquals(false, type.isTypeVariable());
        assertEquals("boolean", type.describe());
    }

    /*@Test
    public void genericCollectionWithWildcardsAndExtensionsPrep() throws ParseException {
        CompilationUnit cu = parseSample("GenericCollectionWithExtension");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Foo");
        MethodDeclaration method = Navigator.demandMethod(clazz, "bar");
        ReturnStmt returnStmt = Navigator.findReturnStmt(method);

        TypeSolver typeSolver = new JreTypeSolver();
        MethodCallExpr call = (MethodCallExpr) returnStmt.getExpr();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);

        List<TypeUsage> params = new ArrayList<>();
        if (call.getArgs() != null) {
            for (Expression param : call.getArgs()) {
                params.add(javaParserFacade.getType(param, false));
            }
        }
        Context context = JavaParserFactory.getContext(call, typeSolver);

        ReferenceTypeUsage typeOfScope = javaParserFacade.getType(call.getScope()).asReferenceType();
        me.tomassetti.symbolsolver.model.declarations.TypeDeclaration typeDeclaration = typeOfScope.getTypeDeclaration();
        List<TypeUsage> typeParametersValues = typeOfScope.typeParametersValues();

        List<MethodUsage> methods = new ArrayList<>();
        for (Method m : List.class.getMethods()) {
            if (m.getName().equals("addAll") && !m.isBridge() && !m.isSynthetic()) {
                me.tomassetti.symbolsolver.model.declarations.MethodDeclaration methodDeclaration = new ReflectionMethodDeclaration(m, typeSolver);
                if (methods.size() == 0) {
                    // ok, e' il primo
                    ReferenceTypeUsage paramType = methodDeclaration.getParam(0).getType(typeSolver).asReferenceType();
                    assertTrue(paramType.asReferenceType().typeParametersValues().get(0).isWildcard());
                }
                MethodUsage mu = new MethodUsage(methodDeclaration, typeSolver);
                int i = 0;
                for (TypeParameter tp : typeDeclaration.getTypeParameters()) {
                    mu = mu.replaceTypeParameter(tp.getName(), typeParametersValues.get(i));
                    i++;
                }
                methods.add(mu);
            }

        }

        assertTrue(MethodResolutionLogic.isApplicable(methods.get(0), "addAll", params, typeSolver));
        //Optional<MethodUsage> methodUsage = MethodResolutionLogic.findMostApplicableUsage(methods, "addAll", params, typeSolver);

        //Optional<MethodUsage> methodUsage = typeDeclaration.solveMethodAsUsage("addAll", params, typeSolver, context, typeParametersValues);

        //Optional<MethodUsage> methodUsage = context.solveMethodAsUsage("addAll", params, typeSolver);

        //assertTrue(methodUsage.isPresent());

    }*/

    @Test
    public void genericCollectionWithWildcardsAndExtensions() throws ParseException {
        CompilationUnit cu = parseSample("GenericCollectionWithExtension");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Foo");
        MethodDeclaration method = Navigator.demandMethod(clazz, "bar");
        ReturnStmt returnStmt = Navigator.findReturnStmt(method);

        TypeSolver typeSolver = new ReflectionTypeSolver();
        Expression returnStmtExpr = returnStmt.getExpression().get();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);

        ResolvedType type = javaParserFacade.getType(returnStmtExpr);

        assertEquals(false, type.isTypeVariable());
        assertEquals("boolean", type.describe());
    }

    @Test
    public void methodWithGenericParameterTypes() throws ParseException {
        CompilationUnit cu = parseSample("GenericCollectionWithExtension");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Foo");
        MethodDeclaration method = Navigator.demandMethod(clazz, "bar");
        MethodCallExpr methodCall = Navigator.findMethodCall(method, "foo");

        TypeSolver typeSolver = new ReflectionTypeSolver();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);

        MethodUsage methodUsage = javaParserFacade.solveMethodAsUsage(methodCall);

        assertEquals("foo", methodUsage.getName());
    }

    @Test
    public void genericCollectionWithWildcards() throws ParseException {
        CompilationUnit cu = parseSample("GenericCollection");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Foo");
        MethodDeclaration method = Navigator.demandMethod(clazz, "bar");
        ReturnStmt returnStmt = Navigator.findReturnStmt(method);

        TypeSolver typeSolver = new ReflectionTypeSolver();
        Expression returnStmtExpr = returnStmt.getExpression().get();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);

        ResolvedType type = javaParserFacade.getType(returnStmtExpr);

        assertEquals(false, type.isTypeVariable());
        assertEquals("boolean", type.describe());
    }
}