List of usage examples for org.eclipse.jdt.internal.compiler CompilationResult CompilationResult
public CompilationResult(ICompilationUnit compilationUnit, int unitIndex, int totalUnitsKnown, int maxProblemPerUnit)
From source file:ch.uzh.ifi.seal.changedistiller.ast.java.JavaCompilationUtils.java
License:Apache License
private static CompilationResult createDefaultCompilationResult(ICompilationUnit cu, CompilerOptions options) { return new CompilationResult(cu, 0, 0, options.maxProblemsPerUnit); }
From source file:ch.uzh.ifi.seal.changedistiller.util.CompilationUtils.java
License:Apache License
private static CompilationResult createDefaultCompilationResult(ICompilationUnit cu, CompilerOptions options) { CompilationResult compilationResult = new CompilationResult(cu, 0, 0, options.maxProblemsPerUnit); return compilationResult; }
From source file:com.android.tools.idea.lint.LombokPsiConverterTest.java
License:Apache License
@Nullable private static Node parse(String code) { CompilerOptions options = new CompilerOptions(); options.complianceLevel = options.sourceLevel = options.targetJDK = ClassFileConstants.JDK1_7; options.parseLiteralExpressionsAsConstants = true; ProblemReporter problemReporter = new ProblemReporter(DefaultErrorHandlingPolicies.exitOnFirstError(), options, new DefaultProblemFactory()); Parser parser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants); parser.javadocParser.checkDocComment = false; EcjTreeConverter converter = new EcjTreeConverter(); org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit = new org.eclipse.jdt.internal.compiler.batch.CompilationUnit( code.toCharArray(), "unitTest", "UTF-8"); CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); CompilationUnitDeclaration unit = parser.parse(sourceUnit, compilationResult); if (unit == null) { return null; }// w w w . j a va 2 s. c o m converter.visit(code, unit); List<? extends Node> nodes = converter.getAll(); for (lombok.ast.Node node : nodes) { if (node instanceof lombok.ast.CompilationUnit) { return node; } } return null; }
From source file:com.android.tools.lint.EcjParser.java
License:Apache License
@Nullable private CompilationUnitDeclaration getParsedUnit(@NonNull JavaContext context, @NonNull String code) { ICompilationUnit sourceUnit = null;//from w w w . j a v a 2 s . c o m if (mSourceUnits != null && mCompiled != null) { sourceUnit = mSourceUnits.get(context.file); if (sourceUnit != null) { CompilationUnitDeclaration unit = mCompiled.get(sourceUnit); if (unit != null) { return unit; } } } if (sourceUnit == null) { sourceUnit = new CompilationUnit(code.toCharArray(), context.file.getName(), UTF_8); } try { CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0); return getParser().parse(sourceUnit, compilationResult); } catch (AbortCompilation e) { // No need to report Java parsing errors while running in Eclipse. // Eclipse itself will already provide problem markers for these files, // so all this achieves is creating "multiple annotations on this line" // tooltips instead. return null; } }
From source file:com.codenvy.ide.ext.java.server.internal.codeassist.impl.Engine.java
License:Open Source License
/** * Add an additional compilation unit./*from www. ja v a 2 s.c om*/ */ public void accept(ICompilationUnit sourceUnit, AccessRestriction accessRestriction) { CompilationResult result = new CompilationResult(sourceUnit, 1, 1, this.compilerOptions.maxProblemsPerUnit); AssistParser assistParser = getParser(); Object parserState = assistParser.becomeSimpleParser(); CompilationUnitDeclaration parsedUnit = assistParser.dietParse(sourceUnit, result); assistParser.restoreAssistParser(parserState); this.lookupEnvironment.buildTypeBindings(parsedUnit, accessRestriction); this.lookupEnvironment.completeTypeBindings(parsedUnit, true); }
From source file:com.codenvy.ide.ext.java.server.internal.codeassist.impl.Engine.java
License:Open Source License
/** * Add additional source types (the first one is the requested type, the rest is formed by the * secondary types defined in the same compilation unit). *//* w ww . ja v a2 s.c om*/ public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) { CompilationResult result = new CompilationResult(sourceTypes[0].getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration unit = SourceTypeConverter.buildCompilationUnit(sourceTypes, //sourceTypes[0] is always toplevel here SourceTypeConverter.FIELD_AND_METHOD // need field and methods | SourceTypeConverter.MEMBER_TYPE, // need member types // no need for field initialization this.lookupEnvironment.problemReporter, result); if (unit != null) { this.lookupEnvironment.buildTypeBindings(unit, accessRestriction); this.lookupEnvironment.completeTypeBindings(unit, true); } }
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 . ja va 2 s .c o m * @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//w ww . ja va2 s .co m * * @param typeName char[] * a type name which is to be resolved in the context of a compilation unit. * NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left) * * @param context org.eclipse.jdt.core.IType * the context in which code assist is invoked. */ public void selectType(char[] typeName, IType context) throws JavaModelException { try { this.acceptedAnswer = false; // only the type erasure are returned by IType.resolvedType(...) if (CharOperation.indexOf('<', typeName) != -1) { char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/); typeSig = Signature.getTypeErasure(typeSig); typeName = Signature.toCharArray(typeSig); } CompilationUnitDeclaration parsedUnit = null; TypeDeclaration typeDeclaration = null; org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit(); if (cu != null) { IType[] topLevelTypes = cu.getTypes(); int length = topLevelTypes.length; SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length]; for (int i = 0; i < length; i++) { topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo(); } CompilationResult result = new CompilationResult( (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) cu, 1, 1, this.compilerOptions.maxProblemsPerUnit); int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE; if (context.isAnonymous() || context.isLocal()) flags |= SourceTypeConverter.LOCAL_TYPE; parsedUnit = SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags, this.parser.problemReporter(), result); if (parsedUnit != null && parsedUnit.types != null) { if (DEBUG) { System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$ System.out.println(parsedUnit.toString()); } // find the type declaration that corresponds to the original source type typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context); } } else { // binary type ClassFile classFile = (ClassFile) context.getClassFile(); ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo( (IFile) null/*classFile.resource()*/, false/*don't fully initialize so as to keep constant pool (used below)*/); CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1, this.compilerOptions.maxProblemsPerUnit); parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0); HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray(); BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result, typeNames); typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit); parsedUnit.imports = converter.buildImports(reader); } if (typeDeclaration != null) { // add fake field with the type we're looking for // note: since we didn't ask for fields above, there is no field defined yet FieldDeclaration field = new FieldDeclaration(); int dot; if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) { this.selectedIdentifier = typeName; field.type = new SelectionOnSingleTypeReference(typeName, -1); // position not used } else { char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot); char[] selectionIdentifier = CharOperation.subarray(typeName, dot + 1, typeName.length); this.selectedIdentifier = selectionIdentifier; field.type = new SelectionOnQualifiedTypeReference(previousIdentifiers, selectionIdentifier, new long[previousIdentifiers.length + 1]); } field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$ typeDeclaration.fields = new FieldDeclaration[] { field }; // build bindings this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/); if ((this.unitScope = parsedUnit.scope) != null) { try { // build fields // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along) this.lookupEnvironment.completeTypeBindings(parsedUnit, true); // resolve parsedUnit.scope.faultInTypes(); parsedUnit.resolve(); } catch (SelectionNodeFound e) { if (e.binding != null) { if (DEBUG) { System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$ System.out.println(e.binding.toString()); } // if null then we found a problem in the selection node selectFrom(e.binding, parsedUnit, e.isDeclaration); } } } } if (this.noProposal && this.problem != null) { this.requestor.acceptError(this.problem); } } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object } finally { reset(true); } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java
License:Open Source License
public void searchAllConstructorDeclarations(final char[] packageName, final char[] typeName, final int typeMatchRule, IJavaSearchScope scope, final IRestrictedAccessConstructorRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { // Validate match rule first final int validatedTypeMatchRule = SearchPattern .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule); final int pkgMatchRule = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE; final char NoSuffix = IIndexConstants.TYPE_SUFFIX; // Used as TYPE_SUFFIX has no effect in method #match(char, char[] , int, char[], int , int, char[], char[]) // Debug// ww w . j a va 2 s . c o m if (VERBOSE) { Util.verbose( "BasicSearchEngine.searchAllConstructorDeclarations(char[], char[], int, IJavaSearchScope, IRestrictedAccessConstructorRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ if (validatedTypeMatchRule != typeMatchRule) { Util.verbose(" - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$ } Util.verbose(" - scope: " + scope); //$NON-NLS-1$ } if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results // Create pattern final ConstructorDeclarationPattern pattern = new ConstructorDeclarationPattern(packageName, typeName, validatedTypeMatchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types ConstructorDeclarationPattern record = (ConstructorDeclarationPattern) indexRecord; if ((record.extraFlags & ExtraFlags.IsMemberType) != 0) { return true; // filter out member classes } if ((record.extraFlags & ExtraFlags.IsLocalType) != 0) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // filter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.declaringPackageName == null || record.declaringPackageName.length == 0) ? 0 : record.declaringPackageName.length + 1; int nameLength = record.declaringSimpleName == null ? 0 : record.declaringSimpleName.length; char[] path = new char[pkgLength + nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.declaringPackageName, 0, path, pos, pkgLength - 1); CharOperation.replace(path, '.', '/'); path[pkgLength - 1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.declaringSimpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } nameRequestor.acceptConstructor(record.modifiers, record.declaringSimpleName, record.parameterCount, record.signature, record.parameterTypes, record.parameterNames, record.declaringTypeModifiers, record.declaringPackageName, record.extraFlags, documentPath, accessRestriction); return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 1000); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only scope, searchRequestor, indexManager), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength)); // add type names from working copies if (copies != null) { for (int i = 0; i < copiesLength; i++) { final ICompilationUnit workingCopy = copies[i]; if (scope instanceof HierarchyScope) { if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor)) continue; } else { if (!scope.encloses(workingCopy)) continue; } final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; char[] simpleName = type.getElementName().toCharArray(); if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, simpleName) && !type.isMember()) { int extraFlags = ExtraFlags.getExtraFlags(type); boolean hasConstructor = false; IMethod[] methods = type.getMethods(); for (int k = 0; k < methods.length; k++) { IMethod method = methods[k]; if (method.isConstructor()) { hasConstructor = true; String[] stringParameterNames = method.getParameterNames(); String[] stringParameterTypes = method.getParameterTypes(); int length = stringParameterNames.length; char[][] parameterNames = new char[length][]; char[][] parameterTypes = new char[length][]; for (int l = 0; l < length; l++) { parameterNames[l] = stringParameterNames[l].toCharArray(); parameterTypes[l] = Signature.toCharArray(Signature .getTypeErasure(stringParameterTypes[l]).toCharArray()); } nameRequestor.acceptConstructor(method.getFlags(), simpleName, parameterNames.length, null, // signature is not used for source type parameterTypes, parameterNames, type.getFlags(), packageDeclaration, extraFlags, path, null); } } if (!hasConstructor) { nameRequestor.acceptConstructor(Flags.AccPublic, simpleName, -1, null, // signature is not used for source type CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, type.getFlags(), packageDeclaration, extraFlags, path, null); } } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllConstructorDeclarationsVisitor extends ASTVisitor { private TypeDeclaration[] declaringTypes = new TypeDeclaration[0]; private int declaringTypesPtr = -1; private void endVisit(TypeDeclaration typeDeclaration) { if (!hasConstructor(typeDeclaration) && typeDeclaration.enclosingType == null) { if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) { nameRequestor.acceptConstructor(Flags.AccPublic, typeName, -1, null, // signature is not used for source type CharOperation.NO_CHAR_CHAR, CharOperation.NO_CHAR_CHAR, typeDeclaration.modifiers, packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path, null); } } this.declaringTypes[this.declaringTypesPtr] = null; this.declaringTypesPtr--; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope s) { endVisit(typeDeclaration); } public void endVisit(TypeDeclaration memberTypeDeclaration, ClassScope s) { endVisit(memberTypeDeclaration); } private boolean hasConstructor(TypeDeclaration typeDeclaration) { AbstractMethodDeclaration[] methods = typeDeclaration.methods; int length = methods == null ? 0 : methods.length; for (int j = 0; j < length; j++) { if (methods[j].isConstructor()) { return true; } } return false; } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope classScope) { TypeDeclaration typeDeclaration = this.declaringTypes[this.declaringTypesPtr]; if (match(NoSuffix, packageName, pkgMatchRule, typeName, validatedTypeMatchRule, 0/*no kind*/, packageDeclaration, typeDeclaration.name)) { Argument[] arguments = constructorDeclaration.arguments; int length = arguments == null ? 0 : arguments.length; char[][] parameterNames = new char[length][]; char[][] parameterTypes = new char[length][]; for (int l = 0; l < length; l++) { Argument argument = arguments[l]; parameterNames[l] = argument.name; if (argument.type instanceof SingleTypeReference) { parameterTypes[l] = ((SingleTypeReference) argument.type).token; } else { parameterTypes[l] = CharOperation.concatWith( ((QualifiedTypeReference) argument.type).tokens, '.'); } } TypeDeclaration enclosing = typeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { enclosingTypeNames = CharOperation.arrayConcat( new char[][] { enclosing.name }, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } nameRequestor.acceptConstructor(constructorDeclaration.modifiers, typeName, parameterNames.length, null, // signature is not used for source type parameterTypes, parameterNames, typeDeclaration.modifiers, packageDeclaration, ExtraFlags.getExtraFlags(typeDeclaration), path, null); } return false; // no need to find constructors from local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; } private boolean visit(TypeDeclaration typeDeclaration) { if (this.declaringTypes.length <= ++this.declaringTypesPtr) { int length = this.declaringTypesPtr; System.arraycopy(this.declaringTypes, 0, this.declaringTypes = new TypeDeclaration[length * 2 + 1], 0, length); } this.declaringTypes[this.declaringTypesPtr] = typeDeclaration; return true; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope s) { return visit(typeDeclaration); } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope s) { return visit(memberTypeDeclaration); } } parsedUnit.traverse(new AllConstructorDeclarationsVisitor(), parsedUnit.scope); } } if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java
License:Open Source License
/** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package or a type name * prefix and match modes)./*from w ww . j a va2 s . co m*/ * * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int, * org.eclipse.jdt.core.search.IJavaSearchScope, org.eclipse.jdt.core.search.TypeNameRequestor, int, * org.eclipse.core.runtime.IProgressMonitor) * for detailed comment */ public void searchAllTypeNames(final char[] packageName, final int packageMatchRule, final char[] typeName, final int typeMatchRule, int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { // Validate match rule first final int validatedTypeMatchRule = SearchPattern .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule); // Debug if (VERBOSE) { Util.verbose( "BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, " + "int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - package match rule: " + getMatchRuleString(packageMatchRule)); //$NON-NLS-1$ Util.verbose(" - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ if (validatedTypeMatchRule != typeMatchRule) { Util.verbose(" - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$ } Util.verbose(" - search for: " + searchFor); //$NON-NLS-1$ Util.verbose(" - scope: " + scope); //$NON-NLS-1$ } if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results final char typeSuffix; switch (searchFor) { case IJavaSearchConstants.CLASS: typeSuffix = IIndexConstants.CLASS_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_INTERFACE: typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_ENUM: typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX; break; case IJavaSearchConstants.INTERFACE: typeSuffix = IIndexConstants.INTERFACE_SUFFIX; break; case IJavaSearchConstants.INTERFACE_AND_ANNOTATION: typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX; break; case IJavaSearchConstants.ENUM: typeSuffix = IIndexConstants.ENUM_SUFFIX; break; case IJavaSearchConstants.ANNOTATION_TYPE: typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; break; default: typeSuffix = IIndexConstants.TYPE_SUFFIX; break; } final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH ? new TypeDeclarationPattern(packageName, null, typeName, typeSuffix, validatedTypeMatchRule) : new QualifiedTypeDeclarationPattern(packageName, packageMatchRule, typeName, typeSuffix, validatedTypeMatchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // filter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.pkg == null || record.pkg.length == 0) ? 0 : record.pkg.length + 1; int nameLength = record.simpleName == null ? 0 : record.simpleName.length; char[] path = new char[pkgLength + nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.pkg, 0, path, pos, pkgLength - 1); CharOperation.replace(path, '.', '/'); path[pkgLength - 1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } if (match(record.typeSuffix, record.modifiers)) { nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); } return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 1000); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only scope, searchRequestor, indexManager), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength)); // add type names from working copies if (copies != null) { for (int i = 0; i < copiesLength; i++) { final ICompilationUnit workingCopy = copies[i]; if (scope instanceof HierarchyScope) { if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor)) continue; } else { if (!scope.encloses(workingCopy)) continue; } final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; IJavaElement parent = type.getParent(); char[][] enclosingTypeNames; if (parent instanceof IType) { char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.') .toCharArray(); enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); } else { enclosingTypeNames = CharOperation.NO_CHAR_CHAR; } char[] simpleName = type.getElementName().toCharArray(); int kind; if (type.isEnum()) { kind = TypeDeclaration.ENUM_DECL; } else if (type.isAnnotation()) { kind = TypeDeclaration.ANNOTATION_TYPE_DECL; } else if (type.isClass()) { kind = TypeDeclaration.CLASS_DECL; } else /*if (type.isInterface())*/ { kind = TypeDeclaration.INTERFACE_DECL; } if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, kind, packageDeclaration, simpleName)) { if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { ((TypeNameMatchRequestorWrapper) nameRequestor).requestor.acceptTypeNameMatch( new JavaSearchTypeNameMatch(type, type.getFlags())); } else { nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); } } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllTypeDeclarationsVisitor extends ASTVisitor { public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; // no local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) { if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { IType type = workingCopy.getType(new String(typeName)); ((TypeNameMatchRequestorWrapper) nameRequestor).requestor .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, typeDeclaration.modifiers)); } else { nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); } } return true; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) { // compute enclosing type names TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { enclosingTypeNames = CharOperation.arrayConcat( new char[][] { enclosing.name }, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } // report if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { IType type = workingCopy.getType(new String(enclosingTypeNames[0])); for (int j = 1, l = enclosingTypeNames.length; j < l; j++) { type = type.getType(new String(enclosingTypeNames[j])); } ((TypeNameMatchRequestorWrapper) nameRequestor).requestor .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0)); } else { nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); } } return true; } } parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); } } if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } }