org.eclipse.jdt.internal.corext.dom.IASTSharedValues Java Examples
The following examples show how to use
org.eclipse.jdt.internal.corext.dom.IASTSharedValues.
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: SarlClassPathDetector.java From sarl with Apache License 2.0 | 6 votes |
/** Visit the given Java compilation unit. * * @param jfile the compilation unit. */ protected void visitJavaCompilationUnit(IFile jfile) { final ICompilationUnit cu = JavaCore.createCompilationUnitFrom(jfile); if (cu != null) { final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(cu); parser.setFocalPosition(0); final CompilationUnit root = (CompilationUnit) parser.createAST(null); final PackageDeclaration packDecl = root.getPackage(); final IPath packPath = jfile.getParent().getFullPath(); final String cuName = jfile.getName(); if (packDecl == null) { addToMap(this.sourceFolders, packPath, new Path(cuName)); } else { final IPath relPath = new Path(packDecl.getName().getFullyQualifiedName().replace('.', '/')); final IPath folderPath = getFolderPath(packPath, relPath); if (folderPath != null) { addToMap(this.sourceFolders, folderPath, relPath.append(cuName)); } } } }
Example #2
Source File: JDTUtils.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private static IBinding getHoveredNodeBinding(IJavaElement element, ITypeRoot typeRoot, IRegion region) { if (typeRoot == null || region == null) { return null; } IBinding binding; ASTNode node = getHoveredASTNode(typeRoot, region); if (node == null) { ASTParser p = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); p.setProject(element.getJavaProject()); p.setBindingsRecovery(true); try { binding = p.createBindings(new IJavaElement[] { element }, null)[0]; } catch (OperationCanceledException e) { return null; } } else { binding = resolveBinding(node); } return binding; }
Example #3
Source File: OverrideMethodsOperation.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static TextEdit addOverridableMethods(IType type, OverridableMethod[] overridableMethods) { if (type == null || type.getCompilationUnit() == null || overridableMethods == null || overridableMethods.length == 0) { return null; } RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); try { ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding == null) { return null; } IMethodBinding[] methodBindings = convertToMethodBindings(astRoot, typeBinding, overridableMethods); return createTextEditForOverridableMethods(type.getCompilationUnit(), astRoot, typeBinding, methodBindings); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Add overridable methods", e); } return null; }
Example #4
Source File: HashCodeEqualsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static TextEdit generateHashCodeEqualsTextEdit(IType type, LspVariableBinding[] fields, boolean regenerate, boolean useJava7Objects, boolean useInstanceof, boolean useBlocks, boolean generateComments) { if (type == null) { return null; } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding != null) { IVariableBinding[] variableBindings = JdtDomModels.convertToVariableBindings(typeBinding, fields); CodeGenerationSettings codeGenSettings = new CodeGenerationSettings(); codeGenSettings.createComments = generateComments; codeGenSettings.overrideAnnotation = true; GenerateHashCodeEqualsOperation operation = new GenerateHashCodeEqualsOperation(typeBinding, variableBindings, astRoot, null, codeGenSettings, useInstanceof, useJava7Objects, regenerate, false, false); operation.setUseBlocksForThen(useBlocks); operation.run(null); return operation.getResultingEdit(); } } catch (CoreException e) { JavaLanguageServerPlugin.logException("Generate hashCode and equals methods", e); } return null; }
Example #5
Source File: HashCodeEqualsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static CheckHashCodeEqualsResponse checkHashCodeEqualsStatus(IType type) { CheckHashCodeEqualsResponse response = new CheckHashCodeEqualsResponse(); if (type == null) { return response; } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding != null) { response.type = type.getTypeQualifiedName(); response.fields = JdtDomModels.getDeclaredFields(typeBinding, false); response.existingMethods = findExistingMethods(typeBinding); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Check hashCode and equals status", e); } return response; }
Example #6
Source File: GenerateToStringHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static TextEdit generateToString(IType type, LspVariableBinding[] fields, ToStringGenerationSettingsCore settings) { if (type == null) { return null; } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding != null) { IVariableBinding[] selectedFields = JdtDomModels.convertToVariableBindings(typeBinding, fields); GenerateToStringOperation operation = GenerateToStringOperation.createOperation(typeBinding, selectedFields, astRoot, null, settings, false, false); operation.run(null); return operation.getResultingEdit(); } } catch (CoreException e) { JavaLanguageServerPlugin.logException("Failed to generate toString()", e); } return null; }
Example #7
Source File: GenerateToStringHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
public static CheckToStringResponse checkToStringStatus(IType type) { CheckToStringResponse response = new CheckToStringResponse(); if (type == null) { return response; } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding != null) { response.type = type.getTypeQualifiedName(); response.fields = JdtDomModels.getDeclaredFields(typeBinding, false); response.exists = Stream.of(typeBinding.getDeclaredMethods()).anyMatch(method -> method.getName().equals(METHODNAME_TOSTRING) && method.getParameterTypes().length == 0); } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Failed to check toString status", e); } return response; }
Example #8
Source File: NewCUProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException { // String fileComment = getFileComment(cu, lineDelimiter); // String typeComment = getTypeComment(cu, lineDelimiter); IPackageFragment pack = (IPackageFragment) cu.getParent(); String content = CodeGeneration.getCompilationUnitContent(cu, null/*fileComment*/, null/*typeComment*/, typeContent, lineDelimiter); if (content != null) { ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(cu.getJavaProject()); parser.setSource(content.toCharArray()); CompilationUnit unit = (CompilationUnit) parser.createAST(null); if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) { return content; } } StringBuilder buf = new StringBuilder(); if (!pack.isDefaultPackage()) { buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$ } buf.append(lineDelimiter).append(lineDelimiter); // if (typeComment != null) { // buf.append(typeComment).append(lineDelimiter); // } buf.append(typeContent); return buf.toString(); }
Example #9
Source File: OverrideCompletionProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 6 votes |
private CompilationUnit getRecoveredAST(IDocument document, int offset, Document recoveredDocument) { CompilationUnit ast = CoreASTProvider.getInstance().getAST(fCompilationUnit, CoreASTProvider.WAIT_YES, null); if (ast != null) { recoveredDocument.set(document.get()); return ast; } char[] content= document.get().toCharArray(); // clear prefix to avoid compile errors int index= offset - 1; while (index >= 0 && Character.isJavaIdentifierPart(content[index])) { content[index]= ' '; index--; } recoveredDocument.set(new String(content)); final ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setResolveBindings(true); parser.setStatementsRecovery(true); parser.setSource(content); parser.setUnitName(fCompilationUnit.getElementName()); parser.setProject(fCompilationUnit.getJavaProject()); return (CompilationUnit) parser.createAST(new NullProgressMonitor()); }
Example #10
Source File: JavadocContentAccess2.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static CompilationUnit createAST(IJavaElement element, String cuSource) { Assert.isNotNull(element); ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); IJavaProject javaProject = element.getJavaProject(); parser.setProject(javaProject); Map<String, String> options = javaProject.getOptions(true); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207 parser.setCompilerOptions(options); parser.setSource(cuSource.toCharArray()); return (CompilationUnit) parser.createAST(null); }
Example #11
Source File: ChangeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static void convertPackageUpdateEdit(ICompilationUnit cu, String newPkgName, WorkspaceEdit rootEdit) throws JavaModelException { CompilationUnit unit = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(cu, true); ASTRewrite rewrite = ASTRewrite.create(unit.getAST()); if (updatePackageStatement(unit, newPkgName, rewrite, cu)) { TextEdit textEdit = rewrite.rewriteAST(); convertTextEdit(rootEdit, cu, textEdit); } }
Example #12
Source File: OverrideMethodsOperation.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static List<OverridableMethod> listOverridableMethods(IType type) { if (type == null || type.getCompilationUnit() == null) { return Collections.emptyList(); } List<OverridableMethod> overridables = new ArrayList<>(); RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); try { ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding == null) { return overridables; } IMethodBinding cloneMethod = null; ITypeBinding cloneable = astRoot.getAST().resolveWellKnownType("java.lang.Cloneable"); if (Bindings.isSuperType(cloneable, typeBinding)) { cloneMethod = resolveWellKnownCloneMethod(astRoot.getAST()); } IPackageBinding pack = typeBinding.getPackage(); IMethodBinding[] methods = StubUtility2Core.getOverridableMethods(astRoot.getAST(), typeBinding, false); for (IMethodBinding method : methods) { if (Bindings.isVisibleInHierarchy(method, pack)) { boolean toImplement = Objects.equals(method, cloneMethod); overridables.add(convertToSerializableMethod(method, toImplement)); } } } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("List overridable methods", e); } return overridables; }
Example #13
Source File: GenerateDelegateMethodsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static TextEdit generateDelegateMethods(IType type, LspDelegateEntry[] delegateEntries, CodeGenerationSettings settings) { if (type == null || type.getCompilationUnit() == null || delegateEntries == null || delegateEntries.length == 0) { return null; } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding == null) { return null; } DelegateEntry[] methodEntries = StubUtility2Core.getDelegatableMethods(typeBinding); Map<String, DelegateEntry> delegateEntryMap = new HashMap<>(); for (DelegateEntry methodEntry : methodEntries) { delegateEntryMap.put(methodEntry.field.getKey() + "#" + methodEntry.delegateMethod.getKey(), methodEntry); } //@formatter:off DelegateEntry[] selectedDelegateEntries = Arrays.stream(delegateEntries) .map(delegateEntry -> delegateEntryMap.get(delegateEntry.field.bindingKey + "#" + delegateEntry.delegateMethod.bindingKey)) .filter(delegateEntry -> delegateEntry != null) .toArray(DelegateEntry[]::new); //@formatter:on AddDelegateMethodsOperation operation = new AddDelegateMethodsOperation(astRoot, selectedDelegateEntries, null, settings, false, false); operation.run(null); return operation.getResultingEdit(); } catch (CoreException e) { JavaLanguageServerPlugin.logException("Failed to generate delegate methods", e); } return null; }
Example #14
Source File: GenerateDelegateMethodsHandler.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static CheckDelegateMethodsResponse checkDelegateMethodsStatus(CodeActionParams params) { IType type = SourceAssistProcessor.getSelectionType(params); if (type == null || type.getCompilationUnit() == null) { return new CheckDelegateMethodsResponse(); } try { RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); if (typeBinding == null) { return new CheckDelegateMethodsResponse(); } DelegateEntry[] delegateEntries = StubUtility2Core.getDelegatableMethods(typeBinding); Map<IVariableBinding, List<IMethodBinding>> fieldToMethods = new LinkedHashMap<>(); for (DelegateEntry delegateEntry : delegateEntries) { List<IMethodBinding> methods = fieldToMethods.getOrDefault(delegateEntry.field, new ArrayList<>()); methods.add(delegateEntry.delegateMethod); fieldToMethods.put(delegateEntry.field, methods); } //@formatter:off return new CheckDelegateMethodsResponse(fieldToMethods.entrySet().stream() .map(entry -> new LspDelegateField(entry.getKey(), entry.getValue().toArray(new IMethodBinding[0]))) .toArray(LspDelegateField[]::new)); //@formatter:on } catch (JavaModelException e) { JavaLanguageServerPlugin.logException("Failed to check delegate methods status", e); } return new CheckDelegateMethodsResponse(); }
Example #15
Source File: NewCUProposal.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private TextEdit constructEnclosingTypeEdit(ICompilationUnit icu) throws CoreException { ASTParser astParser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); astParser.setSource(icu); CompilationUnit cu = (CompilationUnit) astParser.createAST(null); TypeDeclaration enclosingDecl = findEnclosingTypeDeclaration(cu, fTypeContainer.getElementName()); AST ast = cu.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); final AbstractTypeDeclaration newDeclaration; switch (fTypeKind) { case K_CLASS: newDeclaration = ast.newTypeDeclaration(); ((TypeDeclaration) newDeclaration).setInterface(false); break; case K_INTERFACE: newDeclaration = ast.newTypeDeclaration(); ((TypeDeclaration) newDeclaration).setInterface(true); break; case K_ENUM: newDeclaration = ast.newEnumDeclaration(); break; case K_ANNOTATION: newDeclaration = ast.newAnnotationTypeDeclaration(); break; default: return null; } newDeclaration.setJavadoc(null); newDeclaration.setName(ast.newSimpleName(ASTNodes.getSimpleNameIdentifier(fNode))); newDeclaration.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD)); if (isParameterizedType(fTypeKind, fNode)) { addTypeParameters((TypeDeclaration) newDeclaration); } ListRewrite lrw = rewrite.getListRewrite(enclosingDecl, TypeDeclaration.BODY_DECLARATIONS_PROPERTY); lrw.insertLast(newDeclaration, null); return rewrite.rewriteAST(); }
Example #16
Source File: JavadocContentAccess.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private static CompilationUnit createAST(IJavaElement element, String cuSource) { ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); IJavaProject javaProject= element.getJavaProject(); parser.setProject(javaProject); Map<String, String> options= javaProject.getOptions(true); options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED); // workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=212207 parser.setCompilerOptions(options); parser.setSource(cuSource.toCharArray()); return (CompilationUnit) parser.createAST(null); }
Example #17
Source File: SelfEncapsulateFieldRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
@Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { if (fVisibility < 0) { fVisibility = (fField.getFlags() & (Flags.AccPublic | Flags.AccProtected | Flags.AccPrivate)); } RefactoringStatus result = new RefactoringStatus(); result.merge(Checks.checkAvailability(fField)); if (result.hasFatalError()) { return result; } fRoot = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(fField.getCompilationUnit(), true, pm); ISourceRange sourceRange = fField.getNameRange(); ASTNode node = NodeFinder.perform(fRoot, sourceRange.getOffset(), sourceRange.getLength()); if (node == null) { return mappingErrorFound(result, node); } fFieldDeclaration = ASTNodes.getParent(node, VariableDeclarationFragment.class); if (fFieldDeclaration == null) { return mappingErrorFound(result, node); } if (fFieldDeclaration.resolveBinding() == null) { if (!processCompilerError(result, node)) { result.addFatalError(RefactoringCoreMessages.SelfEncapsulateField_type_not_resolveable); } return result; } computeUsedNames(); return result; }
Example #18
Source File: ReorgPolicyFactory.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private CompilationUnit createSourceCuNode() { Assert.isTrue(getSourceCu() != null || getSourceClassFile() != null); Assert.isTrue(getSourceCu() == null || getSourceClassFile() == null); ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setBindingsRecovery(true); parser.setResolveBindings(true); if (getSourceCu() != null) { parser.setSource(getSourceCu()); } else { parser.setSource(getSourceClassFile()); } return (CompilationUnit) parser.createAST(null); }
Example #19
Source File: ExtractConstantRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private void checkSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException { String newCuSource = fChange.getPreviewContent(new NullProgressMonitor()); CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor); IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCuRewrite.getRoot()); for (int i = 0; i < newProblems.length; i++) { IProblem problem = newProblems[i]; if (problem.isError()) { result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem)))); } } }
Example #20
Source File: ExtractTempRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException { String newCuSource = fChange.getPreviewContent(new NullProgressMonitor()); CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor); IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode); for (int i = 0; i < newProblems.length; i++) { IProblem problem = newProblems[i]; if (problem.isError()) { result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem)))); } } }
Example #21
Source File: RenameAnalyzeUtil.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
/** * This method analyzes a set of local variable renames inside one cu. It checks whether * any new compile errors have been introduced by the rename(s) and whether the correct * node(s) has/have been renamed. * * @param analyzePackages the LocalAnalyzePackages containing the information about the local renames * @param cuChange the TextChange containing all local variable changes to be applied. * @param oldCUNode the fully (incl. bindings) resolved AST node of the original compilation unit * @param recovery whether statements and bindings recovery should be performed when parsing the changed CU * @return a RefactoringStatus containing errors if compile errors or wrongly renamed nodes are found * @throws CoreException thrown if there was an error greating the preview content of the change */ public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyzePackages, TextChange cuChange, CompilationUnit oldCUNode, boolean recovery) throws CoreException { RefactoringStatus result= new RefactoringStatus(); ICompilationUnit compilationUnit= (ICompilationUnit) oldCUNode.getJavaElement(); String newCuSource= cuChange.getPreviewContent(new NullProgressMonitor()); CompilationUnit newCUNode= new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, compilationUnit, true, recovery, null); result.merge(analyzeCompileErrors(newCuSource, newCUNode, oldCUNode)); if (result.hasError()) { return result; } for (int i= 0; i < analyzePackages.length; i++) { ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode); // get new declaration IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange); ASTNode newDeclaration= NodeFinder.perform(newCUNode, newRegion.getOffset(), newRegion.getLength()); Assert.isTrue(newDeclaration instanceof Name); VariableDeclaration declaration= getVariableDeclaration((Name) newDeclaration); Assert.isNotNull(declaration); SimpleName[] problemNodes= ProblemNodeFinder.getProblemNodes(enclosing, declaration, analyzePackages[i].fOccurenceEdits, cuChange); result.merge(RefactoringAnalyzeUtil.reportProblemNodes(newCuSource, problemNodes)); } return result; }
Example #22
Source File: SourceAssistProcessor.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private boolean supportsHashCodeEquals(IInvocationContext context, IType type) { try { if (type == null || type.isAnnotation() || type.isInterface() || type.isEnum() || type.getCompilationUnit() == null) { return false; } RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL); CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true); ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type); return (typeBinding == null) ? false : Arrays.stream(typeBinding.getDeclaredFields()).filter(f -> !Modifier.isStatic(f.getModifiers())).findAny().isPresent(); } catch (JavaModelException e) { return false; } }
Example #23
Source File: JDTUtils.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
public static String getPackageName(IJavaProject javaProject, String fileContent) { if (fileContent == null) { return ""; } //TODO probably not the most efficient way to get the package name as this reads the whole file; char[] source = fileContent.toCharArray(); ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(javaProject); parser.setIgnoreMethodBodies(true); parser.setSource(source); CompilationUnit ast = (CompilationUnit) parser.createAST(null); PackageDeclaration pkg = ast.getPackage(); return (pkg == null || pkg.getName() == null)?"":pkg.getName().getFullyQualifiedName(); }
Example #24
Source File: CompletionProposalReplacementProvider.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 5 votes |
private ITypeBinding getExpectedTypeForGenericParameters() { char[][] chKeys= context.getExpectedTypesKeys(); if (chKeys == null || chKeys.length == 0) { return null; } String[] keys= new String[chKeys.length]; for (int i= 0; i < keys.length; i++) { keys[i]= String.valueOf(chKeys[0]); } final ASTParser parser = ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(compilationUnit.getJavaProject()); parser.setResolveBindings(true); parser.setStatementsRecovery(true); final Map<String, IBinding> bindings= new HashMap<>(); ASTRequestor requestor= new ASTRequestor() { @Override public void acceptBinding(String bindingKey, IBinding binding) { bindings.put(bindingKey, binding); } }; parser.createASTs(new ICompilationUnit[0], keys, requestor, null); if (bindings.size() > 0) { return (ITypeBinding) bindings.get(keys[0]); } return null; }
Example #25
Source File: SelfEncapsulateFieldRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@Override public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { pm.beginTask(NO_NAME, 12); pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_checking_preconditions); RefactoringStatus result = new RefactoringStatus(); fRewriter = ASTRewrite.create(fRoot.getAST()); fChangeManager.clear(); boolean usingLocalGetter = isUsingLocalGetter(); boolean usingLocalSetter = isUsingLocalSetter(); result.merge(checkMethodNames(usingLocalGetter, usingLocalSetter)); pm.worked(1); if (result.hasFatalError()) { return result; } pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_searching_for_cunits); final SubProgressMonitor subPm = new SubProgressMonitor(pm, 5); ICompilationUnit[] affectedCUs = RefactoringSearchEngine.findAffectedCompilationUnits(SearchPattern.createPattern(fField, IJavaSearchConstants.REFERENCES), RefactoringScopeFactory.create(fField, fConsiderVisibility), subPm, result, true); checkInHierarchy(result, usingLocalGetter, usingLocalSetter); if (result.hasFatalError()) { return result; } pm.setTaskName(RefactoringCoreMessages.SelfEncapsulateField_analyzing); IProgressMonitor sub = new SubProgressMonitor(pm, 5); sub.beginTask(NO_NAME, affectedCUs.length); IVariableBinding fieldIdentifier = fFieldDeclaration.resolveBinding(); ITypeBinding declaringClass = ASTNodes.getParent(fFieldDeclaration, AbstractTypeDeclaration.class).resolveBinding(); List<TextEditGroup> ownerDescriptions = new ArrayList<>(); ICompilationUnit owner = fField.getCompilationUnit(); fImportRewrite = StubUtility.createImportRewrite(fRoot, true); for (int i = 0; i < affectedCUs.length; i++) { ICompilationUnit unit = affectedCUs[i]; sub.subTask(BasicElementLabels.getFileName(unit)); CompilationUnit root = null; ASTRewrite rewriter = null; ImportRewrite importRewrite; List<TextEditGroup> descriptions; if (owner.equals(unit)) { root = fRoot; rewriter = fRewriter; importRewrite = fImportRewrite; descriptions = ownerDescriptions; } else { root = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(unit, true); rewriter = ASTRewrite.create(root.getAST()); descriptions = new ArrayList<>(); importRewrite = StubUtility.createImportRewrite(root, true); } checkCompileErrors(result, root, unit); AccessAnalyzer analyzer = new AccessAnalyzer(this, unit, fieldIdentifier, declaringClass, rewriter, importRewrite); root.accept(analyzer); result.merge(analyzer.getStatus()); if (!fSetterMustReturnValue) { fSetterMustReturnValue= analyzer.getSetterMustReturnValue(); } if (result.hasFatalError()) { fChangeManager.clear(); return result; } descriptions.addAll(analyzer.getGroupDescriptions()); if (!owner.equals(unit)) { createEdits(unit, rewriter, descriptions, importRewrite); } sub.worked(1); if (pm.isCanceled()) { throw new OperationCanceledException(); } } ownerDescriptions.addAll(addGetterSetterChanges(fRoot, fRewriter, owner.findRecommendedLineSeparator(), usingLocalSetter, usingLocalGetter)); createEdits(owner, fRewriter, ownerDescriptions, fImportRewrite); sub.done(); IFile[] filesToBeModified = ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()); result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext(), pm)); if (result.hasFatalError()) { return result; } ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)); return result; }
Example #26
Source File: SurroundWithTryCatchRefactoring.java From eclipse.jdt.ls with Eclipse Public License 2.0 | 4 votes |
@Override public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { CompilationUnit rootNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(fCUnit, true, pm); return checkActivationBasics(rootNode); }