Search in sources :

Example 6 with FunctionDef

use of org.python.pydev.parser.jython.ast.FunctionDef in project Pydev by fabioz.

the class NoSelfChecker method beforeFunctionDef.

/**
 * when a class is declared inside a function scope, it must start with self if it does
 * not start with the self parameter, unless it has a staticmethod decoration or is
 * later assigned to a staticmethod.
 *
 * @param node
 */
public void beforeFunctionDef(FunctionDef node) {
    if (scope.peek().equals(Scope.SCOPE_TYPE_CLASS)) {
        // let's check if we have to start with self or cls
        boolean startsWithSelf = false;
        boolean startsWithCls = false;
        String received = "";
        if (node.args != null) {
            if (node.args.args.length > 0) {
                exprType arg = node.args.args[0];
                if (arg instanceof Name) {
                    Name n = (Name) arg;
                    if (n.id.equals("self")) {
                        startsWithSelf = true;
                    } else if (n.id.equals("cls")) {
                        startsWithCls = true;
                    }
                    received = n.id;
                }
            }
        }
        boolean isStaticMethod = false;
        boolean isClassMethod = false;
        if (node.decs != null) {
            for (decoratorsType dec : node.decs) {
                if (dec != null) {
                    String rep = NodeUtils.getRepresentationString(dec.func);
                    if (rep != null) {
                        if (rep.equals("staticmethod")) {
                            isStaticMethod = true;
                        } else if (rep.equals("classmethod")) {
                            isClassMethod = true;
                        }
                    }
                }
            }
        }
        ZopeInterfaceComputer zopeInterfaceComputer = zopeInterfaceComputers.peek();
        // didn't have staticmethod decorator either
        String rep = NodeUtils.getRepresentationString(node);
        if (rep.equals("__new__")) {
            // __new__ could start wit cls or self
            if (!startsWithCls && !startsWithSelf) {
                if (!zopeInterfaceComputer.isZopeInterface()) {
                    // zope check is more expensive, so, do as the last thing.
                    maybeNoSelfDefinedItems.peek().put(rep, new Tuple<Expected, FunctionDef>(new Expected("self or cls", received), node));
                }
            }
        } else if (!startsWithSelf && !startsWithCls && !isStaticMethod && !isClassMethod) {
            if (!zopeInterfaceComputer.isZopeInterface()) {
                // zope check is more expensive, so, do as the last thing.
                maybeNoSelfDefinedItems.peek().put(rep, new Tuple<Expected, FunctionDef>(new Expected("self", received), node));
            }
        } else if (startsWithCls && !isClassMethod && !isStaticMethod) {
            String classBase = classBases.peek();
            if (rep.equals("__init__") && "type".equals(classBase)) {
            // ok, in this case, cls is expected
            } else {
                if (!zopeInterfaceComputer.isZopeInterface()) {
                    // zope check is more expensive, so, do as the last thing.
                    maybeNoSelfDefinedItems.peek().put(rep, new Tuple<Expected, FunctionDef>(new Expected("self", received), node));
                }
            }
        }
    }
    scope.push(Scope.SCOPE_TYPE_METHOD);
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) org.python.pydev.parser.jython.ast.decoratorsType(org.python.pydev.parser.jython.ast.decoratorsType) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) Tuple(org.python.pydev.shared_core.structure.Tuple) Name(org.python.pydev.parser.jython.ast.Name)

Example 7 with FunctionDef

use of org.python.pydev.parser.jython.ast.FunctionDef in project Pydev by fabioz.

the class PyRefactoringFindDefinition method findActualTokenFromImportFromDefinition.

/**
 * Given some definition, find its actual token (if that's possible)
 * @param request the original request
 * @param tok the token we're looking for
 * @param lFindInfo place to store info
 * @param selected place to add the new definition (if found)
 * @param d the definition found before (this function will only work if this definition
 * @param completionCache all completions found previously
 * @param searchForMethodParameterFromParticipants find definition for method parameters
 * maps to an ImportFrom)
 *
 * @return true if we found a new definition (and false otherwise)
 * @throws Exception
 */
private static boolean findActualTokenFromImportFromDefinition(IPythonNature nature, String tok, List<IDefinition> selected, Definition d, ICompletionState completionCache, boolean searchForMethodParameterFromParticipants) throws Exception {
    boolean didFindNewDef = false;
    Set<Tuple3<String, Integer, Integer>> whereWePassed = new HashSet<Tuple3<String, Integer, Integer>>();
    // in an import..from, the last part will always be the token imported
    tok = FullRepIterable.getLastPart(tok);
    if (searchForMethodParameterFromParticipants) {
        if (d.ast instanceof Name) {
            Name name = (Name) d.ast;
            if (name.ctx == Name.Param) {
                if (d.scope != null && !d.scope.getScopeStack().empty()) {
                    Object peek = d.scope.getScopeStack().peek();
                    if (peek instanceof FunctionDef) {
                        IDefinition found = CompletionParticipantsHelper.findDefinitionForMethodParameterFromParticipants(d, nature, completionCache);
                        if (found != null) {
                            selected.add(found);
                            return true;
                        }
                    }
                }
            }
        }
    }
    while (d.ast instanceof ImportFrom) {
        IDefinition[] found = followDefinition(d, whereWePassed, tok, nature, completionCache);
        if (found != null && found.length == 1) {
            Tuple3<String, Integer, Integer> tupFromDefinition = getTupFromDefinition((Definition) found[0]);
            if (tupFromDefinition == null) {
                break;
            }
            didFindNewDef = true;
            d = (Definition) found[0];
        } else {
            break;
        }
    }
    if (didFindNewDef) {
        selected.add(d);
    }
    return didFindNewDef;
}
Also used : FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) IDefinition(org.python.pydev.core.IDefinition) Name(org.python.pydev.parser.jython.ast.Name) Tuple3(org.python.pydev.shared_core.structure.Tuple3) ImportFrom(org.python.pydev.parser.jython.ast.ImportFrom) HashSet(java.util.HashSet)

Example 8 with FunctionDef

use of org.python.pydev.parser.jython.ast.FunctionDef in project Pydev by fabioz.

the class FastDefinitionsParser method endScopesInStack.

private void endScopesInStack(int currLogicalCol) {
    while (stack.size() > 0) {
        NodeEntry peek = stack.peek();
        if (peek.logicalColumn < currLogicalCol) {
            break;
        }
        NodeEntry currNode = stack.pop();
        currNode.onEndScope();
        if (stack.size() > 0) {
            NodeEntry parentNode = stack.peek();
            if (parentNode.node instanceof FunctionDef) {
                // Inside a function def, only deal with attributes (if func inside class)
                if (currNode.node instanceof Assign) {
                    if (stack.size() > 1) {
                        Assign assign = (Assign) currNode.node;
                        exprType target = assign.targets[0];
                        if (target instanceof Attribute) {
                            NodeEntry parentParents = stack.peek(1);
                            if (parentParents.node instanceof ClassDef) {
                                parentNode.body.add(currNode.node);
                            }
                        }
                    }
                }
            } else if (parentNode.node instanceof ClassDef) {
                parentNode.body.add(currNode.node);
            } else {
                String msg = "Did not expect to find item below node: " + parentNode.node + " (module: " + this.moduleName + " file: " + this.file + " row: " + row + ").";
                if (throwErrorOnWarnings) {
                    throw new RuntimeException(msg);
                } else {
                    Log.log(msg);
                }
            }
        } else {
            body.add(currNode.node);
        }
    }
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) ClassDef(org.python.pydev.parser.jython.ast.ClassDef) Attribute(org.python.pydev.parser.jython.ast.Attribute) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) Assign(org.python.pydev.parser.jython.ast.Assign)

Example 9 with FunctionDef

use of org.python.pydev.parser.jython.ast.FunctionDef in project Pydev by fabioz.

the class FastParser method createFunctionDef.

private FunctionDef createFunctionDef(int lastReturnedLine, NameTok nameTok, int matchedCol) {
    argumentsType args;
    if (cythonParse) {
        Name name = new Name("self", Name.Store, false);
        exprType[] selfExprType = new exprType[] { name };
        name.beginLine = lastReturnedLine + 1;
        // 4 for 'def ' and 1 for '('
        name.beginColumn = matchedCol + 1 + 4 + 1 + nameTok.id.length();
        args = new argumentsType(selfExprType, null, null, EMTPY_EXPR_TYPE, null, null, null, null, null, null);
    } else {
        args = new argumentsType(EMTPY_EXPR_TYPE, null, null, EMTPY_EXPR_TYPE, null, null, null, null, null, null);
    }
    FunctionDef functionDef = new FunctionDef(nameTok, args, EMTPY_STMT_TYPE, EMTPY_DECORATORS_TYPE, null, false);
    functionDef.beginLine = lastReturnedLine + 1;
    functionDef.beginColumn = matchedCol + 1;
    return functionDef;
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) org.python.pydev.parser.jython.ast.argumentsType(org.python.pydev.parser.jython.ast.argumentsType) Name(org.python.pydev.parser.jython.ast.Name)

Example 10 with FunctionDef

use of org.python.pydev.parser.jython.ast.FunctionDef in project Pydev by fabioz.

the class NodeUtils method getRepresentationString.

/**
 * @param node this is the node from whom we want to get the representation
 * @return A suitable String representation for some node.
 */
public static String getRepresentationString(SimpleNode node, boolean useTypeRepr) {
    if (node instanceof NameTok) {
        NameTok tok = (NameTok) node;
        return tok.id;
    }
    if (node instanceof Name) {
        Name name = (Name) node;
        return name.id;
    }
    if (node instanceof aliasType) {
        aliasType type = (aliasType) node;
        return ((NameTok) type.name).id;
    }
    if (node instanceof Attribute) {
        Attribute attribute = (Attribute) node;
        return discoverRep(attribute.attr);
    }
    if (node instanceof keywordType) {
        keywordType type = (keywordType) node;
        return discoverRep(type.arg);
    }
    if (node instanceof ClassDef) {
        ClassDef def = (ClassDef) node;
        return ((NameTok) def.name).id;
    }
    if (node instanceof FunctionDef) {
        FunctionDef def = (FunctionDef) node;
        return ((NameTok) def.name).id;
    }
    if (node instanceof Call) {
        Call call = ((Call) node);
        return getRepresentationString(call.func, useTypeRepr);
    }
    if (node instanceof org.python.pydev.parser.jython.ast.List || node instanceof ListComp) {
        String val = "[]";
        if (useTypeRepr) {
            val = getBuiltinType(val);
        }
        return val;
    }
    if (node instanceof org.python.pydev.parser.jython.ast.Dict || node instanceof org.python.pydev.parser.jython.ast.DictComp) {
        String val = "{}";
        if (useTypeRepr) {
            val = getBuiltinType(val);
        }
        return val;
    }
    if (node instanceof BinOp) {
        BinOp binOp = (BinOp) node;
        if (binOp.left instanceof Str && binOp.op == BinOp.Mod) {
            node = binOp.left;
        // Just change the node... the check below will work with the Str already.
        }
    }
    if (node instanceof Str) {
        String val;
        if (useTypeRepr) {
            val = getBuiltinType("''");
        } else {
            val = "'" + ((Str) node).s + "'";
        }
        return val;
    }
    if (node instanceof Tuple) {
        StringBuffer buf = new StringBuffer();
        Tuple t = (Tuple) node;
        for (exprType e : t.elts) {
            buf.append(getRepresentationString(e, useTypeRepr));
            buf.append(", ");
        }
        if (t.elts.length > 0) {
            int l = buf.length();
            buf.deleteCharAt(l - 1);
            buf.deleteCharAt(l - 2);
        }
        String val = "(" + buf + ")";
        if (useTypeRepr) {
            val = getBuiltinType(val);
        }
        return val;
    }
    if (node instanceof Num) {
        String val = ((Num) node).n.toString();
        if (useTypeRepr) {
            val = getBuiltinType(val);
        }
        return val;
    }
    if (node instanceof Import) {
        aliasType[] names = ((Import) node).names;
        for (aliasType n : names) {
            if (n.asname != null) {
                return ((NameTok) n.asname).id;
            }
            return ((NameTok) n.name).id;
        }
    }
    if (node instanceof commentType) {
        commentType type = (commentType) node;
        return type.id;
    }
    if (node instanceof excepthandlerType) {
        excepthandlerType type = (excepthandlerType) node;
        return type.name.toString();
    }
    return null;
}
Also used : org.python.pydev.parser.jython.ast.exprType(org.python.pydev.parser.jython.ast.exprType) Import(org.python.pydev.parser.jython.ast.Import) Attribute(org.python.pydev.parser.jython.ast.Attribute) FunctionDef(org.python.pydev.parser.jython.ast.FunctionDef) DictComp(org.python.pydev.parser.jython.ast.DictComp) Name(org.python.pydev.parser.jython.ast.Name) Str(org.python.pydev.parser.jython.ast.Str) ISpecialStr(org.python.pydev.parser.jython.ISpecialStr) ClassDef(org.python.pydev.parser.jython.ast.ClassDef) org.python.pydev.parser.jython.ast.commentType(org.python.pydev.parser.jython.ast.commentType) org.python.pydev.parser.jython.ast.keywordType(org.python.pydev.parser.jython.ast.keywordType) Call(org.python.pydev.parser.jython.ast.Call) Dict(org.python.pydev.parser.jython.ast.Dict) Num(org.python.pydev.parser.jython.ast.Num) ListComp(org.python.pydev.parser.jython.ast.ListComp) FastStringBuffer(org.python.pydev.shared_core.string.FastStringBuffer) org.python.pydev.parser.jython.ast.aliasType(org.python.pydev.parser.jython.ast.aliasType) org.python.pydev.parser.jython.ast.excepthandlerType(org.python.pydev.parser.jython.ast.excepthandlerType) BinOp(org.python.pydev.parser.jython.ast.BinOp) NameTok(org.python.pydev.parser.jython.ast.NameTok) Tuple(org.python.pydev.parser.jython.ast.Tuple)

Aggregations

FunctionDef (org.python.pydev.parser.jython.ast.FunctionDef)137 ClassDef (org.python.pydev.parser.jython.ast.ClassDef)63 Module (org.python.pydev.parser.jython.ast.Module)44 SimpleNode (org.python.pydev.parser.jython.SimpleNode)36 NameTok (org.python.pydev.parser.jython.ast.NameTok)30 ArrayList (java.util.ArrayList)27 org.python.pydev.parser.jython.ast.stmtType (org.python.pydev.parser.jython.ast.stmtType)27 org.python.pydev.parser.jython.ast.exprType (org.python.pydev.parser.jython.ast.exprType)26 Name (org.python.pydev.parser.jython.ast.Name)25 Assign (org.python.pydev.parser.jython.ast.Assign)17 org.python.pydev.parser.jython.ast.argumentsType (org.python.pydev.parser.jython.ast.argumentsType)17 Attribute (org.python.pydev.parser.jython.ast.Attribute)15 Call (org.python.pydev.parser.jython.ast.Call)14 SourceToken (org.python.pydev.ast.codecompletion.revisited.modules.SourceToken)13 Expr (org.python.pydev.parser.jython.ast.Expr)13 Return (org.python.pydev.parser.jython.ast.Return)12 AdapterPrefs (org.python.pydev.parser.jython.ast.factory.AdapterPrefs)12 PyAstFactory (org.python.pydev.parser.jython.ast.factory.PyAstFactory)12 TokensList (org.python.pydev.core.TokensList)10 Yield (org.python.pydev.parser.jython.ast.Yield)10