// Função auxiliar para copiar o tipo da variável // considerando que um tipo nao pode pertencer a outra AST private Type getType(ITypeBinding typeBinding, AST newAST) { if (typeBinding.isPrimitive()) { return newAST.newPrimitiveType(PrimitiveType.toCode(typeBinding.getName())); } else if (typeBinding.isArray()) { return newAST.newArrayType( this.getType(typeBinding.getElementType(), newAST), typeBinding.getDimensions()); } else if (typeBinding.isParameterizedType()) { ParameterizedType pt = newAST.newParameterizedType(this.getType(typeBinding.getTypeDeclaration(), newAST)); for (ITypeBinding itb : typeBinding.getTypeArguments()) { pt.typeArguments().add(this.getType(itb, newAST)); } return pt; } else if (typeBinding.isWildcardType()) { WildcardType wt = newAST.newWildcardType(); wt.setBound( typeBinding.getBound() == null ? null : this.getType(typeBinding.getBound(), newAST), typeBinding.isUpperbound()); return wt; } else { try { return newAST.newSimpleType(newAST.newName(typeBinding.getQualifiedName())); } catch (Exception e) { return newAST.newSimpleType(newAST.newName(typeBinding.getName())); } } }
/** @since 2.4 */ protected URI getFullURI(ITypeBinding typeBinding, SegmentSequence.Builder builder) { if (typeBinding.isPrimitive()) { builder.append(PRIMITIVE_URIS[typeBinding.getKey().charAt(0) - 'B'].fragment()); return PRIMITIVES_URI; } if (typeBinding.isClass() || typeBinding.isInterface() || typeBinding.isAnnotation() || typeBinding.isEnum()) { ITypeBinding declaringClass = typeBinding.getDeclaringClass(); if (declaringClass != null) { URI uri = getFullURI(declaringClass, builder); builder.append("$"); builder.append(typeBinding.getName()); return uri; } String qualifiedName = typeBinding.getErasure().getQualifiedName(); URI uri = COMMON_URIS.get(qualifiedName); if (uri == null) { uri = OBJECTS_URI.appendSegment(qualifiedName); } builder.append(uri.lastSegment()); return uri; } if (typeBinding.isArray()) { URI uri = getFullURI(typeBinding.getComponentType(), builder); builder.append("[]"); return uri; } if (typeBinding.isTypeVariable()) { ITypeBinding declaringClass = typeBinding.getDeclaringClass(); if (declaringClass != null) { URI uri = getFullURI(declaringClass, builder); builder.append("/"); builder.append(typeBinding.getName()); return uri; } IMethodBinding declaringMethod = typeBinding.getDeclaringMethod(); URI uri = getFullURI(declaringMethod.getDeclaringClass(), builder); builder.append("."); builder.append(declaringMethod.getName()); builder.append("("); ITypeBinding[] parameterTypes = declaringMethod.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) { if (i != 0) { builder.append(","); } getQualifiedName(parameterTypes[i], builder); } builder.append(")"); builder.append("/"); builder.append(typeBinding.getName()); return uri; } throw new IllegalStateException("Unexpected type: " + typeBinding); }
public ImplementInterfaceProposal( ICompilationUnit targetCU, ITypeBinding binding, CompilationUnit astRoot, ITypeBinding newInterface, int relevance) { super( "", targetCU, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); // $NON-NLS-1$ Assert.isTrue(binding != null && Bindings.isDeclarationBinding(binding)); fBinding = binding; fAstRoot = astRoot; fNewInterface = newInterface; String[] args = { BasicElementLabels.getJavaElementName(binding.getName()), BasicElementLabels.getJavaElementName(Bindings.getRawName(newInterface)) }; setDisplayName(Messages.format(CorrectionMessages.ImplementInterfaceProposal_name, args)); }
public URI getFullURI(ITypeBinding typeBinding) { // The URIs for primitive types are cached and indexed by their one character key // representation. // if (typeBinding.isPrimitive()) { return PRIMITIVE_URIS[typeBinding.getKey().charAt(0) - 'B']; } if (typeBinding.isClass() || typeBinding.isInterface() || typeBinding.isAnnotation() || typeBinding.isEnum()) { ITypeBinding declaringClass = typeBinding.getDeclaringClass(); if (declaringClass == null) { // This special case handling for common case of top level types that avoids creating a // builder. // String qualifiedName = typeBinding.getErasure().getQualifiedName(); URI uri = COMMON_URIS.get(qualifiedName); if (uri != null) { return uri; } uri = OBJECTS_URI.appendSegment(qualifiedName); return uri.appendFragment(uri.lastSegment()); } SegmentSequence.Builder builder = SegmentSequence.newBuilder(""); URI uri = getFullURI(declaringClass, builder); builder.append("$"); builder.append(typeBinding.getName()); return uri.appendFragment(builder.toString()); } SegmentSequence.Builder builder = SegmentSequence.newBuilder(""); URI uri = getFullURI(typeBinding, builder); return uri.appendFragment(builder.toString()); }
/** Returns the inner type with the specified name. */ public static ITypeBinding findDeclaredType(ITypeBinding type, String name) { for (ITypeBinding innerType : type.getDeclaredTypes()) { if (innerType.getName().equals(name)) { return innerType; } } return null; }
protected void createFragmentForTypeVariable(ITypeBinding typeBinding, StringBuilder uriBuilder) { if (typeBinding.getDeclaringMethod() != null) { createFragmentForMethod(typeBinding.getDeclaringMethod(), uriBuilder); } else { createFragment(typeBinding.getDeclaringClass(), uriBuilder); } uriBuilder.append('/'); uriBuilder.append(typeBinding.getName()); }
/** @since 2.4 */ protected SegmentSequence.Builder getQualifiedName( ITypeBinding binding, SegmentSequence.Builder builder) { if (binding.isParameterizedType()) { getQualifiedName(binding.getErasure(), builder); } else if (binding.isArray()) { getQualifiedName(binding.getComponentType(), builder).append("[]"); } else if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) { builder.append(binding.getQualifiedName()); } else { getQualifiedName(binding.getDeclaringClass(), builder).append('$').append(binding.getName()); } return builder; }
/** @since 2.4 */ public StringBuilder getQualifiedName(ITypeBinding binding, StringBuilder stringBuilder) { if (binding.isParameterizedType()) { getQualifiedName(binding.getErasure(), stringBuilder); } else if (binding.isArray()) { getQualifiedName(binding.getComponentType(), stringBuilder).append("[]"); } else if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) { stringBuilder.append(binding.getQualifiedName()); } else { getQualifiedName(binding.getDeclaringClass(), stringBuilder) .append('$') .append(binding.getName()); } return stringBuilder; }
public String getQualifiedName(ITypeBinding binding) { if (binding.isParameterizedType()) { return getQualifiedName(binding.getErasure()); } if (binding.isArray()) { return getQualifiedName(binding.getComponentType(), new StringBuilder()) .append("[]") .toString(); } if (binding.isTopLevel() || binding.isTypeVariable() || binding.isPrimitive()) return binding.getQualifiedName(); return getQualifiedName(binding.getDeclaringClass(), new StringBuilder()) .append('$') .append(binding.getName()) .toString(); }
/** * 中断接受节点 * * @param node : 函数调用 */ public void interruptAcceptNodeHandle(MethodInvocation node) { int lineNumber = compilationUnit.getLineNumber(node.getStartPosition()); Node interruptedNode = new Node(filePath, lineNumber); String threadKey; Expression expression = node.getExpression(); ITypeBinding iTypeBinding = castHelper.getResolveTypeBinding(expression); if (expression == null || iTypeBinding == null) { System.out.println(filePath); System.out.println(compilationUnit.getLineNumber(node.getStartPosition())); System.out.println("interrupt iTypeBinding error!"); return; } // 普通变量 if (expression instanceof SimpleName && ((SimpleName) expression).resolveBinding() != null) { SimpleName simpleName = (SimpleName) expression; if (castHelper.getDecNode(simpleName) == null) { return; } int decLineNumber = compilationUnit.getLineNumber(castHelper.getDecNode(simpleName).getStartPosition()); String varKey = filePath + "_" + decLineNumber + "_" + iTypeBinding.getName() + "_" + simpleName.getIdentifier(); System.out.println(varKey); if (threadVarHashMap.containsKey(varKey)) { threadKey = threadVarHashMap.get(varKey).getThreadInfoKey(); if (threadInfo.get(threadKey).getInterruptNodes() != null) { threadInfo.get(threadKey).getInterruptNodes().add(interruptedNode); } } else { System.out.println("ERROR: didn't contains the varKey"); } } // 其它调用 else if (((SimpleName) expression).resolveBinding() != null) { threadKey = iTypeBinding.getBinaryName(); if (threadInfo.get(threadKey).getInterruptNodes() != null) { threadInfo.get(threadKey).getInterruptNodes().add(interruptedNode); } } }
/** * 中断通知节点 * * @param node :函数调用 * @param threadInterruptNode :中断节点类 */ public void interruptNotifyNodeHandle( MethodInvocation node, ThreadInterruptNode threadInterruptNode) { String threadKey; Expression expression = node.getExpression(); ITypeBinding iTypeBinding = castHelper.getResolveTypeBinding(expression); if (expression == null || iTypeBinding == null) { System.out.println(filePath); System.out.println(compilationUnit.getLineNumber(node.getStartPosition())); System.out.println("interrupt iTypeBinding error!"); return; } // 普通变量,从变量集中获取线程key if (expression instanceof SimpleName && ((SimpleName) expression).resolveBinding() != null) { SimpleName simpleName = (SimpleName) expression; int lineNumber = compilationUnit.getLineNumber(castHelper.getDecNode(simpleName).getStartPosition()); String varKey = filePath + "_" + lineNumber + "_" + iTypeBinding.getName() + "_" + simpleName.getIdentifier(); System.out.println(varKey); if (threadVarHashMap.containsKey(varKey)) { threadKey = threadVarHashMap.get(varKey).getThreadInfoKey(); threadInterruptNode.getThreadKeyList().add(threadKey); // 添加至中断通知节点集合 threadInterruptNodes.add(threadInterruptNode); } else { System.out.println("ERROR: didn't contains the varKey"); } } // 其它调用(函数返回值等):直接从返回值类型推断具体线程key else { threadKey = iTypeBinding.getBinaryName(); threadInterruptNode.getThreadKeyList().add(threadKey); } }
/** * Builds a new {@link ClassInstanceCreation} instance. * * @param typeBinding the type binding of the instantiated type * @param arguments the constructor invocation arguments * @return a new class instance creation */ public ClassInstanceCreation new0(ITypeBinding typeBinding, Expression... arguments) { final String className = typeBinding.getName(); final int ltIdx = className.indexOf('<'); if (ltIdx == -1) { final ClassInstanceCreation cic = ast.newClassInstanceCreation(); cic.setType(newSimpleType(className)); addAll(arguments(cic), arguments); return cic; } final String erasedClassName = className.substring(0, ltIdx); final int gtIdx = className.indexOf('>', ltIdx); final String typeParams = className.substring(ltIdx + 1, gtIdx); final ClassInstanceCreation cic = ast.newClassInstanceCreation(); final ParameterizedType type = ast.newParameterizedType(newSimpleType(erasedClassName)); addNewTypesFromTypeParameters(typeArguments(type), typeParams); cic.setType(type); addAll(arguments(cic), arguments); return cic; }
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()))); } }
/** List has a toArray() method that uses array types. */ public void testAbstractMethodsAddedWithArrayType() { String source = "import java.util.List; public abstract class Test implements List<Object> { " + "public boolean isEmpty() { return true; } }"; CompilationUnit unit = translateType("Test", source); List<AbstractTypeDeclaration> types = unit.getTypes(); assertEquals(1, types.size()); assertTrue(types.get(0) instanceof TypeDeclaration); TypeDeclaration testType = (TypeDeclaration) types.get(0); List<MethodDeclaration> methods = TreeUtil.getMethodDeclarationsList(testType); assertEquals(26, methods.size()); // verify added methods are abstract, and that existing method wasn't changed for (MethodDeclaration m : methods) { int modifiers = m.getModifiers(); String name = m.getName().getIdentifier(); if (name.equals("isEmpty")) { assertFalse(Modifier.isAbstract(modifiers)); } else if (name.equals(NameTable.FINALIZE_METHOD) || name.equals(NameTable.DEALLOC_METHOD) || name.equals(NameTable.INIT_NAME)) { // it's ok. } else { // it's an added method assertTrue(Modifier.isAbstract(modifiers)); ITypeBinding returnType = m.getReturnType().getTypeBinding(); if (name.equals("toArray")) { assertEquals("IOSObjectArray", returnType.getName()); if (!m.getParameters().isEmpty()) { assertEquals(1, m.getParameters().size()); SingleVariableDeclaration param = m.getParameters().get(0); IVariableBinding paramBinding = param.getVariableBinding(); assertTrue(paramBinding.getType().isArray()); } } } } }
@Override public boolean visit(MethodInvocation node) { IMethodBinding methodBinding = node.resolveMethodBinding(); ITypeBinding declaringClass = methodBinding.getDeclaringClass(); IMethodBinding methodDeclaration = methodBinding.getMethodDeclaration(); String denyToSrcLocation = getSourceLocation(methodBinding, declaringClass); if (denyToSrc != null && denyToSrcLocation != null && !denyToSrc.matcher(denyToSrcLocation).find()) { return true; } String declaringClassName = declaringClass.getName(); String declaringClassPackage = declaringClass.getPackage() == null ? "" : declaringClass.getPackage().getName() + "."; String methodDeclarationName = methodDeclaration.getName(); String methodCall = declaringClassPackage + declaringClassName + "#" + methodDeclarationName; if (denyTo.matcher(methodCall).matches()) { String txt = createWarningText( this.acu.getFullyQualifiedClassName(), methodCall, this.acu.getSourceLocation(), denyToSrcLocation); this.acu.addMarker( "Method dependency " + txt, this.acu.getCompilationUnit().getLineNumber(node.getStartPosition()), IMarker.SEVERITY_WARNING); } return true; }
public static void getMissingJavadocCommentProposals( IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException { ASTNode node = problem.getCoveringNode(context.getASTRoot()); if (node == null) { return; } BodyDeclaration declaration = ASTResolving.findParentBodyDeclaration(node); if (declaration == null) { return; } ICompilationUnit cu = context.getCompilationUnit(); ITypeBinding binding = Bindings.getBindingOfParentType(declaration); if (binding == null) { return; } if (declaration instanceof MethodDeclaration) { MethodDeclaration methodDecl = (MethodDeclaration) declaration; IMethodBinding methodBinding = methodDecl.resolveBinding(); IMethodBinding overridden = null; if (methodBinding != null) { overridden = Bindings.findOverriddenMethod(methodBinding, true); } String string = CodeGeneration.getMethodComment( cu, binding.getName(), methodDecl, overridden, String.valueOf('\n')); if (string != null) { String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_method_description; proposals.add( new AddJavadocCommentProposal( label, cu, IProposalRelevance.ADD_JAVADOC_METHOD, declaration.getStartPosition(), string)); } } else if (declaration instanceof AbstractTypeDeclaration) { String typeQualifiedName = Bindings.getTypeQualifiedName(binding); String[] typeParamNames; if (declaration instanceof TypeDeclaration) { List<TypeParameter> typeParams = ((TypeDeclaration) declaration).typeParameters(); typeParamNames = new String[typeParams.size()]; for (int i = 0; i < typeParamNames.length; i++) { typeParamNames[i] = (typeParams.get(i)).getName().getIdentifier(); } } else { typeParamNames = new String[0]; } String string = CodeGeneration.getTypeComment( cu, typeQualifiedName, typeParamNames, String.valueOf('\n')); if (string != null) { String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_type_description; proposals.add( new AddJavadocCommentProposal( label, cu, IProposalRelevance.ADD_JAVADOC_TYPE, declaration.getStartPosition(), string)); } } else if (declaration instanceof FieldDeclaration) { String comment = "/**\n *\n */\n"; // $NON-NLS-1$ List<VariableDeclarationFragment> fragments = ((FieldDeclaration) declaration).fragments(); if (fragments != null && fragments.size() > 0) { VariableDeclaration decl = fragments.get(0); String fieldName = decl.getName().getIdentifier(); String typeName = binding.getName(); comment = CodeGeneration.getFieldComment(cu, typeName, fieldName, String.valueOf('\n')); } if (comment != null) { String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_field_description; proposals.add( new AddJavadocCommentProposal( label, cu, IProposalRelevance.ADD_JAVADOC_FIELD, declaration.getStartPosition(), comment)); } } else if (declaration instanceof EnumConstantDeclaration) { EnumConstantDeclaration enumDecl = (EnumConstantDeclaration) declaration; String id = enumDecl.getName().getIdentifier(); String comment = CodeGeneration.getFieldComment(cu, binding.getName(), id, String.valueOf('\n')); String label = CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_enumconst_description; proposals.add( new AddJavadocCommentProposal( label, cu, IProposalRelevance.ADD_JAVADOC_ENUM, declaration.getStartPosition(), comment)); } }
private void insertAllMissingMethodTags(ASTRewrite rewriter, MethodDeclaration methodDecl) { AST ast = methodDecl.getAST(); Javadoc javadoc = methodDecl.getJavadoc(); ListRewrite tagsRewriter = rewriter.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY); List<TypeParameter> typeParams = methodDecl.typeParameters(); ASTNode root = methodDecl.getRoot(); if (root instanceof CompilationUnit) { ITypeRoot typeRoot = ((CompilationUnit) root).getTypeRoot(); if (typeRoot != null && !StubUtility.shouldGenerateMethodTypeParameterTags(typeRoot.getJavaProject())) typeParams = Collections.emptyList(); } List<String> typeParamNames = new ArrayList<>(); for (int i = typeParams.size() - 1; i >= 0; i--) { TypeParameter decl = typeParams.get(i); String name = '<' + decl.getName().getIdentifier() + '>'; if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); TextElement text = ast.newTextElement(); text.setText(name); newTag.fragments().add(text); insertTabStop(rewriter, newTag.fragments(), "typeParam" + i); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousTypeParamNames(typeParams, decl)); } typeParamNames.add(name); } List<SingleVariableDeclaration> params = methodDecl.parameters(); for (int i = params.size() - 1; i >= 0; i--) { SingleVariableDeclaration decl = params.get(i); String name = decl.getName().getIdentifier(); if (findTag(javadoc, TagElement.TAG_PARAM, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_PARAM); newTag.fragments().add(ast.newSimpleName(name)); insertTabStop(rewriter, newTag.fragments(), "methParam" + i); // $NON-NLS-1$ Set<String> sameKindLeadingNames = getPreviousParamNames(params, decl); sameKindLeadingNames.addAll(typeParamNames); insertTag(tagsRewriter, newTag, sameKindLeadingNames); } } if (!methodDecl.isConstructor()) { Type type = methodDecl.getReturnType2(); if (!type.isPrimitiveType() || (((PrimitiveType) type).getPrimitiveTypeCode() != PrimitiveType.VOID)) { if (findTag(javadoc, TagElement.TAG_RETURN, null) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_RETURN); insertTabStop(rewriter, newTag.fragments(), "return"); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, null); } } } List<Type> thrownExceptions = methodDecl.thrownExceptionTypes(); for (int i = thrownExceptions.size() - 1; i >= 0; i--) { Type exception = thrownExceptions.get(i); ITypeBinding binding = exception.resolveBinding(); if (binding != null) { String name = binding.getName(); if (findThrowsTag(javadoc, name) == null) { TagElement newTag = ast.newTagElement(); newTag.setTagName(TagElement.TAG_THROWS); TextElement excNode = ast.newTextElement(); excNode.setText(ASTNodes.getQualifiedTypeName(exception)); newTag.fragments().add(excNode); insertTabStop(rewriter, newTag.fragments(), "exception" + i); // $NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousExceptionNames(thrownExceptions, exception)); } } } }
protected void createFragmentForPrimitive(ITypeBinding typeBinding, StringBuilder uriBuilder) { uriBuilder.append(typeBinding.getName()); }