Example usage for org.eclipse.jdt.internal.compiler.env ICompilationUnit getContents

List of usage examples for org.eclipse.jdt.internal.compiler.env ICompilationUnit getContents

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.env ICompilationUnit getContents.

Prototype

char[] getContents();

Source Link

Document

Answer the contents of the compilation unit.

Usage

From source file:com.codenvy.ide.ext.java.SearchableEnvironmentTest.java

License:Open Source License

private CompilationUnit getCompilationUnit(IJavaProject project, INameEnvironment environment,
        ICompilationUnit compilationUnit) throws JavaModelException {
    int flags = 0;
    flags |= org.eclipse.jdt.core.ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
    flags |= org.eclipse.jdt.core.ICompilationUnit.IGNORE_METHOD_BODIES;
    flags |= org.eclipse.jdt.core.ICompilationUnit.ENABLE_BINDINGS_RECOVERY;
    HashMap<String, String> opts = new HashMap<>(options);
    CompilationUnitDeclaration compilationUnitDeclaration = CodenvyCompilationUnitResolver
            .resolve(compilationUnit, project, environment, opts, flags, null);
    return CodenvyCompilationUnitResolver.convert(compilationUnitDeclaration, compilationUnit.getContents(),
            flags, opts);/*  ww w  .j a  v a2  s . c om*/
}

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

License:Open Source License

/**
 * Ask the engine to compute the selection at the specified position
 * of the given compilation unit.//from   w w w. j  a v a2  s .c om
        
 *  @param sourceUnit org.eclipse.jdt.internal.compiler.env.ICompilationUnit
 *      the source of the current compilation unit.
 *
 *  @param selectionSourceStart int
 *  @param selectionSourceEnd int
 *      a range in the source where the selection is.
 */
public void select(ICompilationUnit sourceUnit, int selectionSourceStart, int selectionSourceEnd) {

    char[] source = sourceUnit.getContents();

    if (DEBUG) {
        System.out.print("SELECTION IN "); //$NON-NLS-1$
        System.out.print(sourceUnit.getFileName());
        System.out.print(" FROM "); //$NON-NLS-1$
        System.out.print(selectionSourceStart);
        System.out.print(" TO "); //$NON-NLS-1$
        System.out.println(selectionSourceEnd);
        System.out.println("SELECTION - Source :"); //$NON-NLS-1$
        System.out.println(source);
    }
    if (!checkSelection(source, selectionSourceStart, selectionSourceEnd)) {
        return;
    }
    if (DEBUG) {
        System.out.print("SELECTION - Checked : \""); //$NON-NLS-1$
        System.out.print(new String(source, this.actualSelectionStart,
                this.actualSelectionEnd - this.actualSelectionStart + 1));
        System.out.println('"');
    }
    try {
        this.acceptedAnswer = false;
        CompilationResult result = new CompilationResult(sourceUnit, 1, 1,
                this.compilerOptions.maxProblemsPerUnit);
        CompilationUnitDeclaration parsedUnit = this.parser.dietParse(sourceUnit, result,
                this.actualSelectionStart, this.actualSelectionEnd);

        if (parsedUnit != null) {
            if (DEBUG) {
                System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                System.out.println(parsedUnit.toString());
            }

            // scan the package & import statements first
            if (parsedUnit.currentPackage instanceof SelectionOnPackageReference) {
                char[][] tokens = ((SelectionOnPackageReference) parsedUnit.currentPackage).tokens;
                this.noProposal = false;
                this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                return;
            }
            ImportReference[] imports = parsedUnit.imports;
            if (imports != null) {
                for (int i = 0, length = imports.length; i < length; i++) {
                    ImportReference importReference = imports[i];
                    if (importReference instanceof SelectionOnImportReference) {
                        char[][] tokens = ((SelectionOnImportReference) importReference).tokens;
                        this.noProposal = false;
                        this.requestor.acceptPackage(CharOperation.concatWith(tokens, '.'));
                        this.nameEnvironment.findTypes(CharOperation.concatWith(tokens, '.'), false, false,
                                IJavaSearchConstants.TYPE, this);

                        this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                        if ((this.unitScope = parsedUnit.scope) != null) {
                            int tokenCount = tokens.length;
                            char[] lastToken = tokens[tokenCount - 1];
                            char[][] qualifierTokens = CharOperation.subarray(tokens, 0, tokenCount - 1);

                            if (qualifierTokens != null && qualifierTokens.length > 0) {
                                Binding binding = this.unitScope.getTypeOrPackage(qualifierTokens);
                                if (binding != null && binding instanceof ReferenceBinding) {
                                    ReferenceBinding ref = (ReferenceBinding) binding;
                                    selectMemberTypeFromImport(parsedUnit, lastToken, ref,
                                            importReference.isStatic());
                                    if (importReference.isStatic()) {
                                        selectStaticFieldFromStaticImport(parsedUnit, lastToken, ref);
                                        selectStaticMethodFromStaticImport(parsedUnit, lastToken, ref);
                                    }
                                }
                            }
                        }

                        // accept qualified types only if no unqualified type was accepted
                        if (!this.acceptedAnswer) {
                            acceptQualifiedTypes();
                            if (!this.acceptedAnswer) {
                                this.nameEnvironment.findTypes(this.selectedIdentifier, false, false,
                                        IJavaSearchConstants.TYPE, this);
                                // try with simple type name
                                if (!this.acceptedAnswer) {
                                    acceptQualifiedTypes();
                                }
                            }
                        }
                        if (this.noProposal && this.problem != null) {
                            this.requestor.acceptError(this.problem);
                        }
                        return;
                    }
                }
            }
            if (parsedUnit.types != null || parsedUnit.isPackageInfo()) {
                if (selectDeclaration(parsedUnit))
                    return;
                this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
                if ((this.unitScope = parsedUnit.scope) != null) {
                    try {
                        this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                        CompilationUnitDeclaration previousUnitBeingCompleted = this.lookupEnvironment.unitBeingCompleted;
                        this.lookupEnvironment.unitBeingCompleted = parsedUnit;
                        parsedUnit.scope.faultInTypes();
                        this.lookupEnvironment.unitBeingCompleted = previousUnitBeingCompleted;
                        ASTNode node = null;
                        if (parsedUnit.types != null)
                            node = parseBlockStatements(parsedUnit, selectionSourceStart);
                        if (DEBUG) {
                            System.out.println("SELECTION - AST :"); //$NON-NLS-1$
                            System.out.println(parsedUnit.toString());
                        }
                        parsedUnit.resolve();
                        if (node != null) {
                            selectLocalDeclaration(node);
                        }
                    } 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, sourceUnit, e.isDeclaration);
                        }
                    }
                }
            }
        }
        // only reaches here if no selection could be derived from the parsed tree
        // thus use the selected source and perform a textual type search
        if (!this.acceptedAnswer) {
            this.nameEnvironment.findTypes(this.selectedIdentifier, false, false, IJavaSearchConstants.TYPE,
                    this);

            // accept qualified types only if no unqualified type was accepted
            if (!this.acceptedAnswer) {
                acceptQualifiedTypes();

                // accept types from all the workspace only if no type was found in the project scope
                if (this.noProposal) {
                    findAllTypes(this.selectedIdentifier);
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (IndexOutOfBoundsException e) { // work-around internal failure - 1GEMF6D
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
        if (DEBUG) {
            System.out.println("Exception caught by SelectionEngine:"); //$NON-NLS-1$
            e.printStackTrace(System.out);
        }
    } finally {
        reset(true);
    }
}

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);//from ww w  . j  a v  a  2s  .  c  o  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.codehaus.jdt.groovy.integration.internal.MultiplexingCommentRecorderParser.java

License:Open Source License

@Override
public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) {
    if (ContentTypeUtils.isGroovyLikeFileName(sourceUnit.getFileName())) {
        // even though the Java scanner is not used, its contents can be asked for.
        if (this.scanner != null) {
            this.scanner.setSource(sourceUnit.getContents());
        }//w w  w.j  a  va2 s  .c o  m
        // FIXASC Is it ok to use a new parser here everytime? If we don't we sometimes recurse back into the first one
        // FIXASC ought to reuse to ensure types end up in same groovy CU
        return new GroovyParser(this.groovyParser.requestor, this.groovyParser.getCompilerOptions(),
                this.groovyParser.problemReporter, allowTransforms, true).dietParse(sourceUnit,
                        compilationResult);
        // return groovyParser.dietParse(sourceUnit, compilationResult);
    } else {
        return super.dietParse(sourceUnit, compilationResult);
    }
}

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

License:Open Source License

@Override
public CompilationUnitDeclaration parseCompilationUnit(ICompilationUnit unit, boolean fullParse,
        IProgressMonitor pm) {/* w w w .  ja va2  s.  c  om*/
    if (ContentTypeUtils.isGroovyLikeFileName(unit.getFileName())) {

        // ASSUMPTIONS:
        // 1) there is no difference between a diet and full parse in the groovy works, so can ignore the fullParse parameter
        // 2) parsing is for the entire CU (ie- from character 0, to unit.getContents().length)
        // 3) nodesToCategories map is not necessary. I think it has something to do with JavaDoc, but not sure

        CompilationResult compilationResult = new CompilationResult(unit, 0, 0,
                this.options.maxProblemsPerUnit);

        // FIXASC Is it ok to use a new parser here everytime? If we don't we sometimes recurse back into the first one
        GroovyCompilationUnitDeclaration cud = (GroovyCompilationUnitDeclaration) new GroovyParser(this.options,
                problemReporter, false, true).dietParse(unit, compilationResult);

        // CompilationUnitDeclaration cud groovyParser.dietParse(sourceUnit, compilationResult);
        HashtableOfObjectToInt sourceEnds = createSourceEnds(cud);
        GroovyIndexingVisitor visitor = new GroovyIndexingVisitor(requestor);
        visitor.doVisit(cud.getModuleNode(), cud.currentPackage);

        notifier.notifySourceElementRequestor(cud, 0, unit.getContents().length, groovyReportReferenceInfo,
                sourceEnds,
                /* We don't care about the @category tag, so pass empty map */Collections.EMPTY_MAP);
        return cud;
    } else {
        return super.parseCompilationUnit(unit, fullParse, pm);
    }
}

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

License:Open Source License

@Override
public CompilationUnitDeclaration parseCompilationUnit(ICompilationUnit unit, boolean fullParse,
        IProgressMonitor pm) {/*from w  ww .  j a  va  2 s.c om*/

    if (ContentTypeUtils.isGroovyLikeFileName(unit.getFileName())) {
        // ASSUMPTIONS:
        // 1) there is no difference between a diet and full parse in the groovy works, so can ignore the fullParse parameter
        // 2) parsing is for the entire CU (ie- from character 0, to unit.getContents().length)
        // 3) nodesToCategories map is not necessary. I think it has something to do with JavaDoc, but not sure

        CompilationResult compilationResult = new CompilationResult(unit, 0, 0,
                this.options.maxProblemsPerUnit);

        // FIXASC Is it ok to use a new parser here everytime? If we don't we sometimes recurse back into the first one
        // FIXASC ought to reuse to ensure types end up in same groovy CU
        CompilationUnitDeclaration cud = new GroovyParser(this.parser.requestor, this.options, problemReporter,
                false, true).dietParse(unit, compilationResult);

        // CompilationUnitDeclaration cud = parser.dietParse(unit, compilationResult);

        HashtableOfObjectToInt sourceEnds = createSourceEnds(cud);

        notifier.notifySourceElementRequestor(cud, 0, unit.getContents().length, groovyReportReferenceInfo,
                sourceEnds,
                /* We don't care about the @category tag, so pass empty map */Collections.EMPTY_MAP);
        return cud;
    } else {
        return super.parseCompilationUnit(unit, fullParse, pm);
    }
}

From source file:org.codehaus.jdt.groovy.internal.compiler.ast.GroovyParser.java

License:Open Source License

/**
 * Call the groovy parser to drive the first few phases of
 *///from   w  ww  . j a  va 2s . c  o  m
public CompilationUnitDeclaration dietParse(ICompilationUnit sourceUnit, CompilationResult compilationResult) {
    char[] sourceCode = sourceUnit.getContents();
    if (sourceCode == null) {
        sourceCode = CharOperation.NO_CHAR; // pretend empty from thereon
    }

    // FIXASC (M3) need our own tweaked subclass of CompilerConfiguration?
    CompilerConfiguration groovyCompilerConfig = new CompilerConfiguration();
    // groovyCompilerConfig.setPluginFactory(new ErrorRecoveredCSTParserPluginFactory(null));
    ErrorCollector errorCollector = new GroovyErrorCollectorForJDT(groovyCompilerConfig);
    String filepath = null;

    // This check is necessary because the filename is short (as in the last part, eg. Foo.groovy) for types coming in
    // from the hierarchy resolver. If there is the same type in two different packages then the compilation process
    // is going to go wrong because the filename is used as a key in some groovy data structures. This can lead to false
    // complaints about the same file defining duplicate types.
    if (sourceUnit instanceof org.eclipse.jdt.internal.compiler.batch.CompilationUnit) {
        filepath = new String(((org.eclipse.jdt.internal.compiler.batch.CompilationUnit) sourceUnit).fileName);
    } else {
        filepath = new String(sourceUnit.getFileName());
    }

    // Try to turn this into a 'real' absolute file system reference (this is because Grails 1.5 expects it).
    Path path = new Path(filepath);
    IFile eclipseFile = null;
    // GRECLIPSE-1269 ensure get plugin is not null to ensure the workspace is open (ie- not in batch mode)
    if (ResourcesPlugin.getPlugin() != null && path.segmentCount() >= 2) { // Needs 2 segments: a project and file name or
        // eclipse throws assertion failed here.
        eclipseFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filepath));
        final IPath location = eclipseFile.getLocation();
        if (location != null) {
            filepath = location.toFile().getAbsolutePath();
        }
    }

    SourceUnit groovySourceUnit = new EclipseSourceUnit(eclipseFile, filepath, new String(sourceCode),
            groovyCompilerConfig, groovyCompilationUnit.getClassLoader(), errorCollector);
    groovySourceUnit.isReconcile = isReconcile;
    GroovyCompilationUnitDeclaration gcuDeclaration = new GroovyCompilationUnitDeclaration(problemReporter,
            compilationResult, sourceCode.length, groovyCompilationUnit, groovySourceUnit, compilerOptions);
    // FIXASC get this from the Antlr parser
    compilationResult.lineSeparatorPositions = GroovyUtils.getSourceLineSeparatorsIn(sourceCode);
    groovyCompilationUnit.addSource(groovySourceUnit);

    // Check if it is worth plugging in a callback listener for parse/generation
    if (requestor instanceof org.eclipse.jdt.internal.compiler.Compiler) {
        org.eclipse.jdt.internal.compiler.Compiler compiler = ((org.eclipse.jdt.internal.compiler.Compiler) requestor);
        if (compiler.requestor instanceof BatchImageBuilder) {
            BuildNotifier notifier = ((BatchImageBuilder) compiler.requestor).notifier;
            if (notifier != null) {
                groovyCompilationUnit.setProgressListener(new ProgressListenerImpl(notifier));
            }
        }
    }
    gcuDeclaration.processToPhase(Phases.CONVERSION);

    // Groovy moduleNode is null when there is a fatal error
    // Otherwise, recover what we can
    if (gcuDeclaration.getModuleNode() != null) {
        gcuDeclaration.populateCompilationUnitDeclaration();
        for (TypeDeclaration decl : gcuDeclaration.types) {
            GroovyTypeDeclaration gtDeclaration = (GroovyTypeDeclaration) decl;
            resolver.record(gtDeclaration);
        }
    }
    // Is this a script?
    // If allowTransforms is TRUE then this is a 'full build' and we should remember which are scripts so that
    // .class file output can be suppressed
    if (allowTransforms && (sourceUnit instanceof SourceFile)) {
        if (this.scriptFolderSelector == null) {
            this.scriptFolderSelector = new ScriptFolderSelector(
                    ((SourceFile) sourceUnit).resource.getProject());
        }
        SourceFile file = (SourceFile) sourceUnit;
        if (scriptFolderSelector.isScript(file.resource)) {
            gcuDeclaration.tagAsScript();
        }
        // System.out.println(sourceUnit + " " + (isScript ? "IS" : "is NOT") + " a script");
    }
    if (debugRequestor != null) {
        debugRequestor.acceptCompilationUnitDeclaration(gcuDeclaration);
    }
    return gcuDeclaration;
}

From source file:org.eclipse.che.jdt.RestNameEnvironment.java

License:Open Source License

private CompilationUnit getCompilationUnit(IJavaProject project, INameEnvironment environment,
        ICompilationUnit compilationUnit) throws JavaModelException {
    int flags = 0;
    flags |= org.eclipse.jdt.core.ICompilationUnit.ENABLE_STATEMENTS_RECOVERY;
    flags |= org.eclipse.jdt.core.ICompilationUnit.IGNORE_METHOD_BODIES;
    flags |= org.eclipse.jdt.core.ICompilationUnit.ENABLE_BINDINGS_RECOVERY;
    HashMap<String, String> opts = new HashMap<>(javaProjectService.getOptions());
    CompilationUnitDeclaration compilationUnitDeclaration = CodenvyCompilationUnitResolver
            .resolve(compilationUnit, project, environment, opts, flags, null);
    return CodenvyCompilationUnitResolver.convert(compilationUnitDeclaration, compilationUnit.getContents(),
            flags, opts);/* ww  w  . ja  v  a 2  s .c om*/
}

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 o  m*/
    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.mappings.CallinImplementorDyn.java

License:Open Source License

Expression copyExpression(Expression expression, Scope scope, ICompilationUnit cu) {
    if (cu == null)
        return expression; // FIXME: do we need a fallback when cu is built from model?
    final Parser parser = new Parser(scope.problemReporter(), false);
    char[] source = cu.getContents();
    return parser.parseExpression(source, expression.sourceStart,
            expression.sourceEnd - expression.sourceStart + 1, scope.referenceCompilationUnit(),
            false /* record line separators */);
}