Search in sources :

Example 16 with ASTEntry

use of org.python.pydev.parser.visitors.scope.ASTEntry in project Pydev by fabioz.

the class PyOutlineSelectionDialog method calculateHierarchy.

@Override
protected void calculateHierarchy() {
    if (root != null) {
        return;
    }
    if (this.ast == null && pyEdit != null) {
        this.ast = pyEdit.getAST();
    }
    if (ast == null) {
        return;
    }
    DefinitionsASTIteratorVisitor visitor = DefinitionsASTIteratorVisitor.create(ast);
    if (visitor == null) {
        return;
    }
    Map<ASTEntry, DataAndImageTreeNode<Object>> entryToTreeNode = new HashMap<ASTEntry, DataAndImageTreeNode<Object>>();
    // Step 1: create 'regular' tree structure from the nodes.
    DataAndImageTreeNode<Object> root = new DataAndImageTreeNode<Object>(null, null, null);
    for (Iterator<ASTEntry> it = visitor.getOutline(); it.hasNext(); ) {
        ASTEntry next = it.next();
        DataAndImageTreeNode<Object> n;
        if (next.parent != null) {
            DataAndImageTreeNode<Object> parent = entryToTreeNode.get(next.parent);
            if (parent == null) {
                Log.log("Unexpected condition: child found before parent!");
                parent = root;
            }
            n = new DataAndImageTreeNode<Object>(parent, new OutlineEntry(next), null);
        } else {
            n = new DataAndImageTreeNode<Object>(root, new OutlineEntry(next), null);
        }
        if (((OutlineEntry) n.data).node.beginLine <= startLineIndex) {
            initialSelection = n;
        }
        entryToTreeNode.put(next, n);
    }
    this.root = root;
}
Also used : HashMap(java.util.HashMap) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) DefinitionsASTIteratorVisitor(org.python.pydev.parser.visitors.scope.DefinitionsASTIteratorVisitor) DataAndImageTreeNode(org.python.pydev.shared_core.structure.DataAndImageTreeNode)

Example 17 with ASTEntry

use of org.python.pydev.parser.visitors.scope.ASTEntry in project Pydev by fabioz.

the class ShowOutlineLabelProvider method getStyledText.

@Override
public StyledString getStyledText(Object element) {
    if (element instanceof DataAndImageTreeNode) {
        @SuppressWarnings("rawtypes") DataAndImageTreeNode treeNode = (DataAndImageTreeNode) element;
        element = treeNode.data;
    }
    if (element instanceof OutlineEntry) {
        OutlineEntry entry = (OutlineEntry) element;
        String start = NodeUtils.getFullRepresentationString(entry.node);
        if (entry.model != null) {
            FastStringBuffer suffix = new FastStringBuffer("    (", entry.model.name.length() + 50).append(entry.model.name);
            if (entry.model.moduleName != null && entry.model.moduleName.length() > 0) {
                suffix.append(" - ").append(entry.model.moduleName);
            }
            suffix.append(')');
            return new StyledString(start).append(suffix.toString(), StyledString.QUALIFIER_STYLER);
        } else if (entry.parentClass != null) {
            FastStringBuffer suffix = new FastStringBuffer("    (", entry.parentClass.length() + 4).append(entry.parentClass).append(')');
            return new StyledString(start).append(suffix.toString(), StyledString.QUALIFIER_STYLER);
        }
        return new StyledString(start);
    }
    if (element instanceof ASTEntry) {
        return new StyledString(NodeUtils.getFullRepresentationString(((ASTEntry) element).node));
    }
    return new StyledString(element.toString());
}
Also used : FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) StyledString(org.eclipse.jface.viewers.StyledString) StyledString(org.eclipse.jface.viewers.StyledString) DataAndImageTreeNode(org.python.pydev.shared_core.structure.DataAndImageTreeNode)

Example 18 with ASTEntry

use of org.python.pydev.parser.visitors.scope.ASTEntry in project Pydev by fabioz.

the class PyMoveImportsToLocalCompletionProposal method apply.

@Override
public void apply(IDocument doc) {
    RefactoringRequest req = refactoringRequest;
    final IPyRefactoring2 r = (IPyRefactoring2) AbstractPyRefactoring.getPyRefactoring();
    if (req.qualifier != null && req.qualifier.trim().length() > 0) {
        try {
            final Map<Tuple<String, File>, HashSet<ASTEntry>> occurrences = r.findAllOccurrences(req);
            final Set<Entry<Tuple<String, File>, HashSet<ASTEntry>>> entrySet = occurrences.entrySet();
            final MultiTextEdit multiTextEdit = new MultiTextEdit();
            final IDocument document = req.getDoc();
            final Set<Integer> appliedContextLines = new HashSet<Integer>();
            for (Map.Entry<Tuple<String, File>, HashSet<ASTEntry>> o : entrySet) {
                HashSet<ASTEntry> entries = o.getValue();
                ASTEntry[] ordered = entries.toArray(new ASTEntry[0]);
                Arrays.sort(ordered, (entry0, entry1) -> {
                    // Note: order is reversed.
                    return Integer.compare(entry1.node.beginLine, entry0.node.beginLine);
                });
                for (ASTEntry entry : entries) {
                    if (entry.node != null) {
                        int beginLine = entry.node.beginLine;
                        int useLine = beginLine - 1;
                        if (useLine >= importHandleInfo.getStartLine() && useLine <= importHandleInfo.getEndLine()) {
                            // Skip the import itself.
                            continue;
                        }
                        String currLine = TextSelectionUtils.getLine(document, useLine);
                        if (!currLine.isEmpty() && !Character.isWhitespace(currLine.charAt(0))) {
                            // Skip global occurrences of the token
                            continue;
                        }
                        for (int i = useLine; i < document.getNumberOfLines(); i++) {
                            String line = TextSelectionUtils.getLine(document, i);
                            if (!line.trim().isEmpty()) {
                                if (Character.isWhitespace(line.charAt(0))) {
                                    useLine = i;
                                    break;
                                }
                            }
                        }
                        boolean addLocalImport = true;
                        boolean addLocalImportsOnTopOfMethod = true;
                        boolean groupImports = false;
                        int offset = new PySelection(req.ps.getDoc(), useLine, 0).getAbsoluteCursorOffset();
                        int maxCols = 200;
                        char trigger = ' ';
                        String fromImportStr = importHandleInfo.getFromImportStr();
                        String realImportRep;
                        if (fromImportStr == null || fromImportStr.isEmpty()) {
                            realImportRep = "import " + this.importedToken;
                        } else {
                            realImportRep = "from " + fromImportStr + " import " + this.importedToken;
                        }
                        int fReplacementOffset = offset;
                        int fLen = 0;
                        String indentString = "               ";
                        this.fReplacementString = "";
                        AddTokenAndImportStatement.ComputedInfo computedInfo = new AddTokenAndImportStatement.ComputedInfo(realImportRep, fReplacementOffset, fLen, indentString, fReplacementString, appliedWithTrigger, importLen, document);
                        this.appliedWithTrigger = computedInfo.appliedWithTrigger;
                        this.importLen = computedInfo.importLen;
                        AddTokenAndImportStatement t = new AddTokenAndImportStatement(document, trigger, offset, addLocalImport, addLocalImportsOnTopOfMethod, groupImports, maxCols);
                        LineStartingScope previousLineThatStartsScope = t.getPreviousLineThatStartsScope();
                        if (previousLineThatStartsScope != null) {
                            if (appliedContextLines.contains(previousLineThatStartsScope.iLineStartingScope)) {
                                continue;
                            }
                            appliedContextLines.add(previousLineThatStartsScope.iLineStartingScope);
                            t.createTextEdit(computedInfo);
                            for (ReplaceEdit edit : computedInfo.replaceEdit) {
                                multiTextEdit.addChild(edit);
                            }
                        }
                    }
                }
            }
            try {
                multiTextEdit.apply(document);
            } catch (Exception e) {
                Log.log(e);
            }
        } catch (OperationCanceledException | CoreException e) {
            Log.log(e);
        }
    }
}
Also used : RefactoringRequest(org.python.pydev.ast.refactoring.RefactoringRequest) AddTokenAndImportStatement(com.python.pydev.analysis.refactoring.quick_fixes.AddTokenAndImportStatement) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) IPyRefactoring2(org.python.pydev.ast.refactoring.IPyRefactoring2) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) Entry(java.util.Map.Entry) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) HashSet(java.util.HashSet) Point(org.eclipse.swt.graphics.Point) LineStartingScope(org.python.pydev.core.docutils.PySelection.LineStartingScope) CoreException(org.eclipse.core.runtime.CoreException) OperationCanceledException(org.eclipse.core.runtime.OperationCanceledException) CoreException(org.eclipse.core.runtime.CoreException) ReplaceEdit(org.eclipse.text.edits.ReplaceEdit) PySelection(org.python.pydev.core.docutils.PySelection) File(java.io.File) Map(java.util.Map) Tuple(org.python.pydev.shared_core.structure.Tuple) MultiTextEdit(org.eclipse.text.edits.MultiTextEdit) IDocument(org.eclipse.jface.text.IDocument)

Example 19 with ASTEntry

use of org.python.pydev.parser.visitors.scope.ASTEntry in project Pydev by fabioz.

the class PyRenameClassProcess method findReferencesOnOtherModule.

/**
 * This method is called for each module that may have some reference to the definition
 * we're looking for.
 */
@Override
protected List<ASTEntry> findReferencesOnOtherModule(RefactoringStatus status, RefactoringRequest request, String initialName, SourceModule module) {
    SimpleNode root = module.getAst();
    List<ASTEntry> entryOccurrences = ScopeAnalysis.getLocalOccurrences(initialName, root);
    entryOccurrences.addAll(ScopeAnalysis.getAttributeReferences(initialName, root));
    if (entryOccurrences.size() > 0) {
        // only add comments and strings if there's at least some other occurrence
        entryOccurrences.addAll(ScopeAnalysis.getCommentOccurrences(request.qualifier, root));
        entryOccurrences.addAll(ScopeAnalysis.getStringOccurrences(request.qualifier, root));
    }
    return entryOccurrences;
}
Also used : ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) SimpleNode(org.python.pydev.parser.jython.SimpleNode)

Example 20 with ASTEntry

use of org.python.pydev.parser.visitors.scope.ASTEntry in project Pydev by fabioz.

the class PyRenameFunctionProcess method getLocalOccurrences.

/**
 * This method is the method that should be used to get the occurrences in the same
 * module where the function is defined.
 *
 * @param occurencesFor the name of the function we're looking for
 * @param simpleNode the root of the module
 * @param status if we're unable to find the reference for the function definition in this module,
 * an error is added to this status.
 *
 * @return a list with the entries with the references (and definition) to the function searched.
 */
private List<ASTEntry> getLocalOccurrences(String occurencesFor, SimpleNode simpleNode, RefactoringStatus status) {
    List<ASTEntry> ret = new ArrayList<ASTEntry>();
    // get the entry for the function itself
    ASTEntry functionDefEntry = getOriginalFunctionInAst(simpleNode);
    if (functionDefEntry == null) {
        status.addFatalError("Unable to find the original definition for the function definition.");
        return ret;
    }
    if (functionDefEntry.parent != null) {
        // it has some parent
        final SimpleNode parentNode = functionDefEntry.parent.node;
        if (parentNode instanceof ClassDef) {
            // ok, we're in a class, the first thing is to add the reference to the function just gotten
            ret.add(new ASTEntry(functionDefEntry, ((FunctionDef) functionDefEntry.node).name));
            // get the entry for the self.xxx that access that attribute in the class
            SequencialASTIteratorVisitor classVisitor = SequencialASTIteratorVisitor.create(parentNode);
            Iterator<ASTEntry> it = classVisitor.getIterator(Attribute.class);
            while (it.hasNext()) {
                ASTEntry entry = it.next();
                List<SimpleNode> parts = NodeUtils.getAttributeParts((Attribute) entry.node);
                if (!(parts.get(1) instanceof Attribute)) {
                    final String rep0 = NodeUtils.getRepresentationString(parts.get(0));
                    final String rep1 = NodeUtils.getRepresentationString(parts.get(1));
                    if (rep0 != null && rep1 != null && rep0.equals("self") && rep1.equals(occurencesFor)) {
                        ret.add(entry);
                    }
                }
            }
            final List<ASTEntry> attributeReferences = ScopeAnalysis.getAttributeReferences(occurencesFor, simpleNode);
            NameTokType funcName = ((FunctionDef) functionDefEntry.node).name;
            for (ASTEntry entry : attributeReferences) {
                if (entry.node != funcName) {
                    if (entry.node instanceof NameTok) {
                        NameTok nameTok = (NameTok) entry.node;
                        if (nameTok.ctx == NameTok.ClassName) {
                            continue;
                        }
                    }
                    ret.add(entry);
                }
            }
        } else if (parentNode instanceof FunctionDef) {
            // get the references inside of the parent (this will include the function itself)
            ret.addAll(ScopeAnalysis.getLocalOccurrences(occurencesFor, parentNode));
        }
    } else {
        ret.addAll(ScopeAnalysis.getLocalOccurrences(occurencesFor, simpleNode));
    }
    if (ret.size() > 0) {
        // only add comments and strings if there's at least some other occurrence
        ret.addAll(ScopeAnalysis.getCommentOccurrences(occurencesFor, simpleNode));
        ret.addAll(ScopeAnalysis.getStringOccurrences(occurencesFor, simpleNode));
    }
    // get the references to Names that access that method in the same scope
    return ret;
}
Also used : NameTokType(org.python.pydev.parser.jython.ast.NameTokType) Attribute(org.python.pydev.parser.jython.ast.Attribute) ArrayList(java.util.ArrayList) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) SimpleNode(org.python.pydev.parser.jython.SimpleNode) ClassDef(org.python.pydev.parser.jython.ast.ClassDef) SequencialASTIteratorVisitor(org.python.pydev.parser.visitors.scope.SequencialASTIteratorVisitor) ASTEntry(org.python.pydev.parser.visitors.scope.ASTEntry) NameTok(org.python.pydev.parser.jython.ast.NameTok)

Aggregations

ASTEntry (org.python.pydev.parser.visitors.scope.ASTEntry)81 ArrayList (java.util.ArrayList)30 SimpleNode (org.python.pydev.parser.jython.SimpleNode)30 HashSet (java.util.HashSet)13 SequencialASTIteratorVisitor (org.python.pydev.parser.visitors.scope.SequencialASTIteratorVisitor)13 Tuple (org.python.pydev.shared_core.structure.Tuple)13 IToken (org.python.pydev.core.IToken)11 File (java.io.File)9 ClassDef (org.python.pydev.parser.jython.ast.ClassDef)9 FunctionDef (org.python.pydev.parser.jython.ast.FunctionDef)9 SourceToken (org.python.pydev.ast.codecompletion.revisited.modules.SourceToken)8 Str (org.python.pydev.parser.jython.ast.Str)8 CoreException (org.eclipse.core.runtime.CoreException)7 SourceModule (org.python.pydev.ast.codecompletion.revisited.modules.SourceModule)7 PySelection (org.python.pydev.core.docutils.PySelection)7 Name (org.python.pydev.parser.jython.ast.Name)7 Found (com.python.pydev.analysis.visitors.Found)6 HashMap (java.util.HashMap)6 List (java.util.List)6 Attribute (org.python.pydev.parser.jython.ast.Attribute)6