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]");
  }
  /**
   * Updates the content of <code>cu</code>, modifying the type name and/or package declaration as
   * necessary.
   *
   * @return an AST rewrite or null if no rewrite needed
   */
  private TextEdit updateContent(ICompilationUnit cu, PackageFragment dest, String newName)
      throws JavaModelException {
    String[] currPackageName = ((PackageFragment) cu.getParent()).names;
    String[] destPackageName = dest.names;
    if (Util.equalArraysOrNull(currPackageName, destPackageName) && newName == null) {
      return null; // nothing to change
    } else {
      // ensure cu is consistent (noop if already consistent)
      cu.makeConsistent(this.progressMonitor);

      // GROOVY start
      // don't use the ASTParser if not a Java compilation unit
      if (LanguageSupportFactory.isInterestingSourceFile(cu.getElementName())) {
        // ZALUUM
        // old return updateNonJavaContent(cu, destPackageName, currPackageName, newName);
        return LanguageSupportFactory.updateContent(cu, destPackageName, currPackageName, newName);
        // END ZALUUM
      }
      // GROOVY end

      this.parser.setSource(cu);
      CompilationUnit astCU = (CompilationUnit) this.parser.createAST(this.progressMonitor);
      AST ast = astCU.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);
      updateTypeName(cu, astCU, cu.getElementName(), newName, rewrite);
      updatePackageStatement(astCU, destPackageName, rewrite, cu);
      return rewrite.rewriteAST();
    }
  }
  public static ICleanUpFix createCleanUp(
      CompilationUnit compilationUnit,
      boolean addFinalFields,
      boolean addFinalParameters,
      boolean addFinalLocals) {

    if (!addFinalFields && !addFinalParameters && !addFinalLocals) return null;

    HashMap writtenNames = new HashMap();
    WrittenNamesFinder finder = new WrittenNamesFinder(writtenNames);
    compilationUnit.accept(finder);

    List operations = new ArrayList();
    VariableDeclarationFinder visitor =
        new VariableDeclarationFinder(
            addFinalFields, addFinalParameters, addFinalLocals, operations, writtenNames);
    compilationUnit.accept(visitor);

    if (operations.isEmpty()) return null;

    return new VariableDeclarationFix(
        FixMessages.VariableDeclarationFix_add_final_change_name,
        compilationUnit,
        (CompilationUnitRewriteOperation[])
            operations.toArray(new CompilationUnitRewriteOperation[operations.size()]));
  }
 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");
   }
 }
  @Override
  protected ASTRewrite getRewrite() throws CoreException {
    ASTNode boundNode = fAstRoot.findDeclaringNode(fBinding);
    ASTNode declNode = null;
    CompilationUnit newRoot = fAstRoot;
    if (boundNode != null) {
      declNode = boundNode; // is same CU
    } else {
      newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
      declNode = newRoot.findDeclaringNode(fBinding.getKey());
    }
    ImportRewrite imports = createImportRewrite(newRoot);

    if (declNode instanceof TypeDeclaration) {
      AST ast = declNode.getAST();
      ASTRewrite rewrite = ASTRewrite.create(ast);

      ImportRewriteContext importRewriteContext =
          new ContextSensitiveImportRewriteContext(declNode, imports);
      Type newInterface = imports.addImport(fNewInterface, ast, importRewriteContext);
      ListRewrite listRewrite =
          rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
      listRewrite.insertLast(newInterface, null);

      // set up linked mode
      final String KEY_TYPE = "type"; // $NON-NLS-1$
      addLinkedPosition(rewrite.track(newInterface), true, KEY_TYPE);
      return rewrite;
    }
    return null;
  }
 private static boolean processJavadocComments(CompilationUnit astRoot) {
   // don't visit Javadoc for 'package-info' (bug 216432)
   if (astRoot != null && astRoot.getTypeRoot() != null) {
     return !JavaModelUtil.PACKAGE_INFO_JAVA.equals(astRoot.getTypeRoot().getElementName());
   }
   return true;
 }
 private ITypeBinding[] computeTypeVariables(ITypeBinding[] bindings) {
   Selection selection = getSelection();
   Set<ITypeBinding> result = new HashSet<>();
   // first remove all type variables that come from outside of the method
   // or are covered by the selection
   CompilationUnit compilationUnit = (CompilationUnit) fEnclosingBodyDeclaration.getRoot();
   for (int i = 0; i < bindings.length; i++) {
     ASTNode decl = compilationUnit.findDeclaringNode(bindings[i]);
     if (decl == null
         || (!selection.covers(decl) && decl.getParent() instanceof MethodDeclaration))
       result.add(bindings[i]);
   }
   // all all type variables which are needed since a local variable uses it
   for (int i = 0; i < fArguments.length; i++) {
     IVariableBinding arg = fArguments[i];
     ITypeBinding type = arg.getType();
     if (type != null && type.isTypeVariable()) {
       ASTNode decl = compilationUnit.findDeclaringNode(type);
       if (decl == null
           || (!selection.covers(decl) && decl.getParent() instanceof MethodDeclaration))
         result.add(type);
     }
   }
   return result.toArray(new ITypeBinding[result.size()]);
 }
Exemple #8
0
  /**
   * 取得Method相關資訊
   *
   * @param resource 來源
   * @param methodIdx Method的Index
   * @return 是否成功
   */
  protected boolean findCurrentMethod(IResource resource, int methodIdx) {
    if (resource instanceof IFile && resource.getName().endsWith(".java")) {
      try {
        IJavaElement javaElement = JavaCore.create(resource);

        if (javaElement instanceof IOpenable) {
          actOpenable = (IOpenable) javaElement;
        }

        // Create AST to parse
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        parser.setSource((ICompilationUnit) javaElement);
        parser.setResolveBindings(true);
        actRoot = (CompilationUnit) parser.createAST(null);
        // AST 2.0紀錄方式
        actRoot.recordModifications();

        // 取得該class所有的method
        ASTMethodCollector methodCollector = new ASTMethodCollector();
        actRoot.accept(methodCollector);
        List<MethodDeclaration> methodList = methodCollector.getMethodList();

        // 取得目前要被修改的method node
        currentMethodNode = methodList.get(methodIdx);

        return true;
      } catch (Exception ex) {
        logger.error("[Find DH Method] EXCEPTION ", ex);
      }
    }
    return false;
  }
  /**
   * 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");
    }
  }
  private static boolean hasFatalError(CompilationUnit compilationUnit) {
    try {
      if (!((ICompilationUnit) compilationUnit.getJavaElement()).isStructureKnown()) return true;
    } catch (JavaModelException e) {
      JavaPlugin.log(e);
      return true;
    }

    IProblem[] problems = compilationUnit.getProblems();
    for (int i = 0; i < problems.length; i++) {
      if (problems[i].isError()) {
        if (!(problems[i] instanceof CategorizedProblem)) return true;

        CategorizedProblem categorizedProblem = (CategorizedProblem) problems[i];
        int categoryID = categorizedProblem.getCategoryID();

        if (categoryID == CategorizedProblem.CAT_BUILDPATH) return true;
        if (categoryID == CategorizedProblem.CAT_SYNTAX) return true;
        if (categoryID == CategorizedProblem.CAT_IMPORT) return true;
        if (categoryID == CategorizedProblem.CAT_TYPE) return true;
        if (categoryID == CategorizedProblem.CAT_MEMBER) return true;
        if (categoryID == CategorizedProblem.CAT_INTERNAL) return true;
      }
    }

    return false;
  }
  /** 測試當使用者自訂的type1是否能抓到Outer class 未測試完成 */
  @Test
  public void testAddDummyHandlerSmellInfoForUserPatternType1() {
    String testClassPattern = UserDefineDummyHandlerFish.class.getName() + ".*";

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // 確認全部的Example中恰有偵測到兩次呼叫
    smellSettings.addDummyHandlerPattern(testClassPattern, true);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());

    // 確認當使用者未勾選時不會偵測到
    setEmptySetting();
    smellSettings.addDummyHandlerPattern(testClassPattern, false);
    smellSettings.writeXMLFile(UserDefinedMethodAnalyzer.SETTINGFILEPATH);
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
  }
  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();
    }
  }
  @Test
  public void testAddDummyHandlerSmellInfoForExtraRule_PrintStackTrace() throws Exception {
    Method method =
        DummyHandlerVisitor.class.getDeclaredMethod(
            "addDummyHandlerSmellInfo", MethodInvocation.class);
    method.setAccessible(true);

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());

    // ePrintStackTrace case
    dummyHandlerPatternsInXML = new String[] {SmellSettings.EXTRARULE_ePrintStackTrace};
    setNewSettingsWithExtraRules(dummyHandlerPatternsInXML);
    //   分別測試:全部例子、符合例子、不符合例子 是否有抓出
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(10, dummyHandlerVisitor.getDummyList().size());

    MethodInvocation mi = null;
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_printStackTrace_protected", "e.printStackTrace()")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(11, dummyHandlerVisitor.getDummyList().size());
  }
  @Test
  public void testAddDummyHandlerSmellInfoForExtraRule_OrgApacheLog4j() throws Exception {
    Method method =
        DummyHandlerVisitor.class.getDeclaredMethod(
            "addDummyHandlerSmellInfo", MethodInvocation.class);
    method.setAccessible(true);

    // 確認初始值
    setEmptySetting();
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(0, dummyHandlerVisitor.getDummyList().size());
    // OrgApacheLog4j case
    dummyHandlerPatternsInXML = new String[] {SmellSettings.EXTRARULE_OrgApacheLog4j};
    setNewSettingsWithExtraRules(dummyHandlerPatternsInXML);
    //   分別測試:全部例子、符合例子、不符合例子 是否有抓出
    dummyHandlerVisitor = new DummyHandlerVisitor(compilationUnit);
    compilationUnit.accept(dummyHandlerVisitor);
    assertEquals(1, dummyHandlerVisitor.getDummyList().size());

    MethodInvocation mi = null;
    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_Log4J", "log4j.info(\"message\")")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());

    mi =
        ASTNodeFinder.getMethodInvocationByMethodNameAndCode(
                compilationUnit, "true_javaLogInfo", "javaLog.info(\"\")")
            .get(0);
    method.invoke(dummyHandlerVisitor, mi);
    assertEquals(2, dummyHandlerVisitor.getDummyList().size());
  }
  @SuppressWarnings("rawtypes") // DOM AST API returns raw collections
  public SourcePosition getPosition() {
    final MirrorKind kind = _parent.kind();
    ASTNode astNode = null;
    switch (kind) {
      case ANNOTATION_MIRROR:
        final AnnotationMirrorImpl anno = (AnnotationMirrorImpl) _parent;
        astNode = anno.getASTNodeForElement(_name);
        break;
      case ANNOTATION_ELEMENT:
        final AnnotationElementDeclarationImpl element = (AnnotationElementDeclarationImpl) _parent;
        astNode = element.getAstNodeForDefault();
        break;
      default:
        throw new IllegalStateException(); // should never reach this point.
    }
    // did not come from source.
    if (astNode == null) return null;
    if (_index >= 0 && astNode.getNodeType() == ASTNode.ARRAY_INITIALIZER) {
      final ArrayInitializer arrayInit = (ArrayInitializer) astNode;
      final List exprs = arrayInit.expressions();
      if (exprs != null && _index < exprs.size()) astNode = (ASTNode) exprs.get(_index);
    }
    if (astNode == null) return null;

    final CompilationUnit unit = getCompilationUnit();
    if (unit == null) return null;
    final int offset = astNode.getStartPosition();
    return new SourcePositionImpl(
        astNode.getStartPosition(),
        astNode.getLength(),
        unit.getLineNumber(offset),
        unit.getColumnNumber(offset),
        this);
  }
  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;
  }
  /**
   * 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();
      }
    }
  }
 /**
  * Construct a {@code Formatter} given Java compilation unit. Parses the code; builds a {@link
  * JavaInput} and the corresponding {@link JavaOutput}.
  *
  * @param javaInput the input, a Java compilation unit
  * @param javaOutput the {@link JavaOutput}
  * @param maxWidth the maximum formatted width
  * @param errors mutable list to receive errors
  * @param indentationMultiplier the multiplier for the unit of indent; the default is 1
  */
 static void format(
     JavaInput javaInput,
     JavaOutput javaOutput,
     int maxWidth,
     List<FormatterDiagnostic> errors,
     int indentationMultiplier) {
   ASTParser parser = ASTParser.newParser(AST.JLS8);
   parser.setSource(javaInput.getText().toCharArray());
   @SuppressWarnings("unchecked") // safe by specification
   Map<String, String> options = JavaCore.getOptions();
   JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);
   parser.setCompilerOptions(options);
   CompilationUnit unit = (CompilationUnit) parser.createAST(null);
   javaInput.setCompilationUnit(unit);
   if (unit.getMessages().length > 0) {
     for (Message message : unit.getMessages()) {
       errors.add(javaInput.createDiagnostic(message.getStartPosition(), message.getMessage()));
     }
     return;
   }
   OpsBuilder builder = new OpsBuilder(javaInput, javaOutput, errors);
   // Output compilation unit.
   new JavaInputAstVisitor(builder, indentationMultiplier).visit(unit);
   builder.sync(javaInput.getText().length());
   builder.drain();
   Doc doc = new DocBuilder().withOps(builder.build()).build();
   doc.computeBreaks(javaOutput.getCommentsHelper(), maxWidth, new Doc.State(+0, 0, 0));
   doc.write(javaOutput);
   javaOutput.flush();
 }
  private ASTRewrite doAddEnumConst(CompilationUnit astRoot) {
    SimpleName node = fOriginalNode;

    ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
    if (newTypeDecl == null) {
      astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
      newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
    }

    if (newTypeDecl != null) {
      AST ast = newTypeDecl.getAST();

      ASTRewrite rewrite = ASTRewrite.create(ast);

      EnumConstantDeclaration constDecl = ast.newEnumConstantDeclaration();
      constDecl.setName(ast.newSimpleName(node.getIdentifier()));

      ListRewrite listRewriter =
          rewrite.getListRewrite(newTypeDecl, EnumDeclaration.ENUM_CONSTANTS_PROPERTY);
      listRewriter.insertLast(constDecl, null);

      addLinkedPosition(rewrite.track(constDecl.getName()), false, KEY_NAME);

      return rewrite;
    }
    return null;
  }
Exemple #20
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom
  * .CompilationUnit)
  */
 @Override
 public boolean visit(final CompilationUnit node) {
   if (node.getPackage() != null) {
     currentPackageName = node.getPackage().getName().getFullyQualifiedName();
   }
   return super.visit(node);
 }
  @Override
  public void acceptAST(String sourceFilePath, CompilationUnit compUnit) {
    checkForProblems(sourceFilePath, compUnit);

    if (isTestFile(sourceFilePath)) {
      ModificationRecordingVisitor visitor = new AutocheckVisitor(compUnit.getAST());
      compUnit.accept(visitor);
      actualResults.put(sourceFilePath, compUnit);
    } else if (isExpectedFile(sourceFilePath)
        && actualResults.containsKey(testFileMapping.get(sourceFilePath))) {
      CompilationUnit actual = actualResults.get(testFileMapping.get(sourceFilePath));
      Object diff = ASTCompare.getDifference(compUnit, actual);
      if (diff != null) {
        throw new RuntimeException(
            "The expected and the actual AST does not match. Expected file: "
                + sourceFilePath
                + ", actual content:\n"
                + actual
                + "\ndifference around: "
                + diff);
      }
    } else {
      throw new RuntimeException("Unexpected AST: " + sourceFilePath);
    }
  }
Exemple #22
0
  /**
   * Function for traversing the source files in the application under analysis
   *
   * @param astC
   * @return
   */
  public TreeSet analyzeLibraryCode(ASTCrawler astC) {
    IJavaProject libProject = RepositoryAnalyzer.getInstance().getCurrentJProject();
    if (libProject == null) {
      logger.warn("No library project is available as input. Nothing can be done, Sorry!!!!");
      return null;
    }

    try {
      IPackageFragment[] fragments = libProject.getPackageFragments();
      for (int j = 0; j < fragments.length; j++) {
        switch (fragments[j].getKind()) {
          case IPackageFragmentRoot.K_SOURCE:

            /**
             * @todo I'm not sure whether K_SOURCE actually means non-Archive (and therefore further
             *     testing is obsolete)
             */
            IPackageFragmentRoot root =
                (IPackageFragmentRoot) fragments[j].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

            if (!root.isArchive()) {
              ICompilationUnit[] units = fragments[j].getCompilationUnits();
              for (ICompilationUnit icu : units) {
                ASTParser parser = ASTParser.newParser(AST.JLS3);
                parser.setProject(libProject);
                parser.setResolveBindings(true);
                parser.setStatementsRecovery(true);

                parser.setSource(icu);
                CompilationUnit cu_java = (CompilationUnit) parser.createAST(null);

                try {
                  // This also clears the class specific data of the previous run
                  String path = icu.getPath().toString();
                  int indexOfLastSlash;
                  if ((indexOfLastSlash = path.lastIndexOf("/")) != -1) {
                    path = path.substring(indexOfLastSlash + 1, path.length());
                  }
                  astC.preProcessClass(cu_java, path);
                  MethodInvocationHolder.MIHKEYGEN = 0;
                  cu_java.accept(astC);
                } catch (Exception ex) {
                  ex.printStackTrace();
                }
              }
            }

            break;

          default:
            break;
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return astC.postProcess();
  }
Exemple #23
0
 @Override
 public O setPackage(final String name) {
   if (unit.getPackage() == null) {
     unit.setPackage(unit.getAST().newPackageDeclaration());
   }
   unit.getPackage().setName(unit.getAST().newName(name));
   return (O) this;
 }
 /*
  * 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());
 }
Exemple #25
0
 @Override
 public O removeImport(final Import imprt) {
   Object internal = imprt.getInternal();
   if (unit.imports().contains(internal)) {
     unit.imports().remove(internal);
   }
   return (O) this;
 }
Exemple #26
0
 /**
  * Scans the specified source {@linkplain CompilationUnit} for contributed API javadoc tags. Tags
  * on methods will have unresolved signatures.
  *
  * @param source the source file to scan for tags
  * @param description the API description to annotate with any new tag rules found
  * @param container optional class file container containing the class file for the given source
  *     that can be used to resolve method signatures if required (for tags on methods). If not
  *     provided (<code>null</code>), method signatures will be unresolved.
  * @param options a map of Java compiler options to use when creating the AST to scan or <code>
  *     null</code> if default options should be used
  * @param monitor
  * @throws CoreException
  */
 public void scan(
     CompilationUnit source,
     IApiDescription description,
     IApiTypeContainer container,
     Map options,
     IProgressMonitor monitor)
     throws CoreException {
   SubMonitor localmonitor = SubMonitor.convert(monitor, 2);
   ASTParser parser = ASTParser.newParser(AST.JLS3);
   InputStream inputStream = null;
   try {
     inputStream = source.getInputStream();
     parser.setSource(
         Util.getInputStreamAsCharArray(
             inputStream, -1, System.getProperty("file.encoding"))); // $NON-NLS-1$
   } catch (FileNotFoundException e) {
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             ApiPlugin.PLUGIN_ID,
             MessageFormat.format(
                 "Compilation unit source not found: {0}", new String[] {source.getName()}),
             e)); //$NON-NLS-1$
   } catch (IOException e) {
     if (DEBUG) {
       System.err.println(source.getName());
     }
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             ApiPlugin.PLUGIN_ID,
             MessageFormat.format(
                 "Error reading compilation unit: {0}", new String[] {source.getName()}),
             e)); //$NON-NLS-1$
   } finally {
     if (inputStream != null) {
       try {
         inputStream.close();
       } catch (IOException e) {
         ApiPlugin.log(e);
       }
     }
   }
   Util.updateMonitor(localmonitor);
   Map loptions = options;
   if (loptions == null) {
     loptions = JavaCore.getOptions();
   }
   loptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
   parser.setCompilerOptions(loptions);
   org.eclipse.jdt.core.dom.CompilationUnit cunit =
       (org.eclipse.jdt.core.dom.CompilationUnit) parser.createAST(localmonitor.newChild(1));
   Visitor visitor = new Visitor(description, container);
   cunit.accept(visitor);
   if (visitor.getException() != null) {
     throw visitor.getException();
   }
 }
  public void lookForCompilantionProblems(ArrayList<String> errorFiles) {
    try {
      for (String entry : errorFiles) {
        String[] columns = entry.split(";");
        String revisionFile = columns[0];
        String classFile = columns[1];
        String projectDir = revisionFile.split("\\.")[0];

        // Listing the folders, encodings and classpath of the project
        ArrayList<String> folders = new ArrayList<String>();
        listSourceFolders(folders, projectDir);
        folders.add(projectDir);

        String[] sources = new String[folders.size()];
        sources = folders.toArray(sources);

        String[] encodings = fillEncodings(sources.length);

        // FIXME change if needed
        String[] classPaths = null;

        File javaFile = new File(classFile);
        String contents = getFileContents(javaFile.getAbsolutePath());
        int errors = 0;
        if (contents != null) {
          // Create the ASTParser which will be a CompilationUnit
          ASTParser parser = ASTParser.newParser(AST.JLS8);
          parser.setKind(ASTParser.K_COMPILATION_UNIT);
          parser.setSource(contents.toCharArray());

          // Parsing
          parser.setEnvironment(classPaths, sources, encodings, true);
          parser.setBindingsRecovery(true);
          parser.setResolveBindings(true);
          parser.setUnitName(javaFile.getName());
          Map options = JavaCore.getOptions();
          options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8);
          parser.setCompilerOptions(options);
          CompilationUnit parse = (CompilationUnit) parser.createAST(null);

          // Listing compilation problems
          IProblem[] problems = parse.getProblems();
          if (problems != null && problems.length > 0) {
            System.out.println("Got {} problems compiling the source file: " + problems.length);
            for (IProblem problem : problems) {
              System.out.println("{}" + problem);
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private void assertProblems(
     String expectedProblems, String path, String source, WorkingCopyOwner owner)
     throws JavaModelException {
   this.workingCopy = getWorkingCopy(path, source);
   ASTParser parser = ASTParser.newParser(JLS3_INTERNAL);
   parser.setSource(this.workingCopy);
   parser.setResolveBindings(true);
   parser.setWorkingCopyOwner(owner);
   CompilationUnit cu = (CompilationUnit) parser.createAST(null);
   assertProblems("Unexpected problems", expectedProblems, cu.getProblems(), source.toCharArray());
 }
Exemple #29
0
 public void scan(final Collection<File> files) {
   final MethodExtractor me = new MethodExtractor();
   final JavaASTExtractor jEx = new JavaASTExtractor(false);
   for (final File f : files) {
     try {
       final CompilationUnit cu = jEx.getAST(f);
       cu.accept(me);
     } catch (final Throwable e) {
       LOGGER.warning("Failed to get methods from " + f);
     }
   }
 }
Exemple #30
0
  /** Return this {@link JavaSource} file as a String */
  @Override
  public String toString() {
    Document document = new Document(this.document.get());

    try {
      TextEdit edit = unit.rewrite(document, null);
      edit.apply(document);
    } catch (Exception e) {
      throw new ParserException("Could not modify source: " + unit.toString(), e);
    }

    return Formatter.format(document.get());
  }