use of com.github.antlrjavaparser.api.type.ReferenceType in project spring-roo by spring-projects.
the class JavaParserUtils method getJavaType.
/**
* Resolves the effective {@link JavaType} a {@link Type} represents. A
* {@link Type} includes low-level types such as void, arrays and
* primitives.
*
* @param compilationUnitServices to use for package resolution (required)
* @param type to locate (required)
* @param typeParameters names to consider type parameters (can be null if
* there are none)
* @return the {@link JavaType}, with proper indication of primitive and
* array status (never null)
*/
public static JavaType getJavaType(final CompilationUnitServices compilationUnitServices, final Type type, final Set<JavaSymbolName> typeParameters) {
Validate.notNull(compilationUnitServices, "Compilation unit services required");
Validate.notNull(type, "The reference type must be provided");
if (type instanceof VoidType) {
return JavaType.VOID_PRIMITIVE;
}
int array = 0;
Type internalType = type;
if (internalType instanceof ReferenceType) {
array = ((ReferenceType) internalType).getArrayCount();
if (array > 0) {
internalType = ((ReferenceType) internalType).getType();
}
}
if (internalType instanceof PrimitiveType) {
final PrimitiveType pt = (PrimitiveType) internalType;
if (pt.getType().equals(Primitive.Boolean)) {
return new JavaType(Boolean.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Char)) {
return new JavaType(Character.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Byte)) {
return new JavaType(Byte.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Short)) {
return new JavaType(Short.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Int)) {
return new JavaType(Integer.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Long)) {
return new JavaType(Long.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Float)) {
return new JavaType(Float.class.getName(), array, DataType.PRIMITIVE, null, null);
}
if (pt.getType().equals(Primitive.Double)) {
return new JavaType(Double.class.getName(), array, DataType.PRIMITIVE, null, null);
}
throw new IllegalStateException("Unsupported primitive '" + pt.getType() + "'");
}
if (internalType instanceof WildcardType) {
// We only provide very primitive support for wildcard types; Roo
// only needs metadata at the end of the day,
// not complete binding support from an AST
final WildcardType wt = (WildcardType) internalType;
if (wt.getSuper() != null) {
final ReferenceType rt = wt.getSuper();
final ClassOrInterfaceType cit = (ClassOrInterfaceType) rt.getType();
final JavaType effectiveType = getJavaTypeNow(compilationUnitServices, cit, typeParameters);
return new JavaType(effectiveType.getFullyQualifiedTypeName(), rt.getArrayCount(), effectiveType.getDataType(), JavaType.WILDCARD_SUPER_ARG, effectiveType.getParameters());
} else if (wt.getExtends() != null) {
final ReferenceType rt = wt.getExtends();
final ClassOrInterfaceType cit = (ClassOrInterfaceType) rt.getType();
final JavaType effectiveType = getJavaTypeNow(compilationUnitServices, cit, typeParameters);
return new JavaType(effectiveType.getFullyQualifiedTypeName(), rt.getArrayCount(), effectiveType.getDataType(), JavaType.WILDCARD_EXTENDS_ARG, effectiveType.getParameters());
} else {
return new JavaType(OBJECT.getFullyQualifiedTypeName(), 0, DataType.TYPE, JavaType.WILDCARD_NEITHER_ARG, null);
}
}
ClassOrInterfaceType cit;
if (internalType instanceof ClassOrInterfaceType) {
cit = (ClassOrInterfaceType) internalType;
} else if (internalType instanceof ReferenceType) {
cit = (ClassOrInterfaceType) ((ReferenceType) type).getType();
} else {
throw new IllegalStateException("The presented type '" + internalType.getClass() + "' with value '" + internalType + "' is unsupported by JavaParserUtils");
}
final JavaType effectiveType = getJavaTypeNow(compilationUnitServices, cit, typeParameters);
if (array > 0) {
return new JavaType(effectiveType.getFullyQualifiedTypeName(), array, effectiveType.getDataType(), effectiveType.getArgName(), effectiveType.getParameters());
}
return effectiveType;
}
use of com.github.antlrjavaparser.api.type.ReferenceType in project spring-roo by spring-projects.
the class JavaParserMethodMetadataBuilder method addMethod.
public static void addMethod(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final MethodMetadata method, Set<JavaSymbolName> typeParameters) {
Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
Validate.notNull(members, "Members required");
Validate.notNull(method, "Method required");
if (typeParameters == null) {
typeParameters = new HashSet<JavaSymbolName>();
}
// Create the return type we should use
Type returnType = null;
if (method.getReturnType().isPrimitive()) {
returnType = JavaParserUtils.getType(method.getReturnType());
} else {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), method.getReturnType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(importedType);
// Add any type arguments presented for the return type
if (method.getReturnType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : method.getReturnType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (method.getReturnType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(method.getReturnType().getArray());
rt.setType(cit);
returnType = rt;
} else {
returnType = cit;
}
}
// Start with the basic method
final MethodDeclaration d = new MethodDeclaration();
d.setModifiers(JavaParserUtils.getJavaParserModifier(method.getModifier()));
d.setName(method.getMethodName().getSymbolName());
d.setType(returnType);
// Add any method-level annotations (not parameter annotations)
final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
d.setAnnotations(annotations);
for (final AnnotationMetadata annotation : method.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
}
// Add any method parameters, including their individual annotations and
// type parameters
final List<Parameter> parameters = new ArrayList<Parameter>();
d.setParameters(parameters);
int index = -1;
for (final AnnotatedJavaType methodParameter : method.getParameterTypes()) {
index++;
// Add the parameter annotations applicable for this parameter type
final List<AnnotationExpr> parameterAnnotations = new ArrayList<AnnotationExpr>();
for (final AnnotationMetadata parameterAnnotation : methodParameter.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, parameterAnnotations, parameterAnnotation);
}
// Compute the parameter name
final String parameterName = method.getParameterNames().get(index).getSymbolName();
// Compute the parameter type
Type parameterType = null;
if (methodParameter.getJavaType().isPrimitive()) {
parameterType = JavaParserUtils.getType(methodParameter.getJavaType());
} else {
final NameExpr type = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), methodParameter.getJavaType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(type);
// Add any type arguments presented for the return type
if (methodParameter.getJavaType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : methodParameter.getJavaType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (methodParameter.getJavaType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(methodParameter.getJavaType().getArray());
rt.setType(cit);
parameterType = rt;
} else {
parameterType = cit;
}
}
// Create a Java Parser method parameter and add it to the list of
// parameters
final Parameter p = new Parameter(parameterType, new VariableDeclaratorId(parameterName));
p.setVarArgs(methodParameter.isVarArgs());
p.setAnnotations(parameterAnnotations);
parameters.add(p);
}
// Add exceptions which the method my throw
if (method.getThrowsTypes().size() > 0) {
final List<NameExpr> throwsTypes = new ArrayList<NameExpr>();
for (final JavaType javaType : method.getThrowsTypes()) {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), javaType);
throwsTypes.add(importedType);
}
d.setThrows(throwsTypes);
}
// Set the body
if (StringUtils.isBlank(method.getBody())) {
// Never set the body if an abstract method
if (!Modifier.isAbstract(method.getModifier()) && !PhysicalTypeCategory.INTERFACE.equals(compilationUnitServices.getPhysicalTypeCategory())) {
d.setBody(new BlockStmt());
}
} else {
// There is a body.
// We need to make a fake method that we can have JavaParser parse.
// Easiest way to do that is to build a simple source class
// containing the required method and re-parse it.
final StringBuilder sb = new StringBuilder();
sb.append("class TemporaryClass {\n");
sb.append(" public void temporaryMethod() {\n");
sb.append(method.getBody());
sb.append("\n");
sb.append(" }\n");
sb.append("}\n");
final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
CompilationUnit ci;
try {
ci = JavaParser.parse(bais);
} catch (final IOException e) {
throw new IllegalStateException("Illegal state: Unable to parse input stream", e);
} catch (final ParseException pe) {
throw new IllegalStateException("Illegal state: JavaParser did not parse correctly", pe);
}
final List<TypeDeclaration> types = ci.getTypes();
if (types == null || types.size() != 1) {
throw new IllegalArgumentException("Method body invalid");
}
final TypeDeclaration td = types.get(0);
final List<BodyDeclaration> bodyDeclarations = td.getMembers();
if (bodyDeclarations == null || bodyDeclarations.size() != 1) {
throw new IllegalStateException("Illegal state: JavaParser did not return body declarations correctly");
}
final BodyDeclaration bd = bodyDeclarations.get(0);
if (!(bd instanceof MethodDeclaration)) {
throw new IllegalStateException("Illegal state: JavaParser did not return a method declaration correctly");
}
final MethodDeclaration md = (MethodDeclaration) bd;
d.setBody(md.getBody());
}
// ROO-3678: Add-on which include new method should be the responsible to check if method
// exists, not JavaParser.
/*// Locate where to add this method; also verify if this method already
// exists
for (final BodyDeclaration bd : members) {
if (bd instanceof MethodDeclaration) {
// Next method should appear after this current method
final MethodDeclaration md = (MethodDeclaration) bd;
/*if (md.getName().equals(d.getName())) {
if ((md.getParameters() == null || md.getParameters()
.isEmpty())
&& (d.getParameters() == null || d.getParameters()
.isEmpty())) {
throw new IllegalStateException("Method '"
+ method.getMethodName().getSymbolName()
+ "' already exists");
}
else if (md.getParameters() != null
&& md.getParameters().size() == d.getParameters()
.size()) {
// Possible match, we need to consider parameter types
// as well now
final MethodMetadata methodMetadata = JavaParserMethodMetadataBuilder
.getInstance(method.getDeclaredByMetadataId(),
md, compilationUnitServices,
typeParameters).build();
boolean matchesFully = true;
index = -1;
for (final AnnotatedJavaType existingParameter : methodMetadata
.getParameterTypes()) {
index++;
final AnnotatedJavaType parameterType = method
.getParameterTypes().get(index);
if (!existingParameter.getJavaType().equals(
parameterType.getJavaType())) {
matchesFully = false;
break;
}
}
if (matchesFully) {
throw new IllegalStateException(
"Method '"
+ method.getMethodName()
.getSymbolName()
+ "' already exists with identical parameters");
}
}
}
}
}*/
// ROO-3834: Append Javadoc
CommentStructure commentStructure = method.getCommentStructure();
if (commentStructure != null) {
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, commentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, commentStructure);
}
} else {
// ROO-3834: Include default documentation
CommentStructure defaultCommentStructure = new CommentStructure();
// ROO-3834: Append default Javadoc if not exists a comment structure,
// including method params, return and throws.
List<String> parameterNames = new ArrayList<String>();
for (JavaSymbolName name : method.getParameterNames()) {
parameterNames.add(name.getSymbolName());
}
List<String> throwsTypesNames = new ArrayList<String>();
for (JavaType type : method.getThrowsTypes()) {
throwsTypesNames.add(type.getSimpleTypeName());
}
String returnInfo = null;
JavaType returnJavaType = method.getReturnType();
if (!returnJavaType.equals(JavaType.VOID_OBJECT) && !returnJavaType.equals(JavaType.VOID_PRIMITIVE)) {
returnInfo = returnJavaType.getSimpleTypeName();
}
JavadocComment javadocComment = new JavadocComment("TODO Auto-generated method documentation", parameterNames, returnInfo, throwsTypesNames);
defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
method.setCommentStructure(defaultCommentStructure);
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, defaultCommentStructure);
}
}
// Add the method to the end of the compilation unit
members.add(d);
}
use of com.github.antlrjavaparser.api.type.ReferenceType in project spring-roo by spring-projects.
the class JavaParserUtils method getResolvedName.
public static Type getResolvedName(final JavaType target, final JavaType current, final CompilationUnitServices compilationUnit) {
final NameExpr nameExpr = JavaParserUtils.importTypeIfRequired(target, compilationUnit.getImports(), current);
final ClassOrInterfaceType resolvedName = JavaParserUtils.getClassOrInterfaceType(nameExpr);
if (current.getParameters() != null && current.getParameters().size() > 0) {
resolvedName.setTypeArgs(new ArrayList<Type>());
for (final JavaType param : current.getParameters()) {
resolvedName.getTypeArgs().add(getResolvedName(target, param, compilationUnit));
}
}
if (current.getArray() > 0) {
// Primitives includes array declaration in resolvedName
if (!current.isPrimitive()) {
return new ReferenceType(resolvedName, current.getArray());
}
}
return resolvedName;
}
use of com.github.antlrjavaparser.api.type.ReferenceType in project spring-roo by spring-projects.
the class JavaParserUtils method importExpressionIfRequired.
/**
* Recognises {@link Expression}s of type {@link FieldAccessExpr} and
* {@link ClassExpr} and automatically imports them if required, returning
* the correct {@link Expression} that should subsequently be used.
* <p>
* Even if an {@link Expression} is not resolved by this method into a type
* and/or imported, the method guarantees to always return an
* {@link Expression} that the caller can subsequently use in place of the
* passed {@link Expression}. In practical terms, the {@link Expression}
* passed to this method will be returned unless the type was already
* imported, just imported, or represented a java.lang type.
*
* @param targetType the compilation unit target type (required)
* @param imports the existing imports (required)
* @param value that expression, which need not necessarily be resolvable to
* a type (required)
* @return the expression to now use, as appropriately resolved (never
* returns null)
*/
public static Expression importExpressionIfRequired(final JavaType targetType, final List<ImportDeclaration> imports, final Expression value) {
Validate.notNull(targetType, "Target type required");
Validate.notNull(imports, "Imports required");
Validate.notNull(value, "Expression value required");
if (value instanceof FieldAccessExpr) {
final Expression scope = ((FieldAccessExpr) value).getScope();
final String field = ((FieldAccessExpr) value).getField();
if (scope instanceof QualifiedNameExpr) {
final String packageName = ((QualifiedNameExpr) scope).getQualifier().getName();
final String simpleName = ((QualifiedNameExpr) scope).getName();
final String fullyQualifiedName = packageName + "." + simpleName;
final JavaType javaType = new JavaType(fullyQualifiedName);
final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
if (!(nameToUse instanceof QualifiedNameExpr)) {
return new FieldAccessExpr(nameToUse, field);
}
}
} else if (value instanceof ClassExpr) {
final Type type = ((ClassExpr) value).getType();
if (type instanceof ClassOrInterfaceType) {
final JavaType javaType = new JavaType(((ClassOrInterfaceType) type).getName());
final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
if (!(nameToUse instanceof QualifiedNameExpr)) {
return new ClassExpr(new ClassOrInterfaceType(javaType.getSimpleTypeName()));
}
} else if (type instanceof ReferenceType && ((ReferenceType) type).getType() instanceof ClassOrInterfaceType) {
final ClassOrInterfaceType cit = (ClassOrInterfaceType) ((ReferenceType) type).getType();
final JavaType javaType = new JavaType(cit.getName());
final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
if (!(nameToUse instanceof QualifiedNameExpr)) {
return new ClassExpr(new ClassOrInterfaceType(javaType.getSimpleTypeName()));
}
}
} else if (value instanceof ArrayInitializerExpr) {
List<Expression> values = ((ArrayInitializerExpr) value).getValues();
for (Expression expressionValue : values) {
// Check annotation expression
if (expressionValue instanceof NormalAnnotationExpr) {
Validate.isInstanceOf(NormalAnnotationExpr.class, expressionValue, "Attempting to add >1 annotation member-value pair requires an existing normal annotation expression");
final List<MemberValuePair> annotationPairs = ((NormalAnnotationExpr) expressionValue).getPairs();
for (final MemberValuePair pair : annotationPairs) {
final Expression toUse = JavaParserUtils.importExpressionIfRequired(targetType, imports, pair.getValue());
pair.setValue(toUse);
}
}
}
}
// Make no changes
return value;
}
use of com.github.antlrjavaparser.api.type.ReferenceType in project spring-roo by spring-projects.
the class JavaParserUtils method importParametersForType.
public static ReferenceType importParametersForType(final JavaType targetType, final List<ImportDeclaration> imports, final JavaType typeToImport) {
Validate.notNull(targetType, "Target type is required");
Validate.notNull(imports, "Compilation unit imports required");
Validate.notNull(typeToImport, "Java type to import is required");
final ClassOrInterfaceType cit = getClassOrInterfaceType(importTypeIfRequired(targetType, imports, typeToImport));
// Add any type arguments presented for the return type
if (typeToImport.getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : typeToImport.getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(targetType, imports, parameter));
}
}
final ReferenceType refType = new ReferenceType(cit);
// Handle arrays
if (typeToImport.isArray()) {
refType.setArrayCount(typeToImport.getArray());
}
return refType;
}
Aggregations