Search in sources :

Example 1 with OrderedSet

use of com.intellij.util.containers.OrderedSet in project intellij-community by JetBrains.

the class JavaSmartStepIntoHandler method findSmartStepTargets.

protected List<SmartStepTarget> findSmartStepTargets(final SourcePosition position, @Nullable SuspendContextImpl suspendContext, @NotNull DebuggerContextImpl debuggerContext) {
    final int line = position.getLine();
    if (line < 0) {
        // the document has been changed
        return Collections.emptyList();
    }
    final PsiFile file = position.getFile();
    final VirtualFile vFile = file.getVirtualFile();
    if (vFile == null) {
        // the file is not physical
        return Collections.emptyList();
    }
    final Document doc = FileDocumentManager.getInstance().getDocument(vFile);
    if (doc == null)
        return Collections.emptyList();
    if (line >= doc.getLineCount()) {
        // the document has been changed
        return Collections.emptyList();
    }
    TextRange curLineRange = DocumentUtil.getLineTextRange(doc, line);
    PsiElement element = position.getElementAt();
    PsiElement body = DebuggerUtilsEx.getBody(DebuggerUtilsEx.getContainingMethod(element));
    final TextRange lineRange = (body != null) ? curLineRange.intersection(body.getTextRange()) : curLineRange;
    if (lineRange == null || lineRange.isEmpty()) {
        return Collections.emptyList();
    }
    if (element != null && !(element instanceof PsiCompiledElement)) {
        do {
            final PsiElement parent = element.getParent();
            if (parent == null || (parent.getTextOffset() < lineRange.getStartOffset())) {
                break;
            }
            element = parent;
        } while (true);
        //noinspection unchecked
        final List<SmartStepTarget> targets = new OrderedSet<>();
        final Ref<TextRange> textRange = new Ref<>(lineRange);
        final PsiElementVisitor methodCollector = new JavaRecursiveElementVisitor() {

            final Deque<PsiMethod> myContextStack = new LinkedList<>();

            final Deque<String> myParamNameStack = new LinkedList<>();

            private int myNextLambdaExpressionOrdinal = 0;

            private boolean myInsideLambda = false;

            @Nullable
            private String getCurrentParamName() {
                return myParamNameStack.peekFirst();
            }

            @Override
            public void visitAnonymousClass(PsiAnonymousClass aClass) {
                for (PsiMethod psiMethod : aClass.getMethods()) {
                    targets.add(0, new MethodSmartStepTarget(psiMethod, getCurrentParamName(), psiMethod.getBody(), true, null));
                }
            }

            public void visitLambdaExpression(PsiLambdaExpression expression) {
                boolean inLambda = myInsideLambda;
                myInsideLambda = true;
                super.visitLambdaExpression(expression);
                myInsideLambda = inLambda;
                targets.add(0, new LambdaSmartStepTarget(expression, getCurrentParamName(), expression.getBody(), myNextLambdaExpressionOrdinal++, null, !myInsideLambda));
            }

            @Override
            public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
                PsiElement element = expression.resolve();
                if (element instanceof PsiMethod) {
                    PsiElement navMethod = element.getNavigationElement();
                    if (navMethod instanceof PsiMethod) {
                        targets.add(0, new MethodSmartStepTarget(((PsiMethod) navMethod), null, expression, true, null));
                    }
                }
            }

            @Override
            public void visitField(PsiField field) {
                if (checkTextRange(field, false)) {
                    super.visitField(field);
                }
            }

            @Override
            public void visitMethod(PsiMethod method) {
                if (checkTextRange(method, false)) {
                    super.visitMethod(method);
                }
            }

            @Override
            public void visitStatement(PsiStatement statement) {
                if (checkTextRange(statement, true)) {
                    super.visitStatement(statement);
                }
            }

            @Override
            public void visitIfStatement(PsiIfStatement statement) {
                visitConditional(statement.getCondition(), statement.getThenBranch(), statement.getElseBranch());
            }

            @Override
            public void visitConditionalExpression(PsiConditionalExpression expression) {
                visitConditional(expression.getCondition(), expression.getThenExpression(), expression.getElseExpression());
            }

            private void visitConditional(@Nullable PsiElement condition, @Nullable PsiElement thenBranch, @Nullable PsiElement elseBranch) {
                if (condition != null && checkTextRange(condition, true)) {
                    condition.accept(this);
                }
                ThreeState conditionRes = evaluateCondition(condition);
                if (conditionRes != ThreeState.NO && thenBranch != null && checkTextRange(thenBranch, true)) {
                    thenBranch.accept(this);
                }
                if (conditionRes != ThreeState.YES && elseBranch != null && checkTextRange(elseBranch, true)) {
                    elseBranch.accept(this);
                }
            }

            private ThreeState evaluateCondition(@Nullable PsiElement condition) {
                if (condition != null && !DebuggerUtils.hasSideEffects(condition)) {
                    try {
                        ExpressionEvaluator evaluator = EvaluatorBuilderImpl.getInstance().build(condition, position);
                        return ThreeState.fromBoolean(DebuggerUtilsEx.evaluateBoolean(evaluator, debuggerContext.createEvaluationContext()));
                    } catch (EvaluateException e) {
                        LOG.info(e);
                    }
                }
                return ThreeState.UNSURE;
            }

            @Override
            public void visitExpression(PsiExpression expression) {
                checkTextRange(expression, true);
                super.visitExpression(expression);
            }

            boolean checkTextRange(@NotNull PsiElement expression, boolean expand) {
                TextRange range = expression.getTextRange();
                if (lineRange.intersects(range)) {
                    if (expand) {
                        textRange.set(textRange.get().union(range));
                    }
                    return true;
                }
                return false;
            }

            public void visitExpressionList(PsiExpressionList expressionList) {
                PsiMethod psiMethod = myContextStack.peekFirst();
                if (psiMethod != null) {
                    final String methodName = psiMethod.getName();
                    final PsiExpression[] expressions = expressionList.getExpressions();
                    final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
                    for (int idx = 0; idx < expressions.length; idx++) {
                        final String paramName = (idx < parameters.length && !parameters[idx].isVarArgs()) ? parameters[idx].getName() : "arg" + (idx + 1);
                        myParamNameStack.push(methodName + ": " + paramName + ".");
                        final PsiExpression argExpression = expressions[idx];
                        try {
                            argExpression.accept(this);
                        } finally {
                            myParamNameStack.pop();
                        }
                    }
                } else {
                    super.visitExpressionList(expressionList);
                }
            }

            @Override
            public void visitCallExpression(final PsiCallExpression expression) {
                final PsiMethod psiMethod = expression.resolveMethod();
                if (psiMethod != null) {
                    myContextStack.push(psiMethod);
                    targets.add(new MethodSmartStepTarget(psiMethod, null, expression instanceof PsiMethodCallExpression ? ((PsiMethodCallExpression) expression).getMethodExpression().getReferenceNameElement() : expression instanceof PsiNewExpression ? ((PsiNewExpression) expression).getClassOrAnonymousClassReference() : expression, myInsideLambda, null));
                }
                try {
                    super.visitCallExpression(expression);
                } finally {
                    if (psiMethod != null) {
                        myContextStack.pop();
                    }
                }
            }
        };
        element.accept(methodCollector);
        for (PsiElement sibling = element.getNextSibling(); sibling != null; sibling = sibling.getNextSibling()) {
            if (!lineRange.intersects(sibling.getTextRange())) {
                break;
            }
            sibling.accept(methodCollector);
        }
        Range<Integer> lines = new Range<>(doc.getLineNumber(textRange.get().getStartOffset()), doc.getLineNumber(textRange.get().getEndOffset()));
        targets.forEach(t -> t.setCallingExpressionLines(lines));
        if (!targets.isEmpty()) {
            StackFrameProxyImpl frameProxy = suspendContext != null ? suspendContext.getFrameProxy() : null;
            if (frameProxy != null) {
                try {
                    Location location = frameProxy.location();
                    MethodBytecodeUtil.visit(location.method(), location.codeIndex(), new MethodVisitor(Opcodes.API_VERSION) {

                        boolean myLineMatch = false;

                        @Override
                        public void visitLineNumber(int line, Label start) {
                            myLineMatch = lines.isWithin(line - 1);
                        }

                        @Override
                        public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
                            if (myLineMatch) {
                                targets.removeIf(t -> {
                                    if (t instanceof MethodSmartStepTarget) {
                                        return DebuggerUtilsEx.methodMatches(((MethodSmartStepTarget) t).getMethod(), owner.replace("/", "."), name, desc, suspendContext.getDebugProcess());
                                    }
                                    return false;
                                });
                            }
                        }
                    }, true);
                } catch (Exception e) {
                    LOG.info(e);
                }
            }
            return targets;
        }
    }
    return Collections.emptyList();
}
Also used : DebuggerContextImpl(com.intellij.debugger.impl.DebuggerContextImpl) VirtualFile(com.intellij.openapi.vfs.VirtualFile) Document(com.intellij.openapi.editor.Document) Opcodes(org.jetbrains.org.objectweb.asm.Opcodes) DebuggerUtilsEx(com.intellij.debugger.impl.DebuggerUtilsEx) OrderedSet(com.intellij.util.containers.OrderedSet) Computable(com.intellij.openapi.util.Computable) MethodBytecodeUtil(com.intellij.debugger.jdi.MethodBytecodeUtil) Deque(java.util.Deque) DebuggerUIUtil(com.intellij.xdebugger.impl.ui.DebuggerUIUtil) ExpressionEvaluator(com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator) DebuggerContextCommandImpl(com.intellij.debugger.engine.events.DebuggerContextCommandImpl) DebuggerSession(com.intellij.debugger.impl.DebuggerSession) DocumentUtil(com.intellij.util.DocumentUtil) SuspendContextImpl(com.intellij.debugger.engine.SuspendContextImpl) Location(com.sun.jdi.Location) Logger(com.intellij.openapi.diagnostic.Logger) LinkedList(java.util.LinkedList) JavaLanguage(com.intellij.lang.java.JavaLanguage) TextEditor(com.intellij.openapi.fileEditor.TextEditor) StackFrameProxyImpl(com.intellij.debugger.jdi.StackFrameProxyImpl) Range(com.intellij.util.Range) DebuggerUtils(com.intellij.debugger.engine.DebuggerUtils) EvaluateException(com.intellij.debugger.engine.evaluation.EvaluateException) MethodVisitor(org.jetbrains.org.objectweb.asm.MethodVisitor) ThreeState(com.intellij.util.ThreeState) FileDocumentManager(com.intellij.openapi.fileEditor.FileDocumentManager) TextRange(com.intellij.openapi.util.TextRange) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) EvaluatorBuilderImpl(com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl) ApplicationManager(com.intellij.openapi.application.ApplicationManager) Registry(com.intellij.openapi.util.registry.Registry) com.intellij.psi(com.intellij.psi) NotNull(org.jetbrains.annotations.NotNull) Ref(com.intellij.openapi.util.Ref) Collections(java.util.Collections) SourcePosition(com.intellij.debugger.SourcePosition) Label(org.jetbrains.org.objectweb.asm.Label) Label(org.jetbrains.org.objectweb.asm.Label) Document(com.intellij.openapi.editor.Document) MethodVisitor(org.jetbrains.org.objectweb.asm.MethodVisitor) ThreeState(com.intellij.util.ThreeState) TextRange(com.intellij.openapi.util.TextRange) Range(com.intellij.util.Range) TextRange(com.intellij.openapi.util.TextRange) Nullable(org.jetbrains.annotations.Nullable) VirtualFile(com.intellij.openapi.vfs.VirtualFile) StackFrameProxyImpl(com.intellij.debugger.jdi.StackFrameProxyImpl) ExpressionEvaluator(com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator) NotNull(org.jetbrains.annotations.NotNull) EvaluateException(com.intellij.debugger.engine.evaluation.EvaluateException) OrderedSet(com.intellij.util.containers.OrderedSet) Deque(java.util.Deque) EvaluateException(com.intellij.debugger.engine.evaluation.EvaluateException) Ref(com.intellij.openapi.util.Ref) Location(com.sun.jdi.Location)

Example 2 with OrderedSet

use of com.intellij.util.containers.OrderedSet in project intellij-community by JetBrains.

the class CompilerPathsEx method getOutputPaths.

@NotNull
public static String[] getOutputPaths(@NotNull Module[] modules) {
    Set<String> outputPaths = new OrderedSet<>();
    for (Module module : modules) {
        CompilerModuleExtension compilerModuleExtension = !module.isDisposed() ? CompilerModuleExtension.getInstance(module) : null;
        if (compilerModuleExtension == null)
            continue;
        String outputPathUrl = compilerModuleExtension.getCompilerOutputUrl();
        if (outputPathUrl != null) {
            outputPaths.add(VirtualFileManager.extractPath(outputPathUrl).replace('/', File.separatorChar));
        }
        String outputPathForTestsUrl = compilerModuleExtension.getCompilerOutputUrlForTests();
        if (outputPathForTestsUrl != null) {
            outputPaths.add(VirtualFileManager.extractPath(outputPathForTestsUrl).replace('/', File.separatorChar));
        }
        ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
        for (OrderEnumerationHandler.Factory handlerFactory : OrderEnumerationHandler.EP_NAME.getExtensions()) {
            if (handlerFactory.isApplicable(module)) {
                OrderEnumerationHandler handler = handlerFactory.createHandler(module);
                List<String> outputUrls = new SmartList<>();
                handler.addCustomModuleRoots(OrderRootType.CLASSES, moduleRootManager, outputUrls, true, true);
                for (String outputUrl : outputUrls) {
                    outputPaths.add(VirtualFileManager.extractPath(outputUrl).replace('/', File.separatorChar));
                }
            }
        }
    }
    return ArrayUtil.toStringArray(outputPaths);
}
Also used : OrderedSet(com.intellij.util.containers.OrderedSet) Module(com.intellij.openapi.module.Module) SmartList(com.intellij.util.SmartList) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with OrderedSet

use of com.intellij.util.containers.OrderedSet in project android by JetBrains.

the class ImportDependenciesUtil method doImportDependencies.

public static void doImportDependencies(@NotNull Project project, @NotNull List<Module> modules, boolean updateBackwardDependencies) {
    final List<ImportDependenciesTask> tasks = new OrderedSet<ImportDependenciesTask>();
    final List<MyUnresolvedDependency> unresolvedDependencies = new ArrayList<MyUnresolvedDependency>();
    for (Module module : modules) {
        importDependencies(module, updateBackwardDependencies, tasks, unresolvedDependencies);
    }
    final Map<VirtualFile, ModuleProvidingTask> libDir2ModuleProvidingTask = new HashMap<VirtualFile, ModuleProvidingTask>();
    for (ImportDependenciesTask task : tasks) {
        if (task instanceof ModuleProvidingTask) {
            final ModuleProvidingTask moduleProvidingTask = (ModuleProvidingTask) task;
            libDir2ModuleProvidingTask.put(moduleProvidingTask.getContentRoot(), moduleProvidingTask);
        }
    }
    for (MyUnresolvedDependency unresolvedDependency : unresolvedDependencies) {
        final ModuleProvidingTask taskProvidingDepModule = libDir2ModuleProvidingTask.get(unresolvedDependency.myLibDir);
        if (taskProvidingDepModule != null) {
            tasks.add(new AddModuleDependencyTask(unresolvedDependency.myModuleProvider, ModuleProvider.create(taskProvidingDepModule)));
        }
    }
    if (tasks.size() > 0) {
        doImportDependencies(project, tasks);
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) OrderedSet(com.intellij.util.containers.OrderedSet) HashMap(com.intellij.util.containers.HashMap) Module(com.intellij.openapi.module.Module)

Example 4 with OrderedSet

use of com.intellij.util.containers.OrderedSet in project intellij-community by JetBrains.

the class SmartEnterProcessorWithFixers method process.

protected void process(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file, final int attempt, boolean afterCompletion) throws TooManyAttemptsException {
    if (attempt > MAX_ATTEMPTS)
        throw new TooManyAttemptsException();
    myAttempt = attempt;
    try {
        commit(editor);
        if (myFirstErrorOffset != Integer.MAX_VALUE) {
            editor.getCaretModel().moveToOffset(myFirstErrorOffset);
        }
        myFirstErrorOffset = Integer.MAX_VALUE;
        PsiElement atCaret = getStatementAtCaret(editor, file);
        if (atCaret == null) {
            processDefaultEnter(project, editor, file);
            return;
        }
        OrderedSet<PsiElement> queue = new OrderedSet<>();
        collectAllElements(atCaret, queue, collectChildrenRecursively(atCaret));
        queue.add(atCaret);
        for (PsiElement psiElement : queue) {
            for (Fixer fixer : myFixers) {
                fixer.apply(editor, this, psiElement);
                if (LookupManager.getInstance(project).getActiveLookup() != null) {
                    return;
                }
                if (isUncommited(project) || !psiElement.isValid()) {
                    moveCaretInsideBracesIfAny(editor, file);
                    process(project, editor, file, attempt + 1, afterCompletion);
                    return;
                }
            }
        }
        doEnter(atCaret, file, editor, afterCompletion);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
Also used : OrderedSet(com.intellij.util.containers.OrderedSet) IncorrectOperationException(com.intellij.util.IncorrectOperationException) PsiElement(com.intellij.psi.PsiElement)

Aggregations

OrderedSet (com.intellij.util.containers.OrderedSet)4 Module (com.intellij.openapi.module.Module)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)2 NotNull (org.jetbrains.annotations.NotNull)2 SourcePosition (com.intellij.debugger.SourcePosition)1 DebuggerUtils (com.intellij.debugger.engine.DebuggerUtils)1 SuspendContextImpl (com.intellij.debugger.engine.SuspendContextImpl)1 EvaluateException (com.intellij.debugger.engine.evaluation.EvaluateException)1 EvaluatorBuilderImpl (com.intellij.debugger.engine.evaluation.expression.EvaluatorBuilderImpl)1 ExpressionEvaluator (com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator)1 DebuggerContextCommandImpl (com.intellij.debugger.engine.events.DebuggerContextCommandImpl)1 DebuggerContextImpl (com.intellij.debugger.impl.DebuggerContextImpl)1 DebuggerSession (com.intellij.debugger.impl.DebuggerSession)1 DebuggerUtilsEx (com.intellij.debugger.impl.DebuggerUtilsEx)1 MethodBytecodeUtil (com.intellij.debugger.jdi.MethodBytecodeUtil)1 StackFrameProxyImpl (com.intellij.debugger.jdi.StackFrameProxyImpl)1 JavaLanguage (com.intellij.lang.java.JavaLanguage)1 ApplicationManager (com.intellij.openapi.application.ApplicationManager)1 Logger (com.intellij.openapi.diagnostic.Logger)1 Document (com.intellij.openapi.editor.Document)1