@Override public boolean visit(MethodInvocation node) { String mName = node.getName().getFullyQualifiedName().toString(); Expression e = node.getExpression(); String typName = ""; if (e instanceof StringLiteral) { typName = "string"; } else if (e instanceof FieldAccess) { FieldAccess field = (FieldAccess) e; typName = field.getName().getFullyQualifiedName(); } else if (e instanceof Name) { typName = ((Name) e).getFullyQualifiedName(); if (varTypMap.containsKey(typName)) { typName = varTypMap.get(typName); } } else { if (e != null) { typName = e.toString(); if (typName.contains(".")) typName = typName.substring(0, typName.indexOf('.', 0)); if (varTypMap.containsKey(typName)) typName = varTypMap.get(typName); } } String key = typName + "->" + mName; if (freqRecord.containsKey(key)) { freqRecord.put(key, freqRecord.get(key) + 1); } else { freqRecord.put(key, 1); } return super.visit(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; }
private String getTarget(Expression expression) { String target = ""; if (expression != null) { target = expression.toString().trim(); if (target.isEmpty() || target.equals("this")) { return "this"; } if (!target.isEmpty() && !isValidIdentifier(target)) { return ""; } } return target; }
/* * Visit the AST expression and get the ParseTree Expression. * This is used by the individual visits when parsing a tree. * It passes to the top method (createExpression), which can * handle the InvalidExpressionException. * * If any visit doesn't return an expression, then an invalid * expression exception will be thrown to indicate this. If the * incoming expression is <code>null</code>, then return of <code>null</code> is ok because * this would be for an optional expression which didn't exist. * * @return The new ParseTree Expression or <code>null</code> if incoming expression was null. * * @see createExpression(org.eclipse.jdt.core.dom.Expression) * @exception InvalidExpressionException * @since 1.0.0 */ protected final PTExpression perform(Expression astExpression) { if (astExpression != null) { expression = null; astExpression.accept(this); if (expression == null) throw new InvalidExpressionException( MessageFormat.format( WorkbenchUtilityMessages.ParseTreeCreationFromAST_ExpressionTooComplicated_EXC_, new Object[] {astExpression.toString()})); return expression; } else return null; // This is ok. It means an optional expression was being processed and the // expression didn't exist. }
private String getValue(Expression value, ASTNode astNode, final JstType jstType) { if (value == null) { return null; } String v = null; if (value instanceof QualifiedName) { v = getValue((QualifiedName) value, astNode, jstType); } else if (value instanceof StringLiteral) { v = ((StringLiteral) value).getLiteralValue(); } else { v = value.toString(); } return v; }
/** * Process the AST Expression and return a PTExpression. If any part was invalid, then only an * PTInvalidExpression will be returned. * * @param astExpression * @return The PTExpression. * @since 1.0.0 */ public final PTExpression createExpression(Expression astExpression) { try { return perform(astExpression); } catch (InvalidExpressionException e) { // Create a msg that is formed of the exception message and the full init string. String msg = MessageFormat.format( WorkbenchUtilityMessages.ParseTreeCreationFromAST_0, new Object[] {e.getLocalizedMessage(), astExpression.toString()}); PTInvalidExpression exp = InstantiationFactory.eINSTANCE.createPTInvalidExpression(); exp.setMessage(msg); return exp; } }
private Example makeExample( MethodDeclaration node, Set<? extends Expression> envolvedInvocations, List<ApiMethod> envolvedApiMethods) { // Visitor responsável por realizar o slicing de programas SlicingStatementVisitor visitor = new SlicingStatementVisitor(node, new HashSet<ASTNode>(envolvedInvocations)); node.accept(visitor); Collection<Statement> relatedStatements = visitor.getSlicedStatements(); ASTNode newAST = ASTUtil.copyStatements(node.getBody(), relatedStatements, AST.newAST(AST.JLS3)); if (!relatedStatements.isEmpty()) { LOGGER.error("Some statements were not included!"); } if (newAST == null) { LOGGER.error("Slicing process failed for node "); // TODO Se AST retornada for nula é porque faltou incluir statement(s) return null; } else if (((Block) newAST).statements().isEmpty()) { LOGGER.error("Slicing process failed for node "); // TODO Se o Block retornado for vazio é porque faltou incluir statement(s) return null; } ASTUtil.removeEmptyBlocks((Block) newAST); // Adiciona declarações de variáveis que não foram encontradas no escopo do método // Para facilitar, tipos iguais são declarados no mesmo Statement Set<String> additionalDeclarationLines = new HashSet<String>(); Map<ITypeBinding, List<IVariableBinding>> typesMap = new HashMap<ITypeBinding, List<IVariableBinding>>(); for (IVariableBinding ivb : visitor.getUndiscoveredDeclarations()) { if (!typesMap.containsKey(ivb.getType())) { typesMap.put(ivb.getType(), new ArrayList<IVariableBinding>(2)); } typesMap.get(ivb.getType()).add(ivb); } for (ITypeBinding typeBinding : typesMap.keySet()) { List<IVariableBinding> variableBindings = typesMap.get(typeBinding); Stack<VariableDeclarationFragment> fragments = new Stack<VariableDeclarationFragment>(); for (IVariableBinding ivb : variableBindings) { VariableDeclarationFragment declarationFragment = newAST.getAST().newVariableDeclarationFragment(); declarationFragment.setName(newAST.getAST().newSimpleName(ivb.getName())); fragments.add(declarationFragment); } VariableDeclarationStatement statement = newAST.getAST().newVariableDeclarationStatement(fragments.pop()); while (!fragments.isEmpty()) { statement.fragments().add(fragments.pop()); } statement.setType(this.getType(typeBinding, newAST.getAST())); additionalDeclarationLines.add(statement.toString()); ((Block) newAST).statements().add(0, statement); } Example example = new Example(); example.setAttachment(this.attachmentMap.get(node.getRoot())); example.setApiMethods(new HashSet<ApiElement>(envolvedApiMethods)); example.setImports(visitor.getImports()); for (Expression seed : envolvedInvocations) { example.getSeeds().add(seed.toString()); } example.setSourceMethod(node.toString()); example.setAddedAt(new Date(System.currentTimeMillis())); try { IMethodBinding nodeBinding = node.resolveBinding(); if (!this.methodMap.containsKey(nodeBinding)) { ApiClass newApiClass = new ApiClass(nodeBinding.getDeclaringClass().getQualifiedName()); methodDeclarationHandler(node, newApiClass); } example.setSourceMethodCall(this.methodMap.get(nodeBinding).getFullName()); } catch (Exception e) { LOGGER.error(e); if (example.getSourceMethodCall() == null) { example.setSourceMethodCall("?"); } } String codeExample = newAST.toString(); for (String line : additionalDeclarationLines) { codeExample = codeExample.replace( line, line.replace("\n", "").concat(" ").concat("//initialized previously").concat("\n")); } // FIXME codeExample = codeExample.replaceAll("(\\{\n)(\\s+)(\\})", "$1 //do something \n$3"); try { example.setCodeExample(codeExample); example.setFormattedCodeExample(ASTUtil.codeFormatter(codeExample)); } catch (Exception e) { LOGGER.error(e); if (example.getFormattedCodeExample() == null) { example.setFormattedCodeExample(codeExample); } } // TODO Obter métricas do exemplo example .getMetrics() .put(ExampleMetric.LOC.name(), example.getFormattedCodeExample().split("\n").length - 1); example.getMetrics().put(ExampleMetric.ARGUMENTS.name(), visitor.getNumberOfArguments()); example .getMetrics() .put(ExampleMetric.DECISION_STATEMENTS.name(), visitor.getNumberOfDecisionStatements()); example.getMetrics().put(ExampleMetric.INVOCATIONS.name(), visitor.getNumberOfInvocations()); example .getMetrics() .put(ExampleMetric.NULL_ARGUMENTS.name(), visitor.getNumberOfNullArguments()); example .getMetrics() .put(ExampleMetric.PRIMITIVE_ARGUMENTS.name(), visitor.getNumberOfPrimitiveArguments()); example .getMetrics() .put(ExampleMetric.FIELD_ARGUMENTS.name(), visitor.getNumberOfFieldArguments()); example .getMetrics() .put( ExampleMetric.UNDISCOVERED_DECLARATIONS.name(), visitor.getNumberOfUndiscoveredDeclarations()); example .getMetrics() .put(ExampleMetric.UNHANDLED_EXCEPTIONS.name(), visitor.getNumberOfUnhandledExceptions()); return example; }
/** * @return a string representation of the matching case expression, or "default" for the default * case. */ public String getLabel() { if (matchExpression == null) return "default"; else return matchExpression.toString(); }