Search in sources :

Example 1 with OrderedSet

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

the class ArgumentsChecker method analyzeCallAndFunctionMatch.

protected void analyzeCallAndFunctionMatch(Call callNode, FunctionDef functionDefinitionReferenced, IToken nameToken, boolean callingBoundMethod) throws Exception {
    int functionArgsLen = functionDefinitionReferenced.args.args != null ? functionDefinitionReferenced.args.args.length : 0;
    Collection<String> functionRequiredArgs = new OrderedSet<String>(functionArgsLen);
    Collection<String> functionOptionalArgs = new OrderedSet<String>(functionArgsLen);
    int staticOrClassMethod = isStaticOrClassMethod(functionDefinitionReferenced);
    boolean ignoreFirstParameter = callingBoundMethod;
    if (staticOrClassMethod != NO_STATIC_NOR_CLASSMETHOD) {
        switch(staticOrClassMethod) {
            case STATICMETHOD:
                ignoreFirstParameter = false;
                break;
            case CLASSMETHOD:
                ignoreFirstParameter = true;
                break;
            default:
                throw new AssertionError("Unexpected condition.");
        }
    }
    for (int i = 0; i < functionArgsLen; i++) {
        if (i == 0 && ignoreFirstParameter) {
            // Ignore first parameter when calling a bound method.
            continue;
        }
        String rep = NodeUtils.getRepresentationString(functionDefinitionReferenced.args.args[i]);
        if (rep == null) {
            continue;
        }
        if (functionDefinitionReferenced.args.defaults == null || (functionDefinitionReferenced.args.defaults.length > i && functionDefinitionReferenced.args.defaults[i] == null)) {
            // it's null, so, it's required
            functionRequiredArgs.add(rep);
        } else {
            // not null: optional with default value
            functionOptionalArgs.add(rep);
        }
    }
    exprType[] kwonlyargs = functionDefinitionReferenced.args.kwonlyargs;
    Collection<String> functionKeywordOnlyArgs = null;
    if (kwonlyargs != null) {
        functionKeywordOnlyArgs = new OrderedSet<String>(kwonlyargs.length);
        for (exprType exprType : kwonlyargs) {
            if (exprType != null) {
                String representationString = NodeUtils.getRepresentationString(exprType);
                if (representationString != null) {
                    functionKeywordOnlyArgs.add(representationString);
                }
            }
        }
    }
    int callArgsLen = callNode.args != null ? callNode.args.length : 0;
    for (int i = 0; i < callArgsLen; i++) {
        if (functionRequiredArgs.size() > 0) {
            // Remove first one (no better api in collection...)
            Iterator<String> it = functionRequiredArgs.iterator();
            it.next();
            it.remove();
            continue;
        } else if (functionOptionalArgs.size() > 0) {
            Iterator<String> it = functionOptionalArgs.iterator();
            it.next();
            it.remove();
            continue;
        }
        // be possible to accept an item that's in *args at this point.
        if (functionDefinitionReferenced.args.vararg == null) {
            onArgumentsMismatch(nameToken, callNode);
            // Error reported, so, bail out of function!
            return;
        }
    }
    int callKeywordArgsLen = callNode.keywords != null ? callNode.keywords.length : 0;
    for (int i = 0; i < callKeywordArgsLen; i++) {
        String rep = NodeUtils.getRepresentationString(callNode.keywords[i].arg);
        if (rep != null) {
            // keyword argument (i.e.: call(a=10)), so, only accepted in kwargs or with some argument with that name.
            if (functionRequiredArgs.remove(rep)) {
                continue;
            } else if (functionOptionalArgs.remove(rep)) {
                continue;
            } else if (functionKeywordOnlyArgs != null && functionKeywordOnlyArgs.remove(rep)) {
                continue;
            } else {
                // An argument with that name was not found, so, it may only be handled through kwargs at this point!
                if (functionDefinitionReferenced.args.kwarg == null) {
                    onArgumentsMismatch(nameToken, callNode);
                    // Error reported, so, bail out of function!
                    return;
                }
            }
        }
    }
    if (functionRequiredArgs.size() > 0 || (functionKeywordOnlyArgs != null && functionKeywordOnlyArgs.size() > 0)) {
        if (callNode.kwargs == null && callNode.starargs == null) {
            // Not all required parameters were consumed!
            onArgumentsMismatch(nameToken, callNode);
            // Error reported, so, bail out of function!
            return;
        }
    } else if (functionOptionalArgs.size() > 0) {
    } else {
        // required and optional size == 0
        if (callNode.kwargs != null && functionDefinitionReferenced.args.kwarg == null) {
            // We have more things that were not handled
            onArgumentsMismatch(nameToken, callNode);
            // Error reported, so, bail out of function!
            return;
        }
        if (callNode.starargs != null && functionDefinitionReferenced.args.vararg == null) {
            // We have more things that were not handled
            onArgumentsMismatch(nameToken, callNode);
            // Error reported, so, bail out of function!
            return;
        }
    }
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) Iterator(java.util.Iterator)

Example 2 with OrderedSet

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

the class AbstractAnalysisMarkersParticipants method getProps.

@Override
public List<ICompletionProposalHandle> getProps(PySelection ps, IImageCache imageCache, File f, IPythonNature nature, IPyEdit edit, int offset) throws BadLocationException {
    fillParticipants();
    PySourceViewer s = ((PyEdit) edit).getPySourceViewer();
    int line = ps.getLineOfOffset(offset);
    OrderedSet<MarkerAnnotationAndPosition> markersAtLine = new OrderedSet<MarkerAnnotationAndPosition>();
    // Add it to a set to make sure that the entries are unique.
    // -- i.e.: the code analysis seems to be creating 2 markers in the following case (when sys is undefined):
    // sys.call1().call2()
    // So, we add it to a set to make sure we'll only analyze unique markers.
    // Note that it'll check equality by the marker type and text (not by position), so, if a given error
    // appears twice in the same line being correct, we'll only show the options once here (which is what
    // we want).
    List<MarkerAnnotationAndPosition> markersAtLine2 = s.getMarkersAtLine(line, getMarkerType());
    markersAtLine.addAll(markersAtLine2);
    ArrayList<ICompletionProposalHandle> props = new ArrayList<ICompletionProposalHandle>();
    if (markersAtLine != null) {
        IAnalysisPreferences analysisPreferences = new AnalysisPreferences(edit);
        String currLine = ps.getLine();
        for (MarkerAnnotationAndPosition marker : markersAtLine) {
            for (IAnalysisMarkersParticipant participant : participants) {
                try {
                    participant.addProps(marker, analysisPreferences, currLine, ps, offset, nature, (PyEdit) edit, props);
                } catch (Exception e) {
                    Log.log("Error when getting proposals.", e);
                }
            }
        }
    }
    return props;
}
Also used : OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) AnalysisPreferences(com.python.pydev.analysis.AnalysisPreferences) IAnalysisPreferences(org.python.pydev.ast.analysis.IAnalysisPreferences) ArrayList(java.util.ArrayList) BadLocationException(org.eclipse.jface.text.BadLocationException) IAnalysisPreferences(org.python.pydev.ast.analysis.IAnalysisPreferences) ICompletionProposalHandle(org.python.pydev.shared_core.code_completion.ICompletionProposalHandle) PySourceViewer(org.python.pydev.editor.codefolding.PySourceViewer) IPyEdit(org.python.pydev.core.IPyEdit) PyEdit(org.python.pydev.editor.PyEdit) MarkerAnnotationAndPosition(org.python.pydev.editor.codefolding.MarkerAnnotationAndPosition)

Example 3 with OrderedSet

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

the class PyRenameGlobalProcess method findReferencesOnOtherModule.

@Override
protected List<ASTEntry> findReferencesOnOtherModule(RefactoringStatus status, RefactoringRequest request, String initialName, SourceModule module) {
    ICompletionState completionCache = new CompletionState();
    completionCache.setAcceptTypeshed(request.acceptTypeshed);
    Set<ASTEntry> ret = new OrderedSet<ASTEntry>();
    List<ASTEntry> localOccurrences = ScopeAnalysis.getLocalOccurrences(initialName, module.getAst(), false);
    localOccurrences.addAll(ScopeAnalysis.getFullAttributeReferencesFromPartialName(initialName, module.getAst()));
    if (localOccurrences.size() > 0) {
        try {
            List<IDefinition> actualDefinitions = request.findActualDefinitions(completionCache);
            for (ASTEntry occurrence : localOccurrences) {
                String fullRepresentationString = NodeUtils.getFullRepresentationString(occurrence.node);
                List<IDefinition> foundDefs = PyRefactoringFindDefinition.findActualDefinition(request.getMonitor(), request.acceptTypeshed, module, fullRepresentationString, null, occurrence.node.beginLine, occurrence.node.beginColumn, module.getNature(), completionCache, false);
                for (IDefinition def : foundDefs) {
                    IModule defModule = def.getModule();
                    if (defModule == null || (def instanceof Definition && ((Definition) def).ast == null)) {
                        // If we're unsure, just add it.
                        ret.add(occurrence);
                        continue;
                    }
                    for (IDefinition actualDef : actualDefinitions) {
                        IModule actualDefModule = actualDef.getModule();
                        if (defModule.getName().equals(actualDefModule.getName())) {
                            ret.add(occurrence);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.log(e);
        }
    }
    return new ArrayList<ASTEntry>(ret);
}
Also used : OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) 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) ArrayList(java.util.ArrayList) CompletionState(org.python.pydev.ast.codecompletion.revisited.CompletionState) ICompletionState(org.python.pydev.core.ICompletionState) IDefinition(org.python.pydev.core.IDefinition) ICompletionState(org.python.pydev.core.ICompletionState) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry)

Example 4 with OrderedSet

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

the class SyncSystemModulesManager method computeChanges.

/**
 * Given the tree structure we created initially with all the changes (root) and the elements
 * that the user selected in the tree (selectElements), return a list of infos updated with the
 * proper pythonpath.
 */
private List<IInterpreterInfo> computeChanges(final DataAndImageTreeNode root, List<TreeNode> selectElements) {
    List<IInterpreterInfo> changedInfos = new ArrayList<>();
    HashSet<TreeNode> set = new HashSet<TreeNode>(selectElements.size());
    set.addAll(selectElements);
    for (Object n : root.getChildren()) {
        DataAndImageTreeNode interpreterNode = (DataAndImageTreeNode) n;
        if (set.contains(interpreterNode)) {
            IInterpreterInfo info = (IInterpreterInfo) interpreterNode.getData();
            List<String> pythonPath = info.getPythonPath();
            boolean changed = false;
            OrderedSet<String> newPythonPath = new OrderedSet<String>(pythonPath);
            for (Object entryNode : interpreterNode.getChildren()) {
                DataAndImageTreeNode pythonpathNode = (DataAndImageTreeNode) entryNode;
                if (set.contains(pythonpathNode)) {
                    PythonpathChange change = (PythonpathChange) pythonpathNode.data;
                    change.apply(newPythonPath);
                    changed = true;
                }
            }
            if (changed) {
                InterpreterInfo copy = (InterpreterInfo) info.makeCopy();
                copy.libs.clear();
                copy.libs.addAll(newPythonPath);
                changedInfos.add(copy);
            }
        }
    }
    return changedInfos;
}
Also used : OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) ArrayList(java.util.ArrayList) DataAndImageTreeNode(org.python.pydev.shared_core.structure.DataAndImageTreeNode) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) DataAndImageTreeNode(org.python.pydev.shared_core.structure.DataAndImageTreeNode) TreeNode(org.python.pydev.shared_core.structure.TreeNode) DefaultPathsForInterpreterInfo(org.python.pydev.ast.interpreter_managers.DefaultPathsForInterpreterInfo) InterpreterInfo(org.python.pydev.ast.interpreter_managers.InterpreterInfo) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) HashSet(java.util.HashSet)

Example 5 with OrderedSet

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

the class SyncSystemModulesManager method updateStructures.

/**
 * Here we'll update the tree structure to be shown to the user with the changes (root).
 * The managerToNameToInfo structure has the information on the interpreter manager and related
 * interpreter infos for which the changes should be checked.
 */
public void updateStructures(IProgressMonitor monitor, final DataAndImageTreeNode root, ManagerInfoToUpdate managerToNameToInfo, CreateInterpreterInfoCallback callback) {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }
    IImageCache imageCache = SharedCorePlugin.getImageCache();
    if (imageCache == null) {
        imageCache = new IImageCache() {

            @Override
            public IImageHandle getStringDecorated(String key, String stringToAddToDecoration) {
                return null;
            }

            @Override
            public IImageHandle getImageDecorated(String key, String decoration, int decorationLocation, String secondDecoration, int secondDecorationLocation) {
                return null;
            }

            @Override
            public IImageHandle getImageDecorated(String key, String decoration, int decorationLocation) {
                return null;
            }

            @Override
            public IImageHandle getImageDecorated(String key, String decoration) {
                return null;
            }

            @Override
            public IImageDescriptor getDescriptor(String projectIcon) {
                return null;
            }

            @Override
            public IImageHandle get(String key) {
                return null;
            }
        };
    }
    for (Tuple<IInterpreterManager, IInterpreterInfo> infos : managerToNameToInfo.getManagerAndInfos()) {
        IInterpreterManager manager = infos.o1;
        IInterpreterInfo internalInfo = infos.o2;
        String executable = internalInfo.getExecutableOrJar();
        IInterpreterInfo newInterpreterInfo = callback.createInterpreterInfo(manager, executable, monitor);
        if (newInterpreterInfo == null) {
            continue;
        }
        DefaultPathsForInterpreterInfo defaultPaths = new DefaultPathsForInterpreterInfo();
        OrderedSet<String> newEntries = new OrderedSet<String>(newInterpreterInfo.getPythonPath());
        newEntries.removeAll(internalInfo.getPythonPath());
        // Iterate over the new entries to suggest what should be added (we already have only what's not there).
        for (Iterator<String> it = newEntries.iterator(); it.hasNext(); ) {
            String entryInPythonpath = it.next();
            if (!defaultPaths.selectByDefault(entryInPythonpath) || !defaultPaths.exists(entryInPythonpath)) {
                // Don't suggest the addition of entries in the workspace or entries which do not exist.
                it.remove();
            }
        }
        // Iterate over existing entries to suggest what should be removed.
        OrderedSet<String> removedEntries = new OrderedSet<String>();
        List<String> pythonPath = internalInfo.getPythonPath();
        for (String string : pythonPath) {
            if (!new File(string).exists()) {
                // Only suggest a removal if it was removed from the filesystem.
                removedEntries.add(string);
            }
        }
        if (newEntries.size() > 0 || removedEntries.size() > 0) {
            DataAndImageTreeNode<IInterpreterInfo> interpreterNode = new DataAndImageTreeNode<IInterpreterInfo>(root, internalInfo, imageCache.get(UIConstants.PY_INTERPRETER_ICON));
            for (String s : newEntries) {
                new DataAndImageTreeNode(interpreterNode, new PythonpathChange(s, true), imageCache.get(UIConstants.LIB_SYSTEM));
            }
            for (String s : removedEntries) {
                new DataAndImageTreeNode(interpreterNode, new PythonpathChange(s, false), imageCache.get(UIConstants.REMOVE_LIB_SYSTEM));
            }
        }
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) OrderedSet(org.python.pydev.shared_core.structure.OrderedSet) IImageCache(org.python.pydev.shared_core.image.IImageCache) IImageDescriptor(org.python.pydev.shared_core.image.IImageDescriptor) DefaultPathsForInterpreterInfo(org.python.pydev.ast.interpreter_managers.DefaultPathsForInterpreterInfo) DataAndImageTreeNode(org.python.pydev.shared_core.structure.DataAndImageTreeNode) IInterpreterManager(org.python.pydev.core.IInterpreterManager) IImageHandle(org.python.pydev.shared_core.image.IImageHandle) IInterpreterInfo(org.python.pydev.core.IInterpreterInfo) File(java.io.File)

Aggregations

OrderedSet (org.python.pydev.shared_core.structure.OrderedSet)5 ArrayList (java.util.ArrayList)3 DefaultPathsForInterpreterInfo (org.python.pydev.ast.interpreter_managers.DefaultPathsForInterpreterInfo)2 IInterpreterInfo (org.python.pydev.core.IInterpreterInfo)2 DataAndImageTreeNode (org.python.pydev.shared_core.structure.DataAndImageTreeNode)2 AnalysisPreferences (com.python.pydev.analysis.AnalysisPreferences)1 File (java.io.File)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)1 BadLocationException (org.eclipse.jface.text.BadLocationException)1 IAnalysisPreferences (org.python.pydev.ast.analysis.IAnalysisPreferences)1 CompletionState (org.python.pydev.ast.codecompletion.revisited.CompletionState)1 Definition (org.python.pydev.ast.codecompletion.revisited.visitors.Definition)1 InterpreterInfo (org.python.pydev.ast.interpreter_managers.InterpreterInfo)1 PyRefactoringFindDefinition (org.python.pydev.ast.refactoring.PyRefactoringFindDefinition)1 ICompletionState (org.python.pydev.core.ICompletionState)1 IDefinition (org.python.pydev.core.IDefinition)1 IInterpreterManager (org.python.pydev.core.IInterpreterManager)1 IModule (org.python.pydev.core.IModule)1