public static void getInvalidQualificationProposals( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) { ASTNode node = problem.getCoveringNode(context.getASTRoot()); if (!(node instanceof Name)) { return; } Name name = (Name) node; IBinding binding = name.resolveBinding(); if (!(binding instanceof ITypeBinding)) { return; } ITypeBinding typeBinding = (ITypeBinding) binding; AST ast = node.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null); String label = CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description; Image image = JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal( label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME, image); proposals.add(proposal); }
/* * @see ASTVisitor#visit(MethodDeclaration) */ public boolean visit(MethodDeclaration node) { if (node.getJavadoc() != null) { node.getJavadoc().accept(this); } if (node.getAST().apiLevel() >= AST.JLS3) { printModifiers(node.modifiers()); if (!node.typeParameters().isEmpty()) { this.fBuffer.append("<"); // $NON-NLS-1$ for (Iterator it = node.typeParameters().iterator(); it.hasNext(); ) { TypeParameter t = (TypeParameter) it.next(); t.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append("> "); // $NON-NLS-1$ } } if (!node.isConstructor()) { if (node.getReturnType2() != null) { node.getReturnType2().accept(this); } else { // methods really ought to have a return type this.fBuffer.append("void"); // $NON-NLS-1$ } this.fBuffer.append(" "); // $NON-NLS-1$ } node.getName().accept(this); this.fBuffer.append("("); // $NON-NLS-1$ for (Iterator it = node.parameters().iterator(); it.hasNext(); ) { SingleVariableDeclaration v = (SingleVariableDeclaration) it.next(); v.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(")"); // $NON-NLS-1$ for (int i = 0; i < node.getExtraDimensions(); i++) { this.fBuffer.append("[]"); // $NON-NLS-1$ } if (!node.thrownExceptions().isEmpty()) { this.fBuffer.append(" throws "); // $NON-NLS-1$ for (Iterator it = node.thrownExceptions().iterator(); it.hasNext(); ) { Name n = (Name) it.next(); n.accept(this); if (it.hasNext()) { this.fBuffer.append(", "); // $NON-NLS-1$ } } this.fBuffer.append(" "); // $NON-NLS-1$ } if (node.getBody() == null) { this.fBuffer.append(";"); // $NON-NLS-1$ } else { node.getBody().accept(this); } return false; }
private static VariableDeclaration getVariableDeclaration(Name node) { IBinding binding = node.resolveBinding(); if (binding == null && node.getParent() instanceof VariableDeclaration) return (VariableDeclaration) node.getParent(); if (binding != null && binding.getKind() == IBinding.VARIABLE) { CompilationUnit cu = (CompilationUnit) ASTNodes.getParent(node, CompilationUnit.class); return ASTNodes.findVariableDeclaration(((IVariableBinding) binding), cu); } return null; }
private void possibleTypeRefFound(Name node) { while (node.isQualifiedName()) { node = ((QualifiedName) node).getQualifier(); } IBinding binding = node.resolveBinding(); if (binding == null || binding.getKind() == IBinding.TYPE) { // if the binding is null, we cannot determine if // we have a type binding or not, so we will assume // we do. addReference((SimpleName) node); } }
@Override protected void visitName(Name node) { IBinding binding = node.resolveBinding(); if (binding instanceof IVariableBinding && !((IVariableBinding) binding).isField()) { if (knownVariableDeclarations.get(binding) != null) checks.add( new LocalVariableReferenceCheck( file, jdtTypingProvider, bridge(node), knownVariableDeclarations.get(binding), node.toString())); } super.visitName(node); }
private void possibleStaticImportFound(Name name) { if (fStaticImports == null || fASTRoot == null) { return; } while (name.isQualifiedName()) { name = ((QualifiedName) name).getQualifier(); } if (!isAffected(name)) { return; } IBinding binding = name.resolveBinding(); SimpleName simpleName = (SimpleName) name; if (binding == null || binding instanceof ITypeBinding || !Modifier.isStatic(binding.getModifiers()) || simpleName.isDeclaration()) { return; } if (binding instanceof IVariableBinding) { IVariableBinding varBinding = (IVariableBinding) binding; if (varBinding.isField()) { varBinding = varBinding.getVariableDeclaration(); ITypeBinding declaringClass = varBinding.getDeclaringClass(); if (declaringClass != null && !declaringClass.isLocal()) { if (new ScopeAnalyzer(fASTRoot) .isDeclaredInScope( varBinding, simpleName, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY)) return; fStaticImports.add(simpleName); } } } else if (binding instanceof IMethodBinding) { IMethodBinding methodBinding = ((IMethodBinding) binding).getMethodDeclaration(); ITypeBinding declaringClass = methodBinding.getDeclaringClass(); if (declaringClass != null && !declaringClass.isLocal()) { if (new ScopeAnalyzer(fASTRoot) .isDeclaredInScope( methodBinding, simpleName, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY)) return; fStaticImports.add(simpleName); } } }
private void typeRefFound(Name node) { if (node != null) { while (node.isQualifiedName()) { node = ((QualifiedName) node).getQualifier(); } addReference((SimpleName) node); } }
@Override public boolean visit(NormalAnnotation node) { // // Test method? // if (isTestAnnotation(node.getTypeName().toString())) { ASTNode parent = node.getParent(); if (parent instanceof MethodDeclaration) { addTestMethod((MethodDeclaration) parent, JDK15_ANNOTATION); } else if (parent instanceof TypeDeclaration) { m_typeIsTest = true; m_annotationType = JDK15_ANNOTATION; } List pairs = node.values(); for (Iterator it = pairs.iterator(); it.hasNext(); ) { MemberValuePair mvp = (MemberValuePair) it.next(); Name attribute = mvp.getName(); String name = attribute.getFullyQualifiedName(); if ("groups".equals(name)) { Expression value = mvp.getValue(); // Array? if (value instanceof ArrayInitializer) { ArrayInitializer ai = (ArrayInitializer) value; List expressions = ai.expressions(); for (Iterator it2 = expressions.iterator(); it2.hasNext(); ) { Expression e = (Expression) it2.next(); addGroup(e.toString()); } } else if (value instanceof SimpleName) { Object boundValue = value.resolveConstantExpressionValue(); addGroup(boundValue.toString()); } else if (value instanceof StringLiteral) { addGroup(value.toString()); } } } } else if (isFactoryAnnotation(node.getTypeName().toString())) { if (node.getParent() instanceof MethodDeclaration) { m_annotationType = JDK15_ANNOTATION; addFactoryMethod((MethodDeclaration) node.getParent(), JDK15_ANNOTATION); } } return false; }
// !! - like one in ExtractTempRefactoring private static boolean canReplace(IASTFragment fragment) { ASTNode node = fragment.getAssociatedNode(); ASTNode parent = node.getParent(); if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent; if (node.equals(vdf.getName())) return false; } if (parent instanceof ExpressionStatement) return false; if (parent instanceof SwitchCase) { if (node instanceof Name) { Name name = (Name) node; ITypeBinding typeBinding = name.resolveTypeBinding(); if (typeBinding != null) { return !typeBinding.isEnum(); } } } return true; }
/** * generate checks accordingly. * * @param node * @param binding * @param declTypeBinding */ private void handleInheritedAbstractMethodImplementation( MethodDeclaration node, IMethodBinding methodBinding, List<MethodPathItem> inhMethods) { // add check for method name checks.add( new MethodImplementationNameCheck( file, jdtTypingProvider, bridge(node), methodBinding, inhMethods)); // add checks for parameters List parameterList = node.parameters(); for (int j = 0; j < parameterList.size(); j++) { checks.add( new MethodImplementationParameterCheck( file, jdtTypingProvider, bridge((SingleVariableDeclaration) parameterList.get(j)), methodBinding, j, inhMethods)); } // add checks for exceptions List exceptionList = node.thrownExceptions(); Name curExcNode; for (int i = 0; i < exceptionList.size(); i++) { curExcNode = (Name) exceptionList.get(i); ITypeBinding curExcBinding = curExcNode.resolveTypeBinding(); if (curExcBinding == null) continue; checks.add( new MethodImplementationExceptionCheck( file, jdtTypingProvider, bridge(curExcNode), methodBinding, curExcBinding.getKey(), inhMethods)); } }
private static ASTNode getRawReference( MethodInvocation invocation, CompilationUnit compilationUnit) { Name name1 = (Name) invocation.getStructuralProperty(MethodInvocation.NAME_PROPERTY); if (name1 instanceof SimpleName) { ASTNode rawReference = getRawReference((SimpleName) name1, compilationUnit); if (rawReference != null) { return rawReference; } } Expression expr = (Expression) invocation.getStructuralProperty(MethodInvocation.EXPRESSION_PROPERTY); if (expr instanceof SimpleName) { ASTNode rawReference = getRawReference((SimpleName) expr, compilationUnit); if (rawReference != null) { return rawReference; } } else if (expr instanceof QualifiedName) { Name name = (Name) expr; while (name instanceof QualifiedName) { SimpleName simpleName = (SimpleName) name.getStructuralProperty(QualifiedName.NAME_PROPERTY); ASTNode rawReference = getRawReference(simpleName, compilationUnit); if (rawReference != null) { return rawReference; } name = (Name) name.getStructuralProperty(QualifiedName.QUALIFIER_PROPERTY); } if (name instanceof SimpleName) { ASTNode rawReference = getRawReference((SimpleName) name, compilationUnit); if (rawReference != null) { return rawReference; } } } else if (expr instanceof MethodInvocation) { ASTNode rawReference = getRawReference((MethodInvocation) expr, compilationUnit); if (rawReference != null) { return rawReference; } } return null; }
@Override protected void visitName(Name node) { IBinding binding = node.resolveBinding(); if (binding != null && binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) { handleFieldChecks(node, (IVariableBinding) binding); } super.visitName(node); }
/* * Must be one of: * <ul> * <li>[result].length</li> * </ul> */ private boolean validateLengthQuery(Expression lengthQuery) { if (lengthQuery instanceof QualifiedName) { QualifiedName qualifiedName = (QualifiedName) lengthQuery; SimpleName name = qualifiedName.getName(); if (!LENGTH_QUERY.equals(name.getIdentifier())) return false; Name arrayAccess = qualifiedName.getQualifier(); ITypeBinding accessType = arrayAccess.resolveTypeBinding(); if (accessType == null) return false; if (!accessType.isArray()) return false; IBinding arrayBinding = arrayAccess.resolveBinding(); if (arrayBinding == null) return false; fArrayBinding = arrayBinding; fArrayAccess = arrayAccess; return true; } else if (lengthQuery instanceof FieldAccess) { FieldAccess fieldAccess = (FieldAccess) lengthQuery; SimpleName name = fieldAccess.getName(); if (!LENGTH_QUERY.equals(name.getIdentifier())) return false; Expression arrayAccess = fieldAccess.getExpression(); ITypeBinding accessType = arrayAccess.resolveTypeBinding(); if (accessType == null) return false; if (!accessType.isArray()) return false; IBinding arrayBinding = getBinding(arrayAccess); if (arrayBinding == null) return false; fArrayBinding = arrayBinding; fArrayAccess = arrayAccess; return true; } return false; }
private void handleOverridingRelationshipViolation( MethodDeclaration node, IMethodBinding methodBinding, List<MethodPathItem> inhMethods) { // get first overridden item MethodPathItem superItem = OverridingRelationUtils.getFirstNonAbstractItem(inhMethods); if (superItem == null) return; // add check for method name and params checks.add( new InheritedMethodCheck( file, jdtTypingProvider, bridge(node), OverridingRelationUtils.getIASTNodeList(node.parameters()), methodBinding.getName(), superItem)); // get all keys of method exceptions in super classes which are cast // compatible to exceptions of "node" // the list should contain at least one overridden exception key List exceptionList = node.thrownExceptions(); Name curExcNode; for (int i = 0; i < exceptionList.size(); i++) { curExcNode = (Name) exceptionList.get(i); ITypeBinding curExcBinding = curExcNode.resolveTypeBinding(); if (curExcBinding == null) continue; checks.add( new InheritedMethodExceptionCheck( file, jdtTypingProvider, bridge(curExcNode), curExcBinding.getName(), superItem.getInheritedExceptionKeys(methodBinding).get(curExcBinding.getKey()))); } }
@Override public void endVisit(CompilationUnit node) { RefactoringStatus status = getStatus(); superCall: { if (status.hasFatalError()) break superCall; if (!hasSelectedNodes()) { ASTNode coveringNode = getLastCoveringNode(); if (coveringNode instanceof Block && coveringNode.getParent() instanceof MethodDeclaration) { MethodDeclaration methodDecl = (MethodDeclaration) coveringNode.getParent(); Message[] messages = ASTNodes.getMessages(methodDecl, ASTNodes.NODE_ONLY); if (messages.length > 0) { status.addFatalError( Messages.format( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors, BasicElementLabels.getJavaElementName(methodDecl.getName().getIdentifier())), JavaStatusContext.create(fCUnit, methodDecl)); break superCall; } } status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } fEnclosingBodyDeclaration = (BodyDeclaration) ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class); if (fEnclosingBodyDeclaration == null || (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding); break superCall; } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { fEnclosingMethodBinding = ((MethodDeclaration) fEnclosingBodyDeclaration).resolveBinding(); } if (!isSingleExpressionOrStatementSet()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_single_expression_or_set); break superCall; } if (isExpressionSelected()) { ASTNode expression = getFirstSelectedNode(); if (expression instanceof Name) { Name name = (Name) expression; if (name.resolveBinding() instanceof ITypeBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_type_reference); break superCall; } if (name.resolveBinding() instanceof IMethodBinding) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_method_name_reference); break superCall; } if (name.resolveBinding() instanceof IVariableBinding) { StructuralPropertyDescriptor locationInParent = name.getLocationInParent(); if (locationInParent == QualifiedName.NAME_PROPERTY || (locationInParent == FieldAccess.NAME_PROPERTY && !(((FieldAccess) name.getParent()).getExpression() instanceof ThisExpression))) { status.addFatalError( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name); break superCall; } } if (name.isSimpleName() && ((SimpleName) name).isDeclaration()) { status.addFatalError( RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_name_in_declaration); break superCall; } } fForceStatic = ASTNodes.getParent(expression, ASTNode.SUPER_CONSTRUCTOR_INVOCATION) != null || ASTNodes.getParent(expression, ASTNode.CONSTRUCTOR_INVOCATION) != null; } status.merge(LocalTypeAnalyzer.perform(fEnclosingBodyDeclaration, getSelection())); computeLastStatementSelected(); } super.endVisit(node); }
private ClipboardData getClipboardData(ITypeRoot inputElement, int offset, int length) { CompilationUnit astRoot = SharedASTProvider.getAST(inputElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null); if (astRoot == null) { return null; } // do process import if selection spans over import declaration or package List<ImportDeclaration> list = astRoot.imports(); if (!list.isEmpty()) { if (offset < ((ASTNode) list.get(list.size() - 1)).getStartPosition()) { return null; } } else if (astRoot.getPackage() != null) { if (offset < ((ASTNode) astRoot.getPackage()).getStartPosition()) { return null; } } ArrayList<SimpleName> typeImportsRefs = new ArrayList<SimpleName>(); ArrayList<SimpleName> staticImportsRefs = new ArrayList<SimpleName>(); ImportReferencesCollector.collect( astRoot, inputElement.getJavaProject(), new Region(offset, length), typeImportsRefs, staticImportsRefs); if (typeImportsRefs.isEmpty() && staticImportsRefs.isEmpty()) { return null; } HashSet<String> namesToImport = new HashSet<String>(typeImportsRefs.size()); for (int i = 0; i < typeImportsRefs.size(); i++) { Name curr = typeImportsRefs.get(i); IBinding binding = curr.resolveBinding(); if (binding != null && binding.getKind() == IBinding.TYPE) { ITypeBinding typeBinding = (ITypeBinding) binding; if (typeBinding.isArray()) { typeBinding = typeBinding.getElementType(); } if (typeBinding.isTypeVariable() || typeBinding.isCapture() || typeBinding.isWildcardType()) { // can be removed when bug 98473 is fixed continue; } if (typeBinding.isMember() || typeBinding.isTopLevel()) { String name = Bindings.getRawQualifiedName(typeBinding); if (name.length() > 0) { namesToImport.add(name); } } } } HashSet<String> staticsToImport = new HashSet<String>(staticImportsRefs.size()); for (int i = 0; i < staticImportsRefs.size(); i++) { Name curr = staticImportsRefs.get(i); IBinding binding = curr.resolveBinding(); if (binding != null) { StringBuffer buf = new StringBuffer(Bindings.getImportName(binding)); if (binding.getKind() == IBinding.METHOD) { buf.append("()"); // $NON-NLS-1$ } staticsToImport.add(buf.toString()); } } if (namesToImport.isEmpty() && staticsToImport.isEmpty()) { return null; } String[] typeImports = namesToImport.toArray(new String[namesToImport.size()]); String[] staticImports = staticsToImport.toArray(new String[staticsToImport.size()]); return new ClipboardData(inputElement, typeImports, staticImports); }
public static void addFinalAndValAnnotationToModifierList( Object converter, List<IExtendedModifier> modifiers, AST ast, LocalDeclaration in) { // First check that 'in' has the final flag on, and a @val / @lombok.val annotation. if ((in.modifiers & ClassFileConstants.AccFinal) == 0) return; if (in.annotations == null) return; boolean found = false; Annotation valAnnotation = null; for (Annotation ann : in.annotations) { if (PatchVal.couldBeVal(ann.type)) { found = true; valAnnotation = ann; break; } } if (!found) return; // Now check that 'out' is missing either of these. if (modifiers == null) return; // This is null only if the project is 1.4 or less. Lombok doesn't work in that. boolean finalIsPresent = false; boolean valIsPresent = false; for (Object present : modifiers) { if (present instanceof Modifier) { ModifierKeyword keyword = ((Modifier) present).getKeyword(); if (keyword == null) continue; if (keyword.toFlagValue() == Modifier.FINAL) finalIsPresent = true; } if (present instanceof org.eclipse.jdt.core.dom.Annotation) { Name typeName = ((org.eclipse.jdt.core.dom.Annotation) present).getTypeName(); if (typeName != null) { String fullyQualifiedName = typeName.getFullyQualifiedName(); if ("val".equals(fullyQualifiedName) || "lombok.val".equals(fullyQualifiedName)) { valIsPresent = true; } } } } if (!finalIsPresent) { modifiers.add( createModifier( ast, ModifierKeyword.FINAL_KEYWORD, valAnnotation.sourceStart, valAnnotation.sourceEnd)); } if (!valIsPresent) { MarkerAnnotation newAnnotation = createValAnnotation( ast, valAnnotation, valAnnotation.sourceStart, valAnnotation.sourceEnd); try { Reflection.astConverterRecordNodes.invoke(converter, newAnnotation, valAnnotation); Reflection.astConverterRecordNodes.invoke( converter, newAnnotation.getTypeName(), valAnnotation.type); } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e.getCause()); } modifiers.add(newAnnotation); } }
/* (non-Javadoc) * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.PackageDeclaration) */ public boolean visit(PackageDeclaration node) { Name name = node.getName(); fPackage = Factory.packageDescriptor(name.getFullyQualifiedName()); return false; }