summaryrefslogtreecommitdiff
path: root/python/src/com/jetbrains/python/refactoring/changeSignature/PyChangeSignatureHandler.java
blob: 6895249a641f14a7642e47dfbba9e2482fe4a2c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
/*
 * 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.jetbrains.python.refactoring.changeSignature;

import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ex.ApplicationManagerEx;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.changeSignature.ChangeSignatureHandler;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.jetbrains.python.PyBundle;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import com.jetbrains.python.psi.resolve.PyResolveContext;
import com.jetbrains.python.psi.search.PySuperMethodsSearch;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * User : ktisha
 */

public class PyChangeSignatureHandler implements ChangeSignatureHandler {
  @Nullable
  @Override
  public PsiElement findTargetMember(PsiFile file, Editor editor) {
    PsiElement element = PyUtil.findNonWhitespaceAtOffset(file, editor.getCaretModel().getOffset());
    return findTargetMember(element);
  }

  @Nullable
  @Override
  public PsiElement findTargetMember(@Nullable PsiElement element) {
    final PyCallExpression callExpression = PsiTreeUtil.getParentOfType(element, PyCallExpression.class);
    if (callExpression != null) {
      return callExpression.resolveCalleeFunction(PyResolveContext.defaultContext());
    }
    return PsiTreeUtil.getParentOfType(element, PyFunction.class);
  }

  @Override
  public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    PsiElement element = findTargetMember(file, editor);
    if (element == null) {
      element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
    }
    invokeOnElement(project, element, editor);
  }

  @Override
  public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, @Nullable DataContext dataContext) {
    if (elements.length != 1) return;
    Editor editor = dataContext == null ? null : CommonDataKeys.EDITOR.getData(dataContext);
    invokeOnElement(project, elements[0], editor);
  }

  @Nullable
  @Override
  public String getTargetNotFoundMessage() {
    return PyBundle.message("refactoring.change.signature.error.wrong.caret.position.method.name");
  }

  private static void invokeOnElement(Project project, PsiElement element, Editor editor) {
    if (element instanceof PyLambdaExpression) {
      String message =
        RefactoringBundle.getCannotRefactorMessage("Caret is positioned on lambda call.");
      CommonRefactoringUtil.showErrorHint(project, editor, message,
                                          REFACTORING_NAME, REFACTORING_NAME);
      return;
    }
    if (!(element instanceof PyFunction)) {
      String message =
        RefactoringBundle.getCannotRefactorMessage(
          PyBundle.message("refactoring.change.signature.error.wrong.caret.position.method.name"));
      CommonRefactoringUtil.showErrorHint(project, editor, message,
                                          REFACTORING_NAME, REFACTORING_NAME);
      return;
    }

    if (isNotUnderSourceRoot(project, element.getContainingFile(), editor)) return;

    final PyFunction superMethod = getSuperMethod((PyFunction)element);
    if (superMethod == null) return;
    if (!superMethod.equals(element)) {
      element = superMethod;
      if (isNotUnderSourceRoot(project, superMethod.getContainingFile(), editor)) return;
    }

    final PyFunction function = (PyFunction)element;
    final PyParameter[] parameters = function.getParameterList().getParameters();
    for (PyParameter p : parameters) {
      if (p instanceof PyTupleParameter) {
        String message =
          RefactoringBundle.getCannotRefactorMessage("Function contains tuple parameters");
        CommonRefactoringUtil.showErrorHint(project, editor, message,
                                            REFACTORING_NAME, REFACTORING_NAME);
        return;
      }
    }

    final PyMethodDescriptor method = new PyMethodDescriptor((PyFunction)element);
    PyChangeSignatureDialog dialog = new PyChangeSignatureDialog(project, method);
    dialog.show();
  }

  private static boolean isNotUnderSourceRoot(@NotNull final Project project,
                                              @Nullable final PsiFile psiFile,
                                              @NotNull final Editor editor) {
    if (psiFile == null) return true;
    final VirtualFile virtualFile = psiFile.getVirtualFile();
    if (virtualFile != null) {
      if (ProjectRootManager.getInstance(project).getFileIndex().isInLibraryClasses(virtualFile)) {
        String message =
            RefactoringBundle.getCannotRefactorMessage("Function is not under the source root");
          CommonRefactoringUtil.showErrorHint(project, editor, message,
                                              REFACTORING_NAME, REFACTORING_NAME);
        return true;
      }
    }
    return false;
  }

  @Nullable
  protected static PyFunction getSuperMethod(@Nullable PyFunction function) {
    if (function == null) return null;
    final PyClass containingClass = function.getContainingClass();
    if (containingClass == null) {
      return function;
    }
    final PyFunction deepestSuperMethod = PySuperMethodsSearch.findDeepestSuperMethod(function);
    if (!deepestSuperMethod.equals(function)) {
      final PyClass baseClass = deepestSuperMethod.getContainingClass();
      final PyBuiltinCache cache = PyBuiltinCache.getInstance(baseClass);
      String baseClassName = baseClass == null? "" : baseClass.getName();
      if (cache.isBuiltin(baseClass))
        return function;
      final String message = PyBundle.message(
        "refactoring.change.signature.find.usages.of.base.class",
        function.getName(),
        containingClass.getName(),
        baseClassName);
      int choice;
      if (ApplicationManagerEx.getApplicationEx().isUnitTestMode()) {
        choice = 0;
      }
      else {
        choice = Messages.showYesNoCancelDialog(function.getProject(), message,
                                                REFACTORING_NAME, Messages.getQuestionIcon());
      }
      switch (choice) {
        case Messages.YES:
          return deepestSuperMethod;
        case Messages.NO:
          return function;
        default:
          return null;
      }

    }
    return function;
  }
}