return new NameExpr(typeToImport.getSimpleTypeName());
}
NameExpr typeToImportExpr;
if (typeToImport.getEnclosingType() == null) {
typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport
.getPackage().getFullyQualifiedPackageName()),
typeToImport.getSimpleTypeName());
}
else {
typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport
.getEnclosingType().getFullyQualifiedTypeName()),
typeToImport.getSimpleTypeName());
}
final ImportDeclaration newImport = new ImportDeclaration(
typeToImportExpr, false, false);
boolean addImport = true;
boolean useSimpleTypeName = false;
for (final ImportDeclaration existingImport : imports) {
if (existingImport.getName().getName()
.equals(newImport.getName().getName())) {
// Do not import, as there is already an import with the simple
// type name
addImport = false;
// If this is a complete match, it indicates we can use the
// simple type name
if (isEqual(existingImport.getName(), newImport.getName())) {
useSimpleTypeName = true;
break;
}
}
}
if (addImport
&& JdkJavaType.isPartOfJavaLang(typeToImport
.getSimpleTypeName())) {
// This simple type name would be part of java.lang if left as the
// simple name. We want a fully-qualified name.
addImport = false;
useSimpleTypeName = false;
}
if (JdkJavaType.isPartOfJavaLang(typeToImport)) {
// So we would have imported, but we don't need to
addImport = false;
// The fact we could have imported means there was no other
// conflicting simple type names
useSimpleTypeName = true;
}
if (addImport
&& typeToImport.getPackage().equals(compilationUnitPackage)) {
// It is not theoretically necessary to add an import for something
// in the same package,
// but we elect to explicitly perform an import so future
// conflicting types are not imported
// addImport = true;
// useSimpleTypeName = false;
}
if (addImport
&& targetType.getSimpleTypeName().equals(
typeToImport.getSimpleTypeName())) {
// So we would have imported it, but then it would conflict with the
// simple name of the type
addImport = false;
useSimpleTypeName = false;
}
if (addImport) {
imports.add(newImport);
useSimpleTypeName = true;
}
// This is pretty crude, but at least it emits source code for people
// (forget imports, though!)
if (typeToImport.getArgName() != null) {
return new NameExpr(typeToImport.toString());
}
if (useSimpleTypeName) {
return new NameExpr(typeToImport.getSimpleTypeName());
}
return new QualifiedNameExpr(new NameExpr(typeToImport.getPackage()
.getFullyQualifiedPackageName()),
typeToImport.getSimpleTypeName());
}