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;
}
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;
}
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()]);
}
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();
}
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;
}
Aggregations