/** * 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); } }
@Override public void launch(IEditorPart editor, String mode) { ITypeRoot element= JavaUI.getEditorInputTypeRoot(editor.getEditorInput()); if (element != null) { launch(new Object[] { element }, mode); } }
public CompilationUnit getAST(final ITypeRoot input, IProgressMonitor progressMonitor) { if (progressMonitor != null && progressMonitor.isCanceled()) { return null; } if (!shouldCache(input)) { JavaLanguageServerPlugin.logInfo("Creating uncached AST for " + input.getPath().toString()); return createAST(input, progressMonitor); } final String identifier = input.getHandleIdentifier(); return cache.computeIfAbsent(identifier, k -> { JavaLanguageServerPlugin.logInfo("Caching AST for " + input.getPath().toString()); CompilationUnit astRoot = createAST(input, progressMonitor); astCreationCount++; return astRoot; }); }
/** * Returns the source of the given node from the location where it was parsed. * @param node the node to get the source from * @param extendedRange if set, the extended ranges of the nodes should ne used * @param removeIndent if set, the indentation is removed. * @return return the source for the given node or null if accessing the source failed. */ public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) { ASTNode root= node.getRoot(); if (root instanceof CompilationUnit) { CompilationUnit astRoot= (CompilationUnit) root; ITypeRoot typeRoot= astRoot.getTypeRoot(); try { if (typeRoot != null && typeRoot.getBuffer() != null) { IBuffer buffer= typeRoot.getBuffer(); int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); String str= buffer.getText(offset, length); if (removeIndent) { IJavaProject project= typeRoot.getJavaProject(); int indent= getIndentUsed(buffer, node.getStartPosition(), project); str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator()); } return str; } } catch (JavaModelException e) { // ignore } } return null; }
/** * 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; }
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; }
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; }
private Location computeDefinitionNavigation(ITypeRoot unit, int line, int column, IProgressMonitor monitor) { try { IJavaElement element = JDTUtils.findElementAtSelection(unit, line, column, this.preferenceManager, monitor); if (element == null) { return null; } ICompilationUnit compilationUnit = (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); IClassFile cf = (IClassFile) element.getAncestor(IJavaElement.CLASS_FILE); if (compilationUnit != null || (cf != null && cf.getSourceRange() != null) ) { return JDTUtils.toLocation(element); } if (element instanceof IMember && ((IMember) element).getClassFile() != null) { return JDTUtils.toLocation(((IMember) element).getClassFile()); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Problem computing definition for" + unit.getElementName(), e); } return null; }
public static Integer getLineNumber(IMember member) throws JavaModelException { ITypeRoot typeRoot = member.getTypeRoot(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { return null; } Document document = new Document(buffer.getContents()); int offset = 0; if (SourceRange.isAvailable(member.getNameRange())) { offset = member.getNameRange().getOffset(); } else if (SourceRange.isAvailable(member.getSourceRange())) { offset = member.getSourceRange().getOffset(); } try { return document.getLineOfOffset(offset); } catch (BadLocationException e) { return null; } }
@Override public void runAnalysis(IAnalysisReporter reporter, IAnalysisInput input, ITypeRoot compUnit, CompilationUnit rootNode) { this.savedReporter = reporter; this.savedInput = input; // Save the compilation units to analyze; analyze them later this.compUnits.add(compUnit); super.runAnalysis(reporter, input, compUnit, rootNode); // Must initialize the path on the facade // In case, we don't run anything! // XXX. Also, need root class...(less crucial) if (projectPath == null) { projectPath = compUnit.getJavaProject().getResource().getLocation().toOSString(); } }
public void run(final String analysis_to_run) { Crystal crystal = AbstractCrystalPlugin.getCrystalInstance(); crystal.runAnalyses(new IRunCrystalCommand() { @Override public IAnalysisReporter reporter() { return reporter; } @Override public Collection<? extends ITypeRoot> compilationUnits() { return compilationUnits; } @Override public Set<String> analyses() { Set<String> hashSet = new HashSet<String>(); hashSet.add(analysis_to_run); return hashSet; } }, null); }
/** * Determines the Java element the given {@link ITextSelection} points to (i.e. the Java element the cursor is * positioned to). * * @param textSelection * the {@link ITextSelection} to be checked * @return the {@link IJavaElement} the cursor is positioned to or {@link Optional#empty()}, if there is no active * editor, or the active editor is not a Java editor. */ public static Optional<IJavaElement> getSelectedJavaElement(final ITextSelection textSelection) { final Optional<ITypeRoot> javaRootElement = getJavaRootElementOfActiveEditor(); if (javaRootElement.isPresent()) { try { final IJavaElement selectedJavaElement = ((ICompilationUnit) javaRootElement.get()).getElementAt(textSelection.getOffset()); if (selectedJavaElement != null) { return Optional.of(selectedJavaElement); } } catch (final JavaModelException e) { e.printStackTrace(); } } return Optional.empty(); }
/** * Creates a TokenScanner * * @param typeRoot The type root to scan on * @throws CoreException thrown if the buffer cannot be accessed */ public TokenScanner(ITypeRoot typeRoot) throws CoreException { IJavaProject project = typeRoot.getJavaProject(); IBuffer buffer = typeRoot.getBuffer(); if (buffer == null) { throw new CoreException( createError(DOCUMENT_ERROR, "Element has no source", null)); // $NON-NLS-1$ } String sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true); String complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true); fScanner = ToolFactory.createScanner( true, false, true, sourceLevel, complianceLevel); // line info required fScanner.setSource(buffer.getCharacters()); fDocument = null; // use scanner for line information fEndPosition = fScanner.getSource().length - 1; }
/** * Creates a new inline method refactoring * * @param unit the compilation unit or class file * @param node the compilation unit node * @param selectionStart start * @param selectionLength length * @return returns the refactoring */ public static InlineMethodRefactoring create( ITypeRoot unit, CompilationUnit node, int selectionStart, int selectionLength) { ASTNode target = RefactoringAvailabilityTester.getInlineableMethodNode( unit, node, selectionStart, selectionLength); if (target == null) return null; if (target.getNodeType() == ASTNode.METHOD_DECLARATION) { return new InlineMethodRefactoring( unit, (MethodDeclaration) target, selectionStart, selectionLength); } else { ICompilationUnit cu = (ICompilationUnit) unit; if (target.getNodeType() == ASTNode.METHOD_INVOCATION) { return new InlineMethodRefactoring( cu, (MethodInvocation) target, selectionStart, selectionLength); } else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) { return new InlineMethodRefactoring( cu, (SuperMethodInvocation) target, selectionStart, selectionLength); } else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) { return new InlineMethodRefactoring( cu, (ConstructorInvocation) target, selectionStart, selectionLength); } } return null; }
public CompilationUnit parse( ITypeRoot typeRoot, WorkingCopyOwner owner, boolean resolveBindings, boolean statementsRecovery, boolean bindingsRecovery, IProgressMonitor pm) { fParser.setResolveBindings(resolveBindings); fParser.setStatementsRecovery(statementsRecovery); fParser.setBindingsRecovery(bindingsRecovery); fParser.setSource(typeRoot); if (owner != null) fParser.setWorkingCopyOwner(owner); fParser.setCompilerOptions(getCompilerOptions(typeRoot)); CompilationUnit result = (CompilationUnit) fParser.createAST(pm); return result; }
/** * Tries to get the shared AST from the ASTProvider. If the shared AST is not available, parses * the type root with a RefactoringASTParser that uses settings similar to the ASTProvider. * * @param typeRoot the type root * @param resolveBindings whether bindings are to be resolved if a new AST needs to be created * @param pm an {@link IProgressMonitor}, or <code>null</code> * @return the parsed CompilationUnit */ public static CompilationUnit parseWithASTProvider( ITypeRoot typeRoot, boolean resolveBindings, IProgressMonitor pm) { CompilationUnit cuNode = SharedASTProvider.getAST(typeRoot, SharedASTProvider.WAIT_ACTIVE_ONLY, pm); if (cuNode != null) { return cuNode; } else { return new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL) .parse( typeRoot, null, resolveBindings, ASTProvider.SHARED_AST_STATEMENT_RECOVERY, ASTProvider.SHARED_BINDING_RECOVERY, pm); } }
/** * 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); // } }
private String getInfoText( IJavaElement element, ITypeRoot editorInputElement, 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); 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()); }
/** * 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 String getConstantValue(IField field, ITypeRoot editorInputElement) { // 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); // } return null; }
private List<AutocompleteResponse.Completion> Autocomplete(ITypeRoot cu, int cursorPosition) throws JavaModelException { final List<AutocompleteResponse.Completion> proposals = new ArrayList<AutocompleteResponse.Completion>(); cu.codeComplete(cursorPosition, new CompletionRequestor() { @Override public void accept(CompletionProposal proposal) { try { System.out.println(proposal.toString()); proposals.add(translateToCompletion(proposal)); } catch(Exception e) { e.printStackTrace(); } } }); return proposals; }
public String ProcessOpenTypeRequest(String fileName) throws Exception { File file = new File(fileName); IFile[] files = WorkspaceRoot.findFilesForLocationURI(file.toURI(), IResource.FILE); if (files.length > 1) throw new Exception("Ambigous parse request for file " + fileName); else if (files.length == 0) throw new Exception("File not found: " + fileName); IJavaElement javaFile = JavaCore.create(files[0]); if (javaFile instanceof ITypeRoot) { //int hashCode = javaFile.hashCode(); String handle = javaFile.getHandleIdentifier(); ActiveTypeRoots.put(handle, (ITypeRoot)javaFile); return handle; } return null; }
private Expression getAssignedValue(ParameterObjectFactory pof, String parameterName, IJavaProject javaProject, RefactoringStatus status, ASTRewrite rewrite, ParameterInfo pi, boolean useSuper, ITypeBinding typeBinding, Expression qualifier, ASTNode replaceNode, ITypeRoot typeRoot) { AST ast= rewrite.getAST(); boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject); Expression assignedValue= handleSimpleNameAssignment(replaceNode, pof, parameterName, ast, javaProject, useSuper); if (assignedValue == null) { NullLiteral marker= qualifier == null ? null : ast.newNullLiteral(); Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, useSuper, marker); assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding, is50OrHigher); boolean markerReplaced= replaceMarker(rewrite, qualifier, assignedValue, marker); if (markerReplaced) { switch (qualifier.getNodeType()) { case ASTNode.METHOD_INVOCATION: case ASTNode.CLASS_INSTANCE_CREATION: case ASTNode.SUPER_METHOD_INVOCATION: case ASTNode.PARENTHESIZED_EXPRESSION: status.addWarning(RefactoringCoreMessages.ExtractClassRefactoring_warning_semantic_change, JavaStatusContext.create(typeRoot, replaceNode)); break; } } } return assignedValue; }
/** * Link selection to active editor. * @param editor The activated editor */ protected void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) { return; } if (fInputElements == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); if (elem instanceof ITypeRoot) { IType type= ((ITypeRoot) elem).findPrimaryType(); if (type != null) { internalSelectType(type, true); if (getCurrentViewer().getSelection().isEmpty()) { updateMethodViewer(null); } else { updateMethodViewer(type); } } } }
void activeJavaEditorChanged(IWorkbenchPart editor) { ITypeRoot javaElement= null; if (editor instanceof JavaEditor) javaElement= ((JavaEditor)editor).getInputJavaElement(); synchronized (this) { fActiveEditor= editor; fActiveJavaElement= javaElement; cache(null, javaElement); } if (DEBUG) System.out.println(getThreadName() + " - " + DEBUG_PREFIX + "active editor is: " + toString(javaElement)); //$NON-NLS-1$ //$NON-NLS-2$ synchronized (fReconcileLock) { if (fIsReconciling && (fReconcilingJavaElement == null || !fReconcilingJavaElement.equals(javaElement))) { fIsReconciling= false; fReconcilingJavaElement= null; } else if (javaElement == null) { fIsReconciling= false; fReconcilingJavaElement= null; } } }
/** * Creates a new inline method refactoring * @param unit the compilation unit or class file * @param node the compilation unit node * @param selectionStart start * @param selectionLength length * @return returns the refactoring */ public static InlineMethodRefactoring create(ITypeRoot unit, CompilationUnit node, int selectionStart, int selectionLength) { ASTNode target= RefactoringAvailabilityTester.getInlineableMethodNode(unit, node, selectionStart, selectionLength); if (target == null) return null; if (target.getNodeType() == ASTNode.METHOD_DECLARATION) { return new InlineMethodRefactoring(unit, (MethodDeclaration)target, selectionStart, selectionLength); } else { ICompilationUnit cu= (ICompilationUnit) unit; if (target.getNodeType() == ASTNode.METHOD_INVOCATION) { return new InlineMethodRefactoring(cu, (MethodInvocation)target, selectionStart, selectionLength); } else if (target.getNodeType() == ASTNode.SUPER_METHOD_INVOCATION) { return new InlineMethodRefactoring(cu, (SuperMethodInvocation)target, selectionStart, selectionLength); } else if (target.getNodeType() == ASTNode.CONSTRUCTOR_INVOCATION) { return new InlineMethodRefactoring(cu, (ConstructorInvocation)target, selectionStart, selectionLength); } } return null; }
@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); }
private void addRefactorSubmenu(IMenuManager menu) { MenuManager refactorSubmenu= new MenuManager(ActionMessages.RefactorMenu_label, MENU_ID); refactorSubmenu.setActionDefinitionId(QUICK_MENU_ID); if (fEditor != null) { final ITypeRoot element= getEditorInput(); if (element != null && ActionUtil.isOnBuildPath(element)) { refactorSubmenu.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { refactorMenuShown(manager); } }); refactorSubmenu.add(fNoActionAvailable); menu.appendToGroup(fGroupName, refactorSubmenu); } } else { ISelection selection= fSelectionProvider.getSelection(); for (Iterator<SelectionDispatchAction> iter= fActions.iterator(); iter.hasNext(); ) { iter.next().update(selection); } if (fillRefactorMenu(refactorSubmenu) > 0) menu.appendToGroup(fGroupName, refactorSubmenu); } }
@Override protected Object getCurrentInput() { try { ITypeRoot input= SelectionConverter.getInput(getJavaEditor()); if (input == null) return null; ITextSelection selection; if (fEditorSelection instanceof ITextSelection) { selection= (ITextSelection) fEditorSelection; } else { selection= (ITextSelection) getJavaEditor().getSelectionProvider().getSelection(); } return getInput(SelectionConverter.getElementAtOffset(input, selection)); } catch (JavaModelException e) { return null; } }
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; }
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()); }
/** * Compute the textual representation of a 'static' 'final' field's constant initializer value. * * @param activePart the part that triggered the computation, or <code>null</code> * @param selection the selection that references the field, or <code>null</code> * @param resolvedField the filed whose constant value will be computed * @param monitor the progress monitor * * @return the textual representation of the constant, or <code>null</code> if the * field is not a constant field, the initializer value could not be computed, or * the progress monitor was cancelled * @since 3.4 */ private String computeFieldConstant(IWorkbenchPart activePart, ISelection selection, IField resolvedField, IProgressMonitor monitor) { if (!isStaticFinal(resolvedField)) return null; Object constantValue; IJavaProject preferenceProject; if (selection instanceof ITextSelection && activePart instanceof JavaEditor) { IEditorPart editor= (IEditorPart) activePart; ITypeRoot activeType= JavaUI.getEditorInputTypeRoot(editor.getEditorInput()); preferenceProject= activeType.getJavaProject(); constantValue= getConstantValueFromActiveEditor(activeType, resolvedField, (ITextSelection) selection, monitor); if (constantValue == null) // fall back - e.g. when selection is inside Javadoc of the element constantValue= computeFieldConstantFromTypeAST(resolvedField, monitor); } else { constantValue= computeFieldConstantFromTypeAST(resolvedField, monitor); preferenceProject= resolvedField.getJavaProject(); } if (constantValue != null) return getFormattedAssignmentOperator(preferenceProject) + formatCompilerConstantValue(constantValue); return null; }
private void collectCodeLenses(ITypeRoot unit, IJavaElement[] elements, List<ICodeLens> lenses, IProgressMonitor monitor) throws JavaModelException { for (IJavaElement element : elements) { if (monitor.isCanceled()) { return; } if (element.getElementType() == IJavaElement.TYPE) { collectCodeLenses(unit, ((IType) element).getChildren(), lenses, monitor); } else if (element.getElementType() != IJavaElement.METHOD || JDTUtils.isHiddenGeneratedElement(element)) { continue; } // if (preferenceManager.getPreferences().isReferencesCodeLensEnabled()) { ICodeLens lens = getCodeLens(REFERENCES_TYPE, element, unit); lenses.add(lens); // } // if (preferenceManager.getPreferences().isImplementationsCodeLensEnabled() && // element instanceof IType) { if (element instanceof IType) { IType type = (IType) element; if (type.isInterface() || Flags.isAbstract(type.getFlags())) { lens = getCodeLens(IMPLEMENTATION_TYPE, element, unit); lenses.add(lens); } } } }
private ICodeLens getCodeLens(String type, IJavaElement element, ITypeRoot unit) throws JavaModelException { ISourceRange r = ((ISourceReference) element).getNameRange(); final Range range = JDTUtils.toRange(unit, r.getOffset(), r.getLength()); ICodeLens lens = new JavaCodeLens(range, type); // String uri = ResourceUtils.toClientUri(JDTUtils.getFileURI(unit)); // lens.setData(Arrays.asList(uri, range.getStart(), type)); return lens; }
public static IJavaElement findElementAtSelection(ITypeRoot unit, int line, int column) throws JavaModelException, BadLocationException { IJavaElement[] elements = findElementsAtSelection(unit, line, column); if (elements != null && elements.length == 1) { return elements[0]; } return null; }
public void invalidate(ITypeRoot root){ if(root != null){ CompilationUnit removed = cache.remove(root.getHandleIdentifier()); if (removed != null) { JavaLanguageServerPlugin.logInfo("Releasing AST for " + root.getPath().toString()); } } }
/** * Checks whether the given Java element has accessible source. * * @param je the Java element to test * @return <code>true</code> if the element has source */ private static boolean hasSource(ITypeRoot je) { if (je == null || !je.exists()) { return false; } try { return je.getBuffer() != null; } catch (JavaModelException ex) { IStatus status= new Status(IStatus.ERROR, JavaLanguageServerPlugin.PLUGIN_ID, IStatus.OK, "Error in JDT Core during AST creation", ex); //$NON-NLS-1$ JavaLanguageServerPlugin.log(status); } return false; }
/** * Convenience method that combines {@link #resolveClassFile(String)} and * {@link #resolveCompilationUnit(String)}. * * @param uri * @return either a class file or compilation unit */ public static ITypeRoot resolveTypeRoot(String uriString) { URI uri = toURI(uriString); if (uri == null) { return null; } if (JDT_SCHEME.equals(uri.getScheme())) { return resolveClassFile(uri); } return resolveCompilationUnit(uri); }