Search in sources :

Example 26 with InjectedLanguageManager

use of com.intellij.lang.injection.InjectedLanguageManager in project intellij-plugins by JetBrains.

the class AngularJSProcessor method scopeMatches.

private static boolean scopeMatches(PsiElement element, PsiElement declaration) {
    final InjectedLanguageManager injector = InjectedLanguageManager.getInstance(element.getProject());
    if (declaration instanceof JSImplicitElement) {
        if ($EVENT.equals(((JSImplicitElement) declaration).getName())) {
            return eventScopeMatches(injector, element, declaration.getParent());
        }
        declaration = declaration.getParent();
    }
    final PsiLanguageInjectionHost elementContainer = injector.getInjectionHost(element);
    final XmlTagChild elementTag = PsiTreeUtil.getNonStrictParentOfType(elementContainer, XmlTag.class, XmlText.class);
    final PsiLanguageInjectionHost declarationContainer = injector.getInjectionHost(declaration);
    final XmlTagChild declarationTag = PsiTreeUtil.getNonStrictParentOfType(declarationContainer, XmlTag.class, XmlText.class);
    if (declarationContainer != null && elementContainer != null && elementTag != null && declarationTag != null) {
        return PsiTreeUtil.isAncestor(declarationTag, elementTag, true) || (PsiTreeUtil.isAncestor(declarationTag, elementTag, false) && declarationContainer.getTextOffset() < elementContainer.getTextOffset()) || isInRepeatStartEnd(declarationTag, declarationContainer, elementContainer);
    }
    return true;
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) PsiLanguageInjectionHost(com.intellij.psi.PsiLanguageInjectionHost) JSImplicitElement(com.intellij.lang.javascript.psi.stubs.JSImplicitElement)

Example 27 with InjectedLanguageManager

use of com.intellij.lang.injection.InjectedLanguageManager in project intellij-community by JetBrains.

the class LocalInspectionTool method processFile.

@NotNull
public List<ProblemDescriptor> processFile(@NotNull PsiFile file, @NotNull InspectionManager manager) {
    final ProblemsHolder holder = new ProblemsHolder(manager, file, false);
    LocalInspectionToolSession session = new LocalInspectionToolSession(file, 0, file.getTextLength());
    final PsiElementVisitor customVisitor = buildVisitor(holder, false, session);
    LOG.assertTrue(!(customVisitor instanceof PsiRecursiveElementVisitor), "The visitor returned from LocalInspectionTool.buildVisitor() must not be recursive");
    inspectionStarted(session, false);
    final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(holder.getProject());
    file.accept(new PsiRecursiveElementWalkingVisitor() {

        @Override
        public void visitElement(PsiElement element) {
            element.accept(customVisitor);
            processInjectedFile(element);
            super.visitElement(element);
        }

        private void processInjectedFile(PsiElement element) {
            if (element instanceof PsiLanguageInjectionHost) {
                final List<Pair<PsiElement, TextRange>> files = injectedLanguageManager.getInjectedPsiFiles(element);
                if (files != null) {
                    for (Pair<PsiElement, TextRange> pair : files) {
                        pair.first.accept(new PsiRecursiveElementWalkingVisitor() {

                            @Override
                            public void visitElement(PsiElement injectedElement) {
                                injectedElement.accept(customVisitor);
                                super.visitElement(injectedElement);
                            }
                        });
                    }
                }
            }
        }
    });
    inspectionFinished(session, holder);
    return holder.getResults();
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) List(java.util.List) TextRange(com.intellij.openapi.util.TextRange) Pair(com.intellij.openapi.util.Pair) NotNull(org.jetbrains.annotations.NotNull)

Example 28 with InjectedLanguageManager

use of com.intellij.lang.injection.InjectedLanguageManager in project intellij-community by JetBrains.

the class BackspaceHandler method isOffsetInsideInjected.

private static boolean isOffsetInsideInjected(Editor injectedEditor, int injectedOffset) {
    if (injectedOffset == 0 || injectedOffset >= injectedEditor.getDocument().getTextLength()) {
        return false;
    }
    PsiFile injectedFile = ((EditorWindow) injectedEditor).getInjectedFile();
    InjectedLanguageManager ilm = InjectedLanguageManager.getInstance(injectedFile.getProject());
    TextRange rangeToEdit = new TextRange(injectedOffset - 1, injectedOffset + 1);
    List<TextRange> editables = ilm.intersectWithAllEditableFragments(injectedFile, rangeToEdit);
    return editables.size() == 1 && editables.get(0).equals(rangeToEdit);
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) PsiFile(com.intellij.psi.PsiFile) TextRange(com.intellij.openapi.util.TextRange) EditorWindow(com.intellij.injected.editor.EditorWindow)

Example 29 with InjectedLanguageManager

use of com.intellij.lang.injection.InjectedLanguageManager in project intellij-community by JetBrains.

the class IntroduceVariableBase method getSelectedExpression.

/**
   * @return can return NotNull value although extraction will fail: reason could be retrieved from {@link #getErrorMessage(PsiExpression)}
   */
public static PsiExpression getSelectedExpression(final Project project, PsiFile file, int startOffset, int endOffset) {
    final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(project);
    PsiElement elementAtStart = file.findElementAt(startOffset);
    if (elementAtStart == null || elementAtStart instanceof PsiWhiteSpace || elementAtStart instanceof PsiComment) {
        final PsiElement element = PsiTreeUtil.skipSiblingsForward(elementAtStart, PsiWhiteSpace.class, PsiComment.class);
        if (element != null) {
            startOffset = element.getTextOffset();
            elementAtStart = file.findElementAt(startOffset);
        }
        if (elementAtStart == null) {
            if (injectedLanguageManager.isInjectedFragment(file)) {
                return getSelectionFromInjectedHost(project, file, injectedLanguageManager, startOffset, endOffset);
            } else {
                return null;
            }
        }
        startOffset = elementAtStart.getTextOffset();
    }
    PsiElement elementAtEnd = file.findElementAt(endOffset - 1);
    if (elementAtEnd == null || elementAtEnd instanceof PsiWhiteSpace || elementAtEnd instanceof PsiComment) {
        elementAtEnd = PsiTreeUtil.skipSiblingsBackward(elementAtEnd, PsiWhiteSpace.class, PsiComment.class);
        if (elementAtEnd == null)
            return null;
        endOffset = elementAtEnd.getTextRange().getEndOffset();
    }
    if (endOffset <= startOffset)
        return null;
    PsiElement elementAt = PsiTreeUtil.findCommonParent(elementAtStart, elementAtEnd);
    final PsiExpression containingExpression = PsiTreeUtil.getParentOfType(elementAt, PsiExpression.class, false);
    if (containingExpression != null && containingExpression == elementAtEnd && startOffset == containingExpression.getTextOffset()) {
        return containingExpression;
    }
    if (containingExpression == null || containingExpression instanceof PsiLambdaExpression) {
        if (injectedLanguageManager.isInjectedFragment(file)) {
            return getSelectionFromInjectedHost(project, file, injectedLanguageManager, startOffset, endOffset);
        }
        elementAt = null;
    }
    final PsiLiteralExpression literalExpression = PsiTreeUtil.getParentOfType(elementAt, PsiLiteralExpression.class);
    final PsiLiteralExpression startLiteralExpression = PsiTreeUtil.getParentOfType(elementAtStart, PsiLiteralExpression.class);
    final PsiLiteralExpression endLiteralExpression = PsiTreeUtil.getParentOfType(file.findElementAt(endOffset), PsiLiteralExpression.class);
    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
    String text = null;
    PsiExpression tempExpr;
    try {
        text = file.getText().subSequence(startOffset, endOffset).toString();
        String prefix = null;
        if (startLiteralExpression != null) {
            final int startExpressionOffset = startLiteralExpression.getTextOffset();
            if (startOffset == startExpressionOffset + 1) {
                text = "\"" + text;
            } else if (startOffset > startExpressionOffset + 1) {
                prefix = "\" + ";
                text = "\"" + text;
            }
        }
        String suffix = null;
        if (endLiteralExpression != null) {
            final int endExpressionOffset = endLiteralExpression.getTextOffset() + endLiteralExpression.getTextLength();
            if (endOffset == endExpressionOffset - 1) {
                text += "\"";
            } else if (endOffset < endExpressionOffset - 1) {
                suffix = " + \"";
                text += "\"";
            }
        }
        if (literalExpression != null && text.equals(literalExpression.getText()))
            return literalExpression;
        final PsiElement parent = literalExpression != null ? literalExpression : elementAt;
        tempExpr = elementFactory.createExpressionFromText(text, parent);
        final boolean[] hasErrors = new boolean[1];
        final JavaRecursiveElementWalkingVisitor errorsVisitor = new JavaRecursiveElementWalkingVisitor() {

            @Override
            public void visitElement(final PsiElement element) {
                if (hasErrors[0]) {
                    return;
                }
                super.visitElement(element);
            }

            @Override
            public void visitErrorElement(final PsiErrorElement element) {
                hasErrors[0] = true;
            }
        };
        tempExpr.accept(errorsVisitor);
        if (hasErrors[0])
            return null;
        tempExpr.putUserData(ElementToWorkOn.PREFIX, prefix);
        tempExpr.putUserData(ElementToWorkOn.SUFFIX, suffix);
        final RangeMarker rangeMarker = FileDocumentManager.getInstance().getDocument(file.getVirtualFile()).createRangeMarker(startOffset, endOffset);
        tempExpr.putUserData(ElementToWorkOn.TEXT_RANGE, rangeMarker);
        if (parent != null) {
            tempExpr.putUserData(ElementToWorkOn.PARENT, parent);
        } else {
            PsiErrorElement errorElement = elementAtStart instanceof PsiErrorElement ? (PsiErrorElement) elementAtStart : PsiTreeUtil.getNextSiblingOfType(elementAtStart, PsiErrorElement.class);
            if (errorElement == null) {
                errorElement = PsiTreeUtil.getParentOfType(elementAtStart, PsiErrorElement.class);
            }
            if (errorElement == null)
                return null;
            if (!(errorElement.getParent() instanceof PsiClass))
                return null;
            tempExpr.putUserData(ElementToWorkOn.PARENT, errorElement);
            tempExpr.putUserData(ElementToWorkOn.OUT_OF_CODE_BLOCK, Boolean.TRUE);
        }
        final String fakeInitializer = "intellijidearulezzz";
        final int[] refIdx = new int[1];
        final PsiElement toBeExpression = createReplacement(fakeInitializer, project, prefix, suffix, parent, rangeMarker, refIdx);
        toBeExpression.accept(errorsVisitor);
        if (hasErrors[0])
            return null;
        if (literalExpression != null && toBeExpression instanceof PsiExpression) {
            PsiType type = ((PsiExpression) toBeExpression).getType();
            if (type != null && !type.equals(literalExpression.getType())) {
                return null;
            }
        }
        final PsiReferenceExpression refExpr = PsiTreeUtil.getParentOfType(toBeExpression.findElementAt(refIdx[0]), PsiReferenceExpression.class);
        if (refExpr == null)
            return null;
        if (toBeExpression == refExpr && refIdx[0] > 0) {
            return null;
        }
        if (ReplaceExpressionUtil.isNeedParenthesis(refExpr.getNode(), tempExpr.getNode())) {
            tempExpr.putCopyableUserData(NEED_PARENTHESIS, Boolean.TRUE);
            return tempExpr;
        }
    } catch (IncorrectOperationException e) {
        if (elementAt instanceof PsiExpressionList) {
            final PsiElement parent = elementAt.getParent();
            return parent instanceof PsiCallExpression ? createArrayCreationExpression(text, startOffset, endOffset, (PsiCallExpression) parent) : null;
        }
        return null;
    }
    return tempExpr;
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager) IncorrectOperationException(com.intellij.util.IncorrectOperationException)

Example 30 with InjectedLanguageManager

use of com.intellij.lang.injection.InjectedLanguageManager in project intellij-community by JetBrains.

the class GroovyAnnotator method checkStringLiteral.

private void checkStringLiteral(PsiElement literal) {
    InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(literal.getProject());
    String text;
    if (injectedLanguageManager.isInjectedFragment(literal.getContainingFile())) {
        text = injectedLanguageManager.getUnescapedText(literal);
    } else {
        text = literal.getText();
    }
    assert text != null;
    StringBuilder builder = new StringBuilder(text.length());
    String quote = GrStringUtil.getStartQuote(text);
    if (quote.isEmpty())
        return;
    String substring = text.substring(quote.length());
    if (!GrStringUtil.parseStringCharacters(substring, new StringBuilder(text.length()), null)) {
        myHolder.createErrorAnnotation(literal, GroovyBundle.message("illegal.escape.character.in.string.literal"));
        return;
    }
    int[] offsets = new int[substring.length() + 1];
    boolean result = GrStringUtil.parseStringCharacters(substring, builder, offsets);
    LOG.assertTrue(result);
    if (!builder.toString().endsWith(quote) || substring.charAt(offsets[builder.length() - quote.length()]) == '\\') {
        myHolder.createErrorAnnotation(literal, GroovyBundle.message("string.end.expected"));
    }
}
Also used : InjectedLanguageManager(com.intellij.lang.injection.InjectedLanguageManager)

Aggregations

InjectedLanguageManager (com.intellij.lang.injection.InjectedLanguageManager)41 TextRange (com.intellij.openapi.util.TextRange)12 PsiElement (com.intellij.psi.PsiElement)12 PsiFile (com.intellij.psi.PsiFile)11 PsiLanguageInjectionHost (com.intellij.psi.PsiLanguageInjectionHost)10 Pair (com.intellij.openapi.util.Pair)7 Nullable (org.jetbrains.annotations.Nullable)7 Document (com.intellij.openapi.editor.Document)5 Project (com.intellij.openapi.project.Project)5 DocumentWindow (com.intellij.injected.editor.DocumentWindow)4 NotNull (org.jetbrains.annotations.NotNull)4 ASTNode (com.intellij.lang.ASTNode)2 TextAttributes (com.intellij.openapi.editor.markup.TextAttributes)2 IncorrectOperationException (com.intellij.util.IncorrectOperationException)2 ScopeOwner (com.jetbrains.python.codeInsight.controlflow.ScopeOwner)2 THashMap (gnu.trove.THashMap)2 THashSet (gnu.trove.THashSet)2 ConcurrentMap (java.util.concurrent.ConcurrentMap)2 HighlightInfoHolder (com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder)1 TemplateBuilder (com.intellij.codeInsight.template.TemplateBuilder)1