@SuppressWarnings("unchecked") private void createUnobservedInitStmt(final int logRecNo, final Block methodBlock, final AST ast) { // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = this.log.objectIds.get(logRecNo); final String type = this.log.oidClassNames.get(this.log.oidRecMapping.get(oid)); final Object value = this.log.params.get(logRecNo)[0]; this.isXStreamNeeded = true; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); // handling because there must always be a new instantiation statement for pseudo inits this.oidToVarMapping.remove(oid); vd.setName(ast.newSimpleName(this.createNewVarName(oid, type))); final MethodInvocation methodInvocation = ast.newMethodInvocation(); final Name name = ast.newSimpleName("XSTREAM"); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("fromXML")); final StringLiteral xmlParam = ast.newStringLiteral(); xmlParam.setLiteralValue((String) value); methodInvocation.arguments().add(xmlParam); final CastExpression castExpr = ast.newCastExpression(); castExpr.setType(this.createAstType(type, ast)); castExpr.setExpression(methodInvocation); vd.setInitializer(castExpr); final VariableDeclarationStatement vs = ast.newVariableDeclarationStatement(vd); vs.setType(this.createAstType(type, ast)); methodBlock.statements().add(vs); }
private VariableDeclarationStatement createDeclaration( IVariableBinding binding, Expression intilizer) { VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration()); VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment(); fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName())); fragment.setInitializer(intilizer); VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment); result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original))); result.setType( ASTNodeFactory.newType( fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter))); return result; }
@SuppressWarnings("unchecked") @Override public void createUnobservedInitStmt(CaptureLog log, int logRecNo) { PostProcessor.notifyRecentlyProcessedLogRecNo(logRecNo); // NOTE: PLAIN INIT: has always one non-null param // TODO: use primitives final int oid = log.objectIds.get(logRecNo); // final String type = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Object value = log.params.get(logRecNo)[0]; this.isXStreamNeeded = true; final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); // handling because there must always be a new instantiation statement for pseudo inits this.oidToVarMapping.remove(oid); vd.setName(ast.newSimpleName(this.createNewVarName(oid, log.oidClassNames.get(log.oidRecMapping.get(oid)), true))); final MethodInvocation methodInvocation = ast.newMethodInvocation(); final Name name = ast.newSimpleName("XSTREAM"); methodInvocation.setExpression(name); methodInvocation.setName(ast.newSimpleName("fromXML")); final StringLiteral xmlParam = ast.newStringLiteral(); xmlParam.setLiteralValue((String) value); methodInvocation.arguments().add(xmlParam); // final CastExpression castExpr = ast.newCastExpression(); // castExpr.setType(this.createAstType(type, ast)); // castExpr.setExpression(methodInvocation); // vd.setInitializer(castExpr); vd.setInitializer(methodInvocation); final VariableDeclarationStatement vs = ast.newVariableDeclarationStatement(vd); vs.setType(this.createAstType("Object", ast)); methodBlock.statements().add(vs); }
public VariableDeclarationStatement variableDeclarationStatement(String name, Type type, Expression initializer) { VariableDeclarationFragment variableDeclarationFragment = variableDeclarationFragment(name); variableDeclarationFragment.setInitializer(initializer); VariableDeclarationStatement statement = ast.get().newVariableDeclarationStatement(variableDeclarationFragment); statement.setType(type); return statement; }
@Override public boolean visit(FieldDeclaration fieldDeclaration) { Type fieldType = fieldDeclaration.getType(); int fieldModifiers = fieldDeclaration.getModifiers(); Visibility visibility = getVisibility(fieldModifiers); // boolean isFinal = (fieldModifiers & Modifier.FINAL) != 0; boolean isStatic = (fieldModifiers & Modifier.STATIC) != 0; List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments(); for (VariableDeclarationFragment fragment : fragments) { String fieldName = fragment.getName().getIdentifier(); final SDAttribute attribute = model.createAttribute(fieldName, containerStack.peek()); attribute.setStatic(isStatic); attribute.setVisibility(visibility); attribute.setType(AstUtils.normalizeTypeName(fieldType, fragment.getExtraDimensions(), false)); Expression expression = fragment.getInitializer(); if (expression != null) { //attribute.setAssignment(srbForAttributes.buildSourceRepresentation(fileContent, expression.getStartPosition(), expression.getLength())); addClientCode(attribute.key().toString(), srbForAttributes.buildPartialSourceRepresentation(fileContent, expression)); } attribute.setClientCode(srbForAttributes.buildEmptySourceRepresentation()); } return true; }
public boolean visit(VariableDeclarationStatement vds) { if (mtbStack.isEmpty()) // not part of a method return true; // make local variable declaration for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) ovdf; try { facts.add(Fact.makeLocalVarFact(getQualifiedName(mtbStack .peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception e) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) { if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) { // e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ... return false; } if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY || locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.MESSAGE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == SwitchStatement.EXPRESSION_PROPERTY || locationInParent == SwitchCase.EXPRESSION_PROPERTY || locationInParent == ArrayAccess.INDEX_PROPERTY || locationInParent == ThrowStatement.EXPRESSION_PROPERTY || locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY || locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { return false; } return true; }
private VariableDeclarationStatement createDeclaration(IVariableBinding binding, Expression intilizer) { VariableDeclaration original = ASTNodes.findVariableDeclaration(binding, fAnalyzer.getEnclosingBodyDeclaration()); VariableDeclarationFragment fragment = fAST.newVariableDeclarationFragment(); fragment.setName((SimpleName) ASTNode.copySubtree(fAST, original.getName())); fragment.setInitializer(intilizer); VariableDeclarationStatement result = fAST.newVariableDeclarationStatement(fragment); result.modifiers().addAll(ASTNode.copySubtrees(fAST, ASTNodes.getModifiers(original))); result.setType(ASTNodeFactory.newType(fAST, original, fImportRewriter, new ContextSensitiveImportRewriteContext(original, fImportRewriter))); return result; }
@Override public boolean visit(FieldDeclaration node) { int modifiers = node.getModifiers(); if (Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers)) { List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment varDeclFrag : fragments) { IVariableBinding varBinding = varDeclFrag.resolveBinding(); String enclosingClass = varBinding.getDeclaringClass().getQualifiedName(); if(!varBinding.getType().isPrimitive() && !varBinding.getType().getQualifiedName().equals("java.lang.String")){ final TACVariable fieldVar = new TACVariable(varBinding); if(!enclosingClass.equals(Config.MAINCLASS)){ context.addEncapsulatedVariable(fieldVar); } } } } return super.visit(node); }
@Override public boolean visit(VariableDeclarationFragment param) { ASTNode parent = param.getParent(); if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement statement = (VariableDeclarationStatement) parent; ASTNode annotation = getAnnotation(statement.modifiers(), "Domain"); if (annotation != null) { ListRewrite paramRewrite = rewrite.getListRewrite(statement, VariableDeclarationStatement.MODIFIERS2_PROPERTY); paramRewrite.remove(annotation, null); } } return super.visit(param); }
private static boolean hasFieldInitializers(TypeDeclaration typeDecl) { boolean returnFlag = false; for (FieldDeclaration fd : typeDecl.getFields()) { // Skip over primitive types if (fd.getType().isPrimitiveType() ) { continue; } if (fd.fragments().size() > 0) if (fd.fragments().get(0) instanceof VariableDeclarationFragment) { VariableDeclarationFragment vdf = (VariableDeclarationFragment) fd.fragments().get(0); if (vdf.getInitializer() != null) returnFlag = true; } } return returnFlag; }
@Override public boolean visit(VariableDeclarationFragment node) { if (isDeclarationTarget(DeclarationType.FIELD_DECLARATION)) { IVariableBinding variableBinding = node.resolveBinding(); if (variableBinding != null) { if (variableBinding.isField()) { variableFound = variableBinding.getName(); if (matchTypeDeclaration() && TraceUtility .match(variableToFind, variableFound)) { TraceUtility.selectInEditor(node); setEnclosingDeclaration(node); } } } } return super.visit(node); }
public boolean visit(VariableDeclarationStatement vds) { if (this.mtbStack.isEmpty()) { return true; } for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment)ovdf; try { this.facts.add(Fact.makeLocalVarFact(getQualifiedName( (IMethodBinding)this.mtbStack.peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception e) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
public boolean visit(VariableDeclarationStatement vds) { if (this.mtbStack.isEmpty()) { return true; } for (Object ovdf : vds.fragments()) { VariableDeclarationFragment vdf = (VariableDeclarationFragment)ovdf; try { this.facts.add(Fact.makeLocalVarFact(getQualifiedName( (IMethodBinding)this.mtbStack.peek()), getQualifiedName(vds.getType() .resolveBinding()), vdf.getName().getIdentifier(), vdf .getInitializer().toString())); } catch (Exception localException) { System.err.println("Cannot resolve variable declaration \"" + vdf.getName().toString() + "\""); } } return true; }
private IStatus checkIteratorCondition() { List<Expression> initializers = getForStatement().initializers(); if (initializers.size() != 1) return SEMANTIC_CHANGE_WARNING_STATUS; Expression expression = initializers.get(0); if (!(expression instanceof VariableDeclarationExpression)) return SEMANTIC_CHANGE_WARNING_STATUS; VariableDeclarationExpression declaration = (VariableDeclarationExpression) expression; List<VariableDeclarationFragment> variableDeclarationFragments = declaration.fragments(); if (variableDeclarationFragments.size() != 1) return SEMANTIC_CHANGE_WARNING_STATUS; VariableDeclarationFragment declarationFragment = variableDeclarationFragments.get(0); Expression initializer = declarationFragment.getInitializer(); if (!(initializer instanceof MethodInvocation)) return SEMANTIC_CHANGE_WARNING_STATUS; MethodInvocation methodInvocation = (MethodInvocation) initializer; String methodName = methodInvocation.getName().getIdentifier(); if (!"iterator".equals(methodName) || methodInvocation.arguments().size() != 0) // $NON-NLS-1$ return SEMANTIC_CHANGE_WARNING_STATUS; return StatusInfo.OK_STATUS; }
private void handleSimpleName(SimpleName node) { ASTNode firstExpression = node.getParent(); if (firstExpression instanceof FieldAccess) { while (firstExpression instanceof FieldAccess) { firstExpression = ((FieldAccess) firstExpression).getExpression(); } if (!(firstExpression instanceof SimpleName)) return; node = (SimpleName) firstExpression; } else if (firstExpression instanceof SuperFieldAccess) return; StructuralPropertyDescriptor parentDescription = node.getLocationInParent(); if (parentDescription == VariableDeclarationFragment.NAME_PROPERTY || parentDescription == SwitchCase.EXPRESSION_PROPERTY) return; IBinding binding = node.resolveBinding(); if (!(binding instanceof IVariableBinding)) return; handleVariable(node, (IVariableBinding) binding); }
@SuppressWarnings("unchecked") @Override public void createCollectionInitStmt(final CaptureLog log, final int logRecNo) { final int oid = log.objectIds.get(logRecNo); final Object[] params = log.params.get(logRecNo); String collTypeName = log.oidClassNames.get(log.oidRecMapping.get(oid)); final Class<?> collType = getClassForName(collTypeName); final String varName; // -- determine if an alternative collection must be used for code generation final boolean isPrivate = java.lang.reflect.Modifier.isPrivate(collType.getModifiers()); if(isPrivate || ! hasDefaultConstructor(collType)) { if(Set.class.isAssignableFrom(collType)) { collTypeName = HashSet.class.getName(); } else if (List.class.isAssignableFrom(collType)) { collTypeName = ArrayList.class.getName(); } else if(Queue.class.isAssignableFrom(collType)) { collTypeName = ArrayDeque.class.getName(); } else { throw new RuntimeException("Collection " + collType + " is not supported"); } } // -- create code for instantiating collection varName = this.createNewVarName(oid, collTypeName); final VariableDeclarationFragment vd = ast.newVariableDeclarationFragment(); final SimpleName varNameExpr = ast.newSimpleName(varName); vd.setName(varNameExpr); final ClassInstanceCreation ci = ast.newClassInstanceCreation(); ci.setType(this.createAstType(collTypeName, ast)); vd.setInitializer(ci); final VariableDeclarationStatement stmt = ast.newVariableDeclarationStatement(vd); stmt.setType(this.createAstType(collTypeName, ast)); methodBlock.statements().add(stmt); // --- create code for filling the collection Integer paramOID; MethodInvocation mi; for(int i = 0; i < params.length; i++) { mi = ast.newMethodInvocation(); mi.setName(ast.newSimpleName("add")); paramOID = (Integer) params[i]; if(paramOID == null) { mi.arguments().add(ast.newNullLiteral()); } else { mi.arguments().add(ast.newSimpleName(this.oidToVarMapping.get(paramOID))); } methodBlock.statements().add(mi); } }
/** {@inheritDoc} */ @Override public boolean visit(VariableDeclarationFragment node) { SimpleName name = node.getName(); IBinding binding = name.resolveBinding(); if (binding == null) return true; if (fWrittenVariables.containsKey(binding)) return true; ModifierChangeOperation op = createAddFinalOperation(name, node); if (op == null) return true; fResult.add(op); return true; }
/** {@inheritDoc} */ @Override protected void addLinkedPositions( final ASTRewrite rewrite, final VariableDeclarationFragment fragment, final LinkedProposalModel positionGroups) { Assert.isNotNull(rewrite); Assert.isNotNull(fragment); final Expression initializer = fragment.getInitializer(); if (initializer != null) { LinkedProposalPositionGroup group = new LinkedProposalPositionGroup(GROUP_INITIALIZER); group.addPosition(rewrite.track(initializer), true); positionGroups.addPositionGroup(group); } }
@Override public void endVisit(VariableDeclarationFragment node) { VariableVariable2 cv = fTCModel.makeDeclaredVariableVariable(node.resolveBinding(), fCU); if (cv == null) return; setConstraintVariable(node, cv); // TODO: prune unused CV for local variables (but not fields) Expression initializer = node.getInitializer(); if (initializer == null) return; ConstraintVariable2 initializerCv = getConstraintVariable(initializer); if (initializerCv == null) return; fTCModel.createElementEqualsConstraints(cv, initializerCv); // name= initializer --> [initializer] <= [name] // if (initializerCv instanceof CollectionElementVariable2) // fTCModel.createSubtypeConstraint(initializerCv, cv); }
private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException { AST ast = fCURewrite.getAST(); VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); vdf.setName(ast.newSimpleName(fTempName)); vdf.setInitializer(initializer); VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf); if (fDeclareFinal) { vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD)); } vds.setType(createTempType()); if (fLinkedProposalModel != null) { ASTRewrite rewrite = fCURewrite.getASTRewrite(); LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true); nameGroup.addPosition(rewrite.track(vdf.getName()), true); String[] nameSuggestions = guessTempNames(); if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) { nameGroup.addProposal(fTempName, null, nameSuggestions.length + 1); } for (int i = 0; i < nameSuggestions.length; i++) { nameGroup.addProposal(nameSuggestions[i], null, nameSuggestions.length - i); } } return vds; }
@Override public boolean visit(VariableDeclarationFragment node) { boolean result = super.visit(node); if (isFirstSelectedNode(node)) { if (node.getParent() instanceof FieldDeclaration) { invalidSelection( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node)); } else { invalidSelection( RefactoringCoreMessages .ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node)); } return false; } return result; }
private Collection<ITypeConstraint> getConstraintsForHiding( VariableDeclarationFragment fragment) { Collection<ITypeConstraint> result = new ArrayList<ITypeConstraint>(); IVariableBinding fieldBinding = fragment.resolveBinding(); Assert.isTrue(fieldBinding.isField()); Set<ITypeBinding> declaringTypes = getDeclaringSuperTypes(fieldBinding); ConstraintVariable hiddingFieldVar = fConstraintVariableFactory.makeDeclaringTypeVariable(fieldBinding); for (Iterator<ITypeBinding> iter = declaringTypes.iterator(); iter.hasNext(); ) { ITypeBinding declaringSuperType = iter.next(); IVariableBinding hiddenField = findField(fieldBinding, declaringSuperType); Assert.isTrue(hiddenField.isField()); ConstraintVariable hiddenFieldVar = fConstraintVariableFactory.makeDeclaringTypeVariable(hiddenField); result.addAll( Arrays.asList( fTypeConstraintFactory.createStrictSubtypeConstraint( hiddingFieldVar, hiddenFieldVar))); } return result; }
private void visitFragment(VariableDeclarationFragment fragment, FieldDeclaration field) { Attribute attribute = importer.ensureAttributeForFragment(fragment, field); importer.createSourceAnchor(attribute, fragment, (CompilationUnit) field.getRoot()); importer.ensureCommentFromBodyDeclaration(attribute, field); /* only the last fragment of a field contains the initializer code. * thus, to create the access to each variable in the fragment we need to ask that last fragment * we do not have to check the existence of that last fragment, because we already know that the field has at least one fragment */ VariableDeclarationFragment lastFragment = (VariableDeclarationFragment) field.fragments().get(field.fragments().size() - 1); if (lastFragment.getInitializer() != null) { Access access = importer.createAccessFromExpression(fragment.getName()); access.setIsWrite(true); importer.createAccessFromExpression((Expression) lastFragment.getInitializer()); } attribute.setIsStub(false); }
/** * Generates a {@link VariableDeclarationExpression}, which initializes the loop variable to * iterate over an array. * * @param ast the current {@link AST} instance * @param loopVariableName the name of the variable which should be initialized * @return a filled {@link VariableDeclarationExpression}, declaring a int variable, which is * initializes with 0 */ private VariableDeclarationExpression getForInitializer(AST ast, SimpleName loopVariableName) { // initializing fragment VariableDeclarationFragment firstDeclarationFragment = ast.newVariableDeclarationFragment(); firstDeclarationFragment.setName(loopVariableName); NumberLiteral startIndex = ast.newNumberLiteral(); firstDeclarationFragment.setInitializer(startIndex); // declaration VariableDeclarationExpression variableDeclaration = ast.newVariableDeclarationExpression(firstDeclarationFragment); PrimitiveType variableType = ast.newPrimitiveType(PrimitiveType.INT); variableDeclaration.setType(variableType); return variableDeclaration; }
/** {@inheritDoc} */ @Override public boolean visit(FieldDeclaration fieldDeclaration) { if (Modifier.isStatic(fieldDeclaration.getModifiers())) { testCase.setCurrentScope(TestScope.STATICFIELDS); } VariableDeclarationFragment varDeclFrgmnt = (VariableDeclarationFragment) fieldDeclaration.fragments().get(0); Expression expression = varDeclFrgmnt.getInitializer(); VariableReference varRef; if (expression == null) { varRef = retrieveDefaultValueAssignment(retrieveTypeClass(varDeclFrgmnt)); } else { varRef = retrieveVariableReference(expression, null); } varRef.setOriginalCode(fieldDeclaration.toString()); // TODO Use the name here as well? // String name = varDeclFrgmt.getName().getIdentifier(); // new BoundVariableReferenceImpl(testCase, varType, name); testCase.addVariable(varDeclFrgmnt.resolveBinding(), varRef); testCase.setCurrentScope(TestScope.FIELDS); return true; }
/** * This is a data dependency if this is a declaration and the * variable being declared is in the right hand side of the * seed assignment expression. */ public boolean visit(VariableDeclarationFragment node){ IBinding binding = node.resolveBinding(); if(binding == null){ if(this.aliases.contains((node.getName().getFullyQualifiedName()))) this.result = true; } else if(binding instanceof IVariableBinding){ /* If this variable is in the alias list, then this statement * is a data dependency. */ if(this.aliases.contains(binding.getKey())){ this.result = true; } } return false; }
private VariableReference retrieveVariableReference( VariableDeclarationFragment varDeclFrgmnt) { IVariableBinding variableBinding = varDeclFrgmnt.resolveBinding(); Class<?> clazz = retrieveTypeClass(variableBinding.getType()); if (clazz.isArray()) { ArrayReference arrayReference = new ValidArrayReference( testCase.getReference(), clazz); arrayReference.setOriginalCode(varDeclFrgmnt.toString()); testCase.addVariable(varDeclFrgmnt.resolveBinding(), arrayReference); return arrayReference; } VariableReference result = new BoundVariableReferenceImpl(testCase, clazz, variableBinding.getName()); testCase.addVariable(variableBinding, result); return result; }
private void handleVarDeclaration(VariableDeclarationFragment var, boolean isField) { String varName = var.getName().getIdentifier(); VariableInfo varInfo = current.addVar(varName, isField); Expression init = var.getInitializer(); if(init instanceof SimpleName) { String initVar = ((SimpleName) init).getIdentifier(); varInfo.addOperation(new VariableOperation(varName, VariableOperation.Type.INIT, initVar)); } }
@Override public boolean visit(VariableDeclarationStatement node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); Scope scope = new Scope(line, getEndLine(node.getParent(), cunit)); VariableTags tags = new VariableTags(varName, null, line, scope, false); variables.add(tags); } return super.visit(node); }
@Override public boolean visit(FieldDeclaration node) { List fragments = node.fragments(); for(Object o : fragments) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; String varName = frag.getName().getIdentifier(); int line = cunit.getLineNumber(frag.getStartPosition()); ASTNode parent = node.getParent(); Scope scope = new Scope(cunit.getLineNumber(parent.getStartPosition()), getEndLine(parent, cunit)); TypeDeclaration dec = (TypeDeclaration) node.getParent(); String qName = dec.getName().getFullyQualifiedName(); PackageDeclaration packageDec = cunit.getPackage(); if(packageDec != null) qName = packageDec.getName().getFullyQualifiedName() + "." + qName; String type = !Modifier.isStatic(node.getModifiers()) ? qName : null; VariableTags tags = new VariableTags(varName, type, line, scope, true); variables.add(tags); } return false; }
@Override public boolean visit(VariableDeclarationStatement node) { List fragments = node.fragments(); VariableDeclarationFragment varDec = (VariableDeclarationFragment) fragments.get(0); System.out.println(varDec.getName().getIdentifier() + " " + node.getParent()); return super.visit(node); }
@Override public boolean visit(TypeDeclaration node) { System.out.println(node.getParent().getClass()); if(info == null) info = new ClassInfo(node.resolveBinding().getQualifiedName(), VisibilityInfo.from(node)); for(FieldDeclaration f : node.getFields()) { if(!Modifier.isStatic(f.getModifiers())) { for(Object o : f.fragments()) { VariableDeclarationFragment frag = (VariableDeclarationFragment) o; info.addField(new FieldInfo(frag.getName().toString())); } } } return true; }
private List<FieldInfo> createFieldInfos(FieldDeclaration node, String belongTo) { List<FieldInfo> fieldInfos = new ArrayList<>(); Type type = node.getType(); Set<String> types = getTypes(type); String typeString = type.toString(); String visibility = getVisibility(node); boolean isStatic = isStatic(node); boolean isFinal = isFinal(node); String comment = ""; if (node.getJavadoc() != null) comment = sourceContent.substring(node.getJavadoc().getStartPosition(), node.getJavadoc().getStartPosition() + node.getJavadoc().getLength()); List<VariableDeclarationFragment> fragments = node.fragments(); for (VariableDeclarationFragment fragment : fragments) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.belongTo = belongTo; fieldInfo.name = fragment.getName().getFullyQualifiedName(); fieldInfo.typeString = typeString; fieldInfo.types = types; fieldInfo.visibility = visibility; fieldInfo.isFinal = isFinal; fieldInfo.isStatic = isStatic; fieldInfo.comment = comment; fieldInfos.add(fieldInfo); } return fieldInfos; }
/** * Method to get class attributes and add them in a list. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void getClassAttributes(CompilationUnit node){ for (Object type : node.types()){ if (type instanceof TypeDeclaration){ FieldDeclaration [] attributes = ((TypeDeclaration) type).getFields(); for (FieldDeclaration attribute: attributes){ List<FieldDeclaration> fragments = attribute.fragments(); Object obj = fragments.get(0); if (obj instanceof VariableDeclarationFragment){ String str = ((VariableDeclarationFragment) obj).getName().toString(); this.listOfAttributes.add(str); } } } } }
/** * Method to get all attributes or fields of a class. * @author Mariana Azevedo * @since 13/07/2014 * @param node */ @SuppressWarnings("unchecked") private void getClassAttributes(CompilationUnit node){ for (Object type : node.types()){ if (type instanceof TypeDeclaration){ FieldDeclaration [] attributes = ((TypeDeclaration) type).getFields(); for (FieldDeclaration attribute: attributes){ List<FieldDeclaration> fragments = attribute.fragments(); Object obj = fragments.get(0); if (obj instanceof VariableDeclarationFragment){ String s = ((VariableDeclarationFragment) obj).getName().toString(); this.listOfAttributes.add(s); } } } } }
/** * Returns the type node for the given declaration. * * @param declaration the declaration * @return the type node or <code>null</code> if the given declaration represents a type * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { return ((SingleVariableDeclaration)declaration).getType(); } else if (declaration instanceof VariableDeclarationFragment) { ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); if (parent instanceof VariableDeclarationExpression) { return ((VariableDeclarationExpression)parent).getType(); } else if (parent instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)parent).getType(); } else if (parent instanceof FieldDeclaration) { return ((FieldDeclaration)parent).getType(); } else if (parent instanceof LambdaExpression) { return null; } } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; }