Example usage for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration CompilationUnitDeclaration

List of usage examples for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration CompilationUnitDeclaration

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration CompilationUnitDeclaration.

Prototype

public CompilationUnitDeclaration(ProblemReporter problemReporter, CompilationResult compilationResult,
            int sourceLength) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

/**
 * Asks the engine to compute the selection of the given type
 * from the given context//from   ww  w  .ja  v a2 s  .  c o  m
 *
 *  @param typeName char[]
 *      a type name which is to be resolved in the context of a compilation unit.
 *      NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left)
 *
 *  @param context org.eclipse.jdt.core.IType
 *      the context in which code assist is invoked.
 */
public void selectType(char[] typeName, IType context) throws JavaModelException {
    try {
        this.acceptedAnswer = false;

        // only the type erasure are returned by IType.resolvedType(...)
        if (CharOperation.indexOf('<', typeName) != -1) {
            char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
            typeSig = Signature.getTypeErasure(typeSig);
            typeName = Signature.toCharArray(typeSig);
        }

        CompilationUnitDeclaration parsedUnit = null;
        TypeDeclaration typeDeclaration = null;
        org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit();
        if (cu != null) {
            IType[] topLevelTypes = cu.getTypes();
            int length = topLevelTypes.length;
            SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
            for (int i = 0; i < length; i++) {
                topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo();
            }
            CompilationResult result = new CompilationResult(
                    (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) cu, 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
            if (context.isAnonymous() || context.isLocal())
                flags |= SourceTypeConverter.LOCAL_TYPE;
            parsedUnit = SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags,
                    this.parser.problemReporter(), result);
            if (parsedUnit != null && parsedUnit.types != null) {
                if (DEBUG) {
                    System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                    System.out.println(parsedUnit.toString());
                }
                // find the type declaration that corresponds to the original source type
                typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context);
            }
        } else { // binary type
            ClassFile classFile = (ClassFile) context.getClassFile();
            ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo(
                    (IFile) null/*classFile.resource()*/,
                    false/*don't fully initialize so as to keep constant pool (used below)*/);
            CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0);
            HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray();

            BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result,
                    typeNames);
            typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit);
            parsedUnit.imports = converter.buildImports(reader);
        }

        if (typeDeclaration != null) {

            // add fake field with the type we're looking for
            // note: since we didn't ask for fields above, there is no field defined yet
            FieldDeclaration field = new FieldDeclaration();
            int dot;
            if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
                this.selectedIdentifier = typeName;
                field.type = new SelectionOnSingleTypeReference(typeName, -1);
                // position not used
            } else {
                char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
                char[] selectionIdentifier = CharOperation.subarray(typeName, dot + 1, typeName.length);
                this.selectedIdentifier = selectionIdentifier;
                field.type = new SelectionOnQualifiedTypeReference(previousIdentifiers, selectionIdentifier,
                        new long[previousIdentifiers.length + 1]);
            }
            field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
            typeDeclaration.fields = new FieldDeclaration[] { field };

            // build bindings
            this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
            if ((this.unitScope = parsedUnit.scope) != null) {
                try {
                    // build fields
                    // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
                    this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                    // resolve
                    parsedUnit.scope.faultInTypes();
                    parsedUnit.resolve();
                } catch (SelectionNodeFound e) {
                    if (e.binding != null) {
                        if (DEBUG) {
                            System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$
                            System.out.println(e.binding.toString());
                        }
                        // if null then we found a problem in the selection node
                        selectFrom(e.binding, parsedUnit, e.isDeclaration);
                    }
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
    } finally {
        reset(true);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.compiler.parser.SourceTypeConverter.java

License:Open Source License

private CompilationUnitDeclaration convert(ISourceType[] sourceTypes, CompilationResult compilationResult)
        throws JavaModelException {
    this.unit = new CompilationUnitDeclaration(this.problemReporter, compilationResult, 0);
    // not filled at this point

    if (sourceTypes.length == 0)
        return this.unit;
    SourceTypeElementInfo topLevelTypeInfo = (SourceTypeElementInfo) sourceTypes[0];
    org.eclipse.jdt.core.ICompilationUnit cuHandle = topLevelTypeInfo.getHandle().getCompilationUnit();
    this.cu = (ICompilationUnit) cuHandle;

    final CompilationUnitElementInfo compilationUnitElementInfo = (CompilationUnitElementInfo) ((JavaElement) this.cu)
            .getElementInfo();/*from w  w  w  .j  a v a  2s  .  co m*/
    if (this.has1_5Compliance
            && (compilationUnitElementInfo.annotationNumber >= CompilationUnitElementInfo.ANNOTATION_THRESHOLD_FOR_DIET_PARSE
                    || (compilationUnitElementInfo.hasFunctionalTypes && (this.flags & LOCAL_TYPE) != 0))) {
        // If more than 10 annotations, diet parse as this is faster, but not if
        // the client wants local and anonymous types to be converted (https://bugs.eclipse.org/bugs/show_bug.cgi?id=254738)
        // Also see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=405843
        if ((this.flags & LOCAL_TYPE) == 0) {
            return new Parser(this.problemReporter, true).dietParse(this.cu, compilationResult);
        } else {
            return new Parser(this.problemReporter, true).parse(this.cu, compilationResult);
        }
    }

    /* only positions available */
    int start = topLevelTypeInfo.getNameSourceStart();
    int end = topLevelTypeInfo.getNameSourceEnd();

    /* convert package and imports */
    String[] packageName = ((PackageFragment) cuHandle.getParent()).names;
    if (packageName.length > 0)
        // if its null then it is defined in the default package
        this.unit.currentPackage = createImportReference(packageName, start, end, false,
                ClassFileConstants.AccDefault);
    IImportDeclaration[] importDeclarations = topLevelTypeInfo.getHandle().getCompilationUnit().getImports();
    int importCount = importDeclarations.length;
    this.unit.imports = new ImportReference[importCount];
    for (int i = 0; i < importCount; i++) {
        ImportDeclaration importDeclaration = (ImportDeclaration) importDeclarations[i];
        ISourceImport sourceImport = (ISourceImport) importDeclaration.getElementInfo();
        String nameWithoutStar = importDeclaration.getNameWithoutStar();
        this.unit.imports[i] = createImportReference(
                Util.splitOn('.', nameWithoutStar, 0, nameWithoutStar.length()),
                sourceImport.getDeclarationSourceStart(), sourceImport.getDeclarationSourceEnd(),
                importDeclaration.isOnDemand(), sourceImport.getModifiers());
    }
    /* convert type(s) */
    try {
        int typeCount = sourceTypes.length;
        final TypeDeclaration[] types = new TypeDeclaration[typeCount];
        /*
         * We used a temporary types collection to prevent this.unit.types from being null during a call to
         * convert(...) when the source is syntactically incorrect and the parser is flushing the unit's types.
         * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=97466
         */
        for (int i = 0; i < typeCount; i++) {
            SourceTypeElementInfo typeInfo = (SourceTypeElementInfo) sourceTypes[i];
            types[i] = convert((SourceType) typeInfo.getHandle(), compilationResult);
        }
        this.unit.types = types;
        return this.unit;
    } catch (AnonymousMemberFound e) {
        return new Parser(this.problemReporter, true).parse(this.cu, compilationResult);
    }
}

From source file:com.google.gwt.dev.javac.BinaryTypeReferenceRestrictionsCheckerTest.java

License:Apache License

/**
 * Creates a mock {@link CompilationUnitDeclaration} that has binary type
 * references in a superclass reference, in a method return type, in an
 * annotation and in a local variable declaration. It then checks that the we
 * find all of these locations except for the one used in an annotation.
 */// www. j a  v a  2  s. c o  m
public void testFindAllBinaryTypeReferenceSites() {
    CompilationResult compilationResult = new CompilationResult("TestCompilationUnit.java".toCharArray(), 0, 0,
            0);
    CompilationUnitDeclaration cud = new CompilationUnitDeclaration(null, compilationResult, 1);
    LookupEnvironment lookupEnvironment = createMockLookupEnvironment();
    cud.scope = new CompilationUnitScope(cud, lookupEnvironment);

    TypeDeclaration typeDeclaration = new TypeDeclaration(compilationResult);
    typeDeclaration.scope = new ClassScope(cud.scope, null);
    typeDeclaration.staticInitializerScope = new MethodScope(typeDeclaration.scope, null, false);
    cud.types = new TypeDeclaration[] { typeDeclaration };

    BinaryTypeBinding binaryTypeBinding = new BinaryTypeBinding(null, new MockBinaryType(BINARY_TYPE_NAME),
            lookupEnvironment);
    typeDeclaration.superclass = createMockBinaryTypeReference(binaryTypeBinding);

    MethodDeclaration methodDeclaration = new MethodDeclaration(compilationResult);
    methodDeclaration.scope = new MethodScope(typeDeclaration.scope, null, false);
    methodDeclaration.returnType = createMockBinaryTypeReference(binaryTypeBinding);

    LocalDeclaration localDeclaration = new LocalDeclaration(null, 0, 0);
    localDeclaration.type = createMockBinaryTypeReference(binaryTypeBinding);
    methodDeclaration.statements = new Statement[] { localDeclaration };

    SingleMemberAnnotation annotation = new SingleMemberAnnotation(
            createMockBinaryTypeReference(binaryTypeBinding), 0);
    annotation.memberValue = annotation.type;
    typeDeclaration.annotations = new Annotation[] { annotation };

    typeDeclaration.methods = new AbstractMethodDeclaration[] { methodDeclaration };

    /*
     * Check that we find binary type references in the following expected
     * locations.
     */
    Expression[] expectedExpressions = new Expression[] { typeDeclaration.superclass,
            methodDeclaration.returnType, localDeclaration.type };

    List<BinaryTypeReferenceSite> binaryTypeReferenceSites = BinaryTypeReferenceRestrictionsChecker
            .findAllBinaryTypeReferenceSites(cud);
    assertEquals(expectedExpressions.length, binaryTypeReferenceSites.size());
    for (int i = 0; i < binaryTypeReferenceSites.size(); ++i) {
        BinaryTypeReferenceSite binaryTypeReferenceSite = binaryTypeReferenceSites.get(i);
        assertSame(binaryTypeBinding, binaryTypeReferenceSite.getBinaryTypeBinding());
        assertSame(expectedExpressions[i], binaryTypeReferenceSite.getExpression());
    }
}

From source file:com.google.gwt.dev.javac.GWTProblemTest.java

License:Apache License

public void testRecordError() {
    String fileName = "TestCompilationUnit.java";
    String errorMessage = "Unit has errors";
    CompilationResult compilationResult = new CompilationResult(fileName.toCharArray(), 0, 0, 0);
    CompilationUnitDeclaration cud = new CompilationUnitDeclaration(null, compilationResult, 0);

    HelpInfo info = new HelpInfo() {
    };/*w w w.  java 2s. c  o m*/

    // Pick an Expression subtype to pass in
    GWTProblem.recordError(new Wildcard(Wildcard.EXTENDS), cud, errorMessage, info);

    CategorizedProblem[] errors = compilationResult.getErrors();
    assertEquals(1, errors.length);
    GWTProblem problem = (GWTProblem) errors[0];
    assertTrue(problem.isError());
    assertEquals(1, problem.getSourceLineNumber());
    assertEquals(errorMessage, problem.getMessage());
    assertSame(info, problem.getHelpInfo());
}

From source file:org.codehaus.jdt.groovy.integration.DefaultLanguageSupport.java

License:Open Source License

public CompilationUnitDeclaration newCompilationUnitDeclaration(ICompilationUnit unit,
        ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength) {
    return new CompilationUnitDeclaration(problemReporter, compilationResult, sourceLength);
}

From source file:org.codehaus.jdt.groovy.integration.internal.GroovyLanguageSupport.java

License:Open Source License

public CompilationUnitDeclaration newCompilationUnitDeclaration(ICompilationUnit unit,
        ProblemReporter problemReporter, CompilationResult compilationResult, int sourceLength) {
    if (ContentTypeUtils.isGroovyLikeFileName(compilationResult.getFileName())) {
        CompilerConfiguration groovyCompilerConfig = new CompilerConfiguration();
        // groovyCompilerConfig.setPluginFactory(new ErrorRecoveredCSTParserPluginFactory(null));
        ErrorCollector errorCollector = new GroovyErrorCollectorForJDT(groovyCompilerConfig);
        SourceUnit groovySourceUnit = new SourceUnit(new String(compilationResult.getFileName()),
                new String(unit.getContents()), groovyCompilerConfig, null, errorCollector);

        // FIXASC missing the classloader configuration (eg. to include transformers)
        org.codehaus.groovy.control.CompilationUnit groovyCU = new org.codehaus.groovy.control.CompilationUnit(
                groovyCompilerConfig);//  w w w. j  a v a2  s.  co  m
        // groovyCU.removeOutputPhaseOperation();
        JDTResolver resolver = new JDTResolver(groovyCU);
        groovyCU.setResolveVisitor(resolver);

        // TODO groovy get this from the Antlr parser
        compilationResult.lineSeparatorPositions = GroovyUtils.getSourceLineSeparatorsIn(unit.getContents());

        groovyCU.addSource(groovySourceUnit);
        GroovyCompilationUnitDeclaration gcuDeclaration = new GroovyCompilationUnitDeclaration(problemReporter,
                compilationResult, sourceLength, groovyCU, groovySourceUnit, null);

        // boolean success =
        gcuDeclaration.processToPhase(Phases.CONVERSION);

        // Regardless of a successful outcome, build what is possible in the face of any errors
        gcuDeclaration.populateCompilationUnitDeclaration();
        for (TypeDeclaration decl : gcuDeclaration.types) {
            GroovyTypeDeclaration gtDeclaration = (GroovyTypeDeclaration) decl;
            resolver.record(gtDeclaration);
        }

        return gcuDeclaration;
    } else {
        return new CompilationUnitDeclaration(problemReporter, compilationResult, sourceLength);
    }
}

From source file:org.eclipse.jdt.internal.compiler.parser.Parser.java

License:Open Source License

public CompilationUnitDeclaration parse(ICompilationUnit sourceUnit, CompilationResult compilationResult,
        int start, int end) {
    // parses a compilation unit and manages error handling (even bugs....)

    CompilationUnitDeclaration unit;/*from  w  ww .j  av a 2 s . c om*/
    try {
        /* automaton initialization */
        initialize(true);
        goForCompilationUnit();

        /* unit creation */
        this.referenceContext = this.compilationUnit = new CompilationUnitDeclaration(this.problemReporter,
                compilationResult, 0);

        /* scanners initialization */
        char[] contents;
        try {
            contents = this.readManager != null ? this.readManager.getContents(sourceUnit)
                    : sourceUnit.getContents();
        } catch (AbortCompilationUnit abortException) {
            problemReporter().cannotReadSource(this.compilationUnit, abortException, this.options.verbose);
            contents = CharOperation.NO_CHAR; // pretend empty from thereon
        }
        this.scanner.setSource(contents);
        this.compilationUnit.sourceEnd = this.scanner.source.length - 1;
        if (end != -1)
            this.scanner.resetTo(start, end);
        if (this.javadocParser != null && this.javadocParser.checkDocComment) {
            this.javadocParser.scanner.setSource(contents);
            if (end != -1) {
                this.javadocParser.scanner.resetTo(start, end);
            }
        }
        /* run automaton */
        parse();
    } finally {
        unit = this.compilationUnit;
        this.compilationUnit = null; // reset parser
        // tag unit has having read bodies
        if (!this.diet)
            unit.bits |= ASTNode.HasAllMethodBodies;
    }
    return unit;
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.lookup.OTClassScope.java

License:Open Source License

public void checkAndSetBaseImports(LookupEnvironment env, ImportReference[] references,
        ImportBinding[] resolvedBaseImports) {
    // TODO what checks need to be performed??
    // TODO: support base class decapsulation for base imports!
    // TODO: perhaps we should not report name class between a role's name and its base-imported
    //       baseclass??
    ImportReference currentPackage = referenceCompilationUnit().currentPackage;
    if (currentPackage != null && currentPackage.isTeam()) {
        for (ImportReference reference : references)
            if (reference != null)
                problemReporter().baseImportInRoleFile(reference);
        return;//  w  ww.  j a v a 2 s .  com
    }
    CompilationUnitDeclaration cud = new CompilationUnitDeclaration(problemReporter(),
            this.referenceContext.compilationResult, 0);
    cud.currentPackage = currentPackage;
    this.baseImportScope = new CompilationUnitScope(cud, env);
    this.baseImportScope.imports = resolvedBaseImports;
    this.baseImportScope.fPackage = compilationUnitScope().fPackage;
    this.baseImportScope.topLevelTypes = new SourceTypeBinding[0];
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.util.AstConverter.java

License:Open Source License

public static TypeDeclaration createNestedType(char[] name, int modifiers, boolean isNestedType,
        boolean isPurelyCopied, TypeDeclaration teamDecl, ReferenceBinding tsuperRole) {
    TypeDeclaration enclosingTypeDecl = teamDecl;
    if (tsuperRole != null && isNestedType) {
        ReferenceBinding srcEnclosing = tsuperRole.enclosingType();
        // TODO (SH): recurse even more
        TypeDeclaration[] members = enclosingTypeDecl.memberTypes;
        if (members != null)
            for (int i = 0; i < members.length; i++) {
                if (CharOperation.equals(members[i].name, srcEnclosing.internalName())) {
                    enclosingTypeDecl = members[i];
                    break;
                }//  w  w w  .j  ava 2s.  co m
            }
    }

    TypeDeclaration nestedType = new TypeDeclaration(enclosingTypeDecl.compilationResult);
    nestedType.name = name;
    nestedType.modifiers = modifiers;
    nestedType.isGenerated = true;
    nestedType.isPurelyCopied = isPurelyCopied;
    int sStart = enclosingTypeDecl.sourceStart;
    int sEnd = enclosingTypeDecl.sourceEnd;
    if (enclosingTypeDecl.superclass != null) {
        sStart = enclosingTypeDecl.superclass.sourceStart;
        sEnd = enclosingTypeDecl.superclass.sourceEnd;
    }
    nestedType.declarationSourceStart = sStart;
    nestedType.declarationSourceEnd = sEnd;
    nestedType.sourceStart = sStart;
    nestedType.sourceEnd = sEnd;
    nestedType.bodyStart = sStart;
    nestedType.bodyEnd = sEnd;
    AstGenerator gen = new AstGenerator(sStart, sEnd);
    if (tsuperRole != null && tsuperRole.isInterface()) {
        ReferenceBinding superclass = tsuperRole.superclass();
        if (superclass != null && CharOperation.equals(superclass.internalName(), IOTConstants.OTCONFINED)) {
            nestedType.superclass = gen.qualifiedTypeReference(IOTConstants.ORG_OBJECTTEAMS_TEAM_OTCONFINED);
            nestedType.superclass.resolvedType = superclass;
        }
    }

    if (tsuperRole != null && tsuperRole.isLocalType()) {
        nestedType.bits |= ASTNode.IsLocalType;
        if (tsuperRole.isAnonymousType()) {
            // have no name, need at least a super type
            // (otherwise ClassScope.checkAndSetModifiers() will fail)
            ReferenceBinding superType;
            ReferenceBinding[] superIfcs = tsuperRole.superInterfaces();
            if (superIfcs != Binding.NO_SUPERINTERFACES)
                superType = superIfcs[0];
            else
                superType = tsuperRole.superclass();
            nestedType.allocation = new QualifiedAllocationExpression();
            nestedType.allocation.type = gen.typeReference(superType);
            nestedType.allocation.anonymousType = nestedType;
        }
        AstEdit.addLocalTypeDeclaration(enclosingTypeDecl, nestedType);
    } else {
        AstEdit.addMemberTypeDeclaration(enclosingTypeDecl, nestedType);
    }

    if (tsuperRole != null && tsuperRole.roleModel != null && tsuperRole.roleModel.isRoleFile()) {
        // for role copied from a role file create an enclosing CUD to allow for
        // late role catch-up of this phantom role.
        ProblemReporter reporter = enclosingTypeDecl.scope.problemReporter();
        CompilationResult compilationResult = new CompilationResult("nofile".toCharArray(), 0, 0, 0); //$NON-NLS-1$
        CompilationUnitDeclaration cud = new CompilationUnitDeclaration(reporter, compilationResult, 0);
        nestedType.compilationResult = compilationResult;
        nestedType.compilationUnit = cud;
        cud.types = new TypeDeclaration[] { nestedType };
        char[][] enclosingName = enclosingTypeDecl.binding.compoundName;
        char[][] tokens = CharOperation.arrayConcat(enclosingName, nestedType.name);
        long[] positions = new long[tokens.length];
        Arrays.fill(positions, 0L);
        cud.currentPackage = new ImportReference(enclosingName, positions, false, ClassFileConstants.AccTeam);
    }

    // Create TypeBindings for this type
    enclosingTypeDecl.scope.addGeneratedType(nestedType);

    int state = enclosingTypeDecl.getModel().getState();
    if (enclosingTypeDecl.isTeam())
        state = enclosingTypeDecl.getTeamModel().getState();

    // Create Type-Hierarchy?
    nestedType.scope
            .connectTypeHierarchyForGenerated(state >= ITranslationStates.STATE_LENV_CONNECT_TYPE_HIERARCHY);

    // don't set past the state of the enclosing team:
    state = Math.min(state, ITranslationStates.STATE_LENV_CONNECT_TYPE_HIERARCHY);

    if (nestedType.getRoleModel() != null)
        nestedType.getRoleModel().setState(state);
    if (nestedType.isTeam() && nestedType.getTeamModel() != null)
        nestedType.getTeamModel().setState(state);

    return nestedType;
}

From source file:org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer.java

License:Open Source License

public CompilationUnitDeclaration createCompilationUnitDeclaration(ProblemReporter reporter,
        CompilationResult result) throws JavaModelException {
    return new CompilationUnitDeclaration(reporter, result, 0);
}