treemaker.java

来自「是一款用JAVA 编写的编译器 具有很强的编译功能」· Java 代码 · 共 892 行 · 第 1/2 页

JAVA
892
字号
        return tree;    }    public JCAnnotation Annotation(JCTree annotationType, List<JCExpression> args) {        JCAnnotation tree = new JCAnnotation(annotationType, args);        tree.pos = pos;        return tree;    }    public JCModifiers Modifiers(long flags, List<JCAnnotation> annotations) {        JCModifiers tree = new JCModifiers(flags, annotations);        boolean noFlags = (flags & Flags.StandardFlags) == 0;        tree.pos = (noFlags && annotations.isEmpty()) ? Position.NOPOS : pos;        return tree;    }    public JCModifiers Modifiers(long flags) {        return Modifiers(flags, List.<JCAnnotation>nil());    }    public JCErroneous Erroneous() {        return Erroneous(List.<JCTree>nil());    }    public JCErroneous Erroneous(List<? extends JCTree> errs) {        JCErroneous tree = new JCErroneous(errs);        tree.pos = pos;        return tree;    }    public LetExpr LetExpr(List<JCVariableDecl> defs, JCTree expr) {        LetExpr tree = new LetExpr(defs, expr);        tree.pos = pos;        return tree;    }/* *************************************************************************** * Derived building blocks. ****************************************************************************/    public JCClassDecl AnonymousClassDef(JCModifiers mods,					 List<JCTree> defs)    {	return ClassDef(mods,			names.empty,			List.<JCTypeParameter>nil(),			null,			List.<JCExpression>nil(),			defs);    }    public LetExpr LetExpr(JCVariableDecl def, JCTree expr) {        LetExpr tree = new LetExpr(List.of(def), expr);        tree.pos = pos;        return tree;    }    /** Create an identifier from a symbol.     */    public JCIdent Ident(Symbol sym) {        return (JCIdent)new JCIdent((sym.name != names.empty)				? sym.name				: sym.flatName(), sym)            .setPos(pos)            .setType(sym.type);    }    /** Create a selection node from a qualifier tree and a symbol.     *  @param base   The qualifier tree.     */    public JCExpression Select(JCExpression base, Symbol sym) {        return new JCFieldAccess(base, sym.name, sym).setPos(pos).setType(sym.type);    }    /** Create a qualified identifier from a symbol, adding enough qualifications     *  to make the reference unique.     */    public JCExpression QualIdent(Symbol sym) {        return isUnqualifiable(sym)            ? Ident(sym)            : Select(QualIdent(sym.owner), sym);    }    /** Create an identifier that refers to the variable declared in given variable     *  declaration.     */    public JCExpression Ident(JCVariableDecl param) {        return Ident(param.sym);    }    /** Create a list of identifiers referring to the variables declared     *  in given list of variable declarations.     */    public List<JCExpression> Idents(List<JCVariableDecl> params) {        ListBuffer<JCExpression> ids = new ListBuffer<JCExpression>();        for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail)            ids.append(Ident(l.head));        return ids.toList();    }    /** Create a tree representing `this', given its type.     */    public JCExpression This(Type t) {        return Ident(new VarSymbol(FINAL, names._this, t, t.tsym));    }    /** Create a tree representing a class literal.     */    public JCExpression ClassLiteral(ClassSymbol clazz) {        return ClassLiteral(clazz.type);    }    /** Create a tree representing a class literal.     */    public JCExpression ClassLiteral(Type t) {        VarSymbol lit = new VarSymbol(STATIC | PUBLIC | FINAL,                                      names._class,                                      t,                                      t.tsym);        return Select(Type(t), lit);    }    /** Create a tree representing `super', given its type and owner.     */    public JCIdent Super(Type t, TypeSymbol owner) {        return Ident(new VarSymbol(FINAL, names._super, t, owner));    }    /**     * Create a method invocation from a method tree and a list of     * argument trees.     */    public JCMethodInvocation App(JCExpression meth, List<JCExpression> args) {        return Apply(null, meth, args).setType(meth.type.getReturnType());    }    /**     * Create a no-arg method invocation from a method tree     */    public JCMethodInvocation App(JCExpression meth) {        return Apply(null, meth, List.<JCExpression>nil()).setType(meth.type.getReturnType());    }    /** Create a method invocation from a method tree and a list of argument trees.     */    public JCExpression Create(Symbol ctor, List<JCExpression> args) {        Type t = ctor.owner.erasure(types);        JCNewClass newclass = NewClass(null, null, Type(t), args, null);        newclass.constructor = ctor;        newclass.setType(t);        return newclass;    }    /** Create a tree representing given type.     */    public JCExpression Type(Type t) {        if (t == null) return null;        JCExpression tp;        switch (t.tag) {        case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:        case DOUBLE: case BOOLEAN: case VOID:            tp = TypeIdent(t.tag);            break;        case TYPEVAR:            tp = Ident(t.tsym);            break;        case WILDCARD: {            WildcardType a = ((WildcardType) t);            tp = Wildcard(TypeBoundKind(a.kind), Type(a.type));            break;        }        case CLASS:            Type outer = t.getEnclosingType();            JCExpression clazz = outer.tag == CLASS && t.tsym.owner.kind == TYP                ? Select(Type(outer), t.tsym)                : QualIdent(t.tsym);            tp = t.getTypeArguments().isEmpty()                ? clazz                : TypeApply(clazz, Types(t.getTypeArguments()));            break;        case ARRAY:            tp = TypeArray(Type(types.elemtype(t)));            break;        case ERROR:            tp = TypeIdent(ERROR);            break;        default:            throw new AssertionError("unexpected type: " + t);        }        return tp.setType(t);    }//where        private JCExpression Selectors(JCExpression base, Symbol sym, Symbol limit) {            if (sym == limit) return base;            else return Select(Selectors(base, sym.owner, limit), sym);        }    /** Create a list of trees representing given list of types.     */    public List<JCExpression> Types(List<Type> ts) {        ListBuffer<JCExpression> types = new ListBuffer<JCExpression>();        for (List<Type> l = ts; l.nonEmpty(); l = l.tail)            types.append(Type(l.head));        return types.toList();    }    /** Create a variable definition from a variable symbol and an initializer     *  expression.     */    public JCVariableDecl VarDef(VarSymbol v, JCExpression init) {        return (JCVariableDecl)            new JCVariableDecl(                Modifiers(v.flags(), Annotations(v.getAnnotationMirrors())),                v.name,                Type(v.type),                init,                v).setPos(pos).setType(v.type);    }    /** Create annotation trees from annotations.     */    public List<JCAnnotation> Annotations(List<Attribute.Compound> attributes) {        if (attributes == null) return List.nil();        ListBuffer<JCAnnotation> result = new ListBuffer<JCAnnotation>();        for (List<Attribute.Compound> i = attributes; i.nonEmpty(); i=i.tail) {            Attribute a = i.head;            result.append(Annotation(a));        }        return result.toList();    }    public JCLiteral Literal(Object value) {        JCLiteral result = null;        if (value instanceof String) {            result = Literal(CLASS, value).                setType(syms.stringType.constType(value));        } else if (value instanceof Integer) {            result = Literal(INT, value).                setType(syms.intType.constType(value));        } else if (value instanceof Long) {            result = Literal(LONG, value).                setType(syms.longType.constType(value));        } else if (value instanceof Byte) {            result = Literal(BYTE, value).                setType(syms.byteType.constType(value));        } else if (value instanceof Character) {            result = Literal(CHAR, value).                setType(syms.charType.constType(value));        } else if (value instanceof Double) {            result = Literal(DOUBLE, value).                setType(syms.doubleType.constType(value));        } else if (value instanceof Float) {            result = Literal(FLOAT, value).                setType(syms.floatType.constType(value));        } else if (value instanceof Short) {            result = Literal(SHORT, value).                setType(syms.shortType.constType(value));        } else {            throw new AssertionError(value);        }        return result;    }    class AnnotationBuilder implements Attribute.Visitor {        JCExpression result = null;        public void visitConstant(Attribute.Constant v) {            result = Literal(v.value);        }        public void visitClass(Attribute.Class clazz) {            result = ClassLiteral(clazz.type).setType(syms.classType);        }        public void visitEnum(Attribute.Enum e) {            result = QualIdent(e.value);        }        public void visitError(Attribute.Error e) {            result = Erroneous();        }        public void visitCompound(Attribute.Compound compound) {            result = visitCompoundInternal(compound);        }        public JCAnnotation visitCompoundInternal(Attribute.Compound compound) {            ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();            for (List<Pair<Symbol.MethodSymbol,Attribute>> values = compound.values; values.nonEmpty(); values=values.tail) {                Pair<MethodSymbol,Attribute> pair = values.head;                JCExpression valueTree = translate(pair.snd);                args.append(Assign(Ident(pair.fst), valueTree).setType(valueTree.type));            }            return Annotation(Type(compound.type), args.toList());        }        public void visitArray(Attribute.Array array) {            ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>();            for (int i = 0; i < array.values.length; i++)                elems.append(translate(array.values[i]));            result = NewArray(null, List.<JCExpression>nil(), elems.toList()).setType(array.type);        }        JCExpression translate(Attribute a) {            a.accept(this);            return result;        }        JCAnnotation translate(Attribute.Compound a) {            return visitCompoundInternal(a);        }    }    AnnotationBuilder annotationBuilder = new AnnotationBuilder();    /** Create an annotation tree from an attribute.     */    public JCAnnotation Annotation(Attribute a) {        return annotationBuilder.translate((Attribute.Compound)a);    }    /** Create a method definition from a method symbol and a method body.     */    public JCMethodDecl MethodDef(MethodSymbol m, JCBlock body) {        return MethodDef(m, m.type, body);    }    /** Create a method definition from a method symbol, method type     *  and a method body.     */    public JCMethodDecl MethodDef(MethodSymbol m, Type mtype, JCBlock body) {        return (JCMethodDecl)            new JCMethodDecl(                Modifiers(m.flags(), Annotations(m.getAnnotationMirrors())),                m.name,                Type(mtype.getReturnType()),                TypeParams(mtype.getTypeArguments()),                Params(mtype.getParameterTypes(), m),                Types(mtype.getThrownTypes()),                body,                null,                m).setPos(pos).setType(mtype);    }    /** Create a type parameter tree from its name and type.     */    public JCTypeParameter TypeParam(Name name, TypeVar tvar) {        return (JCTypeParameter)            TypeParameter(name, Types(types.getBounds(tvar))).setPos(pos).setType(tvar);    }    /** Create a list of type parameter trees from a list of type variables.     */    public List<JCTypeParameter> TypeParams(List<Type> typarams) {        ListBuffer<JCTypeParameter> tparams = new ListBuffer<JCTypeParameter>();        int i = 0;        for (List<Type> l = typarams; l.nonEmpty(); l = l.tail)            tparams.append(TypeParam(l.head.tsym.name, (TypeVar)l.head));        return tparams.toList();    }    /** Create a value parameter tree from its name, type, and owner.     */    public JCVariableDecl Param(Name name, Type argtype, Symbol owner) {        return VarDef(new VarSymbol(0, name, argtype, owner), null);    }    /** Create a a list of value parameter trees x0, ..., xn from a list of     *  their types and an their owner.     */    public List<JCVariableDecl> Params(List<Type> argtypes, Symbol owner) {        ListBuffer<JCVariableDecl> params = new ListBuffer<JCVariableDecl>();        MethodSymbol mth = (owner.kind == MTH) ? ((MethodSymbol)owner) : null;        if (mth != null && mth.params != null && argtypes.length() == mth.params.length()) {            for (VarSymbol param : ((MethodSymbol)owner).params)                params.append(VarDef(param, null));        } else {            int i = 0;            for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail)                params.append(Param(paramName(i++), l.head, owner));        }        return params.toList();    }    /** Wrap a method invocation in an expression statement or return statement,     *  depending on whether the method invocation expression's type is void.     */    public JCStatement Call(JCExpression apply) {        return apply.type.tag == VOID ? Exec(apply) : Return(apply);    }    /** Construct an assignment from a variable symbol and a right hand side.     */    public JCStatement Assignment(Symbol v, JCExpression rhs) {        return Exec(Assign(Ident(v), rhs).setType(v.type));    }    /** Construct an index expression from a variable and an expression.     */    public JCArrayAccess Indexed(Symbol v, JCExpression index) {        JCArrayAccess tree = new JCArrayAccess(QualIdent(v), index);        tree.type = ((ArrayType)v.type).elemtype;        return tree;    }    /** Make an attributed type cast expression.     */    public JCTypeCast TypeCast(Type type, JCExpression expr) {        return (JCTypeCast)TypeCast(Type(type), expr).setType(type);    }/* *************************************************************************** * Helper methods. ****************************************************************************/    /** Can given symbol be referred to in unqualified form?     */    boolean isUnqualifiable(Symbol sym) {        if (sym.name == names.empty ||            sym.owner == null ||            sym.owner.kind == MTH || sym.owner.kind == VAR) {            return true;        } else if (sym.kind == TYP && toplevel != null) {            Scope.Entry e;            e = toplevel.namedImportScope.lookup(sym.name);            if (e.scope != null) {                return                  e.sym == sym &&                  e.next().scope == null;            }            e = toplevel.packge.members().lookup(sym.name);            if (e.scope != null) {                return                  e.sym == sym &&                  e.next().scope == null;            }            e = toplevel.starImportScope.lookup(sym.name);            if (e.scope != null) {                return                  e.sym == sym &&                  e.next().scope == null;            }        }        return false;    }    /** The name of synthetic parameter number `i'.     */    public Name paramName(int i)   { return names.fromString("x" + i); }    /** The name of synthetic type parameter number `i'.     */    public Name typaramName(int i) { return names.fromString("A" + i); }}    

⌨️ 快捷键说明

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