Example usage for org.eclipse.jdt.core.dom Expression resolveConstantExpressionValue

List of usage examples for org.eclipse.jdt.core.dom Expression resolveConstantExpressionValue

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.dom Expression resolveConstantExpressionValue.

Prototype

public final Object resolveConstantExpressionValue() 

Source Link

Document

Resolves and returns the compile-time constant expression value as specified in JLS2 15.28, if this expression has one.

Usage

From source file:astview.ASTViewContentProvider.java

License:Open Source License

private Object[] getNodeChildren(ASTNode node) {
    ArrayList<Object> res = new ArrayList<>();

    if (node instanceof Expression) {
        Expression expression = (Expression) node;
        ITypeBinding expressionTypeBinding = expression.resolveTypeBinding();
        res.add(createExpressionTypeBinding(node, expressionTypeBinding));

        // expressions:
        if (expression instanceof Name) {
            IBinding binding = ((Name) expression).resolveBinding();
            if (binding != expressionTypeBinding)
                res.add(createBinding(expression, binding));
        } else if (expression instanceof MethodInvocation) {
            MethodInvocation methodInvocation = (MethodInvocation) expression;
            IMethodBinding binding = methodInvocation.resolveMethodBinding();
            res.add(createBinding(expression, binding));
            String inferred = String.valueOf(methodInvocation.isResolvedTypeInferredFromExpectedType());
            res.add(new GeneralAttribute(expression, "ResolvedTypeInferredFromExpectedType", inferred)); //$NON-NLS-1$
        } else if (expression instanceof SuperMethodInvocation) {
            SuperMethodInvocation superMethodInvocation = (SuperMethodInvocation) expression;
            IMethodBinding binding = superMethodInvocation.resolveMethodBinding();
            res.add(createBinding(expression, binding));
            String inferred = String.valueOf(superMethodInvocation.isResolvedTypeInferredFromExpectedType());
            res.add(new GeneralAttribute(expression, "ResolvedTypeInferredFromExpectedType", inferred)); //$NON-NLS-1$
        } else if (expression instanceof ClassInstanceCreation) {
            ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression;
            IMethodBinding binding = classInstanceCreation.resolveConstructorBinding();
            res.add(createBinding(expression, binding));
            String inferred = String.valueOf(classInstanceCreation.isResolvedTypeInferredFromExpectedType());
            res.add(new GeneralAttribute(expression, "ResolvedTypeInferredFromExpectedType", inferred)); //$NON-NLS-1$
        } else if (expression instanceof FieldAccess) {
            IVariableBinding binding = ((FieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof SuperFieldAccess) {
            IVariableBinding binding = ((SuperFieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof Annotation) {
            IAnnotationBinding binding = ((Annotation) expression).resolveAnnotationBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof LambdaExpression) {
            ASTAttribute bindingAttribute;
            try {
                IMethodBinding binding = ((LambdaExpression) expression).resolveMethodBinding();
                bindingAttribute = createBinding(expression, binding);
            } catch (RuntimeException e) {
                bindingAttribute = new Error(res, ">binding: Error: " + e.getMessage(), e);
            }/*  w  w w  .  j a v  a  2s. c o  m*/
            res.add(bindingAttribute);
        } else if (expression instanceof MethodReference) {
            IMethodBinding binding = ((MethodReference) expression).resolveMethodBinding();
            res.add(createBinding(expression, binding));
        }
        // Expression attributes:
        res.add(new GeneralAttribute(expression,
                "Boxing: " + expression.resolveBoxing() + "; Unboxing: " + expression.resolveUnboxing())); //$NON-NLS-1$ //$NON-NLS-2$
        res.add(new GeneralAttribute(expression, "ConstantExpressionValue", //$NON-NLS-1$
                expression.resolveConstantExpressionValue()));

        // references:
    } else if (node instanceof ConstructorInvocation) {
        IMethodBinding binding = ((ConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof SuperConstructorInvocation) {
        IMethodBinding binding = ((SuperConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MethodRef) {
        IBinding binding = ((MethodRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberRef) {
        IBinding binding = ((MemberRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof Type) {
        IBinding binding = ((Type) node).resolveBinding();
        res.add(createBinding(node, binding));

        // declarations:
    } else if (node instanceof AbstractTypeDeclaration) {
        IBinding binding = ((AbstractTypeDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnnotationTypeMemberDeclaration) {
        IBinding binding = ((AnnotationTypeMemberDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof EnumConstantDeclaration) {
        IBinding binding = ((EnumConstantDeclaration) node).resolveVariable();
        res.add(createBinding(node, binding));
        IBinding binding2 = ((EnumConstantDeclaration) node).resolveConstructorBinding();
        res.add(createBinding(node, binding2));
    } else if (node instanceof MethodDeclaration) {
        IBinding binding = ((MethodDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof VariableDeclaration) {
        IBinding binding = ((VariableDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnonymousClassDeclaration) {
        IBinding binding = ((AnonymousClassDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof ImportDeclaration) {
        IBinding binding = ((ImportDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof PackageDeclaration) {
        IBinding binding = ((PackageDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof TypeParameter) {
        IBinding binding = ((TypeParameter) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberValuePair) {
        IBinding binding = ((MemberValuePair) node).resolveMemberValuePairBinding();
        res.add(createBinding(node, binding));
    }

    @SuppressWarnings("unchecked")
    List<StructuralPropertyDescriptor> list = node.structuralPropertiesForType();
    for (int i = 0; i < list.size(); i++) {
        StructuralPropertyDescriptor curr = list.get(i);
        res.add(new NodeProperty(node, curr));
    }

    return res.toArray();
}

From source file:coloredide.astview.ASTViewContentProvider.java

License:Open Source License

private Object[] getNodeChildren(ASTNode node) {
    ArrayList res = new ArrayList();

    if (node instanceof Expression) {
        Expression expression = (Expression) node;
        ITypeBinding expressionTypeBinding = expression.resolveTypeBinding();
        res.add(createExpressionTypeBinding(node, expressionTypeBinding));

        // expressions:
        if (expression instanceof Name) {
            IBinding binding = ((Name) expression).resolveBinding();
            if (binding != expressionTypeBinding)
                res.add(createBinding(expression, binding));
        } else if (expression instanceof MethodInvocation) {
            IMethodBinding binding = ((MethodInvocation) expression).resolveMethodBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof SuperMethodInvocation) {
            IMethodBinding binding = ((SuperMethodInvocation) expression).resolveMethodBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof ClassInstanceCreation) {
            IMethodBinding binding = ((ClassInstanceCreation) expression).resolveConstructorBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof FieldAccess) {
            IVariableBinding binding = ((FieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof SuperFieldAccess) {
            IVariableBinding binding = ((SuperFieldAccess) expression).resolveFieldBinding();
            res.add(createBinding(expression, binding));
        } else if (expression instanceof Annotation) {
            IAnnotationBinding binding = ((Annotation) expression).resolveAnnotationBinding();
            res.add(createBinding(expression, binding));
        }//from  w  ww  .ja  va 2s  .co  m
        // Expression attributes:
        res.add(new GeneralAttribute(expression,
                "Boxing: " + expression.resolveBoxing() + "; Unboxing: " + expression.resolveUnboxing())); //$NON-NLS-1$ //$NON-NLS-2$
        res.add(new GeneralAttribute(expression, "ConstantExpressionValue", //$NON-NLS-1$
                expression.resolveConstantExpressionValue()));

        // references:
    } else if (node instanceof ConstructorInvocation) {
        IMethodBinding binding = ((ConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof SuperConstructorInvocation) {
        IMethodBinding binding = ((SuperConstructorInvocation) node).resolveConstructorBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MethodRef) {
        IBinding binding = ((MethodRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberRef) {
        IBinding binding = ((MemberRef) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof Type) {
        IBinding binding = ((Type) node).resolveBinding();
        res.add(createBinding(node, binding));

        // declarations:
    } else if (node instanceof AbstractTypeDeclaration) {
        IBinding binding = ((AbstractTypeDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnnotationTypeMemberDeclaration) {
        IBinding binding = ((AnnotationTypeMemberDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof EnumConstantDeclaration) {
        IBinding binding = ((EnumConstantDeclaration) node).resolveVariable();
        res.add(createBinding(node, binding));
        IBinding binding2 = ((EnumConstantDeclaration) node).resolveConstructorBinding();
        res.add(createBinding(node, binding2));
    } else if (node instanceof MethodDeclaration) {
        IBinding binding = ((MethodDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof VariableDeclaration) {
        IBinding binding = ((VariableDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof AnonymousClassDeclaration) {
        IBinding binding = ((AnonymousClassDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof ImportDeclaration) {
        IBinding binding = ((ImportDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof PackageDeclaration) {
        IBinding binding = ((PackageDeclaration) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof TypeParameter) {
        IBinding binding = ((TypeParameter) node).resolveBinding();
        res.add(createBinding(node, binding));
    } else if (node instanceof MemberValuePair) {
        IBinding binding = ((MemberValuePair) node).resolveMemberValuePairBinding();
        res.add(createBinding(node, binding));
    }

    List list = node.structuralPropertiesForType();
    for (int i = 0; i < list.size(); i++) {
        StructuralPropertyDescriptor curr = (StructuralPropertyDescriptor) list.get(i);
        res.add(new NodeProperty(node, curr));
    }

    if (node instanceof CompilationUnit) {
        CompilationUnit root = (CompilationUnit) node;
        res.add(new JavaElement(root, root.getJavaElement()));
        res.add(new CommentsProperty(root));
        res.add(new ProblemsProperty(root));
    }

    return res.toArray();
}

From source file:com.google.devtools.j2cpp.gen.CppImplementationGenerator.java

License:Open Source License

private void printConstant(String name, Expression initializer) {
    Object constant = initializer.resolveConstantExpressionValue();
    String text = generateExpression(initializer);
    // non-constant initializers were already moved to static blocks
    assert constant != null;
    print("static ");
    if (constant instanceof String) {
        printf("NSString * %s = %s;\n", name, text);
    } else if (constant instanceof Boolean) {
        printf("BOOL %s = %s;\n;", name, ((Boolean) constant).booleanValue() ? "YES" : "NO");
    } else if (constant instanceof Character) {
        printf("unichar %s = %s;\n", name, text);
    } else {//ww w. j a  v a 2  s  .  c  o m
        assert constant instanceof Number;
        Number number = (Number) constant;
        if (constant instanceof Byte) {
            printf("char %s = %d;\n", name, number.byteValue());
        } else if (constant instanceof Double) {
            printf("double %s = %s;\n", name, text);
        } else if (constant instanceof Float) {
            printf("float %s = %s;\n", name, text);
        } else if (constant instanceof Integer) {
            printf("int %s = %s;\n", name, text);
        } else if (constant instanceof Long) {
            printf("long long %s = %s;\n", name, text);
        } else {
            printf("short %s = %d;\n", name, number.shortValue());
        }
    }
}

From source file:com.google.devtools.j2cpp.translate.Rewriter.java

License:Open Source License

@Override
public boolean visit(FieldDeclaration node) {
    int mods = node.getModifiers();
    if (Modifier.isStatic(mods)) {
        ASTNode parent = node.getParent();
        @SuppressWarnings("unchecked")
        List<BodyDeclaration> classMembers = parent instanceof AbstractTypeDeclaration
                ? ((AbstractTypeDeclaration) parent).bodyDeclarations()
                : ((AnonymousClassDeclaration) parent).bodyDeclarations(); // safe by specification
        int indexOfNewMember = classMembers.indexOf(node) + 1;

        @SuppressWarnings("unchecked")
        List<VariableDeclarationFragment> fragments = node.fragments(); // safe by specification
        for (VariableDeclarationFragment var : fragments) {
            IVariableBinding binding = Types.getVariableBinding(var);
            if (Types.isPrimitiveConstant(binding) && Modifier.isPrivate(binding.getModifiers())) {
                // Don't define accessors for private constants, since they can be
                // directly referenced.
                continue;
            }/*from w  w  w. ja  v  a2  s.com*/

            // rename varName to varName_, per Obj-C style guide
            SimpleName oldName = var.getName();
            ITypeBinding type = ((AbstractTypeDeclaration) node.getParent()).resolveBinding();
            String varName = NameTable.getStaticVarQualifiedName(type, oldName.getIdentifier());
            NameTable.rename(binding, varName);
            ITypeBinding typeBinding = binding.getType();
            var.setExtraDimensions(0); // if array, type was corrected above

            // add accessor(s)
            if (needsReader(var, classMembers)) {
                classMembers.add(indexOfNewMember++, makeStaticReader(var, mods));
            }
            if (!Modifier.isFinal(node.getModifiers()) && needsWriter(var, classMembers)) {
                classMembers.add(indexOfNewMember++,
                        makeStaticWriter(var, oldName.getIdentifier(), node.getType(), mods));
            }

            // move non-constant initialization to init block
            Expression initializer = var.getInitializer();
            if (initializer != null && initializer.resolveConstantExpressionValue() == null) {
                var.setInitializer(null);

                AST ast = var.getAST();
                SimpleName newName = ast.newSimpleName(varName);
                Types.addBinding(newName, binding);
                Assignment assign = ast.newAssignment();
                assign.setLeftHandSide(newName);
                Expression newInit = NodeCopier.copySubtree(ast, initializer);
                assign.setRightHandSide(newInit);
                Types.addBinding(assign, typeBinding);

                Block initBlock = ast.newBlock();
                @SuppressWarnings("unchecked")
                List<Statement> stmts = initBlock.statements(); // safe by definition
                stmts.add(ast.newExpressionStatement(assign));
                Initializer staticInitializer = ast.newInitializer();
                staticInitializer.setBody(initBlock);
                @SuppressWarnings("unchecked")
                List<IExtendedModifier> initMods = staticInitializer.modifiers(); // safe by definition
                initMods.add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
                classMembers.add(indexOfNewMember++, staticInitializer);
            }
        }
    }
    return true;
}

From source file:com.ibm.wala.cast.java.translator.jdt.JDTJava2CAstTranslator.java

License:Open Source License

private CAstNode getSwitchCaseConstant(SwitchCase n, WalkContext context) {
    // TODO: enums
    Expression expr = n.getExpression();
    Object constant = (expr == null) ? new Integer(0) : expr.resolveConstantExpressionValue(); // default case label of
    // "0" (what polyglot
    // does). we also set
    // SWITCH_DEFAULT
    // somewhere else
    // polyglot converts all labels to longs. why? who knows...
    if (constant instanceof Character)
        constant = new Long(((Character) constant).charValue());
    else if (constant instanceof Byte)
        constant = new Long(((Byte) constant).longValue());
    else if (constant instanceof Integer)
        constant = new Long(((Integer) constant).longValue());
    else if (constant instanceof Short)
        constant = new Long(((Short) constant).longValue());

    if (constant != null) {
        return fFactory.makeConstant(constant);
    } else if (expr instanceof SimpleName) {
        // enum constant
        return visit((SimpleName) expr, context);
    } else {// w w  w.j  a  v a  2  s .co m
        Assertions.UNREACHABLE("null constant for non-enum switch case!");
        return null;
    }
}

From source file:net.sf.j2s.core.astvisitors.ASTFieldVisitor.java

License:Open Source License

protected boolean isFieldNeedPreparation(FieldDeclaration node) {
    if ((node.getModifiers() & Modifier.STATIC) != 0) {
        return false;
    }/*from  w w w. j a v  a  2s  .c o m*/

    List fragments = node.fragments();
    for (Iterator iter = fragments.iterator(); iter.hasNext();) {
        VariableDeclarationFragment element = (VariableDeclarationFragment) iter.next();
        Expression initializer = element.getInitializer();
        if (initializer != null) {
            Object constValue = initializer.resolveConstantExpressionValue();
            if (constValue != null && (constValue instanceof Number || constValue instanceof Character
                    || constValue instanceof Boolean || constValue instanceof String)) {
                return false;
            }
            if (initializer instanceof NullLiteral) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }
    return false;
}

From source file:net.sf.j2s.core.astvisitors.ASTKeywordVisitor.java

License:Open Source License

public boolean visit(Assignment node) {
    Expression left = node.getLeftHandSide();
    Expression right = node.getRightHandSide();
    IVariableBinding varBinding = null;//from w  w  w . j  a v  a  2s .  c om
    if (left instanceof Name) {
        Name leftName = (Name) left;
        IBinding nameBinding = leftName.resolveBinding();
        if (nameBinding instanceof IVariableBinding) {
            varBinding = (IVariableBinding) nameBinding;
        }
    } else if (left instanceof FieldAccess) {
        FieldAccess leftAccess = (FieldAccess) left;
        varBinding = leftAccess.resolveFieldBinding();
    }
    String op = node.getOperator().toString();
    ITypeBinding declaring = null;
    String qName = null;
    if (varBinding != null && (varBinding.getModifiers() & Modifier.STATIC) != 0
            && (declaring = varBinding.getDeclaringClass()) != null
            && !(qName = declaring.getQualifiedName()).startsWith("org.eclipse.swt.internal.xhtml.")
            && !qName.startsWith("net.sf.j2s.html.")) {
        boolean directStaticAccess = left instanceof SimpleName
                || (left instanceof QualifiedName
                        && ((QualifiedName) left).getQualifier() instanceof SimpleName)
                || (left instanceof FieldAccess
                        && ((FieldAccess) left).getExpression() instanceof ThisExpression);
        ASTNode parent = node.getParent();
        boolean needParenthesis = (supportsObjectStaticFields || !directStaticAccess)
                && !(parent instanceof Statement);
        if (needParenthesis) {
            buffer.append("(");
        }
        if (left instanceof QualifiedName) {
            QualifiedName leftName = (QualifiedName) left;
            if (!(leftName.getQualifier() instanceof SimpleName)) {
                leftName.getQualifier().accept(this);
                buffer.append(", ");
            }
        } else if (left instanceof FieldAccess) {
            FieldAccess leftAccess = (FieldAccess) left;
            if (!(leftAccess.getExpression() instanceof ThisExpression)) {
                leftAccess.getExpression().accept(this);
                buffer.append(", ");
            }
        }
        if (supportsObjectStaticFields) {
            buffer.append(assureQualifiedName(
                    shortenQualifiedName(varBinding.getDeclaringClass().getQualifiedName())));
            buffer.append(".prototype.");
            if (left instanceof QualifiedName) {
                QualifiedName leftName = (QualifiedName) left;
                leftName.getName().accept(this);
            } else if (left instanceof FieldAccess) {
                FieldAccess leftAccess = (FieldAccess) left;
                leftAccess.getName().accept(this);
            } else {
                Name leftName = (Name) left;
                leftName.accept(this);
            }
            buffer.append(" = ");
        }

        buffer.append(
                assureQualifiedName(shortenQualifiedName(varBinding.getDeclaringClass().getQualifiedName())));
        buffer.append('.');
        if (left instanceof QualifiedName) {
            QualifiedName leftName = (QualifiedName) left;
            leftName.getName().accept(this);
        } else if (left instanceof FieldAccess) {
            FieldAccess leftAccess = (FieldAccess) left;
            leftAccess.getName().accept(this);
        } else {
            Name leftName = (Name) left;
            leftName.accept(this);
        }
        buffer.append(' ');
        boolean isMixedOp = op.trim().length() > 1;
        ITypeBinding leftTypeBinding = left.resolveTypeBinding();
        if (leftTypeBinding != null && "char".equals(leftTypeBinding.getName())) {
            ITypeBinding rightTypeBinding = right.resolveTypeBinding();
            if (!isMixedOp) { // =
                buffer.append(op);
                buffer.append(' ');
                if (rightTypeBinding != null && "char".equals(rightTypeBinding.getName())) {
                    boxingNode(right);
                } else {
                    buffer.append("String.fromCharCode (");
                    boxingNode(right);
                    buffer.append(')');
                }
            } else {
                buffer.append("= String.fromCharCode (");
                buffer.append(assureQualifiedName(
                        shortenQualifiedName(varBinding.getDeclaringClass().getQualifiedName())));
                buffer.append('.');
                if (left instanceof QualifiedName) {
                    QualifiedName leftName = (QualifiedName) left;
                    leftName.getName().accept(this);
                } else if (left instanceof FieldAccess) {
                    FieldAccess leftAccess = (FieldAccess) left;
                    leftAccess.getName().accept(this);
                } else {
                    Name leftName = (Name) left;
                    leftName.accept(this);
                }
                buffer.append(".charCodeAt (0) ");
                buffer.append(op.charAt(0));
                buffer.append(' ');
                if (rightTypeBinding != null && "char".equals(rightTypeBinding.getName())) {
                    Object constValue = right.resolveConstantExpressionValue();
                    if (constValue != null && constValue instanceof Character) {
                        buffer.append(((Character) constValue).charValue() + 0);
                    } else {
                        boxingNode(right);
                        buffer.append(".charCodeAt (0)");
                    }
                } else {
                    boxingNode(right);
                }
                buffer.append(")");
            }
        } else {
            buffer.append(op);
            buffer.append(' ');
            boxingNode(right);
        }

        if (needParenthesis) {
            buffer.append(")");
        }
        return false;
    }
    ITypeBinding typeBinding = left.resolveTypeBinding();
    if (typeBinding != null && typeBinding.isPrimitive()) {
        if ("boolean".equals(typeBinding.getName())) {
            if (op.startsWith("^") || op.startsWith("|") || op.startsWith("&")
            /*|| op.startsWith("!")*/) {
                left.accept(this);
                buffer.append(" = new Boolean (");
                left.accept(this);
                buffer.append(' ');
                buffer.append(op.charAt(0));
                if (right instanceof InfixExpression) {
                    buffer.append(" (");
                    right.accept(this);
                    buffer.append("))");
                } else {
                    buffer.append(' ');
                    right.accept(this);
                    buffer.append(')');
                }
                buffer.append(".valueOf ()");
                return false;
            }
        } else if (typeBinding != null && "char".equals(typeBinding.getName())) {
            boolean isMixedOp = op.trim().length() > 1;
            if (!isMixedOp) {
                if (right instanceof Name || right instanceof CharacterLiteral || right instanceof ArrayAccess
                        || right instanceof FieldAccess || right instanceof MethodInvocation
                        || right instanceof ParenthesizedExpression || right instanceof SuperFieldAccess
                        || right instanceof SuperMethodInvocation || right instanceof ThisExpression
                        || right instanceof CastExpression) {
                    left.accept(this);
                    buffer.append(" = ");
                    right.accept(this);
                    return false;
                }
            }
            ITypeBinding rightTypeBinding = right.resolveTypeBinding();
            /*
             * FIXME: Bug here!: 
             * v[count++] += 'a';
             * v[count++] = String.fromCharCode ((v[count++]).charCodeAt (0) + 97);
             */
            left.accept(this);
            if (rightTypeBinding != null && "char".equals(rightTypeBinding.getName()) && !isMixedOp) {
                buffer.append(' ');
                buffer.append(op);
                buffer.append(' ');
                right.accept(this);
            } else {
                buffer.append(" = String.fromCharCode (");
                if (isMixedOp) {
                    if (left instanceof SimpleName || left instanceof QualifiedName) {
                        left.accept(this);
                    } else {
                        buffer.append("(");
                        left.accept(this);
                        buffer.append(")");
                    }
                    buffer.append(".charCodeAt (0) ");
                    buffer.append(op.charAt(0));
                }
                buffer.append(' ');
                if (right instanceof InfixExpression) {
                    String constValue = checkConstantValue(right);
                    if (constValue != null) {
                        buffer.append(constValue);
                    } else {
                        buffer.append("(");
                        right.accept(this);
                        buffer.append(")");
                    }
                    if ("char".equals(rightTypeBinding.getName())) {
                        buffer.append(".charCodeAt (0)");
                    }
                } else {
                    if ("char".equals(rightTypeBinding.getName())) {
                        Object constValue = right.resolveConstantExpressionValue();
                        if (constValue != null && constValue instanceof Character) {
                            buffer.append(((Character) constValue).charValue() + 0);
                        } else {
                            boolean needParenthesis = !(right instanceof ParenthesizedExpression
                                    || right instanceof PrefixExpression || right instanceof PostfixExpression);
                            if (needParenthesis) {
                                buffer.append("(");
                            }
                            right.accept(this);
                            if (needParenthesis) {
                                buffer.append(")");
                            }
                            buffer.append(".charCodeAt (0)");
                        }
                    } else {
                        right.accept(this);
                    }
                }
                buffer.append(')');
            }
            return false;
        }
    }
    left.accept(this);
    buffer.append(' ');
    buffer.append(op);
    buffer.append(' ');
    ITypeBinding binding = right.resolveTypeBinding();
    if (binding != null && "char".equals(binding.getName())) {
        String typeBindingName = (typeBinding != null) ? typeBinding.getName() : null;
        if (right instanceof CharacterLiteral) {
            CharacterLiteral cl = (CharacterLiteral) right;
            if ("char".equals(typeBindingName) || typeBindingName.indexOf("String") != -1) {
                String constValue = checkConstantValue(right);
                buffer.append(constValue);
            } else {
                buffer.append(0 + cl.charValue());
            }
        } else {
            if (typeBindingName != null
                    && ("char".equals(typeBindingName) || typeBindingName.indexOf("String") != -1)) {
                right.accept(this);
            } else {
                int idx1 = buffer.length();
                buffer.append('(');
                right.accept(this);
                buffer.append(")");

                boolean appendingCode = true;
                int length = buffer.length();
                if (right instanceof MethodInvocation) {
                    MethodInvocation m = (MethodInvocation) right;
                    if ("charAt".equals(m.getName().toString())) {
                        int idx2 = buffer.indexOf(".charAt ", idx1);
                        if (idx2 != -1) {
                            StringBuffer newMethodBuffer = new StringBuffer();
                            newMethodBuffer.append(buffer.substring(idx1 + 1, idx2));
                            newMethodBuffer.append(".charCodeAt ");
                            newMethodBuffer.append(buffer.substring(idx2 + 8, length - 1));
                            buffer.delete(idx1, length);
                            buffer.append(newMethodBuffer.toString());
                            appendingCode = false;
                        }
                    }
                }
                if (appendingCode) {
                    buffer.append(".charCodeAt (0)");
                }
            }
        }
    } else {
        boxingNode(right);
    }
    return false;
}

From source file:net.sf.j2s.core.astvisitors.ASTScriptVisitor.java

License:Open Source License

public boolean visit(CastExpression node) {
    Type type = node.getType();//w w  w  .java  2 s.  co  m
    /*
     * TODO: some casting should have its meaning!
     * int to byte, int to short, long to int will lost values
     */
    Expression expression = node.getExpression();
    if (type.isPrimitiveType()) {
        ITypeBinding resolveTypeBinding = expression.resolveTypeBinding();
        if (resolveTypeBinding != null) {
            String name = resolveTypeBinding.getName();
            PrimitiveType pType = (PrimitiveType) type;
            if (pType.getPrimitiveTypeCode() == PrimitiveType.INT
                    || pType.getPrimitiveTypeCode() == PrimitiveType.BYTE
                    || pType.getPrimitiveTypeCode() == PrimitiveType.SHORT
                    || pType.getPrimitiveTypeCode() == PrimitiveType.LONG) {
                if ("char".equals(name)) {
                    buffer.append("(");
                    if (expression instanceof ParenthesizedExpression) {
                        ParenthesizedExpression pe = (ParenthesizedExpression) expression;
                        pe.getExpression().accept(this);
                    } else {
                        expression.accept(this);
                    }
                    buffer.append(").charCodeAt (0)");
                    return false;
                } else if ("float".equals(name) || "double".equals(name)) {
                    //buffer.append("Math.round (");
                    buffer.append("Clazz.");
                    buffer.append(name);
                    buffer.append("To");
                    String targetType = pType.getPrimitiveTypeCode().toString();
                    buffer.append(targetType.substring(0, 1).toUpperCase());
                    buffer.append(targetType.substring(1));
                    buffer.append(" (");
                    if (expression instanceof ParenthesizedExpression) {
                        ParenthesizedExpression pe = (ParenthesizedExpression) expression;
                        pe.getExpression().accept(this);
                    } else {
                        expression.accept(this);
                    }
                    buffer.append(")");
                    return false;
                }
            }
            if (pType.getPrimitiveTypeCode() == PrimitiveType.CHAR) {
                if ("char".equals(name)) {
                    //                  buffer.append("(");
                    //                  node.getExpression().accept(this);
                    //                  buffer.append (").charCodeAt (0)");
                    //                  return false;
                } else if ("float".equals(name) || "double".equals(name)) {
                    // TODO:
                    buffer.append("Clazz.");
                    buffer.append(name);
                    buffer.append("ToChar (");
                    //                  buffer.append("String.fromCharCode (");
                    //                  buffer.append("Math.round (");
                    if (expression instanceof ParenthesizedExpression) {
                        ParenthesizedExpression pe = (ParenthesizedExpression) expression;
                        pe.getExpression().accept(this);
                    } else {
                        expression.accept(this);
                    }
                    //                  buffer.append (")");
                    buffer.append(")");
                    return false;
                } else if ("int".equals(name) || "byte".equals(name)
                // || "double".equals(name) || "float".equals(name)
                        || "short".equals(name) || "long".equals(name)) {
                    Object constantValue = expression.resolveConstantExpressionValue();
                    if (constantValue != null) {
                        if (constantValue instanceof Integer) {
                            int value = ((Integer) constantValue).intValue();
                            if ((value >= '0' && value <= '9') || (value >= 'A' && value <= 'Z')
                                    || (value >= 'a' && value <= 'z')) {
                                buffer.append('\'');
                                buffer.append((char) value);
                                buffer.append('\'');
                                return false;
                            }
                        } else if (constantValue instanceof Long) {
                            long value = ((Long) constantValue).longValue();
                            if ((value >= '0' && value <= '9') || (value >= 'A' && value <= 'Z')
                                    || (value >= 'a' && value <= 'z')) {
                                buffer.append('\'');
                                buffer.append((char) value);
                                buffer.append('\'');
                                return false;
                            }
                        }
                    }
                    buffer.append("String.fromCharCode (");
                    if (expression instanceof ParenthesizedExpression) {
                        ParenthesizedExpression pe = (ParenthesizedExpression) expression;
                        pe.getExpression().accept(this);
                    } else {
                        expression.accept(this);
                    }
                    buffer.append(")");
                    return false;
                }
            }
        }
    }
    expression.accept(this);
    return false;
}

From source file:net.sf.j2s.core.astvisitors.ASTVariableVisitor.java

License:Open Source License

/**
 * If given expression is constant value expression, return its value 
 * string; or return null.//from   w ww.j  a v a2s. c o  m
 * 
 * @param node
 * @return
 */
protected String checkConstantValue(Expression node) {
    Object constValue = node.resolveConstantExpressionValue();
    if (constValue != null && (constValue instanceof Number || constValue instanceof Character
            || constValue instanceof Boolean)) {
        StringBuffer buffer = new StringBuffer();
        if (constValue instanceof Character) {
            buffer.append('\'');
            char charValue = ((Character) constValue).charValue();
            if (charValue < 32 || charValue > 127) {
                buffer.append("\\u");
                String hexStr = Integer.toHexString(charValue);
                int zeroLen = 4 - hexStr.length();
                for (int i = 0; i < zeroLen; i++) {
                    buffer.append('0');
                }
                buffer.append(hexStr);
            } else {
                char c = charValue;
                if (c == '\\' || c == '\'' || c == '\"') {
                    buffer.append('\\');
                    buffer.append(c);
                } else if (c == '\r') {
                    buffer.append("\\r");
                } else if (c == '\n') {
                    buffer.append("\\n");
                } else if (c == '\t') {
                    buffer.append("\\t");
                } else if (c == '\f') {
                    buffer.append("\\f");
                } else {
                    buffer.append(constValue);
                }
            }
            buffer.append('\'');
        } else {
            buffer.append(constValue);
        }
        return buffer.toString();
    }
    if (constValue != null && (constValue instanceof String)) {
        StringBuffer buffer = new StringBuffer();
        String str = (String) constValue;
        int length = str.length();
        /*
        if (length > 20) {
           return null;
        }*/
        buffer.append("\"");
        for (int i = 0; i < length; i++) {
            char c = str.charAt(i);
            if (c == '\\' || c == '\'' || c == '\"') {
                buffer.append('\\');
                buffer.append(c);
            } else if (c == '\r') {
                buffer.append("\\r");
            } else if (c == '\n') {
                buffer.append("\\n");
            } else if (c == '\t') {
                buffer.append("\\t");
            } else if (c == '\f') {
                buffer.append("\\f");
            } else if (c < 32 || c > 127) {
                buffer.append("\\u");
                String hexStr = Integer.toHexString(c);
                int zeroLen = 4 - hexStr.length();
                for (int k = 0; k < zeroLen; k++) {
                    buffer.append('0');
                }
                buffer.append(hexStr);
            } else {
                buffer.append(c);
            }
        }
        buffer.append("\"");
        return buffer.toString();
    }
    return null;
}

From source file:org.autorefactor.refactoring.ASTHelper.java

License:Open Source License

/**
 * Returns whether the provided expression represents a constant value.
 *
 * @param expr the expression to analyze
 * @return true the provided expression represents a constant value, false otherwise
 *//*from w  ww  .  j  av  a  2 s . c om*/
public static boolean isConstant(final Expression expr) {
    return (expr != null && expr.resolveConstantExpressionValue() != null) || isEnumConstant(expr);
}