Java 类org.eclipse.jdt.core.dom.AST 实例源码

项目:gw4e.project    文件:ClassExtension.java   
/**
 * @param methodname
 * @return
 */
public FieldDeclaration getField(   ) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    String s = getStaticVariable ( );
    if (s==null) return null;
    parser.setSource(s.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(FieldDeclaration node) {
            field = node;
            return true;
        }
    });      
    return field;
}
项目:gw4e.project    文件:ClassExtension.java   
/**
 * @return
 */
public NormalAnnotation getGraphWalkerClassAnnotation() {
    String source = getSource ();
    if(source==null) return null;
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(NormalAnnotation node) {
            annotation = node;
            return true;
        }
    });
    if (this.generateAnnotation) return annotation;
    return null;
}
项目:gw4e.project    文件:ClassExtension.java   
public NormalAnnotation getGeneratedClassAnnotation() {
    String source = getGeneratedAnnotationSource ();
    if(source==null) return null;
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(NormalAnnotation node) {
            annotation = node;
            return true;
        }
    });
    return annotation;

}
项目:bayou    文件:Parser.java   
public void parse() throws ParseException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source.toCharArray());
    Map<String, String> options = JavaCore.getOptions();
    options.put("org.eclipse.jdt.core.compiler.source", "1.8");
    parser.setCompilerOptions(options);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setUnitName("Program.java");
    parser.setEnvironment(new String[] { classpath != null? classpath : "" },
            new String[] { "" }, new String[] { "UTF-8" }, true);
    parser.setResolveBindings(true);
    cu = (CompilationUnit) parser.createAST(null);

    List<IProblem> problems = Arrays.stream(cu.getProblems()).filter(p ->
                                        p.isError() &&
                                        p.getID() != IProblem.PublicClassMustMatchFileName && // we use "Program.java"
                                        p.getID() != IProblem.ParameterMismatch // Evidence varargs
                                    ).collect(Collectors.toList());
    if (problems.size() > 0)
        throw new ParseException(problems);
}
项目:java-driver    文件:GoGen.java   
private static List<String> structuralPropertyNamesOf(final List<Class<? extends ASTNode>> nodes) {
    final List<String> names = new ArrayList<>();
    for (final Class<? extends ASTNode> node : nodes) {
        try {
            final Method m = node.getDeclaredMethod("propertyDescriptors", int.class);
            final List l = (List) m.invoke(null, AST.JLS8);
            for (final Object o : l) {
                final StructuralPropertyDescriptor d = (StructuralPropertyDescriptor) o;
                names.add(d.getId());
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
            throw new RuntimeException("unexpected exception", ex);
        }
    }
    return names;
}
项目:java-driver    文件:eclipseParser.java   
/**
 * Creates a new EclipseParser
 *
 * @param sourceFile String of source file to read
 * @param outJ       JSON parsed out
 * @throws IOException when file can't be opened or errors in reading/writing
 */
public EclipseParser(String sourceFile, PrintStream outJ, boolean prettyprint) throws IOException {

    File file = new File(sourceFile);
    final BufferedReader reader = new BufferedReader(new FileReader(file));
    char[] source = IOUtils.toCharArray(reader);
    reader.close();
    this.parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(source);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    final JsonFactory jsonF = new JsonFactory();
    jG = jsonF.createGenerator(outJ);
    if (prettyprint) {
        jG.setPrettyPrinter(new DefaultPrettyPrinter());
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ASTNode.class, new NodeSerializer());
    mapper.registerModule(module);
}
项目:eclipse.jdt.ls    文件:NewVariableCorrectionProposal.java   
private Type evaluateVariableType(AST ast, ImportRewrite imports, ImportRewriteContext importRewriteContext, IBinding targetContext, TypeLocation location) {
    if (fOriginalNode.getParent() instanceof MethodInvocation) {
        MethodInvocation parent= (MethodInvocation) fOriginalNode.getParent();
        if (parent.getExpression() == fOriginalNode) {
            // _x_.foo() -> guess qualifier type by looking for a type with method 'foo'
            ITypeBinding[] bindings= ASTResolving.getQualifierGuess(fOriginalNode.getRoot(), parent.getName().getIdentifier(), parent.arguments(), targetContext);
            if (bindings.length > 0) {
                return imports.addImport(bindings[0], ast, importRewriteContext, location);
            }
        }
    }

    ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode);
    if (binding != null) {
        if (binding.isWildcardType()) {
            binding= ASTResolving.normalizeWildcardType(binding, isVariableAssigned(), ast);
            if (binding == null) {
                // only null binding applies
                binding= ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
            }
        }

        return imports.addImport(binding, ast, importRewriteContext, location);
    }
    // no binding, find type AST node instead -> ABC a= x-> use 'ABC' as is
    Type type = ASTResolving.guessTypeForReference(ast, fOriginalNode);
    if (type != null) {
        return type;
    }
    if (fVariableKind == CONST_FIELD) {
        return ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
    }
    return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
项目:SparkBuilderGenerator    文件:EmptyBuilderClassGeneratorFragment.java   
public TypeDeclaration createBuilderClass(AST ast, TypeDeclaration originalType) {
    TypeDeclaration builderType = ast.newTypeDeclaration();
    builderType.setName(ast.newSimpleName(getBuilderName(originalType)));

    if (preferencesManager.getPreferenceValue(ADD_GENERATED_ANNOTATION)) {
        generatedAnnotationPopulator.addGeneratedAnnotation(ast, builderType);
    }
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
    builderType.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));

    if (preferencesManager.getPreferenceValue(GENERATE_JAVADOC_ON_BUILDER_CLASS)) {
        Javadoc javadoc = javadocGenerator.generateJavadoc(ast, String.format(Locale.ENGLISH, "Builder to build {@link %s}.", originalType.getName().toString()),
                Collections.emptyMap());
        builderType.setJavadoc(javadoc);
    }

    return builderType;
}
项目:SparkBuilderGenerator    文件:StagedBuilderWithMethodAdderFragment.java   
private Block createWithMethodBody(AST ast, BuilderField builderField) {
    String originalFieldName = builderField.getOriginalFieldName();
    String builderFieldName = builderField.getBuilderFieldName();

    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
项目:SparkBuilderGenerator    文件:RegularBuilderWithMethodAdderFragment.java   
private Block createWithMethodBody(AST ast, String originalFieldName, String builderFieldName) {
    Block newBlock = ast.newBlock();
    ReturnStatement builderReturnStatement = ast.newReturnStatement();
    builderReturnStatement.setExpression(ast.newThisExpression());

    Assignment newAssignment = ast.newAssignment();

    FieldAccess fieldAccess = ast.newFieldAccess();
    fieldAccess.setExpression(ast.newThisExpression());
    fieldAccess.setName(ast.newSimpleName(originalFieldName));
    newAssignment.setLeftHandSide(fieldAccess);
    newAssignment.setRightHandSide(ast.newSimpleName(builderFieldName));

    newBlock.statements().add(ast.newExpressionStatement(newAssignment));
    newBlock.statements().add(builderReturnStatement);
    return newBlock;
}
项目:SparkBuilderGenerator    文件:RegularBuilderWithMethodAdderFragment.java   
private MethodDeclaration createNewWithMethod(AST ast, String fieldName, Block newBlock,
        SingleVariableDeclaration methodParameterDeclaration, TypeDeclaration builderType,
        BuilderField builderField) {
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
    builderMethod.setReturnType2(ast.newSimpleType(
            ast.newName(builderType.getName().getIdentifier())));
    builderMethod.setBody(newBlock);
    builderMethod.parameters().add(methodParameterDeclaration);

    javadocAdder.addJavadocForWithMethod(ast, fieldName, builderMethod);
    if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
        markerAnnotationAttacher.attachNonNull(ast, builderMethod);
    }
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    return builderMethod;
}
项目:SparkBuilderGenerator    文件:StagedBuilderWithMethodDefiniationCreatorFragment.java   
public MethodDeclaration createNewWithMethod(AST ast, BuilderField builderField,
        StagedBuilderProperties nextStage) {
    String fieldName = builderField.getBuilderFieldName();
    MethodDeclaration builderMethod = ast.newMethodDeclaration();
    builderMethod.setName(ast.newSimpleName(builderClassMethodNameGeneratorService.build(fieldName)));
    builderMethod.setReturnType2(ast.newSimpleType(ast.newName(nextStage.getInterfaceName())));
    builderMethod.parameters()
            .add(withMethodParameterCreatorFragment.createWithMethodParameter(ast, builderField.getFieldType(), fieldName));

    if (preferencesManager.getPreferenceValue(ADD_NONNULL_ON_RETURN)) {
        markerAnnotationAttacher.attachNonNull(ast, builderMethod);
    }
    builderMethod.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));

    return builderMethod;
}
项目:SparkBuilderGenerator    文件:StaticMethodInvocationFragment.java   
public MethodInvocation createStaticMethodInvocation(AST ast, String className, String methodName) {
    SimpleName typeName = ast.newSimpleName(className);

    MethodInvocation methodInvocation = ast.newMethodInvocation();
    methodInvocation.setName(ast.newSimpleName(methodName));
    methodInvocation.setExpression(typeName);

    return methodInvocation;
}
项目:eclipse.jdt.ls    文件:AbstractSerialVersionOperation.java   
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
    final ASTRewrite rewrite = cuRewrite.getASTRewrite();
    VariableDeclarationFragment fragment = null;
    for (int i = 0; i < fNodes.length; i++) {
        final ASTNode node = fNodes[i];

        final AST ast = node.getAST();

        fragment = ast.newVariableDeclarationFragment();
        fragment.setName(ast.newSimpleName(NAME_FIELD));

        final FieldDeclaration declaration = ast.newFieldDeclaration(fragment);
        declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
        declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));

        if (!addInitializer(fragment, node)) {
            continue;
        }

        if (fragment.getInitializer() != null) {

            final TextEditGroup editGroup = createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
            if (node instanceof AbstractTypeDeclaration) {
                rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
            } else if (node instanceof AnonymousClassDeclaration) {
                rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
            } else if (node instanceof ParameterizedType) {
                final ParameterizedType type = (ParameterizedType) node;
                final ASTNode parent = type.getParent();
                if (parent instanceof ClassInstanceCreation) {
                    final ClassInstanceCreation creation = (ClassInstanceCreation) parent;
                    final AnonymousClassDeclaration anonymous = creation.getAnonymousClassDeclaration();
                    if (anonymous != null) {
                        rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
                    }
                }
            } else {
                Assert.isTrue(false);
            }

            addLinkedPositions(rewrite, fragment, positionGroups);
        }

        final String comment = CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, "\n" /* StubUtility.getLineDelimiterUsed(fUnit) */);
        if (comment != null && comment.length() > 0 && !"/**\n *\n */\n".equals(comment)) {
            final Javadoc doc = (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
            declaration.setJavadoc(doc);
        }
    }
    if (fragment == null) {
        return;
    }

    positionGroups.setEndPosition(rewrite.track(fragment));
}
项目:SparkBuilderGenerator    文件:NewBuilderAndWithMethodCallCreationFragment.java   
public Block createReturnBlock(AST ast, TypeDeclaration builderType, String withName, String parameterName) {
    Block builderMethodBlock = ast.newBlock();
    ReturnStatement returnStatement = ast.newReturnStatement();
    ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
    newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));

    MethodInvocation withMethodInvocation = ast.newMethodInvocation();
    withMethodInvocation.setExpression(newClassInstanceCreation);
    withMethodInvocation.setName(ast.newSimpleName(withName));
    withMethodInvocation.arguments().add(ast.newSimpleName(parameterName));

    returnStatement.setExpression(withMethodInvocation);
    builderMethodBlock.statements().add(returnStatement);
    return builderMethodBlock;
}
项目:eclipse.jdt.ls    文件:NewMethodCorrectionProposal.java   
@Override
protected void addNewParameters(ASTRewrite rewrite, List<String> takenNames, List<SingleVariableDeclaration> params, ImportRewriteContext context) throws CoreException {
    AST ast= rewrite.getAST();

    List<Expression> arguments= fArguments;

    for (int i= 0; i < arguments.size(); i++) {
        Expression elem= arguments.get(i);
        SingleVariableDeclaration param= ast.newSingleVariableDeclaration();

        // argument type
        String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
        Type type= evaluateParameterType(ast, elem, argTypeKey, context);
        param.setType(type);

        // argument name
        String argNameKey= "arg_name_" + i; //$NON-NLS-1$
        String name= evaluateParameterName(takenNames, elem, type, argNameKey);
        param.setName(ast.newSimpleName(name));

        params.add(param);
    }
}
项目:code    文件:WorkspaceUtilities.java   
/**
 * Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
 * source code.
 * 
 * @param compilationUnits the list of compilation units to parse
 * @return the mapping from compilation unit to the AST roots of each
 */
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
    if (compilationUnits == null) {
        throw new CrystalRuntimeException("null list of compilation units");
    }

    ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
    final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);
    parser.setProject(WorkspaceUtilities.javaProject);
    parser.createASTs(compUnits, new String[0], new ASTRequestor() {
        @Override
           public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
            parsedCompilationUnits.put(unit, node);
        }

        @Override
           public final void acceptBinding(final String key, final IBinding binding) {
            // Do nothing
        }
    }, null);
    return parsedCompilationUnits;
}
项目:eclipse.jdt.ls    文件:NewAnnotationMemberProposal.java   
private Type getNewType(ASTRewrite rewrite) {
    AST ast= rewrite.getAST();
    Type newTypeNode= null;
    ITypeBinding binding= null;
    if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
        Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue();
        binding= value.resolveTypeBinding();
    } else if (fInvocationNode instanceof Expression) {
        binding= ((Expression) fInvocationNode).resolveTypeBinding();
    }
    if (binding != null) {
        ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite());
        newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext);
    }
    if (newTypeNode == null) {
        newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
    }
    return newTypeNode;
}
项目:SparkBuilderGenerator    文件:StagedBuilderCreationWithMethodAdder.java   
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType,
        StagedBuilderProperties currentStage) {
    AST ast = modificationDomain.getAst();
    ListRewrite listRewrite = modificationDomain.getListRewrite();
    BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0);

    StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage);
    MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage);
    staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));

    String parameterName = firstField.getBuilderFieldName();
    String withMethodName = staticWithMethod.getName().toString();
    Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName);

    javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod);

    staticWithMethod.setBody(block);

    listRewrite.insertLast(staticWithMethod, null);
}
项目:eclipse.jdt.ls    文件:JavadocTagsSubProcessor.java   
private void insertAllMissingTypeTags(ASTRewrite rewriter, TypeDeclaration typeDecl) {
    AST ast= typeDecl.getAST();
    Javadoc javadoc= typeDecl.getJavadoc();
    ListRewrite tagsRewriter= rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY);

    List<TypeParameter> typeParams= typeDecl.typeParameters();
    for (int i= typeParams.size() - 1; i >= 0; i--) {
        TypeParameter decl= typeParams.get(i);
        String name= '<' + decl.getName().getIdentifier() + '>';
        if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) {
            TagElement newTag= ast.newTagElement();
            newTag.setTagName(TagElement.TAG_PARAM);
            TextElement text= ast.newTextElement();
            text.setText(name);
            newTag.fragments().add(text);
            insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); //$NON-NLS-1$
            insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl));
        }
    }
}
项目:code    文件:WorkspaceUtilities.java   
/**
 * Goes through a list of compilation units and parses them. The act of parsing creates the AST structures from the
 * source code.
 * 
 * @param compilationUnits the list of compilation units to parse
 * @return the mapping from compilation unit to the AST roots of each
 */
public static Map<ICompilationUnit, ASTNode> parseCompilationUnits(List<ICompilationUnit> compilationUnits) {
    if (compilationUnits == null) {
        throw new CrystalRuntimeException("null list of compilation units");
    }

    ICompilationUnit[] compUnits = compilationUnits.toArray(new ICompilationUnit[0]);
    final Map<ICompilationUnit, ASTNode> parsedCompilationUnits = new HashMap<ICompilationUnit, ASTNode>();
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setResolveBindings(true);
    parser.setProject(WorkspaceUtilities.javaProject);
    parser.createASTs(compUnits, new String[0], new ASTRequestor() {
        @Override
           public final void acceptAST(final ICompilationUnit unit, final CompilationUnit node) {
            parsedCompilationUnits.put(unit, node);
        }

        @Override
           public final void acceptBinding(final String key, final IBinding binding) {
            // Do nothing
        }
    }, null);
    return parsedCompilationUnits;
}
项目:eclipse.jdt.ls    文件:CorrectMainTypeNameProposal.java   
@Override
protected ASTRewrite getRewrite() throws CoreException {
    CompilationUnit astRoot= fContext.getASTRoot();

    AST ast= astRoot.getAST();
    ASTRewrite rewrite= ASTRewrite.create(ast);

    AbstractTypeDeclaration decl= findTypeDeclaration(astRoot.types(), fOldName);
    if (decl != null) {
        ASTNode[] sameNodes= LinkedNodeFinder.findByNode(astRoot, decl.getName());
        for (int i= 0; i < sameNodes.length; i++) {
            rewrite.replace(sameNodes[i], ast.newSimpleName(fNewName), null);
        }
    }
    return rewrite;
}
项目:eclipse.jdt.ls    文件:StatementRewrite.java   
@Override
protected void handleOneMany(ASTNode[] replacements, TextEditGroup description) {
    AST ast= fToReplace[0].getAST();
    // to replace == 1, but more than one replacement. Have to check if we
    // need to insert a block to not change structure
    if (ASTNodes.isControlStatementBody(fDescriptor)) {
        Block block= ast.newBlock();
        ListRewrite statements= fRewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
        for (int i= 0; i < replacements.length; i++) {
            statements.insertLast(replacements[i], description);
        }
        fRewrite.replace(fToReplace[0], block, description);
    } else {
        ListRewrite container= fRewrite.getListRewrite(fToReplace[0].getParent(), (ChildListPropertyDescriptor)fDescriptor);
        container.replace(fToReplace[0], replacements[0], description);
        for (int i= 1; i < replacements.length; i++) {
            container.insertAfter(replacements[i], replacements[i - 1], description);
        }
    }
}
项目:eclipse.jdt.ls    文件:DimensionRewrite.java   
/**
 * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of <code>type</code>
 * and adds <code>extraDimensions</code> to it.
 *
 * @param type the type to copy
 * @param extraDimensions the dimensions to add
 * @param rewrite the ASTRewrite with which to create new nodes
 * @return the copy target with added dimensions
 */
public static Type copyTypeAndAddDimensions(Type type, List<Dimension> extraDimensions, ASTRewrite rewrite) {
    AST ast= rewrite.getAST();
    if (extraDimensions.isEmpty()) {
        return (Type) rewrite.createCopyTarget(type);
    }

    ArrayType result;
    if (type instanceof ArrayType) {
        ArrayType arrayType= (ArrayType) type;
        Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType());
        result= ast.newArrayType(varElementType, 0);
        result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
        result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite));
    } else {
        Type elementType= (Type) rewrite.createCopyTarget(type);
        result= ast.newArrayType(elementType, 0);
        result.dimensions().addAll(copyDimensions(extraDimensions, rewrite));
    }
    return result;
}
项目:eclipse.jdt.ls    文件:ReturnTypeSubProcessor.java   
public ITypeBinding getTypeBinding(AST ast) {
    boolean couldBeObject= false;
    for (int i= 0; i < fResult.size(); i++) {
        ReturnStatement node= fResult.get(i);
        Expression expr= node.getExpression();
        if (expr != null) {
            ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
            if (binding != null) {
                return binding;
            } else {
                couldBeObject= true;
            }
        } else {
            return ast.resolveWellKnownType("void"); //$NON-NLS-1$
        }
    }
    if (couldBeObject) {
        return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
    }
    return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
项目:eclipse.jdt.ls    文件:ASTNodeFactory.java   
private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) {
    IMethodBinding method= lambdaExpression.resolveMethodBinding();
    if (method != null) {
        ITypeBinding[] parameterTypes= method.getParameterTypes();
        int index= lambdaExpression.parameters().indexOf(declaration);
        ITypeBinding typeBinding= parameterTypes[index];
        if (importRewrite != null) {
            return importRewrite.addImport(typeBinding, ast, context);
        } else {
            String qualifiedName= typeBinding.getQualifiedName();
            if (qualifiedName.length() > 0) {
                return newType(ast, qualifiedName);
            }
        }
    }
    // fall-back
    return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
项目:eclipse.jdt.ls    文件:ASTNodeFactory.java   
/**
 * Returns the new type node representing the return type of <code>lambdaExpression</code>
 * including the extra dimensions.
 *
 * @param lambdaExpression the lambda expression
 * @param ast the AST to create the return type with
 * @param importRewrite the import rewrite to use, or <code>null</code>
 * @param context the import rewrite context, or <code>null</code>
 * @return a new type node created with the given AST representing the return type of
 *         <code>lambdaExpression</code>
 *
 * @since 3.10
 */
public static Type newReturnType(LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) {
    IMethodBinding method= lambdaExpression.resolveMethodBinding();
    if (method != null) {
        ITypeBinding returnTypeBinding= method.getReturnType();
        if (importRewrite != null) {
            return importRewrite.addImport(returnTypeBinding, ast);
        } else {
            String qualifiedName= returnTypeBinding.getQualifiedName();
            if (qualifiedName.length() > 0) {
                return newType(ast, qualifiedName);
            }
        }
    }
    // fall-back
    return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
项目:eclipse.jdt.ls    文件:ASTNodeFactory.java   
/**
 * Create a Type suitable as the creationType in a ClassInstanceCreation expression.
 * @param ast The AST to create the nodes for.
 * @param typeBinding binding representing the given class type
 * @param importRewrite the import rewrite to use
 * @param importContext the import context used to determine which (null) annotations to consider
 * @return a Type suitable as the creationType in a ClassInstanceCreation expression.
 */
public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) {
    if (typeBinding.isParameterizedType()) {
        Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext);
        IAnnotationBinding[] typeAnnotations= importContext.removeRedundantTypeAnnotations(typeBinding.getTypeAnnotations(), TypeLocation.NEW, typeBinding);
        for (IAnnotationBinding typeAnnotation : typeAnnotations) {
            ((AnnotatableType)baseType).annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext));
        }
        ParameterizedType parameterizedType= ast.newParameterizedType(baseType);
        for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) {
            typeArgument= StubUtility2.replaceWildcardsAndCaptures(typeArgument);
            parameterizedType.typeArguments().add(importRewrite.addImport(typeArgument, ast, importContext, TypeLocation.TYPE_ARGUMENT));
        }
        return parameterizedType;
    } else {
        return importRewrite.addImport(typeBinding, ast, importContext, TypeLocation.NEW);
    }
}
项目:eclipse.jdt.ls    文件:StubUtility2.java   
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) {
    ITypeBinding[] typeParams= binding.getTypeParameters();
    List<TypeParameter> typeParameters= decl.typeParameters();
    for (int i= 0; i < typeParams.length; i++) {
        ITypeBinding curr= typeParams[i];
        TypeParameter newTypeParam= ast.newTypeParameter();
        newTypeParam.setName(ast.newSimpleName(curr.getName()));
        ITypeBinding[] typeBounds= curr.getTypeBounds();
        if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$
            List<Type> newTypeBounds= newTypeParam.typeBounds();
            for (int k= 0; k < typeBounds.length; k++) {
                newTypeBounds.add(imports.addImport(typeBounds[k], ast, context, TypeLocation.TYPE_BOUND));
            }
        }
        typeParameters.add(newTypeParam);
    }
}
项目:BUILD_file_generator    文件:ReferencedClassesParser.java   
private static ASTParser createCompilationUnitParser() {
  ASTParser parser = ASTParser.newParser(AST.JLS8);
  Map options = JavaCore.getOptions();
  JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
  parser.setCompilerOptions(options);
  parser.setKind(ASTParser.K_COMPILATION_UNIT);
  return parser;
}
项目:BUILD_file_generator    文件:ReferencedClassesParserTest.java   
@Test
public void testExtractTypeNameWithoutGenerics() {
  AST ast = AST.newAST(AST.JLS4);
  org.eclipse.jdt.core.dom.SimpleName entry = ast.newSimpleName("Entry");
  ParameterizedType map = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Map")));
  map.typeArguments().add(ast.newSimpleType(ast.newSimpleName("Foo")));
  QualifiedType type = ast.newQualifiedType(map, entry);
  assertThat(type.toString()).isEqualTo("Map<Foo>.Entry");
  assertThat(ReferencedClassesParser.extractTypeNameWithoutGenerics(type)).isEqualTo("Map.Entry");
}
项目:gw4e.project    文件:ClassExtension.java   
/**
 * @param methodname
 * @return
 */
public ExpressionStatement getBodyMethod(String methodname) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setSource(getBodyMethodSource (methodname).toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {
        public boolean visit(ExpressionStatement node) {
            expression = node;
            return true;
        }
    });      
    return expression;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param compilationUnit
 * @param progressMonitor
 * @return
 * @throws JavaModelException
 */

public static CompilationUnit parse(final ICompilationUnit cu) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(cu);
    parser.setResolveBindings(true);
    parser.setEnvironment(null, null, null, true);
    parser.setBindingsRecovery(true);
    final CompilationUnit ast = (CompilationUnit) parser.createAST(new NullProgressMonitor());

    return ast;
}
项目:gw4e.project    文件:JDTManager.java   
/**
 * @param cu
 * @param rewrite
 * @param ast
 * @param pkgDeclaration
 */
private static void addPackageDeclaration(CompilationUnit cu, ASTRewrite rewrite, AST ast,
        String[] pkgDeclaration) {
    PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
    Name name = ast.newName(pkgDeclaration);
    packageDeclaration.setName(name);
    rewrite.set(cu, CompilationUnit.PACKAGE_PROPERTY, packageDeclaration, null);

}
项目:gw4e.project    文件:JDTManager.java   
/**
 * Rename a class name into another name
 * 
 * @param file
 * @param oldClassname
 * @param newName
 * @param monitor
 * @return
 * @throws MalformedTreeException
 * @throws BadLocationException
 * @throws CoreException
 */
public static IFile renameClass(IFile file, String oldClassname, String newName, IProgressMonitor monitor)
        throws MalformedTreeException, BadLocationException, CoreException {
    Display.getDefault().syncExec(new Runnable() {

        @Override
        public void run() {
            try {

                ICompilationUnit unit = JavaCore.createCompilationUnitFrom(file);
                CompilationUnit cu = parse(unit);
                AST ast = cu.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);

                String classname = file.getName();
                classname = classname.substring(0, classname.indexOf("."));
                final String clazz = classname;
                ASTVisitor visitor = new ASTVisitor() {
                    public boolean visit(SimpleName node) {
                        String s = node.getIdentifier();
                        if (oldClassname.equalsIgnoreCase(s)) {
                            rewrite.replace(node, ast.newSimpleName(newName), null);
                        }
                        return true;
                    }
                };
                cu.accept(visitor);

                addPackageDeclarationIfNeeded(file, cu, rewrite, ast);
                file.refreshLocal(IResource.DEPTH_ZERO, monitor);
                cu = parse(JavaCore.createCompilationUnitFrom(file));
                save(cu, rewrite);
            } catch (Exception e) {
                ResourceManager.logException(e);
            }
        }
    });
    return file;
}
项目:bayou    文件:Driver.java   
private CompilationUnit createCompilationUnit(String classpath) throws IOException {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    File input = new File(options.cmdLine.getOptionValue("input-file"));

    parser.setSource(FileUtils.readFileToString(input, "utf-8").toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setUnitName("Program.java");
    parser.setEnvironment(new String[] { classpath != null? classpath : "" },
            new String[] { "" }, new String[] { "UTF-8" }, true);
    parser.setResolveBindings(true);

    return (CompilationUnit) parser.createAST(null);
}
项目:vertigo-chroma-kspplugin    文件:JdtUtils.java   
public static CompilationUnit parseAST(ICompilationUnit unit) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    parser.setSource(unit);
    parser.setResolveBindings(true);
    return (CompilationUnit) parser.createAST(null /* IProgressMonitor */);
}
项目:junit2spock    文件:ASTNodeFactory.java   
public <T extends ASTNode> T clone(T expression) {
    if (expression == null) {
        return null;
    }
    Method method = findMethod(ASTNode.class, "clone", AST.class);
    makeAccessible(method);
    return (T) invokeMethod(method, expression, ast.get());
}
项目:RefDiff    文件:SDModelBuilder.java   
private static ASTParser buildAstParser(String[] sourceFolders) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(new String[0], sourceFolders, null, true);
    // parser.setEnvironment(new String[0], new String[]{"tmp\\refactoring-toy-example\\src"}, null, false);
    return parser;
}
项目:RefDiff    文件:SDModelBuilder.java   
private static ASTParser buildAstParser(String[] sourceFolders) {
    ASTParser parser = ASTParser.newParser(AST.JLS8);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    Map options = JavaCore.getOptions();
    JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
    parser.setCompilerOptions(options);
    parser.setResolveBindings(true);
    parser.setBindingsRecovery(true);
    parser.setEnvironment(new String[0], sourceFolders, null, true);
    //parser.setEnvironment(new String[0], new String[]{"tmp\\refactoring-toy-example\\src"}, null, false);
    return parser;
}