Search in sources :

Example 6 with PsiDirectory

use of com.intellij.psi.PsiDirectory in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoTestFunctionCompletionProvider method addCompletions.

@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
    Project project = parameters.getPosition().getProject();
    PsiFile file = parameters.getOriginalFile();
    PsiDirectory containingDirectory = file.getContainingDirectory();
    if (file instanceof GoFile && containingDirectory != null) {
        CompletionResultSet resultSet = result.withPrefixMatcher(new CamelHumpMatcher(result.getPrefixMatcher().getPrefix(), false));
        Collection<String> allPackageFunctionNames = collectAllFunctionNames(containingDirectory);
        Set<String> allTestFunctionNames = collectAllTestNames(allPackageFunctionNames, project, (GoFile) file);
        String fileNameWithoutTestPrefix = StringUtil.trimEnd(file.getName(), GoConstants.TEST_SUFFIX_WITH_EXTENSION) + ".go";
        GlobalSearchScope packageScope = GoPackageUtil.packageScope(containingDirectory, ((GoFile) file).getCanonicalPackageName());
        GlobalSearchScope scope = new GoUtil.ExceptTestsScope(packageScope);
        IdFilter idFilter = GoIdFilter.getFilesFilter(scope);
        for (String functionName : allPackageFunctionNames) {
            GoFunctionIndex.process(functionName, project, scope, idFilter, declaration -> {
                addVariants(declaration, functionName, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet);
                return false;
            });
        }
        Collection<String> methodKeys = ContainerUtil.newTroveSet();
        StubIndex.getInstance().processAllKeys(GoMethodIndex.KEY, new CancellableCollectProcessor<>(methodKeys), scope, idFilter);
        for (String key : methodKeys) {
            Processor<GoMethodDeclaration> processor = declaration -> {
                GoMethodDeclarationStubElementType.calcTypeText(declaration);
                String typeText = key.substring(Math.min(key.indexOf('.') + 1, key.length()));
                String methodName = declaration.getName();
                if (methodName != null) {
                    if (!declaration.isPublic() || declaration.isBlank()) {
                        return true;
                    }
                    String lookupString = !typeText.isEmpty() ? StringUtil.capitalize(typeText) + "_" + methodName : methodName;
                    addVariants(declaration, lookupString, fileNameWithoutTestPrefix, allTestFunctionNames, resultSet);
                }
                return true;
            };
            GoMethodIndex.process(key, project, scope, idFilter, processor);
        }
    }
}
Also used : com.goide.psi(com.goide.psi) Document(com.intellij.openapi.editor.Document) GoMethodIndex(com.goide.stubs.index.GoMethodIndex) GotestGenerateAction(com.goide.runconfig.testing.frameworks.gotest.GotestGenerateAction) IdFilter(com.intellij.util.indexing.IdFilter) StubIndex(com.intellij.psi.stubs.StubIndex) ContainerUtil(com.intellij.util.containers.ContainerUtil) GoTestFunctionType(com.goide.runconfig.testing.GoTestFunctionType) PsiTreeUtil(com.intellij.psi.util.PsiTreeUtil) GoMethodDeclarationStubElementType(com.goide.stubs.types.GoMethodDeclarationStubElementType) PsiElement(com.intellij.psi.PsiElement) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) GoElementFactory(com.goide.psi.impl.GoElementFactory) CamelHumpMatcher(com.intellij.codeInsight.completion.impl.CamelHumpMatcher) PsiDocumentManager(com.intellij.psi.PsiDocumentManager) ProcessingContext(com.intellij.util.ProcessingContext) GoFunctionIndex(com.goide.stubs.index.GoFunctionIndex) LookupElementBuilder(com.intellij.codeInsight.lookup.LookupElementBuilder) LookupElement(com.intellij.codeInsight.lookup.LookupElement) StringUtil(com.intellij.openapi.util.text.StringUtil) Collection(java.util.Collection) GoUtil(com.goide.util.GoUtil) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) Set(java.util.Set) UniqueNameGenerator(com.intellij.util.text.UniqueNameGenerator) com.intellij.codeInsight.completion(com.intellij.codeInsight.completion) GoIdFilter(com.goide.stubs.index.GoIdFilter) CodeStyleManager(com.intellij.psi.codeStyle.CodeStyleManager) Processor(com.intellij.util.Processor) GoConstants(com.goide.GoConstants) PsiDirectory(com.intellij.psi.PsiDirectory) GoPackageUtil(com.goide.sdk.GoPackageUtil) NotNull(org.jetbrains.annotations.NotNull) IdFilter(com.intellij.util.indexing.IdFilter) GoIdFilter(com.goide.stubs.index.GoIdFilter) CamelHumpMatcher(com.intellij.codeInsight.completion.impl.CamelHumpMatcher) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile)

Example 7 with PsiDirectory

use of com.intellij.psi.PsiDirectory in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoImportPackageQuickFix method getImportPathVariantsToImport.

@NotNull
public static List<String> getImportPathVariantsToImport(@NotNull String packageName, @NotNull PsiElement context) {
    PsiFile contextFile = context.getContainingFile();
    Set<String> imported = contextFile instanceof GoFile ? ((GoFile) contextFile).getImportedPackagesMap().keySet() : Collections.emptySet();
    Project project = context.getProject();
    PsiDirectory parentDirectory = contextFile != null ? contextFile.getParent() : null;
    String testTargetPackage = GoTestFinder.getTestTargetPackage(contextFile);
    Module module = contextFile != null ? ModuleUtilCore.findModuleForPsiElement(contextFile) : null;
    boolean vendoringEnabled = GoVendoringUtil.isVendoringEnabled(module);
    GlobalSearchScope scope = GoUtil.goPathResolveScope(context);
    Collection<GoFile> packages = StubIndex.getElements(GoPackagesIndex.KEY, packageName, project, scope, GoFile.class);
    return sorted(skipNulls(map2Set(packages, file -> {
        if (parentDirectory != null && parentDirectory.isEquivalentTo(file.getParent())) {
            if (testTargetPackage == null || !testTargetPackage.equals(file.getPackageName())) {
                return null;
            }
        }
        if (!GoPsiImplUtil.canBeAutoImported(file, false, module)) {
            return null;
        }
        String importPath = file.getImportPath(vendoringEnabled);
        return !imported.contains(importPath) ? importPath : null;
    })), new MyImportsComparator(context, vendoringEnabled));
}
Also used : GoFile(com.goide.psi.GoFile) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile) Module(com.intellij.openapi.module.Module) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with PsiDirectory

use of com.intellij.psi.PsiDirectory in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoCompletionContributor method fillCompletionVariants.

@Override
public void fillCompletionVariants(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition();
    PsiFile file = parameters.getOriginalFile();
    ASTNode node = position.getNode();
    if (file instanceof GoFile && position.getParent() instanceof GoPackageClause && node.getElementType() == GoTypes.IDENTIFIER) {
        boolean isTestFile = GoTestFinder.isTestFile(file);
        PsiDirectory directory = file.getParent();
        String currentPackageName = ((GoFile) file).getPackageName();
        Collection<String> packagesInDirectory = GoPackageUtil.getAllPackagesInDirectory(directory, null, true);
        for (String packageName : packagesInDirectory) {
            if (!packageName.equals(currentPackageName)) {
                result.addElement(packageLookup(packageName, GoCompletionUtil.PACKAGE_PRIORITY - 1));
            }
            if (isTestFile) {
                result.addElement(packageLookup(packageName + GoConstants.TEST_SUFFIX, GoCompletionUtil.PACKAGE_PRIORITY));
            }
        }
        if (directory != null && ContainerUtil.filter(directory.getFiles(), Conditions.instanceOf(GoFile.class)).size() == 1) {
            String packageFromDirectory = GoPsiImplUtil.getLocalPackageName(directory.getName());
            if (!packageFromDirectory.isEmpty()) {
                result.addElement(packageLookup(packageFromDirectory, GoCompletionUtil.PACKAGE_PRIORITY - 1));
            }
        }
        result.addElement(packageLookup(GoConstants.MAIN, GoCompletionUtil.PACKAGE_PRIORITY - 2));
    }
    super.fillCompletionVariants(parameters, result);
}
Also used : PsiDirectory(com.intellij.psi.PsiDirectory) ASTNode(com.intellij.lang.ASTNode) PsiFile(com.intellij.psi.PsiFile) PsiElement(com.intellij.psi.PsiElement)

Example 9 with PsiDirectory

use of com.intellij.psi.PsiDirectory in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoTestFinder method findTestsForClass.

@NotNull
@Override
public Collection<PsiElement> findTestsForClass(@NotNull PsiElement element) {
    PsiFile file = InjectedLanguageUtil.getTopLevelFile(element);
    if (file instanceof GoFile) {
        PsiDirectory directory = file.getContainingDirectory();
        PsiFile testFile = directory.findFile(FileUtil.getNameWithoutExtension(file.getName()) + GoConstants.TEST_SUFFIX_WITH_EXTENSION);
        if (testFile != null) {
            return ContainerUtil.newSmartList(testFile);
        }
    }
    return Collections.emptyList();
}
Also used : GoFile(com.goide.psi.GoFile) PsiDirectory(com.intellij.psi.PsiDirectory) PsiFile(com.intellij.psi.PsiFile) NotNull(org.jetbrains.annotations.NotNull)

Example 10 with PsiDirectory

use of com.intellij.psi.PsiDirectory in project go-lang-idea-plugin by go-lang-plugin-org.

the class GoAnnotator method annotate.

// todo: unify with DlvApi.Variable.Kind
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
    if (!(element instanceof GoCompositeElement) || !element.isValid())
        return;
    if (element instanceof GoPackageClause) {
        PsiElement identifier = ((GoPackageClause) element).getIdentifier();
        if (identifier != null && identifier.textMatches("_")) {
            holder.createErrorAnnotation(identifier, "Invalid package name");
            return;
        }
    }
    if (element instanceof GoContinueStatement) {
        if (!(PsiTreeUtil.getParentOfType(element, GoForStatement.class, GoFunctionLit.class) instanceof GoForStatement)) {
            Annotation annotation = holder.createErrorAnnotation(element, "Continue statement not inside a for loop");
            annotation.registerFix(new GoReplaceWithReturnStatementQuickFix(element));
        }
    } else if (element instanceof GoBreakStatement) {
        if (GoPsiImplUtil.getBreakStatementOwner(element) == null) {
            Annotation annotation = holder.createErrorAnnotation(element, "Break statement not inside a for loop, select or switch");
            annotation.registerFix(new GoReplaceWithReturnStatementQuickFix(element));
        }
    } else if (element instanceof GoReferenceExpression) {
        GoReferenceExpression reference = (GoReferenceExpression) element;
        PsiElement resolvedReference = reference.resolve();
        if (resolvedReference instanceof PsiDirectory || resolvedReference instanceof GoImportSpec) {
            // It's a package reference. It should either be inside a package clause or part of a larger reference expression.
            if (!(element.getParent() instanceof GoReferenceExpression) && PsiTreeUtil.getParentOfType(reference, GoPackageClause.class) == null) {
                holder.createErrorAnnotation(element, "Use of package " + element.getText() + " without selector");
            }
        }
        if (resolvedReference instanceof GoTypeSpec && isIllegalUseOfTypeAsExpression(reference)) {
            holder.createErrorAnnotation(element, "Type " + element.getText() + " is not an expression");
        }
        if (resolvedReference instanceof GoConstDefinition && resolvedReference.getParent() instanceof GoConstSpec && PsiTreeUtil.getParentOfType(element, GoConstDeclaration.class) != null) {
            checkSelfReference((GoReferenceExpression) element, resolvedReference, holder);
        }
        if (resolvedReference instanceof GoVarDefinition && resolvedReference.getParent() instanceof GoVarSpec && PsiTreeUtil.getParentOfType(element, GoVarDeclaration.class) != null) {
            checkSelfReference((GoReferenceExpression) element, resolvedReference, holder);
        }
    } else if (element instanceof GoLiteralTypeExpr) {
        if (isIllegalUseOfTypeAsExpression(element)) {
            holder.createErrorAnnotation(element, "Type " + element.getText() + " is not an expression");
        }
    } else if (element instanceof GoCompositeLit) {
        GoCompositeLit literal = (GoCompositeLit) element;
        if (literal.getType() instanceof GoMapType) {
            GoLiteralValue literalValue = literal.getLiteralValue();
            if (literalValue != null) {
                for (GoElement literalElement : literalValue.getElementList()) {
                    if (literalElement.getKey() == null) {
                        holder.createErrorAnnotation(literalElement, "Missing key in map literal");
                    }
                }
            }
        }
    } else if (element instanceof GoTypeAssertionExpr) {
        GoType type = ((GoTypeAssertionExpr) element).getExpression().getGoType(null);
        if (type != null) {
            GoType underlyingType = type.getUnderlyingType();
            if (!(underlyingType instanceof GoInterfaceType)) {
                String message = String.format("Invalid type assertion: %s, (non-interface type %s on left)", element.getText(), type.getText());
                holder.createErrorAnnotation(((GoTypeAssertionExpr) element).getExpression(), message);
            }
        }
    } else if (element instanceof GoBuiltinCallExpr) {
        GoBuiltinCallExpr call = (GoBuiltinCallExpr) element;
        if ("make".equals(call.getReferenceExpression().getText())) {
            checkMakeCall(call, holder);
        }
    } else if (element instanceof GoCallExpr) {
        GoCallExpr call = (GoCallExpr) element;
        GoExpression callExpression = call.getExpression();
        if (GoInspectionUtil.getFunctionResultCount(call) == 0) {
            PsiElement parent = call.getParent();
            boolean simpleStatement = parent instanceof GoLeftHandExprList && parent.getParent() instanceof GoSimpleStatement;
            boolean inDeferOrGo = parent instanceof GoDeferStatement || parent instanceof GoGoStatement;
            if (!simpleStatement && !inDeferOrGo) {
                holder.createErrorAnnotation(call, call.getText() + " used as value");
            }
        }
        if (callExpression instanceof GoReferenceExpression) {
            GoReferenceExpression reference = (GoReferenceExpression) callExpression;
            if (reference.textMatches("cap")) {
                if (GoPsiImplUtil.builtin(reference.resolve())) {
                    checkCapCall(call, holder);
                }
            }
        }
    } else if (element instanceof GoTopLevelDeclaration) {
        if (element.getParent() instanceof GoFile) {
            if (element instanceof GoTypeDeclaration) {
                for (GoTypeSpec spec : ((GoTypeDeclaration) element).getTypeSpecList()) {
                    if (spec.getIdentifier().textMatches(GoConstants.INIT)) {
                        holder.createErrorAnnotation(spec, "Cannot declare init, must be a function");
                    }
                }
            } else if (element instanceof GoVarDeclaration) {
                for (GoVarSpec spec : ((GoVarDeclaration) element).getVarSpecList()) {
                    for (GoVarDefinition definition : spec.getVarDefinitionList()) {
                        if (definition.getIdentifier().textMatches(GoConstants.INIT)) {
                            holder.createErrorAnnotation(spec, "Cannot declare init, must be a function");
                        }
                    }
                }
            } else if (element instanceof GoConstDeclaration) {
                for (GoConstSpec spec : ((GoConstDeclaration) element).getConstSpecList()) {
                    for (GoConstDefinition definition : spec.getConstDefinitionList()) {
                        if (definition.getIdentifier().textMatches(GoConstants.INIT)) {
                            holder.createErrorAnnotation(spec, "Cannot declare init, must be a function");
                        }
                    }
                }
            } else if (element instanceof GoFunctionDeclaration) {
                GoFunctionDeclaration declaration = (GoFunctionDeclaration) element;
                if (declaration.getIdentifier().textMatches(GoConstants.INIT) || declaration.getIdentifier().textMatches(GoConstants.MAIN) && GoConstants.MAIN.equals(declaration.getContainingFile().getPackageName())) {
                    GoSignature signature = declaration.getSignature();
                    if (signature != null) {
                        GoResult result = signature.getResult();
                        if (result != null && !result.isVoid()) {
                            Annotation annotation = holder.createErrorAnnotation(result, declaration.getName() + " function must have no arguments and no return values");
                            annotation.registerFix(new GoEmptySignatureQuickFix(declaration));
                        }
                        GoParameters parameters = signature.getParameters();
                        if (!parameters.getParameterDeclarationList().isEmpty()) {
                            Annotation annotation = holder.createErrorAnnotation(parameters, declaration.getName() + " function must have no arguments and no return values");
                            annotation.registerFix(new GoEmptySignatureQuickFix(declaration));
                        }
                    }
                }
            }
        }
    } else if (element instanceof GoIndexOrSliceExpr) {
        GoIndexOrSliceExpr slice = (GoIndexOrSliceExpr) element;
        GoExpression expr = slice.getExpression();
        GoExpression thirdIndex = slice.getIndices().third;
        if (expr == null || thirdIndex == null) {
            return;
        }
        if (GoTypeUtil.isString(expr.getGoType(null))) {
            ASTNode[] colons = slice.getNode().getChildren(TokenSet.create(GoTypes.COLON));
            if (colons.length == 2) {
                PsiElement secondColon = colons[1].getPsi();
                TextRange r = TextRange.create(secondColon.getTextRange().getStartOffset(), thirdIndex.getTextRange().getEndOffset());
                Annotation annotation = holder.createErrorAnnotation(r, "Invalid operation " + slice.getText() + " (3-index slice of string)");
                annotation.registerFix(new GoDeleteRangeQuickFix(secondColon, thirdIndex, "Delete third index"));
            }
        }
    }
}
Also used : GoReplaceWithReturnStatementQuickFix(com.goide.quickfix.GoReplaceWithReturnStatementQuickFix) PsiDirectory(com.intellij.psi.PsiDirectory) PsiElement(com.intellij.psi.PsiElement) GoDeleteRangeQuickFix(com.goide.quickfix.GoDeleteRangeQuickFix) TextRange(com.intellij.openapi.util.TextRange) Annotation(com.intellij.lang.annotation.Annotation) GoEmptySignatureQuickFix(com.goide.quickfix.GoEmptySignatureQuickFix)

Aggregations

PsiDirectory (com.intellij.psi.PsiDirectory)321 VirtualFile (com.intellij.openapi.vfs.VirtualFile)122 PsiFile (com.intellij.psi.PsiFile)111 PsiElement (com.intellij.psi.PsiElement)79 Project (com.intellij.openapi.project.Project)73 Module (com.intellij.openapi.module.Module)68 Nullable (org.jetbrains.annotations.Nullable)62 NotNull (org.jetbrains.annotations.NotNull)50 IdeView (com.intellij.ide.IdeView)31 AbstractTreeNode (com.intellij.ide.util.treeView.AbstractTreeNode)24 ProjectFileIndex (com.intellij.openapi.roots.ProjectFileIndex)24 PsiManager (com.intellij.psi.PsiManager)24 GlobalSearchScope (com.intellij.psi.search.GlobalSearchScope)20 ArrayList (java.util.ArrayList)20 PsiPackage (com.intellij.psi.PsiPackage)17 File (java.io.File)15 PsiFileSystemItem (com.intellij.psi.PsiFileSystemItem)11 IncorrectOperationException (com.intellij.util.IncorrectOperationException)11 Course (com.jetbrains.edu.learning.courseFormat.Course)11 JSClass (com.intellij.lang.javascript.psi.ecmal4.JSClass)10