Search in sources :

Example 1 with Location

use of org.python.pydev.shared_core.structure.Location in project Pydev by fabioz.

the class AnalysisPlugin method getDefinitionFromIInfo.

/**
 * @param pointers the list where the pointers will be added (if null, a new one will be created).
 * @param manager the manager to be used to get the definition.
 * @param nature the nature to be used.
 * @param info the info that we are looking for.
 * @param force whether we should force getting the ItemPointer if it's not readily available.
 * @return whether we actually tried to look for a completion or just bailed out due to force being == false.
 */
public static boolean getDefinitionFromIInfo(List<ItemPointer> pointers, ICodeCompletionASTManager manager, IPythonNature nature, IInfo info, ICompletionState completionCache, boolean requireIDefinition, boolean force) {
    if (pointers == null) {
        pointers = new ArrayList<>();
    }
    if (!requireIDefinition) {
        String file = info.getFile();
        if (file != null) {
            File f = new File(file);
            int line = info.getLine();
            int col = info.getCol();
            if (line > 0 && col > 0) {
                // 0 is invalid.
                ItemPointer itemPointer = new ItemPointer(f, new Location(line - 1, col - 1), new Location(line - 1, col - 1), null, null, f.toURI());
                pointers.add(itemPointer);
                return true;
            }
        }
    }
    if (!force) {
        return false;
    }
    IModule mod;
    String tok;
    mod = manager.getModule(info.getDeclaringModuleName(), nature, true, completionCache);
    if (mod != null) {
        if (info.getType() == IInfo.MOD_IMPORT_TYPE) {
            Definition definition = new Definition(1, 1, "", null, null, mod);
            PyRefactoringFindDefinition.getAsPointers(pointers, new Definition[] { definition });
            return true;
        }
        // ok, now that we found the module, we have to get the actual definition
        tok = "";
        String path = info.getPath();
        if (path != null && path.length() > 0) {
            tok = path + ".";
        }
        tok += info.getName();
        try {
            IDefinition[] definitions = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(tok, nature, completionCache), -1, -1, nature);
            if ((definitions == null || definitions.length == 0) && path != null && path.length() > 0) {
                // this can happen if we have something as an attribute in the path:
                // class Bar(object):
                // def __init__(self):
                // self.xxx = 10
                // 
                // so, we'de get a find definition for Bar.__init__.xxx which is something we won't find
                // for now, let's simply return a match in the correct context (although the correct way of doing
                // it would be analyzing that context to find the match)
                IDefinition[] contextDefinitions = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(path, nature, completionCache), -1, -1, nature);
                if (contextDefinitions != null && contextDefinitions.length > 0) {
                    for (IDefinition iDefinition : contextDefinitions) {
                        if (iDefinition instanceof Definition) {
                            Definition definition = (Definition) iDefinition;
                            if (definition.ast instanceof FunctionDef) {
                                FunctionDef functionDef = (FunctionDef) definition.ast;
                                if (functionDef.args != null) {
                                    exprType[] args = functionDef.args.args;
                                    if (args != null && args.length > 0) {
                                        // I.e.: only analyze functions with at least one argument (for self or cls).
                                        Map<String, SourceToken> repToTokenWithArgs = new HashMap<String, SourceToken>();
                                        HeuristicFindAttrs heuristicFindAttrs = new HeuristicFindAttrs(HeuristicFindAttrs.WHITIN_ANY, HeuristicFindAttrs.IN_ASSIGN, "", definition.module.getName(), null, repToTokenWithArgs, nature);
                                        heuristicFindAttrs.visitFunctionDef(functionDef);
                                        List<IToken> tokens = heuristicFindAttrs.getTokens();
                                        List<IDefinition> newDefs = new ArrayList<>();
                                        for (IToken iToken : tokens) {
                                            if (info.getName().equals(iToken.getRepresentation())) {
                                                newDefs.add(new Definition(iToken, definition.scope, definition.module));
                                            }
                                        }
                                        definitions = newDefs.toArray(new IDefinition[newDefs.size()]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            PyRefactoringFindDefinition.getAsPointers(pointers, definitions);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return true;
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) IModule(org.python.pydev.core.IModule) HashMap(java.util.HashMap) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) PyRefactoringFindDefinition(org.python.pydev.ast.refactoring.PyRefactoringFindDefinition) ArrayList(java.util.ArrayList) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) IDefinition(org.python.pydev.core.IDefinition) IToken(org.python.pydev.core.IToken) File(java.io.File) SourceToken(org.python.pydev.ast.codecompletion.revisited.modules.SourceToken) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer) Location(org.python.pydev.shared_core.structure.Location) HeuristicFindAttrs(org.python.pydev.ast.codecompletion.revisited.visitors.HeuristicFindAttrs)

Example 2 with Location

use of org.python.pydev.shared_core.structure.Location 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 3 with Location

use of org.python.pydev.shared_core.structure.Location in project Pydev by fabioz.

the class PyOpenResourceAction method openFiles.

@Override
protected void openFiles(PythonpathZipChildTreeNode[] pythonPathFilesSelected) {
    for (PythonpathZipChildTreeNode n : pythonPathFilesSelected) {
        try {
            if (PythonPathHelper.isValidSourceFile(n.zipPath)) {
                new PyOpenAction().run(new ItemPointer(n.zipStructure.file, new Location(), new Location(), null, n.zipPath));
            } else {
                IEditorRegistry editorReg = PlatformUI.getWorkbench().getEditorRegistry();
                IEditorDescriptor defaultEditor = editorReg.getDefaultEditor(n.zipPath);
                PydevZipFileStorage storage = new PydevZipFileStorage(n.zipStructure.file, n.zipPath);
                PydevZipFileEditorInput input = new PydevZipFileEditorInput(storage);
                if (defaultEditor != null) {
                    IDE.openEditor(page, input, defaultEditor.getId());
                } else {
                    IDE.openEditor(page, input, EditorsUI.DEFAULT_TEXT_EDITOR_ID);
                }
            }
        } catch (PartInitException e) {
            Log.log(e);
        }
    }
}
Also used : PythonpathZipChildTreeNode(org.python.pydev.navigator.PythonpathZipChildTreeNode) PyOpenAction(org.python.pydev.editor.actions.PyOpenAction) IEditorDescriptor(org.eclipse.ui.IEditorDescriptor) PydevZipFileStorage(org.python.pydev.shared_ui.editor_input.PydevZipFileStorage) PydevZipFileEditorInput(org.python.pydev.shared_ui.editor_input.PydevZipFileEditorInput) PartInitException(org.eclipse.ui.PartInitException) IEditorRegistry(org.eclipse.ui.IEditorRegistry) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer) Location(org.python.pydev.shared_core.structure.Location)

Example 4 with Location

use of org.python.pydev.shared_core.structure.Location in project Pydev by fabioz.

the class ItemPointerTest method testAsPortableString.

public void testAsPortableString() throws Exception {
    ItemPointer pointer = new ItemPointer(Path.fromPortableString("c:/temp/a.py"), new Location(1, 2), new Location(3, 4));
    String asPortableString = pointer.asPortableString();
    assertEquals(pointer, ItemPointer.fromPortableString(asPortableString));
    pointer = new ItemPointer(Path.fromPortableString("c:/temp/a.py"), new Location(1, 2), new Location(3, 4), null, "zipLocation");
    asPortableString = pointer.asPortableString();
    assertEquals(pointer, ItemPointer.fromPortableString(asPortableString));
}
Also used : ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer) Location(org.python.pydev.shared_core.structure.Location)

Example 5 with Location

use of org.python.pydev.shared_core.structure.Location in project Pydev by fabioz.

the class ItemPointer method fromPortableString.

public static ItemPointer fromPortableString(String asPortableString) {
    Properties properties = PropertiesHelper.createPropertiesFromString(asPortableString);
    String filePath = (String) properties.get("FILE_PATH");
    if (filePath == null) {
        return null;
    }
    String startLine = (String) properties.get("START_LINE");
    String startCol = (String) properties.get("START_COL");
    Location start;
    if (startLine != null && startCol != null) {
        start = new Location(Integer.parseInt(startLine), Integer.parseInt(startCol));
    } else {
        start = new Location();
    }
    String endLine = (String) properties.get("END_LINE");
    String endCol = (String) properties.get("END_COL");
    Location end;
    if (endLine != null && endCol != null) {
        end = new Location(Integer.parseInt(endLine), Integer.parseInt(endCol));
    } else {
        end = new Location();
    }
    String zip = (String) properties.get("ZIP");
    return new ItemPointer(Path.fromPortableString(filePath), start, end, null, zip);
}
Also used : Properties(java.util.Properties) Location(org.python.pydev.shared_core.structure.Location) BaseItemPointer(org.python.pydev.shared_core.locator.BaseItemPointer)

Aggregations

Location (org.python.pydev.shared_core.structure.Location)9 ItemPointer (org.python.pydev.ast.item_pointer.ItemPointer)8 File (java.io.File)4 IModule (org.python.pydev.core.IModule)3 Definition (org.python.pydev.ast.codecompletion.revisited.visitors.Definition)2 PyOpenAction (org.python.pydev.editor.actions.PyOpenAction)2 IRefactorRenameProcess (com.python.pydev.analysis.refactoring.wizards.IRefactorRenameProcess)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Properties (java.util.Properties)1 IFile (org.eclipse.core.resources.IFile)1 CoreException (org.eclipse.core.runtime.CoreException)1 FileLink (org.eclipse.debug.ui.console.FileLink)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1 IEditorDescriptor (org.eclipse.ui.IEditorDescriptor)1 IEditorRegistry (org.eclipse.ui.IEditorRegistry)1 PartInitException (org.eclipse.ui.PartInitException)1 IHyperlink (org.eclipse.ui.console.IHyperlink)1 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)1 SourceToken (org.python.pydev.ast.codecompletion.revisited.modules.SourceToken)1