org.eclipse.jdt.core.ITypeRoot Java Examples

The following examples show how to use org.eclipse.jdt.core.ITypeRoot. 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: InternalCompletionContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void setExtendedData(
		ITypeRoot typeRoot,
		CompilationUnitDeclaration compilationUnitDeclaration,
		LookupEnvironment lookupEnvironment,
		Scope scope,
		ASTNode astNode,
		ASTNode astNodeParent,
		WorkingCopyOwner owner,
		CompletionParser parser) {
	this.isExtended = true;
	this.extendedContext =
		new InternalExtendedCompletionContext(
				this,
				typeRoot,
				compilationUnitDeclaration,
				lookupEnvironment,
				scope,
				astNode,
				astNodeParent,
				owner,
				parser);
}
 
Example #2
Source File: InternalExtendedCompletionContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public InternalExtendedCompletionContext(
		InternalCompletionContext completionContext,
		ITypeRoot typeRoot,
		CompilationUnitDeclaration compilationUnitDeclaration,
		LookupEnvironment lookupEnvironment,
		Scope assistScope,
		ASTNode assistNode,
		ASTNode assistNodeParent,
		WorkingCopyOwner owner,
		CompletionParser parser) {
	this.completionContext = completionContext;
	this.typeRoot = typeRoot;
	this.compilationUnitDeclaration = compilationUnitDeclaration;
	this.lookupEnvironment = lookupEnvironment;
	this.assistScope = assistScope;
	this.assistNode = assistNode;
	this.assistNodeParent = assistNodeParent;
	this.owner = owner;
	this.parser = parser;
}
 
Example #3
Source File: DocumentHighlightHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private DocumentHighlight convertToHighlight(ITypeRoot unit, OccurrenceLocation occurrence)
		throws JavaModelException {
	DocumentHighlight h = new DocumentHighlight();
	if ((occurrence.getFlags() | IOccurrencesFinder.F_WRITE_OCCURRENCE) == IOccurrencesFinder.F_WRITE_OCCURRENCE) {
		h.setKind(DocumentHighlightKind.Write);
	} else if ((occurrence.getFlags()
			| IOccurrencesFinder.F_READ_OCCURRENCE) == IOccurrencesFinder.F_READ_OCCURRENCE) {
		h.setKind(DocumentHighlightKind.Read);
	}
	int[] loc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset());
	int[] endLoc = JsonRpcHelpers.toLine(unit.getBuffer(), occurrence.getOffset() + occurrence.getLength());

	h.setRange(new Range(
			new Position(loc[0], loc[1]),
			new Position(endLoc[0],endLoc[1])
			));
	return h;
}
 
Example #4
Source File: ASTProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Update internal structures after reconcile.
 * 
 * @param ast the compilation unit AST or <code>null</code> if the working copy was consistent
 *            or reconciliation has been cancelled
 * @param javaElement the Java element for which the AST was built
 * @param progressMonitor the progress monitor
 * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit,
 *      boolean, IProgressMonitor)
 */
void reconciled(CompilationUnit ast, ITypeRoot javaElement, IProgressMonitor progressMonitor) {
	if (DEBUG)
		System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "reconciled: " + toString(javaElement) + ", AST: " + toString(ast)); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

	synchronized (fReconcileLock) {
		fIsReconciling= false;
		if (javaElement == null || !javaElement.equals(fReconcilingJavaElement)) {

			if (DEBUG)
				System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "  ignoring AST of out-dated editor"); //$NON-NLS-1$ //$NON-NLS-2$

			// Signal - threads might wait for wrong element
			synchronized (fWaitLock) {
				fWaitLock.notifyAll();
			}

			return;
		}
		cache(ast, javaElement);
	}
}
 
Example #5
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected void installOccurrencesFinder(boolean forceUpdate) {
	fMarkOccurrenceAnnotations= true;

	fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
		public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
			updateOccurrenceAnnotations(selection, astRoot);
		}
	};
	SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
	if (forceUpdate && getSelectionProvider() != null) {
		fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
		ITypeRoot inputJavaElement= getInputJavaElement();
		if (inputJavaElement != null)
			updateOccurrenceAnnotations((ITextSelection)fForcedMarkOccurrencesSelection, SharedASTProvider.getAST(inputJavaElement, SharedASTProvider.WAIT_NO, getProgressMonitor()));
	}

	if (fOccurrencesFinderJobCanceler == null) {
		fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
		fOccurrencesFinderJobCanceler.install();
	}
}
 
Example #6
Source File: SelectionListenerWithASTManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected final IStatus calculateASTandInform(ITypeRoot input, ITextSelection selection, IProgressMonitor monitor) {
	if (monitor.isCanceled()) {
		return Status.CANCEL_STATUS;
	}
	// create AST
	try {
		CompilationUnit astRoot= SharedASTProvider.getAST(input, SharedASTProvider.WAIT_ACTIVE_ONLY, monitor);

		if (astRoot != null && !monitor.isCanceled()) {
			Object[] listeners;
			synchronized (PartListenerGroup.this) {
				listeners= fAstListeners.getListeners();
			}
			for (int i= 0; i < listeners.length; i++) {
				((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection, astRoot);
				if (monitor.isCanceled()) {
					return Status.CANCEL_STATUS;
				}
			}
			return Status.OK_STATUS;
		}
	} catch (OperationCanceledException e) {
		// thrown when canceling the AST creation
	}
	return Status.CANCEL_STATUS;
}
 
Example #7
Source File: NLSStringHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
	if (!(getEditor() instanceof JavaEditor))
		return null;

	ITypeRoot je= getEditorInputJavaElement();
	if (je == null)
		return null;

	// Never wait for an AST in UI thread.
	CompilationUnit ast= SharedASTProvider.getAST(je, SharedASTProvider.WAIT_NO, null);
	if (ast == null)
		return null;

	ASTNode node= NodeFinder.perform(ast, offset, 1);
	if (node instanceof StringLiteral) {
		StringLiteral stringLiteral= (StringLiteral)node;
		return new Region(stringLiteral.getStartPosition(), stringLiteral.getLength());
	} else if (node instanceof SimpleName) {
		SimpleName simpleName= (SimpleName)node;
		return new Region(simpleName.getStartPosition(), simpleName.getLength());
	}

	return null;
}
 
Example #8
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the constant value for the given field.
 *
 * @param field the field
 * @param editorInputElement the editor input element
 * @param hoverRegion the hover region in the editor
 * @return the constant value for the given field or <code>null</code> if none
 * @since 3.4
 */
private static String getConstantValue(IField field, ITypeRoot editorInputElement, IRegion hoverRegion) {
	if (!isStaticFinal(field))
		return null;

	ASTNode node= getHoveredASTNode(editorInputElement, hoverRegion);
	if (node == null)
		return null;

	Object constantValue= getVariableBindingConstValue(node, field);
	if (constantValue == null)
		return null;

	if (constantValue instanceof String) {
		return ASTNodes.getEscapedStringLiteral((String) constantValue);
	} else {
		return getHexConstantValue(constantValue);
	}
}
 
Example #9
Source File: JavaLaunchingCodeMiningProvider.java    From jdt-codemining with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer,
		IProgressMonitor monitor) {
	return CompletableFuture.supplyAsync(() -> {
		monitor.isCanceled();
		ITextEditor textEditor = super.getAdapter(ITextEditor.class);
		ITypeRoot unit = EditorUtility.getEditorInputJavaElement(textEditor, true);
		if (unit == null) {
			return Collections.emptyList();
		}
		try {
			IJavaElement[] elements = unit.getChildren();
			List<ICodeMining> minings = new ArrayList<>(elements.length);
			collectMinings(unit, textEditor, unit.getChildren(), minings, viewer, monitor);
			monitor.isCanceled();
			return minings;
		} catch (JavaModelException e) {
			// Should never occur
		}
		return Collections.emptyList();
	});
}
 
Example #10
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a reader for an package fragment's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the package fragment does not contain a Javadoc comment or if no source is available.
 * @param fragment The package fragment to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the package fragment's javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IPackageFragment fragment) throws JavaModelException {
	IPackageFragmentRoot root= (IPackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

	//1==> Handle the case when the documentation is present in package-info.java or package-info.class file
	boolean isBinary= root.getKind() == IPackageFragmentRoot.K_BINARY;
	ITypeRoot packageInfo;
	if (isBinary) {
		packageInfo= fragment.getClassFile(PACKAGE_INFO_CLASS);
	} else {
		packageInfo= fragment.getCompilationUnit(PACKAGE_INFO_JAVA);
	}
	if (packageInfo != null && packageInfo.exists()) {
		String source = packageInfo.getSource();
		//the source can be null for some of the class files
		if (source != null) {
			Javadoc javadocNode = getPackageJavadocNode(fragment, source);
			if (javadocNode != null) {
				int start = javadocNode.getStartPosition();
				int length = javadocNode.getLength();
				return new JavaDocCommentReader(source, start, start + length - 1);
			}
		}
	}
	return null;
}
 
Example #11
Source File: InlineAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(ITextSelection selection) {
	if (!ActionUtil.isEditable(fEditor))
		return;

	ITypeRoot typeRoot= SelectionConverter.getInput(fEditor);
	if (typeRoot == null)
		return;

	CompilationUnit node= RefactoringASTParser.parseWithASTProvider(typeRoot, true, null);

	if (typeRoot instanceof ICompilationUnit) {
		ICompilationUnit cu= (ICompilationUnit) typeRoot;
		if (fInlineTemp.isEnabled() && fInlineTemp.tryInlineTemp(cu, node, selection, getShell()))
			return;

		if (fInlineConstant.isEnabled() && fInlineConstant.tryInlineConstant(cu, node, selection, getShell()))
			return;
	}
	//InlineMethod is last (also tries enclosing element):
	if (fInlineMethod.isEnabled() && fInlineMethod.tryInlineMethod(typeRoot, node, selection, getShell()))
		return;

	MessageDialog.openInformation(getShell(), RefactoringMessages.InlineAction_dialog_title, RefactoringMessages.InlineAction_select);
}
 
Example #12
Source File: OpenAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Object getPackageFragmentObjectToOpen(IPackageFragment packageFragment) throws JavaModelException {
	ITypeRoot typeRoot= null;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY)
		typeRoot= (packageFragment).getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	else
		typeRoot= (packageFragment).getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	if (typeRoot.exists())
		return typeRoot;
	
	Object[] nonJavaResources= (packageFragment).getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return file;
			}
		}
	}
	return packageFragment;
}
 
Example #13
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getInfoText(IJavaElement element, ITypeRoot editorInputElement, IRegion hoverRegion, boolean allowImage) {
		long flags= getHeaderFlags(element);
		StringBuffer label= new StringBuffer(JavaElementLinks.getElementLabel(element, flags));
		
		if (element.getElementType() == IJavaElement.FIELD) {
			String constantValue= getConstantValue((IField) element, editorInputElement, hoverRegion);
			if (constantValue != null) {
				constantValue= HTMLPrinter.convertToHTMLContentWithWhitespace(constantValue);
				IJavaProject javaProject= element.getJavaProject();
				label.append(getFormattedAssignmentOperator(javaProject));
				label.append(constantValue);
			}
		}

//		if (element.getElementType() == IJavaElement.METHOD) {
//			IMethod method= (IMethod)element;
//			//TODO: add default value for annotation type members, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=249016
//		}

		return getImageAndLabel(element, allowImage, label.toString());
	}
 
Example #14
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static String getExpressionBaseName(Expression expr) {
	IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
	if (argBinding instanceof IVariableBinding) {
		IJavaProject project= null;
		ASTNode root= expr.getRoot();
		if (root instanceof CompilationUnit) {
			ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
			if (typeRoot != null)
				project= typeRoot.getJavaProject();
		}
		return StubUtility.getBaseName((IVariableBinding)argBinding, project);
	}
	if (expr instanceof SimpleName)
		return ((SimpleName) expr).getIdentifier();
	return null;
}
 
Example #15
Source File: JavaElementCodeMiningProvider.java    From jdt-codemining with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void initRevisionSupport(ITextViewer viewer, ITypeRoot unit) {
	if (fRevisionInfoSupport != null) {
		return;
	}
	IResource resource = unit.getResource();
	if (resource == null) {
		return;
	}
	if (fRevisionInfoSupport == null) {
		RevisionInformation info = RevisionInformationProviderManager.getInstance().getRevisionInformation(resource,
				viewer, super.getAdapter(ITextEditor.class));
		if (info != null) {
			fRevisionInfoSupport = new RevisionInformationSupport();
			fRevisionInfoSupport.install((ISourceViewer) viewer, info);
		}
	}
}
 
Example #16
Source File: LambdaExpression.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public boolean equals(Object o) {
	if (this == o)
		return true;
	/* I see cases where equal lambdas are dismissed as unequal on account of working copy owner.
	   This results in spurious failures. See JavaSearchBugs8Tests.testBug400905_0021()
	   For now exclude the working copy owner and compare
	*/
	if (o instanceof LambdaExpression) {
		LambdaExpression that = (LambdaExpression) o;
		if (this.sourceStart != that.sourceStart)
			return false;
		ITypeRoot thisTR = this.getTypeRoot();
		ITypeRoot thatTR = that.getTypeRoot();
		return thisTR.getElementName().equals(thatTR.getElementName()) && thisTR.getParent().equals(thatTR.getParent());
	}
	return false;
}
 
Example #17
Source File: JUnitCodeMiningProvider.java    From jdt-codemining with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public CompletableFuture<List<? extends ICodeMining>> provideCodeMinings(ITextViewer viewer,
		IProgressMonitor monitor) {
	this.viewer = viewer;
	return CompletableFuture.supplyAsync(() -> {
		monitor.isCanceled();
		ITextEditor textEditor = super.getAdapter(ITextEditor.class);
		ITypeRoot unit = EditorUtility.getEditorInputJavaElement(textEditor, true);
		if (unit == null) {
			return null;
		}
		try {
			IJavaElement[] elements = unit.getChildren();
			List<ICodeMining> minings = new ArrayList<>(elements.length);
			collectCodeMinings(unit, elements, minings, viewer, monitor);
			monitor.isCanceled();
			return minings;
		} catch (JavaModelException e) {
			// TODO: what should we done when there are some errors?
		}
		return null;
	});
}
 
Example #18
Source File: NodeFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * A visitor that maps a selection to a given ASTNode. The result node is
 * determined as follows:
 * <ul>
 *   <li>first the visitor tries to find a node that is covered by <code>start</code> and
 *       <code>length</code> where either <code>start</code> and <code>length</code> exactly
 *       matches the node or where the text covered before and after the node only consists
 *       of white spaces or comments.</li>
 * 	 <li>if no such node exists than the node that encloses the range defined by
 *       start and end is returned.</li>
 *   <li>if the length is zero than also nodes are considered where the node's
 *       start or end position matches <code>start</code>.</li>
 *   <li>otherwise <code>null</code> is returned.</li>
 * </ul>
 *
 * @param root the root node from which the search starts
 * @param start the start offset
 * @param length the length
 * @param source the source of the compilation unit
 *
 * @return the result node
 * @throws JavaModelException if an error occurs in the Java model
 *
 * @since		3.0
 */
public static ASTNode perform(ASTNode root, int start, int length, ITypeRoot source) throws JavaModelException {
	NodeFinder finder= new NodeFinder(start, length);
	root.accept(finder);
	ASTNode result= finder.getCoveredNode();
	if (result == null)
		return null;
	Selection selection= Selection.createFromStartLength(start, length);
	if (selection.covers(result)) {
		IBuffer buffer= source.getBuffer();
		if (buffer != null) {
			IScanner scanner= ToolFactory.createScanner(false, false, false, false);
			scanner.setSource(buffer.getText(start, length).toCharArray());
			try {
				int token= scanner.getNextToken();
				if (token != ITerminalSymbols.TokenNameEOF) {
					int tStart= scanner.getCurrentTokenStartPosition();
					if (tStart == result.getStartPosition() - start) {
						scanner.resetTo(tStart + result.getLength(), length - 1);
						token= scanner.getNextToken();
						if (token == ITerminalSymbols.TokenNameEOF)
							return result;
					}
				}
			} catch (InvalidInputException e) {
			}
		}
	}
	return finder.getCoveringNode();
}
 
Example #19
Source File: FindExceptionOccurrencesAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final void run(ITextSelection ts) {
	ITypeRoot input= getEditorInput(fEditor);
	if (!ActionUtil.isProcessable(getShell(), input))
		return;
	FindOccurrencesEngine engine= FindOccurrencesEngine.create(new ExceptionOccurrencesFinder());
	try {
		String result= engine.run(input, ts.getOffset(), ts.getLength());
		if (result != null)
			showMessage(getShell(), fEditor, result);
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
}
 
Example #20
Source File: JavaEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected void installOverrideIndicator(boolean provideAST) {
	uninstallOverrideIndicator();
	IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
	final ITypeRoot inputElement= getInputJavaElement();

	if (model == null || inputElement == null)
		return;

	fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, null);

	if (provideAST) {
		CompilationUnit ast= SharedASTProvider.getAST(inputElement, SharedASTProvider.WAIT_ACTIVE_ONLY, getProgressMonitor());
		fOverrideIndicatorManager.reconciled(ast, true, getProgressMonitor());
	}
}
 
Example #21
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private InlineMethodRefactoring(ITypeRoot typeRoot, ASTNode node, int offset, int length) {
	Assert.isNotNull(typeRoot);
	Assert.isTrue(JavaElementUtil.isSourceAvailable(typeRoot));
	Assert.isNotNull(node);
	fInitialTypeRoot= typeRoot;
	fInitialNode= node;
	fSelectionStart= offset;
	fSelectionLength= length;
}
 
Example #22
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ASTNode getInlineableMethodNode(ITypeRoot typeRoot, CompilationUnit root, int offset, int length) {
	ASTNode node= null;
	try {
		node= getInlineableMethodNode(NodeFinder.perform(root, offset, length, typeRoot), typeRoot);
	} catch(JavaModelException e) {
		// Do nothing
	}
	if (node != null)
		return node;
	return getInlineableMethodNode(NodeFinder.perform(root, offset, length), typeRoot);
}
 
Example #23
Source File: JavaSourceHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private int getNextElseOffset(Statement then, ITypeRoot editorInput) {
	int thenEnd= ASTNodes.getExclusiveEnd(then);
	try {
		TokenScanner scanner= new TokenScanner(editorInput);
		return scanner.getNextStartOffset(thenEnd, true);
	} catch (CoreException e) {
		// ignore
	}
	return -1;
}
 
Example #24
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SourceProvider resolveSourceProvider(RefactoringStatus status, ITypeRoot typeRoot, ASTNode invocation) {
	CompilationUnit root= (CompilationUnit)invocation.getRoot();
	IMethodBinding methodBinding= Invocations.resolveBinding(invocation);
	if (methodBinding == null) {
		status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
		return null;
	}
	MethodDeclaration declaration= (MethodDeclaration)root.findDeclaringNode(methodBinding);
	if (declaration != null) {
		return new SourceProvider(typeRoot, declaration);
	}
	IMethod method= (IMethod)methodBinding.getJavaElement();
	if (method != null) {
		CompilationUnit methodDeclarationAstRoot;
		ICompilationUnit methodCu= method.getCompilationUnit();
		if (methodCu != null) {
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(methodCu, true);
		} else {
			IClassFile classFile= method.getClassFile();
			if (! JavaElementUtil.isSourceAvailable(classFile)) {
				String methodLabel= JavaElementLabels.getTextLabel(method, JavaElementLabels.M_FULLY_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES);
				status.addFatalError(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_error_classFile, methodLabel));
				return null;
			}
			methodDeclarationAstRoot= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(classFile, true);
		}
		ASTNode node= methodDeclarationAstRoot.findDeclaringNode(methodBinding.getMethodDeclaration().getKey());
		if (node instanceof MethodDeclaration) {
			return new SourceProvider(methodDeclarationAstRoot.getTypeRoot(), (MethodDeclaration) node);
		}
	}
	status.addFatalError(RefactoringCoreMessages.InlineMethodRefactoring_error_noMethodDeclaration);
	return null;
}
 
Example #25
Source File: RefactoringExecutionStarter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean startInlineMethodRefactoring(final ITypeRoot typeRoot, final CompilationUnit node, final int offset, final int length, final Shell shell) {
	final InlineMethodRefactoring refactoring= InlineMethodRefactoring.create(typeRoot, node, offset, length);
	if (refactoring != null) {
		new RefactoringStarter().activate(new InlineMethodWizard(refactoring), shell, RefactoringMessages.InlineMethodAction_dialog_title, RefactoringSaveHelper.SAVE_REFACTORING);
		return true;
	}
	return false;
}
 
Example #26
Source File: ImplementationsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private int getOffset(TextDocumentPositionParams param, ITypeRoot typeRoot) {
	int offset = 0;
	try {
		IDocument document = JsonRpcHelpers.toDocument(typeRoot.getBuffer());
		offset = document.getLineOffset(param.getPosition().getLine()) + param.getPosition().getCharacter();
	} catch (JavaModelException | BadLocationException e) {
		JavaLanguageServerPlugin.logException(e.getMessage(), e);
	}
	return offset;
}
 
Example #27
Source File: DocumentHighlightHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<DocumentHighlight> computeOccurrences(ITypeRoot unit, int line, int column, IProgressMonitor monitor) {
	if (unit != null) {
		try {
			int offset = JsonRpcHelpers.toOffset(unit.getBuffer(), line, column);
			OccurrencesFinder finder = new OccurrencesFinder();
			CompilationUnit ast = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, monitor);
			if (ast != null) {
				String error = finder.initialize(ast, offset, 0);
				if (error == null){
					List<DocumentHighlight> result = new ArrayList<>();
					OccurrenceLocation[] occurrences = finder.getOccurrences();
					if (occurrences != null) {
						for (OccurrenceLocation loc : occurrences) {
							if (monitor.isCanceled()) {
								return Collections.emptyList();
							}
							result.add(convertToHighlight(unit, loc));
						}
					}
					return result;
				}
			}
		} catch (JavaModelException e) {
			JavaLanguageServerPlugin.logException("Problem with compute occurrences for" + unit.getElementName(), e);
		}
	}
	return Collections.emptyList();
}
 
Example #28
Source File: ASTProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns a string for the given Java element used for debugging.
 *
 * @param javaElement the compilation unit AST
 * @return a string used for debugging
 */
private String toString(ITypeRoot javaElement) {
	if (javaElement == null)
		return "null"; //$NON-NLS-1$
	else
		return javaElement.getElementName();

}
 
Example #29
Source File: CodeLensHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private List<Location> findImplementations(ITypeRoot root, IType type, int offset, IProgressMonitor monitor) throws CoreException {
	//java.lang.Object is a special case. We need to minimize heavy cost of I/O,
	// by avoiding opening all files from the Object hierarchy
	boolean useDefaultLocation = "java.lang.Object".equals(type.getFullyQualifiedName());
	ImplementationToLocationMapper mapper = new ImplementationToLocationMapper(preferenceManager.isClientSupportsClassFileContent(), useDefaultLocation);
	ImplementationCollector<Location> searcher = new ImplementationCollector<>(root, new Region(offset, 0), type, mapper);
	return searcher.findImplementations(monitor);
}
 
Example #30
Source File: FindLinksHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static List<? extends Location> findLinks(String linkType, TextDocumentPositionParams position, IProgressMonitor monitor) {
	if (monitor.isCanceled()) {
		return Collections.emptyList();
	}
	ITypeRoot unit = JDTUtils.resolveTypeRoot(position.getTextDocument().getUri());
	if (unit != null && !monitor.isCanceled()) {
		PreferenceManager preferenceManager = JavaLanguageServerPlugin.getInstance().getPreferencesManager();
		try {
			IJavaElement element = JDTUtils.findElementAtSelection(unit, position.getPosition().getLine(), position.getPosition().getCharacter(), preferenceManager, monitor);
			if (!monitor.isCanceled() && Objects.equals(linkType, "superImplementation")) {
				IMethod overriddenMethod = findOverriddenMethod(element, monitor);
				if (!monitor.isCanceled() && overriddenMethod != null) {
					Location location = NavigateToDefinitionHandler.computeDefinitionNavigation(overriddenMethod, element.getJavaProject());
					if (!monitor.isCanceled() && location != null) {
						String declaringTypeName = overriddenMethod.getDeclaringType().getFullyQualifiedName();
						String methodName = overriddenMethod.getElementName();
						String displayName = declaringTypeName + "." + methodName;
						return Collections.singletonList(new LinkLocation(displayName, "method", location));
					}
				}
			}
		} catch (JavaModelException e) {
			// do nothing
		}
	}

	return Collections.emptyList();
}