org.eclipse.jdt.internal.core.SearchableEnvironment Java Examples

The following examples show how to use org.eclipse.jdt.internal.core.SearchableEnvironment. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PackageBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IJavaElement getJavaElement() {
	INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment; // a package binding always has a LooupEnvironment set
	if (!(nameEnvironment instanceof SearchableEnvironment)) return null;
	// this is not true in standalone DOM/AST
	NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
	if (nameLookup == null) return null;
	IJavaElement[] pkgs = nameLookup.findPackageFragments(getName(), false/*exact match*/);
	if (pkgs == null) return null;
	if (pkgs.length == 0) {
		// add additional tracing as this should not happen
		org.eclipse.jdt.internal.core.util.Util.log(
			new Status(
					IStatus.WARNING,
					JavaCore.PLUGIN_ID,
					"Searching for package " + getName() + " returns an empty array")); //$NON-NLS-1$ //$NON-NLS-2$
		return null;
	}
	return pkgs[0];
}
 
Example #2
Source File: PatchExtensionMethodCompletionProposal.java    From EasyMPermission with MIT License 5 votes vote down vote up
private static void copyNameLookupAndCompletionEngine(CompletionProposalCollector completionProposalCollector, IJavaCompletionProposal proposal,
		InternalCompletionProposal newProposal) {
	
	try {
		InternalCompletionContext context = (InternalCompletionContext) Reflection.contextField.get(completionProposalCollector);
		InternalExtendedCompletionContext extendedContext = (InternalExtendedCompletionContext) Reflection.extendedContextField.get(context);
		LookupEnvironment lookupEnvironment = (LookupEnvironment) Reflection.lookupEnvironmentField.get(extendedContext);
		Reflection.nameLookupField.set(newProposal, ((SearchableEnvironment) lookupEnvironment.nameEnvironment).nameLookup);
		Reflection.completionEngineField.set(newProposal, lookupEnvironment.typeRequestor);
	} catch (IllegalAccessException ignore) {
		// ignore
	}
}
 
Example #3
Source File: RegionBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Configure this type hierarchy that is based on a region.
 */
private void createTypeHierarchyBasedOnRegion(HashMap allOpenablesInRegion, IProgressMonitor monitor) {

	try {
		int size = allOpenablesInRegion.size();
		if (monitor != null) monitor.beginTask("", size * 2/* 1 for build binding, 1 for connect hierarchy*/); //$NON-NLS-1$
		this.infoToHandle = new HashMap(size);
		Iterator javaProjects = allOpenablesInRegion.entrySet().iterator();
		while (javaProjects.hasNext()) {
			Map.Entry entry = (Map.Entry) javaProjects.next();
			JavaProject project = (JavaProject) entry.getKey();
			ArrayList allOpenables = (ArrayList) entry.getValue();
			Openable[] openables = new Openable[allOpenables.size()];
			allOpenables.toArray(openables);

			try {
				// resolve
				SearchableEnvironment searchableEnvironment = project.newSearchableNameEnvironment(this.hierarchy.workingCopies);
				this.nameLookup = searchableEnvironment.nameLookup;
				this.hierarchyResolver.resolve(openables, null, monitor);
			} catch (JavaModelException e) {
				// project doesn't exit: ignore
			}
		}
	} finally {
		if (monitor != null) monitor.done();
	}
}
 
Example #4
Source File: SelectionEngine.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * The SelectionEngine is responsible for computing the selected object.
 *
 * It requires a searchable name environment, which supports some
 * specific search APIs, and a requestor to feed back the results to a UI.
 *
 *  @param nameEnvironment org.eclipse.jdt.internal.core.SearchableEnvironment
 *      used to resolve type/package references and search for types/packages
 *      based on partial names.
 *
 *  @param requestor org.eclipse.jdt.internal.codeassist.ISelectionRequestor
 *      since the engine might produce answers of various forms, the engine
 *      is associated with a requestor able to accept all possible completions.
 *
 *  @param settings java.util.Map
 *		set of options used to configure the code assist engine.
 */
public SelectionEngine(
	SearchableEnvironment nameEnvironment,
	ISelectionRequestor requestor,
	Map settings,
	WorkingCopyOwner owner) {

	super(settings);

	this.requestor = requestor;
	this.nameEnvironment = nameEnvironment;

	ProblemReporter problemReporter =
		new ProblemReporter(
			DefaultErrorHandlingPolicies.proceedWithAllProblems(),
			this.compilerOptions,
			new DefaultProblemFactory(Locale.getDefault())) {

		public CategorizedProblem createProblem(
			char[] fileName,
			int problemId,
			String[] problemArguments,
			String[] messageArguments,
			int severity,
			int problemStartPosition,
			int problemEndPosition,
			int lineNumber,
			int columnNumber) {
			CategorizedProblem pb =  super.createProblem(
				fileName,
				problemId,
				problemArguments,
				messageArguments,
				severity,
				problemStartPosition,
				problemEndPosition,
				lineNumber,
				columnNumber);
				if(SelectionEngine.this.problem == null && pb.isError() && (pb.getID() & IProblem.Syntax) == 0) {
					SelectionEngine.this.problem = pb;
				}

				return pb;
		}
	};
	this.lookupEnvironment =
		new LookupEnvironment(this, this.compilerOptions, problemReporter, nameEnvironment);
	this.parser = new SelectionParser(problemReporter);
	this.owner = owner;
}
 
Example #5
Source File: MatchLocator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Create a new parser for the given project, as well as a lookup environment.
 */
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();
		this.unitScope = null; // don't leak a reference to the cleaned-up name environment
	}

	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.lookupEnvironment.mayTolerateMissingType = true;
	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];

	this.lookupEnvironment.addResolutionListener(this.patternLocator);
}
 
Example #6
Source File: EvaluationContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the selection at the specified positions of the given code snippet.
 * (Note that this evaluation context's VM doesn't need to be running.)
 *  @param codeSnippet char[]
 * 		The code snipper source
 *
 *  @param selectionSourceStart int
 *
 *  @param selectionSourceEnd int
 *
 *  @param environment org.eclipse.jdt.internal.core.SearchableEnvironment
 *      used to resolve type/package references and search for types/packages
 *      based on partial names.
 *
 *  @param requestor org.eclipse.jdt.internal.codeassist.ISelectionRequestor
 *      since the engine might produce answers of various forms, the engine
 *      is associated with a requestor able to accept all possible selections.
 *
 *  @param options java.util.Map
 *		set of options used to configure the code assist engine.
 */
public void select(
	char[] codeSnippet,
	int selectionSourceStart,
	int selectionSourceEnd,
	SearchableEnvironment environment,
	ISelectionRequestor requestor,
	Map options,
	WorkingCopyOwner owner) {

	final char[] className = "CodeSnippetSelection".toCharArray(); //$NON-NLS-1$
	final long complianceVersion = CompilerOptions.versionToJdkLevel(options.get(JavaCore.COMPILER_COMPLIANCE));
	final CodeSnippetToCuMapper mapper = new CodeSnippetToCuMapper(
		codeSnippet,
		this.packageName,
		this.imports,
		className,
		this.installedVars == null ? null : this.installedVars.className,
		this.localVariableNames,
		this.localVariableTypeNames,
		this.localVariableModifiers,
		this.declaringTypeName,
		this.lineSeparator,
		complianceVersion
	);
	ICompilationUnit sourceUnit = new ICompilationUnit() {
		public char[] getFileName() {
			return CharOperation.concat(className, Util.defaultJavaExtension().toCharArray());
		}
		public char[] getContents() {
			return mapper.getCUSource(EvaluationContext.this.lineSeparator);
		}
		public char[] getMainTypeName() {
			return className;
		}
		public char[][] getPackageName() {
			return null;
		}
		public boolean ignoreOptionalProblems() {
			return false;
		}
	};
	SelectionEngine engine = new SelectionEngine(environment, mapper.getSelectionRequestor(requestor), options, owner);
	engine.select(sourceUnit, mapper.startPosOffset + selectionSourceStart, mapper.startPosOffset + selectionSourceEnd);
}
 
Example #7
Source File: PackageBinding.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public IAnnotationBinding[] getAnnotations() {
	try {
		INameEnvironment nameEnvironment = this.binding.environment.nameEnvironment;
		if (!(nameEnvironment instanceof SearchableEnvironment))
			return AnnotationBinding.NoAnnotations;
		NameLookup nameLookup = ((SearchableEnvironment) nameEnvironment).nameLookup;
		if (nameLookup == null)
			return AnnotationBinding.NoAnnotations;
		final String pkgName = getName();
		IPackageFragment[] pkgs = nameLookup.findPackageFragments(pkgName, false/*exact match*/);
		if (pkgs == null)
			return AnnotationBinding.NoAnnotations;

		for (int i = 0, len = pkgs.length; i < len; i++) {
			int fragType = pkgs[i].getKind();
			switch(fragType) {
				case IPackageFragmentRoot.K_SOURCE:
					String unitName = "package-info.java"; //$NON-NLS-1$
					ICompilationUnit unit = pkgs[i].getCompilationUnit(unitName);
					if (unit != null && unit.exists()) {
						ASTParser p = ASTParser.newParser(AST.JLS3_INTERNAL);
						p.setSource(unit);
						p.setResolveBindings(true);
						p.setUnitName(unitName);
						p.setFocalPosition(0);
						p.setKind(ASTParser.K_COMPILATION_UNIT);
						CompilationUnit domUnit = (CompilationUnit) p.createAST(null);
						PackageDeclaration pkgDecl = domUnit.getPackage();
						if (pkgDecl != null) {
							List annos = pkgDecl.annotations();
							if (annos == null || annos.isEmpty())
								return AnnotationBinding.NoAnnotations;
							IAnnotationBinding[] result = new IAnnotationBinding[annos.size()];
							int index=0;
	 						for (Iterator it = annos.iterator(); it.hasNext(); index++) {
								result[index] = ((Annotation) it.next()).resolveAnnotationBinding();
								// not resolving bindings
								if (result[index] == null)
									return AnnotationBinding.NoAnnotations;
							}
							return result;
						}
					}
					break;
				case IPackageFragmentRoot.K_BINARY:
					NameEnvironmentAnswer answer =
						nameEnvironment.findType(TypeConstants.PACKAGE_INFO_NAME, this.binding.compoundName);
					if (answer != null && answer.isBinaryType()) {
						IBinaryType type = answer.getBinaryType();
						char[][][] missingTypeNames = type.getMissingTypeNames();
						IBinaryAnnotation[] binaryAnnotations = type.getAnnotations();
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] binaryInstances =
							BinaryTypeBinding.createAnnotations(binaryAnnotations, this.binding.environment, missingTypeNames);
						org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding[] allInstances =
							org.eclipse.jdt.internal.compiler.lookup.AnnotationBinding.addStandardAnnotations(binaryInstances, type.getTagBits(), this.binding.environment);
						int total = allInstances.length;
						IAnnotationBinding[] domInstances = new AnnotationBinding[total];
						for (int a = 0; a < total; a++) {
							final IAnnotationBinding annotationInstance = this.resolver.getAnnotationInstance(allInstances[a]);
							if (annotationInstance == null) {// not resolving binding
								return AnnotationBinding.NoAnnotations;
							}
							domInstances[a] = annotationInstance;
						}
						return domInstances;
					}
			}
		}
	} catch(JavaModelException e) {
		return AnnotationBinding.NoAnnotations;
	}
	return AnnotationBinding.NoAnnotations;
}