Search in sources :

Example 1 with IPyRefactoring

use of org.python.pydev.ast.refactoring.IPyRefactoring in project Pydev by fabioz.

the class TddCodeGenerationQuickFixParticipant method getTddProps.

public List<ICompletionProposalHandle> getTddProps(PySelection ps, IImageCache imageCache, File f, IPythonNature nature, PyEdit edit, int offset, List<ICompletionProposalHandle> ret) {
    if (ret == null) {
        ret = new ArrayList<ICompletionProposalHandle>();
    }
    // Additional option: Generate markers for 'self.' accesses
    int lineOfOffset = ps.getLineOfOffset(offset);
    String lineContents = ps.getLine(lineOfOffset);
    // Additional option: Generate methods for function calls
    List<TddPossibleMatches> callsAtLine = ps.getTddPossibleMatchesAtLine();
    if (callsAtLine.size() > 0) {
        // Make sure we don't check the same thing twice.
        Map<String, TddPossibleMatches> callsToCheck = new HashMap<String, TddPossibleMatches>();
        for (TddPossibleMatches call : callsAtLine) {
            String callString = call.initialPart + call.secondPart;
            callsToCheck.put(callString, call);
        }
        CONTINUE_FOR: for (Map.Entry<String, TddPossibleMatches> entry : callsToCheck.entrySet()) {
            // we have at least something as SomeClass(a=2,c=3) or self.bar or self.foo.bar() or just foo.bar, etc.
            IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
            try {
                TddPossibleMatches possibleMatch = entry.getValue();
                String callWithoutParens = entry.getKey();
                ItemPointer[] pointers = null;
                PySelection callPs = null;
                TddPossibleMatches lastPossibleMatchNotFound = possibleMatch;
                for (int i = 0; i < 10; i++) {
                    // more than 10 attribute accesses in a line? No way!
                    lastPossibleMatchNotFound = possibleMatch;
                    if (i > 0) {
                        // We have to take 1 level out of the match... i.e.: if it was self.foo.get(), search now for self.foo.
                        String line = FullRepIterable.getWithoutLastPart(possibleMatch.full);
                        List<TddPossibleMatches> tddPossibleMatchesAtLine = ps.getTddPossibleMatchesAtLine(line);
                        if (tddPossibleMatchesAtLine.size() > 0) {
                            possibleMatch = tddPossibleMatchesAtLine.get(0);
                            callWithoutParens = possibleMatch.initialPart + possibleMatch.secondPart;
                        } else {
                            continue CONTINUE_FOR;
                        }
                    }
                    String full = possibleMatch.full;
                    int indexOf = lineContents.indexOf(full);
                    if (indexOf < 0) {
                        Log.log("Did not expect index < 0.");
                        continue CONTINUE_FOR;
                    }
                    callPs = new PySelection(ps.getDoc(), ps.getLineOffset() + indexOf + callWithoutParens.length());
                    RefactoringRequest request = new RefactoringRequest(f, callPs, null, nature, edit);
                    // Don't look in additional info.
                    request.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
                    pointers = pyRefactoring.findDefinition(request);
                    if (((pointers != null && pointers.length > 0) || StringUtils.count(possibleMatch.full, '.') <= 1)) {
                        break;
                    }
                }
                if (pointers == null || callPs == null) {
                    continue CONTINUE_FOR;
                }
                if (lastPossibleMatchNotFound != null && lastPossibleMatchNotFound != possibleMatch && pointers.length >= 1) {
                    // Ok, as we were analyzing a string as self.bar.foo, we didn't find something in a pass
                    // i.e.: self.bar.foo, but we found it in a second pass
                    // as self.bar, so, this means we have to open the chance to create the 'foo' in self.bar.
                    String methodToCreate = FullRepIterable.getLastPart(lastPossibleMatchNotFound.secondPart);
                    int absoluteCursorOffset = callPs.getAbsoluteCursorOffset();
                    // +1 for the dot removed too.
                    absoluteCursorOffset = absoluteCursorOffset - (1 + methodToCreate.length());
                    PySelection newSelection = new PySelection(callPs.getDoc(), absoluteCursorOffset);
                    checkCreationBasedOnFoundPointers(edit, callPs, ret, possibleMatch, pointers, methodToCreate, newSelection, nature);
                    continue CONTINUE_FOR;
                }
                if (pointers.length >= 1) {
                    // the __init__ or something at the class level).
                    if (!checkInitCreation(edit, callPs, pointers, ret)) {
                        // This was called only when isCall == false
                        // Ok, if it's not a call and we found a field, it's still possible that we may want to create
                        // a field if it wasn't found in the __init__
                        boolean foundInInit = false;
                        for (ItemPointer p : pointers) {
                            Definition definition = p.definition;
                            try {
                                Object peek = definition.scope.getScopeStack().peek();
                                if (peek instanceof FunctionDef) {
                                    FunctionDef functionDef = (FunctionDef) peek;
                                    String rep = NodeUtils.getRepresentationString(functionDef);
                                    if (rep != null && rep.equals("__init__")) {
                                        foundInInit = true;
                                        break;
                                    }
                                }
                            } catch (Exception e) {
                            }
                        }
                        if (!foundInInit) {
                            checkMethodCreationAtClass(edit, pyRefactoring, callWithoutParens, callPs, ret, lineContents, possibleMatch, f, nature);
                        }
                    }
                } else if (pointers.length == 0) {
                    checkMethodCreationAtClass(edit, pyRefactoring, callWithoutParens, callPs, ret, lineContents, possibleMatch, f, nature);
                }
            } catch (Exception e) {
                if (onGetTddPropsError != null) {
                    onGetTddPropsError.call(e);
                }
                Log.log(e);
            }
        }
    }
    return ret;
}
Also used : TddPossibleMatches(org.python.pydev.core.docutils.PySelection.TddPossibleMatches) HashMap(java.util.HashMap) RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) AssignDefinition(org.python.pydev.ast.codecompletion.revisited.visitors.AssignDefinition) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring) BadLocationException(org.eclipse.jface.text.BadLocationException) CompletionRecursionException(org.python.pydev.core.structure.CompletionRecursionException) MisconfigurationException(org.python.pydev.core.MisconfigurationException) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) ArrayList(java.util.ArrayList) List(java.util.List) PySelection(org.python.pydev.core.docutils.PySelection) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Example 2 with IPyRefactoring

use of org.python.pydev.ast.refactoring.IPyRefactoring in project Pydev by fabioz.

the class PyRefactorAction method run.

/**
 * Actually executes this action.
 *
 * Checks preconditions... if
 */
@Override
public void run(final IAction action) {
    // Select from text editor
    // clear the cache from previous runs
    request = null;
    ps = PySelectionFromEditor.createPySelectionFromEditor(getTextEditor());
    RefactoringRequest req;
    try {
        req = getRefactoringRequest();
    } catch (MisconfigurationException e2) {
        Log.log(e2);
        return;
    }
    IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
    if (areRefactorPreconditionsOK(req, pyRefactoring) == false) {
        return;
    }
    UIJob job = new UIJob("Performing: " + this.getClass().getName()) {

        @Override
        public IStatus runInUIThread(final IProgressMonitor monitor) {
            try {
                Operation o = new Operation(action);
                o.execute(monitor);
            } catch (Exception e) {
                Log.log(e);
            }
            return Status.OK_STATUS;
        }
    };
    job.setSystem(true);
    job.schedule();
}
Also used : IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) MisconfigurationException(org.python.pydev.core.MisconfigurationException) UIJob(org.eclipse.ui.progress.UIJob) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring) WorkspaceModifyOperation(org.eclipse.ui.actions.WorkspaceModifyOperation) CoreException(org.eclipse.core.runtime.CoreException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MisconfigurationException(org.python.pydev.core.MisconfigurationException)

Example 3 with IPyRefactoring

use of org.python.pydev.ast.refactoring.IPyRefactoring in project Pydev by fabioz.

the class PyRenameRefactoring method rename.

public static String rename(IPyRefactoringRequest request) {
    try {
        List<RefactoringRequest> actualRequests = request.getRequests();
        if (actualRequests.size() == 1) {
            RefactoringRequest req = actualRequests.get(0);
            // Note: if it's already a ModuleRenameRefactoringRequest, no need to change anything.
            if (!(req.isModuleRenameRefactoringRequest())) {
                // Note: if we're renaming an import, we must change to the appropriate req
                IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
                ItemPointer[] pointers = pyRefactoring.findDefinition(req);
                for (ItemPointer pointer : pointers) {
                    Definition definition = pointer.definition;
                    if (RefactorProcessFactory.isModuleRename(definition)) {
                        try {
                            request = new PyRefactoringRequest(new ModuleRenameRefactoringRequest(definition.module.getFile(), req.nature, null));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }
        PyRenameEntryPoint entryPoint = new PyRenameEntryPoint(request);
        RenameRefactoring renameRefactoring = new RenameRefactoring(entryPoint);
        request.fillActivationTokenAndQualifier();
        String title = "Rename";
        if (request instanceof MultiModuleMoveRefactoringRequest) {
            MultiModuleMoveRefactoringRequest multiModuleMoveRefactoringRequest = (MultiModuleMoveRefactoringRequest) request;
            title = "Move To package (project: " + multiModuleMoveRefactoringRequest.getTarget().getProject().getName() + ")";
        }
        final PyRenameRefactoringWizard wizard = new PyRenameRefactoringWizard(renameRefactoring, title, "inputPageDescription", request);
        try {
            RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
            op.run(EditorUtils.getShell(), "Rename Refactor Action");
        } catch (InterruptedException e) {
        // do nothing. User action got cancelled
        }
    } catch (Exception e) {
        Log.log(e);
    }
    return null;
}
Also used : MultiModuleMoveRefactoringRequest(org.python.pydev.ast.refactoring.MultiModuleMoveRefactoringRequest) RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) MultiModuleMoveRefactoringRequest(org.python.pydev.ast.refactoring.MultiModuleMoveRefactoringRequest) ModuleRenameRefactoringRequest(org.python.pydev.ast.refactoring.ModuleRenameRefactoringRequest) PyRefactoringRequest(org.python.pydev.ast.refactoring.PyRefactoringRequest) IPyRefactoringRequest(org.python.pydev.ast.refactoring.IPyRefactoringRequest) RenameRefactoring(org.eclipse.ltk.core.refactoring.participants.RenameRefactoring) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring) IOException(java.io.IOException) IOException(java.io.IOException) RefactoringWizardOpenOperation(org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation) ModuleRenameRefactoringRequest(org.python.pydev.ast.refactoring.ModuleRenameRefactoringRequest) PyRenameEntryPoint(com.python.pydev.analysis.refactoring.wizards.rename.PyRenameEntryPoint) PyRefactoringRequest(org.python.pydev.ast.refactoring.PyRefactoringRequest) IPyRefactoringRequest(org.python.pydev.ast.refactoring.IPyRefactoringRequest) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Example 4 with IPyRefactoring

use of org.python.pydev.ast.refactoring.IPyRefactoring in project Pydev by fabioz.

the class PyReferenceSearcher method prepareSearch.

/**
 * Prepares for an upcoming use of {@link #search(RefactoringRequest)}.  This must be called
 * before a search is performed.
 *
 * @param request the search request.
 * @throws SearchException if the AST can not be found or the definition for the
 *     identifier isn't valid or can't otherwise be searched.
 * @throws BadLocationException
 * @throws TooManyMatchesException
 */
public void prepareSearch(RefactoringRequest request) throws SearchException, TooManyMatchesException, BadLocationException {
    List<IRefactorRenameProcess> processes = requestToProcesses.get(request);
    // Clear the existing processes for the request
    processes.clear();
    ItemPointer[] pointers;
    if (request.isModuleRenameRefactoringRequest()) {
        IModule module = request.getModule();
        pointers = new ItemPointer[] { new ItemPointer(request.file, new Location(0, 0), new Location(0, 0), new Definition(1, 1, "", null, null, module, false), null) };
    } else {
        SimpleNode ast = request.getAST();
        if (ast == null) {
            throw new SearchException("AST not generated (syntax error).");
        }
        IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
        request.communicateWork("Finding definition");
        pointers = pyRefactoring.findDefinition(request);
    }
    if (pointers.length == 0) {
        // no definition found
        IRefactorRenameProcess p = RefactorProcessFactory.getRenameAnyProcess();
        processes.add(p);
    } else {
        for (ItemPointer pointer : pointers) {
            if (pointer.definition == null) {
                throw new SearchException(INVALID_DEFINITION + pointer);
            }
            IRefactorRenameProcess p = RefactorProcessFactory.getProcess(pointer.definition, request);
            if (p == null) {
                throw new SearchException(INVALID_DEFINITION + pointer.definition);
            }
            processes.add(p);
        }
    }
    if (processes.isEmpty()) {
        throw new SearchException("The pre-conditions were not satisfied.");
    }
}
Also used : IModule(org.python.pydev.core.IModule) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring) IRefactorRenameProcess(com.python.pydev.analysis.refactoring.wizards.IRefactorRenameProcess) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer) Location(org.python.pydev.shared_core.structure.Location) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Example 5 with IPyRefactoring

use of org.python.pydev.ast.refactoring.IPyRefactoring in project Pydev by fabioz.

the class PyGoToDefinition method findDefinition.

/**
 * @return an array of ItemPointer with the definitions found
 * @throws MisconfigurationException
 * @throws TooManyMatchesException
 * @throws BadLocationException
 */
public ItemPointer[] findDefinition(PyEdit pyEdit, boolean acceptTypeshed, boolean findInAdditionalInfo) throws TooManyMatchesException, MisconfigurationException, BadLocationException {
    IPyRefactoring pyRefactoring = AbstractPyRefactoring.getPyRefactoring();
    RefactoringRequest refactoringRequest = getRefactoringRequest();
    refactoringRequest.acceptTypeshed = acceptTypeshed;
    refactoringRequest.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, findInAdditionalInfo);
    return pyRefactoring.findDefinition(refactoringRequest);
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) IPyRefactoring(org.python.pydev.ast.refactoring.IPyRefactoring)

Aggregations

IPyRefactoring (org.python.pydev.ast.refactoring.IPyRefactoring)6 RefactoringRequest (org.python.pydev.ast.refactoring.RefactoringRequest)5 Definition (org.python.pydev.ast.codecompletion.revisited.visitors.Definition)3 ItemPointer (org.python.pydev.ast.item_pointer.ItemPointer)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)2 MisconfigurationException (org.python.pydev.core.MisconfigurationException)2 IRefactorRenameProcess (com.python.pydev.analysis.refactoring.wizards.IRefactorRenameProcess)1 PyRenameEntryPoint (com.python.pydev.analysis.refactoring.wizards.rename.PyRenameEntryPoint)1 PyHierarchyView (com.python.pydev.ui.hierarchy.PyHierarchyView)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 CoreException (org.eclipse.core.runtime.CoreException)1 ProgressMonitorDialog (org.eclipse.jface.dialogs.ProgressMonitorDialog)1 IRunnableWithProgress (org.eclipse.jface.operation.IRunnableWithProgress)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1 RenameRefactoring (org.eclipse.ltk.core.refactoring.participants.RenameRefactoring)1 RefactoringWizardOpenOperation (org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation)1