⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 nodeutils.java

📁 Python Development Environment (Python IDE plugin for Eclipse). Features editor, code completion, re
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    }

    
    public static int getColDefinition(SimpleNode ast2) {
        return getColDefinition(ast2, true);
    }
    
    /**
     * @param ast2 the node to work with
     * @return the column definition of a node
     */
    public static int getColDefinition(SimpleNode ast2, boolean always1ForImports) {
        if(ast2 instanceof Attribute){
            //if it is an attribute, we always have to move backward to the first defined token (Attribute.value)
            exprType value = ((Attribute)ast2).value;
            return getColDefinition(value);
        }
        
        //call and subscript are special cases, because they are not gotten directly (we have to go to the first
        //part of it (which in turn may be an attribute)
        else if(ast2 instanceof Call){
            Call c = (Call) ast2;
            return getColDefinition(c.func);
            
        } else if(ast2 instanceof Subscript){
            Subscript s = (Subscript) ast2;
            return getColDefinition(s.value);
            
        } else if(always1ForImports){
            if(ast2 instanceof Import || ast2 instanceof ImportFrom){
                return 1;
            }
        }
        return getClassOrFuncColDefinition(ast2);
    }


	public static int getClassOrFuncColDefinition(SimpleNode ast2) {
		if(ast2 instanceof ClassDef){
            ClassDef def = (ClassDef) ast2;
            return def.name.beginColumn;
        }
        if(ast2 instanceof FunctionDef){
            FunctionDef def = (FunctionDef) ast2;
            return def.name.beginColumn;
        }
        return ast2.beginColumn;
	}


    public static int[] getColLineEnd(SimpleNode v) {
    	return getColLineEnd(v, true);
    }

    /**
     * @param v the token to work with
     * @return a tuple with [line, col] of the definition of a token
     */
    public static int[] getColLineEnd(SimpleNode v, boolean getOnlyToFirstDot) {
        int lineEnd = getLineEnd(v);
        int col = 0;

        if(v instanceof Import || v instanceof ImportFrom){
            return new int[]{lineEnd, -1}; //col is -1... import is always full line
        }
        
        
        if(v instanceof Str){
            if(lineEnd == getLineDefinition(v)){
                String s = ((Str)v).s;
                col = getColDefinition(v) + s.length();
                return new int[]{lineEnd, col};
            }else{
                //it is another line...
                String s = ((Str)v).s;
                int i = s.lastIndexOf('\n');
                String sub = s.substring(i, s.length());
                
                col = sub.length();
                return new int[]{lineEnd, col};
            }
        }
        
        col = getEndColFromRepresentation(v, getOnlyToFirstDot);
        return new int[]{lineEnd, col};
    }

    /**
     * @param v
     * @return
     */
    private static int getEndColFromRepresentation(SimpleNode v, boolean getOnlyToFirstDot) {
        int col;
        String representationString = getFullRepresentationString(v);
        if(representationString == null){
            return -1;
        }
        
        if(getOnlyToFirstDot){
	        int i;
	        if((i = representationString.indexOf('.') )  != -1){
	            representationString = representationString.substring(0,i);
	        }
        }
        
        int colDefinition = getColDefinition(v);
        if(colDefinition == -1){
            return -1;
        }
        
        col = colDefinition + representationString.length();
        return col;
    }
    
    public static int getLineEnd(SimpleNode v) {
        if(v instanceof ImportFrom){
            ImportFrom f = (ImportFrom) v;
            FindLastLineVisitor findLastLineVisitor = new FindLastLineVisitor();
            try {
                f.accept(findLastLineVisitor);
                SimpleNode lastNode = findLastLineVisitor.getLastNode();
                SpecialStr lastSpecialStr = findLastLineVisitor.getLastSpecialStr();
                if(lastSpecialStr != null && lastSpecialStr.str.equals(")")){
                    //it was an from xxx import (euheon, utehon)
                    return lastSpecialStr.beginLine;
                }else{
                    return lastNode.beginLine;
                }
            } catch (Exception e) {
                Log.log(e);
            }
        }
        if(v instanceof Import){
            Import f = (Import) v;
            FindLastLineVisitor findLastLineVisitor = new FindLastLineVisitor();
            try {
                f.accept(findLastLineVisitor);
                SimpleNode lastNode = findLastLineVisitor.getLastNode();
                return lastNode.beginLine;
            } catch (Exception e) {
                Log.log(e);
            }
        }
        if(v instanceof Str){
            String s = ((Str)v).s;
            int found = 0;
            for (int i = 0; i < s.length(); i++) {
     
                if(s.charAt(i) == '\n'){
                    found += 1;
                }
            }
            return getLineDefinition(v) + found;
        }
        return getLineDefinition(v);
    }

    /**
     * @return the builtin type (if any) for some token (e.g.: '' would return str, 1.0 would return float...
     */
    public static String getBuiltinType(String tok) {
        if(tok.endsWith("'") || tok.endsWith("\"")){
            //ok, we are getting code completion for a string.
            return "str";
            
            
        } else if(tok.endsWith("]") && tok.startsWith("[")){
            //ok, we are getting code completion for a list.
            return "list";
            
            
        } else if(tok.endsWith("}") && tok.startsWith("{")){
            //ok, we are getting code completion for a dict.
            return "dict";
            
        } else if(tok.endsWith(")") && tok.startsWith("(")){
            //ok, we are getting code completion for a tuple.
            return "tuple";
            
            
        } else {
            try {
                Integer.parseInt(tok);
                return "int";
            } catch (Exception e) { //ok, not parsed as int
            }
    
            try {
                Float.parseFloat(tok);
                return "float";
            } catch (Exception e) { //ok, not parsed as int
            }
        }
        
        return null;
    }

    public static String getNameFromNameTok(NameTok tok){
        return tok.id;
    }


    /**
     * Gets all the parts contained in some attribute in the right order (when we visit
     * some attribute, we have to get that in a backwards fashion, since the attribute
     * is only determined in the end of the token in the grammar)
     * 
     * @return a list with the attribute parts in its forward order, and not backward as presented
     * in the grammar.
     */
	public static List<SimpleNode> getAttributeParts(Attribute node) {
		ArrayList<SimpleNode> nodes = new ArrayList<SimpleNode>();
		
		nodes.add(node.attr);
		SimpleNode s = node.value;
		
		while(true){
			if(s instanceof Attribute){
				nodes.add(s);
				s = ((Attribute) s).value;
				
			}else if(s instanceof Call){
				nodes.add(s);
				s = ((Call) s).func;
				
			}else{
				nodes.add(s);
				break;
			}
		}
		
		Collections.reverse(nodes);
		
		return nodes;
	}


    /**
     * Gets the parent names for a class definition
     * 
     * @param onlyLastSegment determines whether we should return only the last segment if the name
     * of the parent resolves to a dotted name.
     */
    public static List<String> getParentNames(ClassDef def, boolean onlyLastSegment) {
        ArrayList<String> ret = new ArrayList<String>();
        for(exprType base: def.bases){
            String rep = getFullRepresentationString(base);
            if(onlyLastSegment){
                rep = FullRepIterable.getLastPart(rep);
            }
            ret.add(rep);
        }
        return ret;
    }


    /**
     * @return true if the node is an import node (and false otherwise).
     */
	public static boolean isImport(SimpleNode ast) {
        if(ast instanceof Import || ast instanceof ImportFrom){
            return true;
        }
        return false;
	}


	public static NameTok getNameForAlias(aliasType t) {
		if(t.asname != null){
			return (NameTok) t.asname;
		}else{
			return (NameTok) t.name;
		}
	}


	public static NameTok getNameForRep(aliasType[] names, String representation) {
		for (aliasType name : names) {
			NameTok nameForAlias = getNameForAlias(name);
			String aliasRep = NodeUtils.getRepresentationString(nameForAlias);
			if(representation.equals(aliasRep)){
				return nameForAlias;
			}
		}
		return null;
	}


    /**
     * @param lineNumber the line we want to get the context from (starts at 0)
     * @param ast the ast that corresponds to our context
     * @return the full name for the context where we are (in the format Class.method.xxx.xxx)
     */
    public static String getContextName(int lineNumber, SimpleNode ast) {
        if(ast != null){
            EasyASTIteratorVisitor visitor = EasyASTIteratorVisitor.create(ast);
            Iterator<ASTEntry> classesAndMethodsIterator = visitor.getClassesAndMethodsIterator();
            ASTEntry last = null;
            while (classesAndMethodsIterator.hasNext()) {
                ASTEntry entry = classesAndMethodsIterator.next();
                if(entry.node.beginLine > lineNumber+1){
                    //ok, now, let's find out which context actually contains it...
                    break;
                }                
                last = entry;
            }
            
            while(last != null && last.endLine <= lineNumber){
                last = last.parent;
            }
            
            if(last != null){
    
                StringBuffer buffer = new StringBuffer();
                boolean first = true;
                while (last != null){
                    String name = last.getName();
                    buffer.insert(0, name);
                    last = last.parent;
                    if(!first){
                        buffer.insert(name.length(),".");
                    }
                    first = false;
                }
                return buffer.toString();
            }
        }
    	return null;
    }

    
    protected static final String[] strTypes = new String[]{
        "'''",
        "\"\"\"",
        "'",
        "\""
    };

    public static String getStringToPrint(Str node){
        StringBuffer buffer = new StringBuffer();
        if(node.unicode){
            buffer.append("u");
        }
        if(node.raw){
            buffer.append("r");
        }
        final String s = strTypes[node.type-1];
        
        buffer.append(s);
        buffer.append(node.s);
        buffer.append(s);
        return buffer.toString();
    }


    /**
     * @param node the if node that we want to check.
     * @return null if the passed node is not 
     */
    public static boolean isIfMAinNode(If node) {
        if (node.test instanceof Compare) {
    		Compare compareNode = (Compare)node.test;
    		// handcrafted structure walking
    		if (compareNode.left instanceof Name 
    			&& ((Name)compareNode.left).id.equals("__name__")
    			&& compareNode.ops != null
    			&& compareNode.ops.length == 1 
    			&& compareNode.ops[0] == Compare.Eq){
                
    		    if ( compareNode.comparators != null
        			&& compareNode.comparators.length == 1
        			&& compareNode.comparators[0] instanceof Str 
        			&& ((Str)compareNode.comparators[0]).s.equals("__main__")){
        			return true;
                }
    		}
    	}
        return false;
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -