List of usage examples for org.eclipse.jdt.internal.compiler.ast CompilationUnitDeclaration toString
@Override
public String toString()
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 ava 2s.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: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// www . j a v a 2 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:lombok.RunTestsViaEcj.java
License:Open Source License
@Override public void transformCode(Collection<CompilerMessage> messages, StringWriter result, File file, String encoding, Map<String, String> formatPreferences) throws Throwable { final AtomicReference<CompilationResult> compilationResult_ = new AtomicReference<CompilationResult>(); final AtomicReference<CompilationUnitDeclaration> compilationUnit_ = new AtomicReference<CompilationUnitDeclaration>(); ICompilerRequestor bitbucketRequestor = new ICompilerRequestor() { @Override//from ww w . j a v a2 s . co m public void acceptResult(CompilationResult result) { compilationResult_.set(result); } }; String source = readFile(file); final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), encoding == null ? "UTF-8" : encoding); Compiler ecjCompiler = new Compiler(createFileSystem(file), ecjErrorHandlingPolicy(), ecjCompilerOptions(), bitbucketRequestor, new DefaultProblemFactory(Locale.ENGLISH)) { @Override protected synchronized void addCompilationUnit(ICompilationUnit inUnit, CompilationUnitDeclaration parsedUnit) { if (inUnit == sourceUnit) compilationUnit_.set(parsedUnit); super.addCompilationUnit(inUnit, parsedUnit); } }; ecjCompiler.compile(new ICompilationUnit[] { sourceUnit }); CompilationResult compilationResult = compilationResult_.get(); CategorizedProblem[] problems = compilationResult.getAllProblems(); if (problems != null) for (CategorizedProblem p : problems) { messages.add(new CompilerMessage(p.getSourceLineNumber(), p.getSourceStart(), p.isError(), p.getMessage())); } CompilationUnitDeclaration cud = compilationUnit_.get(); if (cud == null) result.append("---- NO CompilationUnit provided by ecj ----"); else result.append(cud.toString()); }
From source file:lombok.RunTestsViaEclipse.java
License:Open Source License
@Override public void transformCode(final StringBuilder messages, StringWriter result, File file) throws Throwable { // setup parser and compiler final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems(); final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.ENGLISH); final INameEnvironment nameEnvironment = new LombokTestNameEnvironment(); final ICompilerRequestor compilerRequestor = new LombokTestCompilerRequestor(); final ISourceElementRequestor sourceElementRequestor = new LombokTestSourceElementRequestor(); final CompilerOptions options = ecjCompilerOptions(); final LombokTestCompiler jdtCompiler = new LombokTestCompiler(nameEnvironment, policy, options, compilerRequestor, problemFactory); final SourceElementParser parser = new SourceElementParser(sourceElementRequestor, problemFactory, options, true, true);//from w ww.j ava 2 s . co m // read the file final String source = readFile(file); final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(), "UTF-8"); // parse final CompilationUnitDeclaration cud = parser.parseCompilationUnit(sourceUnit, true, null); // build jdtCompiler.lookupEnvironment.buildTypeBindings(cud, null); jdtCompiler.lookupEnvironment.completeTypeBindings(cud, true); // process if (cud.scope != null) cud.scope.verifyMethods(jdtCompiler.lookupEnvironment.methodVerifier()); // handle problems final CategorizedProblem[] problems = cud.compilationResult.getAllProblems(); if (problems != null) for (CategorizedProblem p : problems) { messages.append(String.format("%d %s %s\n", p.getSourceLineNumber(), p.isError() ? "error" : p.isWarning() ? "warning" : "unknown", p.getMessage())); } // set transformed code result.append(cud.toString()); }