private void printImports(CompilationUnit node) {
    ImplementationImportCollector collector = new ImplementationImportCollector();
    collector.collect(node, getSourceFileName());
    Set<Import> imports = collector.getImports();

    if (!imports.isEmpty()) {
      Set<String> includeStmts = Sets.newTreeSet();
      for (Import imp : imports) {
        includeStmts.add(String.format("#include \"%s.h\"", imp.getImportFileName()));
      }
      for (String stmt : includeStmts) {
        println(stmt);
      }

      // Print native includes.
      int endOfImportText =
          node.types().isEmpty()
              ? node.getLength()
              : ((ASTNode) node.types().get(0)).getStartPosition();
      for (Comment c : ASTUtil.getCommentList(node)) {
        int start = c.getStartPosition();
        if (start >= endOfImportText) {
          break;
        }
        if (c instanceof BlockComment) {
          String nativeImport = extractNativeCode(start, c.getLength(), true);
          if (nativeImport != null) { // if it has a JSNI section
            println(nativeImport.trim());
          }
        }
      }

      newline();
    }
  }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account.
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit3() throws CoreException {
    try {
      createJavaProject("P1", new String[] {"src"}, new String[] {"JCL_LIB", "lib"}, "bin");

      // create X.class in lib folder
      /* Evaluate the following in a scrapbook:
      	org.eclipse.jdt.core.tests.model.ModifyingResourceTests.generateClassFile(
      		"X",
      		"public class X {\n" +
      		"}")
      */
      byte[] bytes =
          new byte[] {
            -54, -2, -70, -66, 0, 3, 0, 45, 0, 13, 1, 0, 1, 88, 7, 0, 1, 1, 0, 16, 106, 97, 118, 97,
                47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 7, 0, 3, 1, 0, 6, 60, 105,
                110, 105, 116, 62, 1, 0, 3, 40, 41, 86, 1, 0, 4, 67, 111, 100, 101, 12, 0, 5, 0, 6,
                10, 0, 4, 0, 8, 1, 0, 15, 76, 105, 110, 101, 78, 117,
            109, 98, 101, 114, 84, 97, 98, 108, 101, 1, 0, 10, 83, 111, 117, 114, 99, 101, 70, 105,
                108, 101, 1, 0, 6, 88, 46, 106, 97, 118, 97, 0, 33, 0, 2, 0, 4, 0, 0, 0, 0, 0, 1, 0,
                1, 0, 5, 0, 6, 0, 1, 0, 7, 0, 0, 0, 29, 0, 1, 0, 1, 0, 0, 0, 5, 42, -73, 0, 9, -79,
                0, 0, 0, 1, 0, 10, 0, 0, 0, 6,
            0, 1, 0, 0, 0, 1, 0, 1, 0, 11, 0, 0, 0, 2, 0, 12,
          };
      this.createFile("P1/lib/X.class", bytes);

      // create libsrc and attach source
      createFolder("P1/libsrc");
      createFile("P1/libsrc/X.java", "public class X extends Y {\n" + "}");
      IPackageFragmentRoot lib = getPackageFragmentRoot("P1/lib");
      lib.attachSource(new Path("/P1/libsrc"), null, null);

      // create Y.java in src folder
      createFile("P1/src/Y.java", "");

      // create working copy on Y.java
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      this.workingCopy = getCompilationUnit("P1/src/Y.java").getWorkingCopy(owner, null);
      this.workingCopy.getBuffer().setContents("public class Y {\n" + "}");
      this.workingCopy.makeConsistent(null);

      // parse and resolve class file
      IClassFile classFile = getClassFile("P1/lib/X.class");
      ASTParser parser = ASTParser.newParser(AST.JLS2);
      parser.setSource(classFile);
      parser.setResolveBindings(true);
      parser.setWorkingCopyOwner(owner);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
      List types = cu.types();
      assertEquals("Unexpected number of types in AST", 1, types.size());
      TypeDeclaration type = (TypeDeclaration) types.get(0);
      ITypeBinding typeBinding = type.resolveBinding();
      ITypeBinding superType = typeBinding.getSuperclass();
      assertEquals(
          "Unexpected super type",
          "Y",
          superType == null ? "<null>" : superType.getQualifiedName());
    } finally {
      deleteProject("P1");
    }
  }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account. (regression test for bug 39533 Working copy with no corresponding file not
   * considered by NameLookup)
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit1() throws CoreException {
    ICompilationUnit workingCopy1 = null;
    ICompilationUnit workingCopy2 = null;
    try {
      TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
      workingCopy1 = getCompilationUnit("P/X.java").getWorkingCopy(owner, null);
      workingCopy1.getBuffer().setContents("public class X implements I {\n" + "}");
      workingCopy1.makeConsistent(null);

      workingCopy2 = getCompilationUnit("P/I.java").getWorkingCopy(owner, null);
      workingCopy2.getBuffer().setContents("public interface I {\n" + "}");
      workingCopy2.makeConsistent(null);

      ASTParser parser = ASTParser.newParser(AST.JLS2);
      parser.setSource(workingCopy1);
      parser.setResolveBindings(true);
      parser.setWorkingCopyOwner(owner);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
      List types = cu.types();
      assertEquals("Unexpected number of types in AST", 1, types.size());
      TypeDeclaration type = (TypeDeclaration) types.get(0);
      ITypeBinding typeBinding = type.resolveBinding();
      assertTypeBindingsEqual("Unexpected interfaces", "I", typeBinding.getInterfaces());
    } finally {
      if (workingCopy1 != null) {
        workingCopy1.discardWorkingCopy();
      }
      if (workingCopy2 != null) {
        workingCopy2.discardWorkingCopy();
      }
    }
  }
  public void testMethodVarInSwitch() throws IOException {
    String source =
        "class Test { "
            + "  enum E { ONE, TWO };"
            + "  void foo(E e) { "
            + "    switch (e) {"
            + "      case ONE: {"
            + "        final Integer i = 1;"
            + "        Runnable r = new Runnable() { "
            + "          public void run() { int j = i + 1; } }; }}}}";

    // Verify method var in r1.run() isn't mistakenly made a field in r1.
    CompilationUnit unit = translateType("Test", source);
    List<TypeDeclaration> types = unit.types();
    TypeDeclaration r1 = types.get(2);
    assertEquals("Test_$1", NameTable.getFullName(r1));
    boolean found = false;
    for (FieldDeclaration field : r1.getFields()) {
      List<VariableDeclarationFragment> vars = field.fragments();
      for (VariableDeclaration var : vars) {
        if (var.getName().getIdentifier().equals("val$i")) {
          found = true;
        }
      }
    }
    assertTrue("required field not found", found);

    // Verify constructor takes both outer field and var.
    ObjectiveCImplementationGenerator.generate("Test.java", Language.OBJECTIVE_C, unit, source);
    String translation = getTranslatedFile("Test.m");
    assertTranslation(
        translation,
        "r = [[[Test_$1 alloc] " + "initWithTest:self withJavaLangInteger:i] autorelease]");
  }
示例#5
0
  private static ArrayList<SourceKey> createTree(String[] files) {
    ArrayList<SourceKey> ret = new ArrayList<SourceKey>();
    try {
      log("Processing Source Tree:");
      for (String file : files) {
        String data = Files.toString(new File(file), Charset.forName("UTF-8")).replaceAll("\r", "");
        String name = file.replace('\\', '/').substring(SRC.length() + 1);
        log("    " + name);
        CompilationUnit cu = Util.createUnit(parser, "1.6", name, data);

        ArrayList<TypeDeclaration> classes = new ArrayList<TypeDeclaration>();
        List<AbstractTypeDeclaration> types = (List<AbstractTypeDeclaration>) cu.types();
        for (AbstractTypeDeclaration type : types) {
          TREE.processClass(type);
          if (type instanceof TypeDeclaration) {
            classes.add((TypeDeclaration) type);
          }
        }
        ret.add(new SourceKey(name.substring(0, name.length() - 5), cu, data.trim(), classes));
      }

      for (String lib : libs) {
        // log("Processing Tree: " + lib);
        TREE.processLibrary(new File(lib));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return ret;
  }
  private void assertAllBindings(CompilationUnit astRoot) {
    List<AbstractTypeDeclaration> list = astRoot.types();
    for (int i = 0; i < list.size(); i++) {
      TypeDeclaration decl = (TypeDeclaration) list.get(i);
      assertTrue(decl.resolveBinding() != null);

      if (!decl.isInterface() && decl.getSuperclassType() != null) {
        assertTrue(decl.getSuperclassType().resolveBinding() != null);
      }
      List<Type> interfaces = decl.superInterfaceTypes();
      for (int j = 0; j < interfaces.size(); j++) {
        assertTrue(interfaces.get(j).resolveBinding() != null);
      }

      MethodDeclaration[] declarations = decl.getMethods();
      for (int k = 0; k < declarations.length; k++) {
        MethodDeclaration meth = declarations[k];
        assertTrue(meth.resolveBinding() != null);
        List<SingleVariableDeclaration> params = meth.parameters();
        for (int n = 0; n < params.size(); n++) {
          SingleVariableDeclaration arg = params.get(n);
          assertTrue(arg.resolveBinding() != null);
        }
        if (!meth.isConstructor()) {
          assertTrue(meth.getReturnType2().resolveBinding() != null);
        }
      }
    }
  }
 public void testBug405908() throws CoreException, IOException {
   try {
     createJavaProject("P", new String[] {""}, new String[0], "", CompilerOptions.VERSION_1_5);
     createFile(
         "P/A.java",
         "@interface Generated {\n"
             + "    String comment() default \"\";\n"
             + "    String[] value();\n"
             + "}\n"
             + "@Generated()\n"
             + "class A {\n"
             + "}");
     ICompilationUnit cuA = getCompilationUnit("P/A.java");
     CompilationUnit unitA = (CompilationUnit) runConversion(cuA, true, false, true);
     AbstractTypeDeclaration typeA = (AbstractTypeDeclaration) unitA.types().get(1);
     IAnnotationBinding[] annotations = typeA.resolveBinding().getAnnotations();
     IAnnotationBinding generated = annotations[0];
     IMemberValuePairBinding[] mvps = generated.getAllMemberValuePairs();
     IMemberValuePairBinding valueBinding = mvps[1];
     assertEquals("value", valueBinding.getName());
     Object value = valueBinding.getValue();
     assertEquals(0, ((Object[]) value).length);
   } finally {
     deleteProject("P");
   }
 }
 /*
  * Ensures that no bindings are created when reconciling a new working copy with no resource.
  */
 public void testNewWorkingCopy07() throws CoreException {
   this.workingCopy = newExternalWorkingCopy("X.java", "public class X {\n" + "}");
   this.workingCopy.getBuffer().setContents("public class X {\n" + "  int field;\n" + "}");
   CompilationUnit ast =
       this.workingCopy.reconcile(JLS3_INTERNAL, true /*force resolution*/, null, null);
   TypeDeclaration type = (TypeDeclaration) ast.types().get(0);
   assertNull("Unexpected binding", type.resolveBinding());
 }
  protected void setUp() throws Exception {
    super.setUp();
    _simpleTeam =
        getCompilationUnit(getTestProjectDir(), "src", "parameterMapping.teampkg", "MyTeam.java");

    _parser = ASTParser.newParser(JAVA_LANGUAGE_SPEC_LEVEL);
    _parser.setProject(super.getJavaProject(TEST_PROJECT));
    _parser.setSource(_simpleTeam);

    ASTNode root = _parser.createAST(new NullProgressMonitor());
    CompilationUnit compUnit = (CompilationUnit) root;
    _typeDecl = (TypeDeclaration) compUnit.types().get(0);
    _role = _typeDecl.getTypes()[0];
  }
 /*
  * @see ASTVisitor#visit(CompilationUnit)
  */
 public boolean visit(CompilationUnit node) {
   if (node.getPackage() != null) {
     node.getPackage().accept(this);
   }
   for (Iterator it = node.imports().iterator(); it.hasNext(); ) {
     ImportDeclaration d = (ImportDeclaration) it.next();
     d.accept(this);
   }
   for (Iterator it = node.types().iterator(); it.hasNext(); ) {
     AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next();
     d.accept(this);
   }
   return false;
 }
  @SuppressWarnings("unchecked")
  public void removeUnallowedAssignments() {
    CompilationUnit cu = catroidSource.getSourceAst();
    final List<AbstractTypeDeclaration> types = cu.types();
    assert types.size() > 0;

    for (AbstractTypeDeclaration abstractTypeDecl : types) {
      for (BodyDeclaration bodyDecl :
          new ArrayList<BodyDeclaration>(abstractTypeDecl.bodyDeclarations())) {
        if (bodyDecl.getNodeType() != ASTNode.METHOD_DECLARATION) {
          continue;
        }

        MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDecl;
        Block body = methodDeclaration.getBody();
        if ((body == null) || (body.statements().size() == 0)) {
          continue;
        }
        methodDeclaration.accept(this);
      }
    }
  }
  /**
   * Ensures that creating a DOM AST and computing the bindings takes the owner's working copies
   * into account.
   *
   * @deprecated using deprecated code
   */
  public void testParseCompilationUnit2() throws CoreException {
    TestWorkingCopyOwner owner = new TestWorkingCopyOwner();
    this.workingCopy = getCompilationUnit("P/Y.java").getWorkingCopy(owner, null);
    this.workingCopy.getBuffer().setContents("public class Y {\n" + "}");
    this.workingCopy.makeConsistent(null);

    char[] source = ("public class Z extends Y {\n" + "}").toCharArray();
    ASTParser parser = ASTParser.newParser(AST.JLS2);
    parser.setSource(source);
    parser.setUnitName("Z.java");
    parser.setProject(getJavaProject("P"));
    parser.setWorkingCopyOwner(owner);
    parser.setResolveBindings(true);
    CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    List types = cu.types();
    assertEquals("Unexpected number of types in AST", 1, types.size());
    TypeDeclaration type = (TypeDeclaration) types.get(0);
    ITypeBinding typeBinding = type.resolveBinding();
    assertNotNull("No binding", typeBinding);
    assertEquals("Unexpected super type", "Y", typeBinding.getSuperclass().getQualifiedName());
  }
  public void testAnonymousClassAsInitializer() {
    String source =
        "import java.util.*; public class Test {"
            + "private static final Enumeration<?> EMPTY_ENUMERATION = new Enumeration<Object>() {"
            + "  public boolean hasMoreElements() { return false; }"
            + "  public Object nextElement() { throw new NoSuchElementException(); }}; }";
    CompilationUnit unit = translateType("Test", source);
    List<TypeDeclaration> types = unit.types();
    assertEquals(2, types.size());

    final int[] testsFound = {0};
    types
        .get(0)
        .accept(
            new ASTVisitor() {
              @Override
              public void endVisit(Assignment node) {
                assertEquals("Test_EMPTY_ENUMERATION_=new $1()", node.toString().trim());
                ++testsFound[0];
              }
            });
    assertEquals(1, testsFound[0]);
  }
  public void run(ISelection selection) {

    String errorTitle = CompareMessages.AddFromHistory_title;
    String errorMessage = CompareMessages.AddFromHistory_internalErrorMessage;
    Shell shell = getShell();

    ICompilationUnit cu = null;
    IParent parent = null;
    IMember input = null;

    // analyze selection
    if (selection.isEmpty()) {
      // no selection: we try to use the editor's input
      JavaEditor editor = getEditor();
      if (editor != null) {
        IEditorInput editorInput = editor.getEditorInput();
        IWorkingCopyManager manager = JavaPlugin.getDefault().getWorkingCopyManager();
        if (manager != null) {
          cu = manager.getWorkingCopy(editorInput);
          parent = cu;
        }
      }
    } else {
      input = getEditionElement(selection);
      if (input != null) {
        cu = input.getCompilationUnit();
        parent = input;
        input = null;

      } else {
        if (selection instanceof IStructuredSelection) {
          Object o = ((IStructuredSelection) selection).getFirstElement();
          if (o instanceof ICompilationUnit) {
            cu = (ICompilationUnit) o;
            parent = cu;
          }
        }
      }
    }

    if (parent == null || cu == null) {
      String invalidSelectionMessage = CompareMessages.AddFromHistory_invalidSelectionMessage;
      MessageDialog.openInformation(shell, errorTitle, invalidSelectionMessage);
      return;
    }

    IFile file = getFile(parent);
    if (file == null) {
      MessageDialog.openError(shell, errorTitle, errorMessage);
      return;
    }

    boolean inEditor = beingEdited(file);

    IStatus status = Resources.makeCommittable(file, shell);
    if (!status.isOK()) {
      return;
    }

    // get the document where to insert the text
    IPath path = file.getFullPath();
    ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
    ITextFileBuffer textFileBuffer = null;
    try {
      bufferManager.connect(path, LocationKind.IFILE, null);
      textFileBuffer = bufferManager.getTextFileBuffer(path, LocationKind.IFILE);
      IDocument document = textFileBuffer.getDocument();

      // configure EditionSelectionDialog and let user select an edition
      ITypedElement target = new JavaTextBufferNode(file, document, inEditor);
      ITypedElement[] editions = buildEditions(target, file);

      ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_NAME);
      EditionSelectionDialog d = new EditionSelectionDialog(shell, bundle);
      d.setAddMode(true);
      d.setHelpContextId(IJavaHelpContextIds.ADD_ELEMENT_FROM_HISTORY_DIALOG);
      ITypedElement selected = d.selectEdition(target, editions, parent);
      if (selected == null) return; // user cancel

      ICompilationUnit cu2 = cu;
      if (parent instanceof IMember) cu2 = ((IMember) parent).getCompilationUnit();

      CompilationUnit root = parsePartialCompilationUnit(cu2);
      ASTRewrite rewriter = ASTRewrite.create(root.getAST());

      ITypedElement[] results = d.getSelection();
      for (int i = 0; i < results.length; i++) {

        // create an AST node
        ASTNode newNode =
            createASTNode(
                rewriter,
                results[i],
                TextUtilities.getDefaultLineDelimiter(document),
                cu.getJavaProject());
        if (newNode == null) {
          MessageDialog.openError(shell, errorTitle, errorMessage);
          return;
        }

        // now determine where to put the new node
        if (newNode instanceof PackageDeclaration) {
          rewriter.set(root, CompilationUnit.PACKAGE_PROPERTY, newNode, null);

        } else if (newNode instanceof ImportDeclaration) {
          ListRewrite lw = rewriter.getListRewrite(root, CompilationUnit.IMPORTS_PROPERTY);
          lw.insertFirst(newNode, null);

        } else { // class, interface, enum, annotation, method, field

          if (parent instanceof ICompilationUnit) { // top level
            ListRewrite lw = rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
            int index = ASTNodes.getInsertionIndex((BodyDeclaration) newNode, root.types());
            lw.insertAt(newNode, index, null);

          } else if (parent instanceof IType) {
            ASTNode declaration = getBodyContainer(root, (IType) parent);
            if (declaration instanceof TypeDeclaration
                || declaration instanceof AnnotationTypeDeclaration) {
              List container = ASTNodes.getBodyDeclarations(declaration);
              int index = ASTNodes.getInsertionIndex((BodyDeclaration) newNode, container);
              ListRewrite lw =
                  rewriter.getListRewrite(
                      declaration, ASTNodes.getBodyDeclarationsProperty(declaration));
              lw.insertAt(newNode, index, null);
            } else if (declaration instanceof EnumDeclaration) {
              List container = ((EnumDeclaration) declaration).enumConstants();
              int index = ASTNodes.getInsertionIndex((FieldDeclaration) newNode, container);
              ListRewrite lw =
                  rewriter.getListRewrite(declaration, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
              lw.insertAt(newNode, index, null);
            }
          } else {
            JavaPlugin.logErrorMessage(
                "JavaAddElementFromHistoryImpl: unknown container " + parent); // $NON-NLS-1$
          }
        }
      }

      Map options = null;
      IJavaProject javaProject = cu2.getJavaProject();
      if (javaProject != null) options = javaProject.getOptions(true);
      applyChanges(rewriter, document, textFileBuffer, shell, inEditor, options);

    } catch (InvocationTargetException ex) {
      ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);

    } catch (InterruptedException ex) {
      // shouldn't be called because is not cancelable
      Assert.isTrue(false);

    } catch (CoreException ex) {
      ExceptionHandler.handle(ex, shell, errorTitle, errorMessage);

    } finally {
      try {
        if (textFileBuffer != null) bufferManager.disconnect(path, LocationKind.IFILE, null);
      } catch (CoreException e) {
        JavaPlugin.log(e);
      }
    }
  }
  public void testASTRewriteExample() throws Exception {
    // create a new project
    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("Test");
    project.create(null);
    project.open(null);
    try {
      // set the Java nature and Java build path
      IProjectDescription description = project.getDescription();
      description.setNatureIds(new String[] {JavaCore.NATURE_ID});
      project.setDescription(description, null);

      IJavaProject javaProject = JavaCore.create(project);

      // build path is: project as source folder and JRE container
      IClasspathEntry[] cpentry =
          new IClasspathEntry[] {
            JavaCore.newSourceEntry(javaProject.getPath()),
            JavaRuntime.getDefaultJREContainerEntry()
          };
      javaProject.setRawClasspath(cpentry, javaProject.getPath(), null);
      Map<String, String> options = new HashMap<>();
      options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE);
      options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4");
      javaProject.setOptions(options);

      // create a test file
      IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(project);
      IPackageFragment pack1 = root.createPackageFragment("test1", false, null);
      StringBuffer buf = new StringBuffer();
      buf.append("package test1;\n");
      buf.append("public class E {\n");
      buf.append("    public void foo(int i) {\n");
      buf.append("        while (--i > 0) {\n");
      buf.append("            System.beep();\n");
      buf.append("        }\n");
      buf.append("    }\n");
      buf.append("}\n");
      ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);

      // create an AST
      ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL);
      parser.setSource(cu);
      parser.setResolveBindings(false);
      CompilationUnit astRoot = (CompilationUnit) parser.createAST(null);
      AST ast = astRoot.getAST();

      // create the descriptive ast rewriter
      ASTRewrite rewrite = ASTRewrite.create(ast);

      // get the block node that contains the statements in the method body
      TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
      MethodDeclaration methodDecl = typeDecl.getMethods()[0];
      Block block = methodDecl.getBody();

      // create new statements to insert
      MethodInvocation newInv1 = ast.newMethodInvocation();
      newInv1.setName(ast.newSimpleName("bar1"));
      Statement newStatement1 = ast.newExpressionStatement(newInv1);

      MethodInvocation newInv2 = ast.newMethodInvocation();
      newInv2.setName(ast.newSimpleName("bar2"));
      Statement newStatement2 = ast.newExpressionStatement(newInv2);

      // describe that the first node is inserted as first statement in block, the other one as last
      // statement
      // note: AST is not modified by this
      ListRewrite listRewrite = rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
      listRewrite.insertFirst(newStatement1, null);
      listRewrite.insertLast(newStatement2, null);

      // evaluate the text edits corresponding to the described changes. AST and CU still
      // unmodified.
      TextEdit res = rewrite.rewriteAST();

      // apply the text edits to the compilation unit
      Document document = new Document(cu.getSource());
      res.apply(document);
      cu.getBuffer().setContents(document.get());

      // test result
      String preview = cu.getSource();

      buf = new StringBuffer();
      buf.append("package test1;\n");
      buf.append("public class E {\n");
      buf.append("    public void foo(int i) {\n");
      buf.append("        bar1();\n");
      buf.append("        while (--i > 0) {\n");
      buf.append("            System.beep();\n");
      buf.append("        }\n");
      buf.append("        bar2();\n");
      buf.append("    }\n");
      buf.append("}\n");
      assertEquals(preview, buf.toString());
    } finally {
      project.delete(true, null);
    }
  }
示例#16
0
  private List<ClassObject> parseAST(CompilationUnit compilationUnit, IFile iFile) {
    List<ClassObject> classObjects = new ArrayList<ClassObject>();
    List<AbstractTypeDeclaration> topLevelTypeDeclarations = compilationUnit.types();
    for (AbstractTypeDeclaration abstractTypeDeclaration : topLevelTypeDeclarations) {
      if (abstractTypeDeclaration instanceof TypeDeclaration) {
        TypeDeclaration topLevelTypeDeclaration = (TypeDeclaration) abstractTypeDeclaration;
        List<TypeDeclaration> typeDeclarations = new ArrayList<TypeDeclaration>();
        typeDeclarations.add(topLevelTypeDeclaration);
        typeDeclarations.addAll(getRecursivelyInnerTypes(topLevelTypeDeclaration));
        for (TypeDeclaration typeDeclaration : typeDeclarations) {
          final ClassObject classObject = new ClassObject();
          classObject.setIFile(iFile);
          classObject.setName(typeDeclaration.resolveBinding().getQualifiedName());
          classObject.setTypeDeclaration(typeDeclaration);

          if (typeDeclaration.isInterface()) {
            classObject.setInterface(true);
          }

          int modifiers = typeDeclaration.getModifiers();
          if ((modifiers & Modifier.ABSTRACT) != 0) classObject.setAbstract(true);

          if ((modifiers & Modifier.PUBLIC) != 0) classObject.setAccess(Access.PUBLIC);
          else if ((modifiers & Modifier.PROTECTED) != 0) classObject.setAccess(Access.PROTECTED);
          else if ((modifiers & Modifier.PRIVATE) != 0) classObject.setAccess(Access.PRIVATE);
          else classObject.setAccess(Access.NONE);

          if ((modifiers & Modifier.STATIC) != 0) classObject.setStatic(true);

          Type superclassType = typeDeclaration.getSuperclassType();
          if (superclassType != null) {
            ITypeBinding binding = superclassType.resolveBinding();
            String qualifiedName = binding.getQualifiedName();
            TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
            classObject.setSuperclass(typeObject);
          }

          List<Type> superInterfaceTypes = typeDeclaration.superInterfaceTypes();
          for (Type interfaceType : superInterfaceTypes) {
            ITypeBinding binding = interfaceType.resolveBinding();
            String qualifiedName = binding.getQualifiedName();
            TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
            classObject.addInterface(typeObject);
          }

          FieldDeclaration[] fieldDeclarations = typeDeclaration.getFields();
          for (FieldDeclaration fieldDeclaration : fieldDeclarations) {
            Type fieldType = fieldDeclaration.getType();
            ITypeBinding binding = fieldType.resolveBinding();
            List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
            for (VariableDeclarationFragment fragment : fragments) {
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              typeObject.setArrayDimension(
                  typeObject.getArrayDimension() + fragment.getExtraDimensions());
              FieldObject fieldObject =
                  new FieldObject(typeObject, fragment.getName().getIdentifier());
              fieldObject.setClassName(classObject.getName());
              fieldObject.setVariableDeclarationFragment(fragment);

              int fieldModifiers = fieldDeclaration.getModifiers();
              if ((fieldModifiers & Modifier.PUBLIC) != 0) fieldObject.setAccess(Access.PUBLIC);
              else if ((fieldModifiers & Modifier.PROTECTED) != 0)
                fieldObject.setAccess(Access.PROTECTED);
              else if ((fieldModifiers & Modifier.PRIVATE) != 0)
                fieldObject.setAccess(Access.PRIVATE);
              else fieldObject.setAccess(Access.NONE);

              if ((fieldModifiers & Modifier.STATIC) != 0) fieldObject.setStatic(true);

              classObject.addField(fieldObject);
            }
          }

          MethodDeclaration[] methodDeclarations = typeDeclaration.getMethods();
          for (MethodDeclaration methodDeclaration : methodDeclarations) {
            String methodName = methodDeclaration.getName().getIdentifier();
            final ConstructorObject constructorObject = new ConstructorObject();
            constructorObject.setMethodDeclaration(methodDeclaration);
            constructorObject.setName(methodName);
            constructorObject.setClassName(classObject.getName());

            int methodModifiers = methodDeclaration.getModifiers();
            if ((methodModifiers & Modifier.PUBLIC) != 0)
              constructorObject.setAccess(Access.PUBLIC);
            else if ((methodModifiers & Modifier.PROTECTED) != 0)
              constructorObject.setAccess(Access.PROTECTED);
            else if ((methodModifiers & Modifier.PRIVATE) != 0)
              constructorObject.setAccess(Access.PRIVATE);
            else constructorObject.setAccess(Access.NONE);

            List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
            for (SingleVariableDeclaration parameter : parameters) {
              Type parameterType = parameter.getType();
              ITypeBinding binding = parameterType.resolveBinding();
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              typeObject.setArrayDimension(
                  typeObject.getArrayDimension() + parameter.getExtraDimensions());
              if (parameter.isVarargs()) {
                typeObject.setArrayDimension(1);
              }
              ParameterObject parameterObject =
                  new ParameterObject(typeObject, parameter.getName().getIdentifier());
              parameterObject.setSingleVariableDeclaration(parameter);
              constructorObject.addParameter(parameterObject);
            }

            Block methodBody = methodDeclaration.getBody();
            if (methodBody != null) {
              MethodBodyObject methodBodyObject = new MethodBodyObject(methodBody);
              constructorObject.setMethodBody(methodBodyObject);
            }

            if (methodDeclaration.isConstructor()) {
              classObject.addConstructor(constructorObject);
            } else {
              MethodObject methodObject = new MethodObject(constructorObject);
              List<IExtendedModifier> extendedModifiers = methodDeclaration.modifiers();
              for (IExtendedModifier extendedModifier : extendedModifiers) {
                if (extendedModifier.isAnnotation()) {
                  Annotation annotation = (Annotation) extendedModifier;
                  if (annotation.getTypeName().getFullyQualifiedName().equals("Test")) {
                    methodObject.setTestAnnotation(true);
                    break;
                  }
                }
              }
              Type returnType = methodDeclaration.getReturnType2();
              ITypeBinding binding = returnType.resolveBinding();
              String qualifiedName = binding.getQualifiedName();
              TypeObject typeObject = TypeObject.extractTypeObject(qualifiedName);
              methodObject.setReturnType(typeObject);

              if ((methodModifiers & Modifier.ABSTRACT) != 0) methodObject.setAbstract(true);
              if ((methodModifiers & Modifier.STATIC) != 0) methodObject.setStatic(true);
              if ((methodModifiers & Modifier.SYNCHRONIZED) != 0)
                methodObject.setSynchronized(true);
              if ((methodModifiers & Modifier.NATIVE) != 0) methodObject.setNative(true);

              classObject.addMethod(methodObject);
              FieldInstructionObject fieldInstruction = methodObject.isGetter();
              if (fieldInstruction != null)
                systemObject.addGetter(methodObject.generateMethodInvocation(), fieldInstruction);
              fieldInstruction = methodObject.isSetter();
              if (fieldInstruction != null)
                systemObject.addSetter(methodObject.generateMethodInvocation(), fieldInstruction);
              fieldInstruction = methodObject.isCollectionAdder();
              if (fieldInstruction != null)
                systemObject.addCollectionAdder(
                    methodObject.generateMethodInvocation(), fieldInstruction);
              MethodInvocationObject methodInvocation = methodObject.isDelegate();
              if (methodInvocation != null)
                systemObject.addDelegate(methodObject.generateMethodInvocation(), methodInvocation);
            }
          }
          classObjects.add(classObject);
        }
      }
    }
    return classObjects;
  }
 protected List<TypeDeclaration> translateClassBody(String testSource) {
   String source = "public class Test { " + testSource + " }";
   CompilationUnit unit = translateType("Test", source);
   return unit.types();
 }
  @SuppressWarnings("unchecked")
  @Before
  public void setUp() {
    manager = ModelManager.getInstance();
    manager.clearModel();

    AST ast2 = AST.newAST(AST.JLS3);
    CompilationUnit cu2 = ast2.newCompilationUnit();
    PackageDeclaration pack2 = ast2.newPackageDeclaration();
    pack2.setName(ast2.newName("be.ac.ua.test.otherpack"));
    cu2.setPackage(pack2);
    TypeDeclaration type2 = ast2.newTypeDeclaration();
    type2.setName(ast2.newSimpleName("Foo"));

    cu2.types().add(type2); // created mock compilationunit containing package and class

    PackageRecorder prec2 = new PackageRecorder(pack2);
    prec2.storeChange(new Add()); // store the package addition
    ClassRecorder crec2 = new ClassRecorder(type2);
    declaredclassadd = new Add();
    crec2.storeChange(declaredclassadd);

    AST ast = AST.newAST(AST.JLS3);
    CompilationUnit cu = ast.newCompilationUnit();
    PackageDeclaration pack = ast.newPackageDeclaration();
    pack.setName(ast.newName(packname));
    cu.setPackage(pack);
    TypeDeclaration type = ast.newTypeDeclaration();
    type.setName(ast.newSimpleName(classname));

    cu.types().add(type);

    PackageRecorder prec = new PackageRecorder(pack);
    prec.storeChange(new Add()); // store the package addition
    ClassRecorder crec = new ClassRecorder(type);
    classadd = new Add();
    crec.storeChange(classadd);

    // Class and package created and changes logged, now create the Field.

    VariableDeclarationFragment frag1 = ast.newVariableDeclarationFragment();
    frag1.setName(ast.newSimpleName(intfieldname));
    FieldDeclaration field = ast.newFieldDeclaration(frag1);
    field.setType(ast.newPrimitiveType(PrimitiveType.INT)); // field has type int
    type.bodyDeclarations().add(field);

    VariableDeclarationFragment frag2 = ast.newVariableDeclarationFragment();
    frag2.setName(ast.newSimpleName(fieldname));
    FieldDeclaration field2 = ast.newFieldDeclaration(frag2);
    field2.setType(ast.newSimpleType(ast.newName(declaredTypeName))); // field has type Foo
    type.bodyDeclarations().add(field2);

    VariableDeclarationFragment frag3 = ast.newVariableDeclarationFragment();
    frag3.setName(ast.newSimpleName(field3Name));
    FieldDeclaration field3 = ast.newFieldDeclaration(frag3);
    field3.setType(ast.newSimpleType(ast.newName("Foo"))); // field has type Foo
    type.bodyDeclarations().add(field3);

    ImportDeclaration imp = ast.newImportDeclaration();
    imp.setName(ast.newName(declaredTypeName));
    cu.imports().add(imp);

    // created mock compilationunit containing package and class

    recorder1 = new FieldRecorder(field);
    recorder2 = new FieldRecorder(field2);
    recorder3 = new FieldRecorder(field3);
  }