use of com.github.javaparser.ast.stmt.ExpressionStmt in project javaparser by javaparser.
the class GenericsResolutionTest method resolveUsageOfGenericFieldAdvancedCase.
@Test
public void resolveUsageOfGenericFieldAdvancedCase() {
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());
}
use of com.github.javaparser.ast.stmt.ExpressionStmt in project javaparser by javaparser.
the class NodeWithStatements method addStatement.
public default T addStatement(Expression expr) {
ExpressionStmt statement = new ExpressionStmt(expr);
expr.setParentNode(statement);
return addStatement(statement);
}
use of com.github.javaparser.ast.stmt.ExpressionStmt in project javaparser by javaparser.
the class TypeExtractor method visit.
@Override
public ResolvedType visit(LambdaExpr node, Boolean solveLambdas) {
if (requireParentNode(node) instanceof MethodCallExpr) {
MethodCallExpr callExpr = (MethodCallExpr) requireParentNode(node);
int pos = JavaParserSymbolDeclaration.getParamPos(node);
SymbolReference<ResolvedMethodDeclaration> refMethod = facade.solve(callExpr);
if (!refMethod.isSolved()) {
throw new com.github.javaparser.resolution.UnsolvedSymbolException(requireParentNode(node).toString(), callExpr.getName().getId());
}
logger.finest("getType on lambda expr " + refMethod.getCorrespondingDeclaration().getName());
if (solveLambdas) {
// The type parameter referred here should be the java.util.stream.Stream.T
ResolvedType result = refMethod.getCorrespondingDeclaration().getParam(pos).getType();
if (callExpr.getScope().isPresent()) {
Expression scope = callExpr.getScope().get();
// If it is a static call we should not try to get the type of the scope
boolean staticCall = false;
if (scope instanceof NameExpr) {
NameExpr nameExpr = (NameExpr) scope;
try {
SymbolReference<ResolvedTypeDeclaration> type = JavaParserFactory.getContext(nameExpr, typeSolver).solveType(nameExpr.getName().getId(), typeSolver);
if (type.isSolved()) {
staticCall = true;
}
} catch (Exception e) {
}
}
if (!staticCall) {
ResolvedType scopeType = facade.getType(scope);
if (scopeType.isReferenceType()) {
result = scopeType.asReferenceType().useThisTypeParametersOnTheGivenType(result);
}
}
}
// We need to replace the type variables
Context ctx = JavaParserFactory.getContext(node, typeSolver);
result = solveGenericTypes(result, ctx, typeSolver);
// We should find out which is the functional method (e.g., apply) and replace the params of the
// solveLambdas with it, to derive so the values. We should also consider the value returned by the
// lambdas
Optional<MethodUsage> functionalMethod = FunctionalInterfaceLogic.getFunctionalMethod(result);
if (functionalMethod.isPresent()) {
LambdaExpr lambdaExpr = node;
InferenceContext lambdaCtx = new InferenceContext(MyObjectProvider.INSTANCE);
InferenceContext funcInterfaceCtx = new InferenceContext(MyObjectProvider.INSTANCE);
// At this point parameterType
// if Function<T=? super Stream.T, ? extends map.R>
// we should replace Stream.T
ResolvedType functionalInterfaceType = ReferenceTypeImpl.undeterminedParameters(functionalMethod.get().getDeclaration().declaringType(), typeSolver);
lambdaCtx.addPair(result, functionalInterfaceType);
ResolvedType actualType;
if (lambdaExpr.getBody() instanceof ExpressionStmt) {
actualType = facade.getType(((ExpressionStmt) lambdaExpr.getBody()).getExpression());
} else if (lambdaExpr.getBody() instanceof BlockStmt) {
BlockStmt blockStmt = (BlockStmt) lambdaExpr.getBody();
// Get all the return statements in the lambda block
List<ReturnStmt> returnStmts = blockStmt.findAll(ReturnStmt.class);
if (returnStmts.size() > 0) {
actualType = returnStmts.stream().map(returnStmt -> returnStmt.getExpression().map(e -> facade.getType(e)).orElse(ResolvedVoidType.INSTANCE)).filter(x -> x != null && !x.isVoid() && !x.isNull()).findFirst().orElse(ResolvedVoidType.INSTANCE);
} else {
return ResolvedVoidType.INSTANCE;
}
} else {
throw new UnsupportedOperationException();
}
ResolvedType formalType = functionalMethod.get().returnType();
// Infer the functional interfaces' return vs actual type
funcInterfaceCtx.addPair(formalType, actualType);
// Substitute to obtain a new type
ResolvedType functionalTypeWithReturn = funcInterfaceCtx.resolve(funcInterfaceCtx.addSingle(functionalInterfaceType));
// we don't need to bother inferring types
if (!(formalType instanceof ResolvedVoidType)) {
lambdaCtx.addPair(result, functionalTypeWithReturn);
result = lambdaCtx.resolve(lambdaCtx.addSingle(result));
}
}
return result;
} else {
return refMethod.getCorrespondingDeclaration().getParam(pos).getType();
}
} else {
throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
}
}
use of com.github.javaparser.ast.stmt.ExpressionStmt in project javaparser by javaparser.
the class ArrayTypeTest method getVariableDeclarationWithArrays.
@Test
public void getVariableDeclarationWithArrays() {
ExpressionStmt variableDeclarationStatement = parseStatement("@C int @A[] @B[] a @X[] @Y[];").asExpressionStmt();
VariableDeclarationExpr variableDeclarationExpr = variableDeclarationStatement.getExpression().asVariableDeclarationExpr();
ArrayType arrayType1 = variableDeclarationExpr.getVariable(0).getType().asArrayType();
ArrayType arrayType2 = arrayType1.getComponentType().asArrayType();
ArrayType arrayType3 = arrayType2.getComponentType().asArrayType();
ArrayType arrayType4 = arrayType3.getComponentType().asArrayType();
PrimitiveType elementType = arrayType4.getComponentType().asPrimitiveType();
assertThat(arrayType1.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("A")));
assertThat(arrayType2.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("B")));
assertThat(arrayType3.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("X")));
assertThat(arrayType4.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("Y")));
assertThat(elementType.getType()).isEqualTo(PrimitiveType.Primitive.INT);
assertThat(variableDeclarationExpr.getAnnotations()).containsExactly(new MarkerAnnotationExpr(parseName("C")));
assertThat(arrayType1.getParentNode().get().getParentNode().get()).isSameAs(variableDeclarationExpr);
}
use of com.github.javaparser.ast.stmt.ExpressionStmt in project javaparser by javaparser.
the class LexicalDifferenceCalculatorTest method csmModelAfterAddingStatementToEmptyBlock.
@Test
public void csmModelAfterAddingStatementToEmptyBlock() throws IOException {
LexicalDifferenceCalculator ldc = new LexicalDifferenceCalculator();
considerExample("ASimpleClassWithMoreFormatting_step3");
MethodDeclaration setter = cu.getClassByName("MyRenamedClass").get().getMethodsByName("setAField").get(0);
Statement assignStatement = new ExpressionStmt(new AssignExpr(new FieldAccessExpr(new ThisExpr(), "aField"), new NameExpr("aField"), AssignExpr.Operator.ASSIGN));
LexicalDifferenceCalculator.CalculatedSyntaxModel calculatedSyntaxModel = ldc.calculatedSyntaxModelAfterListAddition(ConcreteSyntaxModel.forClass(BlockStmt.class), ObservableProperty.STATEMENTS, setter.getBody().get().getStatements(), 0, assignStatement);
int index = 0;
assertEquals(CsmElement.token(GeneratedJavaParserConstants.LBRACE), calculatedSyntaxModel.elements.get(index++));
assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++));
assertEquals(CsmElement.indent(), calculatedSyntaxModel.elements.get(index++));
assertTrue(isChild(calculatedSyntaxModel.elements.get(index++), ExpressionStmt.class));
assertEquals(CsmElement.newline(), calculatedSyntaxModel.elements.get(index++));
assertEquals(CsmElement.unindent(), calculatedSyntaxModel.elements.get(index++));
assertEquals(CsmElement.token(GeneratedJavaParserConstants.RBRACE), calculatedSyntaxModel.elements.get(index++));
assertEquals(index, calculatedSyntaxModel.elements.size());
}
Aggregations