private static String decideRuleKind(ReferencedClassesParser parser, Set<String> dependencies) { CompilationUnit cu = parser.compilationUnit; if (cu.types().isEmpty()) { return "java_library"; } AbstractTypeDeclaration topLevelClass = (AbstractTypeDeclaration) cu.types().get(0); if ((topLevelClass.getModifiers() & Modifier.ABSTRACT) != 0) { // Class is abstract, can't be a test. return "java_library"; } // JUnit 4 tests if (parser.className.endsWith("Test") && dependencies.contains("org.junit.Test")) { return "java_test"; } if (any( topLevelClass.bodyDeclarations(), d -> d instanceof MethodDeclaration && isMainMethod((MethodDeclaration) d))) { return "java_binary"; } return "java_library"; }
@Override public DSubTree handle() { DSubTree tree = new DSubTree(); // add the expression's subtree (e.g: foo(..).bar() should handle foo(..) first) DSubTree Texp = new DOMExpression(creation.getExpression()).handle(); tree.addNodes(Texp.getNodes()); // evaluate arguments first for (Object o : creation.arguments()) { DSubTree Targ = new DOMExpression((Expression) o).handle(); tree.addNodes(Targ.getNodes()); } IMethodBinding binding = creation.resolveConstructorBinding(); // get to the generic declaration, if this binding is an instantiation while (binding != null && binding.getMethodDeclaration() != binding) binding = binding.getMethodDeclaration(); MethodDeclaration localMethod = Utils.checkAndGetLocalMethod(binding); if (localMethod != null) { DSubTree Tmethod = new DOMMethodDeclaration(localMethod).handle(); tree.addNodes(Tmethod.getNodes()); } else if (Utils.isRelevantCall(binding)) tree.addNode(new DAPICall(binding, Visitor.V().getLineNumber(creation))); return tree; }
public static Optional<GroovyClosure> asClosure(ASTNodeFactory nodeFactory, GroovyClosureBuilder groovyClosureBuilder, Expression expression, String methodName) { if (expression instanceof ClassInstanceCreation) { ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation) expression; if (classInstanceCreation.getAnonymousClassDeclaration() != null) { AnonymousClassDeclaration classDeclaration = classInstanceCreation.getAnonymousClassDeclaration(); if (classDeclaration.bodyDeclarations().size() == 1 && classDeclaration.bodyDeclarations().get(0) instanceof MethodDeclaration && ((MethodDeclaration) classDeclaration.bodyDeclarations().get(0)) .getName().getIdentifier().equals(methodName)) { MethodDeclaration methodDeclaration = (MethodDeclaration) classDeclaration.bodyDeclarations().get(0); List<Statement> statements = nodeFactory.clone(methodDeclaration.getBody()).statements(); GroovyClosure closure = groovyClosureBuilder.aClosure() .withBodyStatements(statements) .withTypeLiteral(nodeFactory.typeLiteral(type(nodeFactory, classInstanceCreation))) .withArgument(nodeFactory.clone((SingleVariableDeclaration) methodDeclaration.parameters().get(0))) .build(); return Optional.of(closure); } } } return empty(); }
public RastNode createMethod(String methodSignature, HasChildrenNodes parent, String sourceFilePath, boolean constructor, MethodDeclaration ast) { String methodName = ast.isConstructor() ? "" : ast.getName().getIdentifier(); RastNode rastNode = new RastNode(++nodeCounter); rastNode.setType(ast.getClass().getSimpleName()); Block body = ast.getBody(); int bodyStart; int bodyLength; if (body == null) { rastNode.addStereotypes(Stereotype.ABSTRACT); bodyStart = ast.getStartPosition() + ast.getLength(); bodyLength = 0; } else { bodyStart = body.getStartPosition(); bodyLength = body.getLength(); } rastNode.setLocation(new Location(sourceFilePath, ast.getStartPosition(), ast.getStartPosition() + ast.getLength(), bodyStart, bodyStart + bodyLength)); rastNode.setLocalName(methodSignature); rastNode.setSimpleName(methodName); parent.addNode(rastNode); keyMap.put(JavaParser.getKey(rastNode), rastNode); return rastNode; }
public static String getSignatureFromMethodDeclaration(MethodDeclaration methodDeclaration) { String methodName = methodDeclaration.isConstructor() ? "" : methodDeclaration.getName().getIdentifier(); // if (methodName.equals("allObjectsSorted")) { // System.out.println(); // } StringBuilder sb = new StringBuilder(); sb.append(methodName); sb.append('('); @SuppressWarnings("unchecked") Iterator<SingleVariableDeclaration> parameters = methodDeclaration.parameters().iterator(); while (parameters.hasNext()) { SingleVariableDeclaration parameter = parameters.next(); Type parameterType = parameter.getType(); String typeName = normalizeTypeName(parameterType, parameter.getExtraDimensions(), parameter.isVarargs()); sb.append(typeName); if (parameters.hasNext()) { sb.append(", "); } } sb.append(')'); String methodSignature = sb.toString(); return methodSignature; }
private BlockInfo.Type getBlockType(ASTNode node) { if(node instanceof TypeDeclaration) return BlockInfo.Type.TYPE; else if(node instanceof MethodDeclaration) return BlockInfo.Type.METHOD; else if(node instanceof WhileStatement) return BlockInfo.Type.WHILE; else if(node instanceof ForStatement) return BlockInfo.Type.FOR; else if(node instanceof IfStatement) return BlockInfo.Type.IF; else return BlockInfo.Type.OTHER; }
@Override public boolean visit(MethodDeclaration node) { boolean instanceMember = !node.isConstructor() && !Modifier.isStatic(node.getModifiers()); if(((TypeDeclaration) node.getParent()).isPackageMemberTypeDeclaration()) { AssignmentVisitor v = new AssignmentVisitor(); node.accept(v); if(instanceMember) { MethodInfo m = new MethodInfo( node.getName().getIdentifier(), VisibilityInfo.from(node), node.getReturnType2().resolveBinding().isParameterizedType() ? Object.class.toString() : node.getReturnType2().resolveBinding().getQualifiedName(), v.params, v.containsFieldAssignments); info.addMethod(m); } } return false; }
/** * Collects all top level methods from CompilationUnits. (Embedded Methods are currently not collected.) * * @param compilationUnitToASTNode the mapping of CompilationUnits to preparsed ASTNodes * @return the list of all top level methods within the CompilationUnits */ public static List<MethodDeclaration> scanForMethodDeclarations( Map<ICompilationUnit, ASTNode> compilationUnitToASTNode) { if (compilationUnitToASTNode == null) { throw new CrystalRuntimeException("null map of compilation units to ASTNodes"); } // Create an empty list List<MethodDeclaration> methodList = new LinkedList<MethodDeclaration>(); List<MethodDeclaration> tempMethodList; // Get all CompilationUnits and look for MethodDeclarations in each Set<Entry<ICompilationUnit, ASTNode>> entrySet = compilationUnitToASTNode.entrySet(); Iterator<Entry<ICompilationUnit, ASTNode>> iterator = entrySet.iterator(); while(iterator.hasNext()) { Entry<ICompilationUnit, ASTNode> entry = iterator.next(); ICompilationUnit icu = entry.getKey(); tempMethodList = WorkspaceUtilities.scanForMethodDeclarationsFromAST(compilationUnitToASTNode.get(icu)); methodList.addAll(tempMethodList); } return methodList; }
public static RewriteEvent[] listRewriteHandleGeneratedMethods(RewriteEvent parent) { RewriteEvent[] children = parent.getChildren(); List<RewriteEvent> newChildren = new ArrayList<RewriteEvent>(); List<RewriteEvent> modifiedChildren = new ArrayList<RewriteEvent>(); for (int i = 0; i < children.length; i++) { RewriteEvent child = children[i]; boolean isGenerated = isGenerated((org.eclipse.jdt.core.dom.ASTNode) child.getOriginalValue()); if (isGenerated) { boolean isReplacedOrRemoved = child.getChangeKind() == RewriteEvent.REPLACED || child.getChangeKind() == RewriteEvent.REMOVED; boolean convertingFromMethod = child.getOriginalValue() instanceof org.eclipse.jdt.core.dom.MethodDeclaration; if (isReplacedOrRemoved && convertingFromMethod && child.getNewValue() != null) { modifiedChildren.add(new NodeRewriteEvent(null, child.getNewValue())); } } else { newChildren.add(child); } } // Since Eclipse doesn't honor the "insert at specified location" for already existing members, // we'll just add them last newChildren.addAll(modifiedChildren); return newChildren.toArray(new RewriteEvent[newChildren.size()]); }
private void populateMethodDeclarations(TypeDeclaration declaration){ TypeDeclaration[] nestedTypes = declaration.getTypes(); for (int i = 0; i < nestedTypes.length; i++) { TypeDeclaration nestedType = nestedTypes[i]; populateMethodDeclarations(nestedType); } FieldDeclaration[] fields = declaration.getFields(); for (FieldDeclaration fieldDeclaration : fields) { fieldDeclaration.accept(new HeuristicOwnedVisitor()); } MethodDeclaration[] methods = declaration.getMethods(); for (MethodDeclaration methodDeclaration : methods) { methodDeclaration.accept(new HeuristicOwnedVisitor()); methodDeclaration.accept(new HeuristicOwnedLocalsVisitor()); this.methodDecls.add(methodDeclaration); } }
/** * Method that check the method's body to detect some * connection between them * @author Mariana Azevedo * @since 20/01/2016 * @param firstMethod * @param secondMethod */ private void checkMethodsBody(MethodDeclaration firstMethod, MethodDeclaration secondMethod) { if (firstMethod != null && secondMethod != null){ Block firstMethodBody = firstMethod.getBody(); Block secondMethodBody = secondMethod.getBody(); if (firstMethodBody != null && secondMethodBody != null){ for (String attribute : listOfAttributes){ if (firstMethodBody.toString().contains(attribute) && secondMethodBody.toString().contains(attribute)){ numDirectConnections++; } } } } }
/** * Method to calculate the sum of the complexities of all class methods. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void calculateWeightMethods(CompilationUnit node){ for (Object type : node.types()){ if ((type instanceof TypeDeclaration) && !((TypeDeclaration) type).isInterface()){ List<TypeDeclaration> bodyDeclarationsList = ((TypeDeclaration) type). bodyDeclarations(); Iterator<TypeDeclaration> itBodyDeclaration = bodyDeclarationsList.iterator(); while (itBodyDeclaration.hasNext()){ Object itItem = itBodyDeclaration.next(); if (itItem instanceof MethodDeclaration){ checkStatementsInMethodsDeclaration(itItem); } } this.wmcIndex += this.visitor.getCyclomaticComplexityIndex(); } } }
/*** * Lookup an ast.MethodDeclaration based on className and methodName * * @param qualifiedTypeName * @param methodName * @return ast.MethodDeclaration * * HACK: XXX, also include in the search type of parameters. * Currently the search does not distinguish between C.m and C.m(A) * class C{ * void m(){} * void m(A a){} * } */ public static ast.MethodDeclaration getMethodDeclaration(String qualifiedTypeName, String methodName) { ast.MethodDeclaration methodDeclaration = Adapter.getInstance().getMethodDeclaration(qualifiedTypeName + methodName); if (methodDeclaration != null) return methodDeclaration; // If not found, it may not have been added yet? // XXX. But why not do this once? Collection<ast.MethodDeclaration> allNodes = Adapter.getInstance().getMethodDeclarations(); for (ast.MethodDeclaration md : allNodes) { ast.TypeDeclaration td = md.enclosingType; if (td != null && td.type != null) if (td.type.getFullyQualifiedName().equals(qualifiedTypeName)) if (md.methodName.equals(methodName)) { Adapter.getInstance().mapMethodDeclaration(md); return md; } } return null; }
/** * Method to get the number of methods with indirect connections. * @author Mariana Azevedo * @since 13/07/2014 * @param methodsWithDirectConn * @param itMethods */ private void getNumberOfIndirectConnections(List<MethodDeclaration> methodsWithDirectConn, Iterator<MethodDeclaration> itMethods){ int i=0; while (itMethods.hasNext()){ MethodDeclaration firstMethod = itMethods.next(); if (firstMethod != null){ Block firstMethodBody = firstMethod.getBody(); if (firstMethodBody != null){ SimpleName methodDeclaration = methodsWithDirectConn.get(i).getName(); if (firstMethodBody.toString().contains(methodDeclaration.toString())){ numIndirectConnections++; } } } } }
public static IJavaElement getIJavaElement(ASTNode node){ IJavaElement javaElement = null; // Find IJavaElement corresponding to the ASTNode if (node instanceof MethodDeclaration) { javaElement = ((MethodDeclaration) node).resolveBinding() .getJavaElement(); } else if (node instanceof VariableDeclaration) { javaElement = ((VariableDeclaration) node).resolveBinding() .getJavaElement(); }else if(node instanceof TypeDeclaration){ javaElement = ((TypeDeclaration)node).resolveBinding() .getJavaElement(); }else if(node instanceof ClassInstanceCreation){ javaElement = ((ClassInstanceCreation)node).resolveConstructorBinding().getJavaElement(); } return javaElement; }
public void addBuilderMethodToCompilationUnit(CompilationUnitModificationDomain modificationDomain, TypeDeclaration builderType, StagedBuilderProperties currentStage) { AST ast = modificationDomain.getAst(); ListRewrite listRewrite = modificationDomain.getListRewrite(); BuilderField firstField = currentStage.getNamedVariableDeclarationField().get(0); StagedBuilderProperties nextStage = currentStage.getNextStage().orElse(currentStage); MethodDeclaration staticWithMethod = stagedBuilderWithMethodDefiniationCreatorFragment.createNewWithMethod(ast, firstField, nextStage); staticWithMethod.modifiers().add(ast.newModifier(ModifierKeyword.STATIC_KEYWORD)); String parameterName = firstField.getBuilderFieldName(); String withMethodName = staticWithMethod.getName().toString(); Block block = newBuilderAndWithMethodCallCreationFragment.createReturnBlock(ast, builderType, withMethodName, parameterName); javadocAdder.addJavadocForWithBuilderMethod(ast, builderType.getName().toString(), parameterName, staticWithMethod); staticWithMethod.setBody(block); listRewrite.insertLast(staticWithMethod, null); }
/** * returns the method Parameters as a list of ast.VariableDeclarataion * */ public static List<ast.VariableDeclaration> getMethodParameters(MethodDeclaration md) { List<ast.VariableDeclaration> params = new ArrayList<ast.VariableDeclaration>(); IMethodBinding methodBinding = md.resolveBinding(); if(methodBinding != null ) { ITypeBinding[] typeParameters = methodBinding.getTypeParameters(); List<SingleVariableDeclaration> svdList = md.parameters(); for (SingleVariableDeclaration svd : svdList) { ast.Type type = getType(svd.getType().resolveBinding()); ast.VariableDeclaration vd = VariableDeclaration.createFrom(svd); vd.varType = type; vd.varName = svd.getName().getFullyQualifiedName(); params.add(vd); } } return params; }
public static IBinding getEnclosingDeclaration(ASTNode node) { while(node != null) { if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration)node).resolveBinding(); } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration)node).resolveBinding(); } else if (node instanceof MethodDeclaration) { return ((MethodDeclaration)node).resolveBinding(); } else if (node instanceof FieldDeclaration) { List<?> fragments= ((FieldDeclaration)node).fragments(); if (fragments.size() > 0) { return ((VariableDeclarationFragment)fragments.get(0)).resolveBinding(); } } else if (node instanceof VariableDeclarationFragment) { IVariableBinding variableBinding= ((VariableDeclarationFragment)node).resolveBinding(); if (variableBinding.getDeclaringMethod() != null || variableBinding.getDeclaringClass() != null) { return variableBinding; // workaround for incomplete wiring of DOM bindings: keep searching when variableBinding is unparented } } node= node.getParent(); } return null; }
/** * Adds <code>@Override</code> annotation to <code>methodDecl</code> if not already present and * if requested by code style settings or compiler errors/warnings settings. * * @param settings the code generation style settings, may be <code>null</code> * @param project the Java project used to access the compiler settings * @param rewrite the ASTRewrite * @param imports the ImportRewrite * @param methodDecl the method declaration to add the annotation to * @param isDeclaringTypeInterface <code>true</code> if the type declaring the method overridden * by <code>methodDecl</code> is an interface * @param group the text edit group, may be <code>null</code> */ public static void addOverrideAnnotation(CodeGenerationSettings settings, IJavaProject project, ASTRewrite rewrite, ImportRewrite imports, MethodDeclaration methodDecl, boolean isDeclaringTypeInterface, TextEditGroup group) { if (!JavaModelUtil.is50OrHigher(project)) { return; } if (isDeclaringTypeInterface) { String version= project.getOption(JavaCore.COMPILER_COMPLIANCE, true); if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6)) { return; // not allowed in 1.5 } if (JavaCore.DISABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true))) { return; // user doesn't want to use 1.6 style } } if ((settings != null && settings.overrideAnnotation) || !JavaCore.IGNORE.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION, true))) { createOverrideAnnotation(rewrite, imports, methodDecl, group); } }
/** * @param md * @param i * @return */ private int beginAnalysisLoop(MethodDeclaration md, int i) { while (isChanged) { System.out.println("BEGIN " + i++ + " PASS"); System.out.println("=================="); warnings.clear(); FlowGraph fg = null; if (Config.HANDLE_LENT_UNIQUE) fg = resultContext.getFG().propagateAll(); OOGContext oldContext = new OOGContext(hierarchy, resultContext.getG().clone(), fg != null? fg.clone() : null); //System.out.println(fg.print()); OOGContext newContext = doAccept(md, new OOGContext(hierarchy, resultContext.getG(), fg)); if (aliasTF.getLatticeOperations().atLeastAsPrecise(newContext, oldContext, md)) isChanged = false; } return i; }
/** * returns all method declarations in a type, and its supertype recursively. * call MethodDeclaration.getBody() to get the body of the method. TODO: * actual/formal substitution * */ public static Set<MethodDeclaration> mBody(TypeDeclaration typeDecl, TypeHierarchy hierarchy, Map<ast.Type, TypeDeclaration> types, QualifiedClassName cThis) { Set<MethodDeclaration> returnSet = new HashSet<MethodDeclaration>(); for (MethodDeclaration md : typeDecl.getMethods()) { returnSet.add(md); } Type superclassType = typeDecl.getSuperclassType(); if (superclassType == null) return returnSet; if (superclassType.resolveBinding().getQualifiedName().equals(Utils.JAVA_LANG_OBJECT)) return returnSet; TypeDeclaration superTypeDecl = types.get(new QualifiedClassName(superclassType.resolveBinding(), cThis) .getType()); if (superTypeDecl != null) { Set<MethodDeclaration> auxSet = mBody(superTypeDecl, hierarchy, types, cThis); returnSet.addAll(auxSet); // TODO: here you don't want to add OverrideMethod // TODO: find a way to uniquely identify methods: define mtype. } return returnSet; }
private void initializeDestinations() { List<ASTNode> result = new ArrayList<>(); BodyDeclaration decl = fAnalyzer.getEnclosingBodyDeclaration(); ASTNode current = ASTResolving.findParentType(decl.getParent()); if (fAnalyzer.isValidDestination(current)) { result.add(current); } if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding = ASTNodes.getEnclosingType(current); ASTNode next = ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { if (fAnalyzer.isValidDestination(next)) { result.add(next); } current = next; binding = ASTNodes.getEnclosingType(current); next = ASTResolving.findParentType(next.getParent()); } } fDestinations = result.toArray(new ASTNode[result.size()]); fDestination = fDestinations[fDestinationIndex]; }
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<CUCorrectionProposal> proposals) throws JavaModelException { CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof ReturnStatement)) { return; } ReturnStatement returnStatement= (ReturnStatement) selectedNode; Expression expression= returnStatement.getExpression(); if (expression == null) { return; } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methDecl= (MethodDeclaration) decl; Type retType= methDecl.getReturnType2(); if (retType == null || retType.resolveBinding() == null) { return; } TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals); } }
/** * Returns true iff 'methodDeclaration' represents a void static method named 'main' that takes a * single String[] parameter. */ private static boolean isMainMethod(MethodDeclaration methodDeclaration) { // Is it static? if ((methodDeclaration.getModifiers() & Modifier.STATIC) == 0) { return false; } // Does it return void? Type returnType = methodDeclaration.getReturnType2(); if (!returnType.isPrimitiveType()) { return false; } if (((PrimitiveType) returnType).getPrimitiveTypeCode() != PrimitiveType.VOID) { return false; } // Is it called 'main'? if (!"main".equals(methodDeclaration.getName().getIdentifier())) { return false; } // Does it have a single parameter? if (methodDeclaration.parameters().size() != 1) { return false; } // Is the parameter's type String[]? SingleVariableDeclaration pt = getOnlyElement((List<SingleVariableDeclaration>) methodDeclaration.parameters()); IVariableBinding vb = pt.resolveBinding(); if (vb == null) { return false; } ITypeBinding tb = vb.getType(); return tb != null && "java.lang.String[]".equals(tb.getQualifiedName()); }
@Override public DSubTree handle() { DSubTree tree = new DSubTree(); // add the expression's subtree (e.g: foo(..).bar() should handle foo(..) first) DSubTree Texp = new DOMExpression(invocation.getExpression()).handle(); tree.addNodes(Texp.getNodes()); // evaluate arguments first for (Object o : invocation.arguments()) { DSubTree Targ = new DOMExpression((Expression) o).handle(); tree.addNodes(Targ.getNodes()); } IMethodBinding binding = invocation.resolveMethodBinding(); // get to the generic declaration, if this binding is an instantiation while (binding != null && binding.getMethodDeclaration() != binding) binding = binding.getMethodDeclaration(); MethodDeclaration localMethod = Utils.checkAndGetLocalMethod(binding); if (localMethod != null) { Stack<MethodDeclaration> callStack = Visitor.V().callStack; if (! callStack.contains(localMethod)) { callStack.push(localMethod); DSubTree Tmethod = new DOMMethodDeclaration(localMethod).handle(); callStack.pop(); tree.addNodes(Tmethod.getNodes()); } } else if (Utils.isRelevantCall(binding)) tree.addNode(new DAPICall(binding, Visitor.V().getLineNumber(invocation))); return tree; }
public MethodModel get(MethodDeclaration methodDeclaration) { if (isTestMethod(methodDeclaration)) { return new TestMethodModel(nodeFactory, methodDeclaration); } else if (annotatedWith(methodDeclaration, "Before").isPresent()) { return new FixtureMethodModel(nodeFactory, methodDeclaration, "setup"); } else if (annotatedWith(methodDeclaration, "BeforeClass").isPresent()) { return new FixtureMethodModel(nodeFactory, methodDeclaration, "setupSpec"); } else if (annotatedWith(methodDeclaration, "After").isPresent()) { return new FixtureMethodModel(nodeFactory, methodDeclaration, "cleanup"); } else if (annotatedWith(methodDeclaration, "AfterClass").isPresent()) { return new FixtureMethodModel(nodeFactory, methodDeclaration, "cleanupSpec"); } else { return new RegularMethodModel(nodeFactory, methodDeclaration); } }
MethodModel(ASTNodeFactory astNodeFactory, MethodDeclaration methodDeclaration) { this.astNodeFactory = astNodeFactory; this.methodDeclaration = methodDeclaration; groovism = provide(); if (methodDeclaration.getBody() != null && methodDeclaration.getBody().statements() != null) { methodDeclaration.getBody().statements().forEach(statement -> body.add(wrap(statement, 1, methodType()))); } }
private void addThrownSupport(MethodDeclaration methodDeclaration) { Optional<Annotation> testAnnotation = annotatedWith(methodDeclaration, "Test"); Optional<Expression> expected = testAnnotation .filter(annotation -> annotation instanceof NormalAnnotation) .flatMap(this::expectedException); expected.ifPresent(expression -> body() .add(astNodeFactory().methodInvocation(THROWN, singletonList(astNodeFactory().simpleName(((TypeLiteral) expression).getType().toString()))))); }
FixtureMethodModel(ASTNodeFactory nodeFactory, MethodDeclaration methodDeclaration, String fixtureMethodName) { super(nodeFactory, methodDeclaration); this.fixtureMethodName = fixtureMethodName; methodType().applyFeaturesToStatements(body()); }
public static void extractParametersAndReturnType(SDModel model, MethodDeclaration methodDeclaration, RastNode method) { Type returnType = methodDeclaration.getReturnType2(); if (returnType != null) { model.setReturnType(method, AstUtils.normalizeTypeName(returnType, methodDeclaration.getExtraDimensions(), false)); } else { model.setReturnType(method, null); } Iterator<SingleVariableDeclaration> parameters = methodDeclaration.parameters().iterator(); while (parameters.hasNext()) { SingleVariableDeclaration parameter = parameters.next(); Type parameterType = parameter.getType(); String typeName = AstUtils.normalizeTypeName(parameterType, parameter.getExtraDimensions(), parameter.isVarargs()); model.addParameter(method, parameter.getName().getIdentifier(), typeName); } }
public static void extractParametersAndReturnType(MethodDeclaration methodDeclaration, SDMethod method) { Type returnType = methodDeclaration.getReturnType2(); if (returnType != null) { method.setReturnType(AstUtils.normalizeTypeName(returnType, methodDeclaration.getExtraDimensions(), false)); } else { method.setReturnType(null); } Iterator<SingleVariableDeclaration> parameters = methodDeclaration.parameters().iterator(); while (parameters.hasNext()) { SingleVariableDeclaration parameter = parameters.next(); Type parameterType = parameter.getType(); String typeName = AstUtils.normalizeTypeName(parameterType, parameter.getExtraDimensions(), parameter.isVarargs()); method.addParameter(parameter.getName().getIdentifier(), typeName); } }
@Override public boolean visit(Block node) { if(!isLoopStatement(node)) { ASTNode parent = node.getParent(); current = createBlock(parent); if(parent instanceof MethodDeclaration) handleMethodParams((MethodDeclaration) parent); } return true; }
private void handleMethodParams(MethodDeclaration node) { current.setId(node.getName().toString()); List<?> parameters = node.parameters(); for(int i = 0; i < parameters.size(); i++) { SingleVariableDeclaration var = (SingleVariableDeclaration) parameters.get(i); current.addVar(var.getName().getIdentifier(), i, false); } }
/** * @param md * @return */ public static boolean isMainMethod(MethodDeclaration md) { IMethodBinding resolveBinding = md.resolveBinding(); if (resolveBinding == null) return false; ITypeBinding declClassBinding = resolveBinding.getDeclaringClass(); if (declClassBinding == null) return false; String declaringClass = declClassBinding.getQualifiedName(); SimpleName name = md.getName(); if (name == null) return false; String mName = name.toString(); return declaringClass.equals(MAINCLASS) && mName.equals(MAINMETHOD); }
private int findConstructorInsertIndex(List<BodyDeclaration> decls) { int nDecls= decls.size(); int lastMethod= 0; for (int i= nDecls - 1; i >= 0; i--) { BodyDeclaration curr= decls.get(i); if (curr instanceof MethodDeclaration) { if (((MethodDeclaration) curr).isConstructor()) { return i + 1; } lastMethod= i; } } return lastMethod; }
private boolean visitInterface(TypeDeclaration node) { InterfaceInfo interfaceInfo = new InterfaceInfo(); interfaceInfo.name = node.getName().getFullyQualifiedName(); interfaceInfo.fullName = NameResolver.getFullName(node); interfaceInfo.visibility = getVisibility(node); List<Type> superInterfaceList = node.superInterfaceTypes(); for (Type superInterface : superInterfaceList) interfaceInfo.superInterfaceTypeList.add(NameResolver.getFullName(superInterface)); if (node.getJavadoc() != null) interfaceInfo.comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength()); interfaceInfo.content = sourceContent.substring(node.getStartPosition(), node.getStartPosition() + node.getLength()); elementInfoPool.interfaceInfoMap.put(interfaceInfo.fullName, interfaceInfo); MethodDeclaration[] methodDeclarations = node.getMethods(); for (MethodDeclaration methodDeclaration : methodDeclarations) { MethodInfo methodInfo = createMethodInfo(methodDeclaration, interfaceInfo.fullName); elementInfoPool.methodInfoMap.put(methodInfo.hashName(), methodInfo); } FieldDeclaration[] fieldDeclarations = node.getFields(); for (FieldDeclaration fieldDeclaration : fieldDeclarations) { List<FieldInfo> fieldInfos = createFieldInfos(fieldDeclaration, interfaceInfo.fullName); for (FieldInfo fieldInfo : fieldInfos) elementInfoPool.fieldInfoMap.put(fieldInfo.hashName(), fieldInfo); } return true; }
private boolean visitClass(TypeDeclaration node) { ClassInfo classInfo = new ClassInfo(); classInfo.name = node.getName().getFullyQualifiedName(); classInfo.fullName = NameResolver.getFullName(node); classInfo.visibility = getVisibility(node); classInfo.isAbstract = isAbstract(node); classInfo.isFinal = isFinal(node); classInfo.superClassType = node.getSuperclassType() == null ? "java.lang.Object" : NameResolver.getFullName(node.getSuperclassType()); List<Type> superInterfaceList = node.superInterfaceTypes(); for (Type superInterface : superInterfaceList) classInfo.superInterfaceTypeList.add(NameResolver.getFullName(superInterface)); if (node.getJavadoc() != null) classInfo.comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength()); classInfo.content = sourceContent.substring(node.getStartPosition(), node.getStartPosition() + node.getLength()); elementInfoPool.classInfoMap.put(classInfo.fullName, classInfo); MethodDeclaration[] methodDeclarations = node.getMethods(); for (MethodDeclaration methodDeclaration : methodDeclarations) { MethodInfo methodInfo = createMethodInfo(methodDeclaration, classInfo.fullName); elementInfoPool.methodInfoMap.put(methodInfo.hashName(), methodInfo); } FieldDeclaration[] fieldDeclarations = node.getFields(); for (FieldDeclaration fieldDeclaration : fieldDeclarations) { List<FieldInfo> fieldInfos = createFieldInfos(fieldDeclaration, classInfo.fullName); for (FieldInfo fieldInfo : fieldInfos) elementInfoPool.fieldInfoMap.put(fieldInfo.hashName(), fieldInfo); } return true; }
private MethodDeclaration getMethodDeclaration(ASTNode rs) { ASTNode parent = rs.getParent(); if (parent instanceof MethodDeclaration) return (MethodDeclaration) parent; else return getMethodDeclaration(parent); }