use of org.ballerinalang.plugins.idea.psi.ImportDeclarationNode in project ballerina by ballerina-lang.
the class BallerinaImportOptimizer method getUsedImportDeclarations.
/**
* Used to get used imports in a file.
*
* @param file a {@link PsiFile} element
* @return list of used {@link ImportDeclarationNode} in the file.
*/
private List<ImportDeclarationNode> getUsedImportDeclarations(@NotNull PsiFile file) {
// This is used to track all packages used in the file.
List<String> usedPackages = new LinkedList<>();
Collection<PackageNameNode> packageNameNodes = PsiTreeUtil.findChildrenOfType(file, PackageNameNode.class);
for (PackageNameNode packageNameNode : packageNameNodes) {
ProgressManager.checkCanceled();
if (packageNameNode == null) {
continue;
}
PackageDeclarationNode packageDeclarationNode = PsiTreeUtil.getParentOfType(packageNameNode, PackageDeclarationNode.class);
if (packageDeclarationNode != null) {
continue;
}
ImportDeclarationNode importDeclarationNode = PsiTreeUtil.getParentOfType(packageNameNode, ImportDeclarationNode.class);
if (importDeclarationNode != null) {
continue;
}
XmlAttribNode xmlAttribNode = PsiTreeUtil.getParentOfType(packageNameNode, XmlAttribNode.class);
if (xmlAttribNode != null) {
continue;
}
PsiElement nameIdentifier = packageNameNode.getNameIdentifier();
if (nameIdentifier == null) {
continue;
}
usedPackages.add(nameIdentifier.getText());
}
List<ImportDeclarationNode> usedImportDeclarations = new LinkedList<>();
List<String> fullyQualifiedImportedPackages = new LinkedList<>();
List<String> importedPackages = new LinkedList<>();
Collection<ImportDeclarationNode> importDeclarationNodes = PsiTreeUtil.findChildrenOfType(file, ImportDeclarationNode.class);
for (ImportDeclarationNode importDeclarationNode : importDeclarationNodes) {
ProgressManager.checkCanceled();
if (importDeclarationNode == null) {
continue;
}
// Check unused imports. No need to check for fully qualified path since we cant import packages of same
// name.
List<PackageNameNode> packageNames = new ArrayList<>(PsiTreeUtil.findChildrenOfType(importDeclarationNode, PackageNameNode.class));
PackageNameNode lastPackage = ContainerUtil.getLastItem(packageNames);
if (lastPackage == null) {
continue;
}
String lastPackageName = lastPackage.getText();
if (!usedPackages.contains(lastPackageName)) {
continue;
}
// Check conflicting imports (which ends with same package name).
if (importedPackages.contains(lastPackageName)) {
continue;
}
importedPackages.add(lastPackageName);
// Check redeclared imports.
FullyQualifiedPackageNameNode fullyQualifiedPackageName = PsiTreeUtil.getChildOfType(importDeclarationNode, FullyQualifiedPackageNameNode.class);
if (fullyQualifiedPackageName == null) {
continue;
}
if (fullyQualifiedImportedPackages.contains(fullyQualifiedPackageName.getText())) {
continue;
}
fullyQualifiedImportedPackages.add(fullyQualifiedPackageName.getText());
usedImportDeclarations.add(importDeclarationNode);
}
return usedImportDeclarations;
}
Aggregations