Example usage for org.eclipse.jdt.internal.compiler.ast Block Block

List of usage examples for org.eclipse.jdt.internal.compiler.ast Block Block

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast Block Block.

Prototype

public Block(int explicitDeclarations) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private Initializer convert(InitializerElementInfo initializerInfo, CompilationResult compilationResult)
        throws JavaModelException {

    Block block = new Block(0);
    Initializer initializer = new Initializer(block, ClassFileConstants.AccDefault);

    int start = initializerInfo.getDeclarationSourceStart();
    int end = initializerInfo.getDeclarationSourceEnd();

    initializer.sourceStart = initializer.declarationSourceStart = start;
    initializer.sourceEnd = initializer.declarationSourceEnd = end;
    initializer.modifiers = initializerInfo.getModifiers();

    /* convert local and anonymous types */
    IJavaElement[] children = initializerInfo.getChildren();
    int typesLength = children.length;
    if (typesLength > 0) {
        Statement[] statements = new Statement[typesLength];
        for (int i = 0; i < typesLength; i++) {
            SourceType type = (SourceType) children[i];
            TypeDeclaration localType = convert(type, compilationResult);
            if ((localType.bits & ASTNode.IsAnonymousType) != 0) {
                QualifiedAllocationExpression expression = new QualifiedAllocationExpression(localType);
                expression.type = localType.superclass;
                localType.superclass = null;
                localType.superInterfaces = null;
                localType.allocation = expression;
                statements[i] = expression;
            } else {
                statements[i] = localType;
            }/*from w  w w .j  av a  2s. com*/
        }
        block.statements = statements;
    }

    return initializer;
}

From source file:lombok.eclipse.handlers.ast.EclipseASTMaker.java

License:Open Source License

@Override
public ASTNode visitBlock(final lombok.ast.Block node, final Void p) {
    final Block block = new Block(0);
    setGeneratedByAndCopyPos(block, source, posHintOf(node));
    block.statements = toArray(build(node.getStatements()), new Statement[0]);
    return block;
}

From source file:lombok.eclipse.handlers.ast.EclipseASTMaker.java

License:Open Source License

@Override
public ASTNode visitInitializer(lombok.ast.Initializer node, Void p) {
    final Block block = new Block(0);
    setGeneratedByAndCopyPos(block, source, posHintOf(node));
    block.statements = toArray(build(node.getStatements()), new Statement[0]);
    final Initializer initializer = new Initializer(block, modifiersFor(node.getModifiers()));
    initializer.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    setGeneratedByAndCopyPos(initializer, source, posHintOf(node));
    return initializer;
}

From source file:lombok.eclipse.handlers.ast.EclipseASTMaker.java

License:Open Source License

@Override
public ASTNode visitSynchronized(final lombok.ast.Synchronized node, final Void p) {
    final Block block = new Block(0);
    setGeneratedByAndCopyPos(block, source, posHintOf(node));
    block.statements = toArray(build(node.getStatements()), new Statement[0]);
    final SynchronizedStatement synchronizedStatemenet = new SynchronizedStatement(
            build(node.getLock(), Expression.class), block, 0, 0);
    setGeneratedByAndCopyPos(synchronizedStatemenet, source, posHintOf(node));
    return synchronizedStatemenet;
}

From source file:lombok.eclipse.handlers.EclipseHandlerUtil.java

License:Open Source License

/**
 * Generates a new statement that checks if the given variable is null, and if so, throws a specified exception with the
 * variable name as message.//from ww  w  . ja v  a  2  s .c o m
 * 
 * @param exName The name of the exception to throw; normally {@code java.lang.NullPointerException}.
 */
public static Statement generateNullCheck(AbstractVariableDeclaration variable, EclipseNode sourceNode) {
    NullCheckExceptionType exceptionType = sourceNode.getAst()
            .readConfiguration(ConfigurationKeys.NON_NULL_EXCEPTION_TYPE);
    if (exceptionType == null)
        exceptionType = NullCheckExceptionType.NULL_POINTER_EXCEPTION;

    ASTNode source = sourceNode.get();

    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    if (isPrimitive(variable.type))
        return null;
    AllocationExpression exception = new AllocationExpression();
    setGeneratedBy(exception, source);
    int partCount = 1;
    String exceptionTypeStr = exceptionType.getExceptionType();
    for (int i = 0; i < exceptionTypeStr.length(); i++)
        if (exceptionTypeStr.charAt(i) == '.')
            partCount++;
    long[] ps = new long[partCount];
    Arrays.fill(ps, 0L);
    exception.type = new QualifiedTypeReference(fromQualifiedName(exceptionTypeStr), ps);
    setGeneratedBy(exception.type, source);
    exception.arguments = new Expression[] { new StringLiteral(
            exceptionType.toExceptionMessage(new String(variable.name)).toCharArray(), pS, pE, 0) };
    setGeneratedBy(exception.arguments[0], source);
    ThrowStatement throwStatement = new ThrowStatement(exception, pS, pE);
    setGeneratedBy(throwStatement, source);

    SingleNameReference varName = new SingleNameReference(variable.name, p);
    setGeneratedBy(varName, source);
    NullLiteral nullLiteral = new NullLiteral(pS, pE);
    setGeneratedBy(nullLiteral, source);
    EqualExpression equalExpression = new EqualExpression(varName, nullLiteral, OperatorIds.EQUAL_EQUAL);
    equalExpression.sourceStart = pS;
    equalExpression.statementEnd = equalExpression.sourceEnd = pE;
    setGeneratedBy(equalExpression, source);
    Block throwBlock = new Block(0);
    throwBlock.statements = new Statement[] { throwStatement };
    throwBlock.sourceStart = pS;
    throwBlock.sourceEnd = pE;
    setGeneratedBy(throwBlock, source);
    IfStatement ifStatement = new IfStatement(equalExpression, throwBlock, 0, 0);
    setGeneratedBy(ifStatement, source);
    return ifStatement;
}

From source file:lombok.eclipse.handlers.HandleCleanup.java

License:Open Source License

public void handle(AnnotationValues<Cleanup> annotation, Annotation ast, EclipseNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");

    String cleanupName = annotation.getInstance().value();
    if (cleanupName.length() == 0) {
        annotationNode.addError("cleanupName cannot be the empty string.");
        return;/* ww  w  . java2 s .c o  m*/
    }

    if (annotationNode.up().getKind() != Kind.LOCAL) {
        annotationNode.addError("@Cleanup is legal only on local variable declarations.");
        return;
    }

    LocalDeclaration decl = (LocalDeclaration) annotationNode.up().get();

    if (decl.initialization == null) {
        annotationNode.addError("@Cleanup variable declarations need to be initialized.");
        return;
    }

    EclipseNode ancestor = annotationNode.up().directUp();
    ASTNode blockNode = ancestor.get();

    final boolean isSwitch;
    final Statement[] statements;
    if (blockNode instanceof AbstractMethodDeclaration) {
        isSwitch = false;
        statements = ((AbstractMethodDeclaration) blockNode).statements;
    } else if (blockNode instanceof Block) {
        isSwitch = false;
        statements = ((Block) blockNode).statements;
    } else if (blockNode instanceof SwitchStatement) {
        isSwitch = true;
        statements = ((SwitchStatement) blockNode).statements;
    } else {
        annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
        return;
    }

    if (statements == null) {
        annotationNode.addError("LOMBOK BUG: Parent block does not contain any statements.");
        return;
    }

    int start = 0;
    for (; start < statements.length; start++) {
        if (statements[start] == decl)
            break;
    }

    if (start == statements.length) {
        annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
        return;
    }

    start++; //We start with try{} *AFTER* the var declaration.

    int end;
    if (isSwitch) {
        end = start + 1;
        for (; end < statements.length; end++) {
            if (statements[end] instanceof CaseStatement) {
                break;
            }
        }
    } else
        end = statements.length;

    //At this point:
    //  start-1 = Local Declaration marked with @Cleanup
    //  start = first instruction that needs to be wrapped into a try block
    //  end = last instruction of the scope -OR- last instruction before the next case label in switch statements.
    //  hence:
    //  [start, end) = statements for the try block.

    Statement[] tryBlock = new Statement[end - start];
    System.arraycopy(statements, start, tryBlock, 0, end - start);
    //Remove the stuff we just dumped into the tryBlock, and then leave room for the try node.
    int newStatementsLength = statements.length - (end - start); //Remove room for every statement moved into try block...
    newStatementsLength += 1; //But add room for the TryStatement node itself.
    Statement[] newStatements = new Statement[newStatementsLength];
    System.arraycopy(statements, 0, newStatements, 0, start); //copy all statements before the try block verbatim.
    System.arraycopy(statements, end, newStatements, start + 1, statements.length - end); //For switch statements.

    doAssignmentCheck(annotationNode, tryBlock, decl.name);

    TryStatement tryStatement = new TryStatement();
    setGeneratedBy(tryStatement, ast);
    tryStatement.tryBlock = new Block(0);
    tryStatement.tryBlock.statements = tryBlock;
    setGeneratedBy(tryStatement.tryBlock, ast);

    // Positions for in-method generated nodes are special
    int ss = decl.declarationSourceEnd + 1;
    int se = ss;
    if (tryBlock.length > 0) {
        se = tryBlock[tryBlock.length - 1].sourceEnd + 1; //+1 for the closing semicolon. Yes, there could be spaces. Bummer.
        tryStatement.sourceStart = ss;
        tryStatement.sourceEnd = se;
        tryStatement.tryBlock.sourceStart = ss;
        tryStatement.tryBlock.sourceEnd = se;
    }

    newStatements[start] = tryStatement;

    Statement[] finallyBlock = new Statement[1];
    MessageSend unsafeClose = new MessageSend();
    setGeneratedBy(unsafeClose, ast);
    unsafeClose.sourceStart = ast.sourceStart;
    unsafeClose.sourceEnd = ast.sourceEnd;
    SingleNameReference receiver = new SingleNameReference(decl.name, 0);
    setGeneratedBy(receiver, ast);
    unsafeClose.receiver = receiver;
    long nameSourcePosition = (long) ast.sourceStart << 32 | ast.sourceEnd;
    if (ast.memberValuePairs() != null)
        for (MemberValuePair pair : ast.memberValuePairs()) {
            if (pair.name != null && new String(pair.name).equals("value")) {
                nameSourcePosition = (long) pair.value.sourceStart << 32 | pair.value.sourceEnd;
                break;
            }
        }
    unsafeClose.nameSourcePosition = nameSourcePosition;
    unsafeClose.selector = cleanupName.toCharArray();

    int pS = ast.sourceStart, pE = ast.sourceEnd;
    long p = (long) pS << 32 | pE;

    SingleNameReference varName = new SingleNameReference(decl.name, p);
    setGeneratedBy(varName, ast);
    NullLiteral nullLiteral = new NullLiteral(pS, pE);
    setGeneratedBy(nullLiteral, ast);

    MessageSend preventNullAnalysis = preventNullAnalysis(ast, varName);

    EqualExpression equalExpression = new EqualExpression(preventNullAnalysis, nullLiteral,
            OperatorIds.NOT_EQUAL);
    equalExpression.sourceStart = pS;
    equalExpression.sourceEnd = pE;
    setGeneratedBy(equalExpression, ast);

    Block closeBlock = new Block(0);
    closeBlock.statements = new Statement[1];
    closeBlock.statements[0] = unsafeClose;
    setGeneratedBy(closeBlock, ast);
    IfStatement ifStatement = new IfStatement(equalExpression, closeBlock, 0, 0);
    setGeneratedBy(ifStatement, ast);

    finallyBlock[0] = ifStatement;
    tryStatement.finallyBlock = new Block(0);

    // Positions for in-method generated nodes are special
    if (!isSwitch) {
        tryStatement.finallyBlock.sourceStart = blockNode.sourceEnd;
        tryStatement.finallyBlock.sourceEnd = blockNode.sourceEnd;
    }
    setGeneratedBy(tryStatement.finallyBlock, ast);
    tryStatement.finallyBlock.statements = finallyBlock;

    tryStatement.catchArguments = null;
    tryStatement.catchBlocks = null;

    if (blockNode instanceof AbstractMethodDeclaration) {
        ((AbstractMethodDeclaration) blockNode).statements = newStatements;
    } else if (blockNode instanceof Block) {
        ((Block) blockNode).statements = newStatements;
    } else if (blockNode instanceof SwitchStatement) {
        ((SwitchStatement) blockNode).statements = newStatements;
    }

    ancestor.rebuild();
}

From source file:lombok.eclipse.handlers.HandleGetter.java

License:Open Source License

public Statement[] createLazyGetterBody(ASTNode source, EclipseNode fieldNode) {
    /*//from w w  w  .ja va 2  s.co  m
    java.lang.Object value = this.fieldName.get();
    if (value == null) {
       synchronized (this.fieldName) {
    value = this.fieldName.get();
    if (value == null) {
       final RawValueType actualValue = INITIALIZER_EXPRESSION;
       [IF PRIMITIVE]
       value = actualValue;
       [ELSE]
       value = actualValue == null ? this.fieldName : actualValue;
       [END IF]
       this.fieldName.set(value);
    }
       }
    }
    [IF PRIMITIVE]
    return (BoxedValueType) value;
    [ELSE]
    return (BoxedValueType) (value == this.fieldName ? null : value);
    [END IF]
    */

    FieldDeclaration field = (FieldDeclaration) fieldNode.get();
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;

    TypeReference rawComponentType = copyType(field.type, source);
    TypeReference boxedComponentType = null;
    boolean isPrimitive = false;
    if (field.type instanceof SingleTypeReference && !(field.type instanceof ArrayTypeReference)) {
        char[][] newType = TYPE_MAP.get(new String(((SingleTypeReference) field.type).token));
        if (newType != null) {
            boxedComponentType = new QualifiedTypeReference(newType, poss(source, 3));
            isPrimitive = true;
        }
    }
    if (boxedComponentType == null)
        boxedComponentType = copyType(field.type, source);
    boxedComponentType.sourceStart = pS;
    boxedComponentType.sourceEnd = boxedComponentType.statementEnd = pE;

    Statement[] statements = new Statement[3];

    /* java.lang.Object value = this.fieldName.get(); */ {
        LocalDeclaration valueDecl = new LocalDeclaration(valueName, pS, pE);
        valueDecl.type = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3));
        valueDecl.type.sourceStart = pS;
        valueDecl.type.sourceEnd = valueDecl.type.statementEnd = pE;

        MessageSend getter = new MessageSend();
        getter.sourceStart = pS;
        getter.statementEnd = getter.sourceEnd = pE;
        getter.selector = new char[] { 'g', 'e', 't' };
        getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);

        valueDecl.initialization = getter;
        statements[0] = valueDecl;
    }

    /*
    if (value == null) {
       synchronized (this.fieldName) {
    value = this.fieldName.get();
    if (value == null) { 
       final ValueType actualValue = INITIALIZER_EXPRESSION;
       [IF PRIMITIVE]
       value = actualValue;
       [ELSE]
       value = actualValue == null ? this.fieldName : actualValue;
       [END IF]
       this.fieldName.set(value);
    }
       }
    }
     */ {
        EqualExpression cond = new EqualExpression(new SingleNameReference(valueName, p),
                new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
        Block then = new Block(0);
        Expression lock = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
        Block inner = new Block(0);
        inner.statements = new Statement[2];
        /* value = this.fieldName.get(); */ {
            MessageSend getter = new MessageSend();
            getter.sourceStart = pS;
            getter.sourceEnd = getter.statementEnd = pE;
            getter.selector = new char[] { 'g', 'e', 't' };
            getter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
            Assignment assign = new Assignment(new SingleNameReference(valueName, p), getter, pE);
            assign.sourceStart = pS;
            assign.statementEnd = assign.sourceEnd = pE;
            inner.statements[0] = assign;
        }
        /* if (value == null) */ {
            EqualExpression innerCond = new EqualExpression(new SingleNameReference(valueName, p),
                    new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
            innerCond.sourceStart = pS;
            innerCond.sourceEnd = innerCond.statementEnd = pE;
            Block innerThen = new Block(0);
            innerThen.statements = new Statement[3];
            /* final ValueType actualValue = INITIALIZER_EXPRESSION */ {
                LocalDeclaration actualValueDecl = new LocalDeclaration(actualValueName, pS, pE);
                actualValueDecl.type = rawComponentType;
                actualValueDecl.type.sourceStart = pS;
                actualValueDecl.type.sourceEnd = actualValueDecl.type.statementEnd = pE;
                actualValueDecl.initialization = field.initialization;
                actualValueDecl.modifiers = ClassFileConstants.AccFinal;
                innerThen.statements[0] = actualValueDecl;
            }
            /* [IF PRIMITIVE] value = actualValue; */ {
                if (isPrimitive) {
                    Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p),
                            new SingleNameReference(actualValueName, p), pE);
                    innerAssign.sourceStart = pS;
                    innerAssign.statementEnd = innerAssign.sourceEnd = pE;
                    innerThen.statements[1] = innerAssign;
                }
            }
            /* [ELSE] value = actualValue == null ? this.fieldName : actualValue; */ {
                if (!isPrimitive) {
                    EqualExpression avIsNull = new EqualExpression(new SingleNameReference(actualValueName, p),
                            new NullLiteral(pS, pE), BinaryExpression.EQUAL_EQUAL);
                    avIsNull.sourceStart = pS;
                    avIsNull.sourceEnd = avIsNull.statementEnd = pE;
                    Expression fieldRef = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
                    ConditionalExpression ternary = new ConditionalExpression(avIsNull, fieldRef,
                            new SingleNameReference(actualValueName, p));
                    ternary.sourceStart = pS;
                    ternary.sourceEnd = ternary.statementEnd = pE;
                    Assignment innerAssign = new Assignment(new SingleNameReference(valueName, p), ternary, pE);
                    innerAssign.sourceStart = pS;
                    innerAssign.statementEnd = innerAssign.sourceEnd = pE;
                    innerThen.statements[1] = innerAssign;
                }
            }

            /* this.fieldName.set(value); */ {
                MessageSend setter = new MessageSend();
                setter.sourceStart = pS;
                setter.sourceEnd = setter.statementEnd = pE;
                setter.receiver = createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source);
                setter.selector = new char[] { 's', 'e', 't' };
                setter.arguments = new Expression[] { new SingleNameReference(valueName, p) };
                innerThen.statements[2] = setter;
            }

            IfStatement innerIf = new IfStatement(innerCond, innerThen, pS, pE);
            inner.statements[1] = innerIf;
        }

        SynchronizedStatement sync = new SynchronizedStatement(lock, inner, pS, pE);
        then.statements = new Statement[] { sync };

        IfStatement ifStatement = new IfStatement(cond, then, pS, pE);
        statements[1] = ifStatement;
    }

    /* [IF PRIMITIVE] return (BoxedValueType)value; */ {
        if (isPrimitive) {
            CastExpression cast = makeCastExpression(new SingleNameReference(valueName, p), boxedComponentType,
                    source);
            statements[2] = new ReturnStatement(cast, pS, pE);
        }
    }
    /* [ELSE] return (BoxedValueType)(value == this.fieldName ? null : value); */ {
        if (!isPrimitive) {
            EqualExpression vIsThisFieldName = new EqualExpression(new SingleNameReference(valueName, p),
                    createFieldAccessor(fieldNode, FieldAccess.ALWAYS_FIELD, source),
                    BinaryExpression.EQUAL_EQUAL);
            vIsThisFieldName.sourceStart = pS;
            vIsThisFieldName.sourceEnd = vIsThisFieldName.statementEnd = pE;
            ConditionalExpression ternary = new ConditionalExpression(vIsThisFieldName, new NullLiteral(pS, pE),
                    new SingleNameReference(valueName, p));
            ternary.sourceStart = pS;
            ternary.sourceEnd = ternary.statementEnd = pE;
            ternary.bits |= PARENTHESIZED;
            CastExpression cast = makeCastExpression(ternary, boxedComponentType, source);
            statements[2] = new ReturnStatement(cast, pS, pE);
        }
    }

    // update the field type and init last

    /*    private final java.util.concurrent.atomic.AtomicReference<java.lang.Object> fieldName = new java.util.concurrent.atomic.AtomicReference<java.lang.Object>(); */ {
        TypeReference innerType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_OBJECT, poss(source, 3));
        TypeReference[][] typeParams = new TypeReference[5][];
        typeParams[4] = new TypeReference[] { innerType };
        TypeReference type = new ParameterizedQualifiedTypeReference(AR, typeParams, 0, poss(source, 5));

        // Some magic here
        type.sourceStart = -1;
        type.sourceEnd = -2;

        field.type = type;
        AllocationExpression init = new AllocationExpression();
        // Some magic here
        init.sourceStart = field.initialization.sourceStart;
        init.sourceEnd = init.statementEnd = field.initialization.sourceEnd;
        init.type = copyType(type, source);
        field.initialization = init;
    }
    return statements;
}

From source file:lombok.eclipse.handlers.HandleSneakyThrows.java

License:Open Source License

public Statement buildTryCatchBlock(Statement[] contents, DeclaredException exception, ASTNode source,
        AbstractMethodDeclaration method) {
    int methodStart = method.bodyStart;
    int methodEnd = method.bodyEnd;
    long methodPosEnd = ((long) methodEnd) << 32 | (methodEnd & 0xFFFFFFFFL);

    TryStatement tryStatement = new TryStatement();
    setGeneratedBy(tryStatement, source);
    tryStatement.tryBlock = new Block(0);

    // Positions for in-method generated nodes are special
    tryStatement.tryBlock.sourceStart = methodStart;
    tryStatement.tryBlock.sourceEnd = methodEnd;

    setGeneratedBy(tryStatement.tryBlock, source);
    tryStatement.tryBlock.statements = contents;
    TypeReference typeReference;//from w w w.j  a v a 2s. c om
    if (exception.exceptionName.indexOf('.') == -1) {
        typeReference = new SingleTypeReference(exception.exceptionName.toCharArray(), methodPosEnd);
        typeReference.statementEnd = methodEnd;
    } else {
        String[] x = exception.exceptionName.split("\\.");
        char[][] elems = new char[x.length][];
        long[] poss = new long[x.length];
        Arrays.fill(poss, methodPosEnd);
        for (int i = 0; i < x.length; i++) {
            elems[i] = x[i].trim().toCharArray();
        }
        typeReference = new QualifiedTypeReference(elems, poss);
    }
    setGeneratedBy(typeReference, source);

    Argument catchArg = new Argument("$ex".toCharArray(), methodPosEnd, typeReference, Modifier.FINAL);
    setGeneratedBy(catchArg, source);
    catchArg.declarationSourceEnd = catchArg.declarationEnd = catchArg.sourceEnd = methodEnd;
    catchArg.declarationSourceStart = catchArg.modifiersSourceStart = catchArg.sourceStart = methodEnd;

    tryStatement.catchArguments = new Argument[] { catchArg };

    MessageSend sneakyThrowStatement = new MessageSend();
    setGeneratedBy(sneakyThrowStatement, source);
    sneakyThrowStatement.receiver = new QualifiedNameReference(
            new char[][] { "lombok".toCharArray(), "Lombok".toCharArray() }, new long[2], methodEnd, methodEnd);
    setGeneratedBy(sneakyThrowStatement.receiver, source);
    sneakyThrowStatement.receiver.statementEnd = methodEnd;
    sneakyThrowStatement.selector = "sneakyThrow".toCharArray();
    SingleNameReference exRef = new SingleNameReference("$ex".toCharArray(), methodPosEnd);
    setGeneratedBy(exRef, source);
    exRef.statementEnd = methodEnd;
    sneakyThrowStatement.arguments = new Expression[] { exRef };

    // This is the magic fix for rendering issues
    // In org.eclipse.jdt.core.dom.ASTConverter#convert(org.eclipse.jdt.internal.compiler.ast.MessageSend)
    // a new SimpleName is created and the setSourceRange should receive -1, 0. That's why we provide -2L :-)
    sneakyThrowStatement.nameSourcePosition = -2L;

    sneakyThrowStatement.sourceStart = methodEnd;
    sneakyThrowStatement.sourceEnd = sneakyThrowStatement.statementEnd = methodEnd;

    Statement rethrowStatement = new ThrowStatement(sneakyThrowStatement, methodEnd, methodEnd);
    setGeneratedBy(rethrowStatement, source);

    Block block = new Block(0);
    block.sourceStart = methodEnd;
    block.sourceEnd = methodEnd;
    setGeneratedBy(block, source);
    block.statements = new Statement[] { rethrowStatement };

    tryStatement.catchBlocks = new Block[] { block };

    // Positions for in-method generated nodes are special
    tryStatement.sourceStart = method.bodyStart;
    tryStatement.sourceEnd = method.bodyEnd;

    return tryStatement;
}

From source file:lombok.eclipse.handlers.HandleSynchronized.java

License:Open Source License

@Override
public void handle(AnnotationValues<Synchronized> annotation, Annotation source, EclipseNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized");

    int p1 = source.sourceStart - 1;
    int p2 = source.sourceStart - 2;
    long pos = (((long) p1) << 32) | p2;
    EclipseNode methodNode = annotationNode.up();
    if (methodNode == null || methodNode.getKind() != Kind.METHOD
            || !(methodNode.get() instanceof MethodDeclaration)) {
        annotationNode.addError("@Synchronized is legal only on methods.");
        return;//from   ww  w.ja v a2s.com
    }

    MethodDeclaration method = (MethodDeclaration) methodNode.get();
    if (method.isAbstract()) {
        annotationNode.addError("@Synchronized is legal only on concrete methods.");
        return;
    }

    char[] lockName = createLockField(annotation, annotationNode, method.isStatic(), true);
    if (lockName == null)
        return;
    if (method.statements == null)
        return;

    Block block = new Block(0);
    setGeneratedBy(block, source);
    block.statements = method.statements;

    // Positions for in-method generated nodes are special
    block.sourceEnd = method.bodyEnd;
    block.sourceStart = method.bodyStart;

    Expression lockVariable;
    if (method.isStatic())
        lockVariable = new QualifiedNameReference(
                new char[][] { methodNode.up().getName().toCharArray(), lockName }, new long[] { pos, pos }, p1,
                p2);
    else {
        lockVariable = new FieldReference(lockName, pos);
        ThisReference thisReference = new ThisReference(p1, p2);
        setGeneratedBy(thisReference, source);
        ((FieldReference) lockVariable).receiver = thisReference;
    }
    setGeneratedBy(lockVariable, source);

    method.statements = new Statement[] { new SynchronizedStatement(lockVariable, block, 0, 0) };

    // Positions for in-method generated nodes are special
    method.statements[0].sourceEnd = method.bodyEnd;
    method.statements[0].sourceStart = method.bodyStart;

    setGeneratedBy(method.statements[0], source);

    methodNode.rebuild();
}

From source file:lombok.eclipse.handlers.singulars.EclipseJavaUtilMapSingularizer.java

License:Open Source License

private void generatePluralMethod(TypeReference returnType, Statement returnStatement, SingularData data,
        EclipseNode builderType, boolean fluent) {
    MethodDeclaration md = new MethodDeclaration(
            ((CompilationUnitDeclaration) builderType.top().get()).compilationResult);
    md.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
    md.modifiers = ClassFileConstants.AccPublic;

    String pN = new String(data.getPluralName());
    char[] keyFieldName = (pN + "$key").toCharArray();
    char[] valueFieldName = (pN + "$value").toCharArray();

    List<Statement> statements = new ArrayList<Statement>();
    statements.add(createConstructBuilderVarIfNeeded(data, builderType, true));

    char[] entryName = "$lombokEntry".toCharArray();

    TypeReference forEachType = new QualifiedTypeReference(JAVA_UTIL_MAP_ENTRY, NULL_POSS);
    forEachType = addTypeArgs(2, true, builderType, forEachType, data.getTypeArgs());

    MessageSend keyArg = new MessageSend();
    keyArg.receiver = new SingleNameReference(entryName, 0L);
    keyArg.selector = "getKey".toCharArray();
    MessageSend addKey = new MessageSend();
    FieldReference thisDotKeyField = new FieldReference(keyFieldName, 0L);
    thisDotKeyField.receiver = new ThisReference(0, 0);
    addKey.receiver = thisDotKeyField;//from w  w w .j  a  v  a  2s.c o m
    addKey.selector = new char[] { 'a', 'd', 'd' };
    addKey.arguments = new Expression[] { keyArg };

    MessageSend valueArg = new MessageSend();
    valueArg.receiver = new SingleNameReference(entryName, 0L);
    valueArg.selector = "getValue".toCharArray();
    MessageSend addValue = new MessageSend();
    FieldReference thisDotValueField = new FieldReference(valueFieldName, 0L);
    thisDotValueField.receiver = new ThisReference(0, 0);
    addValue.receiver = thisDotValueField;
    addValue.selector = new char[] { 'a', 'd', 'd' };
    addValue.arguments = new Expression[] { valueArg };

    LocalDeclaration elementVariable = new LocalDeclaration(entryName, 0, 0);
    elementVariable.type = forEachType;
    ForeachStatement forEach = new ForeachStatement(elementVariable, 0);
    MessageSend invokeEntrySet = new MessageSend();
    invokeEntrySet.selector = new char[] { 'e', 'n', 't', 'r', 'y', 'S', 'e', 't' };
    invokeEntrySet.receiver = new SingleNameReference(data.getPluralName(), 0L);
    forEach.collection = invokeEntrySet;
    Block forEachContent = new Block(0);
    forEachContent.statements = new Statement[] { addKey, addValue };
    forEach.action = forEachContent;
    statements.add(forEach);
    if (returnStatement != null)
        statements.add(returnStatement);

    md.statements = statements.toArray(new Statement[statements.size()]);

    TypeReference paramType = new QualifiedTypeReference(JAVA_UTIL_MAP, NULL_POSS);
    paramType = addTypeArgs(2, true, builderType, paramType, data.getTypeArgs());
    Argument param = new Argument(data.getPluralName(), 0, paramType, 0);
    md.arguments = new Argument[] { param };
    md.returnType = returnType;
    md.selector = fluent ? data.getPluralName()
            : HandlerUtil.buildAccessorName("putAll", new String(data.getPluralName())).toCharArray();

    data.setGeneratedByRecursive(md);
    injectMethod(builderType, md);
}