Search in sources :

Example 1 with IDefinition

use of org.python.pydev.core.IDefinition 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 IDefinition

use of org.python.pydev.core.IDefinition in project Pydev by fabioz.

the class TddQuickFixParticipant method addProps.

@Override
public void addProps(MarkerAnnotationAndPosition markerAnnotation, IAnalysisPreferences analysisPreferences, String line, PySelection ps, int offset, IPythonNature nature, PyEdit edit, List<ICompletionProposalHandle> props) throws BadLocationException, CoreException {
    if (nature == null) {
        return;
    }
    ICodeCompletionASTManager astManager = nature.getAstManager();
    if (astManager == null) {
        return;
    }
    if (markerAnnotation.position == null) {
        return;
    }
    IMarker marker = markerAnnotation.markerAnnotation.getMarker();
    Integer id = (Integer) marker.getAttribute(AnalysisRunner.PYDEV_ANALYSIS_TYPE);
    int start = markerAnnotation.position.offset;
    int end = start + markerAnnotation.position.length;
    ps.setSelection(start, end);
    String markerContents;
    try {
        markerContents = ps.getSelectedText();
    } catch (Exception e1) {
        // Selection may be wrong.
        return;
    }
    IDocument doc = ps.getDoc();
    List<String> parametersAfterCall = ps.getParametersAfterCall(end);
    switch(id) {
        case IAnalysisPreferences.TYPE_UNDEFINED_VARIABLE:
            addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall);
            addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall);
            break;
        case IAnalysisPreferences.TYPE_UNDEFINED_IMPORT_VARIABLE:
            // Say we had something as:
            // import sys
            // sys.Bar
            // in which case 'Bar' is undefined
            // in this situation, the activationTokenAndQual would be "sys." and "Bar"
            // and we want to get the definition for "sys"
            String[] activationTokenAndQual = ps.getActivationTokenAndQualifier(true);
            if (activationTokenAndQual[0].endsWith(".")) {
                ArrayList<IDefinition> selected = findDefinitions(nature, edit, start - 2, doc);
                for (IDefinition iDefinition : selected) {
                    IModule module = iDefinition.getModule();
                    if (module.getFile() != null) {
                        Definition definition = (Definition) iDefinition;
                        File file = module.getFile();
                        if (definition.ast == null) {
                            // if we have no ast in the definition, it means the module itself was found (global scope)
                            // Add option to create class at the given module!
                            addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
                            addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
                        } else if (definition.ast instanceof ClassDef) {
                            ClassDef classDef = (ClassDef) definition.ast;
                            // Ok, we should create a field or method in this case (accessing a classmethod or staticmethod)
                            PyCreateMethodOrField pyCreateMethod = new PyCreateMethodOrField();
                            String className = NodeUtils.getNameFromNameTok(classDef.name);
                            pyCreateMethod.setCreateInClass(className);
                            pyCreateMethod.setCreateAs(PyCreateMethodOrField.CLASSMETHOD);
                            addCreateClassmethodOption(ps, edit, props, markerContents, parametersAfterCall, pyCreateMethod, file, className);
                        }
                    }
                }
            }
            break;
        case IAnalysisPreferences.TYPE_UNRESOLVED_IMPORT:
            // This case is the following: from other_module4 import Foo
            // with 'Foo' being undefined.
            // So, we have to suggest creating a Foo class/method in other_module4
            PyImportsHandling importsHandling = new PyImportsHandling(ps.getDoc(), false);
            int offsetLine = ps.getLineOfOffset(start);
            String selectedText = ps.getSelectedText();
            Tuple<IModule, String> found = null;
            String foundFromImportStr = null;
            boolean isImportFrom = false;
            OUT: for (ImportHandle handle : importsHandling) {
                if (handle.startFoundLine == offsetLine || handle.endFoundLine == offsetLine || (handle.startFoundLine < offsetLine && handle.endFoundLine > offsetLine)) {
                    List<ImportHandleInfo> importInfo = handle.getImportInfo();
                    for (ImportHandleInfo importHandleInfo : importInfo) {
                        String fromImportStr = importHandleInfo.getFromImportStr();
                        List<String> importedStr = importHandleInfo.getImportedStr();
                        for (String imported : importedStr) {
                            if (selectedText.equals(imported)) {
                                if (fromImportStr != null) {
                                    foundFromImportStr = fromImportStr + "." + imported;
                                    isImportFrom = true;
                                } else {
                                    // if fromImportStr == null, it's not a from xxx import yyy (i.e.: simple import)
                                    foundFromImportStr = imported;
                                }
                                try {
                                    String currentModule = nature.resolveModule(edit.getEditorFile());
                                    ICompletionState state = CompletionStateFactory.getEmptyCompletionState(nature, new CompletionCache());
                                    found = nature.getAstManager().findModule(foundFromImportStr, currentModule, state, new SourceModule(currentModule, edit.getEditorFile(), edit.getAST(), null, nature));
                                } catch (Exception e) {
                                    Log.log(e);
                                }
                                break OUT;
                            }
                        }
                    }
                    break OUT;
                }
            }
            boolean addOptionToCreateClassOrMethod = isImportFrom;
            if (found != null && found.o1 != null) {
                // or just create a class or method at the end.
                if (found.o1 instanceof SourceModule) {
                    // if all was found, there's nothing left to create.
                    if (found.o2 != null && found.o2.length() > 0) {
                        SourceModule sourceModule = (SourceModule) found.o1;
                        File file = sourceModule.getFile();
                        if (found.o2.indexOf('.') != -1) {
                            // We have to create some intermediary structure.
                            if (!addOptionToCreateClassOrMethod) {
                                // Cannot create class or method from the info (only the module structure).
                                if (sourceModule.getName().endsWith(".__init__")) {
                                    File f = getFileStructure(file.getParentFile(), found.o2);
                                    addCreateModuleOption(ps, edit, props, markerContents, f);
                                }
                            } else {
                                // Ok, the leaf may be a class or method.
                                if (sourceModule.getName().endsWith(".__init__")) {
                                    String moduleName = FullRepIterable.getWithoutLastPart(sourceModule.getName());
                                    String withoutLastPart = FullRepIterable.getWithoutLastPart(found.o2);
                                    moduleName += "." + withoutLastPart;
                                    String classOrMethodName = FullRepIterable.getLastPart(found.o2);
                                    File f = getFileStructure(file.getParentFile(), withoutLastPart);
                                    addCreateClassInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
                                    addCreateMethodInNewModuleOption(ps, edit, props, classOrMethodName, moduleName, parametersAfterCall, f);
                                }
                            }
                        } else {
                            // Ok, it's all there, we just have to create the leaf.
                            if (!addOptionToCreateClassOrMethod || sourceModule.getName().endsWith(".__init__")) {
                                // Cannot create class or method from the info (only the module structure).
                                if (sourceModule.getName().endsWith(".__init__")) {
                                    File f = new File(file.getParent(), found.o2 + FileTypesPreferences.getDefaultDottedPythonExtension());
                                    addCreateModuleOption(ps, edit, props, markerContents, f);
                                }
                            } else {
                                // Ok, the leaf may be a class or method.
                                addCreateClassOption(ps, edit, props, markerContents, parametersAfterCall, file);
                                addCreateMethodOption(ps, edit, props, markerContents, parametersAfterCall, file);
                            }
                        }
                    }
                }
            } else if (foundFromImportStr != null) {
                // We couldn't find anything there, so, we have to create the modules structure as needed and
                // maybe create a class or module at the end (but only if it's an import from).
                // Ok, it's all there, we just have to create the leaf.
                // Discover the source folder where we should create the structure.
                File editorFile = edit.getEditorFile();
                String onlyProjectPythonPathStr = nature.getPythonPathNature().getOnlyProjectPythonPathStr(false);
                List<String> split = StringUtils.splitAndRemoveEmptyTrimmed(onlyProjectPythonPathStr, '|');
                for (int i = 0; i < split.size(); i++) {
                    String fullPath = FileUtils.getFileAbsolutePath(split.get(i));
                    fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
                    split.set(i, fullPath);
                }
                HashSet<String> projectSourcePath = new HashSet<String>(split);
                if (projectSourcePath.size() == 0) {
                    // No source folder for editor... this shouldn't happen (code analysis wouldn't even run on it).
                    return;
                }
                String fullPath = FileUtils.getFileAbsolutePath(editorFile);
                fullPath = PythonPathHelper.getDefaultPathStr(fullPath);
                String foundSourceFolderFullPath = null;
                if (projectSourcePath.size() == 1) {
                    foundSourceFolderFullPath = projectSourcePath.iterator().next();
                } else {
                    for (String string : projectSourcePath) {
                        if (fullPath.startsWith(string)) {
                            // Use this as the source folder
                            foundSourceFolderFullPath = string;
                            break;
                        }
                    }
                }
                if (foundSourceFolderFullPath != null) {
                    if (!addOptionToCreateClassOrMethod) {
                        // Cannot create class or method from the info (only the module structure).
                        File f = getFileStructure(new File(foundSourceFolderFullPath), foundFromImportStr);
                        addCreateModuleOption(ps, edit, props, foundFromImportStr, f);
                    } else {
                        // Ok, the leaf may be a class or method.
                        String moduleName = FullRepIterable.getWithoutLastPart(foundFromImportStr);
                        File file = getFileStructure(new File(foundSourceFolderFullPath), moduleName);
                        String lastPart = FullRepIterable.getLastPart(foundFromImportStr);
                        addCreateClassInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
                        addCreateMethodInNewModuleOption(ps, edit, props, lastPart, moduleName, parametersAfterCall, file);
                    }
                }
            }
            break;
    }
}
Also used : IModule(org.python.pydev.core.IModule) ImportHandleInfo(org.python.pydev.core.docutils.ImportHandle.ImportHandleInfo) ClassDef(org.python.pydev.parser.jython.ast.ClassDef) ICompletionState(org.python.pydev.core.ICompletionState) ArrayList(java.util.ArrayList) List(java.util.List) ImportHandle(org.python.pydev.core.docutils.ImportHandle) HashSet(java.util.HashSet) SourceModule(org.python.pydev.ast.codecompletion.revisited.modules.SourceModule) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) PyRefactoringFindDefinition(org.python.pydev.ast.refactoring.PyRefactoringFindDefinition) CoreException(org.eclipse.core.runtime.CoreException) BadLocationException(org.eclipse.jface.text.BadLocationException) CompletionRecursionException(org.python.pydev.core.structure.CompletionRecursionException) IDefinition(org.python.pydev.core.IDefinition) ICodeCompletionASTManager(org.python.pydev.core.ICodeCompletionASTManager) CompletionCache(org.python.pydev.ast.codecompletion.revisited.CompletionCache) IMarker(org.eclipse.core.resources.IMarker) File(java.io.File) PyImportsHandling(org.python.pydev.core.docutils.PyImportsHandling) IDocument(org.eclipse.jface.text.IDocument)

Example 3 with IDefinition

use of org.python.pydev.core.IDefinition in project Pydev by fabioz.

the class ArgumentsChecker method checkNameFound.

/*default*/
void checkNameFound(Call callNode, SourceToken sourceToken) throws Exception {
    FunctionDef functionDefinitionReferenced;
    boolean callingBoundMethod = false;
    SimpleNode ast = sourceToken.getAst();
    if (ast instanceof FunctionDef) {
        functionDefinitionReferenced = (FunctionDef) ast;
        analyzeCallAndFunctionMatch(callNode, functionDefinitionReferenced, sourceToken, callingBoundMethod);
    } else if (ast instanceof ClassDef) {
        ClassDef classDef = (ClassDef) ast;
        SimpleNode initNode = defToConsideredInit.get(classDef);
        callingBoundMethod = true;
        if (initNode == null) {
            String className = ((NameTok) classDef.name).id;
            Definition foundDef = sourceToken.getDefinition();
            IModule mod = this.current;
            if (foundDef != null) {
                mod = foundDef.module;
            }
            SimpleNode n = NodeUtils.getNodeFromPath(classDef, "__init__");
            if (n instanceof FunctionDef) {
                initNode = n;
            } else {
                IDefinition[] definition = mod.findDefinition(CompletionStateFactory.getEmptyCompletionState(className + ".__init__", this.nature, this.completionCache), -1, -1, this.nature);
                for (IDefinition iDefinition : definition) {
                    Definition d = (Definition) iDefinition;
                    if (d.ast instanceof FunctionDef) {
                        initNode = d.ast;
                        defToConsideredInit.put(classDef, initNode);
                        break;
                    }
                }
            }
        }
        if (initNode instanceof FunctionDef) {
            functionDefinitionReferenced = (FunctionDef) initNode;
            analyzeCallAndFunctionMatch(callNode, functionDefinitionReferenced, sourceToken, callingBoundMethod);
        }
    }
}
Also used : ClassDef(org.python.pydev.parser.jython.ast.ClassDef) IModule(org.python.pydev.core.IModule) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) PyRefactoringFindDefinition(org.python.pydev.ast.refactoring.PyRefactoringFindDefinition) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) IDefinition(org.python.pydev.core.IDefinition) ISimpleNode(org.python.pydev.shared_core.model.ISimpleNode) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Example 4 with IDefinition

use of org.python.pydev.core.IDefinition in project Pydev by fabioz.

the class PyRefactoringFindDefinition method findActualDefinition.

/**
 * This method will try to find the actual definition given all the needed parameters (but it will not try to find
 * matches in the whole workspace if it's not able to find an exact match in the context)
 *
 * Note that the request must be already properly configured to be used in this function. Otherwise, the
 * function that should be used is {@link #findActualDefinition(RefactoringRequest, CompletionCache, ArrayList)}
 *
 * @param request: used only to communicateWork and checkCancelled
 * @param mod this is the module where we should find the definition
 * @param tok the token we're looking for (complete with dots)
 * @param foundDefinitions OUT: this is where the definitions should be added
 * @param beginLine starts at 1
 * @param beginCol starts at 1
 * @param pythonNature the nature that we should use to find the definition
 * @param completionCache cache to store completions
 * @return
 *
 * @throws Exception
 */
public static List<IDefinition> findActualDefinition(IProgressMonitor monitor, boolean acceptTypeshed, IModule mod, String tok, List<IDefinition> foundDefinitions, int beginLine, int beginCol, IPythonNature pythonNature, ICompletionCache completionCache, boolean searchForMethodParameterFromParticipants) throws Exception, CompletionRecursionException {
    if (foundDefinitions == null) {
        foundDefinitions = new ArrayList<IDefinition>();
    }
    ICompletionState completionState = CompletionStateFactory.getEmptyCompletionState(tok, pythonNature, beginLine - 1, beginCol - 1, completionCache);
    completionState.setAcceptTypeshed(acceptTypeshed);
    IDefinition[] definitions = mod.findDefinition(completionState, beginLine, beginCol, pythonNature);
    if (monitor != null) {
        monitor.setTaskName("Found:" + definitions.length + " definitions");
        monitor.worked(1);
        if (monitor.isCanceled()) {
            return foundDefinitions;
        }
    }
    int len = definitions.length;
    for (int i = 0; i < len; i++) {
        IDefinition definition = definitions[i];
        boolean doAdd = true;
        if (definition instanceof Definition) {
            Definition d = (Definition) definition;
            doAdd = !findActualTokenFromImportFromDefinition(pythonNature, tok, foundDefinitions, d, completionState, searchForMethodParameterFromParticipants);
        }
        if (monitor != null && monitor.isCanceled()) {
            return foundDefinitions;
        }
        if (doAdd) {
            foundDefinitions.add(definition);
        }
    }
    return foundDefinitions;
}
Also used : ICompletionState(org.python.pydev.core.ICompletionState) IDefinition(org.python.pydev.core.IDefinition) Definition(org.python.pydev.ast.codecompletion.revisited.visitors.Definition) IDefinition(org.python.pydev.core.IDefinition)

Example 5 with IDefinition

use of org.python.pydev.core.IDefinition in project Pydev by fabioz.

the class PyRefactoringFindDefinition method getAsPointers.

/**
 * @param pointers: OUT: list where the pointers will be added
 * @param definitions the definitions that will be gotten as pointers
 */
public static void getAsPointers(List<ItemPointer> pointers, IDefinition[] definitions) {
    for (IDefinition definition : definitions) {
        ItemPointer itemPointer = createItemPointer(definition);
        pointers.add(itemPointer);
    }
}
Also used : IDefinition(org.python.pydev.core.IDefinition) ItemPointer(org.python.pydev.ast.item_pointer.ItemPointer)

Aggregations

IDefinition (org.python.pydev.core.IDefinition)35 ArrayList (java.util.ArrayList)22 Definition (org.python.pydev.ast.codecompletion.revisited.visitors.Definition)21 PyRefactoringFindDefinition (org.python.pydev.ast.refactoring.PyRefactoringFindDefinition)15 IModule (org.python.pydev.core.IModule)14 AssignDefinition (org.python.pydev.ast.codecompletion.revisited.visitors.AssignDefinition)10 ICompletionState (org.python.pydev.core.ICompletionState)9 CompletionRecursionException (org.python.pydev.core.structure.CompletionRecursionException)9 FunctionDef (org.python.pydev.parser.jython.ast.FunctionDef)9 ICompletionCache (org.python.pydev.core.ICompletionCache)8 SimpleNode (org.python.pydev.parser.jython.SimpleNode)7 ClassDef (org.python.pydev.parser.jython.ast.ClassDef)7 ItemPointer (org.python.pydev.ast.item_pointer.ItemPointer)6 MisconfigurationException (org.python.pydev.core.MisconfigurationException)6 TokensList (org.python.pydev.core.TokensList)6 org.python.pydev.parser.jython.ast.exprType (org.python.pydev.parser.jython.ast.exprType)6 HashSet (java.util.HashSet)5 CoreException (org.eclipse.core.runtime.CoreException)5 BadLocationException (org.eclipse.jface.text.BadLocationException)5 File (java.io.File)4