Search in sources :

Example 61 with SmartList

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

the class SurroundAutoCloseableAction method moveStatements.

private static List<PsiElement> moveStatements(PsiElement last, PsiTryStatement statement) {
    PsiCodeBlock tryBlock = statement.getTryBlock();
    assert tryBlock != null : statement.getText();
    PsiElement parent = statement.getParent();
    LocalSearchScope scope = new LocalSearchScope(parent);
    List<PsiElement> toFormat = new SmartList<>();
    PsiElement stopAt = last.getNextSibling();
    PsiElement i = statement.getNextSibling();
    while (i != null && i != stopAt) {
        PsiElement child = i;
        i = PsiTreeUtil.skipSiblingsForward(i, PsiWhiteSpace.class, PsiComment.class);
        if (!(child instanceof PsiDeclarationStatement))
            continue;
        PsiElement anchor = child;
        for (PsiElement declared : ((PsiDeclarationStatement) child).getDeclaredElements()) {
            if (!(declared instanceof PsiLocalVariable))
                continue;
            int endOffset = last.getTextRange().getEndOffset();
            boolean contained = ReferencesSearch.search(declared, scope).forEach(ref -> ref.getElement().getTextOffset() <= endOffset);
            if (!contained) {
                PsiLocalVariable var = (PsiLocalVariable) declared;
                PsiElementFactory factory = JavaPsiFacade.getElementFactory(statement.getProject());
                String name = var.getName();
                assert name != null : child.getText();
                toFormat.add(parent.addBefore(factory.createVariableDeclarationStatement(name, var.getType(), null), statement));
                PsiExpression varInit = var.getInitializer();
                if (varInit != null) {
                    String varAssignText = name + " = " + varInit.getText() + ";";
                    anchor = parent.addAfter(factory.createStatementFromText(varAssignText, parent), anchor);
                }
                var.delete();
            }
        }
        if (child == last && !child.isValid()) {
            last = anchor;
        }
    }
    PsiElement first = statement.getNextSibling();
    tryBlock.addRangeBefore(first, last, tryBlock.getRBrace());
    parent.deleteChildRange(first, last);
    return toFormat;
}
Also used : LocalSearchScope(com.intellij.psi.search.LocalSearchScope) SmartList(com.intellij.util.SmartList)

Example 62 with SmartList

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

the class PsiNewExpressionImpl method doGetType.

@Nullable
private PsiType doGetType(@Nullable PsiAnnotation stopAt) {
    PsiType type = null;
    SmartList<PsiAnnotation> annotations = new SmartList<>();
    boolean stop = false;
    for (ASTNode child = getFirstChildNode(); child != null; child = child.getTreeNext()) {
        IElementType elementType = child.getElementType();
        if (elementType == JavaElementType.ANNOTATION) {
            PsiAnnotation annotation = (PsiAnnotation) child.getPsi();
            annotations.add(annotation);
            if (annotation == stopAt)
                stop = true;
        } else if (elementType == JavaElementType.JAVA_CODE_REFERENCE) {
            assert type == null : this;
            type = new PsiClassReferenceType((PsiJavaCodeReferenceElement) child.getPsi(), null);
            if (stop)
                return type;
        } else if (ElementType.PRIMITIVE_TYPE_BIT_SET.contains(elementType)) {
            assert type == null : this;
            PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
            PsiAnnotation[] copy = ContainerUtil.copyAndClear(annotations, PsiAnnotation.ARRAY_FACTORY, true);
            type = factory.createPrimitiveTypeFromText(child.getText()).annotate(TypeAnnotationProvider.Static.create(copy));
            if (stop)
                return type;
        } else if (elementType == JavaTokenType.LBRACKET) {
            assert type != null : this;
            PsiAnnotation[] copy = ContainerUtil.copyAndClear(annotations, PsiAnnotation.ARRAY_FACTORY, true);
            type = type.createArrayType().annotate(TypeAnnotationProvider.Static.create(copy));
            if (stop)
                return type;
        } else if (elementType == JavaElementType.ANONYMOUS_CLASS) {
            PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
            PsiClass aClass = (PsiClass) child.getPsi();
            PsiSubstitutor substitutor = aClass instanceof PsiTypeParameter ? PsiSubstitutor.EMPTY : factory.createRawSubstitutor(aClass);
            PsiAnnotation[] copy = ContainerUtil.copyAndClear(annotations, PsiAnnotation.ARRAY_FACTORY, true);
            type = factory.createType(aClass, substitutor, PsiUtil.getLanguageLevel(aClass)).annotate(TypeAnnotationProvider.Static.create(copy));
            if (stop)
                return type;
        }
    }
    // stop == true means annotation is misplaced
    return stop ? null : type;
}
Also used : PsiClassReferenceType(com.intellij.psi.impl.source.PsiClassReferenceType) IElementType(com.intellij.psi.tree.IElementType) ASTNode(com.intellij.lang.ASTNode) SmartList(com.intellij.util.SmartList) Nullable(org.jetbrains.annotations.Nullable)

Example 63 with SmartList

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

the class DuplicatesInspectionBase method checkFile.

@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull final PsiFile psiFile, @NotNull final InspectionManager manager, final boolean isOnTheFly) {
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (!(virtualFile instanceof VirtualFileWithId) || /*!isOnTheFly || */
    !DuplicatesIndex.ourEnabled)
        return ProblemDescriptor.EMPTY_ARRAY;
    final DuplicatesProfile profile = DuplicatesIndex.findDuplicatesProfile(psiFile.getFileType());
    if (profile == null)
        return ProblemDescriptor.EMPTY_ARRAY;
    final Ref<DuplicatedCodeProcessor> myProcessorRef = new Ref<>();
    final FileASTNode node = psiFile.getNode();
    boolean usingLightProfile = profile instanceof LightDuplicateProfile && node.getElementType() instanceof ILightStubFileElementType && DuplicatesIndex.ourEnabledLightProfiles;
    if (usingLightProfile) {
        LighterAST ast = node.getLighterAST();
        ((LightDuplicateProfile) profile).process(ast, new LightDuplicateProfile.Callback() {

            DuplicatedCodeProcessor<LighterASTNode> myProcessor;

            @Override
            public void process(int hash, int hash2, @NotNull final LighterAST ast, @NotNull final LighterASTNode... nodes) {
                class LightDuplicatedCodeProcessor extends DuplicatedCodeProcessor<LighterASTNode> {

                    private LightDuplicatedCodeProcessor(VirtualFile file, Project project) {
                        super(file, project, myFilterOutGeneratedCode);
                    }

                    @Override
                    protected TextRange getRangeInElement(LighterASTNode node) {
                        return null;
                    }

                    @Override
                    protected PsiElement getPsi(LighterASTNode node) {
                        return ((TreeBackedLighterAST) ast).unwrap(node).getPsi();
                    }

                    @Override
                    protected int getStartOffset(LighterASTNode node) {
                        return node.getStartOffset();
                    }

                    @Override
                    protected int getEndOffset(LighterASTNode node) {
                        return node.getEndOffset();
                    }

                    @Override
                    protected boolean isLightProfile() {
                        return true;
                    }
                }
                if (myProcessor == null) {
                    myProcessor = new LightDuplicatedCodeProcessor(virtualFile, psiFile.getProject());
                    myProcessorRef.set(myProcessor);
                }
                myProcessor.process(hash, hash2, nodes[0]);
            }
        });
    } else {
        final DuplocatorState state = profile.getDuplocatorState(psiFile.getLanguage());
        profile.createVisitor(new FragmentsCollector() {

            DuplicatedCodeProcessor<PsiFragment> myProcessor;

            @Override
            public void add(int hash, final int cost, @Nullable final PsiFragment frag) {
                if (!DuplicatesIndex.isIndexedFragment(frag, cost, profile, state)) {
                    return;
                }
                class OldDuplicatedCodeProcessor extends DuplicatedCodeProcessor<PsiFragment> {

                    private OldDuplicatedCodeProcessor(VirtualFile file, Project project) {
                        super(file, project, myFilterOutGeneratedCode);
                    }

                    @Override
                    protected TextRange getRangeInElement(PsiFragment node) {
                        PsiElement[] elements = node.getElements();
                        TextRange rangeInElement = null;
                        if (elements.length > 1) {
                            PsiElement lastElement = elements[elements.length - 1];
                            rangeInElement = new TextRange(elements[0].getStartOffsetInParent(), lastElement.getStartOffsetInParent() + lastElement.getTextLength());
                        }
                        return rangeInElement;
                    }

                    @Override
                    protected PsiElement getPsi(PsiFragment node) {
                        PsiElement[] elements = node.getElements();
                        return elements.length > 1 ? elements[0].getParent() : elements[0];
                    }

                    @Override
                    protected int getStartOffset(PsiFragment node) {
                        return node.getStartOffset();
                    }

                    @Override
                    protected int getEndOffset(PsiFragment node) {
                        return node.getEndOffset();
                    }

                    @Override
                    protected boolean isLightProfile() {
                        return false;
                    }
                }
                if (myProcessor == null) {
                    myProcessor = new OldDuplicatedCodeProcessor(virtualFile, psiFile.getProject());
                    myProcessorRef.set(myProcessor);
                }
                myProcessor.process(hash, 0, frag);
            }
        }, true).visitNode(psiFile);
    }
    DuplicatedCodeProcessor<?> processor = myProcessorRef.get();
    final SmartList<ProblemDescriptor> descriptors = new SmartList<>();
    if (processor != null) {
        final VirtualFile baseDir = psiFile.getProject().getBaseDir();
        for (Map.Entry<Integer, TextRange> entry : processor.reportedRanges.entrySet()) {
            final Integer offset = entry.getKey();
            if (!usingLightProfile && processor.fragmentSize.get(offset) < MIN_FRAGMENT_SIZE)
                continue;
            final VirtualFile file = processor.reportedFiles.get(offset);
            String path = null;
            if (file.equals(virtualFile))
                path = "this file";
            else if (baseDir != null) {
                path = VfsUtilCore.getRelativePath(file, baseDir);
            }
            if (path == null) {
                path = file.getPath();
            }
            String message = "Found duplicated code in " + path;
            PsiElement targetElement = processor.reportedPsi.get(offset);
            TextRange rangeInElement = entry.getValue();
            final int offsetInOtherFile = processor.reportedOffsetInOtherFiles.get(offset);
            LocalQuickFix fix = createNavigateToDupeFix(file, offsetInOtherFile);
            long hash = processor.fragmentHash.get(offset);
            LocalQuickFix viewAllDupesFix = hash != 0 ? createShowOtherDupesFix(virtualFile, offset, (int) hash, (int) (hash >> 32), psiFile.getProject()) : null;
            ProblemDescriptor descriptor = manager.createProblemDescriptor(targetElement, rangeInElement, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, fix, viewAllDupesFix);
            descriptors.add(descriptor);
        }
    }
    return descriptors.isEmpty() ? null : descriptors.toArray(new ProblemDescriptor[descriptors.size()]);
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) DuplicatesProfile(com.intellij.dupLocator.DuplicatesProfile) ILightStubFileElementType(com.intellij.psi.tree.ILightStubFileElementType) FileASTNode(com.intellij.lang.FileASTNode) PsiFragment(com.intellij.dupLocator.util.PsiFragment) FragmentsCollector(com.intellij.dupLocator.treeHash.FragmentsCollector) VirtualFileWithId(com.intellij.openapi.vfs.VirtualFileWithId) LightDuplicateProfile(com.intellij.dupLocator.LightDuplicateProfile) PsiElement(com.intellij.psi.PsiElement) LighterASTNode(com.intellij.lang.LighterASTNode) TreeBackedLighterAST(com.intellij.lang.TreeBackedLighterAST) LighterAST(com.intellij.lang.LighterAST) TextRange(com.intellij.openapi.util.TextRange) DuplocatorState(com.intellij.dupLocator.DuplocatorState) Project(com.intellij.openapi.project.Project) Ref(com.intellij.openapi.util.Ref) TreeBackedLighterAST(com.intellij.lang.TreeBackedLighterAST) SmartList(com.intellij.util.SmartList) TIntLongHashMap(gnu.trove.TIntLongHashMap) Map(java.util.Map) TIntObjectHashMap(gnu.trove.TIntObjectHashMap) TIntIntHashMap(gnu.trove.TIntIntHashMap) TreeMap(java.util.TreeMap) SortedMap(java.util.SortedMap) Nullable(org.jetbrains.annotations.Nullable) Nullable(org.jetbrains.annotations.Nullable)

Example 64 with SmartList

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

the class IndexingStamp method getNontrivialFileIndexedStates.

@NotNull
public static List<ID<?, ?>> getNontrivialFileIndexedStates(int fileId) {
    if (fileId != INVALID_FILE_ID) {
        Lock readLock = getStripedLock(fileId).readLock();
        readLock.lock();
        try {
            Timestamps stamp = createOrGetTimeStamp(fileId);
            if (stamp != null && stamp.myIndexStamps != null && !stamp.myIndexStamps.isEmpty()) {
                final SmartList<ID<?, ?>> retained = new SmartList<>();
                stamp.myIndexStamps.forEach(new TObjectProcedure<ID<?, ?>>() {

                    @Override
                    public boolean execute(ID<?, ?> object) {
                        retained.add(object);
                        return true;
                    }
                });
                return retained;
            }
        } catch (InvalidVirtualFileAccessException ignored) /*ok to ignore it here*/
        {
        } finally {
            readLock.unlock();
        }
    }
    return Collections.emptyList();
}
Also used : SmartList(com.intellij.util.SmartList) InvalidVirtualFileAccessException(com.intellij.openapi.vfs.InvalidVirtualFileAccessException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) Lock(java.util.concurrent.locks.Lock) NotNull(org.jetbrains.annotations.NotNull)

Example 65 with SmartList

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

the class SnapshotInputMappings method savePersistentData.

private boolean savePersistentData(Map<Key, Value> data, int id, boolean delayedReading) {
    try {
        if (delayedReading && myContents.containsMapping(id))
            return false;
        BufferExposingByteArrayOutputStream out = new BufferExposingByteArrayOutputStream(ourSpareByteArray.getBuffer(4 * data.size()));
        DataOutputStream stream = new DataOutputStream(out);
        int size = data.size();
        DataInputOutputUtil.writeINT(stream, size);
        if (size > 0) {
            THashMap<Value, List<Key>> values = new THashMap<>();
            List<Key> keysForNullValue = null;
            for (Map.Entry<Key, Value> e : data.entrySet()) {
                Value value = e.getValue();
                List<Key> keys = value != null ? values.get(value) : keysForNullValue;
                if (keys == null) {
                    if (value != null)
                        values.put(value, keys = new SmartList<>());
                    else
                        keys = keysForNullValue = new SmartList<>();
                }
                keys.add(e.getKey());
            }
            if (keysForNullValue != null) {
                myValueExternalizer.save(stream, null);
                mySnapshotIndexExternalizer.save(stream, keysForNullValue);
            }
            for (Value value : values.keySet()) {
                myValueExternalizer.save(stream, value);
                mySnapshotIndexExternalizer.save(stream, values.get(value));
            }
        }
        saveContents(id, out);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return true;
}
Also used : BufferExposingByteArrayOutputStream(com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream) DataOutputStream(com.intellij.util.io.DataOutputStream) THashMap(gnu.trove.THashMap) SmartList(com.intellij.util.SmartList) THashMap(gnu.trove.THashMap)

Aggregations

SmartList (com.intellij.util.SmartList)163 NotNull (org.jetbrains.annotations.NotNull)70 Nullable (org.jetbrains.annotations.Nullable)25 VirtualFile (com.intellij.openapi.vfs.VirtualFile)24 Module (com.intellij.openapi.module.Module)15 Project (com.intellij.openapi.project.Project)14 TextRange (com.intellij.openapi.util.TextRange)12 PsiElement (com.intellij.psi.PsiElement)12 List (java.util.List)12 Element (org.jdom.Element)12 File (java.io.File)11 THashSet (gnu.trove.THashSet)9 ContainerUtil (com.intellij.util.containers.ContainerUtil)8 ArrayList (java.util.ArrayList)8 Collection (java.util.Collection)8 Pair (com.intellij.openapi.util.Pair)7 PsiFile (com.intellij.psi.PsiFile)6 IOException (java.io.IOException)6 PropertiesFile (com.intellij.lang.properties.psi.PropertiesFile)5 IElementType (com.intellij.psi.tree.IElementType)5