@NotNull
  private static PyExpression invertExpression(@NotNull final PsiElement expression) {
    final PyElementGenerator elementGenerator =
        PyElementGenerator.getInstance(expression.getProject());
    if (expression instanceof PyBoolLiteralExpression) {
      final String value =
          ((PyBoolLiteralExpression) expression).getValue() ? PyNames.FALSE : PyNames.TRUE;
      return elementGenerator.createExpressionFromText(LanguageLevel.forElement(expression), value);
    }
    if (expression instanceof PyReferenceExpression
        && (PyNames.FALSE.equals(expression.getText())
            || PyNames.TRUE.equals(expression.getText()))) {

      final String value = PyNames.TRUE.equals(expression.getText()) ? PyNames.FALSE : PyNames.TRUE;
      return elementGenerator.createExpressionFromText(LanguageLevel.forElement(expression), value);
    } else if (expression instanceof PyPrefixExpression) {
      if (((PyPrefixExpression) expression).getOperator() == PyTokenTypes.NOT_KEYWORD) {
        final PyExpression operand = ((PyPrefixExpression) expression).getOperand();
        if (operand != null)
          return elementGenerator.createExpressionFromText(
              LanguageLevel.forElement(expression), operand.getText());
      }
    }
    return elementGenerator.createExpressionFromText(
        LanguageLevel.forElement(expression), "not " + expression.getText());
  }
 @Override
 protected void moveOffsetAfter(boolean success) {
   if (success && (myPanel != null && myPanel.getInitPlace() != InitPlace.SAME_METHOD)
       || myOperation.getInplaceInitPlace() != InitPlace.SAME_METHOD) {
     final AccessToken accessToken =
         ApplicationManager.getApplication().acquireWriteActionLock(getClass());
     try {
       final PyAssignmentStatement initializer =
           PsiTreeUtil.getParentOfType(myTarget, PyAssignmentStatement.class);
       assert initializer != null;
       final Function<String, PyStatement> callback =
           FunctionUtil.<String, PyStatement>constant(initializer);
       final PyClass pyClass = PyUtil.getContainingClassOrSelf(initializer);
       InitPlace initPlace =
           myPanel != null ? myPanel.getInitPlace() : myOperation.getInplaceInitPlace();
       if (initPlace == InitPlace.CONSTRUCTOR) {
         AddFieldQuickFix.addFieldToInit(myProject, pyClass, "", callback);
       } else if (initPlace == InitPlace.SET_UP) {
         addFieldToSetUp(pyClass, callback);
       }
       if (myOperation.getOccurrences().size() > 0) {
         initializer.delete();
       } else {
         final PyExpression copy =
             PyElementGenerator.getInstance(myProject)
                 .createExpressionFromText(
                     LanguageLevel.forElement(myTarget), myTarget.getText());
         initializer.replace(copy);
       }
       initializer.delete();
     } finally {
       accessToken.finish();
     }
   }
 }
  @Override
  @Nullable
  protected TextRange surroundStatement(
      @NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements)
      throws IncorrectOperationException {
    PyTryExceptStatement tryStatement =
        PyElementGenerator.getInstance(project)
            .createFromText(LanguageLevel.getDefault(), PyTryExceptStatement.class, getTemplate());
    final PsiElement parent = elements[0].getParent();
    final PyStatementList statementList = tryStatement.getTryPart().getStatementList();
    statementList.addRange(elements[0], elements[elements.length - 1]);
    statementList.getFirstChild().delete();
    tryStatement = (PyTryExceptStatement) parent.addBefore(tryStatement, elements[0]);
    parent.deleteChildRange(elements[0], elements[elements.length - 1]);

    final PsiFile psiFile = parent.getContainingFile();
    final Document document = psiFile.getViewProvider().getDocument();
    final TextRange range = tryStatement.getTextRange();
    assert document != null;
    final RangeMarker rangeMarker = document.createRangeMarker(range);

    final PsiElement element = psiFile.findElementAt(rangeMarker.getStartOffset());
    tryStatement = PsiTreeUtil.getParentOfType(element, PyTryExceptStatement.class);
    if (tryStatement != null) {
      return getResultRange(tryStatement);
    }
    return null;
  }
 @Override
 protected PyAssignmentStatement createDeclaration(
     Project project, String assignmentText, PsiElement anchor) {
   final PyFunction container = PsiTreeUtil.getParentOfType(anchor, PyFunction.class);
   String selfName = PyUtil.getFirstParameterName(container);
   final LanguageLevel langLevel = LanguageLevel.forElement(anchor);
   return PyElementGenerator.getInstance(project)
       .createFromText(langLevel, PyAssignmentStatement.class, selfName + "." + assignmentText);
 }
 public PyStatement fun(String self_name) {
   if (PyNames.CANONICAL_SELF.equals(self_name)) {
     return (PyStatement) myDeclaration;
   }
   final String text = myDeclaration.getText();
   final Project project = myDeclaration.getProject();
   return PyElementGenerator.getInstance(project)
       .createFromText(
           LanguageLevel.getDefault(),
           PyStatement.class,
           text.replaceFirst(PyNames.CANONICAL_SELF + "\\.", self_name + "."));
 }
 @Override
 public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
   PsiElement expression = descriptor.getPsiElement();
   if (expression instanceof PyTupleExpression) {
     PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);
     PyExpressionStatement statement =
         elementGenerator.createFromText(
             LanguageLevel.forElement(expression),
             PyExpressionStatement.class,
             "(" + expression.getText() + ")");
     expression.replace(statement.getExpression());
   }
 }
 private void addToExistingImport(PyImportElement src) {
   final PyElementGenerator gen = PyElementGenerator.getInstance(myTarget.getProject());
   // did user choose 'import' or 'from import'?
   PsiElement parent = src.getParent();
   if (parent instanceof PyFromImportStatement) {
     // add another import element right after the one we got
     PsiElement newImportElement = gen.createImportElement(LanguageLevel.getDefault(), myName);
     parent.add(newImportElement);
   } else { // just 'import'
     // all we need is to qualify our target
     myTarget.replace(
         gen.createExpressionFromText(
             LanguageLevel.forElement(myTarget), src.getVisibleName() + "." + myName));
   }
 }
 private void addImportStatement(ImportCandidateHolder item) {
   final Project project = myTarget.getProject();
   final PyElementGenerator gen = PyElementGenerator.getInstance(project);
   AddImportHelper.ImportPriority priority =
       AddImportHelper.getImportPriority(myTarget, item.getFile());
   PsiFile file = myTarget.getContainingFile();
   InjectedLanguageManager manager = InjectedLanguageManager.getInstance(project);
   if (manager.isInjectedFragment(file)) {
     file = manager.getTopLevelFile(myTarget);
   }
   // We are trying to import top-level module or package which thus cannot be qualified
   if (isRoot(item.getFile())) {
     if (myImportLocally) {
       AddImportHelper.addLocalImportStatement(myTarget, myName);
     } else {
       AddImportHelper.addImportStatement(file, myName, item.getAsName(), priority, null);
     }
   } else {
     final QualifiedName path = item.getPath();
     final String qualifiedName = path != null ? path.toString() : "";
     if (myUseQualifiedImport) {
       String nameToImport = qualifiedName;
       if (item.getImportable() instanceof PsiFileSystemItem) {
         nameToImport += "." + myName;
       }
       if (myImportLocally) {
         AddImportHelper.addLocalImportStatement(myTarget, nameToImport);
       } else {
         AddImportHelper.addImportStatement(file, nameToImport, item.getAsName(), priority, null);
       }
       myTarget.replace(
           gen.createExpressionFromText(
               LanguageLevel.forElement(myTarget), qualifiedName + "." + myName));
     } else {
       if (myImportLocally) {
         AddImportHelper.addLocalFromImportStatement(myTarget, qualifiedName, myName);
       } else {
         AddImportHelper.addFromImportStatement(
             file, qualifiedName, myName, item.getAsName(), priority, null);
       }
     }
   }
 }
  @Override
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement();
    final PyFunction function = PsiTreeUtil.getParentOfType(element, PyFunction.class, false);
    assert function != null;
    final PyParameterList parameterList = function.getParameterList();
    final PyParameter[] parameters = parameterList.getParameters();
    final PyElementGenerator generator = PyElementGenerator.getInstance(project);
    String selfText = parameters.length != 0 ? parameters[0].getText() : PyNames.CANONICAL_SELF;
    final StringBuilder functionText = new StringBuilder("def foo(" + selfText);
    if (myHasValue) {
      String valueText = parameters.length > 1 ? parameters[1].getText() : "value";
      functionText.append(", ").append(valueText);
    }
    functionText.append("): pass");

    final PyParameterList list =
        generator
            .createFromText(
                LanguageLevel.forElement(element), PyFunction.class, functionText.toString())
            .getParameterList();
    parameterList.replace(list);
  }
 @Override
 protected PyExpression createExpression(Project project, String name, PsiElement declaration) {
   final String text = declaration.getText();
   final String self_name = text.substring(0, text.indexOf('.'));
   return PyElementGenerator.getInstance(project).createExpressionFromText(self_name + "." + name);
 }
 protected PyExpression createExpression(Project project, String name, PsiElement declaration) {
   return PyElementGenerator.getInstance(project)
       .createExpressionFromText(LanguageLevel.forElement(declaration), name);
 }
 protected PyAssignmentStatement createDeclaration(
     Project project, String assignmentText, PsiElement anchor) {
   LanguageLevel langLevel = ((PyFile) anchor.getContainingFile()).getLanguageLevel();
   return PyElementGenerator.getInstance(project)
       .createFromText(langLevel, PyAssignmentStatement.class, assignmentText);
 }
  public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);

    PyExpression expression = elementGenerator.createExpressionFromText(newName);
    myElement.replace(expression);
  }