List of usage examples for org.eclipse.jdt.core.dom CompilationUnit getLineNumber
public int getLineNumber(int position)
From source file:br.ufal.cideei.soot.instrument.asttounit.ASTNodeUnitBridge.java
License:Open Source License
/** * Gets the lines from the AST nodes./*w w w .jav a 2 s . c om*/ * * @param nodes * the nodes * @param compilationUnit * the compilation unit * @return the lines from ast nodes */ public static Collection<Integer> getLinesFromASTNodes(Collection<ASTNode> nodes, CompilationUnit compilationUnit) { Set<Integer> lineSet = new HashSet<Integer>(); for (ASTNode node : nodes) { lineSet.add(compilationUnit.getLineNumber(node.getStartPosition())); } return lineSet; }
From source file:ca.ecliptical.pde.internal.ds.AnnotationProcessor.java
License:Open Source License
@Override public void acceptAST(ICompilationUnit source, CompilationUnit ast) { HashSet<IDSModel> modelSet = new HashSet<IDSModel>(); models.put(source, modelSet);/*from ww w .j a v a 2 s .c o m*/ HashSet<DSAnnotationProblem> problems = new HashSet<DSAnnotationProblem>(); ast.accept(new AnnotationVisitor(modelSet, errorLevel, problems)); if (!problems.isEmpty()) { char[] filename = source.getResource().getFullPath().toString().toCharArray(); for (DSAnnotationProblem problem : problems) { problem.setOriginatingFileName(filename); if (problem.getSourceStart() >= 0) problem.setSourceLineNumber(ast.getLineNumber(problem.getSourceStart())); } BuildContext buildContext = fileMap.get(source); if (buildContext != null) buildContext.recordNewProblems(problems.toArray(new CategorizedProblem[problems.size()])); } }
From source file:com.google.devtools.j2cpp.J2ObjC.java
License:Open Source License
private static int getNodeLine(ASTNode node) { CompilationUnit unit = (CompilationUnit) node.getRoot(); return unit.getLineNumber(node.getStartPosition()); }
From source file:com.google.devtools.j2objc.util.ErrorReportingASTVisitorTest.java
License:Open Source License
public void testBadVisitor() { String source = "public class Test {\n int test() {\n return 0;\n }\n }\n"; CompilationUnit unit = compileType("Test", source); ErrorReportingASTVisitor badVisitor = new ErrorReportingASTVisitor() { @Override/*from www.j av a 2 s. c om*/ public boolean visit(ReturnStatement node) { throw new UnsupportedOperationException("bad code here"); } }; try { badVisitor.run(unit); fail(); } catch (Throwable t) { assertTrue(t instanceof ASTNodeException); ASTNodeException e = (ASTNodeException) t; assertTrue(e.getCause() instanceof UnsupportedOperationException); assertEquals(3, unit.getLineNumber(e.getSourcePosition())); } }
From source file:com.google.gdt.eclipse.core.markers.GdtJavaProblem.java
License:Open Source License
protected GdtJavaProblem(ASTNode node, int offset, int length, T problemType, GdtProblemSeverity severity, String[] messageArguments, String[] problemArguments) { this.id = problemType.getProblemId(); this.filename = getFileNameFromASTNode(node); this.startPosition = offset; this.endPosition = offset + length - 1; CompilationUnit cu = (CompilationUnit) node.getRoot(); this.line = cu.getLineNumber(node.getStartPosition()); this.column = cu.getColumnNumber(node.getStartPosition()); this.problemType = problemType; this.severity = severity; this.message = MessageFormat.format(problemType.getMessage(), (Object[]) messageArguments); this.problemArguments = problemArguments; }
From source file:com.motorolamobility.preflighting.core.internal.utils.ProjectUtils.java
License:Apache License
/** * Extract all needed information from a CompilationUnit and fill the * internal source file model (SourceFileElement). Fill all invoked Methods * and resource constants//from www . j a v a 2 s . co m * * @param javaCompilationUnit * JDT model of a .java source file. * @param parent * SourceFolderElement, the source folder model containing this * compilation unit. * @return */ public static SourceFileElement readFromJava(final CompilationUnit javaCompilationUnit, Element parent) { File file = (File) javaCompilationUnit.getProperty(JAVA_FILE_PROPERTY); final SourceFileElement sourceFileElement = new SourceFileElement(file, parent); /* Fill type information */ Object type = javaCompilationUnit.types().get(0); /* * Grab the class * declaration */ if (type instanceof TypeDeclaration) { TypeDeclaration typeDeclaration = (TypeDeclaration) type; ITypeBinding superClassType = typeDeclaration.resolveBinding().getSuperclass(); String superClass = superClassType != null ? superClassType.getQualifiedName() : null; sourceFileElement.setSuperclassName(superClass); String typeFullName = typeDeclaration.resolveBinding().getQualifiedName(); sourceFileElement.setClassFullPath(typeFullName); } javaCompilationUnit.accept(new ASTVisitor() { /* * Visit method declaration, searching for instructions. */ @Override public boolean visit(MethodDeclaration node) { // Fill Method information Method method = new Method(); SimpleName name = node.getName(); method.setMethodName(name.getFullyQualifiedName()); int modifiers = node.getModifiers(); boolean methodType = isMethodVirtual(modifiers); method.setStatic(ProjectUtils.isStatic(modifiers)); /* * Extract information regarding method parameters */ List<SingleVariableDeclaration> parameters = node.parameters(); for (SingleVariableDeclaration param : parameters) { ITypeBinding typeBinding = param.getType().resolveBinding(); if (typeBinding != null) { String paramTypeName = typeBinding.getName(); method.getParameterTypes().add(paramTypeName); } } method.setConstructor(node.isConstructor()); IMethodBinding binding = node.resolveBinding(); if (binding != null) { String returnTypeStr = binding.getReturnType().getName(); method.setReturnType(returnTypeStr); } Block body = node.getBody(); int lineNumber = body != null ? javaCompilationUnit.getLineNumber(body.getStartPosition()) : javaCompilationUnit.getLineNumber(node.getStartPosition()); method.setLineNumber(lineNumber); // Navigate through statements... if (body != null) { analizeBody(javaCompilationUnit, method, body); } sourceFileElement.addMethod(getMethodTypeString(methodType), method); return super.visit(node); } /* * Visit field declaration, only for R.java file. Extracting * declared constants. */ @Override public boolean visit(FieldDeclaration node) { if (sourceFileElement.getName().equals("R.java")) { String typeName = node.getType().resolveBinding().getName(); int modifiers = node.getModifiers(); boolean isStatic = isStatic(modifiers); Field field = new Field(); field.setType(typeName); field.setStatic(isStatic); field.setVisibility(getVisibility(modifiers)); field.setFinal(isFinal(modifiers)); if (isStatic) { List<VariableDeclarationFragment> fragments = node.fragments(); // TODO Verify what to do when // there's more than one // fragment... enum? for (VariableDeclarationFragment fragment : fragments) { IVariableBinding binding = fragment.resolveBinding(); String name = binding.getName(); String declaringClassName = binding.getDeclaringClass().getName(); field.setName(declaringClassName + "." + name); Expression initializer = fragment.getInitializer(); if (initializer != null) { if (initializer instanceof NumberLiteral) { NumberLiteral numberInitializer = (NumberLiteral) initializer; String value = numberInitializer.getToken(); field.setValue(value); } } } sourceFileElement.getStaticFields().add(field); } } return super.visit(node); } @Override public boolean visit(QualifiedName node) { //visit to recognize R.string or R.layout usage if ((node.getQualifier() != null) && node.getQualifier().isQualifiedName()) { if (node.getQualifier().toString().equals(R_STRING)) { sourceFileElement.getUsedStringConstants().add(node.getName().toString()); } else if (node.getQualifier().toString().equals(R_LAYOUT)) { sourceFileElement.getUsedLayoutConstants().add(node.getName().toString()); } } return super.visit(node); } }); return sourceFileElement; }
From source file:com.motorolamobility.preflighting.core.internal.utils.ProjectUtils.java
License:Apache License
private static void analizeBody(final CompilationUnit javaCompilationUnit, final Method method, Block body) { body.accept(new ASTVisitor() { @Override//from w ww . j av a 2 s . com public boolean visit(VariableDeclarationFragment node) { String varName = node.getName().getIdentifier(); ITypeBinding typeBinding = node.resolveBinding().getType(); String typeQualifiedName = typeBinding.getQualifiedName(); int modifiers = typeBinding.getModifiers(); boolean isFinal = isFinal(modifiers); boolean isStatic = isStatic(modifiers); String value = null; Expression initializer = node.getInitializer(); if (initializer != null) { value = initializer.toString(); } int lineNumber = javaCompilationUnit.getLineNumber(node.getStartPosition()); Variable variable = new Variable(); variable.setName(varName); variable.setType(typeQualifiedName); variable.setFinal(isFinal); variable.setStatic(isStatic); variable.setValue(value); variable.setLineNumber(lineNumber); method.addVariable(variable); return super.visit(node); } @Override public boolean visit(MethodInvocation node) { // Fill invoked method model. MethodInvocation invoked = node; IMethodBinding methodBinding = invoked.resolveMethodBinding(); if (methodBinding != null) { IMethodBinding methodDeclaration = methodBinding.getMethodDeclaration(); ITypeBinding declaringClass = methodDeclaration.getDeclaringClass(); String declaringClassName = ""; if (declaringClass != null) { declaringClassName = declaringClass.getQualifiedName(); } String methodSimpleName = methodBinding.getName(); int lineNumber = javaCompilationUnit.getLineNumber(invoked.getStartPosition()); String returnType = methodBinding.getReturnType().getQualifiedName(); int methodModifiers = methodBinding.getModifiers(); boolean isVirtual = isMethodVirtual(methodModifiers); String sourceFileFullPath = ((File) javaCompilationUnit.getProperty(JAVA_FILE_PROPERTY)) .getAbsolutePath(); // Retrieve parameter types and look for R constants used // within method arguments List arguments = invoked.arguments(); List<String> parameterTypes = new ArrayList<String>(arguments.size()); List<String> parameterNames = new ArrayList<String>(arguments.size()); for (Object argument : arguments) { Expression argumentExpression = (Expression) argument; ITypeBinding typeBinding = argumentExpression.resolveTypeBinding(); String parameterType = ""; String parameterName = ""; if (typeBinding != null) { parameterType = typeBinding.getName(); parameterName = argumentExpression.toString(); } else { continue; } parameterTypes.add(parameterType); parameterNames.add(parameterName); if (argumentExpression instanceof QualifiedName) /* * Can * be a * constant * access */ { QualifiedName qualifiedName = (QualifiedName) argumentExpression; String fullQualifiedName = qualifiedName.getQualifier().getFullyQualifiedName(); if (fullQualifiedName.startsWith("R.")) /* * Accessing * a R * constant */ { Constant constant = new Constant(); constant.setSourceFileFullPath(sourceFileFullPath); constant.setLine(lineNumber); constant.setType(parameterType); Object constantExpressionValue = qualifiedName.resolveConstantExpressionValue(); if (constantExpressionValue != null) { String constantValueHex = constantExpressionValue.toString(); if (constantExpressionValue instanceof Integer) { Integer integerValue = (Integer) constantExpressionValue; constantValueHex = Integer.toHexString(integerValue); } constant.setValue(constantValueHex); method.getInstructions().add(constant); } } } } // Get the name of the object who owns the method being // called. Expression expression = invoked.getExpression(); String objectName = null; if ((expression != null) && (expression instanceof SimpleName)) { SimpleName simpleName = (SimpleName) expression; objectName = simpleName.getIdentifier(); } // Get the variable, if any, that received the method // returned value ASTNode parent = invoked.getParent(); String assignedVariable = null; if (parent instanceof VariableDeclarationFragment) { VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment) parent; assignedVariable = variableDeclarationFragment.getName().getIdentifier(); } else if (parent instanceof Assignment) { Assignment assignment = (Assignment) parent; Expression leftHandSide = assignment.getLeftHandSide(); if (leftHandSide instanceof SimpleName) { SimpleName name = (SimpleName) leftHandSide; assignedVariable = name.getIdentifier(); } } // Fill Invoke object and add to the method model. Invoke invoke = new Invoke(); invoke.setLine(lineNumber); invoke.setMethodName(methodSimpleName); invoke.setObjectName(objectName); invoke.setType(getMethodTypeString(isVirtual)); invoke.setReturnType(returnType); invoke.setClassCalled(declaringClassName); invoke.setParameterTypes(parameterTypes); invoke.setParameterNames(parameterNames); invoke.setSourceFileFullPath(sourceFileFullPath); invoke.setAssignedVariable(assignedVariable); method.getInstructions().add(invoke); } return super.visit(node); } @Override public boolean visit(VariableDeclarationExpression node) { return super.visit(node); } @Override public boolean visit(Assignment node) { Expression lhs = node.getLeftHandSide(); String name = ""; if (lhs instanceof SimpleName) { SimpleName simpleName = (SimpleName) lhs; name = simpleName.getIdentifier(); } ITypeBinding typeBinding = lhs.resolveTypeBinding(); String type = typeBinding.getName(); // method.addAssigment(assignment); // TODO Auto-generated method stub return super.visit(node); } }); }
From source file:com.motorolamobility.preflighting.samplechecker.findviewbyid.quickfix.FindViewByIdMarkerResolution.java
License:Apache License
private MethodInvocation getMethodInvocation(final CompilationUnit compUnit, final int lineNumber, MethodInvocation invokedMethod) { final MethodInvocation[] tempMethodInvocation = new MethodInvocation[1]; compUnit.accept(new ASTVisitor() { @Override/* w w w . jav a 2 s . co m*/ public boolean visit(MethodInvocation node) { if (compUnit.getLineNumber(node.getStartPosition()) == lineNumber) { tempMethodInvocation[0] = node; } return super.visit(node); }; }); if (tempMethodInvocation[0] != null) { invokedMethod = tempMethodInvocation[0]; } return invokedMethod; }
From source file:de.ovgu.featureide.core.framework.FrameworkModelBuilder.java
License:Open Source License
/** * @param feature//ww w.j a v a 2 s .c o m * @param interfaceName * @param implementingClass */ private void addRole(final String feature, final String interfaceName, final String implementingClass) { final IFolder featureFolder = featureProject.getSourceFolder().getFolder(feature); final IFolder location = featureFolder.getFolder("src"); /** Get interface methods **/ final IFile interfaceFile = findFile(featureProject.getBuildFolder(), interfaceName); String interfaceContent; MyASTVisitor interfaceVisitor = null; try { interfaceContent = fileToString(interfaceFile); final ASTParser intefaceParser = ASTParser.newParser(AST_Type); intefaceParser.setSource(interfaceContent.toCharArray()); intefaceParser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit interfaceUnit = (CompilationUnit) intefaceParser.createAST(null); interfaceVisitor = new MyASTVisitor(true); interfaceUnit.accept(interfaceVisitor); } catch (final IOException e) { FrameworkCorePlugin.getDefault().logError(e); } final IFile classFile = findFile(location, implementingClass); final FSTRole role = model.addRole(feature, interfaceName, classFile); final IJavaProject project = JavaCore.create(featureProject.getProject()); try { final IType classType = project.findType(implementingClass); /** ASTNodes **/ final String fileContent = fileToString(classFile); final ASTParser parser = ASTParser.newParser(AST_Type); parser.setSource(fileContent.toCharArray()); parser.setKind(ASTParser.K_COMPILATION_UNIT); final CompilationUnit unit = (CompilationUnit) parser.createAST(null); final MyASTVisitor visitor = new MyASTVisitor(); unit.accept(visitor); /** Get fields **/ if (classType == null) { FrameworkCorePlugin.getDefault().logWarning(implementingClass + " not found"); return; } for (final IField f : classType.getFields()) { final FSTField field = new FSTField(f.getElementName(), Signature.toString(f.getTypeSignature()), ""); if (visitor.getData(f) != null) { field.setLine(unit.getLineNumber(visitor.getData(f).intValue())); } role.getClassFragment().add(field); } /** Get methods **/ for (final IMethod m : classType.getMethods()) { final LinkedList<String> parameterTypes = new LinkedList<>(); for (final String s : m.getParameterTypes()) { parameterTypes.add(s); } final boolean isRefinement = calculateRefinement(parameterTypes, interfaceVisitor.getMethodSignature(m)); final FSTMethod met = new FSTMethod(m.getElementName(), parameterTypes, Signature.toString(m.getReturnType()), getModifiers(m)) { /** * Returns true, if method is from interface or abstract class */ @Override public boolean inRefinementGroup() { return isRefinement; } }; if (visitor.getData(m) != null) { met.setLine(unit.getLineNumber(visitor.getData(m).getStartPosition())); met.setEndLine(unit.getLineNumber( (visitor.getData(m).getStartPosition() + visitor.getData(m).getLength()))); } role.getClassFragment().add(met); } } catch (JavaModelException | IOException e) { FrameworkCorePlugin.getDefault().logError(e); } }
From source file:de.ovgu.featureide.munge.signatures.MungeSignatureBuilder.java
License:Open Source License
private static Collection<AbstractSignature> parse(ProjectSignatures projectSignatures, ASTNode root) { final HashMap<AbstractSignature, AbstractSignature> map = new HashMap<>(); final CompilationUnit cu = (CompilationUnit) root; final PackageDeclaration pckgDecl = cu.getPackage(); final String packageName = (pckgDecl == null) ? null : pckgDecl.getName().getFullyQualifiedName(); List<?> l = cu.getCommentList(); List<Javadoc> cl = new LinkedList<>(); for (Object object : l) { if (object instanceof Javadoc) { Javadoc comment = (Javadoc) object; cl.add(comment);//from w ww .j a va2s. c o m } } final ListIterator<Javadoc> it = cl.listIterator(); final FeatureDataConstructor featureDataConstructor = new FeatureDataConstructor(projectSignatures, FeatureDataConstructor.TYPE_PP); root.accept(new ASTVisitor() { private BodyDeclaration curDeclaration = null; private PreprocessorFeatureData curfeatureData = null; private String lastComment = null; private MethodDeclaration lastCommentedMethod = null; @Override public boolean visit(Javadoc node) { if (curDeclaration != null) { final StringBuilder sb = new StringBuilder(); while (it.hasNext()) { final Javadoc comment = it.next(); if (comment.getStartPosition() <= curDeclaration.getStartPosition()) { sb.append(comment); sb.append("\n"); } else { it.previous(); break; } } lastComment = sb.toString(); curfeatureData.setComment(lastComment); lastCommentedMethod = (curDeclaration instanceof MethodDeclaration) ? (MethodDeclaration) curDeclaration : null; } return false; } private void attachFeatureData(AbstractSignature curSignature, BodyDeclaration curDeclaration) { this.curDeclaration = curDeclaration; final Javadoc javadoc = curDeclaration.getJavadoc(); final int startPosition = (javadoc == null) ? curDeclaration.getStartPosition() : curDeclaration.getStartPosition() + javadoc.getLength(); curfeatureData = (PreprocessorFeatureData) featureDataConstructor.create(null, unit.getLineNumber(startPosition), unit.getLineNumber(curDeclaration.getStartPosition() + curDeclaration.getLength())); curSignature.setFeatureData(curfeatureData); map.put(curSignature, curSignature); } @Override public boolean visit(CompilationUnit unit) { this.unit = unit; return true; } CompilationUnit unit = null; @Override public boolean visit(MethodDeclaration node) { int pos = unit.getLineNumber(node.getBody().getStartPosition()); int end = unit.getLineNumber(node.getBody().getStartPosition() + node.getBody().getLength()); final MungeMethodSignature methodSignature = new MungeMethodSignature(getParent(node.getParent()), node.getName().getIdentifier(), node.getModifiers(), node.getReturnType2(), node.parameters(), node.isConstructor(), pos, end); attachFeatureData(methodSignature, node); if (node.getJavadoc() == null && lastCommentedMethod != null && lastCommentedMethod.getName().equals(node.getName())) { curfeatureData.setComment(lastComment); } else { lastCommentedMethod = null; } return true; } private AbstractClassSignature getParent(ASTNode astnode) { final AbstractClassSignature sig; if (astnode instanceof TypeDeclaration) { final TypeDeclaration node = (TypeDeclaration) astnode; sig = new MungeClassSignature(null, node.getName().getIdentifier(), node.getModifiers(), node.isInterface() ? "interface" : "class", packageName); } else { return null; } AbstractClassSignature uniqueSig = (AbstractClassSignature) map.get(sig); if (uniqueSig == null) { visit((TypeDeclaration) astnode); } return uniqueSig; } @Override public boolean visit(FieldDeclaration node) { for (Iterator<?> it = node.fragments().iterator(); it.hasNext();) { VariableDeclarationFragment fragment = (VariableDeclarationFragment) it.next(); final MungeFieldSignature fieldSignature = new MungeFieldSignature(getParent(node.getParent()), fragment.getName().getIdentifier(), node.getModifiers(), node.getType()); attachFeatureData(fieldSignature, node); } return true; } @Override public boolean visit(TypeDeclaration node) { final MungeClassSignature classSignature = new MungeClassSignature(getParent(node.getParent()), node.getName().getIdentifier(), node.getModifiers(), node.isInterface() ? "interface" : "class", packageName); attachFeatureData(classSignature, node); return super.visit(node); } }); return map.keySet(); }