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

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

Introduction

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

Prototype

public void generateCode() 

Source Link

Document

Bytecode generation

Usage

From source file:net.sf.j2s.core.compiler.Java2ScriptImageCompiler.java

License:Open Source License

/**
 * Process a compilation unit already parsed and build.
 *///from   w w  w. j  a  v a  2 s.c  o  m
public void process(CompilationUnitDeclaration unit, int i) {
    if (binaryFolder != null) {
        ICompilationUnit sourceUnit = (ICompilationUnit) sourceUnits.get(i);
        ExtendedCompilers.process(sourceUnit, binaryFolder);
        sourceUnits.set(i, new String()); // set to null!
    }

    this.lookupEnvironment.unitBeingCompleted = unit;
    long parseStart = System.currentTimeMillis();

    this.parser.getMethodBodies(unit);

    long resolveStart = System.currentTimeMillis();
    this.stats.parseTime += resolveStart - parseStart;

    // fault in fields & methods
    if (unit.scope != null)
        unit.scope.faultInTypes();

    // verify inherited methods
    if (unit.scope != null)
        unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());

    // type checking
    unit.resolve();

    long analyzeStart = System.currentTimeMillis();
    this.stats.resolveTime += analyzeStart - resolveStart;

    //No need of analysis or generation of code if statements are not required      
    if (!this.options.ignoreMethodBodies)
        unit.analyseCode(); // flow analysis

    long generateStart = System.currentTimeMillis();
    this.stats.analyzeTime += generateStart - analyzeStart;

    if (!this.options.ignoreMethodBodies)
        unit.generateCode(); // code generation

    // reference info
    if (this.options.produceReferenceInfo && unit.scope != null)
        unit.scope.storeDependencyInfo();

    // finalize problems (suppressWarnings)
    unit.finalizeProblems();

    this.stats.generateTime += System.currentTimeMillis() - generateStart;

    // refresh the total number of units known at this stage
    unit.compilationResult.totalUnitsKnown = this.totalUnits;

    this.lookupEnvironment.unitBeingCompleted = null;
}

From source file:org.eclipse.jdt.core.dom.CompilationUnitResolver.java

License:Open Source License

private CompilationUnitDeclaration resolve(CompilationUnitDeclaration unit,
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit sourceUnit, NodeSearcher nodeSearcher,
        boolean verifyMethods, boolean analyzeCode, boolean generateCode) {

    try {//from w w  w  .  j a  v  a 2 s  .  com

        if (unit == null) {
            // build and record parsed units
            this.parseThreshold = 0; // will request a full parse
            beginToCompile(new org.eclipse.jdt.internal.compiler.env.ICompilationUnit[] { sourceUnit });
            // find the right unit from what was injected via accept(ICompilationUnit,..):
            for (int i = 0, max = this.totalUnits; i < max; i++) {
                CompilationUnitDeclaration currentCompilationUnitDeclaration = this.unitsToProcess[i];
                if (currentCompilationUnitDeclaration != null
                        && currentCompilationUnitDeclaration.compilationResult.compilationUnit == sourceUnit) {
                    unit = currentCompilationUnitDeclaration;
                    break;
                }
            }
            if (unit == null) {
                unit = this.unitsToProcess[0]; // fall back to old behavior
            }
        } else {
            // initial type binding creation
            this.lookupEnvironment.buildTypeBindings(unit, null /*no access restriction*/);

            // binding resolution
            this.lookupEnvironment.completeTypeBindings();
        }

        if (nodeSearcher == null) {
            this.parser.getMethodBodies(unit); // no-op if method bodies have already been parsed
        } else {
            int searchPosition = nodeSearcher.position;
            char[] source = sourceUnit.getContents();
            int length = source.length;
            if (searchPosition >= 0 && searchPosition <= length) {
                unit.traverse(nodeSearcher, unit.scope);

                org.eclipse.jdt.internal.compiler.ast.ASTNode node = nodeSearcher.found;

                if (node != null) {
                    // save existing values to restore them at the end of the parsing process
                    // see bug 47079 for more details
                    int[] oldLineEnds = this.parser.scanner.lineEnds;
                    int oldLinePtr = this.parser.scanner.linePtr;

                    this.parser.scanner.setSource(source, unit.compilationResult);

                    org.eclipse.jdt.internal.compiler.ast.TypeDeclaration enclosingTypeDeclaration = nodeSearcher.enclosingType;
                    if (node instanceof AbstractMethodDeclaration) {
                        ((AbstractMethodDeclaration) node).parseStatements(this.parser, unit);
                    } else if (enclosingTypeDeclaration != null) {
                        if (node instanceof org.eclipse.jdt.internal.compiler.ast.Initializer) {
                            ((org.eclipse.jdt.internal.compiler.ast.Initializer) node)
                                    .parseStatements(this.parser, enclosingTypeDeclaration, unit);
                        } else if (node instanceof org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) {
                            ((org.eclipse.jdt.internal.compiler.ast.TypeDeclaration) node)
                                    .parseMethods(this.parser, unit);
                        }
                    }
                    // this is done to prevent any side effects on the compilation unit result
                    // line separator positions array.
                    this.parser.scanner.lineEnds = oldLineEnds;
                    this.parser.scanner.linePtr = oldLinePtr;
                }
            }
        }

        if (unit.scope != null) {
            // fault in fields & methods
            unit.scope.faultInTypes();
            if (unit.scope != null && verifyMethods) {
                // http://dev.eclipse.org/bugs/show_bug.cgi?id=23117
                // verify inherited methods
                unit.scope.verifyMethods(this.lookupEnvironment.methodVerifier());
            }
            // type checking
            unit.resolve();

            // flow analysis
            if (analyzeCode)
                unit.analyseCode();

            // code generation
            if (generateCode)
                unit.generateCode();

            // finalize problems (suppressWarnings)
            unit.finalizeProblems();
        }
        if (this.unitsToProcess != null)
            this.unitsToProcess[0] = null; // release reference to processed unit declaration
        this.requestor.acceptResult(unit.compilationResult.tagAsAccepted());
        return unit;
    } catch (AbortCompilation e) {
        this.handleInternalException(e, unit);
        return unit == null ? this.unitsToProcess[0] : unit;
    } catch (Error e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } catch (RuntimeException e) {
        this.handleInternalException(e, unit, null);
        throw e; // rethrow
    } finally {
        // No reset is performed there anymore since,
        // within the CodeAssist (or related tools),
        // the compiler may be called *after* a call
        // to this resolve(...) method. And such a call
        // needs to have a compiler with a non-empty
        // environment.
        // this.reset();
    }
}

From source file:org.eclipse.objectteams.otdt.internal.core.compiler.control.Dependencies.java

License:Open Source License

private static Pair<Boolean, Success> establishUnitState(CompilationUnitDeclaration unit, int state,
        Success success, AccessRestriction accessRestriction) {
    boolean done = true;
    if (StateHelper.unitHasState(unit, state))
        return new Pair<Boolean, Success>(done, Success.OK);

    // original calls stolen from Compiler.process are handled here:
    try {/*from   w  ww. j  a  v a  2  s  . co  m*/
        switch (state) {
        case STATE_ROLE_FILES_LINKED:
            establishRoleFilesLinked(unit, Config.getLookupEnvironment());
            break;
        case STATE_BINDINGS_BUILT:
            Config.getLookupEnvironment().internalBuildTypeBindings(unit, accessRestriction);
            break;
        case STATE_LENV_BUILD_TYPE_HIERARCHY:
        case STATE_LENV_CHECK_AND_SET_IMPORTS:
        case STATE_LENV_CONNECT_TYPE_HIERARCHY:
        case STATE_LENV_DONE_FIELDS_AND_METHODS:
        case STATE_ROLES_LINKED:
            checkReadKnownRoles(unit);
            LookupEnvironment lookupEnvironment = Config.getLookupEnvironment();
            if (Config.getBundledCompleteTypeBindingsMode()) {
                int stateReached = Config.getLookupEnvironment().internalCompleteTypeBindings(unit);
                StateHelper.setStateRecursive(unit, stateReached, true);
                if (stateReached >= state)
                    return new Pair<Boolean, Success>(done,
                            (stateReached >= state) ? Success.OK : Success.NotReady);
                // if not successful try directly:
            }
            // completely under our control:
            switch (state) {
            case STATE_LENV_BUILD_TYPE_HIERARCHY:
                break; // no-op
            case STATE_LENV_CHECK_AND_SET_IMPORTS:
                unit.scope.checkAndSetImports();
                break;
            case STATE_LENV_CONNECT_TYPE_HIERARCHY:
                CompilationUnitDeclaration previousUnit = lookupEnvironment.unitBeingCompleted;
                lookupEnvironment.unitBeingCompleted = unit;
                try {
                    unit.scope.connectTypeHierarchy();
                } finally {
                    lookupEnvironment.unitBeingCompleted = previousUnit;
                }
                break;
            case STATE_LENV_DONE_FIELDS_AND_METHODS:
                unit.scope.checkParameterizedTypes();
                if (Config.getBuildFieldsAndMethods())
                    unit.scope.buildFieldsAndMethods();
                break;
            case STATE_ROLES_LINKED:
                RoleSplitter.linkRoles(unit);
            }
            break;
        case STATE_METHODS_PARSED:
            if (success == Success.OK && unit.parseMethodBodies)
                Config.delegateGetMethodBodies(unit);
            // special case: mark the unit but also descend into types (for role units)
            unit.state.setState(STATE_METHODS_PARSED);
            done = false;
            break;
        case STATE_METHODS_VERIFIED:
            if (Config.getVerifyMethods())
                unit.scope.verifyMethods(Config.getLookupEnvironment().methodVerifier());
            break;
        case STATE_RESOLVED:
            unit.resolve();
            break;
        case STATE_CODE_ANALYZED:
            if (Config.getAnalyzeCode())
                unit.analyseCode();
            break;
        case STATE_BYTE_CODE_GENERATED:
            if (Config.getGenerateCode())
                unit.generateCode();
            // descending into already generated types is
            // prevented by TypeDeclaration.hasBeenGenerated
            break;
        default:
            done = false;
        }
    } catch (Config.NotConfiguredException e) {
        e.logWarning("Processing CU " + String.valueOf(unit.getFileName()) + " failed"); //$NON-NLS-1$ //$NON-NLS-2$
        success = Success.Fail;
    }

    return new Pair<Boolean, Success>(done, success);
}

From source file:org.nabucco.framework.mda.model.java.JavaModelLoader.java

License:Open Source License

/**
 * Process a compilation unit already parsed and build.
 * /*  w w w .  ja  va  2s. com*/
 * @param environment
 *            the lookup environment
 * @param parser
 *            the parser
 * @param unit
 *            the compilation unit
 */
private void process(LookupEnvironment environment, Parser parser, CompilationUnitDeclaration unit) {

    environment.unitBeingCompleted = unit;

    parser.getMethodBodies(unit);

    // fault in fields & methods
    if (unit.scope != null) {
        unit.scope.faultInTypes();
    }

    // verify inherited methods
    if (unit.scope != null) {
        unit.scope.verifyMethods(environment.methodVerifier());
    }

    // type checking
    unit.resolve();

    // flow analysis
    unit.analyseCode();

    // code generation
    unit.generateCode();

    if (JavaModelSupport.createCompilerOptions().produceReferenceInfo && unit.scope != null) {
        unit.scope.storeDependencyInfo();
    }

    unit.finalizeProblems();

    environment.unitBeingCompleted = null;

    unit.ignoreFurtherInvestigation = false;
    unit.cleanUp();
}