コード例 #1
0
  /**
   * 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");
    }
  }
コード例 #2
0
  public boolean visit(TypeDeclaration type) throws Exception {
    if (type instanceof NamespaceDeclaration) {
      NamespaceDeclaration namespaceDecl = (NamespaceDeclaration) type;
      fLastNamespace = namespaceDecl;
      fLastUseParts.clear();
      if (namespaceDecl.isGlobal()) {
        return true;
      }
    }
    type.setModifiers(markAsDeprecated(type.getModifiers(), type));

    // In case we are entering a nested element
    if (!declarations.empty() && declarations.peek() instanceof MethodDeclaration) {
      if (fLastNamespace == null) {
        deferredDeclarations.add(type);
      } else {
        deferredNamespacedDeclarations.add(type);
      }
      return false;
    }

    declarations.push(type);

    for (PHPSourceElementRequestorExtension visitor : extensions) {
      visitor.visit(type);
    }
    return super.visit(type);
  }
コード例 #3
0
  /**
   * 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();
      }
    }
  }
コード例 #4
0
 public void createPackageInfoType() {
   TypeDeclaration declaration = new TypeDeclaration(this.compilationResult);
   declaration.name = TypeConstants.PACKAGE_INFO_NAME;
   declaration.modifiers = ClassFileConstants.AccDefault | ClassFileConstants.AccInterface;
   declaration.javadoc = this.javadoc;
   this.types[0] = declaration; // Assumes the first slot is meant for this type
 }
コード例 #5
0
 public void resolve(int start, int end) {
   try {
     int startingTypeIndex = 0;
     // resolve compilation unit javadoc package if any
     if (this.javadoc != null
         && this.javadoc.sourceStart <= start
         && this.javadoc.sourceEnd >= end) {
       this.javadoc.resolve(this.scope);
     }
     if (types != null) {
       for (int i = startingTypeIndex, count = types.length; i < count; i++) {
         TypeDeclaration typeDeclaration = types[i];
         if (typeDeclaration.sourceStart <= start && typeDeclaration.sourceEnd >= end)
           typeDeclaration.resolve(scope);
       }
     }
     if (statements != null) {
       for (int i = 0, count = statements.length; i < count; i++) {
         ProgramElement programElement = statements[i];
         if (programElement.sourceStart <= start && programElement.sourceEnd >= end)
           programElement.resolve(scope);
       }
     }
     reportNLSProblems();
   } catch (AbortCompilationUnit e) {
     this.ignoreFurtherInvestigation = true;
     return;
   }
 }
コード例 #6
0
 public void process() {
   for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
     ExtractInterface annot = typeDecl.getAnnotation(ExtractInterface.class);
     if (annot == null) break;
     for (MethodDeclaration m : typeDecl.getMethods())
       if (m.getModifiers().contains(Modifier.PUBLIC)
           && !(m.getModifiers().contains(Modifier.STATIC))) interfaceMethods.add(m);
     if (interfaceMethods.size() > 0) {
       try {
         PrintWriter writer = env.getFiler().createSourceFile(annot.value());
         writer.println("package " + typeDecl.getPackage().getQualifiedName() + ";");
         writer.println("public interface " + annot.value() + " {");
         for (MethodDeclaration m : interfaceMethods) {
           writer.print("  public ");
           writer.print(m.getReturnType() + " ");
           writer.print(m.getSimpleName() + " (");
           int i = 0;
           for (ParameterDeclaration parm : m.getParameters()) {
             writer.print(parm.getType() + " " + parm.getSimpleName());
             if (++i < m.getParameters().size()) writer.print(", ");
           }
           writer.println(");");
         }
         writer.println("}");
         writer.close();
       } catch (IOException ioe) {
         throw new RuntimeException(ioe);
       }
     }
   }
 }
コード例 #7
0
 /*
  * 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());
 }
コード例 #8
0
  public void resolve() {
    int startingTypeIndex = 0;
    boolean isPackageInfo = false; // isPackageInfo();
    if (this.types != null && isPackageInfo) {
      // resolve synthetic type declaration
      final TypeDeclaration syntheticTypeDeclaration = types[0];
      // set empty javadoc to avoid missing warning (see bug
      // https://bugs.eclipse.org/bugs/show_bug.cgi?id=95286)
      if (syntheticTypeDeclaration.javadoc == null) {
        syntheticTypeDeclaration.javadoc =
            new Javadoc(
                syntheticTypeDeclaration.declarationSourceStart,
                syntheticTypeDeclaration.declarationSourceStart);
      }
      syntheticTypeDeclaration.resolve(this.scope);
      // resolve annotations if any
      //			if (this.currentPackage!= null && this.currentPackage.annotations != null) {
      //				resolveAnnotations(syntheticTypeDeclaration.staticInitializerScope,
      // this.currentPackage.annotations, this.scope.getDefaultPackage());
      //			}
      // resolve javadoc package if any
      if (this.javadoc != null) {
        this.javadoc.resolve(syntheticTypeDeclaration.staticInitializerScope);
      }
      startingTypeIndex = 1;
    } else {
      // resolve compilation unit javadoc package if any
      if (this.javadoc != null) {
        this.javadoc.resolve(this.scope);
      }
    }

    try {
      if (types != null) {
        for (int i = startingTypeIndex, count = types.length; i < count; i++) {
          types[i].resolve(scope);
        }
      }
      if (statements != null) {
        for (int i = 0, count = statements.length; i < count; i++) {
          statements[i].resolve(scope);
        }
      }
      reportNLSProblems();
    } catch (AbortCompilationUnit e) {
      this.ignoreFurtherInvestigation = true;
      return;
    }
  }
コード例 #9
0
 public void resolve() {
   int startingTypeIndex = 0;
   boolean isPackageInfo = isPackageInfo();
   if (this.types != null && isPackageInfo) {
     // resolve synthetic type declaration
     final TypeDeclaration syntheticTypeDeclaration = this.types[0];
     // set empty javadoc to avoid missing warning (see bug
     // https://bugs.eclipse.org/bugs/show_bug.cgi?id=95286)
     if (syntheticTypeDeclaration.javadoc == null) {
       syntheticTypeDeclaration.javadoc =
           new Javadoc(
               syntheticTypeDeclaration.declarationSourceStart,
               syntheticTypeDeclaration.declarationSourceStart);
     }
     syntheticTypeDeclaration.resolve(this.scope);
     /*
      * resolve javadoc package if any, skip this step if we don't have a valid scope due to an earlier error (bug 252555)
      * we do it now as the javadoc in the fake type won't be resolved. The peculiar usage of MethodScope to resolve the
      * package level javadoc is because the CU level resolve method	is a NOP to mimic Javadoc's behavior and can't be used
      * as such.
      */
     if (this.javadoc != null && syntheticTypeDeclaration.staticInitializerScope != null) {
       this.javadoc.resolve(syntheticTypeDeclaration.staticInitializerScope);
     }
     startingTypeIndex = 1;
   } else {
     // resolve compilation unit javadoc package if any
     if (this.javadoc != null) {
       this.javadoc.resolve(this.scope);
     }
   }
   if (this.currentPackage != null && this.currentPackage.annotations != null && !isPackageInfo) {
     this.scope
         .problemReporter()
         .invalidFileNameForPackageAnnotations(this.currentPackage.annotations[0]);
   }
   try {
     if (this.types != null) {
       for (int i = startingTypeIndex, count = this.types.length; i < count; i++) {
         this.types[i].resolve(this.scope);
       }
     }
     if (!this.compilationResult.hasMandatoryErrors()) checkUnusedImports();
     reportNLSProblems();
   } catch (AbortCompilationUnit e) {
     this.ignoreFurtherInvestigation = true;
     return;
   }
 }
コード例 #10
0
  /** Generates a dex file and returns its bytes. */
  public byte[] generate() {
    DexOptions options = new DexOptions();
    options.targetApiLevel = DexFormat.API_NO_EXTENDED_OPCODES;
    DexFile outputDex = new DexFile(options);

    for (TypeDeclaration typeDeclaration : types.values()) {
      outputDex.add(typeDeclaration.toClassDefItem());
    }

    try {
      return outputDex.toDex(null, false);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #11
0
    @Override
    public void process(CompilationUnitDeclaration cud, int i) {
      super.process(cud, i);
      ClassFile[] classFiles = cud.compilationResult().getClassFiles();
      Map<ClassFile, CompiledClass> results = new LinkedHashMap<ClassFile, CompiledClass>();
      for (ClassFile classFile : classFiles) {
        createCompiledClass(classFile, results);
      }
      List<CompiledClass> compiledClasses = new ArrayList<CompiledClass>(results.values());
      addBinaryTypes(compiledClasses);

      ICompilationUnit icu = cud.compilationResult().compilationUnit;
      Adapter adapter = (Adapter) icu;
      CompilationUnitBuilder builder = adapter.getBuilder();

      // TODO this code was added for the arquillian gwt extension
      if (cud.types != null) {
        for (TypeDeclaration type : cud.types) {
          if (type.methods != null) {
            if (isAnnotationPresent(RunWith.class.getSimpleName(), type.annotations)) {
              Set<AbstractMethodDeclaration> filteredMethods =
                  new HashSet<AbstractMethodDeclaration>();
              boolean match = false;
              for (AbstractMethodDeclaration decl : type.methods) {
                if (decl.annotations != null) {
                  // TODO make this configurable
                  if ((isAnnotationPresent(RunAsGwtClient.class.getSimpleName(), decl.annotations)
                          || isAnnotationPresent(
                              RunAsGwtClient.class.getSimpleName(), type.annotations))
                      && !isAnnotationPresent(Deployment.class.getSimpleName(), decl.annotations)) {
                    filteredMethods.add(decl);
                  } else {
                    match = true;
                    System.out.println("Ignoring non-translatable method:\n" + decl.toString());
                  }
                }
              }
              if (match) {
                type.methods =
                    filteredMethods.toArray(new AbstractMethodDeclaration[filteredMethods.size()]);
              }
            }
          }
        }
      }

      processor.process(builder, cud, compiledClasses);
    }
コード例 #12
0
  protected void classInstanceCreation(boolean alwaysQualified) {
    // ClassInstanceCreationExpression ::= 'new' ClassType '(' ArgumentListopt ')' ClassBodyopt

    // ClassBodyopt produces a null item on the astStak if it produces NO class body
    // An empty class body produces a 0 on the length stack.....

    AllocationExpression alloc;
    int length;
    if (((length = this.astLengthStack[this.astLengthPtr--]) == 1)
        && (this.astStack[this.astPtr] == null)) {
      // NO ClassBody
      this.astPtr--;
      if (alwaysQualified) {
        alloc = new QualifiedAllocationExpression();
      } else {
        alloc = new CodeSnippetAllocationExpression(this.evaluationContext);
      }
      alloc.sourceEnd = this.endPosition; // the position has been stored explicitly

      if ((length = this.expressionLengthStack[this.expressionLengthPtr--]) != 0) {
        this.expressionPtr -= length;
        System.arraycopy(
            this.expressionStack,
            this.expressionPtr + 1,
            alloc.arguments = new Expression[length],
            0,
            length);
      }
      alloc.type = getTypeReference(0);
      // the default constructor with the correct number of argument
      // will be created and added by the TC (see createsInternalConstructorWithBinding)
      alloc.sourceStart = this.intStack[this.intPtr--];
      pushOnExpressionStack(alloc);
    } else {
      dispatchDeclarationInto(length);
      TypeDeclaration anonymousTypeDeclaration = (TypeDeclaration) this.astStack[this.astPtr];
      anonymousTypeDeclaration.declarationSourceEnd = this.endStatementPosition;
      if (anonymousTypeDeclaration.allocation != null) {
        anonymousTypeDeclaration.allocation.sourceEnd = this.endStatementPosition;
      }
      this.astPtr--;
      this.astLengthPtr--;

      // mark initializers with local type mark if needed
      markInitializersWithLocalType(anonymousTypeDeclaration);
    }
  }
コード例 #13
0
 private static String loadPath(TypeDeclaration delegate) {
   Path path = delegate.getAnnotation(Path.class);
   if (path == null) {
     throw new IllegalArgumentException(
         "A JAX-RS root resource must be annotated with @javax.ws.rs.Path.");
   }
   return path.value();
 }
コード例 #14
0
ファイル: XMLSchema.java プロジェクト: wilden/deegree2-base
 private void resolveReferences(TypeDeclaration typeDeclaration)
     throws UnresolvableReferenceException {
   LOG.logDebug(
       "Resolving references in type declaration '"
           + typeDeclaration.getName().getLocalName()
           + "'.");
   if (typeDeclaration instanceof SimpleTypeDeclaration) {
     LOG.logDebug("SimpleType.");
     SimpleTypeDeclaration simpleType = (SimpleTypeDeclaration) typeDeclaration;
     TypeReference typeReference = simpleType.getRestrictionBaseType();
     if (typeReference != null) {
       LOG.logDebug("restriction base='" + typeReference.getName() + "'");
       try {
         resolveType(typeReference);
       } catch (XMLSchemaException e) {
         throw new UndefinedXSDTypeException(
             "Declaration of type '"
                 + typeDeclaration.getName()
                 + "' derives type '"
                 + typeReference.getName()
                 + "' which is not a defined simple type.");
       }
     }
   } else {
     LOG.logDebug("ComplexType.");
     ComplexTypeDeclaration complexType = (ComplexTypeDeclaration) typeDeclaration;
     TypeReference typeReference = complexType.getExtensionBaseType();
     if (typeReference != null) {
       LOG.logDebug("extension base='" + typeReference.getName() + "'");
       try {
         resolveType(typeReference);
       } catch (XMLSchemaException e) {
         throw new UndefinedXSDTypeException(
             "Declaration of type '"
                 + typeDeclaration.getName()
                 + "' derives type '"
                 + typeReference.getName()
                 + "' which is not a defined complex type.");
       }
     }
     ElementDeclaration[] elements = complexType.getExplicitElements();
     for (int i = 0; i < elements.length; i++) {
       resolveReferences(elements[i]);
     }
   }
 }
コード例 #15
0
ファイル: Import.java プロジェクト: davidfestal/ceylon-spec
 @Override
 public String toString() {
   return "Import["
       + alias
       + "="
       + (typeDeclaration == null ? "" : typeDeclaration.getName())
       + declaration.getName()
       + "]";
 }
コード例 #16
0
ファイル: CompilationUnit.java プロジェクト: RPI-WCL/salsa2
 public List<String> generateJavaCode() throws IOException {
   List<String> generatedFiles = new ArrayList<String>();
   String header = this.getHeaderCode("");
   for (Iterator<TypeDeclaration> it = typeDeclarations.iterator(); it.hasNext(); ) {
     TypeDeclaration td = it.next();
     if (td instanceof BehaviorDeclaration) {
       BehaviorDeclaration bd = (BehaviorDeclaration) td;
       String refFileName = sourceDirName + File.separator + bd.getName() + ".java";
       writeFile(refFileName, header + bd.toJavaRefCode(""));
       String stateFileName = sourceDirName + File.separator + td.getName() + "State.java";
       writeFile(stateFileName, header + bd.toJavaCode(""));
       generatedFiles.add(refFileName);
       generatedFiles.add(stateFileName);
     } else if (td instanceof ClassDeclaration) {
       String classFileName = sourceDirName + File.separator + td.getName() + ".java";
       writeFile(classFileName, header + td.toJavaCode(""));
       generatedFiles.add(classFileName);
     }
   }
   return generatedFiles;
 }
コード例 #17
0
  /**
   * Visits a type declaration.
   *
   * @param d the declaration to visit
   */
  public void visitTypeDeclaration(TypeDeclaration d) {
    d.accept(pre);

    SortedSet<Declaration> decls = new TreeSet<Declaration>(SourceOrderDeclScanner.comparator);

    for (TypeParameterDeclaration tpDecl : d.getFormalTypeParameters()) {
      decls.add(tpDecl);
    }

    for (FieldDeclaration fieldDecl : d.getFields()) {
      decls.add(fieldDecl);
    }

    for (MethodDeclaration methodDecl : d.getMethods()) {
      decls.add(methodDecl);
    }

    for (TypeDeclaration typeDecl : d.getNestedTypes()) {
      decls.add(typeDecl);
    }

    for (Declaration decl : decls) decl.accept(this);

    d.accept(post);
  }
コード例 #18
0
  /**
   * 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());
  }
コード例 #19
0
 protected String[] processSuperClasses(TypeDeclaration type) {
   ASTListNode superClasses = type.getSuperClasses();
   if (superClasses == null) {
     return new String[] {};
   }
   List<ASTNode> superClassNames = superClasses.getChilds();
   List<String> result = new ArrayList<String>(superClassNames.size());
   Iterator<ASTNode> iterator = superClassNames.iterator();
   while (iterator.hasNext()) {
     String name = processNameNode(iterator.next());
     if (name != null) {
       result.add(name);
     }
   }
   return (String[]) result.toArray(new String[result.size()]);
 }
コード例 #20
0
 /**
  * Declares {@code type}.
  *
  * @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link Modifier#FINAL} and
  *     {@link Modifier#ABSTRACT}.
  */
 public void declare(
     TypeId<?> type, String sourceFile, int flags, TypeId<?> supertype, TypeId<?>... interfaces) {
   TypeDeclaration declaration = getTypeDeclaration(type);
   int supportedFlags = Modifier.PUBLIC | Modifier.FINAL | Modifier.ABSTRACT;
   if ((flags & ~supportedFlags) != 0) {
     throw new IllegalArgumentException("Unexpected flag: " + Integer.toHexString(flags));
   }
   if (declaration.declared) {
     throw new IllegalStateException("already declared: " + type);
   }
   declaration.declared = true;
   declaration.flags = flags;
   declaration.supertype = supertype;
   declaration.sourceFile = sourceFile;
   declaration.interfaces = new TypeList(interfaces);
 }
コード例 #21
0
 /*
  * @see ASTVisitor#visit(TypeDeclaration)
  */
 @Override
 public boolean visit(TypeDeclaration node) {
   if (node.getJavadoc() != null) {
     node.getJavadoc().accept(this);
   }
   if (node.getAST().apiLevel() >= JLS3) {
     printModifiers(node.modifiers());
   }
   this.fBuffer.append(node.isInterface() ? "interface " : "class "); // $NON-NLS-2$//$NON-NLS-1$
   node.getName().accept(this);
   if (node.getAST().apiLevel() >= JLS3) {
     if (!node.typeParameters().isEmpty()) {
       this.fBuffer.append("<"); // $NON-NLS-1$
       for (Iterator<TypeParameter> it = node.typeParameters().iterator(); it.hasNext(); ) {
         TypeParameter t = it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(","); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(">"); // $NON-NLS-1$
     }
   }
   this.fBuffer.append(" "); // $NON-NLS-1$
   if (node.getAST().apiLevel() >= JLS3) {
     if (node.getSuperclassType() != null) {
       this.fBuffer.append("extends "); // $NON-NLS-1$
       node.getSuperclassType().accept(this);
       this.fBuffer.append(" "); // $NON-NLS-1$
     }
     if (!node.superInterfaceTypes().isEmpty()) {
       this.fBuffer.append(
           node.isInterface() ? "extends " : "implements "); // $NON-NLS-2$//$NON-NLS-1$
       for (Iterator<Type> it = node.superInterfaceTypes().iterator(); it.hasNext(); ) {
         Type t = it.next();
         t.accept(this);
         if (it.hasNext()) {
           this.fBuffer.append(", "); // $NON-NLS-1$
         }
       }
       this.fBuffer.append(" "); // $NON-NLS-1$
     }
   }
   this.fBuffer.append("{"); // $NON-NLS-1$
   BodyDeclaration prev = null;
   for (Iterator<BodyDeclaration> it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
     BodyDeclaration d = it.next();
     if (prev instanceof EnumConstantDeclaration) {
       // enum constant declarations do not include punctuation
       if (d instanceof EnumConstantDeclaration) {
         // enum constant declarations are separated by commas
         this.fBuffer.append(", "); // $NON-NLS-1$
       } else {
         // semicolon separates last enum constant declaration from
         // first class body declarations
         this.fBuffer.append("; "); // $NON-NLS-1$
       }
     }
     d.accept(this);
     prev = d;
   }
   this.fBuffer.append("}"); // $NON-NLS-1$
   return false;
 }
コード例 #22
0
  /*
   * Returns the handles of the super interfaces of the given type.
   * Adds the simple name to the hierarchy missing types if an interface is not found (but don't put null in the returned array)
   */
  private IType[] findSuperInterfaces(IGenericType type, ReferenceBinding typeBinding) {
    char[][] superInterfaceNames;
    char separator;
    if (type instanceof IBinaryType) {
      superInterfaceNames = ((IBinaryType) type).getInterfaceNames();
      separator = '/';
    } else if (type instanceof ISourceType) {
      ISourceType sourceType = (ISourceType) type;
      if (sourceType.isAnonymous()) { // if anonymous type
        if (typeBinding.superInterfaces() != null && typeBinding.superInterfaces().length > 0) {
          superInterfaceNames = new char[][] {sourceType.getSuperclassName()};
        } else {
          superInterfaceNames = sourceType.getInterfaceNames();
        }
      } else {
        if (TypeDeclaration.kind(sourceType.getModifiers()) == TypeDeclaration.ANNOTATION_TYPE_DECL)
          superInterfaceNames =
              new char[][] {TypeConstants.CharArray_JAVA_LANG_ANNOTATION_ANNOTATION};
        else superInterfaceNames = sourceType.getInterfaceNames();
      }
      separator = '.';
    } else if (type instanceof HierarchyType) {
      HierarchyType hierarchyType = (HierarchyType) type;
      if (hierarchyType.isAnonymous()) { // if anonymous type
        if (typeBinding.superInterfaces() != null && typeBinding.superInterfaces().length > 0) {
          superInterfaceNames = new char[][] {hierarchyType.superclassName};
        } else {
          superInterfaceNames = hierarchyType.superInterfaceNames;
        }
      } else {
        superInterfaceNames = hierarchyType.superInterfaceNames;
      }
      separator = '.';
    } else {
      return null;
    }

    ReferenceBinding[] interfaceBindings = typeBinding.superInterfaces();
    int bindingIndex = 0;
    int bindingLength = interfaceBindings == null ? 0 : interfaceBindings.length;
    int length = superInterfaceNames == null ? 0 : superInterfaceNames.length;
    IType[] superinterfaces = new IType[length];
    int index = 0;
    next:
    for (int i = 0; i < length; i++) {
      char[] superInterfaceName = superInterfaceNames[i];
      int end = superInterfaceName.length;

      // find the end of simple name
      int genericStart = CharOperation.indexOf(Signature.C_GENERIC_START, superInterfaceName);
      if (genericStart != -1) end = genericStart;

      // find the start of simple name
      int lastSeparator = CharOperation.lastIndexOf(separator, superInterfaceName, 0, end);
      int start = lastSeparator + 1;

      // case of binary inner type -> take the last part
      int lastDollar = CharOperation.lastIndexOf('$', superInterfaceName, start);
      if (lastDollar != -1) start = lastDollar + 1;

      char[] simpleName = CharOperation.subarray(superInterfaceName, start, end);

      if (bindingIndex < bindingLength) {
        ReferenceBinding interfaceBinding =
            (ReferenceBinding) interfaceBindings[bindingIndex].erasure();

        // ensure that the binding corresponds to the interface defined by the user
        if (CharOperation.equals(simpleName, interfaceBinding.sourceName)) {
          bindingIndex++;
          for (int t = this.typeIndex; t >= 0; t--) {
            if (TypeBinding.equalsEquals(this.typeBindings[t], interfaceBinding)) {
              IType handle = this.builder.getHandle(this.typeModels[t], interfaceBinding);
              if (handle != null) {
                superinterfaces[index++] = handle;
                continue next;
              }
            }
          }
        }
      }
      this.builder.hierarchy.missingTypes.add(new String(simpleName));
    }
    if (index != length)
      System.arraycopy(superinterfaces, 0, superinterfaces = new IType[index], 0, index);
    return superinterfaces;
  }
コード例 #23
0
 protected String[] processSuperClasses(TypeDeclaration type) {
   ASTListNode superClasses = type.getSuperClasses();
   if (superClasses == null) {
     return new String[] {};
   }
   List<ASTNode> superClassNames = superClasses.getChilds();
   List<String> result = new ArrayList<String>(superClassNames.size());
   Iterator<ASTNode> iterator = superClassNames.iterator();
   while (iterator.hasNext()) {
     ASTNode nameNode = iterator.next();
     String name;
     if (nameNode instanceof FullyQualifiedReference) {
       FullyQualifiedReference fullyQualifiedName = (FullyQualifiedReference) nameNode;
       name = fullyQualifiedName.getFullyQualifiedName();
       if (fullyQualifiedName.getNamespace() != null) {
         String namespace = fullyQualifiedName.getNamespace().getName();
         String subnamespace = ""; // $NON-NLS-1$
         if (namespace.charAt(0) != NamespaceReference.NAMESPACE_SEPARATOR
             && namespace.indexOf(NamespaceReference.NAMESPACE_SEPARATOR) > 0) {
           int firstNSLocation = namespace.indexOf(NamespaceReference.NAMESPACE_SEPARATOR);
           subnamespace = namespace.substring(firstNSLocation);
           namespace = namespace.substring(0, firstNSLocation);
         }
         if (name.charAt(0) == NamespaceReference.NAMESPACE_SEPARATOR) {
           name = name.substring(1);
         } else if (fLastUseParts.containsKey(namespace)) {
           name =
               new StringBuilder(
                       fLastUseParts.get(namespace).getNamespace().getFullyQualifiedName())
                   .append(subnamespace)
                   .append(NamespaceReference.NAMESPACE_SEPARATOR)
                   .append(fullyQualifiedName.getName())
                   .toString();
         } else if (fCurrentNamespace != null) {
           name =
               new StringBuilder(fCurrentNamespace.getName())
                   .append(NamespaceReference.NAMESPACE_SEPARATOR)
                   .append(name)
                   .toString();
         }
       } else if (fLastUseParts.containsKey(name)) {
         name = fLastUseParts.get(name).getNamespace().getFullyQualifiedName();
         if (name.charAt(0) == NamespaceReference.NAMESPACE_SEPARATOR) {
           name = name.substring(1);
         }
       } else {
         if (fCurrentNamespace != null) {
           name =
               new StringBuilder(fCurrentNamespace.getName())
                   .append(NamespaceReference.NAMESPACE_SEPARATOR)
                   .append(name)
                   .toString();
         }
       }
       result.add(name);
     } else if (nameNode instanceof SimpleReference) {
       result.add(((SimpleReference) nameNode).getName());
     }
   }
   return (String[]) result.toArray(new String[result.size()]);
 }
コード例 #24
0
  public boolean visit(TypeDeclaration type) throws Exception {
    if (type instanceof NamespaceDeclaration) {
      NamespaceDeclaration namespaceDecl = (NamespaceDeclaration) type;
      fCurrentNamespace = namespaceDecl;
      fLastUseParts.clear();
      if (namespaceDecl.isGlobal()) {
        return visitGeneral(type);
      }
      declarations.push(type);

      int modifiers = type.getModifiers() | Modifiers.AccNameSpace;
      fCurrentQualifier = type.getName();
      Integer count = fCurrentQualifierCounts.get(fCurrentQualifier);
      count = count != null ? count + 1 : 1;
      fCurrentQualifierCounts.put(fCurrentQualifier, count);

      modifiers = markAsDeprecated(modifiers, type);
      StringBuilder metadata = new StringBuilder();
      if (fCurrentQualifier != null) {
        metadata.append(fCurrentQualifierCounts.get(fCurrentQualifier));
        metadata.append(";"); // $NON-NLS-1$
      }
      modifyDeclaration(
          type,
          new DeclarationInfo(
              IModelElement.PACKAGE_DECLARATION,
              modifiers,
              type.sourceStart(),
              type.sourceEnd() - type.sourceStart(),
              type.getNameStart(),
              type.getNameEnd() - type.getNameStart(),
              type.getName(),
              metadata.length() == 0 ? null : metadata.toString(),
              encodeDocInfo(type),
              null,
              null));
    } else {
      Declaration parentDeclaration = null;
      if (!declarations.empty()) {
        parentDeclaration = declarations.peek();
      }
      declarations.push(type);

      if (!(parentDeclaration instanceof NamespaceDeclaration)) {
        type.setModifier(Modifiers.AccGlobal);
      }

      // In case we are entering a nested element
      if (parentDeclaration instanceof MethodDeclaration) {
        if (fCurrentNamespace == null) {
          deferredDeclarations.add(type);
        } else {
          deferredNamespacedDeclarations.add(type);
        }
        return visitGeneral(type);
      }

      int modifiers = type.getModifiers();
      fCurrentParent = type.getName();

      String[] superClasses = processSuperClasses(type);
      StringBuilder metadata = new StringBuilder();
      if (fCurrentQualifier != null) {
        metadata.append(fCurrentQualifierCounts.get(fCurrentQualifier));
        metadata.append(";"); // $NON-NLS-1$
      }
      for (int i = 0; i < superClasses.length; ++i) {
        metadata.append(superClasses[i]);
        if (i < superClasses.length - 1) {
          metadata.append(","); // $NON-NLS-1$
        }
      }
      modifiers = markAsDeprecated(modifiers, type);
      modifyDeclaration(
          type,
          new DeclarationInfo(
              IModelElement.TYPE,
              modifiers,
              type.sourceStart(),
              type.sourceEnd() - type.sourceStart(),
              type.getNameStart(),
              type.getNameEnd() - type.getNameStart(),
              type.getName(),
              metadata.length() == 0 ? null : metadata.toString(),
              encodeDocInfo(type),
              fCurrentQualifier,
              null));
    }

    for (PhpIndexingVisitorExtension visitor : extensions) {
      visitor.visit(type);
    }

    return visitGeneral(type);
  }
コード例 #25
0
  protected void consumeClassHeaderName1() {
    // ClassHeaderName ::= Modifiersopt 'class' 'Identifier'
    TypeDeclaration typeDecl;
    if (this.nestedMethod[this.nestedType] == 0) {
      if (this.nestedType != 0) {
        typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult);
        typeDecl.bits |= ASTNode.IsMemberTypeMASK;
      } else {
        typeDecl = new CodeSnippetTypeDeclaration(this.compilationUnit.compilationResult);
      }
    } else {
      // Record that the block has a declaration for local types
      typeDecl = new TypeDeclaration(this.compilationUnit.compilationResult);
      typeDecl.bits |= ASTNode.IsLocalTypeMASK;
      markEnclosingMemberWithLocalType();
      blockReal();
    }

    // highlight the name of the type
    long pos = this.identifierPositionStack[this.identifierPtr];
    typeDecl.sourceEnd = (int) pos;
    typeDecl.sourceStart = (int) (pos >>> 32);
    typeDecl.name = this.identifierStack[this.identifierPtr--];
    this.identifierLengthPtr--;

    // compute the declaration source too
    typeDecl.declarationSourceStart = this.intStack[this.intPtr--];
    this.intPtr--;
    // 'class' and 'interface' push an int position
    typeDecl.modifiersSourceStart = this.intStack[this.intPtr--];
    typeDecl.modifiers = this.intStack[this.intPtr--];
    if (typeDecl.modifiersSourceStart >= 0) {
      typeDecl.declarationSourceStart = typeDecl.modifiersSourceStart;
    }
    typeDecl.bodyStart = typeDecl.sourceEnd + 1;
    pushOnAstStack(typeDecl);

    this.listLength = 0; // will be updated when reading super-interfaces
    // recovery
    if (this.currentElement != null) {
      this.lastCheckPoint = typeDecl.bodyStart;
      this.currentElement = this.currentElement.add(typeDecl, 0);
      this.lastIgnoredToken = -1;
    }
    // javadoc
    typeDecl.javadoc = this.javadoc;
    this.javadoc = null;
  }
コード例 #26
0
  /**
   * Bytecode generation for a method
   *
   * @param classScope
   * @param classFile
   */
  public void generateCode(ClassScope classScope, ClassFile classFile) {

    classFile.codeStream.wideMode = false; // reset wideMode to false
    if (this.ignoreFurtherInvestigation) {
      // method is known to have errors, dump a problem method
      if (this.binding == null) return; // handle methods with invalid signature or duplicates
      int problemsLength;
      CategorizedProblem[] problems =
          this.scope.referenceCompilationUnit().compilationResult.getProblems();
      CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
      System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
      classFile.addProblemMethod(this, this.binding, problemsCopy);
      return;
    }
    int problemResetPC = 0;
    CompilationResult unitResult = null;
    int problemCount = 0;
    if (classScope != null) {
      TypeDeclaration referenceContext = classScope.referenceContext;
      if (referenceContext != null) {
        unitResult = referenceContext.compilationResult();
        problemCount = unitResult.problemCount;
      }
    }
    boolean restart = false;
    boolean abort = false;
    // regular code generation
    do {
      try {
        problemResetPC = classFile.contentsOffset;
        this.generateCode(classFile);
        restart = false;
      } catch (AbortMethod e) {
        // a fatal error was detected during code generation, need to restart code gen if possible
        if (e.compilationResult == CodeStream.RESTART_IN_WIDE_MODE) {
          // a branch target required a goto_w, restart code gen in wide mode.
          classFile.contentsOffset = problemResetPC;
          classFile.methodCount--;
          classFile.codeStream.resetInWideMode(); // request wide mode
          // reset the problem count to prevent reporting the same warning twice
          if (unitResult != null) {
            unitResult.problemCount = problemCount;
          }
          restart = true;
        } else if (e.compilationResult == CodeStream.RESTART_CODE_GEN_FOR_UNUSED_LOCALS_MODE) {
          classFile.contentsOffset = problemResetPC;
          classFile.methodCount--;
          classFile.codeStream.resetForCodeGenUnusedLocals();
          // reset the problem count to prevent reporting the same warning twice
          if (unitResult != null) {
            unitResult.problemCount = problemCount;
          }
          restart = true;
        } else {
          restart = false;
          abort = true;
        }
      }
    } while (restart);
    // produce a problem method accounting for this fatal error
    if (abort) {
      int problemsLength;
      CategorizedProblem[] problems =
          this.scope.referenceCompilationUnit().compilationResult.getAllProblems();
      CategorizedProblem[] problemsCopy = new CategorizedProblem[problemsLength = problems.length];
      System.arraycopy(problems, 0, problemsCopy, 0, problemsLength);
      classFile.addProblemMethod(this, this.binding, problemsCopy, problemResetPC);
    }
  }
コード例 #27
0
  /*
   * INTERNAL USE-ONLY
   * Innerclasses get their name computed as they are generated, since some may not
   * be actually outputed if sitting inside unreachable code.
   */
  public char[] computeConstantPoolName(LocalTypeBinding localType) {
    if (localType.constantPoolName != null) {
      return localType.constantPoolName;
    }
    // delegates to the outermost enclosing classfile, since it is the only one with a global vision
    // of its innertypes.

    if (this.constantPoolNameUsage == null) this.constantPoolNameUsage = new HashtableOfType();

    ReferenceBinding outerMostEnclosingType =
        localType.scope.outerMostClassScope().enclosingSourceType();

    // ensure there is not already such a local type name defined by the user
    int index = 0;
    char[] candidateName;
    boolean isCompliant15 = compilerOptions().complianceLevel >= ClassFileConstants.JDK1_5;
    while (true) {
      if (localType.isMemberType()) {
        if (index == 0) {
          candidateName =
              CharOperation.concat(
                  localType.enclosingType().constantPoolName(), localType.sourceName, '$');
        } else {
          // in case of collision, then member name gets extra $1 inserted
          // e.g. class X { { class L{} new X(){ class L{} } } }
          candidateName =
              CharOperation.concat(
                  localType.enclosingType().constantPoolName(),
                  '$',
                  String.valueOf(index).toCharArray(),
                  '$',
                  localType.sourceName);
        }
      } else if (localType.isAnonymousType()) {
        if (isCompliant15) {
          // AspectJ Extension start
          char[] extraInsert = null;
          if (outerMostEnclosingType instanceof SourceTypeBinding) {
            SourceTypeBinding sourceTypeBinding = (SourceTypeBinding) outerMostEnclosingType;
            ClassScope classScope = sourceTypeBinding.scope;
            if (classScope != null) {
              TypeDeclaration typeDeclaration = classScope.referenceContext;
              if (typeDeclaration != null) {
                extraInsert = typeDeclaration.getLocalTypeNameSuffix();
              }
            }
          }
          if (extraInsert != null) { // AspectJ Extension end
            candidateName =
                CharOperation.concat(
                    localType.enclosingType.constantPoolName(),
                    '$',
                    extraInsert,
                    '$',
                    String.valueOf(index + 1).toCharArray());
          } else {
            // from 1.5 on, use immediately enclosing type name
            candidateName =
                CharOperation.concat(
                    localType.enclosingType.constantPoolName(),
                    String.valueOf(index + 1).toCharArray(),
                    '$');
          } // AspectJ extension, closing }
        } else {
          candidateName =
              CharOperation.concat(
                  outerMostEnclosingType.constantPoolName(),
                  String.valueOf(index + 1).toCharArray(),
                  '$');
        }
      } else {
        // local type
        if (isCompliant15) {
          candidateName =
              CharOperation.concat(
                  CharOperation.concat(
                      localType.enclosingType().constantPoolName(),
                      String.valueOf(index + 1).toCharArray(),
                      '$'),
                  localType.sourceName);
        } else {
          candidateName =
              CharOperation.concat(
                  outerMostEnclosingType.constantPoolName(),
                  '$',
                  String.valueOf(index + 1).toCharArray(),
                  '$',
                  localType.sourceName);
        }
      }
      if (this.constantPoolNameUsage.get(candidateName) != null) {
        index++;
      } else {
        this.constantPoolNameUsage.put(candidateName, localType);
        break;
      }
    }
    return candidateName;
  }
コード例 #28
0
 public QualifiedAllocationExpression(TypeDeclaration anonymousType) {
   this.anonymousType = anonymousType;
   anonymousType.allocation = this;
 }