Search in sources :

Example 6 with PackageDeclaration

use of org.eclipse.jdt.core.dom.PackageDeclaration in project evosuite by EvoSuite.

the class CodeGenerator method generateCode.

// FIXME specifying classes here might not be needed anymore, if we only instrument observed classes...
@SuppressWarnings("unchecked")
private CompilationUnit generateCode(final String cuName, final String packageName, final boolean postprocessing, final Class<?>... observedClasses) {
    if (cuName == null || cuName.isEmpty()) {
        throw new IllegalArgumentException("Illegal compilation unit name: " + cuName);
    }
    if (observedClasses == null || observedClasses.length == 0) {
        throw new IllegalArgumentException("No observed classes specified");
    }
    if (packageName == null) {
        throw new NullPointerException("package name must not be null");
    }
    // --- 1. step: extract class names
    final HashSet<String> observedClassNames = new HashSet<String>();
    for (int i = 0; i < observedClasses.length; i++) {
        observedClassNames.add(observedClasses[i].getName());
    }
    // --- 2. step: get all oids of the instances of the observed classes
    // NOTE: They are implicitly sorted by INIT_REC_NO because of the natural object creation order captured by the
    // instrumentation
    final TIntArrayList targetOIDs = new TIntArrayList();
    final int numInfoRecs = this.log.oidClassNames.size();
    for (int i = 0; i < numInfoRecs; i++) {
        if (observedClassNames.contains(this.log.oidClassNames.get(i))) {
            targetOIDs.add(this.log.oids.getQuick(i));
        }
    }
    // --- 3. step: init compilation unit
    final AST ast = AST.newAST(AST.JLS3);
    CompilationUnit cu = ast.newCompilationUnit();
    // package declaration
    final PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newName(packageName.split("\\.")));
    cu.setPackage(p1);
    // import specifications
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "org", "junit", "Test" }));
    cu.imports().add(id);
    // class declaration
    final TypeDeclaration td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName(cuName));
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    cu.types().add(td);
    // test method construction
    final MethodDeclaration md = ast.newMethodDeclaration();
    md.setName(ast.newSimpleName("test"));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    // sets @Test annotation to test method
    final NormalAnnotation annotation = ast.newNormalAnnotation();
    annotation.setTypeName(ast.newSimpleName("Test"));
    md.modifiers().add(annotation);
    // sets method to public
    md.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.bodyDeclarations().add(md);
    final Block block = ast.newBlock();
    md.setBody(block);
    // no invocations on objects of observed classes -> return empty but compilable CompilationUnit
    if (targetOIDs.isEmpty()) {
        return cu;
    }
    // --- 4. step: generating code starting with OID with lowest log rec no.
    final int numLogRecords = this.log.objectIds.size();
    int currentOID = targetOIDs.getQuick(0);
    try {
        // TODO knowing last logRecNo for termination criterion belonging to an observed instance would prevent processing unnecessary statements
        for (int currentRecord = this.log.oidRecMapping.get(currentOID); currentRecord < numLogRecords; currentRecord++) {
            currentOID = this.log.objectIds.getQuick(currentRecord);
            if (targetOIDs.contains(currentOID)) {
                this.restorceCodeFromLastPosTo(packageName, currentOID, currentRecord, postprocessing, ast, block);
                // forward to end of method call sequence
                currentRecord = findEndOfMethod(currentRecord, currentOID);
                // each method call is considered as object state modification -> so save last object modification
                log.updateWhereObjectWasInitializedFirst(currentOID, currentRecord);
            }
        }
    } catch (Exception e) {
        // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"+this.log);
        throw new RuntimeException(e.getMessage(), e);
    }
    if (this.isXStreamNeeded) {
        id = ast.newImportDeclaration();
        id.setName(ast.newName(new String[] { "com", "thoughtworks", "xstream", "XStream" }));
        cu.imports().add(id);
        // create XSTREAM constant: private static final XStream XSTREAM = new XStream();
        final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment();
        vd.setName(ast.newSimpleName("XSTREAM"));
        final ClassInstanceCreation ci = ast.newClassInstanceCreation();
        ci.setType(this.createAstType("XStream", ast));
        vd.setInitializer(ci);
        final FieldDeclaration xstreamConst = ast.newFieldDeclaration(vd);
        xstreamConst.setType(this.createAstType("XStream", ast));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.PRIVATE_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD));
        xstreamConst.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD));
        td.bodyDeclarations().add(xstreamConst);
        this.isXStreamNeeded = false;
    }
    // -- creates utility method to set field value via reflections
    if (this.isSetFieldMethodNeeded) {
        this.createSetFieldMethod(td, cu, ast);
        this.isSetFieldMethodNeeded = false;
    }
    // -- creates utility method to get field value via reflections
    if (this.isGetFieldMethodNeeded) {
        this.createGetFieldMethod(td, cu, ast);
        this.isGetFieldMethodNeeded = false;
    }
    // -- creates utility method to call method via reflections
    if (this.isCallMethodMethodNeeded) {
        this.createCallMethod(td, cu, ast);
        this.isCallMethodMethodNeeded = false;
    }
    // -- creates utility method to call constructor via reflections
    if (this.isNewInstanceMethodNeeded) {
        this.createNewInstanceMethod(td, cu, ast);
        this.isNewInstanceMethodNeeded = false;
    }
    return cu;
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) TIntArrayList(gnu.trove.list.array.TIntArrayList) FieldDeclaration(org.eclipse.jdt.core.dom.FieldDeclaration) VariableDeclarationFragment(org.eclipse.jdt.core.dom.VariableDeclarationFragment) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) Block(org.eclipse.jdt.core.dom.Block) TypeDeclaration(org.eclipse.jdt.core.dom.TypeDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) HashSet(java.util.HashSet) TIntHashSet(gnu.trove.set.hash.TIntHashSet)

Example 7 with PackageDeclaration

use of org.eclipse.jdt.core.dom.PackageDeclaration in project evosuite by EvoSuite.

the class JUnitCodeGenerator method before.

@SuppressWarnings("unchecked")
@Override
public void before(CaptureLog log) {
    ast = AST.newAST(AST.JLS3);
    cu = ast.newCompilationUnit();
    // package declaration
    final PackageDeclaration p1 = ast.newPackageDeclaration();
    p1.setName(ast.newName(packageName.split("\\.")));
    cu.setPackage(p1);
    // import specifications
    ImportDeclaration id = ast.newImportDeclaration();
    id.setName(ast.newName(new String[] { "org", "junit", "Test" }));
    cu.imports().add(id);
    // class declaration
    td = ast.newTypeDeclaration();
    td.setName(ast.newSimpleName(cuName));
    td.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    cu.types().add(td);
    // test method construction
    final MethodDeclaration md = ast.newMethodDeclaration();
    md.setName(ast.newSimpleName("test"));
    md.thrownExceptions().add(ast.newSimpleName("Exception"));
    // sets @Test annotation to test method
    final NormalAnnotation annotation = ast.newNormalAnnotation();
    annotation.setTypeName(ast.newSimpleName("Test"));
    md.modifiers().add(annotation);
    // sets method to public
    md.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    td.bodyDeclarations().add(md);
    methodBlock = ast.newBlock();
    md.setBody(methodBlock);
}
Also used : MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) NormalAnnotation(org.eclipse.jdt.core.dom.NormalAnnotation) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 8 with PackageDeclaration

use of org.eclipse.jdt.core.dom.PackageDeclaration in project eclipse.jdt.ls by eclipse.

the class TypeContextChecker method createStubTypeContext.

public static StubTypeContext createStubTypeContext(ICompilationUnit cu, CompilationUnit root, int focalPosition) throws CoreException {
    StringBuilder bufBefore = new StringBuilder();
    StringBuilder bufAfter = new StringBuilder();
    int introEnd = 0;
    PackageDeclaration pack = root.getPackage();
    if (pack != null) {
        introEnd = pack.getStartPosition() + pack.getLength();
    }
    List<ImportDeclaration> imports = root.imports();
    if (imports.size() > 0) {
        ImportDeclaration lastImport = imports.get(imports.size() - 1);
        introEnd = lastImport.getStartPosition() + lastImport.getLength();
    }
    bufBefore.append(cu.getBuffer().getText(0, introEnd));
    fillWithTypeStubs(bufBefore, bufAfter, focalPosition, root.types());
    bufBefore.append(' ');
    bufAfter.insert(0, ' ');
    return new StubTypeContext(cu, bufBefore.toString(), bufAfter.toString());
}
Also used : ImportDeclaration(org.eclipse.jdt.core.dom.ImportDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 9 with PackageDeclaration

use of org.eclipse.jdt.core.dom.PackageDeclaration in project eclipse.jdt.ls by eclipse.

the class JDTUtils method getPackageName.

public static String getPackageName(IJavaProject javaProject, String fileContent) {
    if (fileContent == null) {
        return "";
    }
    // TODO probably not the most efficient way to get the package name as this reads the whole file;
    char[] source = fileContent.toCharArray();
    ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
    parser.setProject(javaProject);
    parser.setIgnoreMethodBodies(true);
    parser.setSource(source);
    CompilationUnit ast = (CompilationUnit) parser.createAST(null);
    PackageDeclaration pkg = ast.getPackage();
    return (pkg == null || pkg.getName() == null) ? "" : pkg.getName().getFullyQualifiedName();
}
Also used : CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ASTParser(org.eclipse.jdt.core.dom.ASTParser) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration)

Example 10 with PackageDeclaration

use of org.eclipse.jdt.core.dom.PackageDeclaration in project eclipse.jdt.ls by eclipse.

the class ChangeUtil method updatePackageStatement.

private static boolean updatePackageStatement(CompilationUnit astCU, String pkgName, ASTRewrite rewriter, ICompilationUnit cu) throws JavaModelException {
    boolean defaultPackage = pkgName.isEmpty();
    AST ast = astCU.getAST();
    if (defaultPackage) {
        // remove existing package statement
        PackageDeclaration pkg = astCU.getPackage();
        if (pkg == null) {
            return false;
        }
        int pkgStart;
        Javadoc javadoc = pkg.getJavadoc();
        if (javadoc != null) {
            pkgStart = javadoc.getStartPosition() + javadoc.getLength() + 1;
        } else {
            pkgStart = pkg.getStartPosition();
        }
        int extendedStart = astCU.getExtendedStartPosition(pkg);
        if (pkgStart != extendedStart) {
            String commentSource = cu.getSource().substring(extendedStart, pkgStart);
            ASTNode comment = rewriter.createStringPlaceholder(commentSource, ASTNode.PACKAGE_DECLARATION);
            rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, comment, null);
        } else {
            rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, null, null);
        }
    } else {
        org.eclipse.jdt.core.dom.PackageDeclaration pkg = astCU.getPackage();
        if (pkg != null) {
            // Skip if the new package name is same as the existing package name.
            if (Objects.equals(pkg.getName().getFullyQualifiedName(), pkgName)) {
                return false;
            }
            // rename package statement
            Name name = ast.newName(pkgName);
            rewriter.set(pkg, PackageDeclaration.NAME_PROPERTY, name, null);
        } else {
            // create new package statement
            pkg = ast.newPackageDeclaration();
            pkg.setName(ast.newName(pkgName));
            rewriter.set(astCU, CompilationUnit.PACKAGE_PROPERTY, pkg, null);
        }
    }
    return true;
}
Also used : PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) AST(org.eclipse.jdt.core.dom.AST) ASTNode(org.eclipse.jdt.core.dom.ASTNode) Javadoc(org.eclipse.jdt.core.dom.Javadoc) IPackageDeclaration(org.eclipse.jdt.core.IPackageDeclaration) PackageDeclaration(org.eclipse.jdt.core.dom.PackageDeclaration) Name(org.eclipse.jdt.core.dom.Name)

Aggregations

PackageDeclaration (org.eclipse.jdt.core.dom.PackageDeclaration)17 ImportDeclaration (org.eclipse.jdt.core.dom.ImportDeclaration)9 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)8 HashSet (java.util.HashSet)6 ASTVisitor (org.eclipse.jdt.core.dom.ASTVisitor)5 MethodDeclaration (org.eclipse.jdt.core.dom.MethodDeclaration)5 ASTNode (org.eclipse.jdt.core.dom.ASTNode)4 ASTParser (org.eclipse.jdt.core.dom.ASTParser)4 FieldDeclaration (org.eclipse.jdt.core.dom.FieldDeclaration)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Set (java.util.Set)3 Name (org.eclipse.jdt.core.dom.Name)3 NormalAnnotation (org.eclipse.jdt.core.dom.NormalAnnotation)3 SingleVariableDeclaration (org.eclipse.jdt.core.dom.SingleVariableDeclaration)3 VariableDeclarationFragment (org.eclipse.jdt.core.dom.VariableDeclarationFragment)3 HashMap (java.util.HashMap)2 Nullable (javax.annotation.Nullable)2 AST (org.eclipse.jdt.core.dom.AST)2 AbstractTypeDeclaration (org.eclipse.jdt.core.dom.AbstractTypeDeclaration)2