Search in sources :

Example 11 with TypedKlass

use of jetbrick.template.parser.support.TypedKlass in project jetbrick-template-1x by subchen.

the class JetTemplateCodeVisitor method visitExpr_field_access.

@Override
public Code visitExpr_field_access(Expr_field_accessContext ctx) {
    SegmentCode code = (SegmentCode) ctx.expression().accept(this);
    String name = ctx.IDENTIFIER().getText();
    assert_not_null_constantContext(code.getNode());
    // 进行类型推导,找到方法的返回类型
    code = code.asBoxedSegmentCode();
    Class<?> beanClass = code.getKlass();
    Member member = null;
    if ((!beanClass.isArray()) || (!"length".equals(name))) {
        // not array.length
        member = resolver.resolveProperty(beanClass, name);
        if (member == null) {
            // reportError
            name = name.substring(0, 1).toUpperCase() + name.substring(1);
            StringBuilder err = new StringBuilder(128);
            err.append("The method ");
            err.append("get" + name);
            err.append("() or ");
            err.append("is" + name);
            err.append("() is undefined for the type ");
            err.append(beanClass.getName());
            err.append('.');
            if (Object.class.equals(beanClass)) {
                err.append("\n advise: ");
                if (code.getNode() instanceof Expr_identifierContext) {
                    err.append("Please use #define(type ");
                    err.append(code.getNode().getText());
                    err.append(") to define variable type.");
                } else {
                    err.append("Please use #set(type xxx = ");
                    err.append(code.getNode().getText());
                    err.append(") to define expression type.");
                }
            }
            throw reportError(err.toString(), ctx.IDENTIFIER());
        }
    }
    boolean isSafeCall = globalSafeCall || "?.".equals(ctx.getChild(1).getText());
    // 生成code
    StringBuilder sb = new StringBuilder(64);
    TypedKlass resultKlass = null;
    if (member instanceof Method) {
        Method method = (Method) member;
        if (securityManager != null) {
            securityManager.checkMemberAccess(method);
        }
        // special code for Map.get()
        // https://github.com/subchen/jetbrick-template/issues/100
        TypedKlass typedKlass = code.getTypedKlass();
        if ("get".equals(method.getName()) && member.getDeclaringClass() == Map.class) {
            if (typedKlass.getTypeArgs().length >= 2) {
                resultKlass = typedKlass.getTypeArgs()[1];
            }
        }
        if (resultKlass == null) {
            resultKlass = TypedKlassUtils.getMethodReturnTypedKlass(method);
        }
        if (method.getParameterTypes().length == 0) {
            // getXXX() or isXXX()
            if (isSafeCall) {
                // 安全调用,防止 NullPointException
                boolean boxWhenSafeCall = false;
                if (resultKlass.isPrimitive()) {
                    boxWhenSafeCall = true;
                    resultKlass = resultKlass.asBoxedTypedKlass();
                }
                sb.append("((");
                sb.append(code.toString());
                sb.append("==null)?(");
                sb.append(resultKlass.getSource());
                sb.append(")null:");
                if (boxWhenSafeCall) {
                    sb.append(resultKlass.getSource()).append(".valueOf(");
                }
                sb.append(code.toString());
                sb.append('.');
                sb.append(method.getName());
                sb.append("()");
                if (boxWhenSafeCall) {
                    sb.append(')');
                }
                sb.append(')');
            } else {
                sb.append(code.toString());
                sb.append('.');
                sb.append(method.getName());
                sb.append("()");
            }
        } else {
            // get(String)
            if (isSafeCall) {
                // 安全调用,防止 NullPointException
                boolean boxWhenSafeCall = false;
                if (resultKlass.isPrimitive()) {
                    boxWhenSafeCall = true;
                    resultKlass = resultKlass.asBoxedTypedKlass();
                }
                sb.append("((");
                sb.append(code.toString());
                sb.append("==null)?(");
                sb.append(resultKlass.getSource());
                sb.append(")null:");
                if (boxWhenSafeCall) {
                    sb.append(resultKlass.getSource()).append(".valueOf(");
                }
                sb.append(code.toString());
                sb.append(".get(\"");
                sb.append(name);
                sb.append("\")");
                if (boxWhenSafeCall) {
                    sb.append(')');
                }
                sb.append(')');
            } else {
                sb.append(code.toString());
                sb.append(".get(\"");
                sb.append(name);
                sb.append("\")");
            }
        }
    } else {
        if (member instanceof Field) {
            if (securityManager != null) {
                securityManager.checkMemberAccess((Field) member);
            }
            resultKlass = TypedKlassUtils.getFieldTypedKlass((Field) member);
        } else {
            // array.length
            resultKlass = TypedKlass.create(Integer.TYPE);
        }
        if (isSafeCall) {
            // 安全调用,防止 NullPointException
            boolean boxWhenSafeCall = false;
            if (resultKlass.isPrimitive()) {
                boxWhenSafeCall = true;
                resultKlass = resultKlass.asBoxedTypedKlass();
            }
            sb.append("((");
            sb.append(code.toString());
            sb.append("==null)?(");
            sb.append(resultKlass.getSource());
            sb.append(")null:");
            if (boxWhenSafeCall) {
                sb.append(resultKlass.getSource()).append(".valueOf(");
            }
            sb.append(code.toString());
            sb.append('.');
            sb.append(name);
            if (boxWhenSafeCall) {
                sb.append(')');
            }
            sb.append(')');
        } else {
            sb.append(code.toString());
            sb.append('.');
            sb.append(name);
        }
    }
    return new SegmentCode(resultKlass, sb.toString(), ctx);
}
Also used : Field(java.lang.reflect.Field) TypedKlass(jetbrick.template.parser.support.TypedKlass) SegmentCode(jetbrick.template.parser.code.SegmentCode) Method(java.lang.reflect.Method) Member(java.lang.reflect.Member) Map(java.util.Map) HashMap(java.util.HashMap) Expr_identifierContext(jetbrick.template.parser.grammer.JetTemplateParser.Expr_identifierContext)

Example 12 with TypedKlass

use of jetbrick.template.parser.support.TypedKlass in project jetbrick-template-1x by subchen.

the class JetTemplateCodeVisitor method visitFor_expression.

@Override
public Code visitFor_expression(For_expressionContext ctx) {
    String name = ctx.IDENTIFIER().getText();
    SegmentCode code = (SegmentCode) ctx.expression().accept(this);
    assert_not_void_expression(code);
    TypedKlass resultKlass = null;
    TypeContext type = ctx.type();
    if (type != null) {
        // 手动定义返回变量的类型
        SegmentCode c = (SegmentCode) type.accept(this);
        resultKlass = c.getTypedKlass();
    } else {
        // 根据 expression 来进行自动类型推导
        Class<?> rhsKlass = code.getKlass();
        if (rhsKlass.isArray()) {
            resultKlass = TypedKlass.create(rhsKlass.getComponentType(), code.getTypeArgs());
        } else if (Map.class.isAssignableFrom(rhsKlass)) {
            resultKlass = TypedKlass.create(Map.Entry.class, code.getTypeArgs());
        } else if (Collection.class.isAssignableFrom(rhsKlass)) {
            if (code.getTypeArgs() != null && code.getTypeArgs().length == 1) {
                resultKlass = code.getTypeArgs()[0];
            }
        }
    }
    if (resultKlass == null) {
        resultKlass = TypedKlass.Object;
    }
    // 必须是 Boxed 对象,因为需要强制类型转换 from iterator.next()
    resultKlass = resultKlass.asBoxedTypedKlass();
    if (!scopeCode.define(name, resultKlass)) {
        throw reportError("Duplicate local variable " + name, ctx.IDENTIFIER());
    }
    return new ForExpressionCode(resultKlass, name, code.toString(), ctx);
}
Also used : ForExpressionCode(jetbrick.template.parser.code.ForExpressionCode) TypedKlass(jetbrick.template.parser.support.TypedKlass) SegmentCode(jetbrick.template.parser.code.SegmentCode) TypeContext(jetbrick.template.parser.grammer.JetTemplateParser.TypeContext) Map(java.util.Map) HashMap(java.util.HashMap)

Example 13 with TypedKlass

use of jetbrick.template.parser.support.TypedKlass in project jetbrick-template-1x by subchen.

the class JetTemplateCodeVisitor method visitExpr_identifier.

@Override
public Code visitExpr_identifier(Expr_identifierContext ctx) {
    String name = assert_java_identifier(ctx.IDENTIFIER(), false);
    // 特殊处理 for 变量
    if ("for".equals(name)) {
        assert_inside_of_for_directive(ctx, "Local variable \"for\"");
        // 强制映射成 JetForStatus $for
        // 取出 forStatus 的实际变量名
        String forStatus = forStack.peek();
        return new SegmentCode(TypedKlass.JetForStatus, forStatus, ctx);
    }
    // 找到变量的类型
    TypedKlass resultKlass = scopeCode.resolve(name, false);
    if (resultKlass == null) {
        // 没有定义过,继续向上深度查找
        resultKlass = scopeCode.resolve(name, true);
        // 没有定义过,则查找全局定义
        if (resultKlass == null) {
            resultKlass = resolver.resolveVariable(name);
        }
        if (scopeCode.define(name, resultKlass, true)) {
            if (resultKlass == TypedKlass.Object) {
            //removed unsed warning in 1.2.0
            //log.warn("line " + ctx.getStart().getLine() + ": Implicit definition for context variable: " + resultKlass.toString() + " " + name);
            }
        }
    }
    return new SegmentCode(resultKlass, name, ctx);
}
Also used : TypedKlass(jetbrick.template.parser.support.TypedKlass) SegmentCode(jetbrick.template.parser.code.SegmentCode)

Aggregations

TypedKlass (jetbrick.template.parser.support.TypedKlass)13 SegmentCode (jetbrick.template.parser.code.SegmentCode)12 Method (java.lang.reflect.Method)4 SegmentListCode (jetbrick.template.parser.code.SegmentListCode)4 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Expression_listContext (jetbrick.template.parser.grammer.JetTemplateParser.Expression_listContext)3 Field (java.lang.reflect.Field)2 BlockCode (jetbrick.template.parser.code.BlockCode)2 ForExpressionCode (jetbrick.template.parser.code.ForExpressionCode)2 MacroCode (jetbrick.template.parser.code.MacroCode)2 Expr_identifierContext (jetbrick.template.parser.grammer.JetTemplateParser.Expr_identifierContext)2 TypeContext (jetbrick.template.parser.grammer.JetTemplateParser.TypeContext)2 Member (java.lang.reflect.Member)1 Code (jetbrick.template.parser.code.Code)1 DefineExpressionCode (jetbrick.template.parser.code.DefineExpressionCode)1 ScopeCode (jetbrick.template.parser.code.ScopeCode)1 TagCode (jetbrick.template.parser.code.TagCode)1 TemplateClassCode (jetbrick.template.parser.code.TemplateClassCode)1 TextCode (jetbrick.template.parser.code.TextCode)1