:: Try (in order): @@product_uc@@_JDK, @@vm_options@@.jdk, ..\jre, JDK_HOME, JAVA_HOME.
:: ---------------------------------------------------------------------
SET JDK=
-IF EXIST "%@@product_uc@@_JDK%" (
- SET JDK=%@@product_uc@@_JDK%
-)
-IF "%JDK%" == "" (
- SET BITS=64
- SET USER_JDK64_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
- SET BITS=
- SET USER_JDK_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
- IF EXIST "%USER_JDK64_FILE%" (
- SET /P JDK=<%USER_JDK64_FILE%
- IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
- ) ELSE (
- IF EXIST "%USER_JDK_FILE%" (
- SET /P JDK=<%USER_JDK_FILE%
- IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
- )
- )
-)
-IF "%JDK%" == "" (
- IF EXIST "%IDE_HOME%\jre" SET JDK=%IDE_HOME%\jre
-)
-IF "%JDK%" == "" (
- IF EXIST "%JDK_HOME%" SET JDK=%JDK_HOME%
+
+IF EXIST "%@@product_uc@@_JDK%" SET JDK=%@@product_uc@@_JDK%
+IF NOT "%JDK%" == "" GOTO check
+
+SET BITS=64
+SET USER_JDK64_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
+SET BITS=
+SET USER_JDK_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
+IF EXIST "%USER_JDK64_FILE%" (
+ SET /P JDK=<%USER_JDK64_FILE%
+) ELSE (
+ IF EXIST "%USER_JDK_FILE%" SET /P JDK=<%USER_JDK_FILE%
)
-IF "%JDK%" == "" (
- IF EXIST "%JAVA_HOME%" SET JDK=%JAVA_HOME%
+IF NOT "%JDK%" == "" (
+ IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
+ GOTO check
)
+IF EXIST "%IDE_HOME%\jre" SET JDK=%IDE_HOME%\jre
+IF NOT "%JDK%" == "" GOTO check
+
+IF EXIST "%JDK_HOME%" SET JDK=%JDK_HOME%
+IF NOT "%JDK%" == "" GOTO check
+
+IF EXIST "%JAVA_HOME%" SET JDK=%JAVA_HOME%
+
+:check
SET JAVA_EXE=%JDK%\bin\java.exe
IF NOT EXIST "%JAVA_EXE%" SET JAVA_EXE=%JDK%\jre\bin\java.exe
IF NOT EXIST "%JAVA_EXE%" (
import com.intellij.debugger.engine.JVMNameUtil;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
-import com.intellij.psi.CommonClassNames;
+import com.intellij.psi.PsiPrimitiveType;
+import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
import com.sun.jdi.*;
-import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
return result;
}
- if (result instanceof BooleanValue) {
- return convertToWrapper(context, (BooleanValue)result, CommonClassNames.JAVA_LANG_BOOLEAN);
- }
- if (result instanceof ByteValue) {
- return convertToWrapper(context, (ByteValue)result, CommonClassNames.JAVA_LANG_BYTE);
- }
- if (result instanceof CharValue) {
- return convertToWrapper(context, (CharValue)result, CommonClassNames.JAVA_LANG_CHARACTER);
- }
- if (result instanceof ShortValue) {
- return convertToWrapper(context, (ShortValue)result, CommonClassNames.JAVA_LANG_SHORT);
- }
- if (result instanceof IntegerValue) {
- return convertToWrapper(context, (IntegerValue)result, CommonClassNames.JAVA_LANG_INTEGER);
- }
- if (result instanceof LongValue) {
- return convertToWrapper(context, (LongValue)result, CommonClassNames.JAVA_LANG_LONG);
- }
- if (result instanceof FloatValue) {
- return convertToWrapper(context, (FloatValue)result, CommonClassNames.JAVA_LANG_FLOAT);
- }
- if (result instanceof DoubleValue) {
- return convertToWrapper(context, (DoubleValue)result, CommonClassNames.JAVA_LANG_DOUBLE);
+ if (result instanceof PrimitiveValue) {
+ PrimitiveValue primitiveValue = (PrimitiveValue)result;
+ PsiPrimitiveType primitiveType = PsiJavaParserFacadeImpl.getPrimitiveType(primitiveValue.type().name());
+ if (primitiveType != null) {
+ return convertToWrapper(context, primitiveValue, primitiveType.getBoxedTypeName());
+ }
}
throw new EvaluateException("Cannot perform boxing conversion for a value of type " + ((Value)result).type().name());
}
*/
package com.intellij.debugger.jdi;
+import com.intellij.util.ReflectionUtil;
import com.intellij.util.ThrowableConsumer;
import com.sun.jdi.*;
import org.jetbrains.annotations.NotNull;
visit(classType, method, bytecodes, methodVisitor);
}
+ public static byte[] getConstantPool(ReferenceType type) {
+ try {
+ return type.constantPool();
+ }
+ catch (NullPointerException e) { // workaround for JDK bug 6822627
+ ReflectionUtil.resetField(type, "constantPoolInfoGotten");
+ return type.constantPool();
+ }
+ }
+
private static void visit(ReferenceType type, Method method, byte[] bytecodes, MethodVisitor methodVisitor) {
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) {
dos.writeInt(0xCAFEBABE); // magic
dos.writeInt(Opcodes.V1_8); // version
dos.writeShort(type.constantPoolCount()); // constant_pool_count
- dos.write(type.constantPool()); // constant_pool
+ dos.write(getConstantPool(type)); // constant_pool
dos.writeShort(0); // access_flags;
dos.writeShort(0); // this_class;
dos.writeShort(0); // super_class;
import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
+import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.reference.SoftReference;
import org.jetbrains.annotations.Nullable;
protected Cache initEvaluatorAndChildrenExpression(final Project project) {
final Cache cache = new Cache();
try {
- PsiClass contextClass = DebuggerUtils.findClass(getClassName(), project, GlobalSearchScope.allScope(project));
- if (contextClass instanceof PsiCompiledElement) {
- contextClass = (PsiClass)((PsiCompiledElement)contextClass).getMirror();
+ String className = getClassName();
+ PsiClass contextClass;
+ PsiType contextType;
+ PsiPrimitiveType primitiveType = PsiJavaParserFacadeImpl.getPrimitiveType(className);
+ if (primitiveType != null) {
+ contextClass = JavaPsiFacade.getInstance(project).findClass(primitiveType.getBoxedTypeName(), GlobalSearchScope.allScope(project));
+ contextType = primitiveType;
}
- if(contextClass == null) {
- throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS;
+ else {
+ contextClass = DebuggerUtils.findClass(className, project, GlobalSearchScope.allScope(project));
+ if (contextClass instanceof PsiCompiledElement) {
+ contextClass = (PsiClass)((PsiCompiledElement)contextClass).getMirror();
+ }
+ if (contextClass == null) {
+ throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS;
+ }
+ contextType = DebuggerUtils.getType(className, project);
}
- final PsiType contextType = DebuggerUtils.getType(getClassName(), project);
cache.myPsiChildrenExpression = null;
JavaCodeFragment codeFragment = myDefaultFragmentFactory.createCodeFragment(myReferenceExpression, contextClass, project);
codeFragment.forceResolveScope(GlobalSearchScope.allScope(project));
import com.intellij.psi.util.ClassUtil;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.util.containers.ContainerUtil;
}
public static boolean instanceOf(@Nullable Type subType, @NotNull String superType) {
- if (subType == null || subType instanceof PrimitiveType || subType instanceof VoidType) {
+ if (subType == null || subType instanceof VoidType) {
return false;
}
+ if (subType instanceof PrimitiveType) {
+ return superType.equals(subType.name());
+ }
+
if (CommonClassNames.JAVA_LANG_OBJECT.equals(superType)) {
return true;
}
public static PsiType getType(@NotNull String className, @NotNull Project project) {
ApplicationManager.getApplication().assertReadAccessAllowed();
- final PsiManager psiManager = PsiManager.getInstance(project);
try {
if (getArrayClass(className) != null) {
- return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createTypeFromText(className, null);
+ return JavaPsiFacade.getInstance(project).getElementFactory().createTypeFromText(className, null);
}
- if(project.isDefault()) {
+ if (project.isDefault()) {
return null;
}
- final PsiClass aClass =
- JavaPsiFacade.getInstance(psiManager.getProject()).findClass(className.replace('$', '.'), GlobalSearchScope.allScope(project));
+ PsiClass aClass = findClass(className, project, GlobalSearchScope.allScope(project));
if (aClass != null) {
- return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(aClass);
+ return PsiTypesUtil.getClassType(aClass);
}
}
catch (IncorrectOperationException e) {
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.module.impl.scopes.ModulesScope;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
@Nullable
static HighlightInfo checkFileDuplicates(@NotNull PsiJavaModule element, @NotNull PsiFile file) {
- VirtualFile vFile = file.getVirtualFile();
- if (vFile != null) {
+ Module module = ModuleUtilCore.findModuleForPsiElement(element);
+ if (module != null) {
Project project = file.getProject();
- Module module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(vFile);
- if (module != null) {
- Collection<VirtualFile> others =
- FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(Collections.singleton(module), project));
- if (others.size() > 1) {
- String message = JavaErrorMessages.message("module.file.duplicate");
- HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range(element)).description(message).create();
- others.stream().map(f -> PsiManager.getInstance(project).findFile(f)).filter(f -> f != file).findFirst().ifPresent(
- duplicate -> QuickFixAction.registerQuickFixAction(info, new GoToSymbolFix(duplicate, JavaErrorMessages.message("module.open.duplicate.text")))
- );
- return info;
- }
+ Collection<VirtualFile> others =
+ FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(Collections.singleton(module), project));
+ if (others.size() > 1) {
+ String message = JavaErrorMessages.message("module.file.duplicate");
+ HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range(element)).description(message).create();
+ others.stream().map(f -> PsiManager.getInstance(project).findFile(f)).filter(f -> f != file).findFirst().ifPresent(
+ duplicate -> QuickFixAction.registerQuickFixAction(info, new GoToSymbolFix(duplicate, JavaErrorMessages.message("module.open.duplicate.text")))
+ );
+ return info;
}
}
@NonNls public static final String SHORT_NAME = HighlightInfoType.UNUSED_SYMBOL_SHORT_NAME;
@NonNls public static final String DISPLAY_NAME = HighlightInfoType.UNUSED_SYMBOL_DISPLAY_NAME;
@NonNls public static final String UNUSED_PARAMETERS_SHORT_NAME = "UnusedParameters";
+ @NonNls public static final String UNUSED_ID = "unused";
public boolean LOCAL_VARIABLE = true;
public boolean FIELD = true;
@NotNull
@NonNls
public String getID() {
- return "unused";
+ return UNUSED_ID;
}
@Override
*/
package com.intellij.codeInspection.deadCode;
-import com.intellij.codeInspection.ex.InspectionElementsMerger;
+import com.intellij.codeInspection.ex.InspectionElementsMergerBase;
import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
-public class UnusedDeclarationInspectionMerger extends InspectionElementsMerger {
+public class UnusedDeclarationInspectionMerger extends InspectionElementsMergerBase {
private static final String UNUSED_SYMBOL = "UNUSED_SYMBOL";
private static final String UNUSED_DECLARATION = "UnusedDeclaration";
clearUsedParameters(refMethod, result, checkDeep);
for (RefParameter parameter : result) {
- if (parameter != null && !((RefElementImpl)parameter).isSuppressed(UnusedSymbolLocalInspectionBase.UNUSED_PARAMETERS_SHORT_NAME)) {
+ if (parameter != null && !((RefElementImpl)parameter).isSuppressed(UnusedSymbolLocalInspectionBase.UNUSED_PARAMETERS_SHORT_NAME, UnusedSymbolLocalInspectionBase.UNUSED_ID)) {
res.add(parameter);
}
}
@Nullable
@Override
public String getAlternativeID() {
- return "unused";
+ return UnusedSymbolLocalInspectionBase.UNUSED_ID;
}
}
if (parent != null) {
final Indent defaultChildIndent = getChildIndent(parent, indentOptions);
if (defaultChildIndent != null) return defaultChildIndent;
- }
- if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
- return Indent.getNoneIndent();
+ if (parent.getPsi() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
+ return Indent.getNoneIndent();
+ }
}
return null;
}
private static void writeImport(@NotNull DataOutput out, IndexTree.Import anImport) throws IOException {
- SerializedUnit.writeQualifiedName(out, anImport.myFullname);
- boolean hasAlias = anImport.myAlias != 0;
+ out.writeInt(NameEnvironment.fromString(anImport.myQualifier));
+ boolean hasAlias = anImport.myAlias != null;
int flags = 0;
flags = BitUtil.set(flags, IS_STATIC, anImport.myStaticImport);
flags = BitUtil.set(flags, IS_ON_DEMAND, anImport.myOnDemand);
flags = BitUtil.set(flags, HAS_ALIAS, hasAlias);
out.writeByte(flags);
+ if (anImport.myImportedName != null) {
+ out.writeInt(NameEnvironment.hashIdentifier(anImport.myImportedName));
+ }
if (hasAlias) {
- out.writeInt(anImport.myAlias);
+ out.writeInt(NameEnvironment.hashIdentifier(anImport.myAlias));
}
}
private Import readImport(UnitInputStream in) throws IOException {
- int qualifier = 0;
- int len = DataInputOutputUtil.readINT(in);
- for (int i = 0; i < len - 1; i++) {
- qualifier = in.names.qualifiedName(qualifier, in.readInt());
- }
- int lastId = in.readInt();
+ int qualifier = in.readInt();
int flags = in.readByte();
+ int shortName = BitUtil.isSet(flags, IS_ON_DEMAND) ? 0 : in.readInt();
int alias = BitUtil.isSet(flags, HAS_ALIAS) ? in.readInt() : 0;
- boolean onDemand = BitUtil.isSet(flags, IS_ON_DEMAND);
- boolean isStatic = BitUtil.isSet(flags, IS_STATIC);
-
- int shortName;
- if (onDemand) {
- shortName = 0;
- qualifier = in.names.qualifiedName(qualifier, lastId);
- } else {
- shortName = lastId;
- }
-
- return obtainImport(qualifier, shortName, alias, isStatic);
+ return obtainImport(qualifier, shortName, alias, BitUtil.isSet(flags, IS_STATIC));
}
private Import obtainImport(int qualifier, int shortName, int alias, boolean isStatic) {
package com.intellij.psi.stubsHierarchy.impl;
import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.CommonClassNames;
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-import com.intellij.util.io.DataInputOutputUtil;
+import com.intellij.psi.PsiNameHelper;
+import com.intellij.util.ArrayUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
+import java.util.List;
class NameEnvironment extends UserDataHolderBase {
- public static final int OBJECT_NAME = IndexTree.hashIdentifier("Object");
- public static final int NO_NAME = 0;
- @QNameHash final int java_lang;
- public final QualifiedName java_lang_Enum;
- public final QualifiedName java_lang_annotation_Annotation;
+ static final int OBJECT_NAME = hashIdentifier("Object");
+ static final int NO_NAME = 0;
+ @QNameHash final static int java_lang = fromString("java.lang");
+ static final QualifiedName java_lang_Enum = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ENUM));
+ static final QualifiedName java_lang_annotation_Annotation =
+ new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION));
- NameEnvironment() {
- java_lang = fromString("java.lang");
- java_lang_Enum = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ENUM));
- java_lang_annotation_Annotation = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION));
- }
-
- @QNameHash int fromString(String s) {
+ static @QNameHash int fromString(String s) {
int id = 0;
- for (int shortName : IndexTree.hashQualifiedName(s)) {
+ for (int shortName : hashQualifiedName(s)) {
id = qualifiedName(id, shortName);
}
return id;
}
- /**
- * @see SerializedUnit#writeQualifiedName(DataOutput, int[])
- */
- @QNameHash int readQualifiedName(DataInput in) throws IOException {
- int id = 0;
- int len = DataInputOutputUtil.readINT(in);
- for (int i = 0; i < len; i++) {
- id = qualifiedName(id, in.readInt());
+ static int hashIdentifier(@Nullable String s) {
+ if (StringUtil.isEmpty(s)) return 0;
+
+ // not using String.hashCode because this way there's less collisions for short package names like 'com'
+ int hash = 0;
+ for (int i = 0; i < s.length(); i++) {
+ hash = hash * 239 + s.charAt(i);
}
- return id;
+ return hash == 0 ? 1 : hash;
+ }
+
+ static int[] hashQualifiedName(@NotNull String qName) {
+ qName = PsiNameHelper.getQualifiedClassName(qName, true);
+ if (qName.isEmpty()) return ArrayUtil.EMPTY_INT_ARRAY;
+
+ List<String> components = StringUtil.split(qName, ".");
+ int[] result = new int[components.size()];
+ for (int i = 0; i < components.size(); i++) {
+ result[i] = hashIdentifier(components.get(i));
+ }
+ return result;
}
- int memberQualifiedName(@QNameHash int ownerName, @ShortName int name) {
+ static int memberQualifiedName(@QNameHash int ownerName, @ShortName int name) {
return name == NO_NAME || ownerName == 0 ? 0 : qualifiedName(ownerName, name);
}
- @QNameHash int qualifiedName(@QNameHash int prefix, @ShortName int shortName) {
+ static @QNameHash int qualifiedName(@QNameHash int prefix, @ShortName int shortName) {
int hash = prefix * 31 + shortName;
return hash == 0 ? 1 : hash;
}
}
}
- /**
- * @see NameEnvironment#readQualifiedName(DataInput)
- */
- static void writeQualifiedName(DataOutput out, @QNameHash int[] array) throws IOException {
+ private static void writeNameComponents(DataOutput out, String qName) throws IOException {
+ int[] array = NameEnvironment.hashQualifiedName(qName);
DataInputOutputUtil.writeINT(out, array.length);
for (int i : array) {
out.writeInt(i);
// unit
private static void writeUnit(@NotNull DataOutput out, IndexTree.Unit value) throws IOException {
- writeQualifiedName(out, value.myPackageName);
+ writeNameComponents(out, value.myPackageName);
out.writeByte(value.myUnitType);
- if (value.myUnitType != IndexTree.BYTECODE) {
+ boolean compiled = value.myUnitType == IndexTree.BYTECODE;
+ if (!compiled) {
Imports.writeImports(out, value);
}
// class Declaration
DataInputOutputUtil.writeINT(out, value.myDecls.length);
for (IndexTree.ClassDecl def : value.myDecls) {
- saveClassDecl(out, def);
+ saveClassDecl(out, def, compiled);
}
}
// class
- private static void saveClassDecl(@NotNull DataOutput out, IndexTree.ClassDecl value) throws IOException {
+ private static void saveClassDecl(@NotNull DataOutput out, IndexTree.ClassDecl value, boolean compiled) throws IOException {
DataInputOutputUtil.writeINT(out, value.myStubId);
DataInputOutputUtil.writeINT(out, value.myMods);
- out.writeInt(value.myName);
- writeSupers(out, value);
- writeMembers(out, value.myDecls);
+ out.writeInt(NameEnvironment.hashIdentifier(value.myName));
+ writeSupers(out, value, compiled);
+ writeMembers(out, value.myDecls, compiled);
}
private static ClassSymbol readClassDecl(UnitInputStream in, UnitInfo info, Symbol owner, @QNameHash int ownerName) throws IOException {
@ShortName int name = in.readInt();
@CompactArray(QualifiedName.class) Object superNames = readSupers(in, info.isCompiled());
- @QNameHash int qname = in.names.memberQualifiedName(ownerName, name);
+ @QNameHash int qname = NameEnvironment.memberQualifiedName(ownerName, name);
ClassSymbol symbol = in.stubEnter.classEnter(info, owner, stubId, mods, name, superNames, qname, in.fileId);
readMembers(in, info, qname, symbol);
// supers
- private static void writeSupers(@NotNull DataOutput out, IndexTree.ClassDecl value) throws IOException {
+ private static void writeSupers(@NotNull DataOutput out, IndexTree.ClassDecl value, boolean interned) throws IOException {
DataInputOutputUtil.writeINT(out, value.mySupers.length);
- for (int[] aSuper : value.mySupers) {
- writeQualifiedName(out, aSuper);
+ for (String aSuper : value.mySupers) {
+ writeSuperName(out, interned, aSuper);
}
}
return superNames;
}
+ private static void writeSuperName(@NotNull DataOutput out, boolean interned, String aSuper) throws IOException {
+ if (interned) {
+ out.writeInt(NameEnvironment.fromString(aSuper));
+ } else {
+ writeNameComponents(out, aSuper);
+ }
+ }
+
private static QualifiedName readSuperName(UnitInputStream in, boolean intern) throws IOException {
- return intern ? new QualifiedName.Interned(in.names.readQualifiedName(in)) : readNameComponents(in);
+ return intern ? new QualifiedName.Interned(in.readInt()) : readNameComponents(in);
}
// members
- private static void writeMembers(@NotNull DataOutput out, IndexTree.Decl[] decls) throws IOException {
+ private static void writeMembers(@NotNull DataOutput out, IndexTree.Decl[] decls, boolean compiled) throws IOException {
DataInputOutputUtil.writeINT(out, decls.length);
for (IndexTree.Decl def : decls) {
- saveDecl(out, def);
+ saveDecl(out, def, compiled);
}
}
// decl: class or member
- private static void saveDecl(@NotNull DataOutput out, IndexTree.Decl value) throws IOException {
+ private static void saveDecl(@NotNull DataOutput out, IndexTree.Decl value, boolean compiled) throws IOException {
if (value instanceof IndexTree.ClassDecl) {
out.writeBoolean(true);
- saveClassDecl(out, (IndexTree.ClassDecl)value);
+ saveClassDecl(out, (IndexTree.ClassDecl)value, compiled);
} else if (value instanceof IndexTree.MemberDecl) {
out.writeBoolean(false);
- writeMembers(out, ((IndexTree.MemberDecl)value).myDecls);
+ writeMembers(out, ((IndexTree.MemberDecl)value).myDecls, compiled);
}
}
class UnitInputStream extends DataInputStream {
final int fileId;
final StubEnter stubEnter;
- final NameEnvironment names;
UnitInputStream(InputStream in, int fileId, StubEnter stubEnter) {
super(in);
this.fileId = fileId;
this.stubEnter = stubEnter;
- this.names = stubEnter.myNameEnvironment;
}
}
import static com.intellij.psi.stubsHierarchy.impl.Symbol.PackageSymbol;
public class StubEnter {
- final NameEnvironment myNameEnvironment;
final Imports imports = new Imports();
private final Symbols mySymbols;
private final StubHierarchyConnector myStubHierarchyConnector;
private ArrayList<ClassSymbol> uncompleted = new ArrayList<ClassSymbol>();
StubEnter(Symbols symbols) {
- myNameEnvironment = symbols.myNameEnvironment;
mySymbols = symbols;
- myStubHierarchyConnector = new StubHierarchyConnector(myNameEnvironment, symbols);
+ myStubHierarchyConnector = new StubHierarchyConnector(symbols);
}
PackageSymbol readPackageName(DataInput in) throws IOException {
int len = DataInputOutputUtil.readINT(in);
for (int i = 0; i < len; i++) {
int shortName = in.readInt();
- qname = myNameEnvironment.qualifiedName(qname, shortName);
+ qname = NameEnvironment.qualifiedName(qname, shortName);
pkg = mySymbols.enterPackage(qname, shortName, pkg);
}
return pkg;
@CompactArray(QualifiedName.class)
Object handleSpecialSupers(int flags, @CompactArray(QualifiedName.class) Object superNames) {
if (BitUtil.isSet(flags, IndexTree.ANNOTATION)) {
- return myNameEnvironment.java_lang_annotation_Annotation;
+ return NameEnvironment.java_lang_annotation_Annotation;
}
if (BitUtil.isSet(flags, IndexTree.ENUM)) {
- if (superNames == null) return myNameEnvironment.java_lang_Enum;
- if (superNames instanceof QualifiedName) return new QualifiedName[]{(QualifiedName)superNames, myNameEnvironment.java_lang_Enum};
- return ArrayUtil.append((QualifiedName[])superNames, myNameEnvironment.java_lang_Enum);
+ if (superNames == null) return NameEnvironment.java_lang_Enum;
+ if (superNames instanceof QualifiedName) return new QualifiedName[]{(QualifiedName)superNames, NameEnvironment.java_lang_Enum};
+ return ArrayUtil.append((QualifiedName[])superNames, NameEnvironment.java_lang_Enum);
}
return superNames;
import java.util.Set;
public class StubHierarchyConnector {
- private final NameEnvironment myNameEnvironment;
private final StubResolver myResolve;
- protected StubHierarchyConnector(NameEnvironment nameEnvironment, Symbols symbols) {
- this.myNameEnvironment = nameEnvironment;
+ protected StubHierarchyConnector(Symbols symbols) {
myResolve = new StubResolver(symbols, this);
}
c.setSupers(supertypes);
}
- private boolean isJavaLangObject(Symbol s) {
+ private static boolean isJavaLangObject(Symbol s) {
return s.myShortName == NameEnvironment.OBJECT_NAME &&
s.myOwner instanceof Symbol.PackageSymbol &&
- ((Symbol.PackageSymbol)s.myOwner).myQualifiedName == myNameEnvironment.java_lang;
+ ((Symbol.PackageSymbol)s.myOwner).myQualifiedName == NameEnvironment.java_lang;
}
}
@Override
public int getVersion() {
- return IndexTree.STUB_HIERARCHY_ENABLED ? 7 + Arrays.stream(ourIndexers).mapToInt(StubHierarchyIndexer::getVersion).sum() : 0;
+ return IndexTree.STUB_HIERARCHY_ENABLED ? 8 + Arrays.stream(ourIndexers).mapToInt(StubHierarchyIndexer::getVersion).sum() : 0;
}
@NotNull
*/
package com.intellij.psi.stubsHierarchy.impl;
+import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Set;
public class StubResolver {
+ private static final Import[] DEFAULT_JAVA_IMPORTS = {importPackage("java.lang")};
+ private static final Import[] DEFAULT_GROOVY_IMPORTS = {
+ importPackage("java.lang"),
+ importPackage("java.util"),
+ importPackage("java.io"),
+ importPackage("java.net"),
+ importPackage("groovy.lang"),
+ importPackage("groovy.util"),
+ new Import(NameEnvironment.fromString("java.math"), NameEnvironment.hashIdentifier("BigInteger"), false),
+ new Import(NameEnvironment.fromString("java.math"), NameEnvironment.hashIdentifier("BigDecimal"), false),
+ };
private final Symbols mySymbols;
- private final NameEnvironment myNameEnvironment;
private final StubHierarchyConnector myConnector;
public StubResolver(Symbols symbols, StubHierarchyConnector connector) {
this.mySymbols = symbols;
- this.myNameEnvironment = symbols.myNameEnvironment;
myConnector = connector;
}
+ private static Import importPackage(String qname) {
+ return new Import(NameEnvironment.fromString(qname), 0, false);
+ }
+
+ private static Import[] getDefaultImports(byte type) {
+ if (type == IndexTree.JAVA) return DEFAULT_JAVA_IMPORTS;
+ if (type == IndexTree.GROOVY) return DEFAULT_GROOVY_IMPORTS;
+ return Imports.EMPTY_ARRAY;
+ }
+
// resolve class `sym` extends/implements `baseId`
Set<Symbol> resolveBase(Symbol.ClassSymbol sym, @ShortName int[] qname) throws IncompleteHierarchyException {
Set<Symbol> result = resolveUnqualified(sym, qname[0], qname.length > 1);
}
private void findIdentInPackage(Symbol.PackageSymbol pck, @ShortName int name, boolean processPackages, Set<Symbol> symbols) {
- @QNameHash int fullname = mySymbols.myNameEnvironment.qualifiedName(pck.myQualifiedName, name);
+ @QNameHash int fullname = NameEnvironment.qualifiedName(pck.myQualifiedName, name);
if (processPackages) {
ContainerUtil.addIfNotNull(symbols, mySymbols.getPackage(fullname));
}
}
private void findGlobalType(UnitInfo info, @ShortName int name, Set<Symbol> symbols) throws IncompleteHierarchyException {
- for (Import anImport : Translator.getDefaultImports(info.type, myNameEnvironment))
+ for (Import anImport : getDefaultImports(info.type))
handleImport(anImport, name, symbols);
for (Import anImport : info.imports)
handleImport(anImport, name, symbols);
importNamedStatic(s, anImport.importedName, symbols);
}
else {
- Collections.addAll(symbols, findGlobalType(myNameEnvironment.qualifiedName(anImport.qualifier, anImport.importedName)));
+ Collections.addAll(symbols, findGlobalType(NameEnvironment.qualifiedName(anImport.qualifier, anImport.importedName)));
}
}
}
// handling of `import prefix.*`
private void importAll(@QNameHash int prefix, @ShortName int suffix, final Set<Symbol> symbols) {
- Collections.addAll(symbols, findGlobalType(myNameEnvironment.qualifiedName(prefix, suffix)));
+ Collections.addAll(symbols, findGlobalType(NameEnvironment.qualifiedName(prefix, suffix)));
}
// handling of import static `tsym.name` as
public class Symbols {
public final PackageSymbol myRootPackage = new PackageSymbol(null, 0, NameEnvironment.NO_NAME);
- protected final NameEnvironment myNameEnvironment = new NameEnvironment();
private final AnchorRepository myClassAnchors = new AnchorRepository();
private List<ClassSymbol> myClassSymbols = new ArrayList<>(0x8000);
+++ /dev/null
-/*
- * Copyright 2000-2016 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.psi.stubsHierarchy.impl;
-
-import com.intellij.openapi.util.Key;
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-
-public class Translator {
- private static final Key<Import[]> DEFAULT_JAVA_IMPORTS_KEY = Key.create("java_imports");
- private static final Key<Import[]> DEFAULT_GROOVY_IMPORTS_KEY = Key.create("groovy_imports");
-
- private static Import[] getDefaultJavaImports(NameEnvironment nameEnvironment) {
- Import[] imports = nameEnvironment.getUserData(DEFAULT_JAVA_IMPORTS_KEY);
- if (imports == null) {
- imports = createDefaultJavaImports(nameEnvironment);
- nameEnvironment.putUserData(DEFAULT_JAVA_IMPORTS_KEY, imports);
- }
- return imports;
- }
-
- private static Import[] createDefaultJavaImports(NameEnvironment nameEnvironment) {
- return new Import[]{
- importPackage(nameEnvironment, "java.lang")
- };
- }
-
- private static Import[] getDefaultGroovyImports(NameEnvironment nameEnvironment) {
- Import[] imports = nameEnvironment.getUserData(DEFAULT_GROOVY_IMPORTS_KEY);
- if (imports == null) {
- imports = createDefaultGroovyImports(nameEnvironment);
- nameEnvironment.putUserData(DEFAULT_GROOVY_IMPORTS_KEY, imports);
- }
- return imports;
- }
-
- private static Import[] createDefaultGroovyImports(NameEnvironment nameEnvironment) {
- return new Import[] {
- importPackage(nameEnvironment, "java.lang"),
- importPackage(nameEnvironment, "java.util"),
- importPackage(nameEnvironment, "java.io"),
- importPackage(nameEnvironment, "java.net"),
- importPackage(nameEnvironment, "groovy.lang"),
- importPackage(nameEnvironment, "groovy.util"),
- new Import(nameEnvironment.fromString("java.math"), IndexTree.hashIdentifier("BigInteger"), false),
- new Import(nameEnvironment.fromString("java.math"), IndexTree.hashIdentifier("BigDecimal"), false),
- };
- }
-
- private static Import importPackage(NameEnvironment nameEnvironment, String qname) {
- return new Import(nameEnvironment.fromString(qname), 0, false);
- }
-
- public static Import[] getDefaultImports(byte type, NameEnvironment nameEnvironment) {
- if (type == IndexTree.JAVA)
- return getDefaultJavaImports(nameEnvironment);
- if (type == IndexTree.GROOVY)
- return getDefaultGroovyImports(nameEnvironment);
- return Imports.EMPTY_ARRAY;
- }
-
-}
*/
package com.intellij.psi.stubsHierarchy.impl;
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@interface QNameHash { }
/**
- * int hash of a qualified name part, produced by {@link IndexTree#hashIdentifier(String)}
+ * int hash of a qualified name part, produced by {@link NameEnvironment#hashIdentifier(String)}
*/
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE_USE)
/*
- * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
+ * Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.siyeh.ig.bugs;
+package com.intellij.psi.impl.java.stubs;
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
+import com.intellij.psi.PsiFunctionalExpression;
+import com.intellij.psi.stubs.IStubElementType;
+import com.intellij.psi.stubs.StubBase;
+import com.intellij.psi.stubs.StubElement;
-public class MisspelledCompareToInspection extends MisspelledCompareToInspectionBase {
-
- @Override
- protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix(HardcodedMethodConstants.COMPARE_TO);
+public class FunctionalExpressionStub<T extends PsiFunctionalExpression> extends StubBase<T> {
+ protected FunctionalExpressionStub(StubElement parent,
+ IStubElementType elementType) {
+ super(parent, elementType);
}
}
\ No newline at end of file
JavaAnnotationParameterListType ANNOTATION_PARAMETER_LIST = new JavaAnnotationParameterListType();
JavaNameValuePairType NAME_VALUE_PAIR = new JavaNameValuePairType();
JavaLiteralExpressionElementType LITERAL_EXPRESSION = new JavaLiteralExpressionElementType();
+ LambdaExpressionElementType LAMBDA_EXPRESSION = new LambdaExpressionElementType();
+ MethodReferenceElementType METHOD_REFERENCE = new MethodReferenceElementType();
JavaParameterListElementType PARAMETER_LIST = new JavaParameterListElementType();
JavaParameterElementType PARAMETER = new JavaParameterElementType();
JavaTypeParameterElementType TYPE_PARAMETER = new JavaTypeParameterElementType();
};
IStubFileElementType JAVA_FILE = new JavaFileElementType();
-}
\ No newline at end of file
+}
--- /dev/null
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.impl.java.stubs;
+
+import com.intellij.lang.ASTNode;
+import com.intellij.lang.LighterAST;
+import com.intellij.lang.LighterASTNode;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiLambdaExpression;
+import com.intellij.psi.impl.source.tree.*;
+import com.intellij.psi.impl.source.tree.java.PsiLambdaExpressionImpl;
+import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
+import com.intellij.psi.stubs.*;
+import com.intellij.psi.tree.IElementType;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+
+public class LambdaExpressionElementType extends JavaStubElementType<FunctionalExpressionStub<PsiLambdaExpression>,PsiLambdaExpression> {
+ public LambdaExpressionElementType() {
+ super("LAMBDA_EXPRESSION");
+ }
+
+ @Override
+ public PsiLambdaExpression createPsi(@NotNull ASTNode node) {
+ return new PsiLambdaExpressionImpl(node);
+ }
+
+ @Override
+ public FunctionalExpressionStub<PsiLambdaExpression> createStub(LighterAST tree, LighterASTNode node, StubElement parentStub) {
+ return new FunctionalExpressionStub<PsiLambdaExpression>(parentStub, this);
+ }
+
+ @Override
+ public PsiLambdaExpression createPsi(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub) {
+ return new PsiLambdaExpressionImpl(stub);
+ }
+
+ @Override
+ public void serialize(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub, @NotNull StubOutputStream dataStream) throws IOException {
+ }
+
+ @NotNull
+ @Override
+ public FunctionalExpressionStub<PsiLambdaExpression> deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
+ return new FunctionalExpressionStub<PsiLambdaExpression>(parentStub, this);
+ }
+
+ @Override
+ public void indexStub(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub, @NotNull IndexSink sink) {
+ }
+
+ @NotNull
+ @Override
+ public ASTNode createCompositeNode() {
+ return new CompositeElement(this) {
+ @Override
+ public void replaceChildInternal(@NotNull ASTNode child, @NotNull TreeElement newElement) {
+ if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType()) &&
+ ElementType.EXPRESSION_BIT_SET.contains(newElement.getElementType())) {
+ boolean needParenth = ReplaceExpressionUtil.isNeedParenthesis(child, newElement);
+ if (needParenth) {
+ newElement = JavaSourceUtil.addParenthToReplacedChild(JavaElementType.PARENTH_EXPRESSION, newElement, getManager());
+ }
+ }
+ super.replaceChildInternal(child, newElement);
+ }
+
+ @Override
+ public int getChildRole(ASTNode child) {
+ final IElementType elType = child.getElementType();
+ if (elType == JavaTokenType.ARROW) {
+ return ChildRole.ARROW;
+ } else if (elType == JavaElementType.PARAMETER_LIST) {
+ return ChildRole.PARAMETER_LIST;
+ } else if (elType == JavaElementType.CODE_BLOCK) {
+ return ChildRole.LBRACE;
+ } else {
+ return ChildRole.EXPRESSION;
+ }
+ }
+ };
+ }
+}
--- /dev/null
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.impl.java.stubs;
+
+import com.intellij.lang.ASTNode;
+import com.intellij.lang.LighterAST;
+import com.intellij.lang.LighterASTNode;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiMethodReferenceExpression;
+import com.intellij.psi.impl.source.tree.*;
+import com.intellij.psi.impl.source.tree.java.PsiMethodReferenceExpressionImpl;
+import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
+import com.intellij.psi.stubs.*;
+import com.intellij.psi.tree.IElementType;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+
+public class MethodReferenceElementType extends
+ JavaStubElementType<FunctionalExpressionStub<PsiMethodReferenceExpression>, PsiMethodReferenceExpression> {
+ public MethodReferenceElementType() {
+ super("METHOD_REF_EXPRESSION");
+ }
+
+ @Override
+ public PsiMethodReferenceExpression createPsi(@NotNull ASTNode node) {
+ return new PsiMethodReferenceExpressionImpl(node);
+ }
+
+ @Override
+ public FunctionalExpressionStub<PsiMethodReferenceExpression> createStub(LighterAST tree, LighterASTNode node, StubElement parentStub) {
+ return new FunctionalExpressionStub<PsiMethodReferenceExpression>(parentStub, this);
+ }
+
+ @Override
+ public PsiMethodReferenceExpression createPsi(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub) {
+ return new PsiMethodReferenceExpressionImpl(stub);
+ }
+
+ @Override
+ public void serialize(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub, @NotNull StubOutputStream dataStream) throws IOException {
+ }
+
+ @NotNull
+ @Override
+ public FunctionalExpressionStub<PsiMethodReferenceExpression> deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
+ return new FunctionalExpressionStub<PsiMethodReferenceExpression>(parentStub, this);
+ }
+
+ @Override
+ public void indexStub(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub, @NotNull IndexSink sink) {
+ }
+
+ @NotNull
+ @Override
+ public ASTNode createCompositeNode() {
+ return new CompositeElement(this) {
+ @Override
+ public void replaceChildInternal(@NotNull ASTNode child, @NotNull TreeElement newElement) {
+ if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType()) &&
+ ElementType.EXPRESSION_BIT_SET.contains(newElement.getElementType())) {
+ boolean needParenth = ReplaceExpressionUtil.isNeedParenthesis(child, newElement);
+ if (needParenth) {
+ newElement = JavaSourceUtil.addParenthToReplacedChild(JavaElementType.PARENTH_EXPRESSION, newElement, getManager());
+ }
+ }
+ super.replaceChildInternal(child, newElement);
+ }
+
+
+ @Override
+ public int getChildRole(ASTNode child) {
+ final IElementType elType = child.getElementType();
+ if (elType == JavaTokenType.DOUBLE_COLON) {
+ return ChildRole.DOUBLE_COLON;
+ } else if (elType == JavaTokenType.IDENTIFIER) {
+ return ChildRole.REFERENCE_NAME;
+ } else if (elType == JavaElementType.REFERENCE_EXPRESSION) {
+ return ChildRole.CLASS_REFERENCE;
+ }
+ return ChildRole.EXPRESSION;
+ }
+
+ };
+ }
+}
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.psi.PsiNameHelper;
-import com.intellij.util.ArrayUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
-import java.util.Arrays;
-import java.util.List;
-
public class IndexTree {
public static final boolean STUB_HIERARCHY_ENABLED = Registry.is("java.hierarchy.service");
public static final byte JAVA = 1;
public static final byte GROOVY = 2;
- public static int hashIdentifier(@Nullable String s) {
- if (StringUtil.isEmpty(s)) return 0;
-
- // not using String.hashCode because this way there's less collisions for short package names like 'com'
- int hash = 0;
- for (int i = 0; i < s.length(); i++) {
- hash = hash * 239 + s.charAt(i);
- }
- return hash == 0 ? 1 : hash;
- }
-
- public static int[] hashQualifiedName(@NotNull String qName) {
- qName = PsiNameHelper.getQualifiedClassName(qName, true);
- if (qName.isEmpty()) return ArrayUtil.EMPTY_INT_ARRAY;
-
- List<String> components = StringUtil.split(qName, ".");
- int[] result = new int[components.size()];
- for (int i = 0; i < components.size(); i++) {
- result[i] = hashIdentifier(components.get(i));
- }
- return result;
- }
-
- private static int[][] hashQualifiedNameArray(String[] supers) {
- int[][] superHashes = new int[supers.length][];
- for (int i = 0; i < supers.length; i++) {
- superHashes[i] = hashQualifiedName(supers[i]);
- }
- return superHashes;
- }
-
public static class Unit {
- @NotNull public final int[] myPackageName;
+ @NotNull public final String myPackageName;
public final byte myUnitType;
public final Import[] imports;
public final ClassDecl[] myDecls;
public Unit(@Nullable String packageName, byte unitType, Import[] imports, ClassDecl[] decls) {
- this(hashQualifiedName(StringUtil.notNullize(packageName)), unitType, imports, decls);
- }
-
- public Unit(@NotNull int[] packageName, byte unitType, Import[] imports, ClassDecl[] decls) {
- myPackageName = packageName;
+ myPackageName = StringUtil.notNullize(packageName);
myUnitType = unitType;
this.imports = imports;
myDecls = decls;
}
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Unit unit = (Unit)o;
-
- if (myUnitType != unit.myUnitType) return false;
- if (!Arrays.equals(myPackageName, unit.myPackageName)) return false;
- if (!Arrays.equals(imports, unit.imports)) return false;
- if (!Arrays.equals(myDecls, unit.myDecls)) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int hash = myUnitType * 31 + Arrays.hashCode(myPackageName);
- for (ClassDecl decl : myDecls) {
- int name = decl.myName;
- if (name != 0) {
- return hash * 31 + name;
- }
- }
- return hash;
- }
}
public static class Import {
public static final Import[] EMPTY_ARRAY = new Import[0];
- public final int[] myFullname;
+ @NotNull public final String myQualifier;
+ @Nullable public final String myImportedName;
public final boolean myStaticImport;
public final boolean myOnDemand;
- public final int myAlias;
+ @Nullable public final String myAlias;
public Import(String fullname, boolean staticImport, boolean onDemand, @Nullable String alias) {
- this(hashQualifiedName(fullname), staticImport, onDemand, hashIdentifier(alias));
- }
-
- public Import(int[] fullname, boolean staticImport, boolean onDemand, int alias) {
- myFullname = fullname;
+ myQualifier = onDemand ? fullname : StringUtil.getPackageName(fullname);
+ myImportedName = onDemand ? null : StringUtil.getShortName(fullname);
myStaticImport = staticImport;
myOnDemand = onDemand;
myAlias = alias;
}
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- Import anImport = (Import)o;
-
- if (myStaticImport != anImport.myStaticImport) return false;
- if (myOnDemand != anImport.myOnDemand) return false;
- if (!Arrays.equals(myFullname, anImport.myFullname)) return false;
- if (myAlias != anImport.myAlias) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = Arrays.hashCode(myFullname);
- result = 31 * result + (myStaticImport ? 1 : 0);
- result = 31 * result + (myOnDemand ? 1 : 0);
- result = 31 * result + myAlias;
- return result;
- }
}
public static abstract class Decl {
public static final ClassDecl[] EMPTY_ARRAY = new ClassDecl[0];
public final int myStubId;
public final int myMods;
- public final int myName;
- public final int[][] mySupers;
+ public final String myName;
+ public final String[] mySupers;
public ClassDecl(int stubId, int mods, @Nullable String name, String[] supers, Decl[] decls) {
- this(stubId, mods, hashIdentifier(name), hashQualifiedNameArray(supers), decls);
- }
-
- public ClassDecl(int stubId, int mods, int name, int[][] supers, Decl[] decls) {
super(decls);
assert stubId > 0;
myStubId = stubId;
mySupers = supers;
}
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- ClassDecl classDecl = (ClassDecl)o;
- if (myStubId != classDecl.myStubId) return false;
- if (myMods != classDecl.myMods) return false;
- if (myName != classDecl.myName) return false;
- if (!Arrays.deepEquals(mySupers, classDecl.mySupers)) return false;
- if (!Arrays.equals(myDecls, classDecl.myDecls)) return false;
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = myStubId;
- result = 31 * result + myMods;
- result = 31 * result + myName;
- return result;
- }
}
public static class MemberDecl extends Decl {
super(decls);
}
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- MemberDecl that = (MemberDecl)o;
- if (!Arrays.equals(myDecls, that.myDecls)) return false;
- return true;
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(myDecls);
- }
}
}
* @author max
*/
public class JavaFileElementType extends ILightStubFileElementType<PsiJavaFileStub> {
- public static final int STUB_VERSION = 26;
+ public static final int STUB_VERSION = 27;
public JavaFileElementType() {
super("java.FILE", JavaLanguage.INSTANCE);
@Override
@SuppressWarnings("LambdaUnfriendlyMethodOverload")
public void indexStub(@NotNull PsiJavaFileStub stub, @NotNull IndexSink sink) { }
-}
\ No newline at end of file
+}
private static class CodeBlockVisitor extends RecursiveTreeElementWalkingVisitor implements LighterLazyParseableNode.Visitor {
private static final TokenSet BLOCK_ELEMENTS = TokenSet.create(
- JavaElementType.ANNOTATION, JavaElementType.CLASS, JavaElementType.ANONYMOUS_CLASS);
+ JavaElementType.ANNOTATION, JavaElementType.CLASS, JavaElementType.ANONYMOUS_CLASS,
+ JavaElementType.LAMBDA_EXPRESSION, JavaElementType.METHOD_REF_EXPRESSION);
private boolean result = true;
return true;
}
- // annotations
- if (type == JavaTokenType.AT) {
+ // annotations, method refs & lambdas
+ if (type == JavaTokenType.AT || type == JavaTokenType.ARROW || type == JavaTokenType.DOUBLE_COLON) {
return (result = false);
}
// anonymous classes
return true;
}
}
-}
\ No newline at end of file
+}
}
@Nullable
- private static PsiElement calcBasesResolveContext(PsiClass aClass,
- String className,
+ private static PsiElement calcBasesResolveContext(PsiElement scope,
+ String baseClassName,
boolean isInitialClass,
final PsiElement defaultResolveContext) {
- final PsiClassStub stub = ((PsiClassImpl)aClass).getStub();
- if (stub == null || stub.isAnonymousInQualifiedNew()) {
- return aClass.getParent();
+ final StubElement stub = ((StubBasedPsiElementBase<?>)scope).getStub();
+ if (stub == null || stub instanceof PsiClassStub && ((PsiClassStub)stub).isAnonymousInQualifiedNew()) {
+ return scope.getParent();
}
- boolean isAnonOrLocal = isAnonymousOrLocal(aClass);
-
- if (!isAnonOrLocal) {
- return isInitialClass ? defaultResolveContext : aClass;
- }
+ if (scope instanceof PsiClass) {
+ if (!isAnonymousOrLocal((PsiClass)scope)) {
+ return isInitialClass ? defaultResolveContext : scope;
+ }
- if (!isInitialClass) {
- if (aClass.findInnerClassByName(className, true) != null) return aClass;
+ if (!isInitialClass) {
+ if (((PsiClass)scope).findInnerClassByName(baseClassName, true) != null) return scope;
+ }
}
final StubElement parentStub = stub.getParentStub();
LOG.error(stub + " parent is " + parentStub);
return null;
}
- final StubBasedPsiElementBase<?> context = (StubBasedPsiElementBase)psi;
- @SuppressWarnings("unchecked")
- PsiClass[] classesInScope = (PsiClass[])parentStub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY);
- boolean needPreciseContext = false;
- if (classesInScope.length > 1) {
- for (PsiClass scopeClass : classesInScope) {
- if (scopeClass == aClass) continue;
- String className1 = scopeClass.getName();
- if (className.equals(className1)) {
- needPreciseContext = true;
- break;
- }
- }
- }
- else {
- if (classesInScope.length != 1) {
- LOG.error("Parent stub: " + parentStub.getStubType() + "; children: " + parentStub.getChildrenStubs() + "; \ntext:" + context.getText());
- }
- LOG.assertTrue(classesInScope[0] == aClass);
+ if (hasChildClassStub(parentStub, baseClassName, scope)) {
+ return scope.getParent();
}
- if (needPreciseContext) {
- return aClass.getParent();
+ if (psi instanceof PsiClass || psi instanceof PsiLambdaExpression) {
+ return calcBasesResolveContext(psi, baseClassName, false, defaultResolveContext);
}
- else {
- if (context instanceof PsiClass) {
- return calcBasesResolveContext((PsiClass)context, className, false, defaultResolveContext);
- }
- else if (context instanceof PsiMember) {
- return calcBasesResolveContext(((PsiMember)context).getContainingClass(), className, false, defaultResolveContext);
+ if (psi instanceof PsiMember) {
+ return calcBasesResolveContext(((PsiMember)psi).getContainingClass(), baseClassName, false, defaultResolveContext);
+ }
+ LOG.error(parentStub);
+ return psi;
+ }
+
+ private static boolean hasChildClassStub(StubElement parentStub, String className, PsiElement place) {
+ PsiClass[] classesInScope = (PsiClass[])parentStub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY);
+
+ for (PsiClass scopeClass : classesInScope) {
+ if (scopeClass == place) continue;
+ if (className.equals(scopeClass.getName())) {
+ return true;
}
- else {
- LOG.assertTrue(false);
- return context;
+ }
+
+ if (place instanceof PsiClass) {
+ if (classesInScope.length == 0) {
+ LOG.error("Parent stub: " + parentStub.getStubType() + "; children: " + parentStub.getChildrenStubs() + "; \ntext:" + parentStub.getPsi().getText());
}
+ LOG.assertTrue(Arrays.asList(classesInScope).contains(place));
}
+ return false;
}
@Override
IElementType EXTENDS_BOUND_LIST = JavaStubElementTypes.EXTENDS_BOUND_LIST;
IElementType THROWS_LIST = JavaStubElementTypes.THROWS_LIST;
IElementType MODULE = JavaStubElementTypes.MODULE;
+ IElementType LAMBDA_EXPRESSION = JavaStubElementTypes.LAMBDA_EXPRESSION;
+ IElementType METHOD_REF_EXPRESSION = JavaStubElementTypes.METHOD_REFERENCE;
IElementType IMPORT_STATIC_REFERENCE = new JavaCompositeElementType("IMPORT_STATIC_REFERENCE", PsiImportStaticReferenceElementImpl.class);
IElementType TYPE = new JavaCompositeElementType("TYPE", PsiTypeElementImpl.class);
IElementType INSTANCE_OF_EXPRESSION = new JavaCompositeElementType("INSTANCE_OF_EXPRESSION", PsiInstanceOfExpressionImpl.class);
IElementType CLASS_OBJECT_ACCESS_EXPRESSION = new JavaCompositeElementType("CLASS_OBJECT_ACCESS_EXPRESSION", PsiClassObjectAccessExpressionImpl.class);
IElementType EMPTY_EXPRESSION = new JavaCompositeElementType("EMPTY_EXPRESSION", PsiEmptyExpressionImpl.class, true);
- IElementType METHOD_REF_EXPRESSION = new JavaCompositeElementType("METHOD_REF_EXPRESSION", PsiMethodReferenceExpressionImpl.class);
- IElementType LAMBDA_EXPRESSION = new JavaCompositeElementType("LAMBDA_EXPRESSION", PsiLambdaExpressionImpl.class);
IElementType EXPRESSION_LIST = new JavaCompositeElementType("EXPRESSION_LIST", PsiExpressionListImpl.class, true);
IElementType EMPTY_STATEMENT = new JavaCompositeElementType("EMPTY_STATEMENT", PsiEmptyStatementImpl.class);
IElementType BLOCK_STATEMENT = new JavaCompositeElementType("BLOCK_STATEMENT", PsiBlockStatementImpl.class);
}
}
IElementType DUMMY_ELEMENT = new JavaDummyElementType();
-}
\ No newline at end of file
+}
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.*;
import com.intellij.psi.impl.PsiImplUtil;
+import com.intellij.psi.impl.java.stubs.FunctionalExpressionStub;
+import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
-import com.intellij.psi.impl.source.tree.ChildRole;
-import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.scope.PsiScopeProcessor;
-import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.Map;
-public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements PsiLambdaExpression {
+public class PsiLambdaExpressionImpl extends JavaStubPsiElement<FunctionalExpressionStub<PsiLambdaExpression>>
+ implements PsiLambdaExpression {
private static final ControlFlowPolicy ourPolicy = new ControlFlowPolicy() {
@Nullable
}
};
- public PsiLambdaExpressionImpl() {
- super(JavaElementType.LAMBDA_EXPRESSION);
+ public PsiLambdaExpressionImpl(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub) {
+ super(stub, JavaStubElementTypes.LAMBDA_EXPRESSION);
+ }
+
+ public PsiLambdaExpressionImpl(@NotNull ASTNode node) {
+ super(node);
}
@NotNull
}
@Override
- public int getChildRole(ASTNode child) {
- final IElementType elType = child.getElementType();
- if (elType == JavaTokenType.ARROW) {
- return ChildRole.ARROW;
- } else if (elType == JavaElementType.PARAMETER_LIST) {
- return ChildRole.PARAMETER_LIST;
- } else if (elType == JavaElementType.CODE_BLOCK) {
- return ChildRole.LBRACE;
- } else {
- return ChildRole.EXPRESSION;
- }
+ public PsiElement getParent() {
+ return getParentByTree();
}
@Override
import com.intellij.psi.impl.ResolveScopeManager;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.impl.PsiLiteralStub;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.impl.source.tree.LeafElement;
import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
import java.util.Locale;
public class PsiLiteralExpressionImpl
- extends StubBasedPsiElementBase<PsiLiteralStub>
+ extends JavaStubPsiElement<PsiLiteralStub>
implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
@NonNls private static final String QUOT = """;
import com.intellij.psi.*;
import com.intellij.psi.impl.CheckUtil;
import com.intellij.psi.impl.PsiImplUtil;
+import com.intellij.psi.impl.java.stubs.FunctionalExpressionStub;
+import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
-import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.infos.MethodCandidateInfo;
import com.intellij.psi.scope.ElementClassFilter;
import com.intellij.psi.scope.conflictResolvers.DuplicateConflictResolver;
import com.intellij.psi.scope.processor.FilterScopeProcessor;
import com.intellij.psi.scope.util.PsiScopesUtil;
-import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.*;
+import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.util.*;
-public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase implements PsiMethodReferenceExpression {
+public class PsiMethodReferenceExpressionImpl extends JavaStubPsiElement<FunctionalExpressionStub<PsiMethodReferenceExpression>>
+ implements PsiMethodReferenceExpression {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiMethodReferenceExpressionImpl");
private static final MethodReferenceResolver RESOLVER = new MethodReferenceResolver();
- public PsiMethodReferenceExpressionImpl() {
- super(JavaElementType.METHOD_REF_EXPRESSION);
+ public PsiMethodReferenceExpressionImpl(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub) {
+ super(stub, JavaStubElementTypes.METHOD_REFERENCE);
+ }
+
+ public PsiMethodReferenceExpressionImpl(@NotNull ASTNode node) {
+ super(node);
}
+ @Override
+ public PsiElement getParent() {
+ return getParentByTree();
+ }
+
@Override
public PsiTypeElement getQualifierType() {
final PsiElement qualifier = getQualifier();
}
}
- @Override
- public int getChildRole(ASTNode child) {
- final IElementType elType = child.getElementType();
- if (elType == JavaTokenType.DOUBLE_COLON) {
- return ChildRole.DOUBLE_COLON;
- } else if (elType == JavaTokenType.IDENTIFIER) {
- return ChildRole.REFERENCE_NAME;
- } else if (elType == JavaElementType.REFERENCE_EXPRESSION) {
- return ChildRole.CLASS_REFERENCE;
- }
- return ChildRole.EXPRESSION;
- }
-
@NotNull
@Override
public JavaResolveResult[] multiResolve(boolean incompleteCode) {
final int offsetInParent = element.getStartOffsetInParent();
return new TextRange(offsetInParent, offsetInParent + element.getTextLength());
}
- final PsiElement colons = findPsiChildByType(JavaTokenType.DOUBLE_COLON);
+ final PsiElement colons = findChildByType(JavaTokenType.DOUBLE_COLON);
if (colons != null) {
final int offsetInParent = colons.getStartOffsetInParent();
return new TextRange(offsetInParent, offsetInParent + colons.getTextLength());
@Override
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
- PsiElement oldIdentifier = findChildByRoleAsPsiElement(ChildRole.REFERENCE_NAME);
+ PsiElement oldIdentifier = findChildByType(JavaTokenType.IDENTIFIER);
if (oldIdentifier == null) {
- oldIdentifier = findChildByRoleAsPsiElement(ChildRole.CLASS_REFERENCE);
+ oldIdentifier = findChildByType(JavaElementType.REFERENCE_EXPRESSION);
}
if (oldIdentifier == null) {
throw new IncorrectOperationException();
public Icon getIcon(int flags) {
return AllIcons.Nodes.MethodReference;
}
+
+ @Override
+ public PsiElement bindToElementViaStaticImport(@NotNull final PsiClass qualifierClass) throws IncorrectOperationException {
+ throw new IncorrectOperationException();
+ }
+
+ @Override
+ public PsiElement getElement() {
+ return this;
+ }
+
+ @Override
+ public PsiElement resolve() {
+ return advancedResolve(false).getElement();
+ }
+
+ @NotNull
+ @Override
+ public Object[] getVariants() {
+ // this reference's variants are rather obtained with processVariants()
+ return ArrayUtil.EMPTY_OBJECT_ARRAY;
+ }
+
+ @Override
+ public boolean isSoft() {
+ return false;
+ }
+
+ @Override
+ public PsiReference getReference() {
+ return this;
+ }
+
+ @NotNull
+ @Override
+ public JavaResolveResult advancedResolve(boolean incompleteCode) {
+ final JavaResolveResult[] results = multiResolve(incompleteCode);
+ return results.length == 1 ? results[0] : JavaResolveResult.EMPTY;
+ }
+
+ @Override
+ public String getReferenceName() {
+ final PsiElement element = getReferenceNameElement();
+ return element != null ? element.getText() : null;
+ }
+
+ @Override
+ public PsiReferenceParameterList getParameterList() {
+ return PsiTreeUtil.getChildOfType(this, PsiReferenceParameterList.class);
+ }
+
+ @NotNull
+ @Override
+ public PsiType[] getTypeParameters() {
+ final PsiReferenceParameterList parameterList = getParameterList();
+ return parameterList != null ? parameterList.getTypeArguments() : PsiType.EMPTY_ARRAY;
+ }
+
+ @Override
+ public boolean isQualified() {
+ return getQualifier() != null;
+ }
+
+ @Override
+ public String getQualifiedName() {
+ return getCanonicalText();
+ }
+
}
public void foo(@SuppressWarnings("UnusedParameters") boolean b) {
}
+
+ public void foo(@SuppressWarnings("unused") boolean b) {
+
+ }
}
--- /dev/null
+class Test {
+ {
+ Double d = 1.0;
+ <caret>d.byteValue();
+ }
+}
\ No newline at end of file
--- /dev/null
+class Test {
+ {
+ ((Double) 1.0).byteValue();
+ }
+}
\ No newline at end of file
"</profile>");
}
+ public void testMergedMisspelledInspections() throws Exception {
+ checkMergedNoChanges("<profile version=\"1.0\">\n" +
+ " <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
+ " <inspection_tool class=\"MethodNamesDifferOnlyByCase\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
+ " <option name=\"ignoreIfMethodIsOverride\" value=\"false\" />\n" +
+ " </inspection_tool>\n" +
+ "</profile>");
+ checkMergedNoChanges("<profile version=\"1.0\">\n" +
+ " <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
+ " <inspection_tool class=\"MethodNamesDifferOnlyByCase\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
+ " <option name=\"ignoreIfMethodIsOverride\" value=\"false\" />\n" +
+ " </inspection_tool>\n" +
+ " <inspection_tool class=\"MisspelledSetUp\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\" />\n" +
+ "</profile>");
+ }
+
public void testDisabledUnusedDeclarationWithChanges() throws Exception {
checkMergedNoChanges("<profile version=\"1.0\">\n" +
" <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
" MODIFIER_LIST:PsiModifierListStub[mask=0]\n" +
" ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=O.P]\n" +
" ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=Y inqualifnew]\n" +
- " ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=R]\n");
+ " LAMBDA_EXPRESSION:FunctionalExpressionStub\n" +
+ " ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=R]\n");
}
public void testEnums() {
" ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
" ANNOTATION:PsiAnnotationStub[@A5]\n" +
" ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
- " ANNOTATION:PsiAnnotationStub[@A6]\n" +
- " ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
+ " METHOD_REF_EXPRESSION:FunctionalExpressionStub\n" +
+ " ANNOTATION:PsiAnnotationStub[@A6]\n" +
+ " ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
" ANNOTATION:PsiAnnotationStub[@A7]\n" +
" ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
" ANNOTATION:PsiAnnotationStub[@A8]\n" +
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.search.GlobalSearchScope
+import com.intellij.psi.search.searches.DirectClassInheritorsSearch
import com.intellij.psi.search.searches.OverridingMethodsSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.reference.SoftReference
class MyInner extends Inner {}
};
+ Runnable r = () -> { new B() {}; };
}
class B {
""")
assert !file.contentsLoaded
PsiClass bClass = ((PsiJavaFile) file).classes[1]
+ assert DirectClassInheritorsSearch.search(bClass).findAll().size() == 2
assert !file.contentsLoaded
def fooMethod = bClass.methods[0]
doTest(false);
}
+ public void testParenthesisAroundCast() throws Exception {
+ doTest(false);
+ }
+
public void testLocalVarInsideLambdaBodyWriteUsage() throws Exception {
doTest(true, "Cannot perform refactoring.\n" +
"Variable 'hello' is accessed for writing");
package com.intellij.codeInsight;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
+import com.intellij.ide.fileTemplates.FileTemplate;
+import com.intellij.ide.fileTemplates.FileTemplateManager;
+import com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl;
import com.intellij.injected.editor.EditorWindow;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
/**
* @author Mike
return editor;
}
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ FileTemplateManager manager = FileTemplateManager.getDefaultInstance();
+ for (String tname : Arrays.asList("Class", "AnnotationType", "Enum", "Interface")) {
+ for (FileTemplate template : manager.getInternalTemplates()) {
+ if (tname.equals(template.getName())) {
+ String text = "package $PACKAGE_NAME$;\npublic " + manager.internalTemplateToSubject(tname) + " $NAME$ { }";
+ template.setText(FileTemplateManagerImpl.normalizeText(text));
+ break;
+ }
+ }
+ }
+ }
+
@Override
protected void tearDown() throws Exception {
try {
package com.intellij.codeInspection;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
+import com.intellij.codeInspection.ex.InspectionElementsMerger;
import com.intellij.lang.Language;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
return true;
}
}
+
+ final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(getShortName());
+ if (merger != null) {
+ for (String sourceToolId : merger.getSourceToolNames()) {
+ for (InspectionSuppressor suppressor : suppressors) {
+ if (isSuppressed(sourceToolId, suppressor, element)) {
+ return true;
+ }
+ }
+ }
+ }
+
return false;
}
--- /dev/null
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInspection.ex;
+
+import com.intellij.openapi.extensions.ExtensionPointName;
+import com.intellij.openapi.extensions.Extensions;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+/**
+ * Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}
+ *
+ * {@see com.intellij.codeInspection.ex.InspectionElementsMergerBase} to provide more fine control over xml
+ */
+public abstract class InspectionElementsMerger {
+ public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
+ private static Map<String, InspectionElementsMerger> ourMergers;
+
+ @Nullable
+ public synchronized static InspectionElementsMerger getMerger(String shortName) {
+ if (ourMergers == null) {
+ ourMergers = new HashMap<>();
+ for (InspectionElementsMerger merger : Extensions.getExtensions(EP_NAME)) {
+ ourMergers.put(merger.getMergedToolName(), merger);
+ }
+ }
+ return ourMergers.get(shortName);
+ }
+
+ public abstract String getMergedToolName();
+ public abstract String[] getSourceToolNames();
+}
}
public boolean isToCheckMember(@NotNull RefElement owner, @NotNull InspectionProfileEntry tool) {
- return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool) && !((RefElementImpl)owner).isSuppressed(tool.getShortName());
+ return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool) && !((RefElementImpl)owner).isSuppressed(tool.getShortName(), tool.getAlternativeID());
}
public boolean isToCheckFile(PsiFile file, @NotNull InspectionProfileEntry tool) {
public static boolean isToCheckMember(@NotNull RefElement owner, @NotNull InspectionProfileEntry tool, Tools tools, ProfileManager profileManager) {
- return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool, tools, profileManager) && !((RefElementImpl)owner).isSuppressed(tool.getShortName());
+ return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool, tools, profileManager) && !((RefElementImpl)owner).isSuppressed(tool.getShortName(), tool.getAlternativeID());
}
public static boolean isToCheckFile(PsiFile file, @NotNull InspectionProfileEntry tool, Tools tools, ProfileManager profileManager) {
/*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
package com.intellij.codeInspection.ex;
import com.intellij.lang.annotation.HighlightSeverity;
-import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.WriteExternalException;
import org.jdom.Element;
import java.util.*;
-/**
- * Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}
- */
-public abstract class InspectionElementsMerger {
- public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
- protected abstract String getMergedToolName();
- protected abstract String[] getSourceToolNames();
+public abstract class InspectionElementsMergerBase extends InspectionElementsMerger {
/**
* serialize old inspection settings as they could appear in old profiles
}
}
}
+
+ public static class InspectionElementsMergerDelegate extends InspectionElementsMergerBase {
+ private final InspectionElementsMerger myMerger;
+
+ public InspectionElementsMergerDelegate(InspectionElementsMerger merger) {
+ myMerger = merger;
+ }
+
+ @Override
+ public String getMergedToolName() {
+ return myMerger.getMergedToolName();
+ }
+
+ @Override
+ public String[] getSourceToolNames() {
+ return myMerger.getSourceToolNames();
+ }
+ }
}
@NonNls private static final String USED_LEVELS = "used_levels";
public static final String DEFAULT_PROFILE_NAME = "Default";
@TestOnly
- public static boolean INIT_INSPECTIONS;
- private static Map<String, InspectionElementsMerger> ourMergers;
+ public static boolean INIT_INSPECTIONS = false;
private final InspectionToolRegistrar myRegistrar;
@NotNull
private final Map<String, Element> myInspectionsSettings = new TreeMap<>();
myProfileManager = profileManager;
}
- @NotNull
- private static synchronized Map<String, InspectionElementsMerger> getMergers() {
- if (ourMergers == null) {
- ourMergers = new LinkedHashMap<>();
- for (InspectionElementsMerger merger : Extensions.getExtensions(InspectionElementsMerger.EP_NAME)) {
- ourMergers.put(merger.getMergedToolName(), merger);
- }
- }
- return ourMergers;
- }
-
@NotNull
public static InspectionProfileImpl createSimple(@NotNull String name,
@NotNull Project project,
private void markSettingsMerged(@NotNull String toolName, @NotNull Element element) {
//add marker if already merged but result is now default (-> empty node)
- final String mergedName = InspectionElementsMerger.getMergedMarkerName(toolName);
- if (!myInspectionsSettings.containsKey(mergedName)) {
- final InspectionElementsMerger merger = getMergers().get(toolName);
- if (merger != null && merger.markSettingsMerged(myInspectionsSettings)) {
+ final String mergedName = InspectionElementsMergerBase.getMergedMarkerName(toolName);
+ if (!myUninstalledInspectionsSettings.containsKey(mergedName)) {
+ final InspectionElementsMergerBase merger = getMerger(toolName);
+ if (merger != null && merger.markSettingsMerged(myUninstalledInspectionsSettings)) {
element.addContent(new Element(INSPECTION_TOOL_TAG).setAttribute(CLASS_TAG, mergedName));
}
}
private boolean areSettingsMerged(String toolName, Element inspectionElement) {
//skip merged settings as they could be restored from already provided data
- final InspectionElementsMerger merger = getMergers().get(toolName);
- return merger != null && merger.areSettingsMerged(myInspectionsSettings, inspectionElement);
+ final InspectionElementsMergerBase merger = getMerger(toolName);
+ return merger != null && merger.areSettingsMerged(myUninstalledInspectionsSettings, inspectionElement);
}
public void collectDependentInspections(@NotNull InspectionToolWrapper toolWrapper,
if (element != null) {
toolsList.readExternal(element, this, dependencies);
}
- else if (!myInspectionsSettings.containsKey(InspectionElementsMerger.getMergedMarkerName(shortName))) {
- final InspectionElementsMerger merger = getMergers().get(shortName);
+ else if (!myUninstalledInspectionsSettings.containsKey(InspectionElementsMergerBase.getMergedMarkerName(shortName))) {
+ final InspectionElementsMergerBase merger = getMerger(shortName);
if (merger != null) {
final Element merged = merger.merge(myInspectionsSettings);
if (merged != null) {
myTools.put(shortName, toolsList);
}
+ @Nullable
+ private static InspectionElementsMergerBase getMerger(String shortName) {
+ final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(shortName);
+ if (merger instanceof InspectionElementsMergerBase) {
+ return (InspectionElementsMergerBase)merger;
+ }
+ return merger != null ? new InspectionElementsMergerBase() {
+ @Override
+ public String getMergedToolName() {
+ return merger.getMergedToolName();
+ }
+
+ @Override
+ public String[] getSourceToolNames() {
+ return merger.getSourceToolNames();
+ }
+ } : null;
+ }
+
@Nullable
@Transient
public String[] getScopesOrder() {
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.*
+import com.intellij.openapi.components.ex.ComponentManagerEx
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.StateStorageManager
import com.intellij.openapi.components.impl.stores.StoreUtil
}
@Suppress("DEPRECATION")
- ApplicationManager.getApplication().getComponents(ExportableApplicationComponent::class.java).forEach(processor)
+ (ApplicationManager.getApplication() as ComponentManagerEx).getComponentInstancesOfType(ExportableApplicationComponent::class.java).forEach(processor)
ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
val configPath = storageManager.expandMacros(ROOT_CONFIG)
--- /dev/null
+
+import com.intellij.openapi.application.ApplicationManager
+import com.intellij.openapi.application.impl.ApplicationImpl
+import com.intellij.openapi.components.PersistentStateComponent
+import com.intellij.openapi.components.impl.ComponentManagerImpl
+import com.intellij.openapi.components.impl.ServiceManagerImpl
+import com.intellij.openapi.components.impl.stores.StoreUtil
+import com.intellij.openapi.extensions.PluginDescriptor
+import com.intellij.testFramework.ProjectRule
+import com.intellij.util.PairProcessor
+import com.intellij.util.xmlb.XmlSerializerUtil
+import org.jdom.Attribute
+import org.jdom.Element
+import org.junit.ClassRule
+import org.junit.Test
+import java.lang.reflect.ParameterizedType
+import java.lang.reflect.Type
+import java.util.Collection
+
+class DoNotStorePasswordTest {
+ companion object {
+ @JvmField
+ @ClassRule
+ val projectRule = ProjectRule()
+ }
+
+ @Test
+ fun printPasswordComponents() {
+ val processor = PairProcessor<Class<*>, PluginDescriptor> { aClass, pluginDescriptor ->
+ val stateAnnotation = StoreUtil.getStateSpec(aClass)
+ if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) {
+ return@PairProcessor true
+ }
+
+ for (i in aClass.genericInterfaces) {
+ if (checkType(i)) {
+ return@PairProcessor true
+ }
+ }
+
+
+ // public static class Project extends WebServersConfigManagerBaseImpl<WebServersConfigManagerBaseImpl.State> {
+ // so, we check not only PersistentStateComponent
+ checkType(aClass.genericSuperclass)
+
+ true
+ }
+
+ val app = ApplicationManager.getApplication() as ApplicationImpl
+ ServiceManagerImpl.processAllImplementationClasses(app, processor)
+ // yes, we don't use default project here to be sure
+ ServiceManagerImpl.processAllImplementationClasses(projectRule.project as ComponentManagerImpl, processor)
+
+ @Suppress("DEPRECATION")
+ for (c in app.getComponentInstancesOfType(PersistentStateComponent::class.java)) {
+ processor.process(c.javaClass, null)
+ }
+ @Suppress("DEPRECATION")
+ for (c in (projectRule.project as ComponentManagerImpl).getComponentInstancesOfType(PersistentStateComponent::class.java)) {
+ processor.process(c.javaClass, null)
+ }
+ }
+
+ fun isSavePasswordField(name: String) = name.contains("remember", ignoreCase = true) || name.contains("keep", ignoreCase = true) || name.contains("save", ignoreCase = true)
+
+ fun check(clazz: Class<*>) {
+ if (clazz === Attribute::class.java || clazz === Element::class.java) {
+ return
+ }
+
+ for (accessor in XmlSerializerUtil.getAccessors(clazz)) {
+ val name = accessor.name
+ if (name.contains("password", ignoreCase = true) && !isSavePasswordField(name)) {
+ System.out.println("${clazz.typeName}.${accessor.name}")
+ }
+ else if (!accessor.valueClass.isPrimitive) {
+ @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+ if (Collection::class.java.isAssignableFrom(accessor.valueClass)) {
+ val genericType = accessor.genericType
+ if (genericType is ParameterizedType) {
+ check(genericType.actualTypeArguments[0] as Class<*>)
+ }
+ }
+ else if (accessor.valueClass != clazz) {
+ check(accessor.valueClass)
+ }
+ }
+ }
+ }
+
+ private fun checkType(type: Type): Boolean {
+ if (type !is ParameterizedType || !PersistentStateComponent::class.java.isAssignableFrom(type.rawType as Class<*>)) {
+ return false
+ }
+
+ type.actualTypeArguments[0].let {
+ if (it is ParameterizedType) {
+ check(it.rawType as Class<*>)
+ }
+ else {
+ check(it as Class<*>)
+ }
+ }
+ return true
+ }
+}
\ No newline at end of file
/*
- * Copyright 2000-2015 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@NotNull
public GlobalSearchScope union(@NotNull final LocalSearchScope scope) {
- return new GlobalSearchScope(scope.getScope()[0].getProject()) {
+ PsiElement[] localScopeElements = scope.getScope();
+ if (localScopeElements.length == 0) {
+ return this;
+ }
+ return new GlobalSearchScope(localScopeElements[0].getProject()) {
@Override
public boolean contains(@NotNull VirtualFile file) {
return GlobalSearchScope.this.contains(file) || scope.isInScope(file);
if (this == o) return true;
if (!(o instanceof LocalSearchScope)) return false;
- final LocalSearchScope localSearchScope = (LocalSearchScope)o;
+ LocalSearchScope other = (LocalSearchScope)o;
+
+ if (other.myIgnoreInjectedPsi != myIgnoreInjectedPsi) return false;
+ if (other.myScope.length != myScope.length) return false;
+ if (!Comparing.strEqual(myDisplayName, other.myDisplayName)) return false; // scopes like "Current file" and "Changed files" should be different event if empty
- if (localSearchScope.myIgnoreInjectedPsi != myIgnoreInjectedPsi) return false;
- if (localSearchScope.myScope.length != myScope.length) return false;
for (final PsiElement scopeElement : myScope) {
- final PsiElement[] thatScope = localSearchScope.myScope;
+ final PsiElement[] thatScope = other.myScope;
for (final PsiElement thatScopeElement : thatScope) {
if (!Comparing.equal(scopeElement, thatScopeElement)) return false;
}
public abstract class OptionTreeWithPreviewPanel extends CustomizableLanguageCodeStylePanel {
private static final Logger LOG = Logger.getInstance("#com.intellij.application.options.CodeStyleSpacesPanel");
protected JTree myOptionsTree;
- private final ArrayList<BooleanOptionKey> myKeys = new ArrayList<BooleanOptionKey>();
+ protected final ArrayList<BooleanOptionKey> myKeys = new ArrayList<>();
protected final JPanel myPanel = new JPanel(new GridBagLayout());
private boolean myShowAllStandardOptions = false;
- private Set<String> myAllowedOptions = new HashSet<String>();
- private MultiMap<String, CustomBooleanOptionInfo> myCustomOptions = new MultiMap<String, CustomBooleanOptionInfo>();
+ private Set<String> myAllowedOptions = new HashSet<>();
+ private MultiMap<String, CustomBooleanOptionInfo> myCustomOptions = new MultiMap<>();
protected boolean isFirstUpdate = true;
- private final Map<String, String> myRenamedFields = new THashMap<String, String>();
- private final Map<String, String> myRemappedGroups = new THashMap<String, String>();
+ private final Map<String, String> myRenamedFields = new THashMap<>();
+ private final Map<String, String> myRemappedGroups = new THashMap<>();
public OptionTreeWithPreviewPanel(CodeStyleSettings settings) {
import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
+import com.intellij.util.CommonProcessors;
import com.intellij.util.Processor;
import com.intellij.util.Processors;
import com.intellij.util.containers.ContainerUtil;
final int offset = ((EditorEx)editor).getExpectedCaretOffset();
final Project project = file.getProject();
- final List<HighlightInfo.IntentionActionDescriptor> result = new ArrayList<>();
- DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, info -> {
- addAvailableActionsForGroups(info, editor, file, result, passId, offset);
- return true;
- });
+ List<HighlightInfo> infos = new ArrayList<>();
+ DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true,
+ new CommonProcessors.CollectProcessor<>(infos));
+ List<HighlightInfo.IntentionActionDescriptor> result = new ArrayList<>();
+ infos.forEach(info->addAvailableActionsForGroups(info, editor, file, result, passId, offset));
return result;
}
}
final String text = exportToHTMLSettings.OUTPUT_DIRECTORY;
myTargetDirectoryField.setText(text);
- myTargetDirectoryField.setPreferredSize(new Dimension(GraphicsUtil.stringWidth(text, myTargetDirectoryField.getFont()) + 100, myTargetDirectoryField.getPreferredSize().height));
+ if (text != null) {
+ myTargetDirectoryField.setPreferredSize(new Dimension(GraphicsUtil.stringWidth(text, myTargetDirectoryField.getFont()) + 100, myTargetDirectoryField.getPreferredSize().height));
+ }
}
public void apply() {
import com.intellij.lang.Language;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ConfigurationException;
+import com.intellij.openapi.util.Disposer;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.codeStyle.CodeStyleSettingsCodeFragmentFilter;
import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
private final CodeStyleSettingsCodeFragmentFilter.CodeStyleSettingsToShow mySettingsToShow;
private final SelectedTextFormatter mySelectedTextFormatter;
private SpacesPanelWithoutPreview mySpacesPanel;
+ private WrappingAndBracesPanelWithoutPreview myWrappingPanel;
private Runnable mySomethingChangedCallback;
@Override
protected void initTabs(CodeStyleSettings settings) {
- mySpacesPanel = new SpacesPanelWithoutPreview(settings);
- addTab(mySpacesPanel);
- addTab(new WrappingAndBracesPanelWithoutPreview(settings));
+ SpacesPanelWithoutPreview panel = getSpacesPanel(settings);
+ if (panel != null) {
+ mySpacesPanel = panel;
+ addTab(mySpacesPanel);
+ }
+
+ myWrappingPanel = new WrappingAndBracesPanelWithoutPreview(settings);
+ addTab(myWrappingPanel);
reset(getSettings());
}
+ @Nullable
+ private SpacesPanelWithoutPreview getSpacesPanel(CodeStyleSettings settings) {
+ SpacesPanelWithoutPreview spacesPanel = new SpacesPanelWithoutPreview(settings);
+ if (spacesPanel.hasSomethingToShow()) {
+ return spacesPanel;
+ }
+ Disposer.dispose(spacesPanel);
+ return null;
+ }
+
public JComponent getPreferredFocusedComponent() {
- return mySpacesPanel.getPreferredFocusedComponent();
+ return mySpacesPanel != null ? mySpacesPanel.getPreferredFocusedComponent()
+ : myWrappingPanel.getPreferredFocusedComponent();
}
public static CodeStyleSettingsCodeFragmentFilter.CodeStyleSettingsToShow calcSettingNamesToShow(CodeStyleSettingsCodeFragmentFilter filter) {
return true;
}
}
- return false;
+
+ return !provider.getSupportedFields().isEmpty();
}
private void reformatSelectedTextWithNewSettings() {
@Override
protected void init() {
List<String> settingNames = mySettingsToShow.getSettings(getSettingsType());
+ if (settingNames.isEmpty()) {
+ settingNames = mySettingsToShow.getOtherSetting();
+ }
+
String[] names = ContainerUtil.toArray(settingNames, new String[settingNames.size()]);
showStandardOptions(names);
initTables();
isFirstUpdate = false;
}
+ public boolean hasSomethingToShow() {
+ return !myKeys.isEmpty();
+ }
+
@Override
public JComponent getPanel() {
return myPanel;
@Override
protected void init() {
Collection<String> settingNames = mySettingsToShow.getSettings(getSettingsType());
+ if (settingNames.isEmpty()) {
+ settingNames = mySettingsToShow.getOtherSetting();
+ }
+
initTables();
Collection<String> fields = populateWithAssociatedFields(settingNames);
JBScrollPane scrollPane = new JBScrollPane(myTreeTable) {
@Override
public Dimension getMinimumSize() {
- return super.getPreferredSize();
+ return myTreeTable.getPreferredSize();
}
};
protected String getPreviewText() {
return null;
}
+
+ public JComponent getPreferredFocusedComponent() {
+ return myTreeTable;
+ }
}
}
import com.intellij.application.options.codeStyle.CodeStyleSchemesModel;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.internal.statistic.UsageTrigger;
import com.intellij.lang.Language;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.OptionAction;
-import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction {
private static final Logger LOG = Logger.getInstance(ConfigureCodeStyleOnSelectedFragment.class);
-
+ private static final String ID = "configure.code.style.on.selected.fragment";
+
@Nls
@NotNull
@Override
@Override
public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
+ UsageTrigger.trigger(ID);
SelectedTextFormatter textFormatter = new SelectedTextFormatter(project, editor, file);
CodeStyleSettingsToShow settingsToShow = calculateAffectingSettings(editor, file);
CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project);
import com.intellij.ui.JBColor;
import com.intellij.ui.RetrievableIcon;
import com.intellij.util.PlatformIcons;
-import com.intellij.util.containers.WeakHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
private final VirtualFile myFile;
@NotNull private OpenFileDescriptor myTarget;
private final Project myProject;
- private WeakHashMap<Document, Reference<RangeHighlighterEx>> myHighlighterRefs;
+ private Reference<RangeHighlighterEx> myHighlighterRef;
private String myDescription;
private char myMnemonic = 0;
else {
highlighter = null;
}
- if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();
- if (highlighter != null) {
- myHighlighterRefs.put(markup.getDocument(), new WeakReference<RangeHighlighterEx>(highlighter));
- }
+ myHighlighterRef = highlighter == null ? null : new WeakReference<RangeHighlighterEx>(highlighter);
return highlighter;
}
}
public void release() {
- try {
int line = getLine();
if (line < 0) {
return;
if (markupDocument.getLineCount() <= line) return;
RangeHighlighterEx highlighter = findMyHighlighter();
if (highlighter != null) {
+ myHighlighterRef = null;
highlighter.dispose();
}
- } finally {
- myHighlighterRefs = null;
- }
}
private RangeHighlighterEx findMyHighlighter() {
final Document document = getDocument();
if (document == null) return null;
- Reference<RangeHighlighterEx> reference = myHighlighterRefs != null ? myHighlighterRefs.get(document) : null;
- RangeHighlighterEx result = SoftReference.dereference(reference);
+ RangeHighlighterEx result = SoftReference.dereference(myHighlighterRef);
if (result != null) {
return result;
}
return true;
});
result = found.get();
- if (result != null) {
- if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();
- myHighlighterRefs.put(document, new WeakReference<RangeHighlighterEx>(result));
- }
+ myHighlighterRef = result == null ? null : new WeakReference<RangeHighlighterEx>(result);
return result;
}
*/
package com.intellij.ide.fileTemplates.impl;
-import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.project.ProjectManager;
-import org.jdom.Element;
-import org.jetbrains.annotations.Nullable;
+import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
+import org.jetbrains.annotations.NotNull;
/**
* @author Dmitry Avdeev
storages = @Storage(FileTemplateSettings.EXPORTABLE_SETTINGS_FILE),
additionalExportFile = FileTemplatesLoader.TEMPLATES_DIR
)
-public class ExportableFileTemplateSettings implements PersistentStateComponent<Element> {
- @Nullable
- @Override
- public Element getState() {
- return getSettingInstance().getState();
- }
-
- @Override
- public void loadState(Element state) {
- getSettingInstance().loadState(state);
- }
+public class ExportableFileTemplateSettings extends FileTemplateSettings {
- private static FileTemplateSettings getSettingInstance() {
- return FileTemplateSettings.getInstance(ProjectManager.getInstance().getDefaultProject());
+ public ExportableFileTemplateSettings(@NotNull FileTypeManagerEx typeManager) {
+ super(typeManager);
}
}
import com.intellij.ide.fileTemplates.InternalTemplateBean;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
-import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.State;
-import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.components.StoragePathMacros;
+import com.intellij.openapi.components.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
private final State myState = new State();
private final FileTypeManagerEx myTypeManager;
+ private final FileTemplateSettings myProjectSettings;
+ private final ExportableFileTemplateSettings myDefaultSettings;
private final Project myProject;
- /** Null for default project. */
- @Nullable
private final FileTemplatesScheme myProjectScheme;
private FileTemplatesScheme myScheme = FileTemplatesScheme.DEFAULT;
private boolean myInitialized;
- private final FTManager myInternalTemplatesManager;
- private final FTManager myDefaultTemplatesManager;
- private final FTManager myPatternsManager;
- private final FTManager myCodeTemplatesManager;
- private final FTManager myJ2eeTemplatesManager;
- private final FTManager[] myAllManagers;
- private final URL myDefaultTemplateDescription;
- private final URL myDefaultIncludeDescription;
-
- public static FileTemplateManagerImpl getInstanceImpl(Project project) {
+ public static FileTemplateManagerImpl getInstanceImpl(@NotNull Project project) {
return (FileTemplateManagerImpl)getInstance(project);
}
public FileTemplateManagerImpl(@NotNull FileTypeManagerEx typeManager,
- FileTemplatesLoader loader,
+ FileTemplateSettings projectSettings,
+ ExportableFileTemplateSettings defaultSettings,
/*need this to ensure disposal of the service _after_ project manager*/
@SuppressWarnings("UnusedParameters") ProjectManager pm,
final Project project) {
myTypeManager = typeManager;
+ myProjectSettings = projectSettings;
+ myDefaultSettings = defaultSettings;
myProject = project;
- myInternalTemplatesManager = loader.getInternalTemplatesManager();
- myDefaultTemplatesManager = loader.getDefaultTemplatesManager();
- myPatternsManager = loader.getPatternsManager();
- myCodeTemplatesManager = loader.getCodeTemplatesManager();
- myJ2eeTemplatesManager = loader.getJ2eeTemplatesManager();
- myAllManagers = new FTManager[] { myInternalTemplatesManager, myDefaultTemplatesManager, myPatternsManager, myCodeTemplatesManager, myJ2eeTemplatesManager };
-
- myDefaultTemplateDescription = loader.getDefaultTemplateDescription();
- myDefaultIncludeDescription = loader.getDefaultIncludeDescription();
-
- if (ApplicationManager.getApplication().isUnitTestMode()) {
- for (String tname : Arrays.asList("Class", "AnnotationType", "Enum", "Interface")) {
- for (FileTemplate template : myInternalTemplatesManager.getAllTemplates(true)) {
- if (tname.equals(template.getName())) {
- myInternalTemplatesManager.removeTemplate(((FileTemplateBase)template).getQualifiedName());
- break;
- }
- }
- final FileTemplateBase template = myInternalTemplatesManager.addTemplate(tname, "java");
- template.setText(normalizeText(getTestClassTemplateText(tname)));
- }
- }
-
myProjectScheme = project.isDefault() ? null : new FileTemplatesScheme("Project") {
@NotNull
@Override
};
}
+ private FileTemplateSettings getSettings() {
+ return myScheme == FileTemplatesScheme.DEFAULT ? myDefaultSettings : myProjectSettings;
+ }
+
@NotNull
@Override
public FileTemplatesScheme getCurrentScheme() {
@Override
public void setCurrentScheme(@NotNull FileTemplatesScheme scheme) {
- for (FTManager child : myAllManagers) {
+ for (FTManager child : getAllManagers()) {
child.saveTemplates();
}
setScheme(scheme);
private void setScheme(@NotNull FileTemplatesScheme scheme) {
myScheme = scheme;
- for (FTManager manager : myAllManagers) {
+ for (FTManager manager : getAllManagers()) {
manager.setScheme(scheme);
}
myInitialized = true;
@Override
@NotNull
public FileTemplate[] getAllTemplates() {
- final Collection<FileTemplateBase> templates = myDefaultTemplatesManager.getAllTemplates(false);
+ final Collection<FileTemplateBase> templates = getSettings().getDefaultTemplatesManager().getAllTemplates(false);
return templates.toArray(new FileTemplate[templates.size()]);
}
@Override
public FileTemplate getTemplate(@NotNull String templateName) {
- return myDefaultTemplatesManager.findTemplateByName(templateName);
+ return getSettings().getDefaultTemplatesManager().findTemplateByName(templateName);
}
@Override
@NotNull
public FileTemplate addTemplate(@NotNull String name, @NotNull String extension) {
- return myDefaultTemplatesManager.addTemplate(name, extension);
+ return getSettings().getDefaultTemplatesManager().addTemplate(name, extension);
}
@Override
public void removeTemplate(@NotNull FileTemplate template) {
final String qName = ((FileTemplateBase)template).getQualifiedName();
- for (FTManager manager : myAllManagers) {
+ for (FTManager manager : getAllManagers()) {
manager.removeTemplate(qName);
}
}
}
private void validateRecentNames() {
- final Collection<FileTemplateBase> allTemplates = myDefaultTemplatesManager.getAllTemplates(false);
+ final Collection<FileTemplateBase> allTemplates = getSettings().getDefaultTemplatesManager().getAllTemplates(false);
final List<String> allNames = new ArrayList<>(allTemplates.size());
for (FileTemplate fileTemplate : allTemplates) {
allNames.add(fileTemplate.getName());
}
else {
final String text = normalizeText(getDefaultClassTemplateText(templateName));
- template = myInternalTemplatesManager.addTemplate(templateName, "java");
+ template = getSettings().getInternalTemplatesManager().addTemplate(templateName, "java");
template.setText(text);
}
}
@Override
public FileTemplate findInternalTemplate(@NotNull @NonNls String templateName) {
- LOG.assertTrue(myInternalTemplatesManager != null);
- FileTemplateBase template = myInternalTemplatesManager.findTemplateByName(templateName);
+ FileTemplateBase template = getSettings().getInternalTemplatesManager().findTemplateByName(templateName);
if (template == null) {
// todo: review the hack and try to get rid of this weird logic completely
- template = myDefaultTemplatesManager.findTemplateByName(templateName);
+ template = getSettings().getDefaultTemplatesManager().findTemplateByName(templateName);
}
return template;
}
@NotNull
- private static String normalizeText(@NotNull String text) {
+ public static String normalizeText(@NotNull String text) {
text = StringUtil.convertLineSeparators(text);
text = StringUtil.replace(text, "$NAME$", "${NAME}");
text = StringUtil.replace(text, "$PACKAGE_NAME$", "${PACKAGE_NAME}");
return text;
}
- @NonNls
- @NotNull
- private String getTestClassTemplateText(@NotNull @NonNls String templateName) {
- return "package $PACKAGE_NAME$;\npublic " + internalTemplateToSubject(templateName) + " $NAME$ { }";
- }
-
@Override
@NotNull
public String internalTemplateToSubject(@NotNull @NonNls String templateName) {
@Override
public FileTemplate getCodeTemplate(@NotNull @NonNls String templateName) {
- return getTemplateFromManager(templateName, myCodeTemplatesManager);
+ return getTemplateFromManager(templateName, getSettings().getCodeTemplatesManager());
}
@Override
public FileTemplate getJ2eeTemplate(@NotNull @NonNls String templateName) {
- return getTemplateFromManager(templateName, myJ2eeTemplatesManager);
+ return getTemplateFromManager(templateName, getSettings().getJ2eeTemplatesManager());
}
@Nullable
public FileTemplate getDefaultTemplate(@NotNull final String name) {
final String templateQName = myTypeManager.getExtension(name).isEmpty()? FileTemplateBase.getQualifiedName(name, "java") : name;
- for (FTManager manager : myAllManagers) {
+ for (FTManager manager : getAllManagers()) {
final FileTemplateBase template = manager.getTemplate(templateQName);
if (template instanceof BundledFileTemplate) {
final BundledFileTemplate copy = ((BundledFileTemplate)template).clone();
@Override
@NotNull
public FileTemplate[] getAllPatterns() {
- final Collection<FileTemplateBase> allTemplates = myPatternsManager.getAllTemplates(false);
+ final Collection<FileTemplateBase> allTemplates = getSettings().getPatternsManager().getAllTemplates(false);
return allTemplates.toArray(new FileTemplate[allTemplates.size()]);
}
@Override
public FileTemplate getPattern(@NotNull String name) {
- return myPatternsManager.findTemplateByName(name);
+ return getSettings().getPatternsManager().findTemplateByName(name);
}
@Override
@NotNull
public FileTemplate[] getAllCodeTemplates() {
- final Collection<FileTemplateBase> templates = myCodeTemplatesManager.getAllTemplates(false);
+ final Collection<FileTemplateBase> templates = getSettings().getCodeTemplatesManager().getAllTemplates(false);
return templates.toArray(new FileTemplate[templates.size()]);
}
@Override
@NotNull
public FileTemplate[] getAllJ2eeTemplates() {
- final Collection<FileTemplateBase> templates = myJ2eeTemplatesManager.getAllTemplates(false);
+ final Collection<FileTemplateBase> templates = getSettings().getJ2eeTemplatesManager().getAllTemplates(false);
return templates.toArray(new FileTemplate[templates.size()]);
}
@Override
public void setTemplates(@NotNull String templatesCategory, @NotNull Collection<FileTemplate> templates) {
- for (FTManager manager : myAllManagers) {
+ for (FTManager manager : getAllManagers()) {
if (templatesCategory.equals(manager.getName())) {
manager.updateTemplates(templates);
manager.saveTemplates();
@Override
public void saveAllTemplates() {
- for (FTManager manager : myAllManagers) {
+ for (FTManager manager : getAllManagers()) {
manager.saveTemplates();
}
}
public URL getDefaultTemplateDescription() {
- return myDefaultTemplateDescription;
+ return myDefaultSettings.getDefaultTemplateDescription();
}
public URL getDefaultIncludeDescription() {
- return myDefaultIncludeDescription;
+ return myDefaultSettings.getDefaultIncludeDescription();
}
private Date myTestDate;
public void loadState(State state) {
XmlSerializerUtil.copyBean(state, myState);
FileTemplatesScheme scheme = myProjectScheme != null && myProjectScheme.getName().equals(state.SCHEME) ? myProjectScheme : FileTemplatesScheme.DEFAULT;
- FileTemplateSettings.getInstance(scheme.getProject());
setScheme(scheme);
}
- FTManager[] getAllManagers() {
- return myAllManagers;
+ private FTManager[] getAllManagers() {
+ return getSettings().getAllManagers();
}
public static class State {
package com.intellij.ide.fileTemplates.impl;
import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.project.Project;
+import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
name = "ExportableFileTemplateSettings",
storages = @Storage(FileTemplateSettings.EXPORTABLE_SETTINGS_FILE)
)
-public class FileTemplateSettings implements PersistentStateComponent<Element> {
+public class FileTemplateSettings extends FileTemplatesLoader implements PersistentStateComponent<Element> {
public final static String EXPORTABLE_SETTINGS_FILE = "file.template.settings.xml";
static final String ELEMENT_TEMPLATE = "template";
static final String ATTRIBUTE_REFORMAT = "reformat";
static final String ATTRIBUTE_LIVE_TEMPLATE = "live-template-enabled";
static final String ATTRIBUTE_ENABLED = "enabled";
- private final Project myProject;
- public FileTemplateSettings(Project project) {
- myProject = project;
- }
-
-
- static FileTemplateSettings getInstance(Project project) {
- return ServiceManager.getService(project, FileTemplateSettings.class);
+ public FileTemplateSettings(@NotNull FileTypeManagerEx typeManager) {
+ super(typeManager);
}
@Nullable
return element;
}
- private FTManager[] getAllManagers() {
- return FileTemplateManagerImpl.getInstanceImpl(myProject).getAllManagers();
- }
-
@Override
public void loadState(Element state) {
doLoad(state);
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider;
import com.intellij.openapi.project.DumbModePermission;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
}
}
- CommandProcessor.getInstance().executeCommand(project, () -> {
+ CommandProcessor.getInstance().executeCommand(project, () -> NonProjectFileWritingAccessProvider.disableChecksDuring(() -> {
Collection<PsiElement> directories = ContainerUtil.newSmartList();
for (PsiElement e : elements) {
if (e instanceof PsiFileSystemItem && e.getParent() != null) {
directories.add(e.getParent());
}
}
+
if (!CommonRefactoringUtil.checkReadOnlyStatus(project, Arrays.asList(elements), directories, false)) {
return;
}
}
});
}
- }, RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
+ }), RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
}
private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) {
setText(myText);
setBorder(BorderFactory.createEmptyBorder(0, 0, 0, UIUtil.getListCellHPadding()));
setHorizontalTextPosition(SwingConstants.LEFT);
+ setHorizontalAlignment(SwingConstants.RIGHT); // align icon to the right
setBackground(selected ? UIUtil.getListSelectionBackground() : UIUtil.getListBackground());
setForeground(selected ? UIUtil.getListSelectionForeground() : UIUtil.getInactiveTextColor());
typeToTask.put(type, task);
}
+ Set<String> otherFields = myProvider.getSupportedFields();
+ final FilterFieldsTask otherFieldsTask = new FilterFieldsTask(otherFields);
+ if (!otherFields.isEmpty()) {
+ compositeTask.addTask(otherFieldsTask);
+ }
+
progressTask.setTask(compositeTask);
progressTask.setMinIterationTime(10);
ProgressManager.getInstance().run(progressTask);
FilterFieldsTask task = typeToTask.get(type);
return task.getAffectedFields();
}
+
+ @Override
+ public List<String> getOtherSetting() {
+ return ContainerUtil.newArrayList(otherFieldsTask.getAffectedFields());
+ }
};
}
finally {
public interface CodeStyleSettingsToShow {
List<String> getSettings(LanguageCodeStyleSettingsProvider.SettingsType type);
+
+ List<String> getOtherSetting();
}
}
boolean currentSelection,
boolean usageView,
boolean showEmptyScopes) {
- Collection<SearchScope> result = showEmptyScopes ? ContainerUtil.newArrayList() : ContainerUtil.newLinkedHashSet();
+ Collection<SearchScope> result = ContainerUtil.newLinkedHashSet();
result.add(GlobalSearchScope.projectScope(project));
if (suggestSearchInLibs) {
result.add(GlobalSearchScope.allScope(project));
final Editor selectedTextEditor = ApplicationManager.getApplication().isDispatchThread()
? FileEditorManager.getInstance(project).getSelectedTextEditor()
: null;
- final PsiFile psiFile =
- (selectedTextEditor != null) ? PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument()) : null;
+ PsiFile psiFile = selectedTextEditor == null ? null : PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument());
PsiFile currentFile = psiFile;
if (dataContext != null) {
if (endElement != null) {
final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
if (parent != null) {
- final List<PsiElement> elements = new ArrayList<PsiElement>();
+ final List<PsiElement> elements = new ArrayList<>();
final PsiElement[] children = parent.getChildren();
TextRange selection = new TextRange(start, end);
for (PsiElement child : children) {
if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
final Set<Usage> usages = ContainerUtil.newTroveSet(selectedUsageView.getUsages());
usages.removeAll(selectedUsageView.getExcludedUsages());
- final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());
if (prevSearchFiles) {
final Set<VirtualFile> files = collectFiles(usages, true);
if (!files.isEmpty()) {
GlobalSearchScope prev = new GlobalSearchScope(project) {
- private Set<VirtualFile> myFiles = null;
+ private Set<VirtualFile> myFiles;
@NotNull
@Override
}
}
else {
+ final List<PsiElement> results = new ArrayList<>(usages.size());
for (Usage usage : usages) {
if (usage instanceof PsiElementUsage) {
final PsiElement element = ((PsiElementUsage)usage).getElement();
}
protected static Set<VirtualFile> collectFiles(Set<Usage> usages, boolean findFirst) {
- final Set<VirtualFile> files = new HashSet<VirtualFile>();
+ final Set<VirtualFile> files = new HashSet<>();
for (Usage usage : usages) {
if (usage instanceof PsiElementUsage) {
PsiElement psiElement = ((PsiElementUsage)usage).getElement();
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.DeleteUtil;
import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider;
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.project.DumbModePermission;
import com.intellij.openapi.project.DumbService;
}
DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> {
- if (myCallback != null && isSafeDelete()) {
- myCallback.run(SafeDeleteDialog.this);
- } else {
- SafeDeleteDialog.super.doOKAction();
- }
+ NonProjectFileWritingAccessProvider.disableChecksDuring(() -> {
+ if (myCallback != null && isSafeDelete()) {
+ myCallback.run(SafeDeleteDialog.this);
+ }
+ else {
+ SafeDeleteDialog.super.doOKAction();
+ }
+ });
});
final RefactoringSettings refactoringSettings = RefactoringSettings.getInstance();
static {
predefinedScopeNameToPropertyKey = new THashMap<String, String>();
predefinedScopeNameToPropertyKey.put(NonProjectFilesScope.NAME, "file.colors.enable.non.project");
- if (PlatformUtils.isIntelliJ() || PlatformUtils.isRubyMine()) {
+ // These IDEs have TestScope registered (via PackagesScopesProvider or TestScopeProvider)
+ if (PlatformUtils.isIntelliJ() || PlatformUtils.isRubyMine() || PlatformUtils.isPhpStorm() || PlatformUtils.isWebStorm()) {
predefinedScopeNameToPropertyKey.put(TestsScope.NAME, "file.colors.enable.tests");
}
private UnindexedFilesFinder(@Nullable ProgressIndicator indicator) {
myProgressIndicator = indicator;
- if (!myInitialized) waitUntilIndicesAreInitialized();
}
@NotNull
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
+import com.intellij.util.ArrayUtil;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import javax.swing.event.DocumentEvent;
import java.awt.*;
import java.awt.event.MouseEvent;
+import java.util.Arrays;
+import java.util.Set;
/**
* @author Yura Cangea, dsl
mySupportParens.setSelected(table.isHasParens());
mySupportEscapes.setSelected(table.isHasStringEscapes());
- for (String s : table.getKeywords1()) {
+ for (String s : sorted(table.getKeywords1())) {
myKeywordModels[0].addElement(s);
}
- for (String s : table.getKeywords2()) {
+ for (String s : sorted(table.getKeywords2())) {
myKeywordModels[1].addElement(s);
}
- for (String s : table.getKeywords3()) {
+ for (String s : sorted(table.getKeywords3())) {
myKeywordModels[2].addElement(s);
}
- for (String s : table.getKeywords4()) {
+ for (String s : sorted(table.getKeywords4())) {
myKeywordModels[3].addElement(s);
}
}
}
+ private static String[] sorted(Set<String> keywords) {
+ String[] strings = ArrayUtil.toStringArray(keywords);
+ Arrays.sort(strings);
+ return strings;
+ }
+
@Override
public void applyEditorTo(AbstractFileType type) throws ConfigurationException {
if (myFileTypeName.getText().trim().length() == 0) {
public abstract class AbstractUpdateDialog extends DialogWrapper {
private final boolean myEnableLink;
- protected String myLicenseInfo = null;
-
protected AbstractUpdateDialog(boolean enableLink) {
super(true);
myEnableLink = enableLink;
val status: ChannelStatus = ChannelStatus.fromCode(node.getAttributeValue("status"))
val licensing: String = node.getAttributeValue("licensing", LICENSING_PRODUCTION)
val homePageUrl: String? = node.getAttributeValue("url")
+ val evalDays: Int = node.getAttributeValue("evalDays")?.toInt() ?: 30
val builds: List<BuildInfo> = node.getChildren("build").map { BuildInfo(it) }
override fun toString() = id
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
+import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
private final PatchInfo myPatch;
private final boolean myWriteProtected;
+ private String myLicenseInfo = null;
+ private Color myLicenseInfoColor = null;
+
UpdateInfoDialog(@NotNull UpdateChannel channel,
@NotNull BuildInfo newBuild,
@Nullable PatchInfo patch,
}
else {
Date buildDate = build.getReleaseDate();
- Date expiration = facade.getLicenseExpirationDate();
- if (buildDate != null && facade.isPerpetualForProduct(buildDate)) {
- myLicenseInfo = IdeBundle.message("updates.fallback.build");
- }
- else if (expiration != null && expiration.after(new Date())) {
- myLicenseInfo = IdeBundle.message("updates.subscription.active.till", DateFormatUtil.formatAboutDialogDate(expiration));
+ if (buildDate != null) {
+ if (!facade.isApplicableForProduct(buildDate)) {
+ myLicenseInfo = IdeBundle.message("updates.paid.upgrade", channel.getEvalDays());
+ myLicenseInfoColor = JBColor.RED;
+ }
+ else if (facade.isPerpetualForProduct(buildDate)) {
+ myLicenseInfo = IdeBundle.message("updates.fallback.build");
+ }
+ else {
+ Date expiration = facade.getLicenseExpirationDate();
+ myLicenseInfo = expiration != null
+ ? IdeBundle.message("updates.interim.build", DateFormatUtil.formatAboutDialogDate(expiration))
+ : IdeBundle.message("updates.interim.build.endless");
+ }
}
}
}
}
if (myLicenseInfo != null) {
- configureMessageArea(myLicenseArea, myLicenseInfo, null, null);
+ configureMessageArea(myLicenseArea, myLicenseInfo, myLicenseInfoColor, null);
}
}
}
import com.intellij.openapi.wm.impl.WindowManagerImpl;
import com.intellij.openapi.wm.impl.WindowWatcher;
import com.intellij.util.Alarm;
+import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import java.awt.*;
+import static com.intellij.openapi.wm.ToolWindowType.WINDOWED;
+
/**
* Requests focus for the specified tool window.
*
return;
}
if (c.isShowing()) {
+ if (WINDOWED == myToolWindow.getType()) {
+ Window window = UIUtil.getWindow(c);
+ if (window instanceof Frame) {
+ Frame frame = (Frame)window;
+ frame.setState(Frame.NORMAL);
+ }
+ }
final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
if (owner != null && owner == c) {
myManager.getFocusManager().requestFocus(new FocusCommand() {
public abstract boolean isEvaluationLicense();
+ public abstract boolean isApplicableForProduct(@NotNull Date productBuildDate);
+
public abstract boolean isPerpetualForProduct(@NotNull Date productBuildDate);
@Nullable
update.notifications.title=Platform and Plugin Updates
update.notifications.group=Platform and Plugin Updates
updates.channel.bundled.key=The new version has an expiration date and does not require a license key.
+updates.paid.upgrade=You can evaluate the new version for {0} days, or buy an upgrade online.
updates.fallback.build=You have perpetual fallback license for the new version.
-updates.subscription.active.till=Your subscription is active until {0}.
+updates.interim.build=You can use the new version until your subscription expires on {0}.
+updates.interim.build.endless=You can use the new version until your subscription expires.
updates.ready.message={0} is ready to <a href=\"update\">update</a>.
updates.external.progress=Fetching available updates for external components
updates.external.ready.message=The following component{0,choice,1# is|2#s are} ready to <a href="update">update</a>: {1}
serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl"/>
<projectService serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplateSettings"/>
<applicationService serviceImplementation="com.intellij.ide.fileTemplates.impl.ExportableFileTemplateSettings"/>
- <applicationService serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplatesLoader"/>
<applicationService serviceInterface="com.intellij.ide.PsiCopyPasteManager"
serviceImplementation="com.intellij.ide.PsiCopyPasteManager"/>
// This file contains list of broken plugins.
// Each line contains plugin ID and list of versions that are broken.
// If plugin name or version contains a space you can quote it like in command line.
-NodeJS 163.1479 163.1374.5 144.2986 144.2925.4 144.2911 144.2562 144.2131 144.988 143.1138 143.1088 143.769 143.751 143.516 143.381.8 143.380.6 143.381.11 143.380.8 143.444 143.379.15 143.21 143.110 143.250 142.4426 142.4100 142.3858 142.3224 142.2650 142.2492 142.2481 142.2064 141.1108 140.2045 140.1669 140.642 139.173 139.105 139.496 139.1 139.8 138.2196 138.2254 138.1684 138.1744 138.1879 138.2051 138.1367 138.1495 138.1189 138.1145 138.937 138.1013 138.921 138.447 138.172 138.317 138.21 138.35 138.96 138.85 136.1205 134.1276 134.1163 134.1145 134.1081 134.1039 134.985 134.680 134.31 134.307 134.262 134.198 134.125 136.1141
+NodeJS 163.1616 163.1479 163.1374.5 163.1105 163.1059 163.607 163.198 144.2986 144.2925.4 144.2911 144.2562 144.2131 144.988 143.1138 143.1088 143.769 143.751 143.516 143.381.8 143.380.6 143.381.11 143.380.8 143.444 143.379.15 143.21 143.110 143.250 142.4426 142.4100 142.3858 142.3224 142.2650 142.2492 142.2481 142.2064 141.1108 140.2045 140.1669 140.642 139.173 139.105 139.496 139.1 139.8 138.2196 138.2254 138.1684 138.1744 138.1879 138.2051 138.1367 138.1495 138.1189 138.1145 138.937 138.1013 138.921 138.447 138.172 138.317 138.21 138.35 138.96 138.85 136.1205 134.1276 134.1163 134.1145 134.1081 134.1039 134.985 134.680 134.31 134.307 134.262 134.198 134.125 136.1141
com.jetbrains.php 145.258.2 144.4199.11 144.3891.12 144.3656 144.3168 143.790 143.1770 143.1184.87 143.382.38 143.279 143.381.48 143.129 142.5282 142.2716 142.3969 142.4491 140.2765 141.332 139.732 139.659 139.496 139.173 139.105 138.2502 138.2000.2262 138.1751 138.1806 138.1505 138.1161 138.826 136.1768 136.1672 134.1456 133.982 133.679 133.51 133.326 131.98 131.374 131.332 131.235 131.205 130.1639 130.1481 130.1176 129.91 129.814 129.672 129.362 127.67 127.100 126.334 123.66 122.875 121.62 121.390 121.215 121.12
com.intellij.phing 133.51 131.374 129.672 127.67 124.347 121.62 121.390 121.215 121.12 117.746 117.694 117.501 117.257 117.222 117.132 114.282 114.158
com.intellij.plugins.html.instantEditing 162.5 0.4.1 0.4 0.3.9 0.3.8 0.3.7 0.3.6 0.3.5 0.3.3 0.3.2 0.3.10 0.3.1 0.3 0.2.27 0.2.25 0.2.24 0.2.23
import com.intellij.openapi.diff.impl.patch.formove.PatchApplier;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
+import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
new PatchApplier<BinaryFilePatch>(myProject, myRoot, patches, null, null, null).execute();
}
+
+ protected static void createChildDataWithContent(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
+ createChildData(dir, name);
+ VirtualFile file = dir.findChild(name);
+ setFileText(file, "some content");
+ }
}
import com.intellij.history.core.revisions.Difference;
import com.intellij.history.core.revisions.Revision;
import com.intellij.history.integration.PatchingTestCase;
+import com.intellij.idea.Bombed;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vfs.VirtualFile;
import java.util.ArrayList;
+import java.util.Calendar;
import java.util.List;
public class PatchCreatorTest extends PatchingTestCase {
- public void testCreationPatch() throws Exception {
+
+ @Bombed(user = "Nadya Zabrodina", day = 1, month = Calendar.OCTOBER,
+ description = "Now we are not able to apply empty file creation patch; git special tag needed or smth like that")
+ public void testCreationEmptyPatch() throws Exception {
createChildData(myRoot, "f.txt");
createPatchBetweenRevisions(1, 0);
}
public void testPatchBetweenTwoOldRevisions() throws Exception {
- createChildData(myRoot, "f1.txt");
- createChildData(myRoot, "f2.txt");
- createChildData(myRoot, "f3.txt");
+ createChildDataWithContent(myRoot, "f1.txt");
+ createChildDataWithContent(myRoot, "f2.txt");
+ createChildDataWithContent(myRoot, "f3.txt");
- createPatchBetweenRevisions(3, 1);
+ createPatchBetweenRevisions(6, 1);
clearRoot();
applyPatch();
-
+ myRoot.refresh(false, true);
assertNotNull(myRoot.findChild("f1.txt"));
assertNotNull(myRoot.findChild("f2.txt"));
assertNull(myRoot.findChild("f3.txt"));
public void testRename() throws Exception {
VirtualFile f = createChildData(myRoot, "f.txt");
- setBinaryContent(f,new byte[]{'x'});
+ setBinaryContent(f, new byte[]{'x'});
rename(f, "ff.txt");
}
public void testReversePatch() throws Exception {
- createChildData(myRoot, "f.txt");
-
- createPatchBetweenRevisions(1, 0, true);
+ createChildDataWithContent(myRoot, "f.txt");
+ createPatchBetweenRevisions(2, 0, true);
applyPatch();
assertNull(myRoot.findChild("f.txt"));
public void testDirectoryCreationWithFiles() throws Exception {
VirtualFile dir = createChildDirectory(myRoot, "dir");
- createChildData(dir, "f.txt");
+ createChildDataWithContent(dir, "f.txt");
createPatchBetweenRevisions(2, 0, false);
clearRoot();
public void testDirectoryDeletionWithFiles() throws Exception {
VirtualFile dir = createChildDirectory(myRoot, "dir");
- createChildData(dir, "f1.txt");
- createChildData(dir, "f2.txt");
+ createChildDataWithContent(dir, "f1.txt");
+ createChildDataWithContent(dir, "f2.txt");
delete(dir);
createPatchBetweenRevisions(1, 0, false);
dir = createChildDirectory(myRoot, "dir");
- createChildData(dir, "f1.txt");
- createChildData(dir, "f2.txt");
+ createChildDataWithContent(dir, "f1.txt");
+ createChildDataWithContent(dir, "f2.txt");
applyPatch();
public void testDirectoryRename() throws Exception {
VirtualFile dir = createChildDirectory(myRoot, "dir1");
- createChildData(dir, "f.txt");
+ createChildDataWithContent(dir, "f.txt");
rename(dir, "dir2");
public class DirectoryHistoryDialogPatchCreationTest extends PatchingTestCase {
public void testPatchCreation() throws Exception {
- createChildData(myRoot, "f1.txt");
- createChildData(myRoot, "f2.txt");
- createChildData(myRoot, "f3.txt");
+ createChildDataWithContent(myRoot, "f1.txt");
+ createChildDataWithContent(myRoot, "f2.txt");
+ createChildDataWithContent(myRoot, "f3.txt");
DirectoryHistoryDialogModel m = new DirectoryHistoryDialogModel(myProject, myGateway, getVcs(), myRoot);
- assertSize(3, m.getRevisions());
+ assertSize(6, m.getRevisions());
- m.selectRevisions(0, 2);
+ m.selectRevisions(0, 5);
m.createPatch(patchFilePath, myProject.getBasePath(), false, Charset.defaultCharset());
clearRoot();
import com.intellij.ide.fileTemplates.FileTemplateManager;
import com.intellij.ide.fileTemplates.FileTemplatesScheme;
import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.util.Disposer;
String newText = "good bye";
template.setText(newText);
assertEquals(newText, manager.getTemplate(TEST_TEMPLATE_TXT).getText());
-
+ manager.saveAllTemplates();
PlatformTestUtil.saveProject(project);
closeProject(project);
myTemplateManager.removeTemplate(template);
assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
myTemplateManager.setCurrentScheme(myTemplateManager.getProjectScheme());
- assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
+ assertNotNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
myTemplateManager.setCurrentScheme(FileTemplatesScheme.DEFAULT);
assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
}
assertTrue(template.isReformatCode());
template.setReformatCode(false);
- FileTemplateSettings settings = FileTemplateSettings.getInstance(getProject());
+ FileTemplateSettings settings = ServiceManager.getService(ExportableFileTemplateSettings.class);
Element state = settings.getState();
assertNotNull(state);
Element element = state.getChildren().get(0).getChildren().get(0);
assertFalse(((FileTemplateBase)myTemplateManager.getTemplate(TEST_TEMPLATE_TXT)).isLiveTemplateEnabledByDefault());
FileTemplateBase template = (FileTemplateBase)myTemplateManager.getTemplate("templateWithLiveTemplate.txt");
assertTrue(template.isLiveTemplateEnabledByDefault());
- FileTemplateSettings settings = FileTemplateSettings.getInstance(getProject());
+ FileTemplateSettings settings = ServiceManager.getService(ExportableFileTemplateSettings.class);
assertNull(settings.getState());
template.setLiveTemplateEnabled(false);
Element state = settings.getState();
* By default, IntelliJ Platform considers files as tests only if they are located under test
* sources root {@link FileIndex#isInTestSourceContent(VirtualFile)}.
* <p>
- * However there plenty frameworks and languages which keep test files just nearby production files.
+ * However there are plenty frameworks and languages which keep test files just nearby production files.
* E.g. *_test.go files are test files in Go language and some js/dart files are test files depending
* on their content. The extensions allow IDE to highlight such files with a green background,
* properly check if they are included in built-in search scopes, etc.
* @since 2016.3
* @author zolotov
*/
-
public abstract class TestSourcesFilter {
public static final ExtensionPointName<TestSourcesFilter> EP_NAME = ExtensionPointName.create("com.intellij.testSourcesFilter");
*/
package com.intellij.util.containers;
+import com.intellij.util.ArrayFactory;
+import com.intellij.util.ArrayUtil;
import com.intellij.util.text.StringFactory;
-
-import java.util.ArrayList;
+import org.jetbrains.annotations.NotNull;
public class CharTrie {
- private ArrayList<Node> myAllNodes;
-
- private static class Node {
- private final char myChar;
- private final int myParent;
- private IntArrayList myChildren;
-
- Node(int parent, char c) {
- myChar = c;
- myParent = parent;
- }
- }
+ private int myAllNodesSize;
+ private char[] myAllNodesChars;
+ private char[] myAllNodesParents; // unsigned short
+ private char[][] myAllNodesChildren; // unsigned short
public CharTrie() {
init();
}
private void init() {
- myAllNodes = new ArrayList<Node>();
- final Node root = new Node(-1, (char)0);
- myAllNodes.add(root);
+ myAllNodesChars = null;
+ myAllNodesParents = null;
+ myAllNodesChildren = null;
+ myAllNodesSize = 0;
+ addNode(-1, (char)0);
+ }
+
+ private void addNode(int parentIndex, char ch) {
+ if (myAllNodesSize == 0) {
+ int initialCapacity = 10;
+ myAllNodesChars = new char[initialCapacity];
+ myAllNodesParents = new char[initialCapacity];
+ myAllNodesChildren = new char[initialCapacity][];
+ } else if (myAllNodesSize >= myAllNodesChars.length) {
+ int increment = Math.max(myAllNodesSize >> 2, 10);
+
+ int newSize = myAllNodesSize + increment;
+ myAllNodesChars = ArrayUtil.realloc(myAllNodesChars, newSize);
+ myAllNodesParents = ArrayUtil.realloc(myAllNodesParents, newSize);
+ myAllNodesChildren = ArrayUtil.realloc(myAllNodesChildren, newSize, FACTORY);
+ }
+
+ myAllNodesChars[myAllNodesSize] = ch;
+ myAllNodesParents[myAllNodesSize] = (char)parentIndex;
+ myAllNodesChildren[myAllNodesSize] = null;
+ ++myAllNodesSize;
+ assert myAllNodesSize < Character.MAX_VALUE;
}
public int size() {
- return myAllNodes.size();
+ return myAllNodesSize;
}
/**
int length = 0;
int run = hashCode;
while (run > 0) {
- final CharTrie.Node node = myAllNodes.get(run);
length++;
- run = node.myParent;
+ run = myAllNodesParents[run];
}
char[] result = new char[length];
run = hashCode;
for (int i = 0; i < length; i++) {
assert run > 0;
- final CharTrie.Node node = myAllNodes.get(run);
- result[length - i - 1] = node.myChar;
- run = node.myParent;
+ result[length - i - 1] = myAllNodesChars[run];
+ run = myAllNodesParents[run];
}
return result;
int length = 0;
int run = hashCode;
while (run > 0) {
- final CharTrie.Node node = myAllNodes.get(run);
length++;
- run = node.myParent;
+ run = myAllNodesParents[run];
}
char[] result = new char[length];
run = hashCode;
for (int i = 0; i < length; i++) {
assert run > 0;
- final CharTrie.Node node = myAllNodes.get(run);
- result[i] = node.myChar;
- run = node.myParent;
+ result[i] = myAllNodesChars[run];
+ run = myAllNodesParents[run];
}
return result;
public int findSubNode(int parentIndex, char c) {
return getSubNode(parentIndex, c, false);
}
-
+
+ private static final int LENGTH_SLOT_LENGTH = 1;
+
private int getSubNode(int parentIndex, char c, boolean createIfNotExists) {
- CharTrie.Node parentNode = myAllNodes.get(parentIndex);
- if (parentNode.myChildren == null) {
+ if (myAllNodesChildren[parentIndex] == null) {
if (!createIfNotExists) {
return 0;
}
- parentNode.myChildren = new IntArrayList(1);
+ char[] chars = new char[1 + LENGTH_SLOT_LENGTH];
+ myAllNodesChildren[parentIndex] = chars;
}
- IntArrayList children = parentNode.myChildren;
+
+ char[] children = myAllNodesChildren[parentIndex];
+ char childrenCount = children[children.length - LENGTH_SLOT_LENGTH];
int left = 0;
- int right = children.size() - 1;
+ int right = childrenCount - 1;
while (left <= right) {
int middle = (left + right) >> 1;
- int index = children.get(middle);
- CharTrie.Node node = myAllNodes.get(index);
- int comp = node.myChar - c;
+ int index = children[middle];
+ int comp = myAllNodesChars[index] - c;
if (comp == 0) {
return index;
}
if (!createIfNotExists) {
return 0;
}
-
- int index = myAllNodes.size();
- children.add(left, index);
- myAllNodes.add(new CharTrie.Node(parentIndex, c));
+
+ if (childrenCount == children.length - LENGTH_SLOT_LENGTH) {
+ children = myAllNodesChildren[parentIndex] = ArrayUtil.realloc(children, (children.length * 3 / 2 + 1) + LENGTH_SLOT_LENGTH);
+ }
+
+ if (left != childrenCount) {
+ System.arraycopy(children, left, children, left + 1, childrenCount - left);
+ }
+
+ int index = myAllNodesSize;
+ children[left] = (char)index;
+ assert childrenCount + 1 < Character.MAX_VALUE;
+ children[children.length - LENGTH_SLOT_LENGTH] = (char)(childrenCount + 1);
+
+ addNode(parentIndex, c);
return index;
}
public void clear() {
init();
}
+
+ private static final ArrayFactory<char[]> FACTORY = new ArrayFactory<char[]>() {
+ @NotNull
+ @Override
+ public char[][] create(int count) {
+ return new char[count][];
+ }
+ };
}
import org.jetbrains.annotations.Nullable;
import java.io.File;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
final long started = IOStatistics.DEBUG ? System.currentTimeMillis():0;
myStorageLockContext.myStorageLock.invalidateBuffer(myStorageIndex | (int)(oldSize / myPageSize)); // TODO long page
-
final long unmapAllFinished = IOStatistics.DEBUG ? System.currentTimeMillis():0;
- mySize = -1;
+ resizeFile(newSize);
+ // it is not guaranteed that new partition will consist of null
+ // after resize, so we should fill it manually
long delta = newSize - oldSize;
-
- if (delta > 0) {
- // it is not guaranteed that new partition will consist of null
- // after resize, so we should fill it manually
- byte[] buff = new byte[MAX_FILLER_SIZE];
- Arrays.fill(buff, (byte)0);
- FileOutputStream stream = new FileOutputStream(myFile, true);
-
- try {
- while (delta > 0) {
- final int filled = Math.min((int)delta, MAX_FILLER_SIZE);
- stream.write(buff, 0, filled);
- delta -= filled;
- }
- } finally {
- stream.getFD().sync();
- stream.close();
- }
- }
- else {
- RandomAccessFile raf = new RandomAccessFile(myFile, RW);
- try {
- raf.setLength(newSize);
- raf.getFD().sync();
- }
- finally {
- raf.close();
- }
- }
-
- mySize = newSize;
+ if (delta > 0) fillWithZeros(oldSize, delta);
if (IOStatistics.DEBUG) {
long finished = System.currentTimeMillis();
}
}
+ private void resizeFile(long newSize) throws IOException {
+ mySize = -1;
+ RandomAccessFile raf = new RandomAccessFile(myFile, RW);
+ try {
+ raf.setLength(newSize);
+ }
+ finally {
+ raf.close();
+ }
+ mySize = newSize;
+ }
+
private static final int MAX_FILLER_SIZE = 8192;
+ private void fillWithZeros(long from, long length) {
+ byte[] buff = new byte[MAX_FILLER_SIZE];
+ Arrays.fill(buff, (byte)0);
+
+ while (length > 0) {
+ final int filled = Math.min((int)length, MAX_FILLER_SIZE);
+ put(from, buff, 0, filled);
+ length -= filled;
+ from += filled;
+ }
+ }
+
public final long length() {
long size = mySize;
if (size == -1) {
setupAntialiasing(g2, true, false);
}
- public static int stringWidth(String text, Font font) {
+ public static int stringWidth(@NotNull String text, Font font) {
setupAntialiasing(ourGraphics, true, true);
return ourGraphics.getFontMetrics(font).stringWidth(text);
}
private final TreeMap<TextRange, MyAppliedData> myTransformations;
private final List<String> myLines;
private final List<PatchHunk> myHunks;
+ private final boolean myBaseFileEndsWithNewLine;
private boolean myHadAlreadyAppliedMet;
private final ArrayList<SplitHunk> myNotBound;
debug("GenericPatchApplier created, hunks: " + hunks.size());
myLines = new ArrayList<String>();
Collections.addAll(myLines, LineTokenizer.tokenize(text, false));
+ myBaseFileEndsWithNewLine = StringUtil.endsWithLineBreak(text);
myHunks = hunks;
final Comparator<TextRange> textRangeComparator =
(o1, o2) -> new Integer(o1.getStartOffset()).compareTo(new Integer(o2.getStartOffset()));
for (SplitHunk hunk : myNotBound) {
linesToSb(sb, hunk.getAfterAll());
}
- iterateTransformations(range -> linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1)), range -> {
+ iterateTransformations(range -> {
+ linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1));
+ if (containsLastLine(range) && myBaseFileEndsWithNewLine) {
+ sb.append('\n');
+ }
+ }, range -> {
final MyAppliedData appliedData = myTransformations.get(range);
linesToSb(sb, appliedData.getList());
+ if (containsLastLine(range) && !mySuppressNewLineInEnd) {
+ sb.append('\n');
+ }
});
- if (! mySuppressNewLineInEnd) {
- sb.append('\n');
- }
return sb.toString();
}
+ private boolean containsLastLine(@NotNull TextRange range) {
+ return range.getEndOffset() == myLines.size() - 1;
+ }
+
private static void linesToSb(final StringBuilder sb, final List<String> list) {
if (sb.length() > 0 && !list.isEmpty()) {
sb.append("\n");
}
@NotNull
- private static Notification createNotification(@NotNull NotificationGroup notificationGroup,
- @NotNull String title, @NotNull String message, @NotNull NotificationType type,
- @Nullable NotificationListener listener) {
+ public static Notification createNotification(@NotNull NotificationGroup notificationGroup,
+ @NotNull String title,
+ @NotNull String message,
+ @NotNull NotificationType type,
+ @Nullable NotificationListener listener) {
// title can be empty; message can't be neither null, nor empty
if (StringUtil.isEmptyOrSpaces(message)) {
message = title;
}
@NotNull
- protected Notification notify(@NotNull NotificationGroup notificationGroup, @NotNull String title, @NotNull String message,
- @NotNull NotificationType type, @Nullable NotificationListener listener) {
+ public Notification notify(@NotNull NotificationGroup notificationGroup,
+ @NotNull String title,
+ @NotNull String message,
+ @NotNull NotificationType type,
+ @Nullable NotificationListener listener) {
Notification notification = createNotification(notificationGroup, title, message, type, listener);
notification.notify(myProject);
return notification;
}
+ @NotNull
+ public Notification notify(@NotNull Notification notification) {
+ notification.notify(myProject);
+ return notification;
+ }
+
@NotNull
public Notification notifyError(@NotNull String title, @NotNull String message) {
return notifyError(title, message, null);
*/
package com.intellij.vcs.log;
+import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
Collection<VcsRef> getBranches();
@NotNull
- Collection<VcsRef> refsToCommit(int commit);
+ Collection<VcsRef> refsToCommit(@NotNull Hash hash, @NotNull VirtualFile root);
@NotNull
Collection<VcsRef> getAllRefs();
PermanentGraph<Integer> graph = dataPack.getPermanentGraph();
VcsLogRefs refs = dataPack.getRefsModel();
- VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
- vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
- if (branchRef == null) return Conditions.alwaysFalse();
ContainedInBranchCondition condition = myConditions.get(root);
if (condition == null || !condition.getBranch().equals(branchName)) {
+ VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
+ vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
+ if (branchRef == null) return Conditions.alwaysFalse();
condition = new ContainedInBranchCondition(graph.getContainedInBranchCondition(
Collections.singleton(myLogData.getCommitIndex(branchRef.getCommitHash(), branchRef.getRoot()))), branchName);
myConditions.put(root, condition);
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
-import com.intellij.vcs.log.CommitId;
-import com.intellij.vcs.log.VcsLogHashMap;
-import com.intellij.vcs.log.VcsLogRefs;
-import com.intellij.vcs.log.VcsRef;
+import com.intellij.vcs.log.*;
import gnu.trove.TIntObjectHashMap;
import org.jetbrains.annotations.NotNull;
public class RefsModel implements VcsLogRefs {
@NotNull private final Collection<VcsRef> myBranches;
@NotNull private final Map<VirtualFile, Set<VcsRef>> myRefs;
+ @NotNull private final VcsLogHashMap myHashMap;
@NotNull private final TIntObjectHashMap<SmartList<VcsRef>> myRefsToHashes;
@NotNull private final TIntObjectHashMap<VirtualFile> myRootsToHeadIndices;
@NotNull final Set<Integer> heads,
@NotNull final VcsLogHashMap hashMap) {
myRefs = refsByRoot;
+ myHashMap = hashMap;
Iterable<VcsRef> allRefs = Iterables.concat(refsByRoot.values());
@NotNull
public Collection<VcsRef> branchesToCommit(int index) {
Collection<VcsRef> refs = refsToCommit(index);
- return refs.stream().filter(ref -> ref.getType().isBranch()).collect(Collectors.toList());
+ return ContainerUtil.filter(refs, ref -> ref.getType().isBranch());
}
@NotNull
@NotNull
@Override
+ public Collection<VcsRef> refsToCommit(@NotNull Hash hash, @NotNull VirtualFile root) {
+ return refsToCommit(myHashMap.getCommitIndex(hash, root));
+ }
+
public Collection<VcsRef> refsToCommit(int index) {
if (myRefsToHashes.containsKey(index)) {
return myRefsToHashes.get(index);
@Override
public Iterator<VcsRef> iterator() {
List<Iterator<VcsRef>> iterators = myRefs.values().stream().map(Set::iterator).collect(Collectors.toList());
- return Iterators.concat(iterators.toArray(new Iterator[iterators.size()]));
+ return Iterators.concat(iterators.iterator());
}
@Override
package com.intellij.vcs.log.ui;
import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.Conditions;
+import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
+import com.intellij.util.containers.ContainerUtil;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.impl.VcsLogUtil;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
+import java.util.Map;
public class CurrentBranchHighlighter implements VcsLogHighlighter {
private static final JBColor CURRENT_BRANCH_BG = new JBColor(new Color(228, 250, 255), new Color(63, 71, 73));
private static final String HEAD = "HEAD";
@NotNull private final VcsLogData myLogData;
@NotNull private final VcsLogUi myLogUi;
+ @NotNull private final Map<VirtualFile, Condition<CommitId>> myConditions = ContainerUtil.newHashMap();
@Nullable private String mySingleFilteredBranch;
public CurrentBranchHighlighter(@NotNull VcsLogData logData, @NotNull VcsLogUi logUi) {
@Override
public VcsCommitStyle getStyle(@NotNull VcsShortCommitDetails details, boolean isSelected) {
if (isSelected || !myLogUi.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT;
- VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
- String currentBranch = provider.getCurrentBranch(details.getRoot());
- if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
- Condition<CommitId> condition =
- myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
- if (condition.value(new CommitId(details.getId(), details.getRoot()))) {
- return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
+ Condition<CommitId> condition = myConditions.get(details.getRoot());
+ if (condition == null) {
+ VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
+ String currentBranch = provider.getCurrentBranch(details.getRoot());
+ if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
+ condition = myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
+ myConditions.put(details.getRoot(), condition);
}
+ else {
+ condition = Conditions.alwaysFalse();
+ }
+ }
+ if (condition != null && condition.value(new CommitId(details.getId(), details.getRoot()))) {
+ return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
}
return VcsCommitStyle.DEFAULT;
}
public void update(@NotNull VcsLogDataPack dataPack, boolean refreshHappened) {
VcsLogBranchFilter branchFilter = dataPack.getFilters().getBranchFilter();
mySingleFilteredBranch = branchFilter == null ? null : VcsLogUtil.getSingleFilteredBranch(branchFilter, dataPack.getRefs());
+ myConditions.clear();
}
public static class Factory implements VcsLogHighlighterFactory {
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.StatusText;
import com.intellij.vcs.log.VcsFullCommitDetails;
+import com.intellij.vcs.log.data.RefsModel;
import com.intellij.vcs.log.data.VcsLogData;
import com.intellij.vcs.log.data.VisiblePack;
import com.intellij.vcs.log.ui.VcsLogColorManager;
for (int i = 0; i < mySelection.size(); i++) {
CommitPanel commitPanel = getCommitPanel(i);
Integer commit = myDataPack.getVisibleGraph().getRowInfo(mySelection.get(i)).getCommit();
- commitPanel.setCommit(detailsList.get(i), myDataPack.getRefs().refsToCommit(commit));
+ commitPanel.setCommit(detailsList.get(i), ((RefsModel)myDataPack.getRefs()).refsToCommit(commit));
}
if (!ContainerUtil.intersects(myCommitDetails, newCommitDetails)) {
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.DateFormatUtil;
import com.intellij.vcs.log.*;
-import com.intellij.vcs.log.data.CommitIdByStringCondition;
-import com.intellij.vcs.log.data.DataGetter;
-import com.intellij.vcs.log.data.VcsLogData;
-import com.intellij.vcs.log.data.VisiblePack;
+import com.intellij.vcs.log.data.*;
import com.intellij.vcs.log.impl.VcsLogUtil;
import com.intellij.vcs.log.ui.VcsLogUiImpl;
import com.intellij.vcs.log.ui.render.GraphCommitCell;
@NotNull
private Collection<VcsRef> getRefsAtRow(int row) {
- return myDataPack.getRefs().refsToCommit(getIdAtRow(row));
+ return ((RefsModel)myDataPack.getRefs()).refsToCommit(getIdAtRow(row));
}
@NotNull
public class TestVcsNotifier extends VcsNotifier {
- public static final String TEST_NOTIFICATION_GROUP = "Test";
+ private static final String TEST_NOTIFICATION_GROUP = "Test";
private Notification myLastNotification;
return myLastNotification;
}
+ @NotNull
+ public Notification notify(@NotNull Notification notification) {
+ myLastNotification = notification;
+ return myLastNotification;
+ }
+
public void cleanup() {
myLastNotification = null;
}
*
*/
@NotNull
- XLocalAttachGroup getAttachGroup();
+ default XLocalAttachGroup getAttachGroup() {
+ return XLocalAttachGroup.DEFAULT;
+ }
/**
* Attach to Local Process action invokes {@link #getAvailableDebuggers} method for every running process.
<extensions defaultExtensionNs="com.intellij">
<inspectionElementsMerger implementation="com.siyeh.ig.bugs.ThrowableNeverThrownInspectionMerger"/>
+ <inspectionElementsMerger implementation="com.siyeh.ig.naming.MisspelledMethodNameInspectionMerger"/>
<!--group.names.abstraction.issues-->
<localInspection groupPath="Java" language="JAVA" shortName="BooleanParameter" bundle="com.siyeh.InspectionGadgetsBundle" key="boolean.parameter.display.name"
bundle="com.siyeh.InspectionGadgetsBundle" key="mismatched.string.builder.query.update.display.name" runForWholeFile="true"
groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="true" level="WARNING"
implementationClass="com.siyeh.ig.bugs.MismatchedStringBuilderQueryUpdateInspection"/>
- <localInspection groupPath="Java" language="JAVA" shortName="MisspelledCompareTo" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.compareto.display.name"
- groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
- implementationClass="com.siyeh.ig.bugs.MisspelledCompareToInspection"/>
- <localInspection groupPath="Java" language="JAVA" shortName="MisspelledHashcode" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.hashcode.display.name"
- groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
- implementationClass="com.siyeh.ig.bugs.MisspelledHashcodeInspection"/>
<localInspection groupPath="Java" language="JAVA" shortName="MisspelledEquals" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.equals.display.name"
groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
implementationClass="com.siyeh.ig.bugs.MisspelledEqualsInspection"/>
- <localInspection groupPath="Java" language="JAVA" shortName="MisspelledToString" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.tostring.display.name"
- groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
- implementationClass="com.siyeh.ig.bugs.MisspelledToStringInspection"/>
<localInspection groupPath="Java" language="JAVA" shortName="NewStringBufferWithCharArgument" bundle="com.siyeh.InspectionGadgetsBundle"
key="new.string.buffer.with.char.argument.display.name" groupBundle="messages.InspectionsBundle"
groupKey="group.names.probable.bugs" enabledByDefault="true" level="WARNING"
key="junit.test.class.naming.convention.display.name" groupBundle="messages.InspectionsBundle"
groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
implementationClass="com.siyeh.ig.junit.JUnitTestClassNamingConventionInspection"/>
- <localInspection groupPath="Java" language="JAVA" shortName="MisspelledSetUp" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.set.up.display.name"
- groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
- implementationClass="com.siyeh.ig.junit.MisspelledSetUpInspection"/>
- <localInspection groupPath="Java" language="JAVA" shortName="MisspelledTearDown" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.tear.down.display.name"
- groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
- implementationClass="com.siyeh.ig.junit.MisspelledTearDownInspection"/>
<localInspection groupPath="Java" language="JAVA" suppressId="MisorderedAssertEqualsArguments" alternativeId="MisorderedAssertEqualsArguments" shortName="MisorderedAssertEqualsParameters"
bundle="com.siyeh.InspectionGadgetsBundle" key="misordered.assert.equals.arguments.display.name"
groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
key="method.name.same.as.parent.name.display.name" groupBundle="messages.InspectionsBundle"
groupKey="group.names.naming.conventions" enabledByDefault="false" level="WARNING"
implementationClass="com.siyeh.ig.naming.MethodNameSameAsParentNameInspection"/>
- <localInspection groupPath="Java" language="JAVA" suppressId="MethodNamesDifferingOnlyByCase" shortName="MethodNamesDifferOnlyByCase"
+ <localInspection groupPath="Java" language="JAVA" suppressId="MethodNamesDifferingOnlyByCase" shortName="MisspelledMethodName"
bundle="com.siyeh.InspectionGadgetsBundle" key="method.names.differ.only.by.case.display.name"
groupBundle="messages.InspectionsBundle" groupKey="group.names.naming.conventions" enabledByDefault="false"
- level="WARNING" implementationClass="com.siyeh.ig.naming.MethodNamesDifferOnlyByCaseInspection"/>
+ level="WARNING" implementationClass="com.siyeh.ig.naming.MisspelledMethodNameInspection"/>
<localInspection groupPath="Java" language="JAVA" shortName="NativeMethodNamingConvention"
bundle="com.siyeh.InspectionGadgetsBundle" key="native.method.naming.convention.display.name"
groupBundle="messages.InspectionsBundle" groupKey="group.names.naming.conventions" enabledByDefault="false"
+++ /dev/null
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledCompareToInspectionBase extends BaseInspection {
- @Override
- @NotNull
- public String getDisplayName() {
- return InspectionGadgetsBundle.message(
- "misspelled.compareto.display.name");
- }
-
- @Override
- @NotNull
- public String buildErrorString(Object... infos) {
- return InspectionGadgetsBundle.message(
- "misspelled.compareto.problem.descriptor");
- }
-
- @Override
- public BaseInspectionVisitor buildVisitor() {
- return new MisspelledCompareToVisitor();
- }
-
- private static class MisspelledCompareToVisitor
- extends BaseInspectionVisitor {
-
- @Override
- public void visitMethod(@NotNull PsiMethod method) {
- //note: no call to super
- @NonNls final String methodName = method.getName();
- if (!"compareto".equals(methodName)) {
- return;
- }
- final PsiParameterList parameterList = method.getParameterList();
- if (parameterList.getParametersCount() != 1) {
- return;
- }
- registerMethodError(method);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledHashcodeInspectionBase extends BaseInspection {
- @Override
- @NotNull
- public String getDisplayName() {
- return InspectionGadgetsBundle.message(
- "misspelled.hashcode.display.name");
- }
-
- @Override
- @NotNull
- public String buildErrorString(Object... infos) {
- return InspectionGadgetsBundle.message(
- "misspelled.hashcode.problem.descriptor");
- }
-
- @Override
- public BaseInspectionVisitor buildVisitor() {
- return new MisspelledHashcodeVisitor();
- }
-
- private static class MisspelledHashcodeVisitor
- extends BaseInspectionVisitor {
-
- @Override
- public void visitMethod(@NotNull PsiMethod method) {
- //note: no call to super
- @NonNls final String methodName = method.getName();
- if (!"hashcode".equals(methodName)) {
- return;
- }
- final PsiParameterList parameterList = method.getParameterList();
- if (parameterList.getParametersCount() != 0) {
- return;
- }
- registerMethodError(method);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledToStringInspectionBase extends BaseInspection {
- @Override
- @NotNull
- public String getDisplayName() {
- return InspectionGadgetsBundle.message(
- "misspelled.tostring.display.name");
- }
-
- @Override
- @NotNull
- public String buildErrorString(Object... infos) {
- return InspectionGadgetsBundle.message(
- "misspelled.tostring.problem.descriptor");
- }
-
- @Override
- public BaseInspectionVisitor buildVisitor() {
- return new MisspelledToStringVisitor();
- }
-
- private static class MisspelledToStringVisitor
- extends BaseInspectionVisitor {
-
- @Override
- public void visitMethod(@NotNull PsiMethod method) {
- //note: no call to super
- @NonNls final String methodName = method.getName();
- if (!"tostring".equals(methodName)) {
- return;
- }
- final PsiParameterList parameterList = method.getParameterList();
- if (parameterList.getParametersCount() != 0) {
- return;
- }
- registerMethodError(method);
- }
- }
-}
public class ThrowableNeverThrownInspectionMerger extends InspectionElementsMerger {
@Override
- protected String getMergedToolName() {
+ public String getMergedToolName() {
return "ThrowableNeverThrown";
}
@Override
- protected String[] getSourceToolNames() {
+ public String[] getSourceToolNames() {
return new String[] {"ThrowableInstanceNeverThrown", "ThrowableResultOfMethodCallIgnored"};
}
}
+++ /dev/null
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.junit;
-
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.util.InheritanceUtil;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledSetUpInspectionBase extends BaseInspection {
- @Override
- @NotNull
- public String getDisplayName() {
- return InspectionGadgetsBundle.message(
- "misspelled.set.up.display.name");
- }
-
- @Override
- @NotNull
- protected String buildErrorString(Object... infos) {
- return InspectionGadgetsBundle.message(
- "misspelled.set.up.problem.descriptor");
- }
-
- @Override
- public BaseInspectionVisitor buildVisitor() {
- return new MisspelledSetUpVisitor();
- }
-
- @Override
- protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
- return true;
- }
-
- private static class MisspelledSetUpVisitor extends BaseInspectionVisitor {
-
- @Override
- public void visitMethod(@NotNull PsiMethod method) {
- //note: no call to super
- final PsiClass aClass = method.getContainingClass();
- @NonNls final String methodName = method.getName();
- if (!"setup".equals(methodName)) {
- return;
- }
- if (aClass == null) {
- return;
- }
- if (!InheritanceUtil.isInheritor(aClass,
- "junit.framework.TestCase")) {
- return;
- }
- registerMethodError(method);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.junit;
-
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.util.InheritanceUtil;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledTearDownInspectionBase extends BaseInspection {
- @Override
- @NotNull
- public String getDisplayName() {
- return InspectionGadgetsBundle.message(
- "misspelled.tear.down.display.name");
- }
-
- @Override
- @NotNull
- protected String buildErrorString(Object... infos) {
- return InspectionGadgetsBundle.message(
- "misspelled.tear.down.problem.descriptor");
- }
-
- @Override
- public BaseInspectionVisitor buildVisitor() {
- return new MisspelledSetUpVisitor();
- }
-
- @Override
- protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
- return true;
- }
-
- private static class MisspelledSetUpVisitor extends BaseInspectionVisitor {
-
- @Override
- public void visitMethod(@NotNull PsiMethod method) {
- // note: no call to super
- @NonNls final String methodName = method.getName();
- if (!"teardown".equals(methodName)) {
- return;
- }
- final PsiClass aClass = method.getContainingClass();
- if (aClass == null) {
- return;
- }
- if (!InheritanceUtil.isInheritor(aClass,
- "junit.framework.TestCase")) {
- return;
- }
- registerMethodError(method);
- }
- }
-}
import java.util.Map;
-public class MethodNamesDifferOnlyByCaseInspectionBase extends BaseInspection {
+public class MisspelledMethodNameInspectionBase extends BaseInspection {
@SuppressWarnings("PublicField")
public boolean ignoreIfMethodIsOverride = true;
- @Override
- @NotNull
- public String getID() {
- return "MethodNamesDifferingOnlyByCase";
- }
-
@Override
@NotNull
public String getDisplayName() {
/*
- * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
+ * Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package com.siyeh.ig.bugs;
+package com.siyeh.ig.naming;
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
+import com.intellij.codeInspection.ex.InspectionElementsMerger;
-public class MisspelledToStringInspection extends MisspelledToStringInspectionBase {
+public class MisspelledMethodNameInspectionMerger extends InspectionElementsMerger {
@Override
- protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix(HardcodedMethodConstants.TO_STRING);
+ public String getMergedToolName() {
+ return "MisspelledMethodName";
}
-}
\ No newline at end of file
+
+ @Override
+ public String[] getSourceToolNames() {
+ return new String[]{"MethodNamesDifferOnlyByCase", "MisspelledSetUp", "MisspelledTearDown", "MisspelledHashcode", "MisspelledToString", "MisspelledCompareTo"};
+ }
+}
+++ /dev/null
-/*
- * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.bugs;
-
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledHashcodeInspection extends MisspelledHashcodeInspectionBase {
-
- @Override
- protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix(HardcodedMethodConstants.HASH_CODE);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.junit;
-
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledSetUpInspection extends MisspelledSetUpInspectionBase {
-
- @Override
- protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix("setUp");
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.siyeh.ig.junit;
-
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledTearDownInspection extends MisspelledTearDownInspectionBase {
-
- @Override
- protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix("tearDown");
- }
-}
\ No newline at end of file
import javax.swing.*;
-public class MethodNamesDifferOnlyByCaseInspection extends MethodNamesDifferOnlyByCaseInspectionBase {
+public class MisspelledMethodNameInspection extends MisspelledMethodNameInspectionBase {
@Override
public JComponent createOptionsPanel() {
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
- return new RenameFix();
+ return new RenameFix((String)infos[0]);
}
}
\ No newline at end of file
void xx() {}
void xX() {}
+
+ @SuppressWarnings("MisspelledToString")
+ public String tostring() {
+ return "";
+ }
}
public class MethodNamesDifferOnlyByCaseInspectionTest extends IGInspectionTestCase {
public void test() throws Exception {
- doTest("com/siyeh/igtest/naming/method_names_differ_only_by_case", new MethodNamesDifferOnlyByCaseInspection());
+ doTest("com/siyeh/igtest/naming/method_names_differ_only_by_case", new MisspelledMethodNameInspection());
}
}
\ No newline at end of file
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.components.JBLabel;
import com.intellij.util.ArrayUtil;
import com.intellij.xml.util.XmlStringUtil;
import git4idea.DialogManager;
-import git4idea.GitBranch;
import git4idea.GitCommit;
-import git4idea.i18n.GitBundle;
import git4idea.repo.GitRepository;
import git4idea.ui.GitCommitListWithDiffPanel;
import git4idea.ui.GitRepositoryComboboxListCellRenderer;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
private final Project myProject;
private final Map<GitRepository, List<GitCommit>> myCommits;
- private final String myBranchToDelete;
- private final String myBaseBranch;
- private final List<String> myMergedToBranches;
private final GitCommitListWithDiffPanel myCommitListWithDiffPanel;
private final Collection<GitRepository> myRepositories;
+ @NotNull private final String myRemovedBranch;
+ @NotNull private final Map<GitRepository, String> myBaseBranches;
private final GitRepository myInitialRepository;
/**
* Show the dialog and get user's answer, whether he wants to force delete the branch.
*
- * @param commits the list of commits, which are not merged from the branch being deleted to the current branch,
- * grouped by repository.
- * @param branchToDelete the name of the branch which user chose to delete.
- * @param mergedToBranches the list of branches which the branch is merged to (returned by {@code git branch --merged <branchToDelete>} command.
- * @param baseBranch branch which branchToDelete is not merged to. It is either current branch, or the upstream branch.
- * @return true if user decided to delete the branch.
+ * @param commits the list of commits, which are not merged from the branch being deleted to the current branch,
+ * grouped by repository.
+ * @param baseBranches base branches (which Git reported as not containing commits from the removed branch) per repository.
+ * @return true if user decided to restore the branch.
*/
public static boolean showAndGetAnswer(@NotNull Project project,
@NotNull Map<GitRepository, List<GitCommit>> commits,
- @NotNull String branchToDelete,
- @NotNull List<String> mergedToBranches,
- @Nullable String baseBranch) {
- GitBranchIsNotFullyMergedDialog dialog = new GitBranchIsNotFullyMergedDialog(project, commits, branchToDelete, baseBranch, mergedToBranches);
+ @NotNull Map<GitRepository, String> baseBranches,
+ @NotNull String removedBranch) {
+ GitBranchIsNotFullyMergedDialog dialog = new GitBranchIsNotFullyMergedDialog(project, commits, baseBranches, removedBranch);
DialogManager.show(dialog);
return dialog.isOK();
}
private GitBranchIsNotFullyMergedDialog(@NotNull Project project,
@NotNull Map<GitRepository, List<GitCommit>> commits,
- @NotNull String branchToDelete,
- @Nullable String baseBranch,
- @NotNull List<String> mergedToBranches) {
+ @NotNull Map<GitRepository, String> baseBranches,
+ @NotNull String removedBranch) {
super(project, false);
myProject = project;
myCommits = commits;
- myBranchToDelete = branchToDelete;
- myBaseBranch = baseBranch;
- myMergedToBranches = mergedToBranches;
myRepositories = commits.keySet();
+ myBaseBranches = baseBranches;
+ myRemovedBranch = removedBranch;
myInitialRepository = calcInitiallySelectedRepository();
myCommitListWithDiffPanel = new GitCommitListWithDiffPanel(myProject, new ArrayList<GitCommit>(myCommits.get(myInitialRepository)));
init();
- setTitle("Branch Is Not Fully Merged");
- setOKButtonText("Delete");
- setOKButtonMnemonic('D');
- setCancelButtonText("Cancel");
+ setTitle("Branch Was Not Fully Merged");
+ setOKButtonText("Restore");
+ setOKButtonMnemonic('R');
+ getCancelAction().putValue(DEFAULT_ACTION, Boolean.TRUE);
}
@NotNull
throw new AssertionError("The dialog shouldn't be shown. Unmerged commits: " + myCommits);
}
- private String makeDescription() {
- String currentBranchOrRev;
- boolean onBranch;
- if (myRepositories.size() > 1) {
- LOG.assertTrue(myBaseBranch != null, "Branches have unexpectedly diverged");
- currentBranchOrRev = myBaseBranch;
- onBranch = true;
+ @NotNull
+ private String makeDescription(@NotNull GitRepository repository) {
+ String baseBranch = myBaseBranches.get(repository);
+ String description;
+ if (baseBranch == null) {
+ description = String.format("All commits from branch %s were merged", myRemovedBranch);
}
else {
- GitRepository repository = myInitialRepository;
- if (repository.isOnBranch()) {
- GitBranch currentBranch = repository.getCurrentBranch();
- assert currentBranch != null;
- currentBranchOrRev = currentBranch.getName();
- onBranch = true;
- }
- else {
- currentBranchOrRev = repository.getCurrentRevision();
- onBranch = false;
- }
- }
-
- StringBuilder description = new StringBuilder();
- if (onBranch) {
- description.append(GitBundle.message("branch.delete.not_fully_merged.description", myBranchToDelete, myBaseBranch));
- } else {
- description.append(GitBundle.message("branch.delete.not_fully_merged.description.not_on_branch", myBranchToDelete, currentBranchOrRev,
- myBaseBranch));
- }
- if (!myMergedToBranches.isEmpty()) {
- String listOfMergedBranches = StringUtil.join(StringUtil.surround(ArrayUtil.toStringArray(myMergedToBranches), "<b>", "</b>"), ", ");
- description.append("<br>");
- if (myMergedToBranches.size() == 1) {
- description.append(GitBundle.message("branch.delete.merged_to.one", myBranchToDelete, listOfMergedBranches));
- }
- else {
- description.append(GitBundle.message("branch.delete.merged_to.many", myBranchToDelete, listOfMergedBranches));
- }
+ description = String.format("The branch %s was not fully merged to %s.<br/>Below is the list of unmerged commits.",
+ myRemovedBranch, baseBranch);
}
- description.append("<br>").append(GitBundle.message("branch.delete.warning", myBranchToDelete));
- return description.toString();
+ return XmlStringUtil.wrapInHtml(description);
}
@Override
protected JComponent createNorthPanel() {
- JBLabel descriptionLabel = new JBLabel(XmlStringUtil.wrapInHtml(makeDescription()));
+ JBLabel descriptionLabel = new JBLabel(makeDescription(myInitialRepository));
- final JComboBox repositorySelector = new JComboBox(ArrayUtil.toObjectArray(myRepositories, GitRepository.class));
+ JComboBox repositorySelector = new JComboBox(ArrayUtil.toObjectArray(myRepositories, GitRepository.class));
repositorySelector.setRenderer(new GitRepositoryComboboxListCellRenderer(repositorySelector));
repositorySelector.setSelectedItem(myInitialRepository);
repositorySelector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
- List<GitCommit> commits = myCommits.get((GitRepository)repositorySelector.getSelectedItem());
- myCommitListWithDiffPanel.setCommits(new ArrayList<GitCommit>(commits));
+ GitRepository selectedRepo = (GitRepository)repositorySelector.getSelectedItem();
+ descriptionLabel.setText(makeDescription(selectedRepo));
+ myCommitListWithDiffPanel.setCommits(myCommits.get(selectedRepo));
}
});
*/
package git4idea.branch;
+import com.google.common.collect.Maps;
import com.intellij.dvcs.DvcsUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Function;
-import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
-import git4idea.GitLocalBranch;
import git4idea.GitUtil;
import git4idea.commands.Git;
import git4idea.commands.GitMessageWithFilesDetector;
import static com.intellij.openapi.application.ModalityState.defaultModalityState;
import static com.intellij.openapi.util.text.StringUtil.pluralize;
+import static com.intellij.util.ObjectUtils.chooseNotNull;
/**
* Common class for Git operations with branches aware of multi-root configuration,
@NotNull protected final GitBranchUiHandler myUiHandler;
@NotNull private final Collection<GitRepository> myRepositories;
@NotNull protected final Map<GitRepository, String> myCurrentHeads;
+ @NotNull protected final Map<GitRepository, String> myInitialRevisions;
@NotNull private final GitVcsSettings mySettings;
@NotNull private final Collection<GitRepository> mySuccessfulRepositories;
myGit = git;
myUiHandler = uiHandler;
myRepositories = repositories;
- myCurrentHeads = ContainerUtil.map2Map(repositories, new Function<GitRepository, Pair<GitRepository, String>>() {
- @Override
- public Pair<GitRepository, String> fun(GitRepository repository) {
- GitLocalBranch currentBranch = repository.getCurrentBranch();
- return Pair.create(repository, currentBranch == null ? repository.getCurrentRevision() : currentBranch.getName());
- }
- });
+ myCurrentHeads = Maps.toMap(repositories, repo -> chooseNotNull(repo.getCurrentBranchName(), repo.getCurrentRevision()));
+ myInitialRevisions = Maps.toMap(repositories, GitRepository::getCurrentRevision);
mySuccessfulRepositories = new ArrayList<GitRepository>();
mySkippedRepositories = new ArrayList<GitRepository>();
myRemainingRepositories = new ArrayList<GitRepository>(myRepositories);
VcsNotifier.getInstance(myProject).notifySuccess(message);
}
- protected final void notifySuccess() {
+ protected void notifySuccess() {
notifySuccess(getSuccessMessage());
}
}
}
+ /**
+ * Returns the hash of the revision which was current before the start of this GitBranchOperation.
+ */
+ @NotNull
+ protected String getInitialRevision(@NotNull GitRepository repository) {
+ return myInitialRevisions.get(repository);
+ }
+
@Nullable
private String getRecentCommonBranch() {
String recentCommonBranch = null;
int showSmartOperationDialog(@NotNull Project project, @NotNull List<Change> changes, @NotNull Collection<String> paths,
@NotNull String operation, @Nullable String forceButtonTitle);
- boolean showBranchIsNotFullyMergedDialog(@NotNull Project project, @NotNull Map<GitRepository, List<GitCommit>> history,
- @NotNull String unmergedBranch, @NotNull List<String> mergedToBranches,
- @NotNull String baseBranch);
+ /**
+ * @return true if user decided to restore the branch.
+ */
+ boolean showBranchIsNotFullyMergedDialog(@NotNull Project project,
+ @NotNull Map<GitRepository, List<GitCommit>> history,
+ @NotNull Map<GitRepository, String> baseBranches,
+ @NotNull String removedBranch);
}
}
@Override
- public boolean showBranchIsNotFullyMergedDialog(@NotNull Project project, @NotNull final Map<GitRepository, List<GitCommit>> history,
- @NotNull final String unmergedBranch, @NotNull final List<String> mergedToBranches,
- @NotNull final String baseBranch) {
- final AtomicBoolean forceDelete = new AtomicBoolean();
- ApplicationManager.getApplication().invokeAndWait(() -> forceDelete.set(
- GitBranchIsNotFullyMergedDialog.showAndGetAnswer(myProject, history, unmergedBranch, mergedToBranches, baseBranch)),
+ public boolean showBranchIsNotFullyMergedDialog(@NotNull Project project,
+ @NotNull Map<GitRepository, List<GitCommit>> history,
+ @NotNull Map<GitRepository, String> baseBranches,
+ @NotNull String removedBranch) {
+ AtomicBoolean restore = new AtomicBoolean();
+ ApplicationManager.getApplication().invokeAndWait(() -> restore.set(
+ GitBranchIsNotFullyMergedDialog.showAndGetAnswer(myProject, history, baseBranches, removedBranch)),
ModalityState.defaultModalityState());
- return forceDelete.get();
+ return restore.get();
}
@NotNull
return null;
}
+ @Nullable
+ public static GitBranchTrackInfo getTrackInfo(@NotNull GitRepository repository, @NotNull String localBranchName) {
+ return ContainerUtil.find(repository.getBranchTrackInfos(), it -> it.getLocalBranch().getName().equals(localBranchName));
+ }
+
@NotNull
static String