code cleanup: 'idea' module

This commit is contained in:
Dmitry Jemerov
2015-07-20 20:11:27 +02:00
parent c718b6f9a3
commit a75daf85e2
53 changed files with 130 additions and 150 deletions
@@ -42,7 +42,7 @@ public class ShowKotlinBytecodeAction(): AnAction() {
val contentFactory = ContentFactory.SERVICE.getInstance() val contentFactory = ContentFactory.SERVICE.getInstance()
contentManager.addContent(contentFactory.createContent(KotlinBytecodeToolWindow(project, toolWindow), "", false)) contentManager.addContent(contentFactory.createContent(KotlinBytecodeToolWindow(project, toolWindow), "", false))
} }
toolWindow?.activate(null) toolWindow.activate(null)
} }
override fun update(e: AnActionEvent) { override fun update(e: AnActionEvent) {
@@ -22,7 +22,6 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import java.awt.datatransfer.DataFlavor import java.awt.datatransfer.DataFlavor
import java.io.Serializable import java.io.Serializable
import kotlin.properties.Delegates
public class KotlinReferenceTransferableData( public class KotlinReferenceTransferableData(
val data: Array<KotlinReferenceData> val data: Array<KotlinReferenceData>
@@ -99,7 +98,7 @@ public class KotlinReferenceData(
} }
companion object { companion object {
public val dataFlavor: DataFlavor? by Delegates.lazy { public val dataFlavor: DataFlavor? by lazy {
try { try {
val dataClass = javaClass<KotlinReferenceData>() val dataClass = javaClass<KotlinReferenceData>()
DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + dataClass.getName(), DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=" + dataClass.getName(),
@@ -34,11 +34,13 @@ public class KotlinStatementSurroundDescriptor implements SurroundDescriptor {
new KotlinTryCatchSurrounder() new KotlinTryCatchSurrounder()
}; };
@Override
@NotNull @NotNull
public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) { public PsiElement[] getElementsToSurround(PsiFile file, int startOffset, int endOffset) {
return CodeInsightUtils.findStatements(file, startOffset, endOffset); return CodeInsightUtils.findStatements(file, startOffset, endOffset);
} }
@Override
@NotNull public Surrounder[] getSurrounders() { @NotNull public Surrounder[] getSurrounders() {
return SURROUNDERS; return SURROUNDERS;
} }
@@ -35,16 +35,13 @@ object AbsentSdkAnnotationsNotificationManager: KotlinSingleNotificationManager<
} }
} }
trait KotlinSingleNotificationManager<T: Notification> { interface KotlinSingleNotificationManager<T: Notification> {
fun notify(project: Project, notification: T) { fun notify(project: Project, notification: T) {
val notificationsManager = NotificationsManager.getNotificationsManager() val notificationsManager = NotificationsManager.getNotificationsManager() ?: return
if (notificationsManager == null) {
return
}
var isNotificationExists = false var isNotificationExists = false
val notifications = notificationsManager.getNotificationsOfType(notification.javaClass, project) as Array<Notification> val notifications = notificationsManager.getNotificationsOfType(notification.javaClass, project)
for (oldNotification in notifications) { for (oldNotification in notifications) {
if (oldNotification == notification) { if (oldNotification == notification) {
isNotificationExists = true isNotificationExists = true
@@ -263,7 +263,7 @@ public class JetPositionManager(private val myDebugProcess: DebugProcess) : Mult
myTypeMappers.put(key, value) myTypeMappers.put(key, value)
} }
return value!!.getValue() return value.getValue()
} }
override fun locationsOfLine(type: ReferenceType, position: SourcePosition): List<Location> { override fun locationsOfLine(type: ReferenceType, position: SourcePosition): List<Location> {
@@ -52,14 +52,17 @@ public abstract class AddFieldBreakpointDialog extends DialogWrapper {
init(); init();
} }
@Override
protected JComponent createCenterPanel() { protected JComponent createCenterPanel() {
myClassChooser.getTextField().getDocument().addDocumentListener(new DocumentAdapter() { myClassChooser.getTextField().getDocument().addDocumentListener(new DocumentAdapter() {
@Override
public void textChanged(DocumentEvent event) { public void textChanged(DocumentEvent event) {
updateUI(); updateUI();
} }
}); });
myClassChooser.addActionListener(new ActionListener() { myClassChooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) { public void actionPerformed(ActionEvent e) {
PsiClass currentClass = getSelectedClass(); PsiClass currentClass = getSelectedClass();
TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject).createAllProjectScopeChooser( TreeClassChooser chooser = TreeClassChooserFactory.getInstance(myProject).createAllProjectScopeChooser(
@@ -81,7 +81,7 @@ class KotlinEvaluateExpressionCache(val project: Project) {
val thisDescriptor = value.asmType.getClassDescriptor(project) val thisDescriptor = value.asmType.getClassDescriptor(project)
val superClassDescriptor = jetType.getConstructor().getDeclarationDescriptor() as? ClassDescriptor val superClassDescriptor = jetType.getConstructor().getDeclarationDescriptor() as? ClassDescriptor
return@all thisDescriptor != null && superClassDescriptor != null && runReadAction { DescriptorUtils.isSubclass(thisDescriptor, superClassDescriptor) }!! return@all thisDescriptor != null && superClassDescriptor != null && runReadAction { DescriptorUtils.isSubclass(thisDescriptor, superClassDescriptor) }
} }
} }
@@ -84,7 +84,7 @@ public abstract class KotlinRuntimeTypeEvaluator(
val myValue = value.asValue() val myValue = value.asValue()
var psiClass = myValue.asmType.getClassDescriptor(project) var psiClass = myValue.asmType.getClassDescriptor(project)
if (psiClass != null) { if (psiClass != null) {
return psiClass!!.getDefaultType() return psiClass.getDefaultType()
} }
val type = value.type() val type = value.type()
@@ -93,14 +93,14 @@ public abstract class KotlinRuntimeTypeEvaluator(
if (superclass != null && CommonClassNames.JAVA_LANG_OBJECT != superclass.name()) { if (superclass != null && CommonClassNames.JAVA_LANG_OBJECT != superclass.name()) {
psiClass = AsmType.getType(superclass.signature()).getClassDescriptor(project) psiClass = AsmType.getType(superclass.signature()).getClassDescriptor(project)
if (psiClass != null) { if (psiClass != null) {
return psiClass!!.getDefaultType() return psiClass.getDefaultType()
} }
} }
for (interfaceType in type.interfaces()) { for (interfaceType in type.interfaces()) {
psiClass = AsmType.getType(interfaceType.signature()).getClassDescriptor(project) psiClass = AsmType.getType(interfaceType.signature()).getClassDescriptor(project)
if (psiClass != null) { if (psiClass != null) {
return psiClass!!.getDefaultType() return psiClass.getDefaultType()
} }
} }
} }
@@ -24,7 +24,6 @@ import com.intellij.openapi.projectRoots.JdkVersionUtil
import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfo
import com.sun.jdi.ClassLoaderReference import com.sun.jdi.ClassLoaderReference
import org.jetbrains.kotlin.idea.debugger.evaluate.CompilingEvaluatorUtils import org.jetbrains.kotlin.idea.debugger.evaluate.CompilingEvaluatorUtils
import kotlin.properties.Delegates
public fun loadClasses(evaluationContext: EvaluationContextImpl, classes: Collection<Pair<String, ByteArray>>) { public fun loadClasses(evaluationContext: EvaluationContextImpl, classes: Collection<Pair<String, ByteArray>>) {
val process = evaluationContext.getDebugProcess() val process = evaluationContext.getDebugProcess()
@@ -75,7 +74,7 @@ private val LAMBDA_SUPERCLASSES = listOf(
) )
private class ClassBytes(val name: String) { private class ClassBytes(val name: String) {
val bytes: ByteArray by Delegates.lazy { val bytes: ByteArray by lazy {
val inputStream = this.javaClass.getClassLoader().getResourceAsStream(name.replace('.', '/') + ".class") val inputStream = this.javaClass.getClassLoader().getResourceAsStream(name.replace('.', '/') + ".class")
?: throw EvaluateException("Couldn't find $name class in current class loader") ?: throw EvaluateException("Couldn't find $name class in current class loader")
@@ -131,7 +131,7 @@ private fun JetFile.getElementInCopy(e: PsiElement): PsiElement? {
return null return null
} }
var elementAt = this.findElementAt(offset) var elementAt = this.findElementAt(offset)
while (elementAt == null || elementAt!!.getTextRange()?.getEndOffset() != e.getTextRange()?.getEndOffset()) { while (elementAt == null || elementAt.getTextRange()?.getEndOffset() != e.getTextRange()?.getEndOffset()) {
elementAt = elementAt?.getParent() elementAt = elementAt?.getParent()
} }
return elementAt return elementAt
@@ -169,7 +169,7 @@ private fun getExpressionToAddDebugExpressionBefore(tmpFile: JetFile, contextEle
break break
} }
parent = parent?.getParent() parent = parent.getParent()
parentOfParent = parent?.getParent() parentOfParent = parent?.getParent()
} }
@@ -67,10 +67,10 @@ public class KotlinSmartEnterHandler: SmartEnterProcessorWithFixers() {
while (atCaret != null) { while (atCaret != null) {
when { when {
atCaret?.isJetStatement() == true -> return atCaret atCaret.isJetStatement() == true -> return atCaret
atCaret?.getParent() is JetFunctionLiteral -> return atCaret atCaret.getParent() is JetFunctionLiteral -> return atCaret
atCaret is JetDeclaration -> { atCaret is JetDeclaration -> {
val declaration = atCaret!! val declaration = atCaret
when { when {
declaration is JetParameter && !declaration.isInLambdaExpression() -> {/* proceed to function declaration */} declaration is JetParameter && !declaration.isInLambdaExpression() -> {/* proceed to function declaration */}
declaration.getParent() is JetForExpression -> {/* skip variable declaration in 'for' expression */} declaration.getParent() is JetForExpression -> {/* skip variable declaration in 'for' expression */}
@@ -79,7 +79,7 @@ public class KotlinSmartEnterHandler: SmartEnterProcessorWithFixers() {
} }
} }
atCaret = atCaret?.getParent() atCaret = atCaret.getParent()
} }
return null return null
@@ -28,11 +28,10 @@ public class KotlinDoWhileFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmar
if (psiElement !is JetDoWhileExpression) return if (psiElement !is JetDoWhileExpression) return
val doc = editor.getDocument() val doc = editor.getDocument()
val stmt = psiElement as JetDoWhileExpression val start = psiElement.range.start
val start = stmt.range.start val body = psiElement.getBody()
val body = stmt.getBody()
val whileKeyword = stmt.getWhileKeyword() val whileKeyword = psiElement.getWhileKeyword()
if (body == null) { if (body == null) {
if (whileKeyword == null) { if (whileKeyword == null) {
doc.replaceString(start, start + "do".length(), "do {} while()") doc.replaceString(start, start + "do".length(), "do {} while()")
@@ -42,19 +41,19 @@ public class KotlinDoWhileFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmar
} }
return return
} }
else if (whileKeyword != null && body !is JetBlockExpression && body.startLine(doc) > stmt.startLine(doc)) { else if (whileKeyword != null && body !is JetBlockExpression && body.startLine(doc) > psiElement.startLine(doc)) {
doc.insertString(whileKeyword.range.start, "}") doc.insertString(whileKeyword.range.start, "}")
doc.insertString(start + "do".length(), "{") doc.insertString(start + "do".length(), "{")
return return
} }
if (stmt.getCondition() == null) { if (psiElement.getCondition() == null) {
val lParen = stmt.getLeftParenthesis() val lParen = psiElement.getLeftParenthesis()
val rParen = stmt.getRightParenthesis() val rParen = psiElement.getRightParenthesis()
when { when {
whileKeyword == null -> doc.insertString(stmt.range.end, "while()") whileKeyword == null -> doc.insertString(psiElement.range.end, "while()")
lParen == null && rParen == null -> { lParen == null && rParen == null -> {
doc.replaceString(whileKeyword.range.start, whileKeyword.range.end, "while()") doc.replaceString(whileKeyword.range.start, whileKeyword.range.end, "while()")
} }
@@ -26,11 +26,10 @@ import org.jetbrains.kotlin.psi.JetBlockExpression
public class KotlinMissingIfBranchFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { public class KotlinMissingIfBranchFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
if (element !is JetIfExpression) return if (element !is JetIfExpression) return
val ifExpression = element as JetIfExpression
val document = editor.getDocument() val document = editor.getDocument()
val elseBranch = ifExpression.getElse() val elseBranch = element.getElse()
val elseKeyword = ifExpression.getElseKeyword() val elseKeyword = element.getElseKeyword()
if (elseKeyword != null) { if (elseKeyword != null) {
if (elseBranch == null || elseBranch !is JetBlockExpression && elseBranch.startLine(editor.getDocument()) > elseKeyword.startLine(editor.getDocument())) { if (elseBranch == null || elseBranch !is JetBlockExpression && elseBranch.startLine(editor.getDocument()) > elseKeyword.startLine(editor.getDocument())) {
@@ -39,15 +38,15 @@ public class KotlinMissingIfBranchFixer : SmartEnterProcessorWithFixers.Fixer<Ko
} }
} }
val thenBranch = ifExpression.getThen() val thenBranch = element.getThen()
if (thenBranch is JetBlockExpression) return if (thenBranch is JetBlockExpression) return
val rParen = ifExpression.getRightParenthesis() val rParen = element.getRightParenthesis()
if (rParen == null) return if (rParen == null) return
var transformingOneLiner = false var transformingOneLiner = false
if (thenBranch != null && thenBranch.startLine(editor.getDocument()) == ifExpression.startLine(editor.getDocument())) { if (thenBranch != null && thenBranch.startLine(editor.getDocument()) == element.startLine(editor.getDocument())) {
if (ifExpression.getCondition() != null) return if (element.getCondition() != null) return
transformingOneLiner = true transformingOneLiner = true
} }
@@ -25,15 +25,14 @@ import org.jetbrains.kotlin.psi.JetWhenExpression
public class KotlinMissingWhenBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() { public class KotlinMissingWhenBodyFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) { override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
if (element !is JetWhenExpression) return if (element !is JetWhenExpression) return
val whenExpression = element as JetWhenExpression
val doc = editor.getDocument() val doc = editor.getDocument()
val openBrace = whenExpression.getOpenBrace() val openBrace = element.getOpenBrace()
val closeBrace = whenExpression.getCloseBrace() val closeBrace = element.getCloseBrace()
if (openBrace == null && closeBrace == null && whenExpression.getEntries().isEmpty()) { if (openBrace == null && closeBrace == null && element.getEntries().isEmpty()) {
val openBraceAfter = whenExpression.insertOpenBraceAfter() val openBraceAfter = element.insertOpenBraceAfter()
if (openBraceAfter != null) { if (openBraceAfter != null) {
doc.insertString(openBraceAfter.range.end, "{}") doc.insertString(openBraceAfter.range.end, "{}")
} }
@@ -42,7 +42,7 @@ public class KotlinClassFindUsagesOptions(project: Project) : JavaClassFindUsage
} }
} }
public trait KotlinCallableFindUsagesOptions { public interface KotlinCallableFindUsagesOptions {
public var searchOverrides: Boolean public var searchOverrides: Boolean
} }
@@ -112,5 +112,5 @@ fun <T : PsiNamedElement> FindUsagesOptions.toSearchTarget(element: T, restrictB
else else
UsagesSearchLocation.DEFAULT UsagesSearchLocation.DEFAULT
return UsagesSearchTarget(element, searchScope ?: element.getUseScope(), location, restrictByTarget) return UsagesSearchTarget(element, searchScope, location, restrictByTarget)
} }
@@ -38,7 +38,7 @@ class KotlinSpacingBuilder(val codeStyleSettings: CodeStyleSettings) {
private val builders = ArrayList<Builder>() private val builders = ArrayList<Builder>()
private trait Builder { private interface Builder {
fun getSpacing(parent: ASTBlock, left: ASTBlock, right: ASTBlock): Spacing? fun getSpacing(parent: ASTBlock, left: ASTBlock, right: ASTBlock): Spacing?
} }
@@ -60,17 +60,17 @@ public class SyntheticKotlinBlock(
loop@ loop@
while (treeNode == null) when (child) { while (treeNode == null) when (child) {
is AbstractBlock -> { is AbstractBlock -> {
treeNode = (child as AbstractBlock).getNode() treeNode = child.getNode()
} }
is SyntheticKotlinBlock -> { is SyntheticKotlinBlock -> {
child = (child as SyntheticKotlinBlock).getSubBlocks().first() child = child.getSubBlocks().first()
} }
else -> break@loop else -> break@loop
} }
val textRange = getTextRange() val textRange = getTextRange()
if (treeNode != null) { if (treeNode != null) {
val psi = treeNode!!.getPsi() val psi = treeNode.getPsi()
if (psi != null) { if (psi != null) {
val file = psi.getContainingFile() val file = psi.getContainingFile()
if (file != null) { if (file != null) {
@@ -19,7 +19,7 @@ package org.jetbrains.kotlin.idea.formatter
import com.intellij.formatting.Wrap import com.intellij.formatting.Wrap
import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IElementType
public trait WrappingStrategy { public interface WrappingStrategy {
fun getWrap(childElementType: IElementType): Wrap? fun getWrap(childElementType: IElementType): Wrap?
object NoWrapping: WrappingStrategy { object NoWrapping: WrappingStrategy {
@@ -123,6 +123,6 @@ public fun isImplemented(declaration: JetNamedDeclaration): Boolean {
if (parent !is JetClass) return false if (parent !is JetClass) return false
return (parent as JetClass).isInterface() && (declaration !is JetDeclarationWithBody || !declaration.hasBody()) && (declaration !is JetWithExpressionInitializer || !declaration.hasInitializer()) return parent.isInterface() && (declaration !is JetDeclarationWithBody || !declaration.hasBody()) && (declaration !is JetWithExpressionInitializer || !declaration.hasInitializer())
} }
@@ -85,7 +85,7 @@ public class SuperDeclarationMarkerNavigationHandler : GutterIconNavigationHandl
val declarations = DescriptorToSourceUtilsIde.getAllDeclarations(element.getProject(), overriddenMember) val declarations = DescriptorToSourceUtilsIde.getAllDeclarations(element.getProject(), overriddenMember)
for (declaration in declarations) { for (declaration in declarations) {
if (declaration is NavigatablePsiElement) { if (declaration is NavigatablePsiElement) {
superDeclarations.add(declaration as NavigatablePsiElement) superDeclarations.add(declaration)
} }
} }
} }
@@ -42,10 +42,10 @@ import java.util.Map;
class AnonymousTemplateEditingListener extends TemplateEditingAdapter { class AnonymousTemplateEditingListener extends TemplateEditingAdapter {
private JetReferenceExpression classRef; private JetReferenceExpression classRef;
private ClassDescriptor classDescriptor; private ClassDescriptor classDescriptor;
private Editor editor; private final Editor editor;
private final PsiFile psiFile; private final PsiFile psiFile;
private static Map<Editor, AnonymousTemplateEditingListener> ourAddedListeners = private static final Map<Editor, AnonymousTemplateEditingListener> ourAddedListeners =
new HashMap<Editor, AnonymousTemplateEditingListener>(); new HashMap<Editor, AnonymousTemplateEditingListener>();
public AnonymousTemplateEditingListener(PsiFile psiFile, Editor editor) { public AnonymousTemplateEditingListener(PsiFile psiFile, Editor editor) {
@@ -30,14 +30,17 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class JetFunctionParametersMacro extends Macro { public class JetFunctionParametersMacro extends Macro {
@Override
public String getName() { public String getName() {
return "functionParameters"; return "functionParameters";
} }
@Override
public String getPresentableName() { public String getPresentableName() {
return JetBundle.message("macro.fun.parameters"); return JetBundle.message("macro.fun.parameters");
} }
@Override
public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) { public Result calculateResult(@NotNull Expression[] params, ExpressionContext context) {
Project project = context.getProject(); Project project = context.getProject();
int templateStartOffset = context.getTemplateStartOffset(); int templateStartOffset = context.getTemplateStartOffset();
@@ -37,7 +37,7 @@ import java.util.Collection;
import java.util.List; import java.util.List;
public class JetProjectViewProvider implements SelectableTreeStructureProvider, DumbAware { public class JetProjectViewProvider implements SelectableTreeStructureProvider, DumbAware {
private Project myProject; private final Project myProject;
public JetProjectViewProvider(Project project) { public JetProjectViewProvider(Project project) {
myProject = project; myProject = project;
@@ -64,7 +64,7 @@ public class DeprecatedLambdaSyntaxFix(element: JetFunctionLiteralExpression) :
} }
} }
private trait DeprecatedSyntaxFix { private interface DeprecatedSyntaxFix {
// you must run it under write action // you must run it under write action
fun runFix() fun runFix()
@@ -35,6 +35,7 @@ public class RemoveRightPartOfBinaryExpressionFix<T extends JetExpression> exten
this.message = message; this.message = message;
} }
@Override
public String getText() { public String getText() {
return message; return message;
} }
@@ -49,7 +49,9 @@ import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.refactoring.* import org.jetbrains.kotlin.idea.core.refactoring.*
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind
import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.idea.util.DialogWithEditor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.ShortenReferences
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.lexer.JetTokens import org.jetbrains.kotlin.lexer.JetTokens
@@ -136,7 +138,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val currentFileContext: BindingContext val currentFileContext: BindingContext
val currentFileModule: ModuleDescriptor val currentFileModule: ModuleDescriptor
val pseudocode: Pseudocode? by Delegates.lazy { config.originalElement.getContainingPseudocode(currentFileContext) } val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) }
private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>() private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>()
@@ -21,8 +21,6 @@ import com.intellij.util.ArrayUtil
import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassInfo
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.psi.JetElement import org.jetbrains.kotlin.psi.JetElement
import org.jetbrains.kotlin.psi.JetExpression import org.jetbrains.kotlin.psi.JetExpression
import org.jetbrains.kotlin.psi.JetTypeReference import org.jetbrains.kotlin.psi.JetTypeReference
@@ -30,8 +28,9 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.types.ErrorUtils import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.types.JetType import org.jetbrains.kotlin.types.JetType
import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.types.typeUtil.supertypes
import java.util.Collections import java.util.Collections
import kotlin.properties.Delegates
/** /**
* Represents a concrete type or a set of types yet to be inferred from an expression. * Represents a concrete type or a set of types yet to be inferred from an expression.
@@ -42,7 +41,7 @@ abstract class TypeInfo(val variance: Variance) {
} }
class ByExpression(val expression: JetExpression, variance: Variance): TypeInfo(variance) { class ByExpression(val expression: JetExpression, variance: Variance): TypeInfo(variance) {
override val possibleNamesFromExpression: Array<String> by Delegates.lazy { override val possibleNamesFromExpression: Array<String> by lazy {
KotlinNameSuggester.suggestNamesByExpressionOnly(expression, { true }).toTypedArray() KotlinNameSuggester.suggestNamesByExpressionOnly(expression, { true }).toTypedArray()
} }
@@ -84,7 +84,7 @@ public abstract class CallableRefactoring<T: CallableDescriptor>(
callableFromEditor.getContainingDeclaration().getName().asString(), superString, callableFromEditor.getContainingDeclaration().getName().asString(), superString,
"refactor") "refactor")
val title = IdeBundle.message("title.warning")!! val title = IdeBundle.message("title.warning")!!
val icon = Messages.getQuestionIcon()!! val icon = Messages.getQuestionIcon()
return Messages.showDialog(message, title, options.toTypedArray(), 0, icon) return Messages.showDialog(message, title, options.toTypedArray(), 0, icon)
} }
@@ -48,7 +48,6 @@ import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList
import java.util.ArrayList import java.util.ArrayList
import java.util.HashMap import java.util.HashMap
import java.util.LinkedHashSet import java.util.LinkedHashSet
import kotlin.properties.Delegates
public class JetChangeInfo( public class JetChangeInfo(
val methodDescriptor: JetMethodDescriptor, val methodDescriptor: JetMethodDescriptor,
@@ -72,7 +71,7 @@ public class JetChangeInfo(
private val newParameters = parameterInfos.toArrayList() private val newParameters = parameterInfos.toArrayList()
private val originalPsiMethods: List<PsiMethod> = getMethod().toLightMethods() private val originalPsiMethods: List<PsiMethod> = getMethod().toLightMethods()
private val oldNameToParameterIndex: Map<String, Int> by Delegates.lazy { private val oldNameToParameterIndex: Map<String, Int> by lazy {
val map = HashMap<String, Int>() val map = HashMap<String, Int>()
val parameters = methodDescriptor.baseDescriptor.getValueParameters() val parameters = methodDescriptor.baseDescriptor.getValueParameters()
@@ -81,7 +80,7 @@ public class JetChangeInfo(
map map
} }
public val isParameterSetOrOrderChanged: Boolean by Delegates.lazy { public val isParameterSetOrOrderChanged: Boolean by lazy {
val signatureParameters = getNonReceiverParameters() val signatureParameters = getNonReceiverParameters()
methodDescriptor.receiver != receiverParameterInfo || methodDescriptor.receiver != receiverParameterInfo ||
signatureParameters.size() != methodDescriptor.getParametersCount() || signatureParameters.size() != methodDescriptor.getParametersCount() ||
@@ -22,7 +22,6 @@ import com.intellij.refactoring.changeSignature.MethodDescriptor
import com.intellij.refactoring.changeSignature.OverriderUsageInfo import com.intellij.refactoring.changeSignature.OverriderUsageInfo
import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.asJava.KotlinLightMethod import org.jetbrains.kotlin.asJava.KotlinLightMethod
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.*
@@ -33,8 +32,6 @@ import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.JetCallableDefinitionUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.JetCallableDefinitionUsage
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders
import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.JetCallableDeclaration import org.jetbrains.kotlin.psi.JetCallableDeclaration
import org.jetbrains.kotlin.psi.JetClass import org.jetbrains.kotlin.psi.JetClass
@@ -44,7 +41,6 @@ import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.DescriptorUtils
import java.util.Collections import java.util.Collections
import java.util.HashSet import java.util.HashSet
import kotlin.properties.Delegates
public class JetChangeSignatureData( public class JetChangeSignatureData(
override val baseDescriptor: CallableDescriptor, override val baseDescriptor: CallableDescriptor,
@@ -95,7 +91,7 @@ public class JetChangeSignatureData(
override val original: JetMethodDescriptor override val original: JetMethodDescriptor
get() = this get() = this
override val primaryCallables: Collection<JetCallableDefinitionUsage<PsiElement>> by Delegates.lazy { override val primaryCallables: Collection<JetCallableDefinitionUsage<PsiElement>> by lazy {
descriptorsForSignatureChange.map { descriptorsForSignatureChange.map {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(baseDeclaration.getProject(), it) val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(baseDeclaration.getProject(), it)
assert(declaration != null) { "No declaration found for " + baseDescriptor } assert(declaration != null) { "No declaration found for " + baseDescriptor }
@@ -103,11 +99,11 @@ public class JetChangeSignatureData(
} }
} }
override val originalPrimaryCallable: JetCallableDefinitionUsage<PsiElement> by Delegates.lazy { override val originalPrimaryCallable: JetCallableDefinitionUsage<PsiElement> by lazy {
primaryCallables.first { it.getDeclaration() == baseDeclaration } primaryCallables.first { it.getDeclaration() == baseDeclaration }
} }
override val affectedCallables: Collection<UsageInfo> by Delegates.lazy { override val affectedCallables: Collection<UsageInfo> by lazy {
primaryCallables + primaryCallables.flatMapTo(HashSet<UsageInfo>()) { primaryFunction -> primaryCallables + primaryCallables.flatMapTo(HashSet<UsageInfo>()) { primaryFunction ->
val primaryDeclaration = primaryFunction.getDeclaration() as? JetCallableDeclaration val primaryDeclaration = primaryFunction.getDeclaration() as? JetCallableDeclaration
val lightMethods = primaryDeclaration?.toLightMethods() ?: Collections.emptyList() val lightMethods = primaryDeclaration?.toLightMethods() ?: Collections.emptyList()
@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.descriptors.Visibility
import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.JetCallableDefinitionUsage import org.jetbrains.kotlin.idea.refactoring.changeSignature.usages.JetCallableDefinitionUsage
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
public trait JetMethodDescriptor : MethodDescriptor<JetParameterInfo, Visibility> { public interface JetMethodDescriptor : MethodDescriptor<JetParameterInfo, Visibility> {
enum class Kind(val isConstructor: Boolean) { enum class Kind(val isConstructor: Boolean) {
FUNCTION(false), FUNCTION(false),
PRIMARY_CONSTRUCTOR(true), PRIMARY_CONSTRUCTOR(true),
@@ -31,28 +31,25 @@ import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.Analysis
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.ExpressionValue import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.ExpressionValue
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.Initializer import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.Initializer
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.Jump import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.Jump
import org.jetbrains.kotlin.idea.references.JetSimpleNameReference
import org.jetbrains.kotlin.idea.references.JetSimpleNameReference.ShorteningMode import org.jetbrains.kotlin.idea.references.JetSimpleNameReference.ShorteningMode
import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.approximateFlexibleTypes import org.jetbrains.kotlin.idea.util.approximateFlexibleTypes
import org.jetbrains.kotlin.idea.util.isAnnotatedNotNull import org.jetbrains.kotlin.idea.util.isAnnotatedNotNull
import org.jetbrains.kotlin.idea.util.isAnnotatedNullable import org.jetbrains.kotlin.idea.util.isAnnotatedNullable
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.resolveTopLevelClass import org.jetbrains.kotlin.resolve.descriptorUtil.resolveTopLevelClass
import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.isUnit
import java.util.Collections import java.util.Collections
import kotlin.properties.Delegates
trait Parameter { interface Parameter {
val argumentText: String val argumentText: String
val originalDescriptor: DeclarationDescriptor val originalDescriptor: DeclarationDescriptor
val name: String val name: String
@@ -73,9 +70,9 @@ data class TypeParameter(
val originalConstraints: List<JetTypeConstraint> val originalConstraints: List<JetTypeConstraint>
) )
trait Replacement: Function1<JetElement, JetElement> interface Replacement: Function1<JetElement, JetElement>
trait ParameterReplacement : Replacement { interface ParameterReplacement : Replacement {
val parameter: Parameter val parameter: Parameter
fun copy(parameter: Parameter): ParameterReplacement fun copy(parameter: Parameter): ParameterReplacement
} }
@@ -124,7 +121,7 @@ class FqNameReplacement(val fqName: FqName): Replacement {
} }
} }
trait OutputValue { interface OutputValue {
val originalExpressions: List<JetExpression> val originalExpressions: List<JetExpression>
val valueType: JetType val valueType: JetType
@@ -207,7 +204,7 @@ abstract class OutputValueBoxer(val outputValues: List<OutputValue>) {
private val selectors = arrayOf("first", "second", "third") private val selectors = arrayOf("first", "second", "third")
} }
override val returnType: JetType by Delegates.lazy { override val returnType: JetType by lazy {
fun getType(): JetType { fun getType(): JetType {
val boxingClass = when (outputValues.size()) { val boxingClass = when (outputValues.size()) {
1 -> return outputValues.first().valueType 1 -> return outputValues.first().valueType
@@ -252,7 +249,7 @@ abstract class OutputValueBoxer(val outputValues: List<OutputValue>) {
} }
class AsList(outputValues: List<OutputValue>): OutputValueBoxer(outputValues) { class AsList(outputValues: List<OutputValue>): OutputValueBoxer(outputValues) {
override val returnType: JetType by Delegates.lazy { override val returnType: JetType by lazy {
if (outputValues.isEmpty()) DEFAULT_RETURN_TYPE if (outputValues.isEmpty()) DEFAULT_RETURN_TYPE
else TypeUtils.substituteParameters( else TypeUtils.substituteParameters(
KotlinBuiltIns.getInstance().getList(), KotlinBuiltIns.getInstance().getList(),
@@ -331,7 +328,7 @@ data class ExtractableCodeDescriptor(
val returnType: JetType val returnType: JetType
) { ) {
val name: String get() = suggestedNames.firstOrNull() ?: "" val name: String get() = suggestedNames.firstOrNull() ?: ""
val duplicates: List<DuplicateInfo> by Delegates.lazy { findDuplicates() } val duplicates: List<DuplicateInfo> by lazy { findDuplicates() }
} }
enum class ExtractionTarget(val name: String) { enum class ExtractionTarget(val name: String) {
@@ -16,39 +16,35 @@
package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.psi.PsiNameIdentifierOwner
import kotlin.properties.Delegates
import java.util.HashMap
import org.jetbrains.kotlin.idea.codeInsight.JetFileReferencesResolver
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import java.util.Collections
import org.jetbrains.kotlin.psi.psiUtil.isInsideOf
import java.util.ArrayList
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.codeInsight.JetFileReferencesResolver
import org.jetbrains.kotlin.idea.core.compareDescriptors import org.jetbrains.kotlin.idea.core.compareDescriptors
import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.isInsideOf
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.isSynthesizedInvoke import org.jetbrains.kotlin.resolve.calls.tasks.isSynthesizedInvoke
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver
import org.jetbrains.kotlin.types.JetType import org.jetbrains.kotlin.types.JetType
import java.util.ArrayList
import java.util.Collections
import java.util.HashMap
data class ExtractionOptions( data class ExtractionOptions(
val inferUnitTypeForUnusedValues: Boolean = true, val inferUnitTypeForUnusedValues: Boolean = true,
@@ -106,7 +102,7 @@ data class ExtractionData(
} }
} }
val codeFragmentText: String by Delegates.lazy { val codeFragmentText: String by lazy {
getCodeFragmentTextRange()?.let { originalFile.getText()?.substring(it.getStartOffset(), it.getEndOffset()) } ?: "" getCodeFragmentTextRange()?.let { originalFile.getText()?.substring(it.getStartOffset(), it.getEndOffset()) } ?: ""
} }
@@ -115,12 +111,12 @@ data class ExtractionData(
val commonParent = PsiTreeUtil.findCommonParent(originalElements) as JetElement val commonParent = PsiTreeUtil.findCommonParent(originalElements) as JetElement
val bindingContext: BindingContext? by Delegates.lazy { commonParent.getContextForContainingDeclarationBody() } val bindingContext: BindingContext? by lazy { commonParent.getContextForContainingDeclarationBody() }
private val itFakeDeclaration by Delegates.lazy { JetPsiFactory(originalFile).createParameter("it: Any?") } private val itFakeDeclaration by lazy { JetPsiFactory(originalFile).createParameter("it: Any?") }
private val synthesizedInvokeDeclaration by Delegates.lazy { JetPsiFactory(originalFile).createFunction("fun invoke() {}") } private val synthesizedInvokeDeclaration by lazy { JetPsiFactory(originalFile).createFunction("fun invoke() {}") }
val refOffsetToDeclaration by Delegates.lazy { val refOffsetToDeclaration by lazy {
fun isExtractableIt(descriptor: DeclarationDescriptor, context: BindingContext): Boolean { fun isExtractableIt(descriptor: DeclarationDescriptor, context: BindingContext): Boolean {
if (!(descriptor is ValueParameterDescriptor && (context[BindingContext.AUTO_CREATED_IT, descriptor] ?: false))) return false if (!(descriptor is ValueParameterDescriptor && (context[BindingContext.AUTO_CREATED_IT, descriptor] ?: false))) return false
val function = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.getContainingDeclaration()) as? JetFunctionLiteral val function = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.getContainingDeclaration()) as? JetFunctionLiteral
@@ -81,7 +81,7 @@ public fun processDuplicates(
project, project,
JetRefactoringBundle.message( JetRefactoringBundle.message(
"0.has.detected.1.code.fragments.in.this.file.that.can.be.replaced.with.a.call.to.extracted.declaration", "0.has.detected.1.code.fragments.in.this.file.that.can.be.replaced.with.a.call.to.extracted.declaration",
ApplicationNamesInfo.getInstance()!!.getProductName(), ApplicationNamesInfo.getInstance().getProductName(),
duplicateReplacers.size() duplicateReplacers.size()
), ),
"Process Duplicates", "Process Duplicates",
@@ -19,7 +19,6 @@ package org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine
import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.Logger
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement import com.intellij.psi.PsiNamedElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.util.RefactoringUIUtil import com.intellij.refactoring.util.RefactoringUIUtil
import com.intellij.util.containers.MultiMap import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns
@@ -43,14 +42,12 @@ import org.jetbrains.kotlin.idea.caches.resolve.analyzeFully
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.core.comparePossiblyOverridingDescriptors import org.jetbrains.kotlin.idea.core.comparePossiblyOverridingDescriptors
import org.jetbrains.kotlin.idea.core.getResolutionScope import org.jetbrains.kotlin.idea.core.getResolutionScope
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.refactoring.createTempCopy import org.jetbrains.kotlin.idea.core.refactoring.createTempCopy
import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclarationBody
import org.jetbrains.kotlin.idea.imports.importableFqNameSafe import org.jetbrains.kotlin.idea.imports.importableFqNameSafe
import org.jetbrains.kotlin.idea.kdoc.getResolutionScope
import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator
import org.jetbrains.kotlin.idea.refactoring.JetRefactoringBundle import org.jetbrains.kotlin.idea.refactoring.JetRefactoringBundle
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.ErrorMessage import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.ErrorMessage
import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.Status import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.AnalysisResult.Status
@@ -63,30 +60,26 @@ import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.approximateWithResolvableType import org.jetbrains.kotlin.idea.util.approximateWithResolvableType
import org.jetbrains.kotlin.idea.util.isResolvableInScope import org.jetbrains.kotlin.idea.util.isResolvableInScope
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
import org.jetbrains.kotlin.resolve.calls.CallTransformer
import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.tasks.isSynthesizedInvoke import org.jetbrains.kotlin.resolve.calls.tasks.isSynthesizedInvoke
import org.jetbrains.kotlin.resolve.scopes.JetScope import org.jetbrains.kotlin.resolve.scopes.JetScope
import org.jetbrains.kotlin.resolve.scopes.JetScopeUtils
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver import org.jetbrains.kotlin.resolve.scopes.receivers.ThisReceiver
import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.JetTypeChecker import org.jetbrains.kotlin.types.checker.JetTypeChecker
import org.jetbrains.kotlin.types.typeUtil.makeNullable
import org.jetbrains.kotlin.utils.DFS import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.DFS.CollectingNodeHandler import org.jetbrains.kotlin.utils.DFS.CollectingNodeHandler
import org.jetbrains.kotlin.utils.DFS.Neighbors import org.jetbrains.kotlin.utils.DFS.Neighbors
import org.jetbrains.kotlin.utils.DFS.VisitedWithSet import org.jetbrains.kotlin.utils.DFS.VisitedWithSet
import java.util.* import java.util.*
import kotlin.properties.Delegates
private val DEFAULT_RETURN_TYPE = KotlinBuiltIns.getInstance().getUnitType() private val DEFAULT_RETURN_TYPE = KotlinBuiltIns.getInstance().getUnitType()
private val DEFAULT_PARAMETER_TYPE = KotlinBuiltIns.getInstance().getNullableAnyType() private val DEFAULT_PARAMETER_TYPE = KotlinBuiltIns.getInstance().getNullableAnyType()
@@ -519,12 +512,12 @@ private class MutableParameter(
override var mirrorVarName: String? = null override var mirrorVarName: String? = null
private val defaultType: JetType by Delegates.lazy { private val defaultType: JetType by lazy {
writable = false writable = false
TypeUtils.intersect(JetTypeChecker.DEFAULT, defaultTypes)!! TypeUtils.intersect(JetTypeChecker.DEFAULT, defaultTypes)!!
} }
private val parameterTypeCandidates: List<JetType> by Delegates.lazy { private val parameterTypeCandidates: List<JetType> by lazy {
writable = false writable = false
val typePredicate = and(typePredicates) val typePredicate = and(typePredicates)
@@ -166,7 +166,7 @@ public class KotlinIntroduceParameterDialog private constructor(
doCancelAction() doCancelAction()
} }
} }
parameterTablePanel.init(lambdaExtractionDescriptor!!.receiverParameter, lambdaExtractionDescriptor.parameters) parameterTablePanel.init(lambdaExtractionDescriptor.receiverParameter, lambdaExtractionDescriptor.parameters)
gbConstraints.insets = Insets(4, 4, 4, 8) gbConstraints.insets = Insets(4, 4, 4, 8)
gbConstraints.gridwidth = 1 gbConstraints.gridwidth = 1
@@ -202,7 +202,7 @@ fun selectNewParameterContext(
) )
} }
public trait KotlinIntroduceParameterHelper { public interface KotlinIntroduceParameterHelper {
object Default: KotlinIntroduceParameterHelper object Default: KotlinIntroduceParameterHelper
fun configure(descriptor: IntroduceParameterDescriptor): IntroduceParameterDescriptor = descriptor fun configure(descriptor: IntroduceParameterDescriptor): IntroduceParameterDescriptor = descriptor
@@ -390,7 +390,7 @@ private fun findInternalUsagesOfParametersAndReceiver(
return usages return usages
} }
trait KotlinIntroduceLambdaParameterHelper: KotlinIntroduceParameterHelper { interface KotlinIntroduceLambdaParameterHelper: KotlinIntroduceParameterHelper {
object Default: KotlinIntroduceLambdaParameterHelper object Default: KotlinIntroduceLambdaParameterHelper
fun configureExtractLambda(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptor = descriptor fun configureExtractLambda(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptor = descriptor
@@ -137,7 +137,7 @@ public fun PsiElement.getAllExtractionContainers(strict: Boolean = true): List<J
is JetBlockExpression, is JetClassBody, is JetFile -> containers.add(element as JetElement) is JetBlockExpression, is JetClassBody, is JetFile -> containers.add(element as JetElement)
} }
element = element!!.getParent() element = element.getParent()
} }
return containers return containers
@@ -16,17 +16,15 @@
package org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations package org.jetbrains.kotlin.idea.refactoring.move.moveTopLevelDeclarations
import com.intellij.refactoring.PackageWrapper import com.intellij.openapi.project.Project
import com.intellij.refactoring.MoveDestination
import org.jetbrains.kotlin.psi.JetFile
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager import com.intellij.psi.PsiManager
import com.intellij.refactoring.PackageWrapper
import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.FqName
import com.intellij.openapi.project.Project import org.jetbrains.kotlin.psi.JetFile
import kotlin.properties.Delegates
public trait KotlinMoveTarget { public interface KotlinMoveTarget {
val packageWrapper: PackageWrapper? val packageWrapper: PackageWrapper?
fun getOrCreateTargetPsi(originalPsi: PsiElement): PsiFile? fun getOrCreateTargetPsi(originalPsi: PsiElement): PsiFile?
fun getTargetPsiIfExists(originalPsi: PsiElement): PsiFile? fun getTargetPsiIfExists(originalPsi: PsiElement): PsiFile?
@@ -52,7 +50,7 @@ public class DeferredJetFileKotlinMoveTarget(
project: Project, project: Project,
val packageFqName: FqName, val packageFqName: FqName,
createFile: () -> JetFile?): KotlinMoveTarget { createFile: () -> JetFile?): KotlinMoveTarget {
val createdFile: JetFile? by Delegates.lazy(createFile) val createdFile: JetFile? by lazy(createFile)
override val packageWrapper: PackageWrapper = PackageWrapper(PsiManager.getInstance(project), packageFqName.asString()) override val packageWrapper: PackageWrapper = PackageWrapper(PsiManager.getInstance(project), packageFqName.asString())
@@ -65,7 +65,7 @@ import java.util.ArrayList
import java.util.HashMap import java.util.HashMap
import java.util.HashSet import java.util.HashSet
trait Mover: (originalElement: JetNamedDeclaration, targetFile: JetFile) -> JetNamedDeclaration { interface Mover: (originalElement: JetNamedDeclaration, targetFile: JetFile) -> JetNamedDeclaration {
object Default: Mover { object Default: Mover {
override fun invoke(originalElement: JetNamedDeclaration, targetFile: JetFile): JetNamedDeclaration { override fun invoke(originalElement: JetNamedDeclaration, targetFile: JetFile): JetNamedDeclaration {
val newElement = targetFile.add(originalElement) as JetNamedDeclaration val newElement = targetFile.add(originalElement) as JetNamedDeclaration
@@ -120,7 +120,7 @@ public fun JetElement.getInternalReferencesToUpdateOnPackageNameChange(packageNa
packageName == packageNameInfo.oldPackageName, packageName == packageNameInfo.oldPackageName,
packageName == packageNameInfo.newPackageName, packageName == packageNameInfo.newPackageName,
isImported(descriptor) -> { isImported(descriptor) -> {
refExpr.mainReference?.let { createMoveUsageInfoIfPossible(it, declaration, false) } createMoveUsageInfoIfPossible(refExpr.mainReference, declaration, false)
} }
else -> null else -> null
@@ -27,10 +27,9 @@ import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.JetFunction import org.jetbrains.kotlin.psi.JetFunction
import org.jetbrains.kotlin.psi.JetNamedFunction import org.jetbrains.kotlin.psi.JetNamedFunction
import org.jetbrains.kotlin.psi.JetSecondaryConstructor import org.jetbrains.kotlin.psi.JetSecondaryConstructor
import kotlin.properties.Delegates
public class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() { public class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() {
private val javaMethodProcessorInstance by Delegates.lazy { private val javaMethodProcessorInstance by lazy {
// KT-4250 // KT-4250
// RenamePsiElementProcessor.EP_NAME.findExtension(javaClass<RenameJavaMethodProcessor>())!! // RenamePsiElementProcessor.EP_NAME.findExtension(javaClass<RenameJavaMethodProcessor>())!!
@@ -38,7 +38,7 @@ public class KotlinJavaSafeDeleteDelegate : JavaSafeDeleteDelegate {
) { ) {
if (reference !is JetReference) return if (reference !is JetReference) return
val element = reference.getElement() as JetElement val element = reference.getElement()
val callExpression = element.getNonStrictParentOfType<JetCallExpression>() val callExpression = element.getNonStrictParentOfType<JetCallExpression>()
if (callExpression == null) return if (callExpression == null) return
@@ -39,7 +39,7 @@ public class JetRunConfigurationEditor extends SettingsEditor<JetRunConfiguratio
private CommonJavaParametersPanel myCommonProgramParameters; private CommonJavaParametersPanel myCommonProgramParameters;
private AlternativeJREPanel alternativeJREPanel; private AlternativeJREPanel alternativeJREPanel;
private LabeledComponent<JTextField> mainClass; private LabeledComponent<JTextField> mainClass;
private ConfigurationModuleSelector myModuleSelector; private final ConfigurationModuleSelector myModuleSelector;
private JComponent anchor; private JComponent anchor;
private final LabeledComponent<JComboBox> moduleChooser; private final LabeledComponent<JComboBox> moduleChooser;
@@ -175,7 +175,7 @@ public class DebuggerUtils {
toProcess.add(containingFile); toProcess.add(containingFile);
} }
return new kotlin.Pair<BindingContext, List<JetFile>>(context, new ArrayList<JetFile>(toProcess)); return new Pair<BindingContext, List<JetFile>>(context, new ArrayList<JetFile>(toProcess));
} }
@NotNull @NotNull
@@ -29,7 +29,7 @@ import org.jetbrains.kotlin.idea.util.psi.patternMatching.JetPsiRange.Match
private val SIGNIFICANT_FILTER = { e: PsiElement -> e !is PsiWhiteSpace && e !is PsiComment && e.getTextLength() > 0 } private val SIGNIFICANT_FILTER = { e: PsiElement -> e !is PsiWhiteSpace && e !is PsiComment && e.getTextLength() > 0 }
public trait JetPsiRange { public interface JetPsiRange {
public object Empty : JetPsiRange { public object Empty : JetPsiRange {
override val elements: List<PsiElement> get() = Collections.emptyList<PsiElement>() override val elements: List<PsiElement> get() = Collections.emptyList<PsiElement>()
@@ -90,7 +90,7 @@ import org.jetbrains.kotlin.idea.core.refactoring.getContextForContainingDeclara
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.JetOperationReferenceExpression import org.jetbrains.kotlin.psi.JetOperationReferenceExpression
public trait UnificationResult { public interface UnificationResult {
public enum class Status { public enum class Status {
MATCHED { MATCHED {
override fun and(other: Status): Status = other override fun and(other: Status): Status = other
@@ -107,7 +107,7 @@ public trait UnificationResult {
override val status: Status get() = UNMATCHED override val status: Status get() = UNMATCHED
} }
trait Matched: UnificationResult { interface Matched: UnificationResult {
val substitution: Map<UnifierParameter, JetExpression> val substitution: Map<UnifierParameter, JetExpression>
override val status: Status get() = MATCHED override val status: Status get() = MATCHED
} }
@@ -20,7 +20,7 @@ import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.PsiElement import com.intellij.psi.PsiElement
import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.findUsages.FindUsagesHandler
public trait KotlinFindUsagesHandlerDecorator { public interface KotlinFindUsagesHandlerDecorator {
companion object { companion object {
public val EP_NAME: ExtensionPointName<KotlinFindUsagesHandlerDecorator> = ExtensionPointName.create("org.jetbrains.kotlin.findUsagesHandlerDecorator")!! public val EP_NAME: ExtensionPointName<KotlinFindUsagesHandlerDecorator> = ExtensionPointName.create("org.jetbrains.kotlin.findUsagesHandlerDecorator")!!
} }
@@ -112,7 +112,7 @@ public abstract class AbstractKotlinSteppingTest : KotlinDebuggerTestBase() {
stepTargets.filterIsInstance<MethodSmartStepTarget>().map { stepTargets.filterIsInstance<MethodSmartStepTarget>().map {
stepTarget -> stepTarget ->
when (stepTarget) { when (stepTarget) {
is KotlinMethodSmartStepTarget -> KotlinBasicStepMethodFilter(stepTarget as KotlinMethodSmartStepTarget) is KotlinMethodSmartStepTarget -> KotlinBasicStepMethodFilter(stepTarget)
else -> BasicStepMethodFilter(stepTarget.getMethod(), stepTarget.getCallingExpressionLines()) else -> BasicStepMethodFilter(stepTarget.getMethod(), stepTarget.getCallingExpressionLines())
} }
} }
@@ -88,7 +88,7 @@ public class InplaceRenameTest : LightPlatformCodeInsightTestCase() {
assert(range != null) assert(range != null)
object : WriteCommandAction.Simple<Any>(project) { object : WriteCommandAction.Simple<Any>(project) {
override fun run() { override fun run() {
editor.getDocument().replaceString(range!!.getStartOffset(), range!!.getEndOffset(), newName) editor.getDocument().replaceString(range!!.getStartOffset(), range.getEndOffset(), newName)
} }
}.execute().throwException() }.execute().throwException()
@@ -228,7 +228,7 @@ public abstract class AbstractJetExtractionTest() : JetLightCodeInsightFixtureTe
val handler = KotlinIntroducePropertyHandler(helper) val handler = KotlinIntroducePropertyHandler(helper)
val editor = fixture.getEditor() val editor = fixture.getEditor()
handler.selectElements(editor, file) { elements, previousSibling -> handler.selectElements(editor, file) { elements, previousSibling ->
handler.doInvoke(getProject(), editor, file as JetFile, elements, explicitPreviousSibling ?: previousSibling) handler.doInvoke(getProject(), editor, file, elements, explicitPreviousSibling ?: previousSibling)
} }
} }
} }
@@ -64,7 +64,7 @@ private enum class RenameType {
KOTLIN_CLASS, KOTLIN_CLASS,
KOTLIN_FUNCTION, KOTLIN_FUNCTION,
KOTLIN_PROPERTY, KOTLIN_PROPERTY,
KOTLIN_PACKAGE KOTLIN_PACKAGE,
MARKED_ELEMENT MARKED_ELEMENT
} }
@@ -53,7 +53,7 @@ public abstract class AbstractKotlinFileStructureTest : JetLightCodeInsightFixtu
} }
protected fun FileStructurePopup.setup() { protected fun FileStructurePopup.setup() {
val fileText = FileUtil.loadFile(File(getTestDataPath(), fileName()!!), true) val fileText = FileUtil.loadFile(File(getTestDataPath(), fileName()), true)
val withInherited = InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_INHERITED") val withInherited = InTextDirectivesUtils.isDirectiveDefined(fileText, "WITH_INHERITED")
setTreeActionState(javaClass<KotlinInheritedMembersNodeProvider>(), withInherited) setTreeActionState(javaClass<KotlinInheritedMembersNodeProvider>(), withInherited)