Search in sources :

Example 1 with RefactoringRequest

use of org.python.pydev.ast.refactoring.RefactoringRequest 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 RefactoringRequest

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

the class TddCodeGenerationQuickFixParticipant method checkMethodCreationAtClass.

private boolean checkMethodCreationAtClass(PyEdit edit, IPyRefactoring pyRefactoring, String callWithoutParens, PySelection callPs, List<ICompletionProposalHandle> ret, String lineContents, TddPossibleMatches possibleMatch, File f, IPythonNature nature) throws MisconfigurationException, Exception {
    RefactoringRequest request;
    ItemPointer[] pointers;
    // Ok, no definition found for the full string, so, check if we have a dot there and check
    // if it could be a method in a local variable.
    String[] headAndTail = FullRepIterable.headAndTail(callWithoutParens);
    if (headAndTail[0].length() > 0) {
        String methodToCreate = headAndTail[1];
        if (headAndTail[0].equals("self")) {
            // creating something in the current class -- note that if it was self.bar here, we'd treat it as regular
            // (i.e.: no special support for self), so, we wouldn't enter here!
            int firstCharPosition = PySelection.getFirstCharPosition(lineContents);
            LineStartingScope scopeStart = callPs.getPreviousLineThatStartsScope(PySelection.CLASS_TOKEN, false, firstCharPosition);
            String classNameInLine = null;
            if (scopeStart != null) {
                for (Boolean isCall : new Boolean[] { true, false }) {
                    PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
                    List<String> parametersAfterCall = null;
                    parametersAfterCall = configCreateAsAndReturnParametersAfterCall(callPs, isCall, pyCreateMethod, parametersAfterCall, methodToCreate);
                    String startingScopeLineContents = callPs.getLine(scopeStart.iLineStartingScope);
                    classNameInLine = PySelection.getClassNameInLine(startingScopeLineContents);
                    if (classNameInLine != null && classNameInLine.length() > 0) {
                        pyCreateMethod.setCreateInClass(classNameInLine);
                        addCreateMethodOption(callPs, edit, ret, methodToCreate, parametersAfterCall, pyCreateMethod, classNameInLine);
                    }
                }
            }
            return true;
        }
        int absoluteCursorOffset = callPs.getAbsoluteCursorOffset();
        // +1 for the dot removed too.
        absoluteCursorOffset = absoluteCursorOffset - (1 + methodToCreate.length());
        PySelection newSelection = new PySelection(callPs.getDoc(), absoluteCursorOffset);
        request = new RefactoringRequest(f, newSelection, null, nature, edit);
        // Don't look in additional info.
        request.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
        pointers = pyRefactoring.findDefinition(request);
        if (pointers.length == 1) {
            if (checkCreationBasedOnFoundPointers(edit, callPs, ret, possibleMatch, pointers, methodToCreate, newSelection, nature)) {
                return true;
            }
        }
    }
    return false;
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) PySelection(org.python.pydev.core.docutils.PySelection) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Example 3 with RefactoringRequest

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

the class MarkOccurrencesJob method getRefactoringRequest.

/**
 * @param pyEdit the editor where we should look for the occurrences
 * @param pyRefactorAction the action that will return the initial refactoring request
 * @param ps the pyselection used (if null it will be created in this method)
 * @return a refactoring request suitable for finding the locals in the file
 * @throws BadLocationException
 * @throws MisconfigurationException
 */
public static RefactoringRequest getRefactoringRequest(final PyEdit pyEdit, PyRefactorAction pyRefactorAction, PySelection ps) throws BadLocationException, MisconfigurationException {
    final RefactoringRequest req = pyRefactorAction.getRefactoringRequest();
    req.ps = ps;
    req.fillActivationTokenAndQualifier();
    req.inputName = "foo";
    req.setAdditionalInfo(RefactoringRequest.FIND_DEFINITION_IN_ADDITIONAL_INFO, false);
    req.setAdditionalInfo(RefactoringRequest.FIND_REFERENCES_ONLY_IN_LOCAL_SCOPE, true);
    return req;
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest)

Example 4 with RefactoringRequest

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

the class ClassHierarchySearchTest method setUpModule.

private RefactoringRequest setUpModule(final int line, final int col, String str, String modName, PythonNature natureToAdd) {
    File f = new File(natureToAdd == nature2 ? baseDir2 : baseDir, modName + ".py");
    Document doc = new Document(str);
    PySelection ps = new PySelection(doc, line, col);
    RefactoringRequest request = new RefactoringRequest(null, ps, natureToAdd);
    request.moduleName = modName;
    final SimpleNode ast = request.getAST();
    FileUtils.writeStrToFile(str, f);
    addModuleToNature(ast, modName, natureToAdd, f);
    return request;
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) PySelection(org.python.pydev.core.docutils.PySelection) Document(org.eclipse.jface.text.Document) File(java.io.File) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Example 5 with RefactoringRequest

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

the class ClassHierarchySearchTest method testFindHierarchy3.

public void testFindHierarchy3() {
    String str = "" + "import pickle             \n" + "class Bar:\n" + "    pass                  \n" + "class Foo(Bar, pickle.Pickler):\n" + "    pass                  \n" + "\n" + "";
    final int line = 3;
    final int col = 9;
    RefactoringRequest request = setUpFooModule(line, col, str);
    HierarchyNodeModel node = refactorer.findClassHierarchy(request, false);
    assertEquals("Foo", node.name);
    assertTrue(node.moduleName.startsWith("foo"));
    assertIsIn("Bar", node.moduleName, node.parents);
    assertIsIn("Pickler", "pickle", node.parents);
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) HierarchyNodeModel(org.python.pydev.ast.refactoring.HierarchyNodeModel)

Aggregations

RefactoringRequest (org.python.pydev.ast.refactoring.RefactoringRequest)59 PySelection (org.python.pydev.core.docutils.PySelection)30 ItemPointer (org.python.pydev.ast.item_pointer.ItemPointer)29 File (java.io.File)26 HierarchyNodeModel (org.python.pydev.ast.refactoring.HierarchyNodeModel)10 ArrayList (java.util.ArrayList)7 Document (org.eclipse.jface.text.Document)7 CoreException (org.eclipse.core.runtime.CoreException)6 BadLocationException (org.eclipse.jface.text.BadLocationException)6 MisconfigurationException (org.python.pydev.core.MisconfigurationException)6 HashSet (java.util.HashSet)5 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)5 IDocument (org.eclipse.jface.text.IDocument)5 IPyRefactoring (org.python.pydev.ast.refactoring.IPyRefactoring)5 PyRefactoringRequest (org.python.pydev.ast.refactoring.PyRefactoringRequest)5 Tuple (org.python.pydev.shared_core.structure.Tuple)5 IFile (org.eclipse.core.resources.IFile)4 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)4 Definition (org.python.pydev.ast.codecompletion.revisited.visitors.Definition)4 IPyRefactoringRequest (org.python.pydev.ast.refactoring.IPyRefactoringRequest)4