use of com.jetbrains.python.inspections.PyInspectionExtension in project intellij-community by JetBrains.
the class AddFunctionQuickFix method applyFix.
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
try {
final PsiElement problemElement = descriptor.getPsiElement();
if (!(problemElement instanceof PyQualifiedExpression))
return;
final PyExpression qualifier = ((PyQualifiedExpression) problemElement).getQualifier();
if (qualifier == null)
return;
final PyType type = TypeEvalContext.userInitiated(problemElement.getProject(), problemElement.getContainingFile()).getType(qualifier);
if (!(type instanceof PyModuleType))
return;
final PyFile file = ((PyModuleType) type).getModule();
sure(file);
sure(FileModificationService.getInstance().preparePsiElementForWrite(file));
// try to at least match parameter count
// TODO: get parameter style from code style
PyFunctionBuilder builder = new PyFunctionBuilder(myIdentifier, problemElement);
PsiElement problemParent = problemElement.getParent();
if (problemParent instanceof PyCallExpression) {
PyArgumentList arglist = ((PyCallExpression) problemParent).getArgumentList();
if (arglist == null)
return;
final PyExpression[] args = arglist.getArguments();
for (PyExpression arg : args) {
if (arg instanceof PyKeywordArgument) {
// foo(bar) -> def foo(bar_1)
builder.parameter(((PyKeywordArgument) arg).getKeyword());
} else if (arg instanceof PyReferenceExpression) {
PyReferenceExpression refex = (PyReferenceExpression) arg;
builder.parameter(refex.getReferencedName());
} else {
// use a boring name
builder.parameter("param");
}
}
} else if (problemParent != null) {
for (PyInspectionExtension extension : Extensions.getExtensions(PyInspectionExtension.EP_NAME)) {
List<String> params = extension.getFunctionParametersFromUsage(problemElement);
if (params != null) {
for (String param : params) {
builder.parameter(param);
}
break;
}
}
}
// else: no arglist, use empty args
PyFunction function = builder.buildFunction(project, LanguageLevel.forElement(file));
// add to the bottom
function = (PyFunction) file.add(function);
showTemplateBuilder(function, file);
} catch (IncorrectOperationException ignored) {
// we failed. tell about this
PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.function"), MessageType.ERROR);
}
}
Aggregations