Example usage for org.eclipse.jdt.internal.core JavaProject getOptions

List of usage examples for org.eclipse.jdt.internal.core JavaProject getOptions

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaProject getOptions.

Prototype

@Override
public Map<String, String> getOptions(boolean inheritJavaCoreOptions) 

Source Link

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.NamedMember.java

License:Open Source License

/**
 * @see IType#resolveType(String, org.eclipse.jdt.core.WorkingCopyOwner)
 */// ww w  .  j a v a  2  s. c o  m
public String[][] resolveType(String typeName, WorkingCopyOwner owner) throws JavaModelException {
    JavaProject project = (JavaProject) getJavaProject();
    SearchableEnvironment environment = project.newSearchableNameEnvironment(owner);

    class TypeResolveRequestor implements ISelectionRequestor {
        String[][] answers = null;

        public void acceptType(char[] packageName, char[] tName, int modifiers, boolean isDeclaration,
                char[] uniqueKey, int start, int end) {
            String[] answer = new String[] { new String(packageName), new String(tName) };
            if (this.answers == null) {
                this.answers = new String[][] { answer };
            } else {
                // grow
                int length = this.answers.length;
                System.arraycopy(this.answers, 0, this.answers = new String[length + 1][], 0, length);
                this.answers[length] = answer;
            }
        }

        public void acceptError(CategorizedProblem error) {
            // ignore
        }

        public void acceptField(char[] declaringTypePackageName, char[] declaringTypeName, char[] fieldName,
                boolean isDeclaration, char[] uniqueKey, int start, int end) {
            // ignore
        }

        public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName,
                String enclosingDeclaringTypeSignature, char[] selector, char[][] parameterPackageNames,
                char[][] parameterTypeNames, String[] parameterSignatures, char[][] typeParameterNames,
                char[][][] typeParameterBoundNames, boolean isConstructor, boolean isDeclaration,
                char[] uniqueKey, int start, int end) {
            // ignore
        }

        public void acceptPackage(char[] packageName) {
            // ignore
        }

        public void acceptTypeParameter(char[] declaringTypePackageName, char[] declaringTypeName,
                char[] typeParameterName, boolean isDeclaration, int start, int end) {
            // ignore
        }

        public void acceptMethodTypeParameter(char[] declaringTypePackageName, char[] declaringTypeName,
                char[] selector, int selectorStart, int selcetorEnd, char[] typeParameterName,
                boolean isDeclaration, int start, int end) {
            // ignore
        }

    }
    TypeResolveRequestor requestor = new TypeResolveRequestor();
    SelectionEngine engine = new SelectionEngine(environment, requestor, project.getOptions(true), owner,
            project.getIndexManager(), project);

    engine.selectType(typeName.toCharArray(), (IType) this);
    if (NameLookup.VERBOSE) {
        System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " //$NON-NLS-1$
                + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$
        System.out.println(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " //$NON-NLS-1$
                + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$
    }
    return requestor.answers;
}

From source file:org.codehaus.jdt.groovy.model.GroovyCompilationUnit.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes", "nls", "restriction" })
@Override//  w ww. ja v a  2  s  .co m
protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, Map newElements,
        IResource underlyingResource) throws JavaModelException {
    try {
        depth.set(depth.get() + 1);

        // if (!isOnBuildPath()) {
        // return false;
        // }

        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.log(TraceCategory.COMPILER, "Build Structure starting for " + this.name);
            GroovyLogManager.manager
                    .logStart("Build structure: " + name + " : " + Thread.currentThread().getName());
        }

        CompilationUnitElementInfo unitInfo = (CompilationUnitElementInfo) info;

        // ensure buffer is opened
        IBuffer buffer = getBufferManager().getBuffer(this);
        if (buffer == null) {
            openBuffer(pm, unitInfo); // open buffer independently from the
            // info, since we are building the info
        }

        // generate structure and compute syntax problems if needed
        GroovyCompilationUnitStructureRequestor requestor = new GroovyCompilationUnitStructureRequestor(this,
                unitInfo, newElements);
        JavaModelManager.PerWorkingCopyInfo perWorkingCopyInfo = getPerWorkingCopyInfo();
        JavaProject project = (JavaProject) getJavaProject();

        // determine what kind of buildStructure we are doing
        boolean createAST;
        int reconcileFlags;
        boolean resolveBindings;
        HashMap problems;
        if (info instanceof ASTHolderCUInfo) {
            ASTHolderCUInfo astHolder = (ASTHolderCUInfo) info;
            createAST = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "astLevel", //$NON-NLS-1$
                    astHolder)).intValue() != NO_AST;
            resolveBindings = ((Boolean) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class,
                    "resolveBindings", astHolder)).booleanValue();
            reconcileFlags = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "reconcileFlags", //$NON-NLS-1$
                    astHolder)).intValue();
            problems = (HashMap) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder);
        } else {
            createAST = false;
            resolveBindings = false;
            reconcileFlags = 0;
            problems = null;
        }

        boolean computeProblems = perWorkingCopyInfo != null && perWorkingCopyInfo.isActive() && project != null
                && JavaProject.hasJavaNature(project.getProject());
        IProblemFactory problemFactory = new DefaultProblemFactory();

        // compiler options
        Map<String, String> options = (project == null ? JavaCore.getOptions() : project.getOptions(true));
        if (!computeProblems) {
            // disable task tags checking to speed up parsing
            options.put(JavaCore.COMPILER_TASK_TAGS, ""); //$NON-NLS-1$
        }

        // FIXASC deal with the case of project==null to reduce duplication in this next line and call to setGroovyClasspath
        // Required for Groovy, but not for Java
        options.put(CompilerOptions.OPTIONG_BuildGroovyFiles, CompilerOptions.ENABLED);

        CompilerOptions compilerOptions = new CompilerOptions(options);

        if (project != null) {
            CompilerUtils.setGroovyClasspath(compilerOptions, project);
        }

        // Required for Groovy, but not for Java
        ProblemReporter reporter = new ProblemReporter(new GroovyErrorHandlingPolicy(!computeProblems),
                compilerOptions, new DefaultProblemFactory());

        SourceElementParser parser = new MultiplexingSourceElementRequestorParser(reporter, requestor, /*
                                                                                                       * not needed if
                                                                                                       * computing groovy only
                                                                                                       */
                problemFactory, compilerOptions, true/* report local declarations */, !createAST /*
                                                                                                 * optimize string literals only if not
                                                                                                 * creating a DOM AST
                                                                                                 */);
        parser.reportOnlyOneSyntaxError = !computeProblems;
        // maybe not needed for groovy, but I don't want to find out.
        parser.setMethodsFullRecovery(true);
        parser.setStatementsRecovery((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0);

        if (!computeProblems && !resolveBindings && !createAST) // disable javadoc parsing if not computing problems, not
            // resolving
            // and not creating ast
            parser.javadocParser.checkDocComment = false;
        requestor.setParser(parser);

        // update timestamp (might be IResource.NULL_STAMP if original does not
        // exist)
        if (underlyingResource == null) {
            underlyingResource = getResource();
        }
        // underlying resource is null in the case of a working copy on a class
        // file in a jar
        if (underlyingResource != null) {
            ReflectionUtils.setPrivateField(CompilationUnitElementInfo.class, "timestamp", unitInfo, //$NON-NLS-1$
                    underlyingResource.getModificationStamp());
        }

        GroovyCompilationUnitDeclaration compilationUnitDeclaration = null;
        CompilationUnit source = cloneCachingContents();
        try {
            // GROOVY
            // note that this is a slightly different approach than taken by super.buildStructure
            // in super.buildStructure, there is a test here to see if computeProblems is true.
            // if false, then parser.parserCompilationUnit is called.
            // this will not work for Groovy because we need to ensure bindings are resolved
            // for many operations (content assist and code select) to work.
            // So, for groovy, always use CompilationUnitProblemFinder.process and then process problems
            // separately only if necessary
            // addendum (GRECLIPSE-942). The testcase for that bug includes a package with 200
            // types in that refer to each other in a chain, through field references. If a reconcile
            // references the top of the chain we can go through a massive number of recursive calls into
            // this buildStructure for each one. The 'full' parse (with bindings) is only required for
            // the top most (regardless of the computeProblems setting) and so we track how many recursive
            // calls we have made - if we are at depth 2 we do what JDT was going to do (the quick thing).
            if (computeProblems || depth.get() < 2) {
                if (problems == null) {
                    // report problems to the problem requestor
                    problems = new HashMap();
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                    if (computeProblems) {
                        try {
                            perWorkingCopyInfo.beginReporting();
                            for (Iterator iteraror = problems.values().iterator(); iteraror.hasNext();) {
                                CategorizedProblem[] categorizedProblems = (CategorizedProblem[]) iteraror
                                        .next();
                                if (categorizedProblems == null)
                                    continue;
                                for (int i = 0, length = categorizedProblems.length; i < length; i++) {
                                    perWorkingCopyInfo.acceptProblem(categorizedProblems[i]);
                                }
                            }
                        } finally {
                            perWorkingCopyInfo.endReporting();
                        }
                    }
                } else {
                    // collect problems
                    compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) CompilationUnitProblemFinder
                            .process(source, parser, this.owner, problems, createAST, reconcileFlags, pm);
                }
            } else {
                compilationUnitDeclaration = (GroovyCompilationUnitDeclaration) parser
                        .parseCompilationUnit(source, true /* full parse to find local elements */, pm);
            }

            // GROOVY
            // if this is a working copy, then we have more work to do
            maybeCacheModuleNode(perWorkingCopyInfo, compilationUnitDeclaration);

            // create the DOM AST from the compiler AST
            if (createAST) {
                org.eclipse.jdt.core.dom.CompilationUnit ast;
                try {
                    ast = AST.convertCompilationUnit(AST.JLS3, compilationUnitDeclaration, options,
                            computeProblems, source, reconcileFlags, pm);
                    ReflectionUtils.setPrivateField(ASTHolderCUInfo.class, "ast", info, ast); //$NON-NLS-1$
                } catch (OperationCanceledException e) {
                    // catch this exception so as to not enter the catch(RuntimeException e) below
                    // might need to do the same for AbortCompilation
                    throw e;
                } catch (IllegalArgumentException e) {
                    // if necessary, we can do some better reporting here.
                    Util.log(e, "Problem with build structure: Offset for AST node is incorrect in " //$NON-NLS-1$
                            + this.getParent().getElementName() + "." + getElementName()); //$NON-NLS-1$
                } catch (Exception e) {
                    Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
                }
            }
        } catch (OperationCanceledException e) {
            // catch this exception so as to not enter the catch(RuntimeException e) below
            // might need to do the same for AbortCompilation
            throw e;
        } catch (JavaModelException e) {
            // GRECLIPSE-1480 don't log element does not exist exceptions. since this could occur when element is in a non-java
            // project
            if (e.getStatus().getCode() != IJavaModelStatusConstants.ELEMENT_DOES_NOT_EXIST
                    || this.getJavaProject().exists()) {
                Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
            }
        } catch (Exception e) {
            // GROOVY: The groovy compiler does not handle broken code well in many situations
            // use this general catch clause so that exceptions thrown by broken code
            // do not bubble up the stack.
            Util.log(e, "Problem with build structure for " + this.getElementName()); //$NON-NLS-1$
        } finally {
            if (compilationUnitDeclaration != null) {
                compilationUnitDeclaration.cleanUp();
            }
        }
        return unitInfo.isStructureKnown();
    } finally {
        depth.set(depth.get() - 1);
        if (GroovyLogManager.manager.hasLoggers()) {
            GroovyLogManager.manager.logEnd(
                    "Build structure: " + name + " : " + Thread.currentThread().getName(),
                    TraceCategory.COMPILER);
        }
    }
}

From source file:org.eclipse.ajdt.core.javaelements.AJCompilationUnit.java

License:Open Source License

/**
* this method is a copy of {@link Openable#codeComplete(org.eclipse.jdt.internal.compiler.env.ICompilationUnit, org.eclipse.jdt.internal.compiler.env.ICompilationUnit, int, CompletionRequestor, WorkingCopyOwner, ITypeRoot)}
* The only change is that we need to create an {@link ITDAwareNameEnvironment}, not  standard {@link SearchableEnvironment}.
 * /*from  w  w  w .j  av  a  2  s. c  o m*/
* @param cu
* @param unitToSkip
* @param position
* @param requestor
* @param owner
* @param typeRoot
* @throws JavaModelException
*/
private void internalCodeComplete(org.eclipse.jdt.internal.compiler.env.ICompilationUnit cu,
        org.eclipse.jdt.internal.compiler.env.ICompilationUnit unitToSkip, int position,
        CompletionRequestor requestor, WorkingCopyOwner owner, ITypeRoot typeRoot,
        /* AJDT 1.7 */
        IProgressMonitor monitor) throws JavaModelException {

    if (requestor == null) {
        throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
    }
    PerformanceStats performanceStats = CompletionEngine.PERF
            ? PerformanceStats.getStats(JavaModelManager.COMPLETION_PERF, this)
            : null;
    if (performanceStats != null) {
        performanceStats.startRun(new String(cu.getFileName()) + " at " + position); //$NON-NLS-1$
    }
    IBuffer buffer = getBuffer();
    if (buffer == null) {
        return;
    }
    if (position < -1 || position > buffer.getLength()) {
        throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
    }
    JavaProject project = (JavaProject) getJavaProject();
    /* AJDT 1.7 */
    ITDAwareNameEnvironment environment = new ITDAwareNameEnvironment(project, owner, monitor);

    environment.setUnitToSkip(unitToSkip);

    // code complete
    /* AJDT 1.7 */
    CompletionEngine engine = new CompletionEngine(environment, requestor, project.getOptions(true), project,
            owner, monitor);
    engine.complete(cu, position, 0, typeRoot);
    if (performanceStats != null) {
        performanceStats.endRun();
    }
    if (NameLookup.VERBOSE) {
        AJLog.log(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " //$NON-NLS-1$
                + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$
        AJLog.log(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " //$NON-NLS-1$
                + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$
    }

}

From source file:org.eclipse.ajdt.core.parserbridge.AJCompilationUnitProblemFinder.java

License:Open Source License

public static CompilationUnitDeclaration processAJ( // AspectJ Change
        CompilationUnit unitElement, // AspectJ Change
        CommentRecorderParser parser, // AspectJ Change
        WorkingCopyOwner workingCopyOwner, HashMap<String, CategorizedProblem[]> problems, boolean creatingAST,
        int reconcileFlags, IProgressMonitor monitor) throws JavaModelException {

    boolean isJavaFileInAJEditor = (reconcileFlags & JAVA_FILE_IN_AJ_EDITOR) != 0;

    JavaProject project = (JavaProject) unitElement.getJavaProject();
    ITDAwareNameEnvironment environment = null;
    CancelableProblemFactory problemFactory = null;
    AJCompilationUnitProblemFinder problemFinder = null; // AspectJ Change
    try {//ww w. ja va 2  s  .  co m

        // AspectJ Change begin
        // use an ITDAware environment to ensure that ITDs are included for source types
        environment = new ITDAwareNameEnvironment(project, workingCopyOwner, monitor);
        // AspectJ Change end

        problemFactory = new CancelableProblemFactory(monitor);
        problemFinder = new AJCompilationUnitProblemFinder( // AspectJ Change
                environment, getHandlingPolicy(),
                getCompilerOptions(project.getOptions(true), creatingAST,
                        ((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0)),
                getRequestor(), problemFactory, unitElement);
        CompilationUnitDeclaration unit = null;

        // AspectJ Change begin 
        // the parser should be a SourceElementParser or AJSourceElementParser2.
        // this ensures that a diet parse can be done, while at the same time
        // all declarations be reported
        if (parser != null) {
            problemFinder.parser = parser;
        }
        try {
            if (problemFinder.parser instanceof SourceElementParser) {
                unit = ((SourceElementParser) problemFinder.parser).parseCompilationUnit(unitElement,
                        true/* full parse */, monitor);
                problemFinder.resolve(unit, unitElement, true, // verify methods
                        true, // analyze code
                        true); // generate code
            } else if (problemFinder.parser instanceof AJSourceElementParser2) {
                unit = ((AJSourceElementParser2) problemFinder.parser).parseCompilationUnit(unitElement,
                        true/* full parse */, monitor);
                problemFinder.resolve(unit, unitElement, true, // verify methods
                        true, // analyze code
                        true); // generate code
            } else {
                unit = problemFinder.resolve(unitElement, true, // verify methods
                        true, // analyze code
                        true); // generate code
            }

        } catch (AbortCompilation e) {
            problemFinder.handleInternalException(e, unit);
        }

        // revert the compilation units that have ITDs in them
        ((ITDAwareLookupEnvironment) problemFinder.lookupEnvironment).revertCompilationUnits();
        // AspectJ Change end

        CompilationResult unitResult = unit.compilationResult;
        CategorizedProblem[] unitProblems = unitResult.getProblems();
        int length = unitProblems == null ? 0 : unitProblems.length;
        if (length > 0) {
            // AspectJ Change begin
            // filter out spurious problems
            CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
            System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
            categorizedProblems = removeAJNonProblems(categorizedProblems, unitElement, isJavaFileInAJEditor);
            if (categorizedProblems.length > 0) {
                problems.put(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, categorizedProblems);
            }
            // AspectJ Change end
        }
        unitProblems = unitResult.getTasks();
        length = unitProblems == null ? 0 : unitProblems.length;
        if (length > 0) {
            CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
            System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
            problems.put(IJavaModelMarker.TASK_MARKER, categorizedProblems);
        }
        if (NameLookup.VERBOSE) {
            AJLog.log(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " //$NON-NLS-1$
                    + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$
            AJLog.log(Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " //$NON-NLS-1$
                    + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$
        }
        return unit;
    } catch (OperationCanceledException e) {
        // catch this exception so as to not enter the
        // catch(RuntimeException e) below
        throw e;
    } catch (RuntimeException e) {
        String message = handleException(unitElement, environment, e);
        throw new JavaModelException(new RuntimeException(message, e),
                IJavaModelStatusConstants.COMPILER_FAILURE);

    } finally {
        if (environment != null)
            environment.setMonitor(null); // AJDT 3.6 // don't hold a reference to this
                                          // external object
        if (problemFactory != null)
            problemFactory.monitor = null; // don't hold a reference to this
                                           // external object
                                           // NB: unit.cleanUp() is done by caller
        if (problemFinder != null && !creatingAST)
            problemFinder.lookupEnvironment.reset();
    }
}

From source file:org.eclipse.ajdt.core.text.ITDCodeSelection.java

License:Open Source License

public IJavaElement[] findJavaElement(IRegion wordRegion) throws JavaModelException {
    JavaProject javaProject = (JavaProject) unit.getJavaProject();
    SearchableEnvironment environment = new ITDAwareNameEnvironment(javaProject, unit.getOwner(), null);

    ITDAwareSelectionRequestor requestor = new ITDAwareSelectionRequestor(
            AJProjectModelFactory.getInstance().getModelForJavaElement(javaProject), unit);
    /* AJDT 1.7 */
    SelectionEngine engine = new SelectionEngine(environment, requestor, javaProject.getOptions(true),
            unit.getOwner());//from  ww  w . j a  v a  2s.  co m

    final AspectsConvertingParser converter = new AspectsConvertingParser(
            ((CompilationUnit) unit).getContents());
    converter.setUnit(unit);
    ArrayList<Replacement> replacements = converter.convert(ConversionOptions.CODE_COMPLETION);

    org.eclipse.jdt.internal.compiler.env.ICompilationUnit wrappedUnit = new CompilationUnit(
            (PackageFragment) unit.getParent(), unit.getElementName(), unit.getOwner()) {
        public char[] getContents() {
            return converter.content;
        }
    };
    int transformedStart = AspectsConvertingParser.translatePositionToAfterChanges(wordRegion.getOffset(),
            replacements);
    int transformedEnd = AspectsConvertingParser
            .translatePositionToAfterChanges(wordRegion.getOffset() + wordRegion.getLength(), replacements) - 1;
    requestor.setReplacements(replacements);
    engine.select(wrappedUnit, transformedStart, transformedEnd);

    // maybe perform code select again.  If we are inside of an ITD method
    // must check for ITD references to the target type
    IntertypeElement itd = itdOrNull(unit, wordRegion.getOffset());
    if (itd != null && (itd.getAJKind() == IProgramElement.Kind.INTER_TYPE_METHOD
            || itd.getAJKind() == IProgramElement.Kind.INTER_TYPE_CONSTRUCTOR)) {
        char[] targetType = itd.getTargetType();

        final AspectsConvertingParser converter2 = new AspectsConvertingParser(
                ((CompilationUnit) unit).getContents());
        converter2.setUnit(unit);
        ArrayList<Replacement> replacements2 = converter2.convert(
                ConversionOptions.getCodeCompletionOptionWithContextSwitch(wordRegion.getOffset(), targetType));
        wrappedUnit = new CompilationUnit((PackageFragment) unit.getParent(), unit.getElementName(),
                unit.getOwner()) {
            public char[] getContents() {
                return converter2.content;
            }
        };
        transformedStart = AspectsConvertingParser.translatePositionToAfterChanges(wordRegion.getOffset(),
                replacements2);
        transformedEnd = AspectsConvertingParser.translatePositionToAfterChanges(
                wordRegion.getOffset() + wordRegion.getLength(), replacements2) - 1;
        requestor.setReplacements(replacements2);

        SelectionEngine engine2 = new SelectionEngine(environment, requestor, javaProject.getOptions(true),
                unit.getOwner());
        engine2.select(wrappedUnit, transformedStart, transformedEnd);
    }

    IJavaElement[] elements = requestor.getElements();
    if (itd != null && elements.length == 0) {
        // maybe we are selecting on the name of the itd itself
        ISourceRange nameRange = itd.getNameRange();
        if (nameRange.getOffset() <= wordRegion.getOffset() && (nameRange.getOffset()
                + nameRange.getLength()) >= (wordRegion.getOffset() + wordRegion.getLength())) {
            elements = new IJavaElement[] { itd };
        }

        // maybe we are selecting the target type of the itd
        ISourceRange targetNameRange = itd.getTargetTypeSourceRange();
        if (targetNameRange.getOffset() <= wordRegion.getOffset() && (targetNameRange.getOffset()
                + targetNameRange.getLength()) >= (wordRegion.getOffset() + wordRegion.getLength())) {
            IType targetType = itd.findTargetType();
            if (targetType != null) { // will be null if model not initialized
                elements = new IJavaElement[] { targetType };
            }
        }
    }
    return elements;
}

From source file:org.eclipse.ajdt.internal.core.ajde.CoreCompilerConfiguration.java

License:Open Source License

@SuppressWarnings("unchecked")
public Map<String, String> getJavaOptionsMap() {
    Map<String, String> optionsMap = null;

    JavaProject javaProject;
    try {/*  w ww. j  a v  a  2 s. c om*/
        javaProject = (JavaProject) project.getNature(JavaCore.NATURE_ID);
        optionsMap = javaProject.getOptions(true);
    } catch (CoreException e) {
    }

    if (optionsMap == null) {
        return JavaCore.getOptions();
    } else {
        return optionsMap;
    }
}

From source file:org.eclipse.ajdt.internal.core.contentassist.ContentAssistProvider.java

License:Open Source License

public boolean doContentAssist(ICompilationUnit cu, ICompilationUnit unitToSkip, int position,
        CompletionRequestor requestor, WorkingCopyOwner owner,
        /* AJDT 1.7 */
        ITypeRoot typeRoot, Openable target, IProgressMonitor monitor) throws Exception {
    JavaProject project = (JavaProject) target.getJavaProject();
    if (!AspectJPlugin.isAJProject(project.getProject())) {
        return false;
    }/*from   ww w. j  ava  2s . c o  m*/
    if (target instanceof AJCompilationUnit) {
        // already handled by the compilation unit
        return false;
    }
    if (!(target instanceof CompilationUnit)) {
        return false;
    }
    IBuffer buffer = target.getBuffer();
    if (buffer == null) {
        return false;
    }

    if (requestor == null) {
        throw new IllegalArgumentException("Completion requestor cannot be null"); //$NON-NLS-1$
    }

    MockCompilationUnit mcu = new MockCompilationUnit((CompilationUnit) target);
    ProposalRequestorWrapper wrapped = new ProposalRequestorWrapper(requestor, mcu, mcu.insertionTable);
    int transformedPos = mcu.translatePositionToFake(position);
    if (transformedPos < -1 || transformedPos > mcu.getContents().length) {
        throw new JavaModelException(new JavaModelStatus(IJavaModelStatusConstants.INDEX_OUT_OF_BOUNDS));
    }

    /* AJDT 1.7 */
    ITDAwareNameEnvironment environment = new ITDAwareNameEnvironment(project, owner, monitor);
    environment.setUnitToSkip(unitToSkip);

    // code complete
    /* AJDT 1.7 */
    CompletionEngine engine = new CompletionEngine(environment, wrapped, project.getOptions(true), project,
            owner, monitor);
    engine.lookupEnvironment = new ITDAwareLookupEnvironment(engine.lookupEnvironment, environment);
    engine.complete(mcu, transformedPos, 0, typeRoot);

    return true;
}

From source file:org.eclipse.jdt.internal.core.CompilationUnitProblemFinder.java

License:Open Source License

public static CompilationUnitDeclaration process(CompilationUnit unitElement, SourceElementParser parser,
        WorkingCopyOwner workingCopyOwner, HashMap problems, boolean creatingAST, int reconcileFlags,
        IProgressMonitor monitor) throws JavaModelException {

    JavaProject project = (JavaProject) unitElement.getJavaProject();
    CancelableNameEnvironment environment = null;
    CancelableProblemFactory problemFactory = null;
    CompilationUnitProblemFinder problemFinder = null;
    CompilationUnitDeclaration unit = null;
    try {/*from  w  w w. ja v  a2  s .c om*/
        environment = new CancelableNameEnvironment(project, workingCopyOwner, monitor);
        problemFactory = new CancelableProblemFactory(monitor);
        CompilerOptions compilerOptions = getCompilerOptions(project.getOptions(true), creatingAST,
                ((reconcileFlags & ICompilationUnit.ENABLE_STATEMENTS_RECOVERY) != 0));
        boolean ignoreMethodBodies = (reconcileFlags & ICompilationUnit.IGNORE_METHOD_BODIES) != 0;
        compilerOptions.ignoreMethodBodies = ignoreMethodBodies;
        // GROOVY start
        // options fetched prior to building problem finder then configured based on project
        CompilerUtils.configureOptionsBasedOnNature(compilerOptions, project);
        // GROOVY end
        problemFinder = new CompilationUnitProblemFinder(environment, getHandlingPolicy(), compilerOptions,
                getRequestor(), problemFactory);
        boolean analyzeAndGenerateCode = true;
        if (ignoreMethodBodies) {
            analyzeAndGenerateCode = false;
        }
        try {
            if (parser != null) {
                problemFinder.parser = parser;
                unit = parser.parseCompilationUnit(unitElement, true/*full parse*/, monitor);
                problemFinder.resolve(unit, unitElement, true, // verify methods
                        analyzeAndGenerateCode, // analyze code
                        analyzeAndGenerateCode); // generate code
            } else {
                unit = problemFinder.resolve(unitElement, true, // verify methods
                        analyzeAndGenerateCode, // analyze code
                        analyzeAndGenerateCode); // generate code
            }
        } catch (AbortCompilation e) {
            problemFinder.handleInternalException(e, unit);
        }
        if (unit != null) {
            CompilationResult unitResult = unit.compilationResult;
            CategorizedProblem[] unitProblems = unitResult.getProblems();
            int length = unitProblems == null ? 0 : unitProblems.length;
            if (length > 0) {
                CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
                System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
                problems.put(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, categorizedProblems);
            }
            unitProblems = unitResult.getTasks();
            length = unitProblems == null ? 0 : unitProblems.length;
            if (length > 0) {
                CategorizedProblem[] categorizedProblems = new CategorizedProblem[length];
                System.arraycopy(unitProblems, 0, categorizedProblems, 0, length);
                problems.put(IJavaModelMarker.TASK_MARKER, categorizedProblems);
            }
            if (NameLookup.VERBOSE) {
                System.out.println(
                        Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInSourcePackage: " //$NON-NLS-1$
                                + environment.nameLookup.timeSpentInSeekTypesInSourcePackage + "ms"); //$NON-NLS-1$
                System.out.println(
                        Thread.currentThread() + " TIME SPENT in NameLoopkup#seekTypesInBinaryPackage: " //$NON-NLS-1$
                                + environment.nameLookup.timeSpentInSeekTypesInBinaryPackage + "ms"); //$NON-NLS-1$
            }
        }
    } catch (OperationCanceledException e) {
        // catch this exception so as to not enter the catch(RuntimeException e) below
        throw e;
    } catch (RuntimeException e) {
        // avoid breaking other tools due to internal compiler failure (40334)
        String lineDelimiter = unitElement.findRecommendedLineSeparator();
        StringBuffer message = new StringBuffer("Exception occurred during problem detection:"); //$NON-NLS-1$
        message.append(lineDelimiter);
        message.append(
                "----------------------------------- SOURCE BEGIN -------------------------------------"); //$NON-NLS-1$
        message.append(lineDelimiter);
        message.append(unitElement.getSource());
        message.append(lineDelimiter);
        message.append("----------------------------------- SOURCE END -------------------------------------"); //$NON-NLS-1$
        Util.log(e, message.toString());
        throw new JavaModelException(e, IJavaModelStatusConstants.COMPILER_FAILURE);
    } finally {
        if (environment != null)
            environment.setMonitor(null); // don't hold a reference to this external object
        if (problemFactory != null)
            problemFactory.monitor = null; // don't hold a reference to this external object
        // NB: unit.cleanUp() is done by caller
        if (problemFinder != null && !creatingAST)
            problemFinder.lookupEnvironment.reset();
    }
    return unit;
}

From source file:org.eclipse.jdt.internal.core.hierarchy.HierarchyBuilder.java

License:Open Source License

public HierarchyBuilder(TypeHierarchy hierarchy) throws JavaModelException {

    this.hierarchy = hierarchy;
    JavaProject project = (JavaProject) hierarchy.javaProject();

    IType focusType = hierarchy.getType();
    org.eclipse.jdt.core.ICompilationUnit unitToLookInside = focusType == null ? null
            : focusType.getCompilationUnit();
    org.eclipse.jdt.core.ICompilationUnit[] workingCopies = this.hierarchy.workingCopies;
    org.eclipse.jdt.core.ICompilationUnit[] unitsToLookInside;
    if (unitToLookInside != null) {
        int wcLength = workingCopies == null ? 0 : workingCopies.length;
        if (wcLength == 0) {
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[] { unitToLookInside };
        } else {/*w  ww.ja  v  a2 s.c om*/
            unitsToLookInside = new org.eclipse.jdt.core.ICompilationUnit[wcLength + 1];
            unitsToLookInside[0] = unitToLookInside;
            System.arraycopy(workingCopies, 0, unitsToLookInside, 1, wcLength);
        }
    } else {
        unitsToLookInside = workingCopies;
    }
    if (project != null) {
        // GROOVY start - pulled out of the call
        Map optionMap = project.getOptions(true);
        CompilerUtils.configureOptionsBasedOnNature(optionMap, project);
        // GROOVY end
        SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(unitsToLookInside);
        this.nameLookup = searchableEnvironment.nameLookup;
        this.hierarchyResolver = new HierarchyResolver(searchableEnvironment,
                // GROOVY start
                /* old {
                project.getOptions(true),
                } new */
                optionMap,
                // GROOVY end
                this, new DefaultProblemFactory());
    }
    this.infoToHandle = new HashMap(5);
    this.focusQualifiedName = focusType == null ? null : focusType.getFullyQualifiedName();
}

From source file:org.eclipse.jdt.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Create a new parser for the given project, as well as a lookup environment.
 */// w  w w  . j  a v a2  s .  co  m
public void initialize(JavaProject project, int possibleMatchSize) throws JavaModelException {
    // clean up name environment only if there are several possible match as it is reused
    // when only one possible match (bug 58581)
    if (this.nameEnvironment != null && possibleMatchSize != 1)
        this.nameEnvironment.cleanup();

    SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.workingCopies);

    // if only one possible match, a file name environment costs too much,
    // so use the existing searchable  environment which will populate the java model
    // only for this possible match and its required types.
    this.nameEnvironment = possibleMatchSize == 1 ? (INameEnvironment) searchableEnvironment
            : (INameEnvironment) new JavaSearchNameEnvironment(project, this.workingCopies);

    // create lookup environment
    Map map = project.getOptions(true);
    map.put(CompilerOptions.OPTION_TaskTags, org.eclipse.jdt.internal.compiler.util.Util.EMPTY_STRING);
    this.options = new CompilerOptions(map);
    ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            this.options, new DefaultProblemFactory());
    this.lookupEnvironment = new LookupEnvironment(this, this.options, problemReporter, this.nameEnvironment);

    this.parser = MatchLocatorParser.createParser(problemReporter, this);

    // basic parser needs also to be reset as project options may have changed
    // see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=163072
    this.basicParser = null;

    // remember project's name lookup
    this.nameLookup = searchableEnvironment.nameLookup;

    // initialize queue of units
    this.numberOfMatches = 0;
    this.matchesToProcess = new PossibleMatch[possibleMatchSize];
}