cleanup: fix some embarrassing "expression is always true" warnings

GitOrigin-RevId: 7924e9541bb3e0fe2d328a7624401effba8d4b0a
This commit is contained in:
Alexey Kudravtsev
2020-10-18 12:50:24 +00:00
committed by intellij-monorepo-bot
parent 94368a5895
commit 016f2aef5b
249 changed files with 535 additions and 811 deletions
@@ -152,8 +152,8 @@ public final class ArtifactUtil {
if (processor.shouldProcessSubstitution(complexElement)) {
final List<? extends PackagingElement<?>> substitution = complexElement.getSubstitution(resolvingContext, artifactType);
if (substitution != null) {
return processElementsRecursively(substitution, type, processor, resolvingContext, processSubstitutions, artifactType,
path.appendComplex(complexElement), processed);
return processElementsRecursively(substitution, type, processor, resolvingContext, true, artifactType,
path.appendComplex(complexElement), processed);
}
}
}
@@ -541,11 +541,6 @@ public final class ArtifactUtil {
element.removeChildren(toRemove);
}
public static boolean shouldClearArtifactOutputBeforeRebuild(Artifact artifact) {
final String outputPath = artifact.getOutputPath();
return !StringUtil.isEmpty(outputPath) && artifact.getRootElement() instanceof ArtifactRootElement<?>;
}
public static Set<Module> getModulesIncludedInArtifacts(final @NotNull Collection<? extends Artifact> artifacts, final @NotNull Project project) {
final Set<Module> modules = new HashSet<>();
final PackagingElementResolvingContext resolvingContext = ArtifactManager.getInstance(project).getResolvingContext();
@@ -44,7 +44,7 @@ public class CompilerPaths {
/**
* @return a root directory where compiler caches for the given project are stored
*/
public static File getCacheStoreDirectory(final Project project) {
public static @NotNull File getCacheStoreDirectory(final Project project) {
return new File(getCompilerSystemDirectory(project), ".caches");
}
@@ -157,10 +157,7 @@ public final class ExcludedEntriesConfigurable implements UnnamedConfigurable, N
}
private void addPath(FileChooserDescriptor descriptor) {
int selected = -1 /*myExcludedTable.getSelectedRow() + 1*/;
if(selected < 0) {
selected = myExcludeEntryDescriptions.size();
}
int selected = myExcludeEntryDescriptions.size();
int savedSelected = selected;
VirtualFile[] chosen = FileChooser.chooseFiles(descriptor, myProject, null);
for (final VirtualFile chosenFile : chosen) {
@@ -24,7 +24,6 @@ import com.intellij.xdebugger.impl.XDebugSessionImpl;
import com.sun.jdi.Location;
import com.sun.jdi.request.StepRequest;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
public class StepOutOfBlockAction extends DebuggerAction implements DumbAware {
@@ -88,9 +87,8 @@ public class StepOutOfBlockAction extends DebuggerAction implements DumbAware {
return false;
}
@Nullable
@Override
public Range<Integer> getCallingExpressionLines() {
public @NotNull Range<Integer> getCallingExpressionLines() {
return myLines;
}
}
@@ -60,30 +60,28 @@ final class ExecuteJShellAction extends AnAction{
final Sdk sdk = config != null ? config.getRuntimeSdk() : null;
handler = JShellHandler.create(project, vFile, module, sdk);
}
if (handler != null) {
handler.toFront();
boolean hasDataToEvaluate = false;
handler.toFront();
boolean hasDataToEvaluate = false;
final Document document = editor.getDocument();
final TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor);
if (selectedRange.isEmpty()) {
final PsiElement snippet = getSnippetFromContext(project, e);
if (snippet instanceof PsiJShellFile) {
for (PsiElement element : ((PsiJShellFile)snippet).getExecutableSnippets()) {
hasDataToEvaluate |= scheduleEval(handler, element.getText());
}
}
else if (snippet != null){
hasDataToEvaluate = scheduleEval(handler, snippet.getText());
final Document document = editor.getDocument();
final TextRange selectedRange = EditorUtil.getSelectionInAnyMode(editor);
if (selectedRange.isEmpty()) {
final PsiElement snippet = getSnippetFromContext(project, e);
if (snippet instanceof PsiJShellFile) {
for (PsiElement element : ((PsiJShellFile)snippet).getExecutableSnippets()) {
hasDataToEvaluate |= scheduleEval(handler, element.getText());
}
}
else {
hasDataToEvaluate = scheduleEval(handler, document.getText(selectedRange));
}
if (!hasDataToEvaluate) {
JShellDiagnostic.notifyInfo(JavaCompilerBundle.message("jshell.nothing.to.execute"), project);
else if (snippet != null){
hasDataToEvaluate = scheduleEval(handler, snippet.getText());
}
}
else {
hasDataToEvaluate = scheduleEval(handler, document.getText(selectedRange));
}
if (!hasDataToEvaluate) {
JShellDiagnostic.notifyInfo(JavaCompilerBundle.message("jshell.nothing.to.execute"), project);
}
}
catch (Exception ex) {
Logger.getInstance(ExecuteJShellAction.class).warn(ex);
@@ -100,7 +98,7 @@ final class ExecuteJShellAction extends AnAction{
}
@Nullable
private PsiElement getSnippetFromContext(Project project, AnActionEvent e) {
private static PsiElement getSnippetFromContext(Project project, @NotNull AnActionEvent e) {
final Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor != null) {
final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
@@ -141,10 +141,10 @@ public final class JShellHandler {
return contentFile != null? contentFile.getUserData(MARKER_KEY) : null;
}
public static JShellHandler create(@NotNull final Project project,
@NotNull final VirtualFile contentFile,
@Nullable Module module,
@Nullable Sdk alternateSdk) throws Exception{
public static @NotNull JShellHandler create(@NotNull final Project project,
@NotNull final VirtualFile contentFile,
@Nullable Module module,
@Nullable Sdk alternateSdk) throws Exception{
final OSProcessHandler processHandler = launchProcess(project, module, alternateSdk);
final String title = JShellDiagnostic.TITLE + " " + contentFile.getNameWithoutExtension();
@@ -344,7 +344,7 @@ public final class JShellHandler {
finally {
renderResponse(request, response, stdOut.toString());
}
return response;
return null;
}
private void renderResponse(Request request, @Nullable Response response, String stdOut) {
@@ -62,9 +62,6 @@ public class ConfigFileFactoryImpl extends ConfigFileFactory {
private static String getText(final String templateName, @Nullable Project project) throws IOException {
final FileTemplateManager templateManager = project == null ? FileTemplateManager.getDefaultInstance() : FileTemplateManager.getInstance(project);
final FileTemplate template = templateManager.getJ2eeTemplate(templateName);
if (template == null) {
return "";
}
return template.getText(templateManager.getDefaultProperties());
}
@@ -11,7 +11,6 @@ import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class CastMethodArgumentFix extends MethodArgumentFix implements HighPriorityAction {
private final @IntentionName String myText;
@@ -68,7 +67,7 @@ public final class CastMethodArgumentFix extends MethodArgumentFix implements Hi
}
@Override
public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
public @NotNull FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
return new CastMethodArgumentFix(PsiTreeUtil.findSameElementInCopy(myArgList, target), myIndex, myToType,
myArgumentFixerActionFactory);
}
@@ -201,7 +201,7 @@ public final class ChangeNewOperatorTypeFix implements IntentionAction {
}
@Override
public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
public @NotNull FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
return new ChangeNewOperatorTypeFix(myType, PsiTreeUtil.findSameElementInCopy(myExpression, target));
}
}
@@ -409,12 +409,12 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen
return myAddNonJavaEntries;
}
public void addAllPersistentEntries(EntryPointsManagerBase manager) {
public void addAllPersistentEntries(@NotNull EntryPointsManagerBase manager) {
myPersistentEntryPoints.putAll(manager.myPersistentEntryPoints);
myPatterns.addAll(manager.getPatterns());
}
static void convert(Element element, final Map<? super String, ? super SmartRefElementPointer> persistentEntryPoints) {
static void convert(@NotNull Element element, final Map<? super String, ? super SmartRefElementPointer> persistentEntryPoints) {
List<Element> content = element.getChildren();
for (final Element entryElement : content) {
if (ENTRY_POINT_ATTR.equals(entryElement.getName())) {
@@ -559,7 +559,7 @@ public abstract class EntryPointsManagerBase extends EntryPointsManager implemen
private Pattern regexp;
private Pattern methodRegexp;
public ClassPattern(ClassPattern classPattern) {
public ClassPattern(@NotNull ClassPattern classPattern) {
hierarchically = classPattern.hierarchically;
pattern = classPattern.pattern;
method = classPattern.method;
@@ -729,8 +729,7 @@ public final class JavaReflectionReferenceUtil {
return getText(false, PsiNameHelper::getShortClassName);
}
@Nullable
public Icon getIcon() {
public @NotNull Icon getIcon() {
return myIcon != null ? myIcon : PlatformIcons.METHOD_ICON;
}
@@ -21,7 +21,7 @@ public final class ReturnStatementReturnValue implements ReturnValue {
}
@Override
@Nullable
@NotNull
public PsiStatement createReplacement(@NotNull final PsiMethod extractedMethod, @NotNull final PsiMethodCallExpression methodCallExpression,@Nullable PsiType returnType) throws IncorrectOperationException {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(methodCallExpression.getProject());
final CodeStyleManager styleManager = CodeStyleManager.getInstance(methodCallExpression.getProject());
@@ -642,7 +642,7 @@ public final class PsiAdapter {
public static String @NotNull [] getImplementsClassnames(PsiClass clazz) {
PsiClass[] interfaces = clazz.getInterfaces();
if (interfaces == null || interfaces.length == 0) {
if (interfaces.length == 0) {
return ArrayUtilRt.EMPTY_STRING_ARRAY;
}
@@ -77,9 +77,8 @@ public final class JavaConstructorCallElement extends LookupElementDecorator<Loo
return myConstructor;
}
@Nullable
@Override
public PsiElement getPsiElement() {
public @NotNull PsiElement getPsiElement() {
return myConstructor;
}
@@ -28,7 +28,6 @@ import com.intellij.psi.PsiModifier;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class AddMethodBodyFix implements IntentionAction {
private final PsiMethod myMethod;
@@ -76,7 +75,7 @@ public final class AddMethodBodyFix implements IntentionAction {
}
@Override
public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
public @NotNull FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
return new AddMethodBodyFix(PsiTreeUtil.findSameElementInCopy(myMethod, target));
}
}
@@ -100,7 +100,7 @@ public final class AddMissingRequiredAnnotationParametersFix implements Intentio
name = "value";
}
if (value == null) {
LOG.error(String.format("Invalid annotation parameter name = %s, value = %s", name, value));
LOG.error(String.format("Invalid annotation parameter name = %s, value = %s", name, null));
continue;
}
newParameters.add(Pair.create(name, value));
@@ -110,7 +110,6 @@ public final class BringVariableIntoScopeFix implements IntentionAction {
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiFile file) throws IncorrectOperationException {
PsiLocalVariable outOfScopeVariable = myOutOfScopeVariable;
LOG.assertTrue(outOfScopeVariable != null);
PsiManager manager = file.getManager();
outOfScopeVariable.normalizeDeclaration();
PsiUtil.setModifierProperty(outOfScopeVariable, PsiModifier.FINAL, false);
@@ -409,7 +409,6 @@ public class ChangeMethodSignatureFromUsageFix implements IntentionAction/*, Hig
}
else if (isArgumentInVarargPosition(expressions, ei, varargParam, substitutor)) {
if (pi == parameters.length - 1) {
assert varargParam != null;
final PsiType type = varargParam.getType();
result.add(ParameterInfoImpl.create(pi).withName(varargParam.getName()).withType(type));
buf.append(escapePresentableType(type));
@@ -16,8 +16,6 @@ import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static com.intellij.refactoring.changeSignature.ParameterInfo.NEW_PARAMETER;
public class ChangeMethodSignatureFromUsageReverseOrderFix extends ChangeMethodSignatureFromUsageFix {
public ChangeMethodSignatureFromUsageReverseOrderFix(@NotNull PsiMethod targetMethod,
PsiExpression @NotNull [] expressions,
@@ -80,7 +78,6 @@ public class ChangeMethodSignatureFromUsageReverseOrderFix extends ChangeMethodS
}
else if (isArgumentInVarargPosition(expressions, ei, varargParam, substitutor)) {
if (pi == parameters.length - 1) {
assert varargParam != null;
final PsiType type = varargParam.getType();
result.add(0, ParameterInfoImpl.create(pi).withName(varargParam.getName()).withType(type));
params.add(0, escapePresentableType(type));
@@ -133,7 +133,7 @@ public class CreateClassFromNewFix extends CreateFromUsageBaseFix {
}
templateBuilder.setEndVariableAfter(constructor.getBody().getLBrace());
return supConstructor;
return null;
}
private static void setupInheritance(PsiNewExpression element, PsiClass targetClass) throws IncorrectOperationException {
@@ -28,7 +28,6 @@ import com.intellij.psi.PsiMethod;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* @author ven
@@ -76,7 +75,7 @@ public final class DeleteMethodBodyFix implements IntentionAction {
}
@Override
public @Nullable FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
public @NotNull FileModifier getFileModifierForPreview(@NotNull PsiFile target) {
return new DeleteMethodBodyFix(PsiTreeUtil.findSameElementInCopy(myMethod, target));
}
}
@@ -66,10 +66,8 @@ public class LeaveCodeBlockEnterProcessor implements EnterProcessor {
EditorActionManager actionManager = EditorActionManager.getInstance();
EditorActionHandler actionHandler = actionManager.getActionHandler(IdeActions.ACTION_EDITOR_MOVE_LINE_END);
final DataContext dataContext = DataManager.getInstance().getDataContext(editor.getComponent());
if (dataContext != null) {
actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
return true;
}
actionHandler.execute(editor, editor.getCaretModel().getCurrentCaret(), dataContext);
return true;
}
}
@@ -89,7 +89,6 @@ public class PsiGenerationInfo<T extends PsiMember> extends GenerationInfoBase i
member = (T)existingMember;
if (!member.isValid()) {
LOG.error("invalid member: " + member +
" existing member: " + existingMember.isValid() +
" self modified list: " + modifierList +
" existing modified list: " + existingModifierList);
}
@@ -132,9 +132,8 @@ public class EqualsHashCodeTemplatesPanel extends NamedItemsListEditor<Couple<Te
final GenerateTemplateConfigurable equalsConfigurable = new GenerateTemplateConfigurable(item.first, GenerateEqualsHelper.getEqualsImplicitVars(myProject), myProject);
final GenerateTemplateConfigurable hashCodeConfigurable = new GenerateTemplateConfigurable(item.second, GenerateEqualsHelper.getHashCodeImplicitVars(), myProject);
return new UnnamedConfigurable() {
@Nullable
@Override
public JComponent createComponent() {
public @NotNull JComponent createComponent() {
final Splitter splitter = new Splitter(true);
final JPanel eqPanel = new JPanel(new BorderLayout());
@@ -148,7 +148,7 @@ public final class FinishMarker {
.map(val -> val instanceof PsiLiteralExpression ? ((PsiLiteralExpression)val).getValue() : NULL)
.toSet();
if (!mayNeedMarker) {
PsiExpression initValue = findBestExpression(terminalReturn, nonTerminalReturns, mayNeedMarker);
PsiExpression initValue = findBestExpression(terminalReturn, nonTerminalReturns, false);
if (initValue == null && nonTerminalReturnValues.size() == 1 && nonTerminalReturnValues.iterator().next() != NULL) {
initValue = nonTerminalReturns.iterator().next();
}
@@ -165,7 +165,7 @@ public final class FinishMarker {
}
}
if (PsiType.INT.equals(returnType) || PsiType.LONG.equals(returnType)) {
return getMarkerForIntegral(nonTerminalReturns, terminalReturn, mayNeedMarker, returnType, factory);
return getMarkerForIntegral(nonTerminalReturns, terminalReturn, returnType, factory);
}
if (!(returnType instanceof PsiPrimitiveType)) {
if (StreamEx.of(nonTerminalReturns).map(ret -> NullabilityUtil.getExpressionNullability(ret, true))
@@ -179,7 +179,7 @@ public final class FinishMarker {
return new FinishMarker(FinishMarkerType.SEPARATE_VAR, value);
}
}
return new FinishMarker(FinishMarkerType.SEPARATE_VAR, findBestExpression(terminalReturn, nonTerminalReturns, mayNeedMarker));
return new FinishMarker(FinishMarkerType.SEPARATE_VAR, findBestExpression(terminalReturn, nonTerminalReturns, true));
}
@Nullable
@@ -208,7 +208,7 @@ public final class FinishMarker {
@NotNull
private static FinishMarker getMarkerForIntegral(List<PsiExpression> nonTerminalReturns,
PsiReturnStatement terminalReturn,
boolean mayNeedMarker, PsiType returnType, PsiElementFactory factory) {
PsiType returnType, PsiElementFactory factory) {
boolean isLong = PsiType.LONG.equals(returnType);
LongRangeSet fullSet = requireNonNull(LongRangeSet.fromType(returnType));
LongRangeSet set = nonTerminalReturns.stream()
@@ -246,7 +246,7 @@ public final class FinishMarker {
return new FinishMarker(FinishMarkerType.VALUE_NON_EQUAL, factory.createExpressionFromText(text, null));
}
}
return new FinishMarker(FinishMarkerType.SEPARATE_VAR, findBestExpression(terminalReturn, nonTerminalReturns, mayNeedMarker));
return new FinishMarker(FinishMarkerType.SEPARATE_VAR, findBestExpression(terminalReturn, nonTerminalReturns, true));
}
@Contract("null -> false")
@@ -70,7 +70,7 @@ public class MarkGeneratedSourceRootAction extends MarkRootActionBase {
private static boolean isJavaModule(Module module) {
ModuleType moduleType = ModuleType.get(module);
//this additional check can be removed when we get rid of PluginModuleType
return moduleType instanceof JavaModuleType || moduleType != null && "PLUGIN_MODULE".equals(moduleType.getId());
return moduleType instanceof JavaModuleType || "PLUGIN_MODULE".equals(moduleType.getId());
}
@Override
@@ -60,10 +60,8 @@ public class RemoteRepositoriesConfiguration implements PersistentStateComponent
@Override
public void loadState(@NotNull RemoteRepositoriesConfiguration.State state) {
final List<RemoteRepositoryDescription> loaded = new SmartList<>();
if (state.data != null) {
for (State.Repo repo : state.data) {
loaded.add(new RemoteRepositoryDescription(repo.id, repo.name, repo.url));
}
for (State.Repo repo : state.data) {
loaded.add(new RemoteRepositoryDescription(repo.id, repo.name, repo.url));
}
setRepositories(loaded);
}
@@ -365,8 +365,7 @@ public class TreeModelBuilder {
}
@Nullable
private PackageDependenciesNode getModuleNode(Module module, ScopeType scopeType) {
private @NotNull PackageDependenciesNode getModuleNode(Module module, ScopeType scopeType) {
if (module == null || !myShowModules) {
return getRootNode(scopeType);
}
@@ -53,7 +53,7 @@ public class JavaIndentHelper extends IndentHelperImpl {
}
if (includeNonSpace) {
return getIndentInner(file, prev, includeNonSpace, recursionLevel + 1) + getIndent(file, text, includeNonSpace);
return getIndentInner(file, prev, true, recursionLevel + 1) + getIndent(file, text, true);
}
if (element.getElementType() == JavaElementType.CODE_BLOCK) {
@@ -64,12 +64,12 @@ public class JavaIndentHelper extends IndentHelperImpl {
if (parent.getElementType() != JavaElementType.CODE_BLOCK) {
//Q: use some "anchor" part of parent for some elements?
// e.g. for method it could be declaration start, not doc-comment
return getIndentInner(file, parent, includeNonSpace, recursionLevel + 1);
return getIndentInner(file, parent, false, recursionLevel + 1);
}
}
else {
if (element.getElementType() == JavaTokenType.LBRACE) {
return getIndentInner(file, element.getTreeParent(), includeNonSpace, recursionLevel + 1);
return getIndentInner(file, element.getTreeParent(), false, recursionLevel + 1);
}
}
//Q: any other cases?
@@ -83,14 +83,14 @@ public class JavaIndentHelper extends IndentHelperImpl {
}
if (parent == null) {
return getIndent(file, text, includeNonSpace);
return getIndent(file, text, false);
}
else {
if (prev.getTreeParent().getElementType() == JavaElementType.LABELED_STATEMENT) {
return getIndentInner(file, prev, true, recursionLevel + 1) + getIndent(file, text, true);
}
else
return getIndentInner(file, prev, includeNonSpace, recursionLevel + 1);
return getIndentInner(file, prev, false, recursionLevel + 1);
}
}
else {
@@ -52,11 +52,9 @@ public class JDParser {
if (info == null || !isJavadoc(info)) return;
JDComment comment = parse(info, formatter);
if (comment != null) {
String indent = formatter.getIndent(info.commentOwner);
String commentText = comment.generate(indent);
formatter.replaceCommentText(commentText, info.docComment);
}
String indent = formatter.getIndent(info.commentOwner);
String commentText = comment.generate(indent);
formatter.replaceCommentText(commentText, info.docComment);
}
private static boolean isJavadoc(CommentInfo info) {
@@ -130,7 +128,7 @@ public class JDParser {
return new CommentInfo(docComment, owner, commentHeader, sb.toString(), commentFooter);
}
private JDComment parse(@NotNull CommentInfo info, @NotNull CommentFormatter formatter) {
private @NotNull JDComment parse(@NotNull CommentInfo info, @NotNull CommentFormatter formatter) {
JDComment comment = createComment(info.commentOwner, formatter);
parse(info.comment, comment);
if (info.commentHeader != null) {
@@ -458,7 +456,7 @@ public class JDParser {
// wrap now
if (wrapPos >= seq.length() - 1 || wrapPos < 0) {
seq = isMarked ? seq : seq.trim();
seq = seq.trim();
list.add(seq);
break;
}
@@ -66,7 +66,6 @@ public final class CreateClassUtil {
else {
final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(project);
FileTemplate fileTemplate = fileTemplateManager.getJ2eeTemplate(templateName);
LOG.assertTrue(fileTemplate != null, templateName + " not found");
final String text = fileTemplate.getText(attributes);
aClass = JavaCreateFromTemplateHandler.createClassOrInterface(project, directory, text, true, fileTemplate.getExtension());
}
@@ -2,7 +2,6 @@
package com.intellij.refactoring.changeSignature;
import com.intellij.ide.highlighter.JavaFileType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.project.Project;
@@ -49,9 +48,9 @@ public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetec
}
@Override
public TextRange getHighlightingRange(@NotNull DetectedJavaChangeInfo changeInfo) {
public @NotNull TextRange getHighlightingRange(@NotNull DetectedJavaChangeInfo changeInfo) {
PsiMethod method = changeInfo.getMethod();
return method != null ? getSignatureRange(method) : null;
return getSignatureRange(method);
}
@Override
@@ -141,7 +140,7 @@ public class JavaChangeSignatureDetector implements LanguageChangeSignatureDetec
return currentInfo.createNextInfo(method, delegate);
}
public static TextRange getSignatureRange(PsiMethod method) {
public static @NotNull TextRange getSignatureRange(@NotNull PsiMethod method) {
int endOffset = method.getThrowsList().getTextRange().getEndOffset();
int startOffset = method.getTextRange().getStartOffset();
return new TextRange(startOffset, endOffset);
@@ -60,14 +60,11 @@ class JavaChangeSignatureUsageSearcher {
public UsageInfo[] findUsages() {
ArrayList<UsageInfo> result = new ArrayList<>();
final PsiMethod method = myChangeInfo.getMethod();
if (method != null) {
findSimpleUsages(method, result);
findSimpleUsages(method, result);
final UsageInfo[] usageInfos = result.toArray(UsageInfo.EMPTY_ARRAY);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
return UsageInfo.EMPTY_ARRAY;
final UsageInfo[] usageInfos = result.toArray(UsageInfo.EMPTY_ARRAY);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
@@ -103,8 +103,7 @@ public class JavaParameterTableModel extends ParameterTableModelBase<ParameterIn
try {
type = JavaPsiFacade.getElementFactory(myProject).createTypeFromText((String)aValue, myTypeContext);
}
catch (IncorrectOperationException e) {
type = null;
catch (IncorrectOperationException ignored) {
}
}
@@ -152,7 +151,6 @@ public class JavaParameterTableModel extends ParameterTableModelBase<ParameterIn
private static void completeVariable(EditorTextField editorTextField, PsiType type) {
Editor editor = editorTextField.getEditor();
String prefix = editorTextField.getText();
if (prefix == null) prefix = "";
Set<LookupElement> set = new LinkedHashSet<>();
JavaCompletionUtil.completeVariableNameForRefactoring(editorTextField.getProject(), set, prefix, type, VariableKind.PARAMETER);
@@ -147,23 +147,20 @@ public final class ConvertToInstanceMethodProcessor extends BaseRefactoringProce
}
@Nullable
@Override
protected String getRefactoringId() {
protected @NotNull String getRefactoringId() {
return "refactoring.makeInstance";
}
@Nullable
@Override
protected RefactoringEventData getBeforeData() {
protected @NotNull RefactoringEventData getBeforeData() {
RefactoringEventData data = new RefactoringEventData();
data.addElements(new PsiElement[]{myMethod, myTargetClass});
return data;
}
@Nullable
@Override
protected RefactoringEventData getAfterData(UsageInfo @NotNull [] usages) {
protected @NotNull RefactoringEventData getAfterData(UsageInfo @NotNull [] usages) {
RefactoringEventData data = new RefactoringEventData();
data.addElement(myTargetClass);
return data;
@@ -93,7 +93,7 @@ public class CopyClassesHandler extends CopyHandlerDelegateBase {
if (!fromUpdate) {
final String name = ((PsiDirectory)element).getName();
final String path = relativePath != null ? (relativePath.length() > 0 ? (relativePath + "/") : "") + name : null;
final Map<PsiFile, PsiClass[]> map = convertToTopLevelClasses(element.getChildren(), fromUpdate, path, relativeMap);
final Map<PsiFile, PsiClass[]> map = convertToTopLevelClasses(element.getChildren(), false, path, relativeMap);
if (map == null) return null;
for (Map.Entry<PsiFile, PsiClass[]> entry : map.entrySet()) {
fillResultsMap(result, entry.getKey(), entry.getValue());
@@ -237,7 +237,6 @@ public class EncapsulateFieldsProcessor extends BaseRefactoringProcessor {
for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
for (final PsiReference reference : ReferencesSearch.search(fieldDescriptor.getField())) {
final PsiElement element = reference.getElement();
if (element == null) continue;
final EncapsulateFieldHelper helper = EncapsulateFieldHelper.getHelper(element.getLanguage());
if (helper != null) {
@@ -19,6 +19,7 @@ import com.intellij.refactoring.IntroduceTargetChooser;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.List;
@@ -71,7 +72,12 @@ public final class ElementToWorkOn {
return myExpression == null;
}
public static void processElementToWorkOn(final Editor editor, final PsiFile file, final @NlsContexts.DialogTitle String refactoringName, final String helpId, final Project project, final ElementsProcessor<? super ElementToWorkOn> processor) {
public static void processElementToWorkOn(final @NotNull Editor editor,
final PsiFile file,
final @NlsContexts.DialogTitle String refactoringName,
final String helpId,
final Project project,
final ElementsProcessor<? super ElementToWorkOn> processor) {
PsiLocalVariable localVar = null;
PsiExpression expr = null;
@@ -81,11 +87,12 @@ public final class ElementToWorkOn {
.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil
.LOOKUP_ITEM_ACCEPTED);
if (element instanceof PsiLocalVariable) {
localVar = (PsiLocalVariable) element;
localVar = (PsiLocalVariable)element;
PsiElement elementAt = file.findElementAt(editor.getCaretModel().getOffset());
if (elementAt instanceof PsiIdentifier && elementAt.getParent() instanceof PsiReferenceExpression) {
expr = (PsiExpression) elementAt.getParent();
} else {
expr = (PsiExpression)elementAt.getParent();
}
else {
final PsiReference reference = TargetElementUtil.findReference(editor);
if (reference != null) {
final PsiElement refElement = reference.getElement();
@@ -94,21 +101,25 @@ public final class ElementToWorkOn {
}
}
}
} else {
final PsiLocalVariable variable = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PsiLocalVariable.class);
}
else {
final PsiLocalVariable variable =
PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PsiLocalVariable.class);
final int offset = editor.getCaretModel().getOffset();
final PsiElement[] statementsInRange = IntroduceVariableBase.findStatementsAtOffset(editor, file, offset);
if (statementsInRange.length == 1 && IntroduceVariableBase.selectLineAtCaret(offset, statementsInRange)) {
editor.getSelectionModel().selectLineAtCaret();
final ElementToWorkOn elementToWorkOn = getElementToWorkOn(editor, file, refactoringName, helpId, project, localVar, expr);
if (elementToWorkOn == null || elementToWorkOn.getLocalVariable() == null && elementToWorkOn.getExpression() == null || !processor.accept(elementToWorkOn)) {
final ElementToWorkOn elementToWorkOn = getElementToWorkOn(editor, file, refactoringName, helpId, project, null, null);
if (elementToWorkOn == null ||
elementToWorkOn.getLocalVariable() == null && elementToWorkOn.getExpression() == null ||
!processor.accept(elementToWorkOn)) {
editor.getSelectionModel().removeSelection();
}
}
if (!editor.getSelectionModel().hasSelection()){
if (!editor.getSelectionModel().hasSelection()) {
final List<PsiExpression> expressions = IntroduceVariableBase.collectExpressions(file, editor, offset);
for (Iterator<PsiExpression> iterator = expressions.iterator(); iterator.hasNext(); ) {
PsiExpression expression = iterator.next();
@@ -126,14 +137,14 @@ public final class ElementToWorkOn {
else {
final int selection = IntroduceVariableBase.preferredSelection(statementsInRange, expressions);
IntroduceTargetChooser.showChooser(editor, expressions, new Pass<>() {
@Override
public void pass(final PsiExpression selectedValue) {
PsiLocalVariable var = null; //replace var if selected expression == var initializer
if (variable != null && variable.getInitializer() == selectedValue) {
var = variable;
}
processor.pass(getElementToWorkOn(editor, file, refactoringName, helpId, project, var, selectedValue));
}
@Override
public void pass(final PsiExpression selectedValue) {
PsiLocalVariable var = null; //replace var if selected expression == var initializer
if (variable != null && variable.getInitializer() == selectedValue) {
var = variable;
}
processor.pass(getElementToWorkOn(editor, file, refactoringName, helpId, project, var, selectedValue));
}
}, new PsiExpressionTrimRenderer.RenderFunction(), RefactoringBundle.message("introduce.target.chooser.expressions.title"), selection, ScopeHighlighter.NATURAL_RANGER);
return;
}
@@ -19,7 +19,6 @@ import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.HighlighterTargetArea;
import com.intellij.openapi.editor.markup.MarkupModel;
@@ -222,9 +221,9 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase {
final PsiMethod selectedMethod = list.getSelectedValue();
if (selectedMethod == null) return;
dropHighlighters(highlighters);
updateView(selectedMethod, editor, EditorColors.SEARCH_RESULT_ATTRIBUTES, highlighters, superMethod);
updateView(selectedMethod, editor, highlighters, superMethod);
});
updateView(validEnclosingMethods.get(0), editor, EditorColors.SEARCH_RESULT_ATTRIBUTES, highlighters, superMethod);
updateView(validEnclosingMethods.get(0), editor, highlighters, superMethod);
final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(list);
scrollPane.setBorder(null);
panel.add(scrollPane, BorderLayout.CENTER);
@@ -256,7 +255,6 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase {
private static void updateView(PsiMethod selectedMethod,
Editor editor,
@NotNull TextAttributesKey attributesKey,
List<? super RangeHighlighter> highlighters,
JCheckBox superMethod) {
final MarkupModel markupModel = editor.getMarkupModel();
@@ -264,7 +262,7 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase {
if (nameIdentifier != null) {
final TextRange textRange = nameIdentifier.getTextRange();
final RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(
attributesKey, textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1,
EditorColors.SEARCH_RESULT_ATTRIBUTES, textRange.getStartOffset(), textRange.getEndOffset(), HighlighterLayer.SELECTION - 1,
HighlighterTargetArea.EXACT_RANGE);
highlighters.add(rangeHighlighter);
}
@@ -433,14 +431,13 @@ public class IntroduceParameterHandler extends IntroduceHandlerBase {
}
if (ApplicationManager.getApplication().isUnitTestMode()) {
@NonNls String parameterName = "anObject";
boolean replaceAllOccurences = true;
boolean isDeleteLocalVariable = true;
PsiExpression initializer = myLocalVar != null && myExpr == null ? myLocalVar.getInitializer() : myExpr;
new IntroduceParameterProcessor(myProject, method, methodToSearchFor, initializer, myExpr, myLocalVar, isDeleteLocalVariable, parameterName,
replaceAllOccurences, IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, mustBeFinal,
new IntroduceParameterProcessor(myProject, method, methodToSearchFor, initializer, myExpr, myLocalVar, true, parameterName,
true, IntroduceParameterRefactoring.REPLACE_FIELDS_WITH_GETTERS_NONE, mustBeFinal,
false, null,
getParamsToRemove(method, occurrences)).run();
} else {
}
else {
if (myEditor != null) {
RefactoringUtil.highlightAllOccurrences(myProject, occurrences, myEditor);
}
@@ -36,6 +36,7 @@ import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
@@ -95,7 +96,7 @@ public class MakeClassStaticProcessor extends MakeMethodOrClassStaticProcessor<P
PsiParameter parameter = factory.createParameter(classParameterName, parameterType);
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, makeClassParameterFinal(usages) || generateFinalParams);
addParameterAfter = paramList.addAfter(parameter, null);
anchor = javaDocHelper.addParameterAfter(classParameterName, anchor);
anchor = javaDocHelper.addParameterAfter(classParameterName, null);
addAssignmentToField(classParameterName, constructor);
@@ -159,7 +160,7 @@ public class MakeClassStaticProcessor extends MakeMethodOrClassStaticProcessor<P
}
}
private String convertToFieldName(final String parameterName) {
private @NotNull String convertToFieldName(final String parameterName) {
JavaCodeStyleManager manager = JavaCodeStyleManager.getInstance(myProject);
final String propertyName = manager.variableNameToPropertyName(parameterName, VariableKind.PARAMETER);
final String fieldName = manager.propertyNameToVariableName(propertyName, VariableKind.FIELD);
@@ -209,9 +210,7 @@ public class MakeClassStaticProcessor extends MakeMethodOrClassStaticProcessor<P
String name = mySettings.getNameForField((PsiField)resolved);
if (name != null) {
name = convertToFieldName(name);
if (name != null) {
newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null);
}
newRef = (PsiReferenceExpression) factory.createExpressionFromText(name, null);
}
}
}
@@ -193,7 +193,7 @@ public class MakeMethodStaticProcessor extends MakeMethodOrClassStaticProcessor<
PsiUtil.setModifierProperty(parameter, PsiModifier.FINAL, true);
}
addParameterAfter = paramList.addAfter(parameter, null);
anchor = javaDocHelper.addParameterAfter(classParameterName, anchor);
anchor = javaDocHelper.addParameterAfter(classParameterName, null);
}
if (mySettings.isMakeFieldParameters()) {
@@ -239,7 +239,6 @@ public class MakeParameterizedStaticDialog extends AbstractMakeStaticDialog {
PsiMethod[] methods = myMember instanceof PsiMethod ? new PsiMethod[]{(PsiMethod)myMember} : ((PsiClass)myMember).getConstructors();
for (PsiMethod method : methods) {
PsiParameterList parameterList = method.getParameterList();
if(parameterList == null) continue;
PsiParameter[] parameters = parameterList.getParameters();
for (PsiParameter parameter : parameters) {
if (parameterName.equals(parameter.getName())) return method;
@@ -162,7 +162,6 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor {
myConflicts = new MultiMap<>();
for (PsiElement element : myElementsToMove) {
String newName = getNewQName(element);
if (newName == null) continue;
UsageInfo[] usages = MoveClassesOrPackagesUtil.findUsages(
element, myRefactoringScope, mySearchInComments, mySearchInNonJavaFiles, newName);
final ArrayList<UsageInfo> infos = new ArrayList<>(Arrays.asList(usages));
@@ -395,8 +394,7 @@ public class MoveClassesOrPackagesProcessor extends BaseRefactoringProcessor {
}
@Nullable
private String getNewQName(PsiElement element) {
private @NotNull String getNewQName(PsiElement element) {
final String qualifiedName = myTargetPackage.getQualifiedName();
if (element instanceof PsiClass) {
return StringUtil.getQualifiedName(qualifiedName, StringUtil.notNullize(((PsiClass)element).getName()));
@@ -41,7 +41,7 @@ public class JavaMoveFilesOrDirectoriesHandler extends MoveFilesOrDirectoriesHan
if (elements.length > 1) {
elements = preprocess(elements);
}
return super.canMove(elements, targetContainer, reference);
return super.canMove(elements, targetContainer, null);
}
@Override
@@ -49,7 +49,6 @@ public class InlineDelegatingCall extends FixableUsageInfo {
replacementText.append(myAccess).append(".");
replacementText.append(delegatingName).append('(');
final PsiExpressionList argumentList = expression.getArgumentList();
assert argumentList != null;
final PsiExpression[] args = argumentList.getExpressions();
boolean first = true;
for (int i : paramaterPermutation) {
@@ -24,10 +24,10 @@ import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.IncorrectOperationException;
import java.util.HashSet;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -55,7 +55,7 @@ public abstract class RenameJavaMemberProcessor extends RenamePsiElementProcesso
occurence.replace(qualified);
}
else {
PsiReferenceExpression qualified = createQualifiedMemberReference(occurence, newName, containingClass, isStatic);
PsiReferenceExpression qualified = createQualifiedMemberReference(occurence, newName, containingClass, false);
qualified = (PsiReferenceExpression)CodeStyleManager.getInstance(psiManager.getProject()).reformat(qualified);
occurence.replace(qualified);
}
@@ -244,7 +244,7 @@ public abstract class RenameJavaMemberProcessor extends RenamePsiElementProcesso
if (ref == null) return;
final PsiElement occurrence = ref.getElement();
final PsiElement target = info.getReferencedElement();
if (target instanceof PsiMember && occurrence != null) {
if (target instanceof PsiMember) {
final PsiMember targetMember = (PsiMember)target;
PsiClass containingClass = targetMember.getContainingClass();
qualifyMember(occurrence, targetMember.getName(), containingClass, true);
@@ -82,11 +82,9 @@ abstract class SafeDeleteJavaCallerChooser extends JavaCallerChooser {
foreignMethodUsages.add(new SafeDeleteParameterCallHierarchyUsageInfo(nodeMethod, parameter, nodeMethod, parameter));
ReferencesSearch.search(nodeMethod).forEach(reference -> {
final PsiElement element = reference.getElement();
if (element != null) {
JavaSafeDeleteDelegate safeDeleteDelegate = JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage());
if (safeDeleteDelegate != null) {
safeDeleteDelegate.createUsageInfoForParameter(reference, foreignMethodUsages, parameter, nodeMethod);
}
JavaSafeDeleteDelegate safeDeleteDelegate = JavaSafeDeleteDelegate.EP.forLanguage(element.getLanguage());
if (safeDeleteDelegate != null) {
safeDeleteDelegate.createUsageInfoForParameter(reference, foreignMethodUsages, parameter, nodeMethod);
}
return true;
});
@@ -9,6 +9,7 @@ import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.typeCook.deductive.PsiTypeVariableFactory;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
@@ -24,7 +25,7 @@ public final class Util {
return theType;
}
public static PsiClassType.ClassResolveResult resolveType(PsiType type) {
public static @NotNull PsiClassType.ClassResolveResult resolveType(PsiType type) {
final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(type);
final PsiClass aClass = resolveResult.getElement();
if (aClass instanceof PsiAnonymousClass) {
@@ -43,10 +44,6 @@ public final class Util {
else if (t instanceof PsiClassType) {
PsiClassType.ClassResolveResult result = resolveType(t);
if (result == null) {
return null;
}
PsiClass aclass = result.getElement();
PsiSubstitutor subst = result.getSubstitutor();
PsiManager manager = aclass.getManager();
@@ -354,10 +351,6 @@ public final class Util {
final PsiNewExpression newx = (PsiNewExpression)element;
final PsiClassType.ClassResolveResult result = resolveType(type);
if (result == null) {
return;
}
final PsiSubstitutor subst = result.getSubstitutor();
final PsiTypeParameter[] parms = result.getElement().getTypeParameters();
@@ -512,7 +512,7 @@ public class BindingFactory {
}
}
else {
binding.myBindings.put(index, type);
binding.myBindings.put(index, null);
}
}
@@ -12,7 +12,6 @@ import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -54,15 +53,13 @@ public final class SPIFileType extends LanguageFileType implements FileTypeIdent
return "";
}
@Nullable
@Override
public Icon getIcon() {
public @NotNull Icon getIcon() {
return AllIcons.FileTypes.Text;
}
@Nullable
@Override
public String getCharset(@NotNull VirtualFile file, byte @NotNull [] content) {
public @NotNull String getCharset(@NotNull VirtualFile file, byte @NotNull [] content) {
return CharsetToolkit.UTF8;
}
}
@@ -139,19 +139,16 @@ class ConstructorReferencesSearchHelper {
@NotNull PsiClass aClass, SearchScope searchScope) {
return ReferencesSearch.search(aClass, searchScope).forEach(reference -> {
final PsiElement element = reference.getElement();
if (element != null) {
return DumbService.getInstance(project).runReadActionInSmartMode(() -> {
final PsiElement parent = element.getParent();
if (parent instanceof PsiMethodReferenceExpression &&
((PsiMethodReferenceExpression)parent).getReferenceNameElement() instanceof PsiKeyword) {
if (((PsiMethodReferenceExpression)parent).isReferenceTo(constructor)) {
if (!processor.process((PsiReference)parent)) return false;
}
return DumbService.getInstance(project).runReadActionInSmartMode(() -> {
final PsiElement parent = element.getParent();
if (parent instanceof PsiMethodReferenceExpression &&
((PsiMethodReferenceExpression)parent).getReferenceNameElement() instanceof PsiKeyword) {
if (((PsiMethodReferenceExpression)parent).isReferenceTo(constructor)) {
if (!processor.process((PsiReference)parent)) return false;
}
return true;
});
}
return true;
}
return true;
});
});
}
@@ -68,9 +68,9 @@ public final class ClassUtil {
return null;
}
private static boolean add(PsiMethod method, Set<? super PsiMethod> alreadyImplemented) {
private static boolean add(PsiMethod method, @NotNull Set<? super PsiMethod> alreadyImplemented) {
boolean already = alreadyImplemented.add(method);
if (!already) return already;
if (!already) return false;
for (PsiMethod superSig : method.findSuperMethods()) {
already &= add(superSig, alreadyImplemented);
@@ -46,7 +46,6 @@ public final class JavaGenericsUtil {
return true;
}
assert parameters.length == 0;
final PsiClassType.ClassResolveResult resolved = classType.resolveGenerics();
final PsiClass aClass = resolved.getElement();
if (aClass instanceof PsiTypeParameter) {
@@ -50,9 +50,6 @@ public final class PsiIntersectionType extends PsiType.Stub {
private static PsiType @NotNull [] flattenAndRemoveDuplicates(PsiType @NotNull [] conjuncts) {
try {
final Set<PsiType> flattenConjuncts = flatten(conjuncts, new LinkedHashSet<>());
if (flattenConjuncts == null) {
return conjuncts;
}
return flattenConjuncts.toArray(createArray(flattenConjuncts.size()));
}
catch (NoSuchElementException e) {
@@ -60,7 +57,7 @@ public final class PsiIntersectionType extends PsiType.Stub {
}
}
public static Set<PsiType> flatten(PsiType[] conjuncts, Set<PsiType> types) {
public static @NotNull Set<PsiType> flatten(PsiType @NotNull [] conjuncts, Set<PsiType> types) {
for (PsiType conjunct : conjuncts) {
if (conjunct instanceof PsiIntersectionType) {
PsiIntersectionType type = (PsiIntersectionType)conjunct;
@@ -344,10 +344,6 @@ public abstract class JavaFoldingBuilderBase extends CustomFoldingBuilder implem
if (range.equals(fileRange)) return;
LOG.assertTrue(range.getStartOffset() >= 0 && range.getEndOffset() <= fileRange.getEndOffset());
// PSI element text ranges may be invalid because of reparse exception (see, for example, IDEA-10617)
if (range.getStartOffset() < 0 || range.getEndOffset() > fileRange.getEndOffset()) {
return;
}
if (!allowOneLiners) {
int startLine = document.getLineNumber(range.getStartOffset());
@@ -254,7 +254,7 @@ public class DeclarationParser {
}
@Nullable
public PsiBuilder.Marker parse(final PsiBuilder builder, final Context context) {
public PsiBuilder.Marker parse(final @NotNull PsiBuilder builder, final Context context) {
IElementType tokenType = builder.getTokenType();
if (tokenType == null) return null;
@@ -46,7 +46,7 @@ public class JShellParser extends JavaParser {
!JavaElementType.EXPRESSION_STATEMENT.equals(tokenType);
private static final Predicate<IElementType> DECLARATION_PARSED_CONDITION = tokenType -> TOP_LEVEL_DECLARATIONS.contains(tokenType);
private final FileParser myJShellFileParser = new FileParser(JShellParser.this) {
private final FileParser myJShellFileParser = new FileParser(this) {
private final TokenSet IMPORT_PARSING_STOP_LIST = TokenSet.orSet(
IMPORT_LIST_STOPPER_SET,
TokenSet.orSet(
@@ -103,9 +103,7 @@ public class JShellParser extends JavaParser {
}
if (marker == null) {
if (wrapper != null) {
wrapper.drop();
}
wrapper.drop();
break;
}
@@ -189,7 +189,7 @@ public class LightMemberReference extends LightElement implements PsiJavaCodeRef
public boolean isValid() {
PsiReferenceParameterList parameterList = getParameterList();
if (parameterList != null && !parameterList.isValid()) return false;
return myRefMember == null || myRefMember.isValid();
return myRefMember.isValid();
}
@Override
@@ -13,11 +13,12 @@ import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.ElementType;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public final class ReplaceExpressionUtil {
private static final Logger LOG = Logger.getInstance(ReplaceExpressionUtil.class);
public static boolean isNeedParenthesis(ASTNode oldExpr, ASTNode newExpr) {
public static boolean isNeedParenthesis(@NotNull ASTNode oldExpr, ASTNode newExpr) {
final ASTNode oldParent = oldExpr.getTreeParent();
if (!ElementType.EXPRESSION_BIT_SET.contains(oldParent.getElementType())) return false;
int priority = getExpressionPriority(newExpr);
@@ -31,12 +32,12 @@ public final class ReplaceExpressionUtil {
if (i == JavaElementType.ASSIGNMENT_EXPRESSION) {
return priority < parentPriority || ((CompositeElement)oldParent).getChildRole(oldExpr) == ChildRole.LOPERAND;
}
else if (i == JavaElementType.CONDITIONAL_EXPRESSION) {
if (i == JavaElementType.CONDITIONAL_EXPRESSION) {
int role = ((CompositeElement)oldParent).getChildRole(oldExpr);
if (role == ChildRole.THEN_EXPRESSION) return false;
return priority < parentPriority || role != ChildRole.ELSE_EXPRESSION;
}
else if (i == JavaElementType.BINARY_EXPRESSION || i == JavaElementType.POLYADIC_EXPRESSION) {
if (i == JavaElementType.BINARY_EXPRESSION || i == JavaElementType.POLYADIC_EXPRESSION) {
if (priority < parentPriority) return true;
PsiElement element = SourceTreeToPsiMap.treeElementToPsi(oldParent);
assert element != null;
@@ -52,21 +53,21 @@ public final class ReplaceExpressionUtil {
opType != JavaTokenType.ANDAND &&
opType != JavaTokenType.OROR;
}
else if (i == JavaElementType.POSTFIX_EXPRESSION) {
return priority <= parentPriority;
if (i == JavaElementType.POSTFIX_EXPRESSION) {
return true;
}
else if (i == JavaElementType.INSTANCE_OF_EXPRESSION ||
if (i == JavaElementType.INSTANCE_OF_EXPRESSION ||
i == JavaElementType.PREFIX_EXPRESSION ||
i == JavaElementType.TYPE_CAST_EXPRESSION ||
i == JavaElementType.REFERENCE_EXPRESSION ||
i == JavaElementType.METHOD_REF_EXPRESSION) {
return priority < parentPriority;
}
else if (i == JavaElementType.ARRAY_ACCESS_EXPRESSION) {
if (i == JavaElementType.ARRAY_ACCESS_EXPRESSION) {
int role = ((CompositeElement)oldParent).getChildRole(oldExpr);
return role != ChildRole.ARRAY_DIMENSION && role != ChildRole.INDEX && priority < parentPriority;
}
else if (i == JavaElementType.METHOD_CALL_EXPRESSION ||
if (i == JavaElementType.METHOD_CALL_EXPRESSION ||
i == JavaElementType.NEW_EXPRESSION ||
i == JavaElementType.ARRAY_INITIALIZER_EXPRESSION ||
i == JavaElementType.PARENTH_EXPRESSION ||
@@ -32,9 +32,6 @@ public enum PatternResolveState {
@NotNull
public static PatternResolveState stateAtParent(PsiPatternVariable element, PsiExpression parent) {
PsiPattern pattern = element.getPattern();
if (pattern == null) {
throw new IllegalArgumentException("Variable has no pattern associated");
}
PatternResolveState state = WHEN_TRUE;
for (PsiElement prev = pattern, current = prev.getParent(); prev != parent; prev = current, current = current.getParent()) {
if (current instanceof PsiInstanceOfExpression || current instanceof PsiParenthesizedExpression ||
@@ -532,7 +532,7 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
if (applicable12 || applicable21) {
if (applicable12 && !applicable21) return Specifics.SECOND;
if (applicable21 && !applicable12) return Specifics.FIRST;
if (!applicable12) return Specifics.FIRST;
//from 15.12.2.5 Choosing the Most Specific Method: concrete = nonabstract or default
final boolean abstract1 = method1.hasModifierProperty(PsiModifier.ABSTRACT) || method1.hasModifierProperty(PsiModifier.DEFAULT);
@@ -141,11 +141,11 @@ public final class RefactoringChangeUtil {
}
}
public static PsiThisExpression createThisExpression(PsiManager manager, PsiClass qualifierClass) throws IncorrectOperationException {
public static @NotNull PsiThisExpression createThisExpression(PsiManager manager, PsiClass qualifierClass) throws IncorrectOperationException {
return createQualifiedExpression(manager, qualifierClass, "this");
}
public static PsiSuperExpression createSuperExpression(PsiManager manager, PsiClass qualifierClass) throws IncorrectOperationException {
public static @NotNull PsiSuperExpression createSuperExpression(PsiManager manager, PsiClass qualifierClass) throws IncorrectOperationException {
return createQualifiedExpression(manager, qualifierClass, "super");
}
}
@@ -108,13 +108,12 @@ public class Src15RepositoryUseTest extends JavaPsiTestCase {
final PsiImportStaticStatement classReference1 = importStaticStatements[1];
final PsiClass element1 = classReference1.resolveTargetClass();
assertNotNull(element1);
assertTrue(element1 instanceof PsiClass);
assertEquals("java.util.Arrays", element1.getQualifiedName());
final PsiImportStaticStatement classReference3 = importStaticStatements[3];
final PsiClass element3 = classReference3.resolveTargetClass();
assertNotNull(element3);
assertTrue(element3 instanceof PsiClass);
assertEquals("java.util.Arrays", element3.getQualifiedName());
if (okToLoadTree) {
@@ -100,7 +100,7 @@ public class ShortenClassReferencesTest extends LightJavaCodeInsightFixtureTestC
WriteCommandAction.runWriteCommandAction(getProject(),
() -> {
PsiTypeElement typeElement = (PsiTypeElement)JavaCodeStyleManager.getInstance(getProject()).shortenClassReferences(((PsiParameter)elementAtCaret).getTypeElement());
assertTrue(typeElement != null && typeElement.isValid());
assertTrue(typeElement.isValid());
assertEquals("List<String>", typeElement.getText());
});
@@ -47,10 +47,8 @@ public class PushDownMultifileTest extends LightMultiFileTestCase {
try {
doTest(() -> {
final PsiClass srcClass = myFixture.findClass(sourceClassName);
assertTrue("Source class not found", srcClass != null);
final PsiClass targetClass = myFixture.findClass(targetClassName);
assertTrue("Target class not found", targetClass != null);
myFixture.findClass(targetClassName);
final PsiMethod[] methods = srcClass.getMethods();
assertTrue("No methods found", methods.length > 0);
@@ -97,10 +95,8 @@ public class PushDownMultifileTest extends LightMultiFileTestCase {
try {
doTest(() -> {
final PsiClass srcClass = myFixture.findClass("a.A");
assertTrue("Source class not found", srcClass != null);
final PsiClass targetClass = myFixture.findClass("b.B");
assertTrue("Target class not found", targetClass != null);
myFixture.findClass("b.B");
final PsiField[] fields = srcClass.getFields();
assertTrue("No methods found", fields.length > 0);
@@ -34,9 +34,8 @@ public class ClasspathEditorTest extends LightPlatformTestCase {
disposeOnTearDown(() -> uiRootModel.dispose());
ClasspathEditor e = new ClasspathEditor(new ModuleConfigurationStateImpl(project, new DefaultModulesProvider(project)) {
@Nullable
@Override
public ModifiableRootModel getRootModel() {
public @NotNull ModifiableRootModel getRootModel() {
return uiRootModel;
}
});
@@ -28,7 +28,6 @@ import com.intellij.icons.AllIcons;
import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
@@ -62,9 +61,8 @@ public final class ManifestFileType extends LanguageFileType {
return "MF";
}
@Nullable
@Override
public Icon getIcon() {
public @NotNull Icon getIcon() {
return AllIcons.FileTypes.Manifest;
}
}
@@ -78,7 +78,7 @@ public final class BackwardReferenceIndexUtil {
final CompilerRef
ref = writer.enumerateNames(def.getDefinedElement(), name -> anonymousClassEnumerator.getCompilerRefIfAnonymous(name));
final CompilerRef.JavaCompilerClassRef returnType = writer.asClassUsage(((JavacDef.JavacMemberDef)def).getReturnType());
if (ref != null && returnType != null) {
if (ref != null) {
final SignatureData data = new SignatureData(returnType.getName(), ((JavacDef.JavacMemberDef)def).getIteratorKind(), ((JavacDef.JavacMemberDef)def).isStatic());
signatureData.computeIfAbsent(data, element -> new SmartList<>()).add(ref);
}
@@ -91,7 +91,7 @@ public final class JavaBackwardReferenceIndexWriter extends CompilerReferenceWri
return SystemProperties.getBooleanProperty(PROP_KEY, false);
}
synchronized CompilerRef.JavaCompilerClassRef asClassUsage(JavacRef aClass) throws IOException {
synchronized @NotNull CompilerRef.JavaCompilerClassRef asClassUsage(JavacRef aClass) throws IOException {
return new CompilerRef.JavaCompilerClassRef(id(aClass, myIndex.getByteSeqEum()));
}
@@ -142,15 +142,12 @@ public class Mappings {
myClassToRelativeSourceFilePath = new IntObjectTransientMultiMaplet<>(fileCollectionFactory);
}
else {
if (myIsDelta) {
myRootDir.mkdirs();
}
myClassToSubclasses = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_SUBCLASSES),
EnumeratorIntegerDescriptor.INSTANCE);
myClassToClassDependency = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_CLASS),
EnumeratorIntegerDescriptor.INSTANCE);
myShortClassNameIndex = myIsDelta? null : new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, SHORT_NAMES),
EnumeratorIntegerDescriptor.INSTANCE);
myShortClassNameIndex = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, SHORT_NAMES),
EnumeratorIntegerDescriptor.INSTANCE);
myRelativeSourceFilePathToClasses = new ObjectObjectPersistentMultiMaplet<String, ClassFileRepr>(
DependencyContext.getTableFile(myRootDir, SOURCE_TO_CLASS), PathStringDescriptor.INSTANCE, new ClassFileReprExternalizer(myContext),
() -> new THashSet<>(5, DEFAULT_SET_LOAD_FACTOR)
@@ -595,7 +592,7 @@ public class Mappings {
}
final Boolean inheritorOf = isInheritorOf(s, whom, visitedClasses);
if (inheritorOf != null && inheritorOf) {
return inheritorOf;
return true;
}
}
}
@@ -2474,8 +2471,7 @@ public class Mappings {
for (Pair<ModulePackageRepr, ModulePackageRepr.Diff> p : exportsDiff.changed()) {
final Collection<Integer> removedModuleNames = p.second.targetModules().removed();
affectDeps |= !removedModuleNames.isEmpty();
if (!removedModuleNames.isEmpty()) {
affectDeps = true;
if (affectDeps) {
for (Integer name : removedModuleNames) {
final UsageConstraint matchName = UsageConstraint.exactMatch(name);
if (constraint == null) {
@@ -99,7 +99,7 @@ public class ModulePackageRepr extends Proto {
final StringBuilder sb = new StringBuilder();
sb.append("Module package: ").append(context.getValue(name));
final Set<Integer> moduleNames = myModuleNames;
if (moduleNames != null && !moduleNames.isEmpty()) {
if (!moduleNames.isEmpty()) {
final List<String> names = new ArrayList<>();
for (Integer moduleName : moduleNames) {
names.add(context.getValue(moduleName));
@@ -191,7 +191,7 @@ public final class IncProjectBuilder {
reportRebuiltModules(context);
reportUnprocessedChanges(context);
// If build was canceled for some reasons e.g compilation error we should report built modules
if (sourcesState != null) sourcesState.reportSourcesState();
sourcesState.reportSourcesState();
// some builder decided to stop the build
// report optional progress message if any
final String msg = e.getMessage();
@@ -57,10 +57,9 @@ public abstract class ArtifactCompilerInstructionCreatorBase implements Artifact
@NotNull Condition<? super String> pathInJarFilter) {
//an entry of a jar file is excluded if and only if the jar file itself is excluded. In that case we should unpack entries to the artifact
//because the jar itself is explicitly added to the artifact layout.
boolean includeExcluded = true;
final SourceFileFilterImpl filter = new SourceFileFilterImpl(null, myInstructionsBuilder.getRootsIndex(),
myInstructionsBuilder.getIgnoredFileIndex(), includeExcluded);
myInstructionsBuilder.getIgnoredFileIndex(), true);
DestinationInfo destination = createDirectoryDestination();
if (destination != null) {
ArtifactRootDescriptor descriptor = myInstructionsBuilder.createJarBasedRoot(jarFile, pathInJar, filter, destination, pathInJarFilter);
@@ -60,39 +60,38 @@ public final class LookupElementBuilder extends LookupElement {
this(lookupString, object, null, null, null, null, null, Collections.singleton(lookupString), true);
}
@NotNull
public static LookupElementBuilder create(@NotNull String lookupString) {
public static @NotNull LookupElementBuilder create(@NotNull String lookupString) {
return new LookupElementBuilder(lookupString, lookupString);
}
public static LookupElementBuilder create(@NotNull Object object) {
public static @NotNull LookupElementBuilder create(@NotNull Object object) {
return new LookupElementBuilder(object.toString(), object);
}
public static LookupElementBuilder createWithSmartPointer(@NotNull String lookupString, @NotNull PsiElement element) {
public static @NotNull LookupElementBuilder createWithSmartPointer(@NotNull String lookupString, @NotNull PsiElement element) {
PsiUtilCore.ensureValid(element);
return new LookupElementBuilder(lookupString,
SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element));
}
public static LookupElementBuilder create(@NotNull PsiNamedElement element) {
public static @NotNull LookupElementBuilder create(@NotNull PsiNamedElement element) {
PsiUtilCore.ensureValid(element);
return new LookupElementBuilder(StringUtil.notNullize(element.getName()), element);
}
public static LookupElementBuilder createWithIcon(@NotNull PsiNamedElement element) {
public static @NotNull LookupElementBuilder createWithIcon(@NotNull PsiNamedElement element) {
PsiUtilCore.ensureValid(element);
return create(element).withIcon(element.getIcon(0));
}
public static LookupElementBuilder create(@NotNull Object lookupObject, @NotNull String lookupString) {
public static @NotNull LookupElementBuilder create(@NotNull Object lookupObject, @NotNull String lookupString) {
if (lookupObject instanceof PsiElement) {
PsiUtilCore.ensureValid((PsiElement)lookupObject);
}
return new LookupElementBuilder(lookupString, lookupObject);
}
private LookupElementBuilder cloneWithUserData(@NotNull String lookupString, @NotNull Object object,
private @NotNull LookupElementBuilder cloneWithUserData(@NotNull String lookupString, @NotNull Object object,
@Nullable InsertHandler<LookupElement> insertHandler,
@Nullable LookupElementRenderer<LookupElement> renderer,
@Nullable LookupElementRenderer<LookupElement> expensiveRenderer,
@@ -111,12 +110,12 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setInsertHandler(@Nullable InsertHandler<LookupElement> insertHandler) {
public @NotNull LookupElementBuilder setInsertHandler(@Nullable InsertHandler<LookupElement> insertHandler) {
return withInsertHandler(insertHandler);
}
@Contract(pure=true)
public LookupElementBuilder withInsertHandler(@Nullable InsertHandler<LookupElement> insertHandler) {
public @NotNull LookupElementBuilder withInsertHandler(@Nullable InsertHandler<LookupElement> insertHandler) {
return cloneWithUserData(myLookupString, myObject, insertHandler, myRenderer, myExpensiveRenderer, myHardcodedPresentation,
myPsiElement, myAllLookupStrings, myCaseSensitive);
}
@@ -126,17 +125,17 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setRenderer(@Nullable LookupElementRenderer<LookupElement> renderer) {
public @NotNull LookupElementBuilder setRenderer(@Nullable LookupElementRenderer<LookupElement> renderer) {
return withRenderer(renderer);
}
@Contract(pure=true)
public LookupElementBuilder withRenderer(@Nullable LookupElementRenderer<LookupElement> renderer) {
public @NotNull LookupElementBuilder withRenderer(@Nullable LookupElementRenderer<LookupElement> renderer) {
return cloneWithUserData(myLookupString, myObject, myInsertHandler, renderer, myExpensiveRenderer, myHardcodedPresentation,
myPsiElement, myAllLookupStrings, myCaseSensitive);
}
@Contract(pure=true)
public LookupElementBuilder withExpensiveRenderer(@Nullable LookupElementRenderer<LookupElement> expensiveRenderer) {
public @NotNull LookupElementBuilder withExpensiveRenderer(@Nullable LookupElementRenderer<LookupElement> expensiveRenderer) {
return cloneWithUserData(myLookupString, myObject, myInsertHandler, myRenderer, expensiveRenderer, myHardcodedPresentation,
myPsiElement, myAllLookupStrings, myCaseSensitive);
}
@@ -152,12 +151,12 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setIcon(@Nullable Icon icon) {
public @NotNull LookupElementBuilder setIcon(@Nullable Icon icon) {
return withIcon(icon);
}
@Contract(pure=true)
public LookupElementBuilder withIcon(@Nullable Icon icon) {
public @NotNull LookupElementBuilder withIcon(@Nullable Icon icon) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setIcon(icon);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -180,18 +179,18 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder addLookupString(@NotNull String another) {
public @NotNull LookupElementBuilder addLookupString(@NotNull String another) {
return withLookupString(another);
}
@Contract(pure=true)
public LookupElementBuilder withLookupString(@NotNull String another) {
public @NotNull LookupElementBuilder withLookupString(@NotNull String another) {
final Set<String> set = new HashSet<>(myAllLookupStrings);
set.add(another);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, myRenderer, myExpensiveRenderer, myHardcodedPresentation,
myPsiElement, Collections.unmodifiableSet(set), myCaseSensitive);
}
@Contract(pure=true)
public LookupElementBuilder withLookupStrings(@NotNull Collection<String> another) {
public @NotNull LookupElementBuilder withLookupStrings(@NotNull Collection<String> another) {
Set<String> set = new HashSet<>(myAllLookupStrings.size() + another.size());
set.addAll(myAllLookupStrings);
set.addAll(another);
@@ -209,7 +208,7 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setCaseSensitive(boolean caseSensitive) {
public @NotNull LookupElementBuilder setCaseSensitive(boolean caseSensitive) {
return withCaseSensitivity(caseSensitive);
}
/**
@@ -218,7 +217,7 @@ public final class LookupElementBuilder extends LookupElement {
* @see com.intellij.codeInsight.completion.CompletionResultSet#caseInsensitive()
*/
@Contract(pure=true)
public LookupElementBuilder withCaseSensitivity(boolean caseSensitive) {
public @NotNull LookupElementBuilder withCaseSensitivity(boolean caseSensitive) {
return cloneWithUserData(myLookupString, myObject, myInsertHandler, myRenderer, myExpensiveRenderer, myHardcodedPresentation,
myPsiElement, myAllLookupStrings, caseSensitive);
}
@@ -227,7 +226,7 @@ public final class LookupElementBuilder extends LookupElement {
* Allows to pass custom PSI that will be returned from {@link #getPsiElement()}.
*/
@Contract(pure=true)
public LookupElementBuilder withPsiElement(@Nullable PsiElement psi) {
public @NotNull LookupElementBuilder withPsiElement(@Nullable PsiElement psi) {
return cloneWithUserData(myLookupString, myObject, myInsertHandler, myRenderer, myExpensiveRenderer, myHardcodedPresentation,
psi == null ? null : SmartPointerManager.createPointer(psi),
myAllLookupStrings, myCaseSensitive);
@@ -238,11 +237,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setItemTextForeground(@NotNull Color itemTextForeground) {
public @NotNull LookupElementBuilder setItemTextForeground(@NotNull Color itemTextForeground) {
return withItemTextForeground(itemTextForeground);
}
@Contract(pure=true)
public LookupElementBuilder withItemTextForeground(@NotNull Color itemTextForeground) {
public @NotNull LookupElementBuilder withItemTextForeground(@NotNull Color itemTextForeground) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setItemTextForeground(itemTextForeground);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation,
@@ -254,11 +253,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setItemTextUnderlined(boolean underlined) {
public @NotNull LookupElementBuilder setItemTextUnderlined(boolean underlined) {
return withItemTextUnderlined(underlined);
}
@Contract(pure=true)
public LookupElementBuilder withItemTextUnderlined(boolean underlined) {
public @NotNull LookupElementBuilder withItemTextUnderlined(boolean underlined) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setItemTextUnderlined(underlined);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation,
@@ -266,7 +265,7 @@ public final class LookupElementBuilder extends LookupElement {
}
@Contract(pure=true)
public LookupElementBuilder withItemTextItalic(boolean italic) {
public @NotNull LookupElementBuilder withItemTextItalic(boolean italic) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setItemTextItalic(italic);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation,
@@ -278,11 +277,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setTypeText(@Nullable String typeText) {
public @NotNull LookupElementBuilder setTypeText(@Nullable String typeText) {
return withTypeText(typeText);
}
@Contract(pure=true)
public LookupElementBuilder withTypeText(@Nullable String typeText) {
public @NotNull LookupElementBuilder withTypeText(@Nullable String typeText) {
return withTypeText(typeText, false);
}
@@ -291,17 +290,17 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setTypeText(@Nullable String typeText, boolean grayed) {
public @NotNull LookupElementBuilder setTypeText(@Nullable String typeText, boolean grayed) {
return withTypeText(typeText, grayed);
}
@Contract(pure=true)
public LookupElementBuilder withTypeText(@Nullable String typeText, boolean grayed) {
public @NotNull LookupElementBuilder withTypeText(@Nullable String typeText, boolean grayed) {
return withTypeText(typeText, null, grayed);
}
@Contract(pure=true)
public LookupElementBuilder withTypeText(@Nullable String typeText, @Nullable Icon typeIcon, boolean grayed) {
public @NotNull LookupElementBuilder withTypeText(@Nullable String typeText, @Nullable Icon typeIcon, boolean grayed) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setTypeText(typeText, typeIcon);
presentation.setTypeGrayed(grayed);
@@ -309,7 +308,7 @@ public final class LookupElementBuilder extends LookupElement {
myAllLookupStrings, myCaseSensitive);
}
public LookupElementBuilder withTypeIconRightAligned(boolean typeIconRightAligned) {
public @NotNull LookupElementBuilder withTypeIconRightAligned(boolean typeIconRightAligned) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setTypeIconRightAligned(typeIconRightAligned);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -321,11 +320,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setPresentableText(@NotNull String presentableText) {
public @NotNull LookupElementBuilder setPresentableText(@NotNull String presentableText) {
return withPresentableText(presentableText);
}
@Contract(pure=true)
public LookupElementBuilder withPresentableText(@NotNull String presentableText) {
public @NotNull LookupElementBuilder withPresentableText(@NotNull String presentableText) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setItemText(presentableText);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -337,11 +336,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setBold() {
public @NotNull LookupElementBuilder setBold() {
return bold();
}
@Contract(pure=true)
public LookupElementBuilder bold() {
public @NotNull LookupElementBuilder bold() {
return withBoldness(true);
}
@@ -350,11 +349,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setBold(boolean bold) {
public @NotNull LookupElementBuilder setBold(boolean bold) {
return withBoldness(bold);
}
@Contract(pure=true)
public LookupElementBuilder withBoldness(boolean bold) {
public @NotNull LookupElementBuilder withBoldness(boolean bold) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setItemTextBold(bold);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -366,11 +365,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setStrikeout() {
public @NotNull LookupElementBuilder setStrikeout() {
return strikeout();
}
@Contract(pure=true)
public LookupElementBuilder strikeout() {
public @NotNull LookupElementBuilder strikeout() {
return withStrikeoutness(true);
}
@@ -379,11 +378,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setStrikeout(boolean strikeout) {
public @NotNull LookupElementBuilder setStrikeout(boolean strikeout) {
return withStrikeoutness(strikeout);
}
@Contract(pure=true)
public LookupElementBuilder withStrikeoutness(boolean strikeout) {
public @NotNull LookupElementBuilder withStrikeoutness(boolean strikeout) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setStrikeout(strikeout);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -395,11 +394,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setTailText(@Nullable String tailText) {
public @NotNull LookupElementBuilder setTailText(@Nullable String tailText) {
return withTailText(tailText);
}
@Contract(pure=true)
public LookupElementBuilder withTailText(@Nullable String tailText) {
public @NotNull LookupElementBuilder withTailText(@Nullable String tailText) {
return withTailText(tailText, false);
}
@@ -408,11 +407,11 @@ public final class LookupElementBuilder extends LookupElement {
*/
@Deprecated
@Contract(pure=true)
public LookupElementBuilder setTailText(@Nullable String tailText, boolean grayed) {
public @NotNull LookupElementBuilder setTailText(@Nullable String tailText, boolean grayed) {
return withTailText(tailText, grayed);
}
@Contract(pure=true)
public LookupElementBuilder withTailText(@Nullable String tailText, boolean grayed) {
public @NotNull LookupElementBuilder withTailText(@Nullable String tailText, boolean grayed) {
final LookupElementPresentation presentation = copyPresentation();
presentation.setTailText(tailText, grayed);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -420,7 +419,7 @@ public final class LookupElementBuilder extends LookupElement {
}
@Contract(pure=true)
public LookupElementBuilder appendTailText(@NotNull String tailText, boolean grayed) {
public @NotNull LookupElementBuilder appendTailText(@NotNull String tailText, boolean grayed) {
final LookupElementPresentation presentation = copyPresentation();
presentation.appendTailText(tailText, grayed);
return cloneWithUserData(myLookupString, myObject, myInsertHandler, null, myExpensiveRenderer, presentation, myPsiElement,
@@ -37,11 +37,11 @@ import java.util.Objects;
public class MoveRenameUsageInfo extends UsageInfo implements BranchableUsageInfo, Cloneable {
private static final Logger LOG = Logger.getInstance(MoveRenameUsageInfo.class);
private SmartPsiElementPointer myReferencedElementPointer = null;
private SmartPsiElementPointer<?> myReferencedElementPointer;
private PsiElement myReferencedElement;
private PsiReference myReference;
private RangeMarker myReferenceRangeMarker = null;
private RangeMarker myReferenceRangeMarker;
public MoveRenameUsageInfo(PsiReference reference, PsiElement referencedElement){
this(reference.getElement(), reference, referencedElement);
@@ -101,7 +101,7 @@ public class MoveRenameUsageInfo extends UsageInfo implements BranchableUsageInf
public PsiReference getReference() {
if (myReference != null) {
final PsiElement element = myReference.getElement();
if (element != null && element.isValid()) {
if (element.isValid()) {
if (myReferenceRangeMarker == null) {
return myReference;
}
@@ -7,7 +7,6 @@ import com.intellij.analysis.AnalysisScope;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public final class CleanupAllIntention extends CleanupIntention {
@@ -21,9 +20,8 @@ public final class CleanupAllIntention extends CleanupIntention {
return AnalysisBundle.message("cleanup.in.file");
}
@Nullable
@Override
protected AnalysisScope getScope(Project project, PsiFile file) {
protected @NotNull AnalysisScope getScope(Project project, PsiFile file) {
return new AnalysisScope(file);
}
}
@@ -152,14 +152,13 @@ public class PlainTextFormatter implements InspectionsReportConverter {
}
catch (IOException e) {
throw new ConversionException("Cannot write inspection results: " + e.getMessage());
} finally {
if (w != null) {
try {
w.close();
}
catch (IOException e) {
warn("Cannot save inspection results: " + e.getMessage());
}
}
finally {
try {
w.close();
}
catch (IOException e) {
warn("Cannot save inspection results: " + e.getMessage());
}
}
}
@@ -6,6 +6,7 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -17,23 +18,18 @@ import java.nio.file.Paths;
public final class ReportConverterUtil {
public static @Nullable InspectionsReportConverter getReportConverter(@Nullable String outputFormat) {
return InspectionsReportConverter.EP_NAME.getExtensionList().stream()
.filter(converter -> converter.getFormatName().equals(outputFormat))
.findFirst().orElse(null);
return ContainerUtil.find(InspectionsReportConverter.EP_NAME.getExtensionList(), converter -> converter.getFormatName().equals(outputFormat));
}
@NotNull
public static Path getResultsDataPath(@NotNull Disposable parentDisposable, @Nullable InspectionsReportConverter reportConverter, @NotNull String outputPath) throws IOException {
Path resultsDataPath;
if ((reportConverter == null || !reportConverter.useTmpDirForRawData())
// use default xml converter(if null( or don't store default xml report in tmp dir
&&
outputPath != null) { // and don't use STDOUT stream
// use default xml converter(if null( or don't store default xml report in tmp dir
if (reportConverter == null || !reportConverter.useTmpDirForRawData()) { // and don't use STDOUT stream
resultsDataPath = Paths.get(outputPath);
Files.createDirectories(resultsDataPath);
}
else {
File tmpDir = FileUtilRt.createTempDirectory("inspections", "data", false);
Disposer.register(parentDisposable, () -> FileUtil.delete(tmpDir));
resultsDataPath = tmpDir.toPath();
@@ -4,11 +4,12 @@ package com.intellij.formatting.fileSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import java.util.Objects;
import java.util.regex.Pattern;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.regex.Pattern;
/**
* Describes a set of files specified by a directory and/or by a file mask.
* <p>
@@ -52,7 +53,7 @@ public class PatternDescriptor implements FileSetDescriptor {
if (lastSlashPos >= 0) {
fileSpec = spec.substring(lastSlashPos + 1);
pathSpec = spec.substring(0, lastSlashPos + 1);
if (pathSpec.length() > 0 && pathSpec.charAt(0) != '/') {
if (pathSpec.charAt(0) != '/') {
pathSpec = "/**/" + pathSpec;
}
}
@@ -48,11 +48,9 @@ public class BlockIndentOptions {
final Language language = block.getLanguage();
if (language != null) {
final CommonCodeStyleSettings commonSettings = mySettings.getCommonSettings(language);
if (commonSettings != null) {
final CommonCodeStyleSettings.IndentOptions result = commonSettings.getIndentOptions();
if (result != null) {
return result;
}
final CommonCodeStyleSettings.IndentOptions result = commonSettings.getIndentOptions();
if (result != null) {
return result;
}
}
@@ -109,8 +109,7 @@ public final class DataLanguageBlockWrapper implements ASTBlock, BlockEx, BlockW
children = new ArrayList<>(subWrappers);
}
else if (subWrappers.size() == 0) {
//noinspection unchecked
children = (List<Block>)(subWrappers.size() > 0 ? myTlBlocks : BlockUtil.splitBlockIntoFragments(myOriginal, myTlBlocks));
children = BlockUtil.splitBlockIntoFragments(myOriginal, myTlBlocks);
}
else {
children = BlockUtil.mergeBlocks(myTlBlocks, subWrappers);
@@ -33,7 +33,7 @@ public abstract class TemplateLanguageFormattingModelBuilder implements Delegati
protected Block getRootBlock(PsiElement element, FileViewProvider viewProvider, CodeStyleSettings settings) {
ASTNode node = element.getNode();
if (node == null) {
return createDummyBlock(node);
return createDummyBlock(null);
}
if (viewProvider instanceof TemplateLanguageFileViewProvider) {
final Language dataLanguage = ((TemplateLanguageFileViewProvider)viewProvider).getTemplateDataLanguage();
@@ -66,11 +66,6 @@ public final class WhiteSpaceFormattingStrategyFactory {
return strategies;
}
final Collection<Language> languages = Language.getRegisteredLanguages();
if (languages == null) {
final List<WhiteSpaceFormattingStrategy> result = Collections.emptyList();
myCachedStrategies.set(new PatchedWeakReference<>(result));
return result;
}
Set<WhiteSpaceFormattingStrategy> result = new HashSet<>(SHARED_STRATEGIES);
final LanguageWhiteSpaceFormattingStrategy languageStrategy = LanguageWhiteSpaceFormattingStrategy.INSTANCE;
@@ -65,7 +65,7 @@ public class IndentHelperImpl extends IndentHelper {
}
if (includeNonSpace) {
return getIndentInner(file, prev, includeNonSpace, recursionLevel + 1) + getIndent(file, text, includeNonSpace);
return getIndentInner(file, prev, true, recursionLevel + 1) + getIndent(file, text, true);
}
@@ -78,10 +78,10 @@ public class IndentHelperImpl extends IndentHelper {
}
if (parent == null) {
return getIndent(file, text, includeNonSpace);
return getIndent(file, text, false);
}
else {
return getIndentInner(file, prev, includeNonSpace, recursionLevel + 1);
return getIndentInner(file, prev, false, recursionLevel + 1);
}
}
else {
@@ -31,11 +31,10 @@ public interface Queryable {
}
final class Util {
@Nullable
public static @NonNls String print(@NotNull Queryable ui, @Nullable PrintInfo printInfo, @Nullable Contributor contributor) {
public static @NonNls @NotNull String print(@NotNull Queryable ui, @Nullable PrintInfo printInfo, @Nullable Contributor contributor) {
PrintInfo print = printInfo != null ? printInfo : new PrintInfo();
LinkedHashMap<String, String> map = new LinkedHashMap<>();
Map<String, String> map = new LinkedHashMap<>();
ui.putInfo(map);
if (contributor != null) {
@@ -44,14 +43,6 @@ public interface Queryable {
String id = null;
//String[] names = print.myIdKeys != null ? print.myIdKeys : new String[] {"name"};
//for (String eachKey : names) {
// String eachValue = map.get(eachKey);
// if (eachValue != null) {
// id = eachValue;
// }
//}
if (!map.isEmpty()) {
id = map.values().iterator().next();
}
@@ -72,8 +63,7 @@ public interface Queryable {
return id + (info.length() > 0 ? " " + info : "");
}
@Nullable
public static @NonNls String print(@NotNull Queryable ui, @Nullable PrintInfo printInfo) {
public static @NonNls @NotNull String print(@NotNull Queryable ui, @Nullable PrintInfo printInfo) {
return print(ui, printInfo, null);
}
}
@@ -181,7 +181,7 @@ public class TextChangesStorage {
));
return insertionIndex;
}
else if (insertionIndex > 0 && !myChanges.isEmpty()) {
else if (insertionIndex > 0) {
ChangeEntry changeEntry = myChanges.get(insertionIndex - 1);
clientShift = changeEntry.clientStartOffset - changeEntry.change.getStart() + changeEntry.change.getDiff();
}
@@ -429,7 +429,7 @@ public class TextChangesStorage {
break;
}
}
if (end >= clientStart && clientStart < clientEnd) {
if (clientStart < clientEnd) {
int changeTextStartOffset = start <= clientStart ? 0 : start - clientStart;
int length = Math.min(clientEnd, end) - Math.max(clientStart, start);
CharArrayUtil.getChars(changeEntry.change.getText(), data, changeTextStartOffset, outputOffset, length);
@@ -88,7 +88,6 @@ public final class KShortestPathsFinder<Node> {
root = heapNode;
}
}
LOG.assertTrue(root != null);
heapNodes.remove(root);
myOutRoots.put(node, root);
if (!heapNodes.isEmpty()) {
@@ -187,11 +187,10 @@ public abstract class ActionGroup extends AnAction {
boolean dumbAware = super.isDumbAware();
if (dumbAware) {
myDumbAware = Boolean.TRUE;
} else {
if (myDumbAware == null) {
Class<?> declaringClass = ReflectionUtil.getMethodDeclaringClass(getClass(), "update", AnActionEvent.class);
myDumbAware = AnAction.class.equals(declaringClass) || ActionGroup.class.equals(declaringClass);
}
}
else {
Class<?> declaringClass = ReflectionUtil.getMethodDeclaringClass(getClass(), "update", AnActionEvent.class);
myDumbAware = AnAction.class.equals(declaringClass) || ActionGroup.class.equals(declaringClass);
}
return myDumbAware;
@@ -41,7 +41,7 @@ public class EditLogPatternDialog extends DialogWrapper {
myFilePattern.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
protected void textChanged(@NotNull DocumentEvent e) {
setOKActionEnabled(myFilePattern.getText() != null && myFilePattern.getText().length() > 0);
setOKActionEnabled(myFilePattern.getText().length() > 0);
}
});
return myWholePanel;
@@ -879,9 +879,8 @@ public final class ChooseRunConfigurationPopup implements ExecutorProvider {
}
}
@Nullable
@Override
public Icon getIcon() {
public @NotNull Icon getIcon() {
return AllIcons.Nodes.Folder;
}
@@ -110,7 +110,6 @@ public class ExternalSystemExecuteTaskTask extends AbstractExternalSystemTask {
));
}
}
assert result != null;
return result;
}
@@ -54,7 +54,7 @@ public class ExternalProjectsWorkspaceImpl implements PersistentStateComponent<E
@Override
public void loadState(@NotNull State state) {
myState = state == null ? new State() : state;
myState = state;
}
public static boolean isDependencySubstitutionEnabled() {
@@ -276,7 +276,7 @@ public final class LibraryDataService extends AbstractProjectDataService<Library
for (Map.Entry<OrderRootType, Set<String>> entry: toAdd.entrySet()) {
Map<OrderRootType, Collection<File>> roots = new HashMap<>();
roots.put(entry.getKey(), ContainerUtil.map(entry.getValue(), PATH_TO_FILE));
registerPaths(externalLibrary.isUnresolved(), roots, excludedPaths, libraryModel, externalLibrary.getInternalName());
registerPaths(false, roots, excludedPaths, libraryModel, externalLibrary.getInternalName());
}
}
}
@@ -573,7 +573,7 @@ public final class ExternalProjectDataSelectorDialog extends DialogWrapper {
}
}
if (!deps.isEmpty() && !selectedModules.isEmpty()) {
if (!deps.isEmpty()) {
final String message = checked ? getEnableMessage(selectedModules, deps) : getDisableMessage(deps);
if (Messages.showOkCancelDialog(message, checked ? ExternalSystemBundle.message("enable.dependant.modules")
: ExternalSystemBundle.message("disable.modules.with.dependency.on.this"),
@@ -90,9 +90,8 @@ public class SelectExternalSystemNodeDialog extends DialogWrapper {
};
Disposer.register(myDisposable, treeStructure);
treeStructure.init(new ExternalProjectsViewAdapter(projectsView) {
@Nullable
@Override
public ExternalProjectsStructure getStructure() {
public @NotNull ExternalProjectsStructure getStructure() {
return treeStructure;
}
@@ -61,7 +61,7 @@ final class PanelContentUI implements ContentUI {
return JBIterable.of(myContentManager.getContents())
.map(content -> {
JComponent component = content.getComponent();
return component != null && myPanel != component.getParent() ? component : null;
return myPanel != component.getParent() ? component : null;
})
.filter(Conditions.notNull())
.iterator();
@@ -78,9 +78,8 @@ public final class UnknownSdkType extends SdkType {
}
}
@Nullable
@Override
public SdkAdditionalData loadAdditionalData(@NotNull Element additional) {
public @NotNull SdkAdditionalData loadAdditionalData(@NotNull Element additional) {
return new UnknownSdkAdditionalData(additional);
}
@@ -113,15 +113,9 @@ public abstract class CodeStyleDeriveProcessor {
values = cvalues;
}
if (indentOptions != null) {
List<Value> valuesOrder = readAll("indentOptions", indentOptions);
valuesOrder.addAll(values);
return valuesOrder;
}
else {
Utils.logError("Indent options were not detected.");
return values;
}
List<Value> valuesOrder = readAll("indentOptions", indentOptions);
valuesOrder.addAll(values);
return valuesOrder;
}
@NotNull
@@ -33,5 +33,4 @@ label.tool.program=Program:
checkbox.synchronize.files.after.execution=Synchronize files after execution
border.title.tool.settings=Tool Settings
label.tool.working.directory=Working directory:
dialog.separator.advanced.options=Advanced Options
tools.node.group.name.unnamed.group=[unnamed group]
dialog.separator.advanced.options=Advanced Options
@@ -101,6 +101,6 @@ public class DaemonTooltipRendererProvider implements ErrorStripTooltipRendererP
return new DaemonTooltipWithActionRenderer(text, action, width, action == null ? new Object[]{text} : new Object[]{text, action});
}
return ErrorStripTooltipRendererProvider.super.calcTooltipRenderer(text, action, width);
return ErrorStripTooltipRendererProvider.super.calcTooltipRenderer(text, null, width);
}
}

Some files were not shown because too many files have changed in this diff Show More